GoogleMap = {
	map:null,
	branches:[],
	// load the map into the page
	initialize:function () {
		
		// create new map instance in the div with id="map"
		this.map = new google.maps.Map2(document.getElementById("map"));
		
		// center the map on our chosen location
		//using clientlocation to get users latlong - which will determine where to center map.
		this.map.setCenter(new GLatLng(53.440201,-7.558594), 7);
		
		
		// allow the user to scroll to zoom
		this.map.enableScrollWheelZoom();
		
		// render a zoom control on the map
		this.map.addControl(new GSmallMapControl());
		
		// render a map type control on the map
		this.map.addControl(new GMapTypeControl());
		
		// add the branch/cash machine markers
		this.addBranches();
		
		// create our icon objects
		this.createIcons();
		
		
		
		
	},
	addBranches:function () {
		// create an AJAX request object
		this.branchRequest = HW.extendObject({},Ajax);
		this.branchRequest.createXmlHttpRequestObject();
		
		// point the AJAX request at our XML file
		//this.branchRequest.href = 'aib-branches-backup.xml';
		//LIVE - We need to point to a browsable location on blobshare
		this.branchRequest.href = 'aib-branches.xml';
		
		// set the response handler function
		this.branchRequest.xmlHttp.onreadystatechange = GoogleMap.handleResponse;
		
		// send!
		this.branchRequest.sendRequest();
		
	},
	handleResponse:function () {
		if (GoogleMap.branchRequest.xmlHttp.readyState == 4){
			if (GoogleMap.branchRequest.xmlHttp.status == 200){
				// once our response has returned successfully call the draw locations function
				GoogleMap.drawLocations(GoogleMap.branchRequest.xmlHttp.responseXML);
			}
		}
	},
	drawLocations:function (xml) {
		// create an XML parser
		var x = new XmlParser(xml);
		var locs = x.getNodes('location');
		for(var i=0;i<locs.length;i++) {
			// pull the data for each location from the XML
				var lat = x.getNodeContents('lat',locs[i]);
				var long = x.getNodeContents('long',locs[i]);
				var name = x.getNodeContents('name',locs[i]);
				var branch = x.getNodeContents('branch',locs[i]);
				var tabs = x.getNodes('tab',locs[i]);
				var point = new GLatLng(lat,long);
				if(branch == 'true'){
					var icon = GoogleMap.branchIcon;
				}
				var marker = new GMarker(point,{icon:icon,title:name});
				GEvent.addListener(marker, "click", function() {
					
			
					
					loc = document.location.toString();
					
					if(loc.indexOf('vote')>-1){
						
						$('#smsvote').hide();
						$('#votenow').show();
						$('#thankyou').hide();
						$('#tab_1').removeClass('tab_inactive');
						$('#tab_1').addClass('tab');
						$('#tab_2').removeClass('tab');
						$('#tab_2').addClass('tab_inactive');
					}else{
						
						$('#votenow').show();
						$('#latestnews').hide();
						$('#thankyou').hide();
						$('#smsvote').hide();
						
						$('#tab_2').removeClass('tab_inactive');
						$('#tab_2').addClass('tab');
						
						$('#tab_1').removeClass('tab');
						$('#tab_1').addClass('tab_inactive');
						$('#tab_3').removeClass('tab');
						$('#tab_3').addClass('tab_inactive');
					}
					
					
					$.ajax({
						   type: "POST",
						   data: "action=getCharityByBranchName&id="+this.titleText,
						   url: "process.php",
						   success: function(msg, textStatus){
								output = msg;
								if(output!=""){
								$.ajax({
									   type: "POST",
									   data: "action=getBranchesByCounty",
									   url: "process.php",
									   success: function(msg, textStatus){
											
									$('#branch_drop').html(msg);
											$('#branch_drop').val(output);
											
											$.ajax({
												   type: "POST",
												   data: "action=getCharityByBranch&id="+output,
												   url: "process.php",
												   success: function(msg, textStatus){
														
														output = msg.split('|');
														
														$('#votecontent').html(output[0]);
														$('#votecontent_sms').html(output[1]);
												   
												   }
										   });
											
									   }
								});
								
								}
						   }
					});
					
					
					
					
					
				  });

				var popupTabs = [];
				marker.contentOutput = [];
				for(var j=0;j<tabs.length;j++) {
					// get the title and content for each tab from the XML
					tabTitle = tabs[j].getAttribute('title');
					tabContents = x.getContents(tabs[j]);
					var tab = new GInfoWindowTab(tabTitle,tabContents);
					popupTabs.push(tab);
					marker.contentOutput.push({title:tabTitle,content:tabContents});
			}
			// need to wrap in a function closure because we're adding asynchronous code within a loop
			(function(){
				var _popupTabs = popupTabs;
				marker.showPopupInfo = function() {
					this.openInfoWindowTabsHtml(_popupTabs,{maxWidth:'256'});
				}
				marker.bindInfoWindowTabsHtml(_popupTabs,{maxWidth:'256'});
			})()
			marker.titleText = name;
			//this.map.addOverlay(marker);
			if(branch == 'true'){
				GoogleMap.branches.push(marker);
			}
		}
		var cluster=new ClusterMarker(GoogleMap.map, { markers:GoogleMap.branches } );
		cluster.fitMapToMarkers() 
	},
	  // create the clusterer
	// create icon objects for branch and cash machine
	createIcons:function() {
		// create a default icon to use as a starting point for our custom icons
		// set a marker image
		this.defIcon = new GIcon(G_DEFAULT_ICON,'http://www.aib.ie/futuretense_cs/AIB_IE/_img/mapIcons/aib-branch.png');
		// set the shadow image
		this.defIcon.shadow = 'http://www.aib.ie/futuretense_cs/AIB_IE/_img/mapIcons/shadow.png';
		// set the sizes
		this.defIcon.iconSize = new GSize(32,32);
		this.defIcon.shadowSize = new GSize(59,32);
		
		// now use the default icon to create two new icons with different images
		this.branchIcon = new GIcon(this.defIcon,'http://www.aib.ie/futuretense_cs/AIB_IE/_img/mapIcons/aib-branch.png');
		//this.machineIcon = new GIcon(this.defIcon,'http://www.aib.ie/futuretense_cs/AIB_IE/_img/mapIcons/red-dot.png');
	},
	
	// compare function used to sort points by distance
	sortDist:function(a,b) {
		return a.dist - b.dist;
	}
}

// XML parser object
function XmlParser(xml) {
	this.d = xml.documentElement;
}
XmlParser.prototype = {
	// get nodes with a tagName 't' within optional parent element 'p'
	getNodes:function(t,p){
		// if p is defined search within p, otherwise search within the whole document
		return p?p.getElementsByTagName(t):this.d.getElementsByTagName(t);
	},
	// get the contents of the first element with tagName 't' within a node 'p'
	getNodeContents:function(t,p){
		var node = this.getNodes(t,p)?this.getNodes(t,p)[0]:null;
		return node?node.firstChild.data:null;
	},
	// get the contents of a particular node
	getContents:function(n){
		return n?n.firstChild.data:null;
	}
}


// load the maps API
try {
	google.load("maps", "2.x");	
	//once the API is loaded, call the init function
	google.setOnLoadCallback(function(){GoogleMap.initialize();});
}
catch(e) {}
