var validateFormValue = true;
var defaultToggle = true;
function toggleProductMode()
{
	var toggleMode = document.getElementById("commercial_data").checked;
	if (toggleMode)
	{
		showCommercialProducts();
		map.removeOverlay(tile_overlay);
		clearMap();
		map.addOverlay(tile_overlay);
		if (defaultToggle == true)
		{
			$("#CommercialDataButton").addClass("tabButtonSelected");
			defaultToggle = false;
		}
	}
	else
	{
		showFreeData();
		map.removeOverlay(tile_overlay);
		clearMap();
		map.addOverlay(tile_overlay);
		if (defaultToggle == true)
		{
			$("#FreeDataButton").addClass("tabButtonSelected");
			defaultToggle = false;
		}
	}
}

function toggleCommercialMode()
{
	document.getElementById("commercial_data").checked = "checked";
	
	var imageSelected= icon_url + 'silvergradientselected.png';
	var imageNormal = icon_url + 'silvergradient.png';
	
	$("#CommercialDataButton").addClass("tabButtonSelected");	
	$("#FreeDataButton").removeClass("tabButtonSelected");
	$("#FreeDataButton").addClass("tabButton");
	document.getElementById("SubmitButton").value = "Submit Sales Query";

	toggleProductMode();
}

function toggleFreeMode()
{
	document.getElementById("free_data").checked = "checked";
	
	var imageSelected= icon_url + 'silvergradientselected.png';
	var imageNormal = icon_url + 'silvergradient.png';
	
	$("#FreeDataButton").addClass("tabButtonSelected");
	$("#CommercialDataButton").removeClass("tabButtonSelected");
	$("#CommercialDataButton").addClass("tabButton");
	document.getElementById("SubmitButton").value = "Download Free Data";
	
	toggleProductMode();
}

function hidePanels()
{
	$('#panels > div').hide();
}

function showCommercialProducts()
{
	hidePanels();
	$('#FreeDataContents').html('');
	$('#panels > div:eq(0)').show();
	$('.ProductResult').hide();
}

function showFreeData()
{
	hidePanels();
	$('#AvailableProducts').html('');
	$('#panels > div:eq(1)').show();
	$('.ProductResult').hide();
}

// Utilities to flip menu
function showHelp()
{
	ddaccordion.toggleone('silverheader', 0);
}

function showSearch()
{
	ddaccordion.toggleone('silverheader', 1);
}

function showAvailableProducts()
{
	ddaccordion.toggleone('silverheader', 2);
}

function showClientInfo()
{
	ddaccordion.toggleone('silverheader', 3);
}

// removes duplicate data in tables... currently not used
function remove_duplicate_tables() 
{
	var str = "";
	var i;
	
	var contents = new Array();
	var contentsClass = new Array();
	var inputID = new Array();
	var inputName = new Array();
	i = 0;

	//$('#AvailableProducts tbody tr').each(function()
	$('#datasetResultsTable tbody tr').each(function()
	{
		var currentCounter = 0;
		contentsClass[i] = $(this).attr('class');
		contents[i] = "";
		$("td", $(this)).each(function()
		{
			if (currentCounter != 0)
			{
				contents[i] = contents[i] + "<td>" + $(this).text() + "</td>";
			}
			currentCounter = currentCounter + 1;
		});
		i = i + 1;
	});

	i = 0;
	//$("#AvailableProducts input").each(function()
	$("#datasetResultsTable input").each(function()
	{
		inputID[i] = $(this).attr('id');
		inputName[i] = $(this).attr('name');
		i = i + 1;
	});
	
	var currentContent = "";
	if (contents.length > 0)
	{
		contents[0];
	}
	
	// TODO: Needs some optimising!
	for (i = 1; i < contents.length; i++)
	{
		if (currentContent == contents[i])
		{
			contents[i] = null;
		}
		else
		{
			currentContent = contents[i];
		}
	}
	if (contents.length >= 2)
	{
		if(contents[0] == contents[1])
		{
			contents[0] = null;
		}
	}
	
	str =	"<table id=\"datasetResultsTable\" class=\"datasetTable\">\n" +
		"<thead>\n" +
		"<th> </th>\n" +
		"<th>Name</th>\n" +
		"<th>Region</th>\n" +
		"<th>Date</th>\n" +
		"<th>Res</th>\n" +
		"<th>Size</th>\n" +
		"<th>CLT</th>\n" +
		"<th>VEC</th>\n" +
		"<th>DTM</th>\n" +
		"</thead>\n" +
		"<tbody>";
	
	for (i = 0; i < contents.length; i++)
	{
		if (contents[i] != null)
		{
			str = str + "<tr class=\"" + contentsClass[i] + "\">" + 
				"<td><input type=\"checkbox\" name=\"" + inputName[i] + "\"></input></td>" +
				contents[i] + "</tr>";
		}
	}
	str = str + "</tbody></table>";
	$("#AvailableProducts").html(str);
}

function processFreedata(freeDataTile)
{
	document.getElementById("databaseID").value = freeDataTile;
	$("#SubmitRequestHeading").html("<span class=\"strong\">Please fill in this form to download tile " + freeDataTile + ".</span>");
	showClientInfo();
}

function setDialog(dialogHeight)
{
	if (dialogHeight < 50)
	{
		dialogHeight = 50;
	}
	$("#dialog").dialog(
	{
		autoOpen: false,
		buttons: {"Ok": function(){ $(this).dialog("close");}},
		draggable: true,
		modal: true,
		resizable: false,
		height: dialogHeight  + 100,
		width: 410,
		overlay: {opacity: 0.5, background: "black"}
	});
}

function handleDialogButtonClick_dragSelect()
{
	$("#dialog").dialog("close");
	dragSelectPolygon();
}

function handleDialogButtonClick_customPolygon()
{
	$("#dialog").dialog("close");
	handleCustomPolyonClick();
}

// Custom validation of our form
function CustomValidation()
{
	var commercial_mode = document.getElementById("commercial_data").checked;
	if (commercial_mode)
	{
		getCheckedItem();
		document.getElementById("datatype").value = "commercial";
	}
	else
	{
		document.getElementById("datatype").value = "free";
	}
	
	var errors = "", str, selectOptions;
	var dialogHeight = 0;
	var numErrors = 1;
	var dialogLineHeight = 18;
	str = document.getElementById("KmlRegionBounds").value;
	if (str == "&lt;-- Click on the map to create Kml")
	{
		errors += "<li>No area of interests selected.</li>";
		numErrors += 1;
		document.MM_returnValue = (errors == '');
		validateFormValue = false;
		document.getElementById("dialog").innerHTML = "" + 
			"<p id=\"dialogPrompt\"><span class=\"strong\">First select a geographical area of interest.</span></p>" +
			"<p id=\"dialogPrompt\">You can do this by clicking on one of the &nbsp;<img id=\"helpIcon\" src=\"GMaps_files/boxSelectHover.png\" onclick=\"handleDialogButtonClick_dragSelect();\" width=\"22\" height=\"22\"></img>&nbsp;<img id=\"helpIcon\" src=\"GMaps_files/customPolygonHover.png\" onclick=\"handleDialogButtonClick_customPolygon();\" width=\"22\" height=\"22\"></img> icons.</p>";
		dialogHeight = dialogLineHeight * (numErrors + 1);
		setDialog(dialogHeight);
		$("#dialog").dialog("open");
		return;
	}
	
	selectOptions = document.getElementById("title").options;
	/*for (var i = 0; i < selectOptions.length; i++)
	{
		if (selectOptions[i].selected)
		{
			str = selectOptions[i].value;
		}
	}
	if (str == 'None')
	{
		errors += "<li>Title is required.</li>";
		numErrors += 1;
	}*/
	str = document.getElementById("first_name").value;
	if (str == '')
	{
		errors += "<li>First Name is required.</li>";
		numErrors += 1;
	}
	str = document.getElementById("last_name").value;
	if (str == '')
	{
		errors += "<li>Last Name is required.</li>";
		numErrors += 1;
	}
	str = document.getElementById("company").value;
	if (str == '')
	{
		errors += "<li>Company is required.</li>";
		numErrors += 1;
	}
	str = document.getElementById("email").value;
	var re = /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/; // Some regular expression checking for valid email
	if (re.test(str) != true)
	{
		errors += "<li>Please enter a valid e-mail address.</li>";
		numErrors += 1;
	}
	str = document.getElementById("phone").value;
	if (str == '')
	{
		errors += "<li>Phone number is required.</li>";
		numErrors += 1;
	}
	str = document.getElementById("city").value;
	if (str == '')
	{
		errors += "<li>City is required.</li>";
		numErrors += 1;
	}
	str = document.getElementById("state").value;
	if (str == '')
	{
		errors += "<li>State/Province is required.</li>";
		numErrors += 1;
	}
	str = '';
	selectOptions = document.getElementById("country").options;
	for (var i = 0; i < selectOptions.length; i++)
	{
		if (selectOptions[i].selected)
		{
			str = selectOptions[i].value;
		}
	}
	if (str == 'SELECT')
	{
		errors += "<li>Country is required.</li>";
		numErrors += 1;
	}
	str = document.getElementById("customer_comments").value;
	if (str.length > 2048)
	{
		errors += "<li>Please limit the comments to fewer characters.</li>";
		numErrors += 1;
	}
	/*if (str.indexOf("Commercial Query - ") == 0)
	{
		str = str.substr(20, str.length);
	}
	else if (str.indexOf("WorldBase 250 Data - ") == 0)
	{
		str = str.substr(21, str.length);
	}*/
	document.getElementById("customer_comments").value = str;
	/*if (commercial_mode)
	{
		if (	(str == "Enter your comment here..." || str == "") &&
			(document.getElementById("databaseID").value == ""))
		{
			errors += "<li>Please enter a description of the enquiry in the comments area.</li>";
			numErrors += 1;
		}
	}*/
	
	str = document.getElementById("databaseID").value;
	if (!commercial_mode && str == "")
	{
		errors += "<li>You did specify an UTM tile for your free data query.</li>";
		numErrors = 1;
		$("#dialog").html('Please specify an UTM tile for your free data query.');
		dialogHeight = dialogLineHeight * numErrors;
		setDialog(dialogHeight);
		$("#dialog").dialog("open");
		showAvailableProducts();
		return false;
	}
	
	if (errors != "")
	{
		$("#dialog").html("<p id=\"dialogPrompt\"><span class=\"strong\"><font color=\"white\">The following fields have not been filled in:</font></span><ul class=\"errorlist\">" + errors + "</ul></p>");
		dialogHeight = dialogLineHeight * numErrors;
		setDialog(dialogHeight);
		$("#dialog").dialog("open");
		return false;
	}
	else
	{
		var centroid = "" + border.getBounds().getCenter().lng().toFixed(6) + "," + border.getBounds().getCenter().lat().toFixed(6) + ",0";
		document.getElementById("centroid").value = centroid;
		var areavalue = (border.getArea() / (1000 * 1000)).toFixed(3);
		document.getElementById("areakm2").value = areavalue;
		//var customerComments = document.getElementById("customer_comments").value;
		if (!commercial_mode)
		{
			showAvailableProducts();
			$("#dialog").html("<span class=\"strong\">The download has started...</span>");
			dialogHeight = dialogLineHeight;
			setDialog(dialogHeight);
			$("#dialog").dialog("open");
		}
		/*if (commercial_mode)
		{
			document.getElementById("customer_comments").value = "Commercial Query - " + customerComments;
		}
		else
		{
			document.getElementById("customer_comments").value = "WorldBase 250 Data - " + customerComments;
		}*/
		
		return true;
	}
}

// Used for Selecting all checkboxes in the commercial data table
function selectAllDatasets()
{
	$("#AvailableProducts input").each(function()
	{
		this.checked = true;
	});
}

// Used for Selecting no checkboxes in the commercial data table
function selectNoDatasets()
{
	$("#AvailableProducts input").each(function()
	{
		this.checked = false;
	});
}

//======================================================================================================

//===================================================
// class: Utils
//===================================================
// This module provides a set of utility functions
// that enable map clicking, dragging and screen position 
// queries.
//Thanks to Peter-Paul Koch at http://www.quirksmode.org
// for the basis of this code and his great tutorial site.
//===================================================
function Utils()
{
	//Properties
	this.credits = "Peter-Paul Koch at http://www.quirksmode.org"
	this.curleft = 0
	this.curtop = 0
	this.docPosX = 0
	this.docPosY = 0
	
	//Methods
	this.getElementPositionX = getElementPositionX
	this.getElementPositionY = getElementPositionY
	this.getDocumentClickX = getDocumentClickX
	this.getDocumentClickY = getDocumentClickY
	
	//=================================================
	//find the X position of an element relative to the
	//entire document.
	//Thanks to Peter-Paul Koch at http://www.quirksmode.org
	//for this code.
	//=================================================
	function getElementPositionX(obj)
	{

		this.curleft = 0
		if (obj.offsetParent)
		{
			while (obj.offsetParent)
			{
				this.curleft += obj.offsetLeft
				obj = obj.offsetParent
			}
		}
		else if (obj.x)
			this.curleft += obj.x
		return this.curleft
	}

	//=================================================
	//find the Y position of an element relative to the
	//entire document.
	//Thanks to Peter-Paul Koch at http://www.quirksmode.org
	//for this code.
	//=================================================
	function getElementPositionY(obj)
	{
		
		this.curtop = 0
		if (obj.offsetParent)
		{
			while (obj.offsetParent)
			{
				this.curtop += obj.offsetTop
				obj = obj.offsetParent
			}
		}
		else if (obj.y)
			this.curtop += obj.y
		return this.curtop
	}

	//=================================================
	//find document click position.
	//Thanks to Peter-Paul Koch at http://www.quirksmode.org
	//for the basis of this code.
	//=================================================
	function getDocumentClickX(e)
	{

		this.docPosX = 0
		if (!e)
		{
			var e = window.event
		}
		if (e.pageX)
		{
			this.docPosX = e.pageX
		}
		else if (e.clientX)
		{
			this.docPosX = e.clientX + document.body.scrollLeft
		}
		return this.docPosX
	}

	//=================================================
	//find document click position.
	//Thanks to Peter-Paul Koch at http://www.quirksmode.org
	//for the basis of this code.
	//=================================================
	function getDocumentClickY(e)
	{

		this.docPosY = 0
		if (!e)
		{
			var e = window.event
		}
		if (e.pageY)
		{
			this.docPosY = e.pageY
		}
		else if (e.clientY)
		{
			this.docPosY = e.clientY + document.body.scrollLeft
		}
		return this.docPosY;
	}

}


//** Accordion Content script: By Dynamic Drive, at http://www.dynamicdrive.com
//** Created: Jan 7th, 08'

//Version 1.3: April 3rd, 08':
//**1) Script now no longer conflicts with other JS frameworks
//**2) Adds custom oninit() and onopenclose() event handlers that fire when Accordion Content instance has initialized, plus whenever a header is opened/closed
//**3) Adds support for expanding header(s) using the URL parameter (ie: http://mysite.com/accordion.htm?headerclass=0,1)

//April 9th, 08': Fixed "defaultexpanded" setting not working when page first loads

//Version 1.4: June 4th, 08':
//**1) Added option to activate a header "mouseover" instead of the default "click"
//**2) Bug persistence not working when used with jquery 1.2.6

//Version 1.5: June 20th, 08':
//**1) Adds new "onemustopen:true/false" parameter, which lets you set whether at least one header should be open at all times (so never all closed).
//**2) Changed cookie path to site wide for persistence feature
//**3) Fixed bug so "expandedindices" parameter in oninit(headers, expandedindices) returns empty array [] instead of [-1] when no expanded headers found

//**1) Version 1.5.1: June 27th, 08': Fixed "defaultexpanded" setting not working properly when used with jquery 1.2.6

//Version 1.6: Oct 3rd, 08':
//**1) Adds new "mouseoverdelay" param that sets delay before headers are activated when "revealtype" param is set to "mouseover"
//**2) Fixed bug with "onemustopen" param not working properly when "revealtype" is set to "click"


var ddaccordion={
	
	contentclassname:{}, //object to store corresponding contentclass name based on headerclass

	expandone:function(headerclass, selected){ //PUBLIC function to expand a particular header
		this.toggleone(headerclass, selected, "expand")
	},

	collapseone:function(headerclass, selected){ //PUBLIC function to collapse a particular header
		this.toggleone(headerclass, selected, "collapse")
	},

	expandall:function(headerclass){ //PUBLIC function to expand all headers based on their shared CSS classname
		var $=jQuery
		var $headers=$('.'+headerclass)
		$('.'+this.contentclassname[headerclass]+':hidden').each(function(){
			$headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
		})
	},

	collapseall:function(headerclass){ //PUBLIC function to collapse all headers based on their shared CSS classname
		var $=jQuery
		var $headers=$('.'+headerclass)
		$('.'+this.contentclassname[headerclass]+':visible').each(function(){
			$headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
		})
	},

	toggleone:function(headerclass, selected, optstate){ //PUBLIC function to expand/ collapse a particular header
		var $=jQuery
		var $targetHeader=$('.'+headerclass).eq(selected)
		var $subcontent=$('.'+this.contentclassname[headerclass]).eq(selected)
		if (typeof optstate=="undefined" || optstate=="expand" && $subcontent.is(":hidden") || optstate=="collapse" && $subcontent.is(":visible"))
			$targetHeader.trigger("evt_accordion")
	},

	expandit:function($targetHeader, $targetContent, config, useractivated){
		$targetContent.slideDown(config.animatespeed, function(){config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), useractivated)})
		this.transformHeader($targetHeader, config, "expand")
	},

	collapseit:function($targetHeader, $targetContent, config, isuseractivated){
		$targetContent.slideUp(config.animatespeed, function(){config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), isuseractivated)})
		this.transformHeader($targetHeader, config, "collapse")
	},

	transformHeader:function($targetHeader, config, state){
		$targetHeader.addClass((state=="expand")? config.cssclass.expand : config.cssclass.collapse) //alternate btw "expand" and "collapse" CSS classes
		.removeClass((state=="expand")? config.cssclass.collapse : config.cssclass.expand)
		if (config.htmlsetting.location=='src'){ //Change header image (assuming header is an image)?
			$targetHeader=($targetHeader.is("img"))? $targetHeader : $targetHeader.find('img').eq(0) //Set target to either header itself, or first image within header
			$targetHeader.attr('src', (state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse) //change header image
		}
		else if (config.htmlsetting.location=="prefix") //if change "prefix" HTML, locate dynamically added ".accordprefix" span tag and change it
			$targetHeader.find('.accordprefix').html((state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse)
		else if (config.htmlsetting.location=="suffix")
			$targetHeader.find('.accordsuffix').html((state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse)
	},

	urlparamselect:function(headerclass){
		var result=window.location.search.match(new RegExp(headerclass+"=((\\d+)(,(\\d+))*)", "i")) //check for "?headerclass=2,3,4" in URL
		if (result!=null)
			result=RegExp.$1.split(',')
		return result //returns null, [index], or [index1,index2,etc], where index are the desired selected header indices
	},

	getCookie:function(Name){ 
		var re=new RegExp(Name+"=[^;]+", "i") //construct RE to search for target name/value pair
		if (document.cookie.match(re)) //if cookie found
			return document.cookie.match(re)[0].split("=")[1] //return its value
		return null
	},

	setCookie:function(name, value){
		document.cookie = name + "=" + value + "; path=/"
	},

	init:function(config){
	document.write('<style type="text/css">\n')
	document.write('.'+config.contentclass+'{display: none}\n') //generate CSS to hide contents
	document.write('<\/style>')
	jQuery(document).ready(function($){
		ddaccordion.urlparamselect(config.headerclass)
		var persistedheaders=ddaccordion.getCookie(config.headerclass)
		ddaccordion.contentclassname[config.headerclass]=config.contentclass //remember contentclass name based on headerclass
		config.cssclass={collapse: config.toggleclass[0], expand: config.toggleclass[1]} //store expand and contract CSS classes as object properties
		config.revealtype=/^(click)|(mouseover)$/i.test(config.revealtype)? config.revealtype.replace(/mouseover/i, "mouseenter") : "click"
		config.htmlsetting={location: config.togglehtml[0], collapse: config.togglehtml[1], expand: config.togglehtml[2]} //store HTML settings as object properties
		config.oninit=(typeof config.oninit=="undefined")? function(){} : config.oninit //attach custom "oninit" event handler
		config.onopenclose=(typeof config.onopenclose=="undefined")? function(){} : config.onopenclose //attach custom "onopenclose" event handler
		var lastexpanded={} //object to hold reference to last expanded header and content (jquery objects)
		var expandedindices=ddaccordion.urlparamselect(config.headerclass) || ((config.persiststate && persistedheaders!=null)? persistedheaders : config.defaultexpanded)
		if (typeof expandedindices=='string') //test for string value (exception is config.defaultexpanded, which is an array)
			expandedindices=expandedindices.replace(/c/ig, '').split(',') //transform string value to an array (ie: "c1,c2,c3" becomes [1,2,3]
		var $subcontents=$('.'+config["contentclass"])
		if (expandedindices.length==1 && expandedindices[0]=="-1") //check for expandedindices value of [-1], indicating persistence is on and no content expanded
			expandedindices=[]
		if (config["collapseprev"] && expandedindices.length>1) //only allow one content open?
			expandedindices=[expandedindices.pop()] //return last array element as an array (for sake of jQuery.inArray())
		if (config["onemustopen"] && expandedindices.length==0) //if at least one content should be open at all times and none are, open 1st header
			expandedindices=[0]
		$('.'+config["headerclass"]).each(function(index){ //loop through all headers
			if (/(prefix)|(suffix)/i.test(config.htmlsetting.location) && $(this).html()!=""){ //add a SPAN element to header depending on user setting and if header is a container tag
				$('<span class="accordprefix"></span>').prependTo(this)
				$('<span class="accordsuffix"></span>').appendTo(this)
			}
			$(this).attr('headerindex', index+'h') //store position of this header relative to its peers
			$subcontents.eq(index).attr('contentindex', index+'c') //store position of this content relative to its peers
			var $subcontent=$subcontents.eq(index)
			var needle=(typeof expandedindices[0]=="number")? index : index+'' //check for data type within expandedindices array- index should match that type
			if (jQuery.inArray(needle, expandedindices)!=-1){ //check for headers that should be expanded automatically (convert index to string first)
				if (config.animatedefault==false)
					$subcontent.show()
				ddaccordion.expandit($(this), $subcontent, config, false) //Last Boolean value sets 'isuseractivated' parameter
				lastexpanded={$header:$(this), $content:$subcontent}
			}  //end check
			else{
				$subcontent.hide()
				config.onopenclose($(this).get(0), parseInt($(this).attr('headerindex')), $subcontent.css('display'), false) //Last Boolean value sets 'isuseractivated' parameter
				ddaccordion.transformHeader($(this), config, "collapse")
			}
		})
		$('.'+config["headerclass"]).bind("evt_accordion", function(){ //assign custom event handler that expands/ contacts a header
				var $subcontent=$subcontents.eq(parseInt($(this).attr('headerindex'))) //get subcontent that should be expanded/collapsed
				if ($subcontent.css('display')=="none"){
					ddaccordion.expandit($(this), $subcontent, config, true) //Last Boolean value sets 'isuseractivated' parameter
					if (config["collapseprev"] && lastexpanded.$header && $(this).get(0)!=lastexpanded.$header.get(0)){ //collapse previous content?
						ddaccordion.collapseit(lastexpanded.$header, lastexpanded.$content, config, true) //Last Boolean value sets 'isuseractivated' parameter
					}
					lastexpanded={$header:$(this), $content:$subcontent}
				}
				else if (!config["onemustopen"] || config["onemustopen"] && lastexpanded.$header && $(this).get(0)!=lastexpanded.$header.get(0)){
					ddaccordion.collapseit($(this), $subcontent, config, true) //Last Boolean value sets 'isuseractivated' parameter
				}
 		})
		$('.'+config["headerclass"]).bind(config.revealtype, function(){
			if (config.revealtype=="mouseenter"){
				clearTimeout(config.revealdelay)
				var headerindex=parseInt($(this).attr("headerindex"))
				config.revealdelay=setTimeout(function(){ddaccordion.expandone(config["headerclass"], headerindex)}, config.mouseoverdelay || 0)
			}
			else{
				$(this).trigger("evt_accordion")
				return false //cancel default click behavior
			}
		})
		$('.'+config["headerclass"]).bind("mouseleave", function(){
			clearTimeout(config.revealdelay)
		})
		config.oninit($('.'+config["headerclass"]).get(), expandedindices)
		$(window).bind('unload', function(){ //clean up and persist on page unload
			$('.'+config["headerclass"]).unbind()
			var expandedindices=[]
			$('.'+config["contentclass"]+":visible").each(function(index){ //get indices of expanded headers
				expandedindices.push($(this).attr('contentindex'))
			})
			if (config.persiststate==true){ //persist state?
				expandedindices=(expandedindices.length==0)? '-1c' : expandedindices //No contents expanded, indicate that with dummy '-1c' value?
				ddaccordion.setCookie(config.headerclass, expandedindices)
			}
		})
	})
	}
}

ddaccordion.init({
	headerclass: "silverheader", //Shared CSS class name of headers group
	contentclass: "submenu", //Shared CSS class name of contents group
	revealtype: "click", //Reveal content when user clicks or onmouseover the header? Valid value: "click" or "mouseover"
	mouseoverdelay: 200, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
	collapseprev: true, //Collapse previous content (so only one open at any time)? true/false
	defaultexpanded: [0], //index of content(s) open by default [index1, index2, etc] [] denotes no content
	onemustopen: true, //Specify whether at least one header should be open always (so never all headers closed)
	animatedefault: false, //Should contents open by default be animated into view?
	persiststate: true, //persist state of opened contents within browser session?
	toggleclass: ["", "selected"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
	togglehtml: ["", "", ""], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
	animatespeed: "fast", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
	oninit:function(headers, expandedindices){ //custom code to run when headers have initalized
		//do nothing
	},
	onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
		//do nothing
	}
})
var full_url = parent.document.URL;

var map;
var poly;
var points = new Array();	// not used anymore?
var markers = new Array();	// not used anymore?
var polygonMode;
var polygonDepth = "20";
var marker;

var firstPoint = null;	// used for new box select
var tempPolygonArray = new Array();
var tempPolygon;

var geocoder = null;

var fillColor = "#3355ff";
var lineColor = "#8aa700";
var kmlLineColor = "ff00a78a";
var opacity = 0.3;
var lineWeight = 3;
var kmlFillColor = "#7fff5533";
var geoXml;
var queryStr = null;

//Custom maps
var mapBounds = new GLatLngBounds(new GLatLng(-90.0, -180.0), new GLatLng(90.0, 180.0));
var mapMinZoom = 0;
var mapMaxZoom = 9;
var tile_overlay;
var polygon_overlay;
var tilelayer;
var tileOpacity = 0.3;

var toggleDisplayFlag = true;
var clickedOnToggleDisplay = true;

// box selection variables
var marker_NE;
var marker_SW;
var marker_move;

var border;
var groundOverlay; // not used anymore?

var icon_NE;
var icon_SW;
var icon_move;
var transmitterIcon;

var mapArea;
var mouseCoord;
var mouseStatus;

var tooltip;

var mapdataOpacity = 0.75;

//======================================================================================================
// Starting point of program
//======================================================================================================
function load()
{
	resize();

	// Checking if we came from ComputaMaps website
	if (full_url.indexOf('?') > -1)
	{
		// if url is: http://brightearth.computamaps.com/Catalog?freedata
		var options = full_url.substring(full_url.indexOf('?') + 1, full_url.length);
		if (options == "freedata")
		{
			ddaccordion.toggleone('silverheader', 2);
			document.getElementById("free_data").checked = "checked";
		}
		else
		{
			ddaccordion.toggleone('silverheader', 0);
			document.getElementById("commercial_data").checked = "checked";
		}
	}
	else
	{
		ddaccordion.toggleone('silverheader', 0);
		document.getElementById("commercial_data").checked = "checked";
	}
	
	center = new GLatLng(0, 0);
	latitude = center.lat().toFixed(6);
	longitude = center.lng().toFixed(6);
	zoom = 2;

	if (GBrowserIsCompatible())
	{
		tooltip = document.createElement("div");
		tooltip.className = "tooltip";

		map = new GMap2(document.getElementById("map_canvas"));
		map.getPane(G_MAP_MARKER_PANE).appendChild(tooltip);
		map.setCenter(center, zoom);
		
		map.enableScrollWheelZoom();
		map.disableDoubleClickZoom();
		//map.getEarthInstance(getEarthInstanceCB); // Google Earth Instance
		
		//map.addMapType(G_SATELLITE_3D_MAP); // Google Earth map type
		map.addMapType(G_PHYSICAL_MAP); // Terrain map
		
		//map.addControl(new CustomButton(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(90, 10)));
		map.addControl(new DrawDragPolygon(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(80, 10)));
		map.addControl(new DrawCustomPolygon(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(120, 10)));
		map.addControl(new ClearSelectionButton(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(160, 10)));
		map.addControl(new ResetButton(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(200, 10)));
		map.addControl(new ToggleDisplay(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(240, 10)));
		map.addControl(new SaveKML(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(280, 10)));
		map.addControl(new MapDataButton(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(80, 50)));
		map.addControl(new ShowHideMenu(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 10)));
		map.addControl(new GMapTypeControl());
		map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 50)));
		//map.addControl(new GLargeMapControl());
		map.addControl(new GScaleControl());
		
		geocoder = new GClientGeocoder();
		
		// Custom Maps
		var copyCollection = new GCopyrightCollection('ComputaMaps');
		var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90.0, -180.0000000), new GLatLng(90.0, 180.0000000)), 0, "Created by ComputaMaps");
		copyCollection.addCopyright(copyright);
		
		// Setup the tile layers
		var tilelayers = new Array();
		tilelayers[0] = G_NORMAL_MAP.getTileLayers()[0];
		tilelayers[1] = new GTileLayer(copyCollection, mapMinZoom, mapMaxZoom);
		tilelayers[1].getTileUrl = CustomGetTileUrl;
		tilelayers[1].getOpacity = function() { return tileOpacity; };
		tilelayers[1].isPng = function() { return true; };
		tilelayer = tilelayers[1];
		
		tile_overlay = new GTileLayerOverlay( tilelayer );
		map.addOverlay(tile_overlay);
		
		// Event Listeners
		GEvent.addListener(map, "mousemove", function(point)
		{
			if (zoom > mapMaxZoom)
			{
				if (tilelayers)
				{
					tilelayers[1].getOpacity = function() { return tileOpacity; };
					tilelayer = tilelayers[1];
					try
					{
						if (!tile_overlay.isHidden())
						{
							tile_overlay.hide();
						}
					}
					catch (ex) {}
				}
				else
				{
					alert ("Error - no tilelayers found with zoom greater than maxZoom");
				}
			}
			else
			{
				if (tilelayers)
				{
					tilelayers[1].getOpacity = function() { return tileOpacity; };
					tilelayer = tilelayers[1];
					/*if (clickedOnToggleDisplay == true)
					{
						clickedOnToggleDisplay = false;
						if (toggleDisplayFlag == true)
						{
							tile_overlay.hide();
						}
						else
						{
							tile_overlay.show();
						}
					}*/
					/*try
					{
						if (tile_overlay.isHidden())
						{
							tile_overlay.show();
						}
					}
					catch (ex) {}*/
				}
				else
				{
					alert ("Error - no tilelayers found with zoom less than maxZoom");
				}
			}
			update_mouseposition(point);
			update_mapStatus();
			
			if ((firstPoint != null))
			{
				tempPolygonArray[0] = new GLatLng(firstPoint.lat(), firstPoint.lng());
				tempPolygonArray[1] = new GLatLng(point.lat(), firstPoint.lng());
				tempPolygonArray[2] = new GLatLng(point.lat(), point.lng());
				tempPolygonArray[3] = new GLatLng(firstPoint.lat(), point.lng());
				tempPolygonArray[4] = new GLatLng(firstPoint.lat(), firstPoint.lng());
				
				if (tempPolygon)
				{
					map.removeOverlay(tempPolygon);
				}
				tempPolygon = new GPolygon(tempPolygonArray, lineColor, lineWeight, 1, fillColor, opacity);
				map.addOverlay(tempPolygon);
			}
		});
		GEvent.addListener(map, "maptypechanged", update_mapType);
		/* Used for kml placemark infowindows
		GEvent.addListener(map,"infowindowprepareopen", function(iwtabs)
		{
			iwtabs[0].contentElem.innerHTML = '' +
				'<p>Click on the next button to fill in your details in order to download your free data.</p> <br/>' +
				'<input type="button" onclick="showClientInfo();" value="Next"></input>';
			
			//alert(iwtabs[0].contentElem.innerHTML);
		});*/
		
		// Icons used for box selection
		icon_NE = new GIcon(); 
		icon_NE.image = icon_url + 'markers_NE.png';
		icon_NE.shadow = '';
		icon_NE.iconSize = new GSize(32, 32);
		icon_NE.shadowSize = new GSize(22, 20);
		icon_NE.iconAnchor = new GPoint(22, 10);
		icon_NE.dragCrossImage = '';

		icon_SW = new GIcon(); 
		icon_SW.image = icon_url + 'markers_SW.png';
		icon_SW.shadow = '';
		icon_SW.iconSize = new GSize(32, 32);
		icon_SW.shadowSize = new GSize(22, 20);
		icon_SW.iconAnchor = new GPoint(6, 20);
		icon_SW.dragCrossImage = '';

		icon_move = new GIcon();
		icon_move.image = icon_url + 'markers_move.png';
		icon_move.shadow = '';
		icon_move.iconSize = new GSize(32, 32);
		icon_move.shadowSize = new GSize(6, 20);
		icon_move.iconAnchor = new GPoint(10, 10);
		icon_move.dragCrossImage = '';
		
		if (window.processPlanning)
		{
			processPlanning();
		}
	}
	else
	{
		try
		{
			$("#dialog").html("<p id=\"dialogPrompt\">Your browser is not compatible to use Google Maps.</p>");
			setDialog(50);
			$("#dialog").dialog("open");
		}
		catch (ex)
		{
			alert("Your browser is not compatible to use Google Maps.");
		}
	}
	resetMap();
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// windows resize
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var viewportWidth = 0;
var viewportHeight = 0;
var mapdiv;
var productResultsHeight = "0px";

function resize()
{
	if (self.innerHeight) // all except Explorer
	{
		viewportWidth = self.innerWidth;
		viewportHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
	{
		// Explorer 6 Strict Mode
		viewportWidth = document.documentElement.clientWidth;
		viewportHeight = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		viewportWidth = document.body.clientWidth;
		viewportHeight = document.body.clientHeight;
	}		
	//-----------------------------------------------------
	mapdiv = document.getElementById("map_canvas");
	if ((viewportHeight - 325 > 30))
	{
		if(viewportHeight > 545)
		{
			mapdiv.style.height = (viewportHeight - 265) + "px"; //210    //163
		}
	}
	
	if ((viewportHeight - 325 > 30))
	{
		if(viewportHeight > 545)
		{
			var viewporttext = viewportHeight - 265 + "px";
			$("#theapplemenu").css("height", viewporttext);
			viewporttext = viewportHeight - 371+ "px"; 
			$(".submenu").css("height",  viewporttext);
			
			$("#theapplemenu").resizable('destroy');
			$("#theapplemenu").resizable({
				maxHeight: viewportHeight - 267,
				minHeight: viewportHeight - 267,
				minWidth: 433,
				/*resize: function()
				{
					var theapplemenuResizedWidth = parseInt(document.getElementById("theapplemenu").style.width);
					if (theapplemenuResizedWidth < 433)
					{
						if (theapplemenuResizedWidth < 433/2)
						{
							document.getElementById("applemenuTable").style.width = "10px";
							document.getElementById("theapplemenu").style.width = "10px";
							document.getElementById("mapTable").style.width = viewportWidth - 30 + "px";
						}
						else
						{
							document.getElementById("applemenuTable").style.width = "100%";
							document.getElementById("theapplemenu").style.width = "433px";
							document.getElementById("mapTable").style.width = "100%";
						}
					}
					else
					{
						document.getElementById("applemenuTable").style.width = "100%";
					}
				},*/
				handles: 'e' 
			});
			
			var toggleMode = document.getElementById("commercial_data").checked;
			var currentHeight = viewportHeight;
			if (toggleMode)
			{
				currentHeight = currentHeight - 525;
				productResultsHeight = currentHeight + "px"; 
				if ($("#CommercialProductsHeading").is(":hidden"))
				{
					$(".ProductResult").css("height", productResultsHeight);
					$(".ProductResult").show();
				}
				else
				{
					$(".ProductResult").css("height", "0px");
					$(".ProductResult").hide();
				}
			}
			else
			{
				currentHeight = currentHeight - 490;
				productResultsHeight = currentHeight + "px"; 
				if ($("#FreeDataHeading").is(":hidden"))
				{
					$(".ProductResult").css("height", productResultsHeight);
					$(".ProductResult").show();
				}
				else
				{
					$(".ProductResult").css("height", "0px");
					$(".ProductResult").hide();
				}
			}
		}
	}
}
window.onresize = resize;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Get tile url
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function CustomGetTileUrl(a, b)
{
	var togglemode = document.getElementById("commercial_data").checked;
	var current_tile_url = "";
	if (togglemode)
	{
		current_tile_url = commercial_tile_url;
	}
	else
	{
		current_tile_url = free_tile_url;
	}
	
	if ( b == 0 && a.x >= 0 && a.x <= 0 && a.y >= 0 && a.y <= 0 )
	{
		return current_tile_url + b + "/" + a.y + "_" + a.x + ".png"; 
	}
	else if ( b == 1 && a.x >= 0 && a.x <= 1 && a.y >= 0 && a.y <= 1)
	{
		return current_tile_url + b + "/" + a.y + "_" + a.x + ".png"; 
	}
	else if ( b == 2 && a.x >= 0 && a.x <= 3 && a.y >= 0 && a.y <= 3 )
	{
		return current_tile_url + b + "/" + a.y + "_" + a.x + ".png"; 
	}
	else if ( b == 3 && a.x >= 0 && a.x <= 7 && a.y >= 0 && a.y <= 7 )
	{
		return current_tile_url + b + "/" + a.y + "_" + a.x + ".png"; 
	}
	else if ( b == 4 && a.x >= 0 && a.x <= 15 && a.y >= 0 && a.y <= 15 )
	{
		return current_tile_url + b + "/" + a.y + "_" + a.x + ".png"; 
	}
	else if ( b == 5 && a.x >= 0 && a.x <= 31 && a.y >= 0 && a.y <= 31 )
	{
		return current_tile_url + b + "/" + a.y + "_" + a.x + ".png"; 
	}
	else if ( b == 6 && a.x >= 0 && a.x <= 63 && a.y >= 0 && a.y <= 63 )
	{
		return current_tile_url + b + "/" + a.y + "_" + a.x + ".png"; 
	}
	else if ( b == 7 && a.x >= 0 && a.x <= 127 && a.y >= 0 && a.y <= 127 )
	{
		return current_tile_url + b + "/" + a.y + "_" + a.x + ".png"; 
	}
	else if ( b == 8 && a.x >= 0 && a.x <= 255 && a.y >= 0 && a.y <= 255 )
	{
		return current_tile_url + b + "/" + a.y + "_" + a.x + ".png"; 
	}
	else if ( b == 9 && a.x >= 0 && a.x <= 511 && a.y >= 0 && a.y <= 511 )
	{
		return current_tile_url + b + "/" + a.y + "_" + a.x + ".png"; 
	}
	
	return G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Search Locations using Google Map's GClientGeocoder
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function search()
{
	var geocodeLocation = document.getElementById("geoLocation").value;
	geocoder = new GClientGeocoder();
	geocoder.getLatLng(geocodeLocation, function(point)
	{
		if (point)
		{
			zoom = 5;
			map.setCenter(point, zoom);
			showAvailableProducts();
		}
		else
		{
			$("#dialog").html("<p id=\"dialogPrompt\">Sorry, but <font color=\"#8AA700\">\"" + 
						geocodeLocation + 
						"\"</font> could not be found.<br/> Please try again.</p>");
			setDialog(50);
			$("#dialog").dialog("open");
		}
	});
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Map clearing functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function clear()
{
	if (geoXml != null)
	{
		map.removeOverlay(geoXml);
	}
	if (polygon_overlay != null)
	{
		map.removeOverlay(polygon_overlay);
	}
	if (window.processPlanning)
	{
		clearProcessPlan();
	}
}

function clearMap()
{
	toggleMode();
	if (marker_move)
	{
		map.removeOverlay(marker_move);
	}
	if (marker_SW)
	{
		map.removeOverlay(marker_SW);
	}
	if (marker_NE)
	{
		map.removeOverlay(marker_NE);
	}
	if (border)
	{
		map.removeOverlay(border);
	}
	if (geoXml)
	{
		map.removeOverlay(geoXml);
		geoXml = null;
	}
	if (poly)
	{
		poly.disableEditing();
		map.removeOverlay(poly);
		updatedPolygon = false;
		GEvent.trigger(poly, "cancelline");
		poly = null;
	}
	if (tempPolygon)
	{
		tempPolygon.disableEditing();
		map.removeOverlay(tempPolygon);
		GEvent.trigger(tempPolygon, "cancelline");
		tempPolygon = null;
	}

	firstPoint = null;
	points = [];
	markers = [];
	$("#CommercialProductsHeading").show();
	$("#FreeDataHeading").show();
	$(".ProductResult").css("height", "0px");
	$(".ProductResult").hide();
	document.getElementById("KmlRegionBounds").value = "&lt;-- Click on the map to create Kml";
	document.getElementById("AvailableProducts").innerHTML = "";
	document.getElementById("FreeDataProducts").innerHTML = "";
	$("#ProductButtons").hide();
	clear();
}

function resetMap()
{
	mapArea = "Area: 0.000 km&sup2; ";
	mouseCoord = "Mouse Position: 0.00000, 0.00000 ";
	mouseStatus = "<div>" + mapArea + "</div><div>" + mouseCoord + "</div>";
	document.getElementById("mapdata").innerHTML = mouseStatus;
	
	clearMap();
	
	center = new GLatLng(0.0, 0.0);
	latitude = center.lat().toFixed(6);
	longitude = center.lng().toFixed(6);
	zoom = 2;
	map.setCenter(center, zoom);
	
	queryStr = null;
	
	//utils resetting
	toggleProductMode();
}

function toggleMode()
{
	var polygonMode = document.getElementById("drawMode_polygon").checked;
	if (polygonMode)
	{
		mapArea = "Area: 0.000 km&sup2; ";
	}
	
	if (markers.length > 1)
	{
		drawCoordinates();
	}
}

// Currently clearPolygon = clearMap...
function clearPolygon()
{
	if (poly)
	{
		map.removeOverlay(poly);
		poly = null;
	}
	clearMap();
}

function drawCoordinates()
{
	if (!border)
	{
		return false;
	}
	
	logCoordinates();
	
	// Draws Google Earth stuff
	//parse_kml(poly);
}

function logCoordinates()
{
	var lat, lng;
	var currentVertex;
	var text = "";
	
	for (var i = 0; i < border.getVertexCount(); i++)
	{
		currentVertex = border.getVertex(i);
		lat = currentVertex.lat();
		lon = currentVertex.lng();
		text += lon + "," + lat + "," + polygonDepth + " ";
	}
	
	document.getElementById("KmlRegionBounds").value = text;
}

function showAddress(address)
{
	if (geocoder)
	{
		geocoder.getLatLng(address, function(point)
		{
			if (!point)
			{
				alert(address + " not found");
			}
			else
			{
				clearMap();
				map.setCenter(point, 5);
			}
		});
	}
}

function update_mapStatus()
{
	mouseStatus =	"<div>" + mapArea + "</div><div>" + mouseCoord + "</div>";
	document.getElementById("mapdata").innerHTML = mouseStatus;
}

function update_mouseposition(point)
{
	var decimals = 5;
	var currentLat;
	var currentLon;
	zoom = map.getZoom();
	
	currentLat = 1.0 * point.lat();
	currentLon = 1.0 * point.lng();
	
	var currentCoordStr="Mouse Position: " + currentLat.toFixed(decimals) + ", " + currentLon.toFixed(decimals) + " ";
	mouseCoord = currentCoordStr;
}

function update_mapType()
{
	map.clearOverlays();
	tile_overlay = new GTileLayerOverlay(tilelayer);
	map.addOverlay(tile_overlay);
	if (clickedOnToggleDisplay == false)
	{
		tile_overlay.hide();
	}
}

/*function handleXmlLoad() // some alerts for handling xml loading... not used!
{
	alert("handling xml load:");
	if (geoXml.loadedCorrectly())
	{
		alert("loaded correctly...");
	}
	if (geoXml.hasLoaded())
	{
		alert("has loaded...");
	}
	alert("done...");
}*/

//======================================================================================================
// Custom Buttons on Google Maps... can be used to call other functions...
//======================================================================================================
function ShowHideMenu() {}
ShowHideMenu.prototype = new GControl();
ShowHideMenu.prototype.initialize = function(map)
{
	var container = document.createElement("div");
	//-----------------------------
	// Reset view point
	//-----------------------------
	var showHideMenu = document.createElement("div");
	var image_show = document.createElement("img");
	image_show.src = 'GMaps_files/showMenu.png';
	image_show.title = 'Reset Viewpoint';
	var image_hide = document.createElement("img");
	image_hide.src = 'GMaps_files/hideMenu.png';
	image_hide.title = 'Reset Viewpoint';
	this.setButtonStyle_(showHideMenu);
	container.appendChild(showHideMenu);
	
	showHideMenu.appendChild(image_hide);
	GEvent.addDomListener(showHideMenu, "click", function()
	{
		//Todo:
		// DONE 1. toggle show/hide menu button icon
		// 2. show/hide menu
		if (showHideMenu.firstChild == image_hide)
		{
			showHideMenu.removeChild(image_hide);
			showHideMenu.appendChild(image_show);
			document.getElementById("applemenuTable").style.width = "0px";
			document.getElementById("theapplemenu").style.width = "0px";
			document.getElementById("mapTable").style.width = viewportWidth - 30 + "px";
		}
		else if (showHideMenu.firstChild == image_show)
		{
			showHideMenu.removeChild(image_show);
			showHideMenu.appendChild(image_hide);
			document.getElementById("applemenuTable").style.width = "100%";
			document.getElementById("theapplemenu").style.width = "433px";
			document.getElementById("mapTable").style.width = "100%";
		}
		map.checkResize();
	});
	
	map.getContainer().appendChild(container);
	return container;
}

function MapDataButton() {}
MapDataButton.prototype = new GControl();
MapDataButton.prototype.initialize = function(map)
{
	var container = document.createElement("div");
	//-----------------------------
	// MapData
	//-----------------------------
	var mapdata = document.createElement("div");
	var idattr = document.createAttribute("id");
	idattr.value = "mapdata";
	mapdata.setAttributeNode(idattr);
	this.setButtonStyle_(mapdata);
	container.appendChild(mapdata);
	
	map.getContainer().appendChild(container);
	return container;
}

function ClearSelectionButton() {}
ClearSelectionButton.prototype = new GControl();
ClearSelectionButton.prototype.initialize = function(map)
{
	var container = document.createElement("div");
	//-----------------------------
	// Clear Selection
	//-----------------------------
	var clearSelection = document.createElement("div");
	var image = document.createElement("img");
	image.src = 'GMaps_files/erase.png';
	image.title = 'Clear Selection';
	/* Below commented is used to create hover effect.
	var imageHover = document.createElement("img");
	imageHover.src = 'GMaps_files/eraseHover.png';
	imageHover.title = 'Clear Selection';*/
	
	this.setButtonStyle_(clearSelection);
	container.appendChild(clearSelection);
	clearSelection.appendChild(image);
	/*GEvent.addDomListener(clearSelection, "mouseover", function()
	{
		if (clearSelection.firstChild == image)
		{
			clearSelection.removeChild(image);
			clearSelection.appendChild(imageHover);
		}
	});
	GEvent.addDomListener(clearSelection, "mouseout", function()
	{
		if (clearSelection.firstChild == imageHover)
		{
			clearSelection.removeChild(imageHover);
			clearSelection.appendChild(image);
		}
	});*/
	GEvent.addDomListener(clearSelection, "click", clearMap);
	
	map.getContainer().appendChild(container);
	return container;
}

function ResetButton() {}
ResetButton.prototype = new GControl();
ResetButton.prototype.initialize = function(map)
{
	var container = document.createElement("div");
	//-----------------------------
	// Reset view point
	//-----------------------------
	var resetViewpoint= document.createElement("div");
	var image = document.createElement("img");
	image.src = 'GMaps_files/resetViewpoint.png';
	image.title = 'Reset Viewpoint';
	this.setButtonStyle_(resetViewpoint);
	container.appendChild(resetViewpoint);
	resetViewpoint.appendChild(image);
	GEvent.addDomListener(resetViewpoint, "click", function()
	{
		resetMap();
		update_mapType();
	});
	
	map.getContainer().appendChild(container);
	return container;
}

function ToggleDisplay() {}
ToggleDisplay.prototype = new GControl();
ToggleDisplay.prototype.initialize = function(map)
{
	var container = document.createElement("div");
	//-----------------------------
	// Toggle display
	//-----------------------------
	var toggleDisplay= document.createElement("div");
	var image = document.createElement("img");
	image.src = 'GMaps_files/toggleDisplayOn.png';
	image.title = 'Show/Hide Data';
	this.setButtonStyle_(toggleDisplay);
	container.appendChild(toggleDisplay);
	toggleDisplay.appendChild(image);
	
	var imageOff = document.createElement("img");
	imageOff.src = 'GMaps_files/toggleDisplayOff.png';
	imageOff.title = 'Show/Hide Data';
	
	GEvent.addDomListener(toggleDisplay, "click", function()
	{
		/*if (toggleDisplayFlag == true)
		{
			toggleDisplayFlag = false;
		}
		else
		{
			toggleDisplayFlag = true;
		}*/
		
		if (toggleDisplay.firstChild == image)
		{
			toggleDisplay.removeChild(image);
			toggleDisplay.appendChild(imageOff);
			toggleDisplayFlag = false;
			tile_overlay.hide();
			clickedOnToggleDisplay = false;
		}
		else if (toggleDisplay.firstChild == imageOff)
		{
			toggleDisplay.removeChild(imageOff);
			toggleDisplay.appendChild(image);
			toggleDisplayFlag = true;
			tile_overlay.show();
			clickedOnToggleDisplay = true;
		}
	});
	
	map.getContainer().appendChild(container);
	return container;
}

function DrawCustomPolygon() {}
DrawCustomPolygon.prototype = new GControl();
DrawCustomPolygon.prototype.initialize = function(map)
{
	var container = document.createElement("div");
	//-----------------------------
	// Draw Custom Polygon
	//-----------------------------
	var customPolygon = document.createElement("div");
	var image = document.createElement("img");
	image.src = 'GMaps_files/customPolygon.png';
	image.title = 'Draw Custom Polygon';
	customPolygon.appendChild(image);
	this.setButtonStyle_(customPolygon);
	container.appendChild(customPolygon);
	GEvent.addDomListener(customPolygon, "click", handleCustomPolyonClick);
	
	map.getContainer().appendChild(container);
	return container;
}

function DrawDragPolygon() {}
DrawDragPolygon.prototype = new GControl();
DrawDragPolygon.prototype.initialize = function(map)
{
	var container = document.createElement("div");
	//-----------------------------
	// Draw Drag Polygon
	//-----------------------------
	var drawDragPolygon = document.createElement("div");
	var image = document.createElement("img");
	image.src = 'GMaps_files/boxSelect.png';
	image.title = 'Draw Box Selection';
	this.setButtonStyle_(drawDragPolygon);
	container.appendChild(drawDragPolygon);
	drawDragPolygon.appendChild(image);
	GEvent.addDomListener(drawDragPolygon, "click", dragSelectPolygon);
	map.getContainer().appendChild(container);
	return container;
}

function SaveKML() {}
SaveKML.prototype = new GControl();
SaveKML.prototype.initialize = function(map)
{
	var container = document.createElement("div");
	//-----------------------------
	// Draw Drag Polygon
	//-----------------------------
	var SaveKML = document.createElement("div");
	var image = document.createElement("img");
	image.src = 'GMaps_files/saveAs.png';
	image.title = 'Save KML file';
	this.setButtonStyle_(SaveKML);
	container.appendChild(SaveKML);
	SaveKML.appendChild(image);
	GEvent.addDomListener(SaveKML, "click", downloadKml);
	map.getContainer().appendChild(container);
	return container;
}

function downloadKml()
{
	var str = document.getElementById("KmlRegionBounds").value;
	if (str == "&lt;-- Click on the map to create Kml")
	{
		$("#dialog").html("<p id=\"dialogPrompt\"><span class=\"strong\">First select a geographical area of interest.</span></p>" +
			"<p id=\"dialogPrompt\">You can do this by clicking on one of the &nbsp;<img id=\"helpIcon\" src=\"GMaps_files/boxSelectHover.png\" onclick=\"handleDialogButtonClick_dragSelect();\" width=\"22\" height=\"22\"></img>&nbsp;<img id=\"helpIcon\" src=\"GMaps_files/customPolygonHover.png\" onclick=\"handleDialogButtonClick_customPolygon();\" width=\"22\" height=\"22\"></img> icons.</p>");
		setDialog(70);
		$("#dialog").dialog("open");
		return;
	}
	if (poly)
	{
		poly.disableEditing();
	}
	var area = (border.getArea() / (1000 * 1000)).toFixed(3);
	var centroid = "" + border.getBounds().getCenter().lng().toFixed(6) + "," + border.getBounds().getCenter().lat().toFixed(6) + ",0.0";
	
	var form = document.createElement("form");
	form.setAttribute("method", "post");
	form.setAttribute("action", downloadKmlUrl);
	
	var coordinateField = document.createElement("input");
	coordinateField.setAttribute("type", "hidden");
	coordinateField.setAttribute("name", "coordinates");
	coordinateField.setAttribute("value", str);
	form.appendChild(coordinateField);
	var dataField = document.createElement("input");
	dataField.setAttribute("type", "hidden");
	dataField.setAttribute("name", "aoi_area");
	dataField.setAttribute("value", area);
	form.appendChild(dataField);
	var centroidField = document.createElement("input");
	centroidField.setAttribute("type", "hidden");
	centroidField.setAttribute("name", "centroid");
	centroidField.setAttribute("value", centroid);
	form.appendChild(centroidField);
	
	document.body.appendChild(form);
	form.submit();
	document.body.removeChild(form);
}

//function CustomButton() {}
//CustomButton.prototype = new GControl();
//CustomButton.prototype.initialize = function(map)
//{
//	var container = document.createElement("div");
	
	//-----------------------------
	// Draw Box Selection
	//-----------------------------
//	var boxPolygon = document.createElement("div");
//	var image = document.createElement("img");
//	image.src = 'GMaps_files/boxSelect.png';
//	image.title = 'Draw Box Selection';
//	this.setButtonStyle_(boxPolygon);
//	container.appendChild(boxPolygon);
//	boxPolygon.appendChild(image);
//	GEvent.addDomListener(boxPolygon, "click", handleBoxSelection);

	//-------------------------
	// Project Query - NOT USED ANYMORE
	//-------------------------
	/*var queryDiv = document.createElement("div");
	var image = document.createElement("img");
	image.src = 'GMaps_files/query_region.png';
	image.title = 'Show ComputaMaps Projects';
	this.setButtonStyle_(queryDiv);
	container.appendChild(queryDiv);
	queryDiv.appendChild(image);
	GEvent.addDomListener(queryDiv, "click", function()
	{
		if (poly != null)
		{
			query_project_results(poly);
		}
		else
		{
			alert("Please choose an area.");
		}

	});*/
	
	/*//-------------------------
	// Free Data Query - NOT USED ANYMORE
	//-------------------------
	var queryFreeData = document.createElement("div");
	var image = document.createElement("img");
	image.src = 'GMaps_files/freedata.png';
	image.title = 'Query Free Data';
	this.setButtonStyle_(queryFreeData);
	container.appendChild(queryFreeData);
	queryFreeData.appendChild(image);
	GEvent.addDomListener(queryFreeData, "click", show_free_data);*/
	
	/*//-----------------------------
	// Draw Polygon / Polylines - NOT USED ANYMORE
	//-----------------------------
	var customPolygon = document.createElement("div");
	var image = document.createElement("img");
	image.src = 'GMaps_files/polygon2.png';
	image.title = 'Draw Polygon / Polylines';
	this.setButtonStyle_(customPolygon);
	container.appendChild(customPolygon);
	customPolygon.appendChild(image);
	GEvent.addDomListener(customPolygon, "click", function(poly)
	{
		$("#AvailableProducts").html("");
		var polyShape = document.getElementById("drawMode_polygon").checked;
		if (polyShape)
		{
			poly = new GPolygon([], lineColor, lineWeight, 1, fillColor, opacity);
		}
		else
		{
			poly = new GPolyline([], lineColor, lineWeight, 1);
		}
		clear();
		if (polygon_overlay != null)
		{
			map.removeOverlay(polygon_overlay);
		}
		polygon_overlay = poly;
		map.addOverlay(polygon_overlay);
		
		poly.enableDrawing();
		poly.enableEditing({onEvent: "mouseover"});
		poly.disableEditing({onEvent: "mouseout"});
		var firstPoly = 0;
		GEvent.addListener(poly, "endline", function()
		{
			//query_project_results(poly);
			firstPoly = 1;
		});
		GEvent.addListener(poly, "lineupdated", function()
		{
			if (firstPoly == 1)
			{
				firstPoly = 0;
			}
			else
			{
				if (poly.getVertexCount() > 2)
				{
					query_project_results(poly);
					updatePoints(poly);
				}
			}
			//if (firstPoly == 1)
			//{
			//	query_project_results(poly);
			//}
		});
	});*/

	//map.getContainer().appendChild(container);
	//return container;
//}

function updatePolygon()
{
	if (border)
	{
		map.removeOverlay(border);
	}

	// Check for moved center...
	if ( marker_move.getPoint() != marker_move.savePoint )
	{
		var x = marker_move.getPoint().lat() - marker_move.savePoint.lat() ;
		var y = marker_move.getPoint().lng() - marker_move.savePoint.lng() ;
		marker_SW.setPoint( new GLatLng( marker_SW.getPoint().lat() + x, marker_SW.getPoint().lng() + y) ) ;
		marker_NE.setPoint( new GLatLng( marker_NE.getPoint().lat() + x, marker_NE.getPoint().lng() + y) ) ;
	}
	else // Center not moved so move center
	{
		var x = (marker_SW.getPoint().lat() + marker_NE.getPoint().lat()) / 2 ;
		var y = (marker_NE.getPoint().lng() + marker_SW.getPoint().lng()) / 2 ;
		marker_move.setPoint( new GLatLng(x,y)) ;
	}
	
	marker_move.savePoint = marker_move.getPoint();	// Save for later
	
	var points = [
		marker_NE.getPoint(),
		new GLatLng(marker_SW.getPoint().lat(), marker_NE.getPoint().lng()),
		marker_SW.getPoint(),
		new GLatLng(marker_NE.getPoint().lat(), marker_SW.getPoint().lng()),
		marker_NE.getPoint()];
	border = new GPolygon(points, lineColor, lineWeight, 1, fillColor, opacity);
	
	if ((marker_NE.getPoint().lat() < marker_SW.getPoint().lat()) || (marker_NE.getPoint().lng() < marker_SW.getPoint().lng()))
	{
		marker_NE.setPoint(border.getBounds().getNorthEast());
		marker_SW.setPoint(border.getBounds().getSouthWest());
	}
	
	// Must divide by (1,000,000) because border.getArea() returns square meters
	var area = (border.getArea() / (1000 * 1000)).toFixed(3);
	mapArea = "Area: " + area + " km&sup2; ";
	
	map.addOverlay(border);
	
	// Log area of interest as kml
	drawCoordinates();
	// Query available data
	updateCode(); 
}

function updateCode()
{
	// Jump to Available Products
	showAvailableProducts();
	//ddaccordion.toggleone('silverheader', 2);

	var toggleMode = document.getElementById("commercial_data").checked;
	
	// Show correct product heading
	if (toggleMode)
	{
		$("#CommercialProductsHeading").hide();
		productResultsHeight = viewportHeight - 525 + "px";
		$(".ProductResult").css("height", productResultsHeight);
		showCommercialProducts();
	}
	else
	{
		$("#FreeDataHeading").hide();
		productResultsHeight = viewportHeight - 490 + "px";
		$(".ProductResult").css("height", productResultsHeight);
		showFreeData();
	}
	
	var str;

	if (marker_NE.getPoint().lng() < marker_SW.getPoint().lng())
	{
		$("#dialog").html("<p id=\"dialogPrompt\">Please do not cross the -180/180 longitude line.</p>");
		setDialog(50);
		$("#dialog").dialog("open");
		return;
	}
	
	if (toggleMode)
	{
		str = "";
		str = str + "operation=GetDatasets&format=HTMLForm" + 
		"&north=" + marker_NE.getPoint().lat().toString() +
		"&south=" + marker_SW.getPoint().lat().toString() +
		"&east=" + marker_NE.getPoint().lng().toString() +
		"&west=" + marker_SW.getPoint().lng().toString();
		$(".ProductResult").show();
		$("#AvailableProducts").html("<div align=\"center\"><br/><br/><img src='GMaps_files/ajax-loader.gif'></img></div>");
		$.ajax({
			type: "GET",
			url: retrieveDatasetInfoURL,
			data: str,
			cache: false,
			success: function(msg)
			{
				try
				{
					$("#AvailableProducts").html(msg);
					$("#ProductButtons").show();
					//remove_duplicate_tables();
					$("#SubmitQuery").attr("action", commercialdata_url);
					// See processFreedata() in utils.js to update heading for freedata
					$("#SubmitRequestHeading").html("<span class=\"strong\">Please fill in this form to complete the query.</span>");
				}
				catch (ex) {}
			}
		});
	}
	else
	{
		str = "";
		str = str + "operation=GetFreeDatasets&format=HTMLForm" + 
		"&north=" + marker_NE.getPoint().lat().toString() +
		"&south=" + marker_SW.getPoint().lat().toString() +
		"&east=" + marker_NE.getPoint().lng().toString() +
		"&west=" + marker_SW.getPoint().lng().toString();
		$(".ProductResult").show();
		$("#FreeDataProducts").html("<div align=\"center\"><br/><br/><img src='GMaps_files/ajax-loader.gif'></img></div>");
		$.ajax({
			type: "GET",
			url: retrieveDatasetInfoURL,
			data: str,
			cache: false,
			success: function(msg)
			{
				try
				{
					$("#FreeDataProducts").html(msg);
					$("#ProductButtons").hide();
					$("#SubmitQuery").attr("action", freedata_url);
				}
				catch (ex) {}
			}
		});
	}
	str = null;
}

function dragSelectPolygon()
{
	$("#AvailableProducts").html("");
	$("#FreeDataProducts").html("");
	showAvailableProducts();
	//clearMap();
	if (poly)
	{
		map.removeOverlay(poly);
	}
	if (border)
	{
		map.removeOverlay(border);
	}
	if (marker_move)
	{
		map.removeOverlay(marker_move);
	}
	if (marker_SW)
	{
		map.removeOverlay(marker_SW);
	}
	if (marker_NE)
	{
		map.removeOverlay(marker_NE);
	}
	
	poly = new GPolygon([], lineColor, lineWeight, 1, fillColor, opacity);
	map.addOverlay(poly);
	poly.enableDrawing();
	
	poly.hide();
	var newBounds;
	GEvent.addListener(poly, "lineupdated", function()
	{
		setTimeout(function()
		{
			if (poly)
			{
				if (poly.getVertexCount() == 1)
				{
					firstPoint = new GLatLng(poly.getVertex(0).lat(), poly.getVertex(0).lng());
				}
				else if (poly.getVertexCount() == 2)
				{
					poly.show();
					map.removeOverlay(poly);
					newBounds = poly.getBounds();
					generateBox(newBounds);
					poly.disableEditing();
					GEvent.trigger(poly, "cancelline");
					poly = null;
					firstPoint = null;
					if (tempPolygon)
					{
						map.removeOverlay(tempPolygon);
					}
				}
				else if (poly.getVertexCount() > 2)
				{
					$("#dialog").html("<p id=\"dialogPrompt\">Please do not click too fast</p>");
					setDialog(50);
					$("#dialog").dialog("open");
					map.removeOverlay(poly);
					poly.disableEditing();
					GEvent.trigger(poly, "cancelline");
					poly = null;
					firstPoint = null;
					if (tempPolygon)
					{
						map.removeOverlay(tempPolygon);
					}
				}
			}
		}, 50);
	});
}

function generateBox(newBounds)
{
	if (poly)
	{
		poly.disableEditing();
		map.removeOverlay(poly);
		GEvent.trigger(poly, "cancelline");
	}
	if (poly)
	{
		poly.disableEditing();
		map.removeOverlay(poly);
		GEvent.trigger(poly, "cancelline");
	}
	
	if (marker_move)
	{
		map.removeOverlay(marker_move);
	}
	if (marker_SW)
	{
		map.removeOverlay(marker_SW);
	}
	if (marker_NE)
	{
		map.removeOverlay(marker_NE);
	}
	
	marker_NE = new GMarker(newBounds.getNorthEast(), {draggable: true, icon: icon_NE});
	GEvent.addListener(marker_NE, 'dragend', function()
	{
		updatePolygon();
	});

	marker_SW = new GMarker(newBounds.getSouthWest(), {draggable: true, icon: icon_SW});
	GEvent.addListener(marker_SW, 'dragend', function()
	{
		updatePolygon();
	});

	marker_move = new GMarker( new GLatLng(((marker_SW.getPoint().lat() + marker_NE.getPoint().lat()) / 2), (marker_NE.getPoint().lng() + marker_SW.getPoint().lng()) / 2), {draggable: true, icon: icon_move}) ;
	GEvent.addListener(marker_move, 'dragend', function()
	{
		updatePolygon();
	});
	marker_move.savePoint = marker_move.getPoint();// Save for later

	map.addOverlay(marker_NE);
	map.addOverlay(marker_SW);
	map.addOverlay(marker_move);

	updatePolygon();
}

function handleBoxSelection()
{
	$("#AvailableProducts").html("");
	$("#FreeDataProducts").html("");
	if (poly)
	{
		poly.disableEditing();
		map.removeOverlay(poly);
		GEvent.trigger(poly, "cancelline");
	}
	
	if (marker_move)
	{
		map.removeOverlay(marker_move);
	}
	if (marker_SW)
	{
		map.removeOverlay(marker_SW);
	}
	if (marker_NE)
	{
		map.removeOverlay(marker_NE);
	}
	var divideNum = 2.5;
	var bounds = map.getBounds();
	var span = bounds.toSpan();
	var newSW = new GLatLng(bounds.getSouthWest().lat() + span.lat()/divideNum, 
			  bounds.getSouthWest().lng() + span.lng()/divideNum);
	var newNE = new GLatLng(bounds.getNorthEast().lat() - span.lat()/divideNum, 
			  bounds.getNorthEast().lng() - span.lng()/divideNum);

	var newBounds = new GLatLngBounds(newSW, newNE);

	marker_NE = new GMarker(newBounds.getNorthEast(), {draggable: true, icon: icon_NE});
	GEvent.addListener(marker_NE, 'dragend', function()
	{
		updatePolygon();
	});

	marker_SW = new GMarker(newBounds.getSouthWest(), {draggable: true, icon: icon_SW});
	GEvent.addListener(marker_SW, 'dragend', function()
	{
		updatePolygon();
	});

	marker_move = new GMarker( new GLatLng(((marker_SW.getPoint().lat() + marker_NE.getPoint().lat()) / 2), (marker_NE.getPoint().lng() + marker_SW.getPoint().lng()) / 2), {draggable: true, icon: icon_move}) ;
	GEvent.addListener(marker_move, 'dragend', function()
	{
		updatePolygon();
	});
	marker_move.savePoint = marker_move.getPoint();// Save for later

	map.addOverlay(marker_NE);
	map.addOverlay(marker_SW);
	map.addOverlay(marker_move);

	updatePolygon();
}

var updatedPolygon = false;
function handleCustomPolyonClick()
{
	$("#AvailableProducts").html("");
	$("#FreeDataProducts").html("");
	showAvailableProducts();
	//clearMap();
	if (poly)
	{
		map.removeOverlay(poly);
	}
	if (border)
	{
		map.removeOverlay(border);
	}
	if (marker_move)
	{
		map.removeOverlay(marker_move);
	}
	if (marker_SW)
	{
		map.removeOverlay(marker_SW);
	}
	if (marker_NE)
	{
		map.removeOverlay(marker_NE);
	}
	
	updatedPolygon = false;
	
	poly = new GPolygon([], lineColor, lineWeight, 1, fillColor, opacity);
	var newBounds;
	
	map.addOverlay(poly);
	poly.enableDrawing();
	poly.enableEditing({onEvent: "mouseover"});
	poly.disableEditing({onEvent: "mouseout"});

	marker_NE = new GMarker(new GLatLng(0, 0), {draggable: true, icon: icon_NE});
	marker_SW = new GMarker(new GLatLng(0, 0), {draggable: true, icon: icon_SW});
	GEvent.addListener(poly, "lineupdated", function()
	{
		border = poly;
		drawCoordinates();
		if (updatedPolygon == true)
		{
			try
			{
				setTimeout(function()
				{
					mapArea = "Area: " + poly.getArea() / (1000 * 1000) + " km&sup2; ";
					newBounds = poly.getBounds();
					marker_NE.setPoint(new GLatLng(newBounds.getNorthEast().lat(), newBounds.getNorthEast().lng()));
					marker_SW.setPoint(new GLatLng(newBounds.getSouthWest().lat(), newBounds.getSouthWest().lng()));
					updateCode();
				}, 50);
			}
			catch (ex)
			{
				updatedPolygon = false;
			}
		}
	});
	GEvent.addListener(poly, "endline", function()
	{
		setTimeout(function()
		{
			border = poly;
			drawCoordinates();
			if ((poly.getVertexCount() > 2) && (updatedPolygon == false))
			{
				updatedPolygon = true;
				mapArea = "Area: " + poly.getArea() / (1000 * 1000) + " km&sup2; ";
				newBounds = poly.getBounds();
				marker_NE.setPoint(new GLatLng(newBounds.getNorthEast().lat(), newBounds.getNorthEast().lng()));
				marker_SW.setPoint(new GLatLng(newBounds.getSouthWest().lat(), newBounds.getSouthWest().lng()));
				updateCode();
			}
		}, 50);
	});
	GEvent.addListener(poly, "cancelline", function()
	{
		setTimeout(function()
		{
			if ((poly) && (poly.getVertexCount() == 3))
			{
				$("#dialog").html("<p id=\"dialogPrompt\">Please select a custom region containing 2 or more vertices.</p>");
				setDialog(50);
				$("#dialog").dialog("open");
				clearMap();
			}
		}, 50);
	});
}

DrawCustomPolygon.prototype.setButtonStyle_ = function(button)
{
	button.style.color = "#333333";
	button.style.backgroundColor = "white";
	button.style.fontFamily = "Geneva, Arial, Helvetica, sans-serif";
	button.style.border = "1px solid black";
	button.style.padding = "2px";
	button.style.marginBottom = "3px";
	button.style.textAlign = "center";
	button.style.width = "32px";
	button.style.height = "32px";
	button.style.cursor = "pointer";
}

ToggleDisplay.prototype.setButtonStyle_ = function(button)
{
	button.style.color = "#333333";
	button.style.backgroundColor = "white";
	button.style.fontFamily = "Geneva, Arial, Helvetica, sans-serif";
	button.style.border = "1px solid black";
	button.style.padding = "2px";
	button.style.marginBottom = "3px";
	button.style.textAlign = "center";
	button.style.width = "32px";
	button.style.height = "32px";
	button.style.cursor = "pointer";
}

ResetButton.prototype.setButtonStyle_ = function(button)
{
	button.style.color = "#333333";
	button.style.backgroundColor = "white";
	button.style.fontFamily = "Geneva, Arial, Helvetica, sans-serif";
	button.style.border = "1px solid black";
	button.style.padding = "2px";
	button.style.marginBottom = "3px";
	button.style.textAlign = "center";
	button.style.width = "32px";
	button.style.height = "32px";
	button.style.cursor = "pointer";
}

ClearSelectionButton.prototype.setButtonStyle_ = function(button)
{
	button.style.color = "#333333";
	button.style.backgroundColor = "white";
	button.style.fontFamily = "Geneva, Arial, Helvetica, sans-serif";
	button.style.border = "1px solid black";
	button.style.padding = "2px";
	button.style.marginBottom = "3px";
	button.style.textAlign = "center";
	button.style.width = "32px";
	button.style.height = "32px";
	button.style.cursor = "pointer";
}

MapDataButton.prototype.setButtonStyle_ = function(button)
{
	button.style.color = "#333333";
	button.style.backgroundColor = "white";
	button.style.fontFamily = "Geneva, Arial, Helvetica, sans-serif";
	button.style.fontWeight = "bold";
	button.style.border = "1px solid black";
	button.style.padding = "2px";
	button.style.marginBottom = "3px";
	button.style.textAlign = "left";
	button.style.width = "232px";
	button.style.height = "32px";
	button.style.cursor = "default";
	button.style.opacity = mapdataOpacity;
	button.style.filter = "alpha(opacity=" + mapdataOpacity * 100 + ")";
	button.style.filter =	"alpha(opacity=" + mapdataOpacity * 100 + ") "; 
	//button.style.filter =	"alpha(opacity=" + mapdataOpacity * 100 + ") " + 
	//				"progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr='#ffa0a0a0',EndColorStr='#ff000000');";
	//button.style.-moz-opacity = "0.95";
}

DrawDragPolygon.prototype.setButtonStyle_ = function(button)
{
	button.style.color = "#333333";
	button.style.backgroundColor = "white";
	button.style.fontFamily = "Geneva, Arial, Helvetica, sans-serif";
	button.style.border = "1px solid black";
	button.style.padding = "2px";
	button.style.marginBottom = "3px";
	button.style.textAlign = "center";
	button.style.width = "32px";
	button.style.height = "32px";
	button.style.cursor = "pointer";
}

SaveKML.prototype.setButtonStyle_ = function(button)
{
	button.style.color = "#333333";
	button.style.backgroundColor = "white";
	button.style.fontFamily = "Geneva, Arial, Helvetica, sans-serif";
	button.style.border = "1px solid black";
	button.style.padding = "2px";
	button.style.marginBottom = "3px";
	button.style.textAlign = "center";
	button.style.width = "32px";
	button.style.height = "32px";
	button.style.cursor = "pointer";
}

ShowHideMenu.prototype.setButtonStyle_ = function(button)
{
	button.style.color = "#333333";
	button.style.backgroundColor = "white";
	button.style.fontFamily = "Geneva, Arial, Helvetica, sans-serif";
	button.style.border = "1px solid black";
	button.style.padding = "2px";
	button.style.marginBottom = "3px";
	button.style.textAlign = "center";
	button.style.width = "32px";
	button.style.height = "32px";
	button.style.cursor = "pointer";
}

/* // Not used anymore
CustomButton.prototype.setButtonStyle_ = function(button)
{
	button.style.color = "#333333";
	button.style.backgroundColor = "white";
	button.style.fontFamily = "Geneva, Arial, Helvetica, sans-serif";
	button.style.border = "1px solid black";
	button.style.padding = "2px";
	button.style.marginBottom = "3px";
	button.style.textAlign = "center";
	button.style.width = "32px";
	button.style.height = "32px";
	button.style.cursor = "pointer";
}*/

function getCheckedItem()
{
	var container;
	var str = "";
	var productMode = document.getElementById("commercial_data").checked;
	
	var productElement = "";
	var checkType;
	if (productMode)
	{
		productElement = "AvailableProducts";
	}
	else
	{
		productElement = "FreeDataProducts";
	}
	if (document.getElementById && (container = document.getElementById(productElement))
		&& container.getElementsByTagName)
	{
		var controls = container.getElementsByTagName("input");
		var currentType;
		for (var i = 0, n = controls.length; i < n; ++i)
		{
			if (productMode)
			{
				if (controls[i].type == "checkbox")
				{
					if (controls[i].checked)
					{
						str = str + controls[i].name + "\n";
					}
				}
			}
			else
			{
				if (controls[i].type == "radio")
				{
					if (controls[i].checked)
					{
						str = str + controls[i].value;
					}
				}
			}
		}
	}
	document.getElementById("databaseID").value = str;
}

/*function show_free_data() // Show free data on google earth plugin - Currently not used
{
	try
	{
		if (geoXml)
		{
			if (geoXml.isHidden())
			{
				geoXml.show();
			}
			else
			{
				geoXml.hide();
			}
		}
		else
		{
			$("#FreeDataContents").html("<div align=\"center\"><img src='GMaps_files/ajax-loader.gif'></img></div>");
			geoXml = new GGeoXml(freedata_url, function()
			{
				map.addOverlay(geoXml);
				$("#FreeDataContents").html('');
			});
		}
	}
	catch (ex)
	{
		alert("Error trying to show free data.");
	}
}*/


//]]>
$(document).ready(function()
{
	MM_preloadImages('index_files/marketsX.gif','index_files/productsX.gif','index_files/servicesX.gif','index_files/datasearchX.gif','index_files/aboutX.gif');
	var currentForm = $("#SubmitQuery");
	
	var hidePanels = function()
	{
		$('#panels > div').hide();
	}
	hidePanels();
	
	$('#panels > div:eq(0)').show(); // Show first panel by default
	if (viewportHeight < 267)
	{
		viewportHeight = 268;
	}
	$("#dialog").dialog(
	{
		autoOpen: false,
		buttons: {"Ok": function(){ $(this).dialog("close");}},
		draggable: true,
		modal: true,
		resizable: false,
		height: 285,
		width: 410,
		overlay: {opacity: 0.5, background: "black"}
	});
	
	$("#theapplemenu").resizable({
		maxHeight: viewportHeight - 267,
		minHeight: viewportHeight - 267,
		minWidth: 433,
		/*resize: function()
		{
			var theapplemenuResizedWidth = parseInt(document.getElementById("theapplemenu").style.width);
			if (theapplemenuResizedWidth < 433)
			{
				if (theapplemenuResizedWidth < 433/2)
				{
					document.getElementById("applemenuTable").style.width = "10px";
					document.getElementById("theapplemenu").style.width = "10px";
					document.getElementById("mapTable").style.width = viewportWidth - 30 + "px";
				}
				else
				{
					document.getElementById("applemenuTable").style.width = "100%";
					document.getElementById("theapplemenu").style.width = "433px";
					document.getElementById("mapTable").style.width = "100%";
				}
			}
			else
			{
				document.getElementById("applemenuTable").style.width = "100%";
			}
		},*/
		handles: 'e'
	});
	document.getElementById("theapplemenu").style.width = "433px";
	
	load(); // my load function
	currentForm.submit(function()
	{ 
		if(CustomValidation())
		{
			return true;
		}
		else
		{
			return false;
		}
	});
	
	$("#ProductButtons").hide();
});
