/**
MAP Functions
*/

var gMap = null;
var ajaxCallHandlerPath = null;
var moduleBasePath = "";

function desimap_LoadMap(lat, lng) 
{
	//Load the gMap and print in on the screen
	if (GBrowserIsCompatible()) 
	{
		var mapCenterLat = lat;
		var mapCenterLng = lng;

		gMap = new GMap2(document.getElementById("idDivMap"));
		gMap.clearOverlays();

		gMap.setCenter(new GLatLng(mapCenterLat, mapCenterLng, false), 11);
		gMap.addControl(new GLargeMapControl());
		//gMap.addControl(new GMapTypeControl());

		GEvent.addListener(gMap, "infowindowclose", function() {
			try
			{
				document.getElementById('idTxtMyLocation').blur();
			}
			catch (err_)
			{
			}
		});
  }
}

function desimap_UnLoadWindow() 
{
	//setCookie(CookieName, '', 1);
}

function desimap_UnLoadMap() 
{
	//write cookies
	var CookieData = desimap_ConstructCookie();
	setCookie(CookieName, CookieData, 1);

	//unload gmap
	if (gMap != null) 
	{
		try
		{
			GUnload();	
		}
		catch (e)
		{
			alert(e);
		}
	}
}
function desimap_LoadDefaults()
{
	try
	{
		//Set default values in the my-location textbox.
		document.getElementById('idTxtMyLocation').value = DefaultLocationTextBoxValue;
		
		IconFileArray.push('icon_red.png');
		IconFileArray.push('icon_yellow.png');
		IconFileArray.push('icon_blue.png');
		IconFileArray.push('icon_green.png');
		IconFileArray.push('icon_purple.png');
		IconFileArray.push('icon_maroon.png');
		IconFileArray.push('icon_orange.png');
		IconFileArray.push('icon_pink.png');
	}
	catch (err)
	{
		alert(err);
	}


	var savedSettings = '';

	if(checkCookie(CookieName))
	{
		savedSettings = getCookie(CookieName);
		desimap_LoadDefaultsFromXml(savedSettings);
	}
	else
	{
		var loadXml = '<?xml version="1.0" encoding="ISO-8859-1"?><settings><myLocation></myLocation><filter><divid id="1" open="1"><checkbox>Places_Grocery Stores</checkbox></divid><regionIndex>0</regionIndex></filter></settings>';
		desimap_LoadDefaultsFromXml(loadXml);
	}

	document.getElementById('idTxtMyLocation').blur();

}

function desimap_LoadDefaultsFromXml(xmlStr)
{
	/////////// CREATE XML OBJECT
	xmlObj = null;
	try
	{
		xmlObj = GetXmlObject(xmlStr);	
	}
	catch (err)
	{
		xmlObj = null;
		alert(err);
	}
	
	if(xmlObj == null)
	{
		alert('XMLDom is not supported on your browser'); return;
	}


	/////////// LOAD MYLOCATION
	myLocText = '';
	try
	{
		myLocationElement = xmlObj.getElementsByTagName('myLocation')[0];
		try
		{
			myLocText = myLocationElement.text;
			if(myLocText == '')
			{
				myLocText = myLocationElement.textContent;
			}
		}
		catch (errA0)
		{
			try{myLocText = myLocationElement.textContent;}
			catch (errB0)
			{
			}
		}
	}
	catch (errC0){}

	try{
		if(myLocText != '' && myLocText != 'undefined')
		{
			document.getElementById('idTxtMyLocation').value = myLocText;
			document.getElementById('idTxtMyLocation').style.color = '#000000';
		}
	}
	catch (errD0){}

	/////////// CLICK DEFAULT REGION (EASTSIDE, WEST SEATTLE, ETC)
	regionIndex = 0;
	try
	{
		regionIndexElement = xmlObj.getElementsByTagName('regionIndex')[0];
		try
		{
			regionIndex = regionIndexElement.text;
			if(regionIndex == '')
			{
				regionIndex = regionIndexElement.textContent;
			}
		}
		catch (errA1)
		{
			try{regionIndex = regionIndexElement.textContent;}
			catch (errB1)
			{
			}
		}
	}
	catch (errC1){regionIndex = 0;}
	
	try{
		radioButtonId = 'grpPredefinedLocations-' + regionIndex;
		theRadioButton = document.getElementById(radioButtonId);
		theRadioButton.click();
	}
	catch (errD){regionIndex=0; predefMapPoints[regionIndex].Zoom();}


	//////////////// FIGURE OUT WHAT ALL CATEGORIES TO EXPAND
	divElements = xmlObj.getElementsByTagName('divid');

	for(index_=0; index_<divElements.length; index_++)
	{
		divElem = divElements[index_];
		divIndex = divElem.getAttribute("id");
		divOpen = divElem.getAttribute("open");

		if(divOpen == '1')
		{
			ToggleDiv('div'+divIndex, 'idLi'+divIndex);
		}

		//get all checkboxes in this DIV
		checkBoxes = divElem.getElementsByTagName('checkbox');

		for(index1_=0; index1_<checkBoxes.length; index1_++)
		{
			checkBox = checkBoxes[index1_];
			var checkBoxId = '';

			////////////// DIFFERENT METHODS FOR IE AND FIREFOX. RELY ON TRY-CATCH TO DO THE RIGHT THING :)
			try
			{
				checkBoxId = checkBox.text;
				if(checkBoxId == '')
				{
					checkBoxId = checkBox.textContent;
				}
			}
			catch (errA)
			{
				try{checkBoxId = checkBox.textContent;}
				catch (errB){}
			}

			if(checkBoxId == '') continue;
			try{document.getElementById(checkBoxId).click();}
			catch (errC){}
			
		}//end of foreach checkbox

	}//end of foreach div
}

function desimap_GetMyLocation()
{
	var inputBox = document.getElementById("idTxtMyLocation");
	return inputBox.value;
}

function desimap_TextBoxClicked()
{
	theTextBox = document.getElementById('idTxtMyLocation');
	if(theTextBox.value.toLowerCase() == DefaultLocationTextBoxValue.toLowerCase())
	{
		theTextBox.value='';
	}

	theTextBox.style.color = '#000000';
}

function desimap_TextBoxOnKeyDown(evt)
{
	evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode :
        ((evt.which) ? evt.which : evt.keyCode);
    if (charCode == 13 || charCode == 3) {
        desimap_TextBoxLostFocus('idTxtMyLocation');
    } 
}

function desimap_TextBoxFocussed()
{
	try
	{
		theTextBox = document.getElementById('idTxtMyLocation');
		if(theTextBox.value == '' ||  theTextBox.value == 'undefined')
		{theTextBox.value = DefaultLocationTextBoxValue;}

		if(theTextBox.value == DefaultLocationTextBoxValue)
		{
			theTextBox.style.color = '#AAAAAA';
		}
		else
		{
			theTextBox.style.color = '#000000';
		}
	}
	catch (err)
	{
		alert(err);
	}
	textBoxFocussedFlag = true;
}

function desimap_TextBoxLostFocus(textBoxId)
{
	textBoxFocussedFlag = false;
	theTextBox = document.getElementById(textBoxId);
	if(theTextBox == null || theTextBox == 'undefined')
	{
		return;
	}

	if(theTextBox.value == '' ||  theTextBox.value == 'undefined')// || theTextBox.value == DefaultLocationTextBoxValue)
	{
		theTextBox.value = DefaultLocationTextBoxValue;
	}

	if(theTextBox.value == DefaultLocationTextBoxValue)
	{
		theTextBox.style.color = '#AAAAAA';
	}
	else
	{
		theTextBox.style.color = '#000000';
	}

	var curTBValue = trim(theTextBox.value).toLowerCase();

	if(curTBValue == MyLocationString)
	{
		return;
	}

	if(curTBValue == DefaultLocationTextBoxValue.toLowerCase())
	{
		curTBValue = '';
	}

	MyLocationString = curTBValue;

	//iterate through all existing pushpins
	len = ArrayOfPushPinArray.length;
	for(index1 = 0; index1 < len; index1++)
	{
		var PushPinArray = ArrayOfPushPinArray[index1];

		if(PushPinArray == null) continue;
		if(PushPinArray == 'undefined') continue;

		try
		{
			var subLen = PushPinArray.length;
			for(index2 = 0; index2<subLen; index2++)
			{
				var CurPushPin = PushPinArray[index2];
				if(CurPushPin == null) continue;
				if(CurPushPin == 'undefined') continue;

				try
				{
					desimap_SetDistance(CurPushPin, MyLocationString);
				}
				catch (err1)
				{
				}
			}
		}
		catch (err2)
		{
		}
	}//end of for
}

function desimap_HotSpotSelected(drowpdownId)
{
	var theCombo = document.getElementById(drowpdownId);
	var selectedIndex = theCombo.selectedIndex;
	var option = theCombo.options[selectedIndex];
	var selectedText = option.value;

	document.getElementById("idTxtMyLocation").value = selectedText;
	document.getElementById("idTxtMyLocation").blur();
	desimap_TextBoxLostFocus("idTxtMyLocation");
}

function desimap_SetDistance(givenPushPin, newLocationString)
{
	if(givenPushPin.cachedMyLocation == newLocationString)
	{
		return;
	}

	givenPushPin.ComputeDistance(newLocationString);
}

function desimap_FilterEvent(category, subcategory)
{
	var chkBox = document.getElementById(category + '_' + subcategory);
	if(chkBox == null) return;
	if(chkBox == "undefined") return;

	if(chkBox.checked)
	{
		desimap_ApplyFilter(category, subcategory);
	}
	else
	{
		desimap_RemoveFilter(category, subcategory);
	}

	//desimap_DebugPushPinArrays();
}

function desimap_ApplyFilter(category, subcategory)
{
	PushPinArray = desimap_GetOrCreatePushPinArray(category, subcategory);
	if(PushPinArray != null && PushPinArray != "undefined" && PushPinArray.length > 0)
	{
		//check local cache first
		for(var i44=0; i44<pushPinLen; i44++)
		{
			var curPp = PushPinArray[i44];
			if(curPp == null) continue;
			
			curPp.iconImagePath = IconFileArray[GlobalSelectedIndex];
			curPp.Show();
		}//end of for
	}
	else
	{
		//not found in cache. Query
		var ajaxCall = new AjaxCall(ajaxCallHandlerPath);
		ajaxCall.SetCallback(desimap_Callback_AddNewPushpins);
		ajaxCall.SendRequest("ApplyFilter", "category=" + category + "&subcategory=" + subcategory, false);
	}
}

function desimap_RemoveFilter(category, subcategory)
{
	PushPinArray = desimap_GetOrCreatePushPinArray(category, subcategory);
	
	pushPinLen = PushPinArray.length;
	for(var i55=0; i55<pushPinLen; i55++)
	{
		var curPp = PushPinArray[i55];
		if(curPp == null) continue;
		
		if(  (trim(curPp.category) == trim(category)) &&
			(trim(curPp.subcategory) == trim(subcategory)))
		{
			curPp.Hide();
		}
	}//end of for
}

function desimap_Callback_AddNewPushpins(xmlDoc)
{
	meArray = xmlDoc.getElementsByTagName('MappableEntity');
	len = meArray.length;

	for(index=0; index<len; index++)
	{
		try
		{
			curMe = meArray[index];
			
			var _lat = (curMe.getElementsByTagName('Latitude')[0]).childNodes[0].nodeValue;
			var _lng = (curMe.getElementsByTagName('Longitude')[0]).childNodes[0].nodeValue;
			var _addr = (curMe.getElementsByTagName('Address')[0]).childNodes[0].nodeValue;

			var _street = (curMe.getElementsByTagName('Street')[0]).childNodes[0].nodeValue;
			var _city = (curMe.getElementsByTagName('City')[0]).childNodes[0].nodeValue;
			var _state = (curMe.getElementsByTagName('State')[0]).childNodes[0].nodeValue;
			var _zip = (curMe.getElementsByTagName('Zip')[0]).childNodes[0].nodeValue;
			var _country = (curMe.getElementsByTagName('Country')[0]).childNodes[0].nodeValue;

			var curPp = new PushPin(_lat, _lng, _addr);

			curPp.name = (curMe.getElementsByTagName('Name')[0]).childNodes[0].nodeValue;
			curPp.description = (curMe.getElementsByTagName('Description')[0]).childNodes[0].nodeValue;
			curPp.rating = (curMe.getElementsByTagName('Rating')[0]).childNodes[0].nodeValue;
			curPp.phNum = (curMe.getElementsByTagName('PhNum')[0]).childNodes[0].nodeValue;
			curPp.category = (curMe.getElementsByTagName('Category')[0]).childNodes[0].nodeValue;
			curPp.subcategory = (curMe.getElementsByTagName('SubCategory')[0]).childNodes[0].nodeValue;
			curPp.nodeId = (curMe.getElementsByTagName('NodeId')[0]).childNodes[0].nodeValue;
			curPp.url = (curMe.getElementsByTagName('Url')[0]).childNodes[0].nodeValue;

			try
			{
				var l_datestr = (curMe.getElementsByTagName('StartTime')[0]).childNodes[0].nodeValue;
				curPp.startTime = new Date(l_datestr.replace(/-/g, "/")); 
			}
			catch (errx)
			{
				//alert(errx);
			}

			try
			{
				var l_datestr = (curMe.getElementsByTagName('EndTime')[0]).childNodes[0].nodeValue;
				curPp.endTime = new Date(l_datestr.replace(/-/g, "/")); 
				//curPp.endTime = new Date((curMe.getElementsByTagName('EndTime')[0]).childNodes[0].nodeValue);
				//curPp.endTime = (curMe.getElementsByTagName('EndTime')[0]).childNodes[0].nodeValue;
			}
			catch (errx)
			{
				//alert(erry);
			}
			
			

			curPp.street = _street;
			curPp.city = _city;
			curPp.state = _state;
			curPp.zip = _zip;
			curPp.country = _country;

			//TODO: Get an Existing Pushpin if (you already have it) or else, create a new One
			//When you get an existing pushpin, check if the data is similar to the new data. ??? (do we need this?)

			var existingPin = SearchPin(curPp);

			if(existingPin == null)
			{
				var PushPinArray = desimap_GetOrCreatePushPinArray(curPp.category, curPp.subcategory);
				PushPinArray.push(curPp);
				curPp.iconImagePath = IconFileArray[GlobalSelectedIndex % IconFileArray.length];
				curPp.Show();
			}
			else
			{
				if(existingPin.visible == false)
				{
					existingPin.Show();
				}
			}
		}
		catch (err)
		{
			txt="There was an error on this page.\n\n";
			txt+="Error description: " + err.description + "\n\n";
			txt+="Click OK to continue.\n\n";
			alert(txt);
		}
	} //end of for

}

function desimap_ClearMap()
{
	//divWithFilter = document.getElementById("idDivFilterContents");
	var chkBoxes = document.getElementById('idDivFilterContents').getElementsByTagName("input");
	for (var ind=0; ind<chkBoxes.length; ind++)
	{ 
		if(chkBoxes[ind].type != 'checkbox')
		{
			continue;
		}

		if(chkBoxes[ind].checked == true)
		{
			chkBoxes[ind].checked = false;
			var iid = chkBoxes[ind].id;
			var cat_subcat=iid.split("_");
			desimap_FilterEvent(cat_subcat[0], cat_subcat[1]);
		}
	}
	return false;
}

function desimap_GetOrCreatePushPinArray(category, subcategory)
{
	var key = category + '_' + subcategory;
	key = key.toLowerCase();

	var len = CategoryArray.length;
	var selectedIndex = -1;
	for(i=0; i<len; i++)
	{
		if(trim(CategoryArray[i]) == trim(key))
		{
			selectedIndex = i; break;
		}
	}//end of for

	if(selectedIndex == -1)
	{
		CategoryArray.push(key);

		NewPushPinArray = new Array();
		ArrayOfPushPinArray.push(NewPushPinArray);
		selectedIndex = len;
	}

	GlobalSelectedIndex = selectedIndex;
	return ArrayOfPushPinArray[selectedIndex];
}

/**
 MISCELLANEOUS Functions
 */
 function desimap_ClickPredefinedLocation(index)
 {
	 var mp = predefMapPoints[index];
	 if(mp == "undefined") return;
	 mp.Zoom();
 }

 function desimap_DebugPushPinArrays()
 {
	 var str = '';
	 var len = CategoryArray.length;
	 str = CategoryArray.length + ' ' + ArrayOfPushPinArray.length + "\r\n";
	 for(i=0; i<len; i++)
	 {
		 str += CategoryArray[i];
		 var ppArray = ArrayOfPushPinArray[i];
		 str += " " + ppArray.length + "\r\n";
	 }

	 alert(str);

 }

 function desimap_ConstructCookie()
 {
	 			// = myLocText;
	 //var loadXml = '<filter><divid id="1" open="1"><checkbox>Places_Grocery Stores</checkbox></divid><regionIndex>0</regionIndex></filter>';
	
	var retStr = '<settings>';

	/////////// MYLOCATION
	retStr += '<myLocation>';
	retStr += trim(document.getElementById('idTxtMyLocation').value);
	retStr += '</myLocation>';

	/////////// FILTERS
	retStr += '<filter>';
	var filterDivId = 'idDivFilterContents';
	var filterDiv = document.getElementById(filterDivId);
	if(filterDiv != null && filterDiv != 'undefined')
	{
		allFilterDivs = filterDiv.getElementsByTagName('div');
		for(index1=0; index1<allFilterDivs.length; index1++)
		{
			curFilterDiv = allFilterDivs[index1];
			if(curFilterDiv.id.indexOf('div') == 0)
			{
				idToUse =curFilterDiv.id.substr(3);
				isOpen = 0;
				try{if(curFilterDiv.style.display == "block") isOpen = 1;}catch(err1){isOpen = 0;}
				
				retStr += '<divid id="' + idToUse + '" open="' + isOpen + '">';

				//figure out checkboxes in ths div
				allInputBoxes = curFilterDiv.getElementsByTagName('input');

				for(index2=0; index2<allInputBoxes.length; index2++)
				{
					curInputBox = allInputBoxes[index2];
					if(curInputBox.type != "checkbox")
					{
						continue;
					}

					if(curInputBox.checked)
					{
						retStr += '<checkbox>' + curInputBox.id + '</checkbox>';
					}
				}//end of foreach input

				retStr += '</divid>';
			}
		}//end of foreach filterDiv
	}


	////////// REGIONS
	var predefLocDivId = 'idTdPredefLocations';
	var predefLocDiv = document.getElementById(predefLocDivId);
	retStr += '<regionIndex>';
	if(predefLocDiv != null && predefLocDiv != 'undefined')
	{
		allRadioButtons = predefLocDiv.getElementsByTagName('input');
		for(index3=0; index3<allRadioButtons.length; index3++)
		{
			curRadioButton = allRadioButtons[index3];
			if(curRadioButton.type != 'radio') continue;
			
			if(curRadioButton.checked)
			{
				retStr += index3;
				break;
			}
		}
	}
	retStr += '</regionIndex>';
	retStr += '</filter></settings>';

	return retStr;
 }



///////////// TABLE SORT METHODS -- START

function desimap_SortPushpinList(ColName, imgId, colIndex)
{
	var upicon = "up.png"; 
	var downicon = "down.png"; 
	var noicon = "noimage.png";
	sortOrder = "asc";
	curImgName = document.getElementById(imgId).src;
	newImgName = '';
	CurrentSortColIndex = colIndex;

	////RESET ALL HEADER ICONS -- START
	var TableHeaderDiv = document.getElementById("idDivItemsTableHeader");
	if(TableHeaderDiv != null && TableHeaderDiv != "unknown")
	{
		var AllThElems = document.getElementsByTagName("th");
	    for(i=0; i<AllThElems.length; i++)
		{
			var curTh = AllThElems[i];
			var curImgElem = curTh.getElementsByTagName("img")[0];
			if(curImgElem.src.indexOf(downicon) > 0) curImgElem.src = curImgElem.src.replace(downicon, noicon);
			if(curImgElem.src.indexOf(upicon) > 0) curImgElem.src = curImgElem.src.replace(upicon, noicon);
		}
	}
	////RESET ALL HEADER ICONS -- END

	////SET NEW ICON -- START
	if(curImgName.toLowerCase().indexOf("up.png") > 0)
	{
		sortOrder = "dsc";
	}

	if(sortOrder == "asc")
	{
		CurrentSortOrder = 0; //0=>ASC, 1=>DSC

		if(curImgName.toLowerCase().indexOf(downicon) > 0) newImgName = curImgName.replace(downicon, upicon);
		else if(curImgName.toLowerCase().indexOf(noicon) > 0) newImgName = curImgName.replace(noicon, upicon);
	}
	else
	{
		CurrentSortOrder = 1; //0=>ASC, 1=>DSC
		
		if(curImgName.toLowerCase().indexOf(upicon) > 0) newImgName = curImgName.replace(upicon, downicon);
		else if(curImgName.toLowerCase().indexOf(noicon) > 0) newImgName = curImgName.replace(noicon, downicon);
	}
	document.getElementById(imgId).src = newImgName;
	////SET NEW ICON -- END


	//// ACTUAL SORT FUNCTIONALITY -- START (DSC)
	_desimap_HideAllPushpinsOnTable();
	_desimap_ShowAllPushpinsOnTable();
	//// ACTUAL SORT FUNCTIONALITY -- END

	return false;
}

function _desimap_HideAllPushpinsOnTable()
{
	for(var i11=0; i11<ArrayOfPushPinArray.length; i11++)
	{
		curPushPinArray = ArrayOfPushPinArray[i11];
		if(curPushPinArray == null) continue;

		for(var j11=0; j11<curPushPinArray.length; j11++)
		{
			curPushPin = curPushPinArray[j11];
			if(curPushPin == null) continue;

			if(curPushPin.visible == true)
			{
				curPushPin._HideTableRow();
			}
		}
	}
}

function _desimap_ShowAllPushpinsOnTable()
{
	for(var i22=0; i22<ArrayOfPushPinArray.length; i22++)
	{
		curPushPinArray = ArrayOfPushPinArray[i22];
		if(curPushPinArray == null || curPushPinArray == "undefined")
		{
			//alert('null PPArray'); 
			continue;
		}

		for(var j22=0; j22<curPushPinArray.length; j22++)
		{
			curPushPin = curPushPinArray[j22];
			if(curPushPin == null || curPushPin == "undefined")
			{
				//alert('null PP'); 
				continue;
			}

			if(curPushPin.visible == true)
			{
				//alert("Visible: " + curPushPin.name);
				curPushPin._ShowTableRow();
			}
			else
			{
				//alert("Invisible: " + curPushPin.name);
			}
		}
	}
}

function _desimap_GetInsertIndex(tableRef, name, city, distance, imagename)
{
	var strToCompare = '';
	if(CurrentSortColIndex == 2) strToCompare = city;
	else if(CurrentSortColIndex == 4) strToCompare = distance;
	else if(CurrentSortColIndex == 1) strToCompare = name;
	else if(CurrentSortColIndex == 0) strToCompare = imagename;
	else return 0;

	if(tableRef.rows == null || tableRef.rows == 'undefined' || tableRef.rows.length <= 0)
	{return 0;}

	var allRows = tableRef.rows;
	for(var i33=0; i33<allRows.length; i33++)
	{
		var curRow = allRows[i33];
		var curComparisonValue = curRow.cells[CurrentSortColIndex].innerHTML;
		if(CurrentSortOrder == 0) //0=>ASC, 1=>DSC
		{
			if(curComparisonValue.toLowerCase() >= strToCompare.toLowerCase())
			{
				return i33;
			}
		}
		else
		{
			if(curComparisonValue.toLowerCase() <= strToCompare.toLowerCase())
			{
				return i33;
			}
		}
	}//end of for

	return -1;
}

///////////// TABLE SORT METHODS -- END

var GlobalSelectedIndex = 0;
var predefMapPoints = new Array();
var CategoryArray = new Array();
var IconFileArray = new Array();
var ArrayOfPushPinArray = new Array();
var MyLocationString = '';
var textBoxFocussedFlag = false;
var CookieName = "UISettings";
var DefaultLocationTextBoxValue = '<Enter your location address for Distance and Directions>';
var CurrentSortColIndex = 2;
var CurrentSortOrder = 0; //0=>ASC, 1=>DSC


