var checkedLayers = new Array();
$(document).ready(function() {
	//alert("yous in other.js");
    //requireLogin();
    load();
    });
function firefoxCheck()
{
	var browser = navigator.appCodeName;
	if (browser == "Mozilla")
	{
		var version = navigator.userAgent;
		version = version.substring(version.indexOf("Firefox/")+8);
		if (version != "3.0.4")
			alert("We recomend you use Firefox 3.0.4 for optimal performance");
	}
	else
		alert("We recomend you use Mozilla Firefox for optimal performance");
}
function requireLogin()
{
	var mask = document.getElementById("mapRuler");
	mask.style.visibility = "visible";
	mask.style.position = "";
	mask.style.background = "black";
	
	var html = "<div style='background-color: white; width: 300px; height: 50px; top: 40%; left: 40%; ";
	html += "position: absolute; padding: 5px; padding-top: 30px'><form onsubmit='return login()'>";
	html += "Enter the password: <input type='password' id='pw'><br /> ";
	html += "<input style='margin-top: 3px; margin-left: 13px' type='button' onclick='postLogin()' value='Submit'>";
	html += "</form></div>";
	
	mask.innerHTML = html;
	window.scroll(0,0);
}
function postLogin()
{
	var password = document.getElementById("pw").value;
	$.post('login.jsp', {
		pw: password
		}, login);
}
function login(response)
{
	/*if (response)
		alert(response.toString());
	else
		alert(2);
	*/
	if (response == "Authenticated")
	{
		var mask = document.getElementById("mapRuler");
		mask.style.visibility = "hidden";
		mask.style.position = "absolute";
		load();
	}
	else
		alert("Incorrect login");
		
	return false;
}

function toggleMiles(other)
{
	if (other.value == "miles")
		isMiles = true;
	else
		isMiles = false;
}
function toggleAdvancedOptions()
{
	var header = document.getElementById("searchOptionsHeader");
	var body = document.getElementById("searchOptionsBody");
	if (isAdvSearchShowing) //hide it
	{
		//header.innerHTML = "[ + ] Search options";
		header.innerHTML = "Show Search options";
		body.className = "hidden";
	}
	else //show it
	{
		//header.innerHTML = "[ &ndash; ] Search options";
		header.innerHTML = "Hide Search options";
		body.className = "";
	}
	isAdvSearchShowing = !isAdvSearchShowing; //switch value
}
//=====================================================================
//                              Popups Functions
//=====================================================================
function openFeedbackWindow()
{
    var popupUrl = "feedback.jsp";
    window.open(popupUrl, "feedbackWindow", "left=250,top=150,width=800,height=600,resizable=no,scrollbars=no,status=no,menubar=no,toolbar=no,location=no");
}
function openPrintWindow()
{
	if (selectedJurisdiction.polygon)
		PrintObject.center = selectedJurisdiction.polygon[0].getBounds().getCenter();
	else
		PrintObject.center = gmap.getCenter();
	
	PrintObject.list = document.getElementById("listResults").innerHTML;
	if (PrintObject.list.length == 0)
		PrintObject.list = null;
	PrintObject.selectedJurisID = selectedJurisdiction.mainSguid;
	PrintObject.selectedJurisLabel = selectedJurisdiction.label;
	PrintObject.selectedJurisName = selectedJurisdiction.type;
	
    PrintObject.zoom = gmap.getZoom();
    PrintObject.tiles = [];
    PrintObject.mapType = gmap.getCurrentMapType();
	for (var i=0; i < Layers.length; i++)
		if (document.getElementById("chkbx_"+Layers[i]).checked)
			PrintObject.tiles.push(getLayerID(Layers[i]));
	PrintObject.radiusCenter = radiusSearchCircle.polyClickPoint;
	PrintObject.isMiles = isMiles;
	var popupUrl = "print2.jsp";
    var printWindow = window.open(popupUrl, "printWindow", "left=30,top=30,width=990,height=520,resizable=yes,scrollbars=yes,status=no,menubar=no,toolbar=no,location=no");
    printWindow.focus(); 
}

function openHelpWindow()
{
	var popupUrl = "help.jsp";
    window.open(popupUrl, "helpWindow", "left=250,top=150,width=800,height=600,resizable=yes,scrollbars=yes,status=no,menubar=yes,toolbar=no,location=no");
}
function selectPossibleSplitByList(juris, sguid, name)
{
	currentSelectLayer = juris;
	$.getJSON('api-place-search-by-sguid.action', {label: sguid},selectSplitJurisdiction);
}
function selectByList(juris, id, markerNum, name, lat, lng, additionalSGUID)
{	
	if (additionalSGUID)
		selectedJurisdiction.associatedPrevSelection = selectedJurisdiction.polygon;
	else
		selectedJurisdiction.associatedPrevSelection = false;
	
	removeMarkerAtPoint();
	var displayName = getDisplayName(juris);
	handleLayerDisplay(displayName, true);
	selectLayerForSearching(displayName, true);
	if (lat && lng)
	{
		selectedJurisdiction.infoWindow.lat = lat;
		selectedJurisdiction.infoWindow.lng = lng;
	}
	else
	{
		selectedJurisdiction.infoWindow.lat = null;
		selectedJurisdiction.infoWindow.lng = null;
	}
	
    if (juris == "Parish")
    {
    	juris = "ParishInfo";
    }
    else if (juris == "County")
    {
    	juris = "CountyInfo";
    }
    else if (juris == "Diocese")
    {
    	juris = "DioceseInfo";
    }
    
    var query = new esri.arcgis.gmaps.Query();
    query.returnGeometry = true;
    if (id.constructor.toString().indexOf("Array") != -1)
    {
    	query.where = "";
    	for (var i = 0; i < id.length; i++)
    	{
    		if (i > 0)
    		{
    			query.where += " OR ";
    		}
    		query.where += "SPATIALGUID = '" + id[i] + "'";
    	}
    } 
    else
    {
        query.where = "SPATIALGUID = '"+id+"'";
    }
    query.outFields = [GIS_NOTES_FIELD, GIS_LABEL_FIELD, GIS_SGUID_FIELD, GIS_LAT_FIELD, GIS_LNG_FIELD];
    var num = getLayerID(juris);   
    var queryTask = new esri.arcgis.gmaps.QueryTask(serviceURL+"/"+num);
    gmap.closeInfoWindow(); //close info window before we hide the markers
    if (markerNum != null && markerNum < 50)
    {
    	hideClusteredMarkers(markerNum);
    }
    
    queryTask.execute(query, false, function (result)
    {
   		if (result.features.length > 0)
   		{
	   		var zoomFlag = zoomTypes.always; //never disables zoom
	    	if (juris == "Parish"  || juris == "ParishInfo" && gmap.getZoom() > 9)
	    	{ 
	    		zoomFlag = zoomTypes.conditional;
	    	}
    		result.layerName = displayName;
    		
	       /// selectJurisdiction(result, displayName, zoomFlag);
    		selectOnMap(result, null, additionalSGUID);
        }
        else
        {
        	if (name) alert(name +" was unable to be identified on the map.");
        }
    });    		
}

function getSearchParam(juris)
{
    var param;
    switch (juris)
    {
        case "Parish":
        case "ParishBoundary":
            param = "PARISHID";
            break;
        case "RuralDeanery":
        case "CivilRegistration":
        case "Hundred":
        case "Probate":
        case "PoorLaw":
            param = "NAME";
            break;
        default:
            param = juris;
    }
    return param;
}
function resetView()
{
	allowAutoLayerChange = false;
	gmap.setCenter(center, zoom);
}
function resetMap()
{
	resetLayers();
	resetActiveLayerDDL();
	gmap.setCenter(center, zoom);
	clearAll();
}
function resetActiveLayerDDL()
{
	var ddl = document.getElementById("ddlActiveLayer");
	for (var i=0; i < ddl.options.length; i++)
		if (ddl.options[i].value == "County")
			ddl.options[i].selected = true;
}
function getZoomLevel(area)
{
    if (area < 75000000)
        return 11;
    else if (area < 4500000000)
        return 8;
    else    
        return 6;
}
function retrieveParishes(sguid)
{
   	showLoadResult("listResults");
   	switchTab("#lists");
   	$.getJSON('api-jurisdiction-children.action', {
		sGuid: sguid},
		showParishList);   
}
function showParishList(result)
{
		function parishSort(a, b)
		{
			if (a.name == b.name)
				return 0;
			else if (a.name < b.name)
				return -1;
			else
				return 1;		
		}
	var juris = result.jurisGuid.JURISDICTION;
	var jurisType = result.jurisGuid.LAYER;
    result = result.childrenResult.results[0].jurisdictions;
    result.sort(parishSort);
	var html = "<img src='images/close.gif' class='listClose' onclick='clearListSearch()'><div class='resMainHeader'> Parishes in "+juris;
	if (jurisType != "County")
		html += " "+jurisType;
    html += "</div>";
    html += "<div class='layerListing'>";
    for (var i=0; i < result.length; i++)
    {
        var SGUID = result[i].SGUID;
        var lat = result[i].lat;
        var lng = result[i].lng;
        var parishName = result[i].name;
        var county = result[i].county;
        if (result[i].place && result[i].place.indexOf("[") != -1)
        {
        	parishName = result[i].place;
        	if (parishName.indexOf(",") != -1)
        	{
        		var begining = parishName.substring(parishName.indexOf(", ")+2, parishName.indexOf("["));
        		var middle = parishName.substring(0, parishName.indexOf(","));
        		var end = parishName.substring(parishName.indexOf("["));
        		parishName = begining + middle + " " + end;
        	}
        }
        
        var numOfNamesInCounty = result[i].note.substring(0, result[i].note.indexOf(";"));
		if (parseInt(numOfNamesInCounty) > 1)
			parishName = result[i].note.substring(result[i].note.indexOf(";")+1);
		
        html += "<span onclick=\"selectByList('Parish','"+SGUID+"')\" ";
        html += "onmouseover=\"displayMarkerAtPoint("+lat+","+lng+")\" ";
	 	html += "onmouseout=\"removeMarkerAtPoint()\">"; 
        html += parishName+", "+county+"</span><br />"; 
    }
    html += "</div>";
    html += "<div id='listBottomMark'></div>";
    document.getElementById("listResults").innerHTML = html;
    PrintObject.list = html;
    adjustListResultDiv();
}
function famHistCatalogLink(place)
{
	place = place.replace(/ /g, "+");
	var popupUrl = "http://www.familysearch.org/eng/library/fhlcatalog/supermainframeset.asp?display=localityhitlist&columns=*%2C0%2C0&PLACE="+place+"&PARTOF=England&prePLACE="+place+"&prePARTOF=England";
    window.open(popupUrl, "feedbackWindow", "left=250,top=150,width=800,height=600,resizable=yes,scrollbars=yes,status=yes,menubar=yes,toolbar=yes,location=yes");
}
function famHistCatalogLinkCounty(place)
{
	place = place.replace(/ /g, "+");
	var popupUrl = "http://www.familysearch.org/eng/library/fhlcatalog/supermainframeset.asp?display=localitydetails&subject=23549&subject_disp=England%2C+"+place+"&columns=*,0,0";
    window.open(popupUrl, "feedbackWindow", "left=250,top=150,width=800,height=600,resizable=yes,scrollbars=yes,status=yes,menubar=yes,toolbar=yes,location=yes");
}
function famHistWikiLink(place)
{
	place = place.replace(/ /g, "+");
	var popupUrl = "https://wiki.familysearch.org/en/Special:Search?fulltext=true&search="+place+"&searchbutton=Search";
    window.open(popupUrl, "feedbackWindow", "left=250,top=150,width=800,height=600,resizable=yes,scrollbars=yes,status=yes,menubar=yes,toolbar=yes,location=yes");
}
function activateRadialSearch()
{
	document.getElementById("radialSearchButton").disabled = true;
	isRadialSearch = true;	
}
function getInfoWindowPoint()
{
	var window = gmap.getInfoWindow();
	return window.getPoint();
}

function showLoadResult(div)
{
	var html = "<br /><center>Loading...<br />";
	html += "<img src=images/ajax-loader.gif />";
	document.getElementById(div).innerHTML = html;
}
function getOverlayName(name)
{
	var overlayName = name;
	switch (name)
	{
		case "Rural Deanery":
				overlayName = "RuralDeanery";
				break;
		case "Probate Court":
				overlayName = "Probate";
				break;
		case "Poor Law Union":
				overlayName = "PoorLaw";
				break;						
		case "Civil Registration District":
				overlayName = "CivilRegistration";
				break;
		case "Constituent Country":
				overlayName = "ConstituentCountry";
				break;
		case "Extra Parochial":
				overlayName = "ExtraParochial";
				break;
		case "New Forest":
				overlayName = "NewForest";
				break;
		case "County Color":
				overlayName = "CountyShade";
				break;
	}
	return overlayName;
}
function handleLayerDisplay(layer, isFromAuto)
{
	document.getElementById("chkbx_"+layer).checked = true;
	var sender = {checked: true};
	showHideLayer(sender, layer, isFromAuto);
}
//=====================================================================
//                        Utility Functions
//=====================================================================
function swap(array, val1, val2)
{   
    var temp = array[val2];
    array[val2] = array[val1];
    array[val1] = temp;
}
function isInArray(array, value)
{
    for (var i=0; i < array.length; i++)
        if (array[i] == value)
            return true;
    return false;
}
function getIndexOf(array, value)
{
	var index = -1;
	for (var i=0; i < array.length; i++)
        if (array[i] == value)
        {
            index = i;
            break;
        }
    return index;
}
function lowercaseWord(wordArray, string)
{
	for (var i=0; i < wordArray.length; i++)    
    		while (string.indexOf(wordArray[i]) != -1)
    			string = string.substring(0, string.indexOf(wordArray[i])) + wordArray[i].substring(0, 1).toLowerCase() + string.substring(string.indexOf(wordArray[i])+1);
    return string;
}