var go = true;
var tries = 0;
var ajax = new GLM.AJAX();
var cntrRow = 0;
var apiKey = "ABQIAAAAfr1Kka6TdC3YThX7HIPMIBSJYfbldFIHIMvFZGY7SFfunOft5RRHRgAwBxFi3S3KQuiOLhjolSziKA";
var accuracyArr = new Array("Unknown","Country","State","County","Town","Zip","Street","Intersection","Address","Premise");
var trs = new Array();

function startUpload () {
	document.getElementById('divselectfile').style.visibility = 'hidden';
	initOverlay(); 
	ShowOverlay(true);
	
	var fileDescr = "Brought to you by Totally Awesome Mapping";
	var tblHtml = "<div style=\"text-align: center;\"><style type=\"text/css\">#tblSummary td{text-align:left;}</style>"
		+"<table id=\"tblSummary\" style=\"float: left;\">"
		+"<tr><td style=\"width: 150px;\"><b>Upload File:</b></td><td id=\"tdUploadFile\">Processing...</td></tr>"
		+"<tr><td><b>Load Address Data:</b></td><td id=\"tdLoadAddress\">Pending</td></tr>"
		+"<tr><td><b>Geocode Locations:</b></td><td id=\"tdGeocodeLocations\">Pending</td></tr>"
		+"<tr><td><b>Build Styles:</b></td><td id=\"tdBuildStyles\">Pending</td></tr>"
		+"<tr><td><b>Build Placemarks:</b></td><td id=\"tdBuildPlacemarks\">Pending</td></tr>"
		+"<tr><td><b>Generate KML:</b></td><td id=\"tdGenerateKml\">Pending</td></tr>"
		+"<tr><td><b>Display Map:</b></td><td id=\"tdDisplayMap\">Pending</td></tr>"
		+"</table>"
		+"<div id=\"divMap\" style=\"height: 250px; width: 250px; margin-left: 240px; border: solid black 1px; text-align: center;\"><img src=\"gizmo/images/loading.gif\" alt=\"\" /><br /><br />Loading...</div>"
		+"<br style=\"clear: both;\" />"
		+"<div id=\"divLoading\" style=\"text-align: center;\"><br /><br /><button onclick=\"CancelProcessing(); return false;\" style=\"padding: 3px;\">Cancel Processing</button></div>"
		+"</div>"
		+"<input type=\"hidden\" id=\"hdnFileDescr\" />"
		+"<input type=\"hidden\" id=\"hdnFileName\" />"
		+"<input type=\"hidden\" id=\"hdnGizmoUseId\" />";
	$("divBox").innerHTML = tblHtml;
	$("hdnFileDescr").value = fileDescr;
	
	$("myForm").target = "ifmupload";
	$('myForm').submit();
} 

function TrackEvent(event, notes) {
	//ajax.callPage('gizmo/db_log.php', function (response) { }, "POST", "gizmoUseId="+$("hdnGizmoUseId").value + "&event="+event+"&notes="+notes);
	ajax.callPage('gizmo_log_entry.aspx', function (response) { }, "POST", "gizmoUseId="+$("hdnGizmoUseId").value + "&event="+event+"&notes="+notes);
}

document.uploadComplete = function(response) {
	var respParts = response.split("|");
	if (respParts[0] == "ok") {
		$("hdnFileName").value = respParts[1].replace(/~/g, "\\");
		ajax.callPage('scripts.aspx', function (response) {
			$("hdnGizmoUseId").value = "a7e6e4db711f20e2115437cc7b2678b2" + response;
			TrackEvent("Upload Successful",response);
			startGeocode();
		}, "POST", "a=GetUseId&user="+$("hdnUsername").value);
		
	} else {
		TrackEvent("Upload Error",$("hdnFileName").value+"|"+response);
		alert("There was an error while uploading your file.");
		//alert($("hdnFileName").value+"|"+response);
	}
}

function startGeocode() {
	
	fileName = $("hdnFileName").value;
	$("tdUploadFile").innerHTML = "Done!";
	$("tdLoadAddress").innerHTML = "Processing...";
	
	if (fileName == "") {
		alert("No file selected!");
	} else {
		
		ajax.callPage('gizmo/read_excel_file.php', function (response) {
			if (response == "ERROR") {
				ShowOverlay(false);
				go = false;
				TrackEvent("Read Excel File Error",fileName);
				alert("Your user information has become corrupted. Please try again.");
			} else {
				document.getElementById("divData").innerHTML = response.replace(/&lt;/g,"<").replace(/&gt;/g,">");
				
				trs = GetChildrenByTagName($("tblAddresses").getElementsByTagName("TBODY")[0], "TR");
	
				
				$("tdLoadAddress").innerHTML = "Done!";
				$("tdGeocodeLocations").innerHTML = "<span id=\"spnGeocodeCnt\">0</span> of "+trs.length;
				
				//StartParsing();
				go = true;
				cntrRow = 0;
				sendRequest();
			}
		}, "POST", "file="+fileName+"&user="+$("hdnUsername").value+"&encrypt="+$("hdnEncrypt").value);
	}
}
			
function GetChildrenByTagName(el, tag) {
	var tmpChildNodes = el.childNodes;
	var tmpRetArr = new Array();
	for (var i = 0; i < tmpChildNodes.length; i++) {
		if (tmpChildNodes[i].tagName == tag.toUpperCase()) tmpRetArr[tmpRetArr.length] = tmpChildNodes[i]; //else alert("no");
	}
	return tmpRetArr;
}

function $(id) { return document.getElementById(id); }

function CancelProcessing() {
	TrackEvent("Processing Stopped","");
	go = false;
	ShowOverlay(false);
	$("divselectfile").style.visibility = "visible";
	$("divselectfile").innerHTML = "Select a file: <input name=\"myfile\" type=\"file\" size=\"30\" onchange=\"startUpload();\" /><input type=\"hidden\" value=\"uploadComplete\" id=\"callback\" name=\"callback\" /><iframe id=\"ifmupload\" name=\"ifmupload\" src=\"#\" style=\"width:0; height:0; border: 0px solid white;\"></iframe>";
}

function ShowOverlay(show) {
	var divOverlay = $("divOverlay");
	var divShader = $("divShader");
	var divBox = $("divBox");
	
	if (show) {
		// set the shader and overlay to cover the whole page - not just the top screenful
		
		var windowHeight = document.documentElement.clientHeight;
		var windowWidth = document.documentElement.clientWidth;
		
		// set the vertical position of the dialog box - adjust for scroll position
		divBox.style.top = "20%";//(windowHeight/2-divBox.offsetHeight/2) + 'px';
		
		divOverlay.style.height = (windowHeight > document.body.offsetHeight ? windowHeight : document.body.offsetHeight) + 'px';
		divShader.style.height = divOverlay.style.height;

		divOverlay.style.visibility = 'visible';
		divShader.style.visibility = 'visible';
	} else {
		divOverlay.style.visibility = 'hidden';
		divShader.style.visibility = 'hidden';
	}
}

function initOverlay() {
	//Setup the div that shades the page if it doesn't already exist
	var divShader = document.getElementById("divShader");
	if (!divShader) {
		divShader = document.createElement("div");
		divShader.id = "divShader";
		divShader.style.cssText = 
			'visibility: hidden; position: fixed; left: 0px; top: 0px; width: 100%; text-align: center; '+
			'background-color: black; filter:alpha(opacity=70); -moz-opacity:.70; opacity:.70; z-index: 10000';
		document.body.appendChild(divShader);
	}
	
	// setup the div that contains the dialog box (cannot be same as shader, or dialog box will be transparent)
	var divOverlay = document.getElementById("divOverlay");
	if (!divOverlay) {
		divOverlay = document.createElement('div');
		divOverlay.id = "divOverlay";
		divOverlay.style.cssText = 
			'visibility: hidden; position: fixed; left: 0px; top: 0px; width: 100%; text-align: center; '+
			'z-index: 10001';
		document.body.appendChild(divOverlay);
	}
		
	// setup the dialog box
	var defaultWidth = 500;
	var windowWidth = document.documentElement.clientWidth;
	
	var divBox = $("divBox");
	if (!divBox) {
		divBox = document.createElement('div');
		divBox.id = "divBox";
		divBox.style.cssText = 
			'width: '+defaultWidth
			+'px; margin: 0; background-color: white; border: 1px solid black; padding: 10px; text-align: center; position: fixed; left: '
			+(windowWidth/2-parseInt(defaultWidth,10)/2)+'px';
		divOverlay.appendChild(divBox);
	}
}
		
function sendRequest() {
	//var trs = $("tblAddresses").getElementsByTagName("TBODY")[0].getElementsByTagName("TR");
	//alert(trs.length);
	if (cntrRow < trs.length) {
	//if (10 > cntrRow) {
		//Set Style
		//trs[cntrRow].className = "sending";
		var tds = GetChildrenByTagName(trs[cntrRow], "TD");
		
		var addr = escape(tds[1].innerHTML + ", " + tds[2].innerHTML + ", " + tds[3].innerHTML + " " + tds[4].innerHTML + ", " + tds[10].innerHTML);
		
		if (tds[5].innerHTML == "" || tds[6].innerHTML == "") {
			TrackEvent("Send Geocode Request - " + tds[10].innerHTML,addr);
			var requestURL = "http://maps.google.com/maps/geo?q=" + addr + "&output=json&sensor=true&key=" + apiKey + "&callback=geocodeResp";
 
			//Append new script			
			var script = document.createElement("script");
			script.id = "geoScript" + cntrRow;
			script.type = "text/javascript";
			script.src = requestURL;
			document.head.appendChild(script);
		} else {
			TrackEvent("Lat/Long Provided",tds[5].innerHTML + "|" + tds[6].innerHTML + "|" + addr);
			geocodeResp(null, true);
		}
	} else {
		StartParsing();
	}
}

function geocodeResp(obj, skip) {
	//var trs = $("tblAddresses").getElementsByTagName("TBODY")[0].getElementsByTagName("TR");
	
	var tds = GetChildrenByTagName(trs[cntrRow],"TD");
	var addr = tds[1].innerHTML + ", " + tds[2].innerHTML + ", " + tds[3].innerHTML + " " + tds[4].innerHTML + ", " + tds[10].innerHTML;
	
	var errors = false;
	
	if (obj) {
		if (addr == obj.name) {
			try {
				tds[7].innerHTML = accuracyArr[obj.Placemark[0].AddressDetails.Accuracy];
				tds[5].innerHTML = obj.Placemark[0].Point.coordinates[1];
				tds[6].innerHTML = obj.Placemark[0].Point.coordinates[0];
			} catch (ex) {
				alert("Geocode Error: " + ex.description +"\n\nObject name: " + obj.name);
			}
		} else {
			TrackEvent("Geocode Error - JSON Name != Address",addr + "|" + obj.name);
			errors = true;
		}
	} else if (!skip) { //Row not skipped (Lat & Long. are not already present)
		TrackEvent("Geocode Error - No JSON Returned",addr);
		alert("ERROR: No JSON object was returned!\nRow: " + cntrRow + "\nAddress: " + addr);
	}
	
	//Memory Control: Delete Script Element
	var oldScript = document.getElementById("geoScript" + (cntrRow));
	if (oldScript != null) {
		oldScript.parentNode.removeChild(oldScript);
		delete oldScript;
	}
	
	//Send next request
	if (errors) {
		//Try again
		if (tries < 10) {
			tries++;
			if (go) { window.setTimeout(sendRequest,1000); }
		} else {
			TrackEvent("Geocode Error - Unknown",addr);
			if (go) { alert("ERROR:\nAddress: " + addr); }
			tries = 0;
			cntrRow++;
			$("spnGeocodeCnt").innerHTML = cntrRow ;
			if (go) { window.setTimeout(sendRequest,150); }
		}
	} else {
		tries = 0;
		cntrRow++;
		$("spnGeocodeCnt").innerHTML = cntrRow;
		if (go) {
			if (skip) { window.setTimeout(sendRequest,10); } else { window.setTimeout(sendRequest,150); }
		}
	}
}

function StartParsing() {
	$("tdGeocodeLocations").innerHTML = "Done!";
	$("tdBuildStyles").innerHTML = "Processing...";
	
	var i;
	var j;
	var xml = "";
	var spans;
	
	//Build Styles
	TrackEvent("Build Styles","");
	var stylesDivs = $("divStyles").getElementsByTagName("DIV");
	//var trs = $("tblAddresses").getElementsByTagName("TBODY")[0].getElementsByTagName("TR");
	for (i = 0; i < stylesDivs.length && go; i++) {
		var styleData = stylesDivs[i].id.split("~");
		var iconURL = styleData[0]!=""?styleData[0]:"http://maps.google.com/mapfiles/kml/paddle/blu-blank.png";
		var iconSize = styleData[1]!=""?styleData[1]:"1.0";
		var showName = styleData[2].toUpperCase();
		
		//Build Style XML
		if (showName == "NEVER") {
			xml += "<Style id=\"" + i + "a\"><IconStyle><scale>"
				+ iconSize + "</scale><Icon>" + iconURL
				+ "</Icon></IconStyle><LabelStyle><scale>0</scale></LabelStyle></Style>"
				+ "<StyleMap id=\"" + i + "\"><Pair><key>normal</key><styleUrl>#" + i
				+ "a</styleUrl></Pair><Pair><key>highlight</key><styleUrl>#" + i + "a</styleUrl></Pair></StyleMap>";
		} else if (showName == "ALWAYS") {
			xml += "<Style id=\"" + i + "a\"><IconStyle><scale>"
				+ iconSize + "</scale><Icon>" + iconURL
				+ "</Icon></IconStyle><LabelStyle><scale>1</scale></LabelStyle></Style>"
				+ "<StyleMap id=\"" + i + "\"><Pair><key>normal</key><styleUrl>#" + i
				+ "a</styleUrl></Pair><Pair><key>highlight</key><styleUrl>#" + i + "a</styleUrl></Pair></StyleMap>";
		} else { //showName = "HOVER
			xml += "<Style id=\"" + i + "a\"><IconStyle><scale>"
				+ iconSize + "</scale><Icon>" + iconURL
				+ "</Icon></IconStyle><LabelStyle><scale>0</scale></LabelStyle></Style>"
				+ "<Style id=\"" + i + "b\"><IconStyle><scale>"
				+ iconSize + "</scale><Icon>" + iconURL
				+ "</Icon></IconStyle><LabelStyle><scale>1</scale></LabelStyle></Style>"
				+ "<StyleMap id=\"" + i + "\"><Pair><key>normal</key><styleUrl>#" + i
				+ "a</styleUrl></Pair><Pair><key>highlight</key><styleUrl>#" + i + "b</styleUrl></Pair></StyleMap>";
		}
		
		spans = stylesDivs[i].getElementsByTagName("i");
		
		//Set style for the locations
		for (j = 0; j < spans.length && go; j++) {
			GetChildrenByTagName(trs[spans[j].innerHTML], "TD")[9].innerHTML = i;
		}
	}
	
	
	$("tdBuildStyles").innerHTML = "Done!";
	$("tdBuildPlacemarks").innerHTML = "Processing...";
		
		
	//Get Placemark Info
	TrackEvent("Build Placemarks","");
	var folderDivs = $("divFolders").getElementsByTagName("DIV");
	var folders = new Hash();
	
	for (i = 0; i < folderDivs.length && go; i++) {
		spans = folderDivs[i].getElementsByTagName("i");
		var folderChildPlaces = "";
		
		for (j = 0; j < spans.length && go; j++) {
			var childRow = parseInt(spans[j].innerHTML);
			folderChildPlaces += GetPlacemarkXml(childRow);
		}
		folders.SetItem(folderDivs[i].id, folderChildPlaces);
	}

	while (folders.length > 1 && go) {
		var maxLevel = 0;
		var keysSorted = new Array();
		
		for (i = 0; i < folders.length && go; i++) {
			var levels = folders.GetKey(i).split("~").length;
			if (levels > maxLevel) maxLevel = levels;
			keysSorted[i] = folders.GetKey(i);
		}
		
		keysSorted.sort();
		
		for (i = keysSorted.length - 1; i >= 0 && go; i--) {
			var folder = keysSorted[i];
			
			if (folder.split("~").length == maxLevel) {
				var parentFolder = GetParentFolder(folder);
				var parentXml = folders.GetItem(parentFolder);
				folders.SetItem(parentFolder, "<Folder><name>" + folder.substr(folder.lastIndexOf("~") + 1) + "</name>" + folders.GetItem(folder) + "</Folder>" + parentXml);
				folders.RemoveItem(folder);
			}
		}
	}
	
	//Append folder XML
	for (i=0;i<folders.length && go; i++) {
		xml += folders.GetItem(folders.GetKey(i));
	}
	
	$("tdBuildPlacemarks").innerHTML = "Done!";
	$("tdDisplayMap").innerHTML = "Processing...";

	
	//Build Google Map For Display
	TrackEvent("Show Map","");
	if (GBrowserIsCompatible()) {
		
        var map = new GMap2(document.getElementById("divMap"));
		var tds = GetChildrenByTagName(trs[0], "TD");
        map.setCenter(new GLatLng(tds[5].innerHTML, tds[6].innerHTML), 13);

		//Add markers to map
        for (i=0;i<trs.length;i++) {
			tds = GetChildrenByTagName(trs[i], "TD");
			var point = new GLatLng(tds[5].innerHTML, tds[6].innerHTML);
			map.addOverlay(new GMarker(point));
        }
	}


	//GENERATE KML FILE FOR DOWNLOAD
	$("tdDisplayMap").innerHTML = "Done!";
	$("tdGenerateKml").innerHTML = "Processing...";
		

	if (go) {
		TrackEvent("Generate KML",cntrRow + " placemarks");
		var postData = "name=" + $("hdnFileName").value.replace(/&/gi, "%26")
			+ "&gizmoUseRow="+$("hdnGizmoUseId").value.replace(/&/gi, "%26")
			+ "&descr=" + $("hdnFileDescr").value.replace(/&/gi, "%26")
			+ "&xml=" + xml.replace(/&/gi, "%26")
			+ "&user=" + $("hdnUsername").value.replace(/&/gi, "%26")
			+ "&encrypt=" + $("hdnEncrypt").value.replace(/&/gi, "%26")
			+ "&locs="+cntrRow;
			//alert(postData);
		ajax.callPage("gizmo/get_kmz.php", function (response) {
			$("tdGenerateKml").innerHTML = "Done!";
			
			$("divLoading").innerHTML = "<button onclick=\"CancelProcessing(); return false;\" style=\"padding: 3px;\">Cancel</button> "
				+"<button onclick=\"DownloadFile('"+response+"'); return false;\" style=\"padding: 3px;\">Download My File!</button>";
		}, "POST", postData);
	}
}

function DownloadFile(url) {
	CancelProcessing();
	TrackEvent("Download KML",url);
	window.open(url);
}

function GetPlacemarkXml(rowId) {
	//var trs = $("tblAddresses").getElementsByTagName("TBODY")[0].getElementsByTagName("TR");
	var tds = GetChildrenByTagName(trs[rowId], "TD");
	var xml = "<Placemark>" +
			"<name><![CDATA[" + tds[0].innerHTML + "]]></name>" +
			"<description><![CDATA[" + tds[8].innerHTML + "]]></description>" +
			"<styleUrl>#" + tds[9].innerHTML + "</styleUrl>" +
			"<Point>" +
				"<coordinates>" + tds[6].innerHTML + "," + tds[5].innerHTML + ",0</coordinates>" +
			"</Point>" +
		"</Placemark>";
	return xml;
	}

function GetParentFolder(folder) {
	var parentFolder = "";
	var lastIndex = folder.lastIndexOf("~");
	if (lastIndex >= 0 ) {
		parentFolder = folder.substr(0, lastIndex);
	}
    
	return parentFolder;
}

function Hash() {
	this.keys = new Array();
	this.values = new Array();
	this.length = 0;
	
	this.SetItem = function (key, value) {
		var index = this.length;
		for (var i=0; i<this.keys.length; i++) {
			if (this.keys[i] == key) index = i;
		}
		
		this.keys[index] = key;
		this.values[index] = value;
		this.length = this.keys.length;
	}
	
	this.GetItem = function (key) {
		for (var i=0; i<this.keys.length; i++) {
			if (this.keys[i] == key) {
				return this.values[i];
			}
		}
		return "";
	}
	
	this.GetKey = function(index) {
		return this.keys[index];
	}
	
	this.RemoveItem = function (key) {
		var index = -1;
		for (var i=0; i<this.keys.length; i++) {
			if (this.keys[i] == key) index = i;
		}
		
		this.keys.splice(index,1);
		this.values.splice(index,1);
		this.length = this.keys.length;
	}
}
