﻿var oneworldLinkConstant = "one_world";

function initializeMap(container, officeInfoXml, city, imgBase, officeHoursLabelHtml, phonesLabelHtml) {
    function createMarker(point, html) {
	  var tinyIcon = new GIcon();
	  tinyIcon.image = imgBase + "/office.png";
	  tinyIcon.shadow = imgBase + "/officeShadow.png";
	  tinyIcon.iconSize = new GSize(12, 20);
	  tinyIcon.shadowSize = new GSize(22, 20);
	  tinyIcon.iconAnchor = new GPoint(6, 20);
	  tinyIcon.infoWindowAnchor = new GPoint(5, 1);
	  markerOptions = { icon:tinyIcon };
        var marker = new GMarker(point, markerOptions);
        GEvent.addListener(marker, "mouseover", function() {
          marker.openInfoWindowHtml(html);
        });
/*        GEvent.addListener(marker, "mouseout", function() {
          marker.closeInfoWindow();
        });
*/
        return marker;
    }

    function findCityInfo(xmlDoc, city) {
        var cityInfo = xmlDoc.documentElement.getElementsByTagName("cityInfo");
        for (var i = 0; i < cityInfo.length; i++)
            if (city == cityInfo[i].getElementsByTagName("name")[0].firstChild.nodeValue)
                return cityInfo[i];
              
        return null;
    }

    if (GBrowserIsCompatible()) { 
      var map = new GMap2(document.getElementById(container));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());

      var request = GXmlHttp.create();
      request.open("GET", officeInfoXml, true);
      request.onreadystatechange = function() {
          if (request.readyState == 4) {
              var xmlDoc = GXml.parse(request.responseText);
              var cityInfo = findCityInfo(xmlDoc, city);
              if (cityInfo != null) {
                var mapAttribute = cityInfo.getElementsByTagName("mapAttribute")[0];
                var lat = parseFloat(mapAttribute.getAttribute("lat"));
                var lon = parseFloat(mapAttribute.getAttribute("lon"));
                var zoom = parseFloat(mapAttribute.getAttribute("zoom"));
                map.setCenter(new GLatLng(lat, lon), zoom);
                

              var coordinates = cityInfo.getElementsByTagName("coordinates");
              for (var i = 0; i < coordinates.length; i++) {
                var lat = parseFloat(coordinates[i].getAttribute("lat"));
                var lon = parseFloat(coordinates[i].getAttribute("lon"));
                var point = new GLatLng(lat,lon);

                var officeInfo = coordinates[i].parentNode.parentNode;
                var officeTitleNodes = officeInfo.getElementsByTagName("title");
                var officeTitle = officeTitleNodes.length > 0 ? officeTitleNodes[0].firstChild.nodeValue: null;
                
                var contactInfo = coordinates[i].parentNode;
                var address = contactInfo.getElementsByTagName("address")[0].firstChild.nodeValue;
                var officeHours = null;
                if (contactInfo.getElementsByTagName("officeHours")[0]) {
					officeHours = contactInfo.getElementsByTagName("officeHours")[0].firstChild.nodeValue;
                }
                var phoneNodes = contactInfo.getElementsByTagName("phone");
                var phones = '';
                for (var p = 0; p < phoneNodes.length; p++)
                    phones += phoneNodes[p].firstChild.nodeValue + ',';
                phones = phones.substr(0, phones.length - ','.length);
                var marker = createMarker(point, '<div style="width: 300px;">' +
                     (officeTitle != null ? '<h3>'+officeTitle+'</h3>' + '<br/>':'')
                     + address +
                     (officeHours != null ?'<br/>' + officeHoursLabelHtml + ' '+ officeHours:'')
                     + '<br/>' + phonesLabelHtml + ' '+phones   + '</div>'
                     );
                
                map.addOverlay(marker);
                }
              } else 
                alert("City " + city + " not found");
          }
      }
      request.send(null);
    } else {
      alert("Google Maps API is not supports this browser");
    }
}

var map;
function initializeMap(_id, page, params) {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById(_id));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		if (page == "city") {
			analyzeCityMap(params[0]);
		}		
		if (page == "country") {
			analyzeCountryMap(params[0]);
		}
		if (page == "countries") {
			analyzeCountriesMap();
		}		
	}
}

function initializeOneworldMap(_id, page, param) {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById(_id));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		if (page == "country") {
			analyzeOneworldCountryMap(param);
		}
		if (page == "countries") {
			analyzeOneworldCountriesMap();
		}		
	}
}


function analyzeCityMap(city) {
	if (citiesMaps[city]) {
		map.setCenter(new GLatLng(citiesMaps[city]["lat"], citiesMaps[city]["lon"]), citiesMaps[city]["zoom"]);
		if (citiesMaps[city]["offices"]) {
			$.each(citiesMaps[city]["offices"], function(i, val){
				var opts = {};
				opts.address = val.address;      
				opts.subway = val.subway;
				opts.officeHours = val.officeHours;
				opts.phone = val.phone;
				opts.fax = val.fax;
				addMarker(map, val.lat, val.lon, "red", "city", opts);
			});
		}
	}
}

function analyzeCountryMap(country) {
	if (countriesMaps[country]) {
		map.setCenter(new GLatLng(countriesMaps[country]["lat"], countriesMaps[country]["lon"]), countriesMaps[country]["zoom"]);
		$.each(countriesMaps[country]["cities"], function(i, val){
			if (citiesMaps[val]) {
				var opts = {};
				opts.name = citiesMaps[val].name;
				opts.url = citiesMaps[val].link;
				addMarker(map,citiesMaps[val]["lat"],citiesMaps[val]["lon"], (citiesMaps[val]["hasOffices"])?"green":"red", "", opts);
			}
		});
	}
}

function analyzeOneworldCountryMap(country) {
	if (country2city2address2view[country] && countriesMaps[country]) {
		map.setCenter(new GLatLng(countriesMaps[country]["lat"], countriesMaps[country]["lon"]), countriesMaps[country]["zoom"]);
		$.each(country2city2address2view[country], function(i, val){
			if (i!="0" && i!=0 && citiesMaps[i]) {
			var opts = {};
			opts.name = citiesMaps[i].name;
			opts.url = citiesMaps[i].link.replace('our_cities',oneworldLinkConstant);
			addMarker(map,citiesMaps[i]["lat"],citiesMaps[i]["lon"], "green", "", opts);
			}
		});
	}
}


function analyzeCountriesMap() {
		if (countriesMaps['RU']) {
		map.setCenter(new GLatLng(countriesMaps['RU']["lat"], countriesMaps['RU']["lon"]), countriesMaps['RU']["zoom"]);
		$.each(countriesMaps, function(i, val){
			$.each(countriesMaps[i]["cities"], function(j, val_j){
				if (citiesMaps[val_j]) {
					var opts = {};
					opts.name = citiesMaps[val_j].name;
					opts.url = citiesMaps[val_j].link;
					addMarker(map,citiesMaps[val_j]["lat"],citiesMaps[val_j]["lon"], (citiesMaps[val_j]["hasOffices"])?"green":"red", "", opts);
				}
			});
		});
	}
}

function analyzeOneworldCountriesMap() {
	if (country2city2address2view['RU'] && countriesMaps['RU']) 
		map.setCenter(new GLatLng(countriesMaps['RU']["lat"], countriesMaps['RU']["lon"]), countriesMaps['RU']["zoom"]);
	$.each(country2city2address2view, function(i, val){
		if (i!="0") {
			$.each(country2city2address2view[i], function(j, val_j){
				if (j!="0" && j!=0 && citiesMaps[j]) {
					var opts = {};
					opts.name = citiesMaps[j].name;
					opts.url = citiesMaps[j].link.replace('our_cities',oneworldLinkConstant);
					addMarker(map,citiesMaps[j]["lat"],citiesMaps[j]["lon"], "green", "", opts);
				}
			});
		}
	});
	
}


function addMarker(map, lat, lng, marker, popup, opts){
	var _type = (marker) ? marker : "green";
	var customIcon = new GIcon();
	customIcon.image = '/images/icons/office_' + _type + '.png';
	customIcon.shadow = '/images/icons/officeShadow.png';
	customIcon.iconSize = new GSize(12, 20);
	customIcon.shadowSize = new GSize(22, 20);
	customIcon.iconAnchor = new GPoint(6, 20);
	customIcon.infoWindowAnchor = new GPoint(6, 0);
	var point = new GLatLng(lat, lng);
	var markerOptions;
	var popupBody;
	
	if (popup == "city") {
		markerOptions = {
			icon: customIcon
		};
		popupBody = generateHtml(opts);
		var marker = new GMarker(point, markerOptions);
		GEvent.addListener(marker, "click", function(){
			marker.openInfoWindowHtml(popupBody);
		});
		map.addOverlay(marker);
	}
	if (popup == "") {
		markerOptions = {
			icon: customIcon,
			title: opts.name
		};
		var marker = new GMarker(point, markerOptions);
		GEvent.addListener(marker, "click", function(){
			location.href = opts.url;
		});
		map.addOverlay(marker);
	}
}

function generateHtml(opts) {
	var html = '';
	html += '<div class="office_popup"><div><span class="textBold">' + opts.address + '</span></div>';
	if (opts.subway != '') {
		html += '<div class="subway"> ' + opts.subway + '</div>';
	}
	if (opts.officeHours != '') {
		html += '<div> ' + hoursLabel + ' ' + opts.officeHours + '</div>';
	}
	if (opts.phone != '') {
		html += '<div> ' + phoneLabel + ' ' + opts.phone + '</div>';
	}
	if (opts.fax != '') {
		html += '<div> ' + faxLabel + ' ' + opts.fax + '</div>';
	}
	html += '</div>';
	return html;
}


