﻿var map = {
	init: function() {
		if (GBrowserIsCompatible) {
			var form = null;
			var details = null;
			if (form = document.getElementById('form_locations')) {
				map.dropDownFacilities = form.getElementsByTagName('select').item(0);
				map.dropDownFacilities.onchange = map.changeFacility;
				map.dropDownAllPartners = form.getElementsByTagName('select').item(1);
				map.dropDownAllPartners.onchange = map.changeAllPartners;
				map.dropDownFacilitiesInCity = form.getElementsByTagName('select').item(2);
				map.dropDownFacilitiesInCity.onchange = map.changeFacilityInCity;

			} else {
				return false;
			}
			if (details = document.getElementById('location-details')) {
				map.header = details.getElementsByTagName('h4').item(0);
				map.details = details.getElementsByTagName('p').item(0);
			} else {
				return false;
			}
			map.country = document.getElementById('country').value==""?"Sweden":document.getElementById('country').value;
			map.defaultzoomlevel = document.getElementById('defaultzoomlevel').value==""?5:parseInt(document.getElementById('defaultzoomlevel').value);
			map.defaultcentercoordinates = document.getElementById('defaultcentercoordinates').value;
			map.ddfacilitiesshow = document.getElementById('ddfacilitiesshow').value=="y";
			map.ddfacilitiestopitemtext = document.getElementById('ddfacilitiestopitemtext').value==""?"Våra butiker":document.getElementById('ddfacilitiestopitemtext').value;
			map.ddallpartnersshow = document.getElementById('ddallpartnersshow').value=="y";
		    map.ddallpartnerstopitemtext = document.getElementById('ddallpartnerstopitemtext').value==""?"Alla partners":document.getElementById('ddallpartnerstopitemtext').value;
			map.partnername = document.getElementById('partnername').value==""?"All":document.getElementById('partnername').value;
			map.defaultfacilityid = document.getElementById('defaultfacilityid').value==""?"":document.getElementById('defaultfacilityid').value;
			map.showallfacilitiesonstartup = document.getElementById('showallfacilitiesonstartup').value=="y";
			map.ddallfacilitiesincityshow = false;
			map.searchcity = "";
			map.arrFacilitiesInCity = new Array();
			var fullURL = unescape(document.URL);
			if(fullURL.indexOf('city=')>-1)
			{
				var city = fullURL.substring(fullURL.indexOf('city=')+6, fullURL.length-3)
				if(city!="")
				{
					map.searchcity = city;
					map.ddfacilitiesshow = false;
					map.ddallpartnersshow = false;
					map.ddallfacilitiesincityshow = true;
				}
			}
			
			map.locationsurl = "/map/locations.xml";
			map.nextCity = 0;
			map.tries=0;
			map.init_ajax();
		}
	},

	init_map: function() {
		if(!document.getElementById('location-map'))
			return;
		map.obj = new GMap2($("location-map"));
		
		map.geocoder = new GClientGeocoder();
		map.icon = new GIcon();

		map.obj.addControl(new GOverviewMapControl());
		map.obj.addControl(new GSmallZoomControl());

		map.icon.image = "/images/map-icon.png";
		map.icon.shadow = "/images/map-icon_shadow.png";
		map.icon.iconSize = new GSize(41,35);
		map.icon.shadowSize = new GSize(73,35);
		map.icon.iconAnchor = new GPoint(20,34);
		map.icon.infoWindowAnchor = new GPoint(24,6);
		
		//Center map. If user has filled in coordinates use them, else use user entered country, else use Sweden
		latlong = new GLatLng(63.35212928507874,16.259765652);
		
		var coordinatesArr = map.defaultcentercoordinates.split(',');
		if(coordinatesArr.length == 2)
			latlong = new GLatLng(coordinatesArr[0],coordinatesArr[1]);
		else
		{
			switch(map.country.toLowerCase())
			{
				case "sweden":
				case "sverige":
					latlong = new GLatLng(61.35212928507874,16.259765652);
				break;    
				case "finland":
				case "suomi":
					latlong = new GLatLng(63.35212928507874,25.259765652);
				break;    
				default:
					latlong = new GLatLng(61.35212928507874,16.259765652);  
			}
		}
		map.obj.setCenter(latlong, map.defaultzoomlevel);
	},

	init_ajax: function() {
		
		if (window.XMLHttpRequest) {
			map.ajax = new XMLHttpRequest();
			if (map.ajax.overrideMimeType) map.ajax.overrideMimeType('text/xml');
		} else if (window.ActiveXObject) {
			map.ajax = new ActiveXObject("Microsoft.XMLHTTP");
		}

		if (map.ajax) {
			map.ajax.onreadystatechange = map.handleXML;
			map.ajax.open('GET', map.locationsurl, true);
			map.ajax.send(null);
		}
	},

	handleXML: function() {
		if (map.ajax.readyState == 4) {
			if (map.ajax.status == 200) {
				map.handleResponse(map.ajax.responseXML);
			}
		}
	},

	handleResponse: function(xmlDoc) {
		map.init_map();
		map.cities = xmlDoc.getElementsByTagName('cityname');
		var cities = map.cities;
		var ddfacilities = map.dropDownFacilities;
		var ddallpartners = map.dropDownAllPartners;
		var ddfacilitiesincity = map.dropDownFacilitiesInCity;
		map.removeChildren(ddfacilities);
		map.removeChildren(ddallpartners);
		map.removeChildren(ddfacilitiesincity);
		
		option = document.createElement('option');
		option.value = 0;
		option.appendChild(document.createTextNode(map.ddfacilitiestopitemtext));
		option.selected = true;
		ddfacilities.appendChild(option);
		option = document.createElement('option');
		option.value = 0;
		option.appendChild(document.createTextNode(map.ddallpartnerstopitemtext));
		option.selected = true;
		ddallpartners.appendChild(option);
		option = document.createElement('option');
		option.value = 0;
		option.appendChild(document.createTextNode(map.searchcity + ': ' + map.ddfacilitiestopitemtext));
		option.selected = true;
		ddfacilitiesincity.appendChild(option);

		for(var i = 0; i < cities.length; i++) {
			//Populate ddfacilities
			if(map.partnername.toLowerCase() == "all" || map.partnername.toLowerCase() == map.getTagValue(cities[i], 'name').toLowerCase())
			{
				option = document.createElement('option');
				option.value = i+1;
				option.appendChild(document.createTextNode(cities[i].getAttribute('id')));
				ddfacilities.appendChild(option);
			}
			//Populate dropdown for facilities in city(if this page is called from searchpage
			if(map.searchcity.toLowerCase() == map.getTagValue(cities[i], 'mapcity').toLowerCase())
			{
				option = document.createElement('option');
				option.value = i+1;
				option.appendChild(document.createTextNode(cities[i].getAttribute('id')));
				ddfacilitiesincity.appendChild(option);
				map.arrFacilitiesInCity.push(cities[i]);
			}
			//Populate ddpartners
			option = document.createElement('option');
			option.value = i+1;
			option.appendChild(document.createTextNode(cities[i].getAttribute('id')));
			ddallpartners.appendChild(option);
		}
		
		ddfacilities.style.visibility = map.ddfacilitiesshow?"visible":"hidden";
		ddallpartners.style.visibility = map.ddallpartnersshow?"visible":"hidden";
		ddfacilitiesincity.style.visibility = map.ddallfacilitiesincityshow?"visible":"hidden";
		
		if(map.searchcity != "")
		{
			map.showFacilitiesInCity();
		}
		else if(map.showallfacilitiesonstartup)
		{
			map.showAllFacilities();
		}
		else if(map.defaultfacilityid != "")
		{
			id = map.getIndexOfItem(map.defaultfacilityid);
			if(id > -1)
				map.changeLocation(id+1, map.defaultzoomlevel, false);
		}
	},
	
	removeChildren: function(dropdown){
		if ( dropdown.hasChildNodes() )	
		{
			while ( dropdown.childNodes.length >= 1 )
			{
				dropdown.removeChild( dropdown.firstChild );       
			} 
		}
	},
	
	changeFacility: function() {
		id = parseInt(map.dropDownFacilities.value);
		if(id > 0)
			map.changeLocation(id, 14, true);
		else
			map.init();
	}, 

	changeAllPartners: function() {
		id = parseInt(map.dropDownAllPartners.value);
		if(id > 0)
			map.changeLocation(id, 14, true);
		else
			map.init();

	}, 
	changeFacilityInCity: function() {
		id = parseInt(map.dropDownFacilitiesInCity.value);
		if(id > 0)
			map.changeLocation(id, 14);
		else
			map.init();
	},
	
	changeLocation: function(the_id, map_zoomlevel, redirect) {
		
		if (typeof(the_id) == 'number') id = the_id;
		
		var cities = map.cities;
		if (city = cities[id-1]) {
			
			if(redirect)
			{
				pageid = map.getTagValue(city, 'pageid');
				if(parseInt(pageid)){
					window.location = "finedriver.aspx?request=" + map.getTagValue(city, 'pageid');
					return;
				}
			}
			name = map.getTagValue(city, 'name');
			phonenumber = map.getTagValue(city, 'phonenumber');
			fax = map.getTagValue(city, 'fax');// fax 081031 ER
			email = map.getTagValue(city, 'email');
			website = map.getTagValue(city, 'website');
			mapstreet = map.getTagValue(city, 'mapstreet');
			mapzip = map.getTagValue(city, 'mapzip');
			mapcity = map.getTagValue(city, 'mapcity');
			viewstreet = map.getTagValue(city, 'viewstreet');
			viewzip = map.getTagValue(city, 'viewzip');
			viewcity = map.getTagValue(city, 'viewcity');
			street = viewstreet ? viewstreet : mapstreet;
			zip = viewzip ? viewzip : mapzip;
			cityname = viewcity ? viewcity : mapcity; 
			cityname = map.getTagValue(city, 'viewcity');
			coordinates = map.getTagValue(city, 'coordinates');
			map.obj.clearOverlays();
			map.showAddress(coordinates, map_zoomlevel);

			//Print details
			var header = map.header;
			var details = map.details;
			
			while (header.firstChild) { header.removeChild(header.firstChild); }
			while (details.firstChild) { details.removeChild(details.firstChild); }
			header.appendChild(document.createTextNode(name));
			if (street) { details.appendChild(document.createTextNode(street)); details.appendChild(document.createElement('br')); }
			if (zip) { details.appendChild(document.createTextNode(zip+' ')); }
			if (city) { details.appendChild(document.createTextNode(cityname)); details.appendChild(document.createElement('br')); }
			if (phonenumber) { details.appendChild(document.createTextNode(phonenumber)); details.appendChild(document.createElement('br')); }
			if (fax) { details.appendChild(document.createTextNode(fax)); details.appendChild(document.createElement('br')); }// fax 081031 ER
			if (website) {
				a = document.createElement('a');
				a.href = 'http://'+website;
				a.setAttribute('target',"_blank");
				a.appendChild(document.createTextNode(website));
				details.appendChild(a); details.appendChild(document.createElement('br'));
			}
			if (email) {
				a = document.createElement('a');
				a.href = 'mailto:'+email;
				a.appendChild(document.createTextNode(email));
				details.appendChild(a);
			}
		}
	},
	
	getTagValue: function(base, tagName) {
		
		if ((base.getElementsByTagName(tagName).item(0)) && (base.getElementsByTagName(tagName).item(0).firstChild)) {
			return base.getElementsByTagName(tagName).item(0).firstChild.nodeValue;
		} else {
			return('');
		}
	},
	
	getIndexOfItem: function(id){
		
		var cities = map.cities;
		var index = -1;
		for(var i = 0; i < cities.length; i++) {
			if (city = cities[i]) {
				if(city.getAttribute('id') == id)
					index = i;
			}
		}
		return index;
	},
	
	showAddress: function(coordinates, map_zoomlevel) {
		var coordinatesArr = coordinates.split(',');
		if(coordinatesArr.length != 2)
			return;
		var point = new GLatLng(coordinatesArr[0], coordinatesArr[1]);
		if(map_zoomlevel != null)
			map.obj.setCenter(point, map_zoomlevel);
		var marker = new GMarker(point, map.icon);
		map.obj.addOverlay(marker);		
	},
	
	showAllFacilities: function()
	{
		if(map.nextCity == 0)
			map.obj.clearOverlays();
		var cities = map.cities;
		
		if (map.nextCity < cities.length) {
			coordinates = map.getTagValue(cities[map.nextCity], 'coordinates');
			if(coordinates.length==5)
				coordinates='';
			showit = false;
			if(map.getTagValue(cities[map.nextCity], 'name').toLowerCase().indexOf(map.partnername.toLowerCase())>-1 || map.partnername.toLowerCase() == "all")
				showit = true;
			setTimeout('map.showFacility("'+coordinates+'",map.showAllFacilities, showit)', 10);
          	map.nextCity++;
        } 

	},
	
	showFacility: function(coordinates, next, showit) {
		if(!showit)
		{
			next();
			return;
		}
		map.showAddress(coordinates, null);
		next();
	},
	
	showFacilitiesInCity: function() {
		
		if(map.arrFacilitiesInCity.length==1)
		{
			id = map.getIndexOfItem(map.arrFacilitiesInCity[0].getAttribute('id'));
			if(id > -1)
				map.changeLocation(id+1, 14, false);
			ddfacilitiesincity.style.visibility = 'hidden';
		}
		if(map.arrFacilitiesInCity.length>1)
		{
			for(var i = 0; i < map.arrFacilitiesInCity.length; i++){
				map.showAddress(map.getTagValue(map.arrFacilitiesInCity[i], 'coordinates'), 10);
			}
		}
	}
	
	/*showAddress: function(address, name, map_zoomlevel, coordinates) {	
		if(coordinates=='')
		{
			map.geocoder.getLatLng(
				address,
				function(point) {
					if (!point) {
						alert(address + " kunde inte hittas i kartsystemet. Försök igen senare.");
					} else {
						map.obj.setCenter(point, map_zoomlevel==null?14:map_zoomlevel);
						var marker = new GMarker(point, map.icon);
						map.obj.addOverlay(marker);
					}
				}
			);
		}
		else
		{
			var coordinatesArr = coordinates.split(',');
			if(coordinatesArr.length != 2)
				return;
			var point = new GLatLng(coordinatesArr[0], coordinatesArr[1]);
			alert(coordinatesArr[0]);
			alert(coordinatesArr[1]);
			map.obj.setCenter(point, map_zoomlevel==null?14:map_zoomlevel);
			var marker = new GMarker(point, map.icon);
			map.obj.addOverlay(marker);
		}
	},
		
	showAllFacilities: function()
	{
		if(map.nextCity == 0)
			map.obj.clearOverlays();
		var cities = map.cities;
		
		if (map.nextCity < cities.length) {
			mapstreet = map.getTagValue(cities[map.nextCity], 'mapstreet');
			mapcity = map.getTagValue(cities[map.nextCity], 'mapcity');
			address = mapstreet+', '+mapcity+', ' + map.country;
			showit = false;
			if(map.getTagValue(cities[map.nextCity], 'name').toLowerCase().indexOf(map.partnername.toLowerCase())>-1 || map.partnername.toLowerCase() == "all")
				showit = true;
			setTimeout('map.showFacility("'+address+'",map.showAllFacilities, showit)', map.delay);
          	map.nextCity++;
        } 
	}, 	
	
	showFacility: function(address, next, showit) {
		//Only try 3 times(address could be incorrect)
		if(!showit || map.tries==3)
		{
			map.tries=0;
			next();
			return;
		}
		map.geocoder.getLatLng(address,
			function(point) 
			{	
				if (point!=null) {
					var marker = new GMarker(point, map.icon);
					map.obj.addOverlay(marker);
					map.tries=0;
				}
				else {
              		// === if we were sending the requests to fast, try this one again and increase the delay
		            map.nextCity--;
	            	map.delay++;
					map.tries++;		
				}
				next();
			}
		);
	},
	showFacilitiesInCity: function() {
		
		if(map.arrFacilitiesInCity.length==1)
		{
			id = map.getIndexOfItem(map.arrFacilitiesInCity[0].getAttribute('id'));
			if(id > -1)
				map.changeLocation(id+1, 14, false);
			ddfacilitiesincity.style.visibility = 'hidden';
		}
		if(map.arrFacilitiesInCity.length>1)
		{
			for(var i = 0; i < map.arrFacilitiesInCity.length; i++){
				name = map.getTagValue(map.arrFacilitiesInCity[i], 'name');
				mapstreet = map.getTagValue(map.arrFacilitiesInCity[i], 'mapstreet');
				mapcity = map.getTagValue(map.arrFacilitiesInCity[i], 'mapcity');
				map.showAddress(mapstreet+', '+mapcity+', ' + map.country, name, 10);
			}
		}
	}*/ 
}

