/**
 * AreaMap scripts to choose Google Maps location
 *
 * @copyright (c) 2004-2007, SWsoft
 */ 
var SHOW_MARKERS = 10;
var SHOW_ZOOM = true;
var SHOW_TYPE = true;
var FINDE_MARKERS = 20;
var SearchTableID = '';
var AddressID = ''; 
var MapID = '';
var MarkerContainerId = '';
var Inits = new Array();
var Edit = true;
var ErrorLabelId = '';

var selectedIcon =  null;
try{
	selectedIcon = new GIcon();
	selectedIcon.image = "";
	selectedIcon.shadow = "";
	selectedIcon.iconSize = new GSize(16, 27);
	selectedIcon.shadowSize = new GSize(30, 28);
	selectedIcon.iconAnchor = new GPoint(8, 27);
	selectedIcon.infoWindowAnchor = new GPoint(5, 1);
}
catch(e){}

var Localization = new Array();
try{
	Localization["UnableAddress"] = SbGetLocaleByKey('UnableAddress');
	Localization["MarkersLimit"] = SbGetLocaleByKey('MarkersLimit');
	Localization["InvalidKey"] = SbGetLocaleByKey('InvalidKey');
	Localization["NotSupported"] = SbGetLocaleByKey('NotSupported');
	Localization["Save"] = SbGetLocaleByKey('Save');
	Localization["Delete"] = SbGetLocaleByKey('Delete');
	Localization["Direction"] = SbGetLocaleByKey('Direction');
	Localization["Title"] = SbGetLocaleByKey('Title');
	Localization["Address"] = SbGetLocaleByKey('Address');
}
catch(e){}

var unselectedIcon = null;
try{
	unselectedIcon = new GIcon(selectedIcon);
	unselectedIcon.image = "";
}
catch(e){}

var Markers = new Array();

function Init(center, zoom, type, key)
{
	this.Center = center;
	this.Zoom = zoom;
	this.Type = type;
	this.Key = key;
}

function Marker(marker, title, enable, address)
{
	this.ID = marker["id"];
	this.Enable = enable;
	this.Title = title;
	this.Marker = marker;
	this.Address = address;
}

function Address(streetAddress, city, region, country)
{
	this.StreetAddress = streetAddress;
	this.City = city;
	this.Region = region;
	this.Country = country;
}

function SaveMarkers()
{
	var container = document.getElementById(MarkerContainerId);
	if (container)
	{
		if (map) {
			container.value = GetEscapedMarkersString();
		} else {
			container.value = 'google_not_supported';
		}
	}
}

function CountItems(collection, enable)
{
	var count = 0;
	for (var key in collection)
	{
		if ('undefined' != typeof(collection[key].Marker))
		{
			if (enable != null)
			{
				if (collection[key].Enable == enable)
				{
					count++;
				}
			}
			else
			{
				count++;
			}
		}
	}
	return count;
}

function PrintObject(obj)
{
	var str = "";
	var i = 0;
	for (var key in obj)
	{
		str += key + '=>' + obj[key];
		if (i > 10) {
			str += "\n";
		} else {
			str += " | ";
		}
	}
	alert(str);
}

function GetChar(index)
{
	var ret = "";
	switch (index)
	{
		case 10:
			ret = 'a';
			break;
		case 11:
			ret = 'b';
			break;
		case 12:
			ret = 'c';
			break;
		case 13:
			ret = 'd';
			break;
		case 14:
			ret = 'e';
			break;
		case 15:
			ret = 'f';
			break;
		default:
			ret = index.toString();
			break;
	}
	return ret;
}

function GetNewId()
{
	var id = "Marker";
	for (var i = 0; i < 32; i++)
	{
		var index = Math.floor(Math.random()*16);
		id += GetChar(index); 
	}
	return id;
}

function ShowAddress() {
	SetWarningMessage("", false, true, false);
	var address = document.getElementById(AddressID);
	try
	{
		gs.execute(address.value);
	}
	catch (e)
	{
		SetWarningMessage(Localization["UnableAddress"], false, true, false);
	}
}


var map = null;
var gs = null;

function RemoveMarker(id)
{
	map.removeOverlay(Markers[id].Marker);
	delete Markers[id];
	map.closeInfoWindow();
	SaveMarkers();
}

function SaveMarker(id, title, address)
{
	var pos = Markers[id].Marker.getPoint();
	var mapId = Markers[id].Marker["mapId"];
	var adr = Markers[id].Address;
	if (CountItems(Markers, true) == SHOW_MARKERS)
	{
		SetWarningMessage(Localization["MarkersLimit"], false, true, false);
	}
	else
	{
		RemoveMarker(id);
		CreateMarker(pos, true, id, address.value, title.value, mapId);
	}

	Markers[id].Title = title.value;
	Markers[id].Address = address.value;
	map.closeInfoWindow();
}

function ReplaceQuote(str)
{
	while(str.match(/\'/ig) != null){
		str=str.replace(/\'/ig,"&#39;");
	}
	return 	str;
}

function GetTitle(id)
{
	var result = "";
	try{
		result = Markers[id].Title;
	}catch(e){}
	return result;
}

function GetAddress(id)
{
	var result = "";
	try{
		result = Markers[id].Address;
	}catch(e){}
	return result;
}

function GetAddressFormatted(address)
{
	var result = "";
	if (address == null)
	{
		return result;//Markers[id].Marker.getPoint();
	}
	if (address.StreetAddress != "")
	{
		result += address.StreetAddress;
	}
	if (address.City != "")
	{
		result += ", ";
		result += address.City;
	}
	if (address.Region != "")
	{
		result += ", ";
		result += address.Region;
	}
	return result;
}

function GetDirection(id, from)
{
	var str = "http://www.google.com/maps?source=uds";
	var point = Markers[id].Marker.getPoint();
	str += "&saddr="+from.value;
	str += "&daddr="+point.lat()+","+point.lng();
	window.open(str);
}

function GetPreviewUrl()
{
	var div = document.getElementById(MapID);
	var container = div.childNodes[0].childNodes[0].childNodes[1].childNodes[0];
	var imgs = container.childNodes; 
	var index = 0;
	var point = map.fromLatLngToDivPixel(map.getCenter());
	for (var i = 0; i < imgs.length; i++)
	{
		
		var x = parseInt(imgs[i].style.left);
		var y = parseInt(imgs[i].style.top);
		if ((x+256) >= point.x && x < point.x && (y+256) >= point.y && y < point.y)
		{
			index = i;
			break;
		}
	}
	return imgs[index].src;
}

function GetEscapedMarkersString()
{
	var str = "{";
	str += "\"Map\":{";
	str += "\"zoom\":\""+ escapeQuote(map.getZoom())+"\",";
	str += "\"center_lat\":\""+ escapeQuote(map.getCenter().lat())+"\",";
	str += "\"center_lng\":\""+ escapeQuote(map.getCenter().lng())+"\",";
	str += "\"preview_url\":\""+ escapeQuote(GetPreviewUrl())+"\",";
	str += "\"type\":\""+ escapeQuote(map.getCurrentMapType().getName())+"\"";
	str += "},";
	str += "\"Markers\":[";
	for (var key in Markers)
	{
		if (('undefined' != typeof(Markers[key].Marker)) && (Markers[key].Enable))
		{
			var item = "{\"marker_id\":\""+escapeQuote(Markers[key].ID)+"\",\"title\":\""+escapeQuote(Markers[key].Title)+"\",\"point_lat\":\""+escapeQuote(Markers[key].Marker.getPoint().lat())+"\",\"point_lng\":\""+escapeQuote(Markers[key].Marker.getPoint().lng())+"\",\"address\":\""+escapeQuote(Markers[key].Address)+"\"}";
			str += item;
			str += ",";
		}
	}
	if (str.substr(str.length-1,1) == ",")
	{
		str = str.substr(0,str.length-1);
	}
	str += "]}";
	return str;
}

function escapeQuote(str)
{
	try {
		str = str.replace(/\\/ig, '\\\\');
		str = str.replace(/\"/ig, '\\"');
	} catch(e){ }
	return str;
}

function _htmlSpecialChars(str) {
	try {
		str = str.replace(/&/ig, '&amp;');
		str = str.replace(/\?/ig, '&#63;');
		str = str.replace(/</ig, '&lt;');
		str = str.replace(/>/ig, '&gt;');
		str = str.replace(/\'/ig, '&#39;');
		str = str.replace(/\"/ig, '&#34;');
	} catch(e){ }

	return str;
}

function _unHtmlSpecialChars(str) {
	try {
		str = str.replace(/&#34;/ig, '\"');
		str = str.replace(/&#39;/ig, "'");
		str = str.replace(/&gt;/ig,'>');
		str = str.replace(/&lt;/ig,'<');
		str = str.replace(/&#63;/ig,'?');
		str = str.replace(/&amp;/ig, '&');
	} catch(e){ }

	return str;
}

function GetInfoHtml(id, markAddress)
{
	var str = "";
	var title = _htmlSpecialChars(GetTitle(id));
	var address = _htmlSpecialChars(GetAddress(id));
	
	if (Edit)
	{
		str += "<table width='150px' border='0' cellpadding='2' cellspacing='0'><tr><td style='font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; color: black;'>";
		str += Localization["Title"];
		str += "</td>";
		str += "<td>";
		str += "<input id='Title"+id+"' value='"+title+"' style='border: 1px solid #999EA1; color: black; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px;'/>";
		if (markAddress == true && address != "")
		{
			str += "</td></tr><tr bgcolor='#FFD9D9'><td style='font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; color: black;'>";
		}
		else
		{
			str += "</td></tr><tr><td style='font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; color: black;'>";
		}
		str += Localization["Address"];
		str += "</td>";
		str += "<td>";
		str += "<input id='Address"+id+"' value='"+address+"' style='border: 1px solid #999EA1; color: black; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px;'/>"
		str += "</td></tr><tr><td>";
		str += "</td>";
		str += "<td align='right'>";
		str += "<span style='font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; color: blue; text-decoration: underline; cursor: pointer;' onclick=\"SaveMarker('"+id+"', document.getElementById('Title"+id+"'), document.getElementById('Address"+id+"'));\">"+Localization["Save"]+"</span>  <span  style='font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; color: blue; text-decoration: underline; cursor: pointer;' onclick=\"RemoveMarker('"+id+"');\">"+Localization["Delete"]+"</span>";
		str += "</td></tr></table>";
	}
	else
	{
		
		str += "<table width='100px' border='0'>";
		if (title != "")
		{
			str += "<tr><td style='font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; color: #000000;'>"+Localization["Title"];
			str += "</td><td style='font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; color: #000000;'>";
			str += title+"</td></tr>";	
		}
		if (address != "")
		{
		str += "<tr><td style='font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; color: #000000;'>"+Localization["Address"];
		str += "</td><td style='font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; color: #000000;'>";
		str += address+"</td></tr>"
		}
		str += "<tr><td><span style='font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; color: blue; text-decoration: underline; cursor: pointer;' onclick=\"GetDirection('"+id+"', document.getElementById('From"+id+"'));\">"+Localization["Direction"]+"</span></td><td><input id='From"+id+"' value='' style='border: 1px solid #999EA1; color: black; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px;'/></td></tr>";
		str += "</table>";
	}
	return str;
}
// Creates a marker at the given point with the given number label
function CreateMarker(point, activ, oldId, address, title, mapId) {
	var marker = null;
	var enable = false;
	if (CountItems(Markers, true) == SHOW_MARKERS)
	{
		enable = false;
		activ = false
		SetWarningMessage(Localization["MarkersLimit"], false, true, false);
	}
	var currentIcon = unselectedIcon;
	if (activ == true)
	{
		currentIcon = selectedIcon;
		enable = true;
	}

	if (Edit)
	{
		marker = new GMarker(point, {draggable: true, icon: currentIcon});
	}
	else
	{
		marker = new GMarker(point);
	}
	var id = GetNewId();
	if (oldId != null)
	{
		id = oldId;
	}
	marker["id"] = id;
	if (mapId != null)
	{
		marker["mapId"] = mapId;
	}
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(GetInfoHtml(marker["id"], false));

	});
	GEvent.addListener(marker, "dragstart", function() {
		map.closeInfoWindow();
	});

	GEvent.addListener(marker, "dragend", function() {
		if(GetAddress(marker["id"]) != "")
		{
			marker.openInfoWindowHtml(GetInfoHtml(marker["id"], true));
		}
	});
	
	if(address == null || address == undefined) address = "";
	if(title == null || title == undefined) title = "";
	Markers[id] = new Marker(marker,title,enable, address);
	map.addOverlay(marker);
	SaveMarkers();
	return marker;
}


function ClearMarkers()
{
	for(var key in Markers)
	{
		if (('undefined' != typeof(Markers[key].Marker)) && (Markers[key].Enable == false))
		{
			RemoveMarker(key);
		}
	}
}


var markers = null;
function SetMarkers()
{
	ClearMarkers();
	var markers = new Array();
	var addresses = new Array();
	var bestResultUrl = null;
	if ( gs.results && gs.results.length > 0) {
		for (var i = 0; i < gs.results.length && i < FINDE_MARKERS; i++) {
			var result = gs.results[i];
			markers.push(new GSmapscLocalResult(this, result, i));
			addresses.push(new Address(result.streetAddress, result.city, result.region, result.country)); 
		}

			
		map.setCenter(markers[0], 13);
		for (var i = 0; i < markers.length; i++) {
			if (!IfExists(markers, markers[i], i) && !IfExists(Markers, markers[i]))
			{
				var marker = CreateMarker(markers[i], false, null, GetAddressFormatted(addresses[i]),null,MapID);
			}
		}
	}
	else
	{
		SetWarningMessage(Localization["UnableAddress"], false, true, false);
	}
}

function IfExists(collection, pos, index)
{
	var result = false;
	if (index != null)
	{
		for (var i = 0; i< collection.length; i++ )
		{
			if (collection[i].lat() == pos.lat() && collection[i].lng() == pos.lng() && i != index)
			{
				result = true;
				break;
			}
		}
	}
	else
	{
		for(var key in collection)
		{
			if (('undefined' != typeof(Markers[key].Marker)) &&
				(collection[key].Marker.getPoint().lat() == pos.lat() && collection[key].Marker.getPoint().lng() == pos.lng()))
			{
				result = true;
				break;
			}
		}
	}
	
	return result;
}

function GSmapscLocalResult(gsmsc, result, index) {
	latLng = new GLatLng(parseFloat(result.lat), parseFloat(result.lng));

	return latLng;
}

function Load(mapId, tableId, addressId, errorLabelId) {
	SearchTableID = tableId;
	AddressID = addressId; 
	ErrorLabelId = errorLabelId;
	MapID = mapId;

	if (typeof(GlocalSearch) == "undefined")
	{
		SetWarningMessage(Localization["InvalidKey"], true, true, false);
		return;
	}
	
	if (GBrowserIsCompatible()) {
		var p = document.getElementById(SearchTableID);
		if (p)
		{
			p.style.display = "";
		}
		gs = new GlocalSearch();
		gs.setResultSetSize(GSearch.LARGE_RESULTSET);
		gs.setSearchCompleteCallback(this, SetMarkers, [null]);
		
		var container = document.getElementById(mapId);

		for (var i in document.styleSheets) {
			if (document.styleSheets[i].rules && document.styleSheets[i].rules.length > 0) {
				for (var j in document.styleSheets[i].rules) {
					if ('IMG' == document.styleSheets[i].rules[j].selectorText) {
						document.styleSheets[i].removeRule(j);
					}
				}
			}
		}

		map = new GMap2(container);

		if (Edit)
		{
			GEvent.addListener(map, "click", function(marker, point) {
				if (!marker) {
					var marker = CreateMarker(point, false, null, null, null, mapId);
					if (marker != null)
					{
						marker.openInfoWindowHtml(GetInfoHtml(marker["id"], false));
					}
				}
			});
		}
		
		if (SHOW_ZOOM)
		{
			map.addControl(new GSmallMapControl());
		}
		if (SHOW_TYPE)
		{
			map.addControl(new GMapTypeControl());
		}
		
		if (Inits[mapId].Center == null)
		{
			try
			{
				gs.execute("1600 Amphitheatre Pky, Mountain View, CA");
			}
			catch (e)
			{
				SetWarningMessage(Localization["UnableAddress"], false, true, false);
			}
			
		}
		else
		{
			map.setCenter(Inits[mapId].Center);
			for (var key in Markers)
			{
				if (('undefined' != typeof(Markers[key].Marker)) && (Markers[key].Marker["mapId"] == mapId))
				{
					CreateMarker(Markers[key].Marker.getPoint(), Markers[key].Enable, Markers[key].ID, Markers[key].Address, Markers[key].Title, mapId);
				}
			}
		}

		if (Inits[mapId].Zoom != null)
		{
			map.setZoom(Inits[mapId].Zoom);
		}
		if (Inits[mapId].Type != null)
		{
			var types = map.getMapTypes();
			for (var i = 0;i < types.length; i++)
			{
				if (types[i].getName() == Inits[mapId].Type)
				{
					map.setMapType(types[i]);
					break;
				}
			}
		}
	}
	else
	{
		SetWarningMessage(Localization["NotSupported"], true, true, false);
	}
}

function SetWarningMessage(message, showInDiv, ShowInBar, showAlert )
{
	if (ShowInBar)
	{
		if (ErrorLabelId != '')
		{
			var bar = document.getElementById(ErrorLabelId);
			if (bar)
			{
				bar.innerHTML = message;
			}
		}
		else
		{
			if (message != '')
			{
				alert(message);
			}
		}
	}
	if (showInDiv)
	{
		var div = document.getElementById(MapID);
		div.innerHTML = message;
	}
	if (showAlert)
	{
		if (message != '')
		{
			alert(message);
		}
	}
}

function AddEvent(el, evname, func) {
	if (document.all) {
		el.attachEvent("on" + evname, func);
	} else {
		el.addEventListener(evname, func, true);
	}
};

function OnOk()
{
	SaveMarkers();
}