﻿
var __polys = new Array();
var __curHighPoly;
var entryPostcode;
var hxRequester = null;
var requestWasAddress = false;
var __addr = null;


var addressResultZone = null;
var currentAddress = null;
var currentAddressWasSingular = true;
var currentLat, currentLon;
var bMapVisible = true;
var map = null;
var localSearch = null;
var marker = null;

//########################################################################
//TODO - Set these server side
var vOld = {id:"2009",description:"Jan 09 to Dec 09"}, vNew = {id:"2010",description:"Jan 10 to Mar 10"};
//var vOld = {id:"2007",description:"Jan 07 to Dec 07"}, vNew = {id:"2008",description:"Jan 08 to Mar 08"};
//########################################################################
var currentVersion = vNew;

function highlightActiveOverlay(overlay, zoomToExtents)
{
    
  //reset all overlays to standard opacity
  if(__curHighPoly)
  {
  	__curHighPoly.opacity = 0.2;
  	//__curHighPoly.color = "#ffffff";
  	__curHighPoly.redraw(true);
  }
  __curHighPoly = overlay;
  //Set active opacity
    overlay.opacity = 0.5;
 
  //Fit Map to area
  if(zoomToExtents) zoomToFit(overlay)
  overlay.redraw(true);
  /**/
  
 
}

function getMarkerOptions(){

	var myIcon = new GIcon();
	myIcon.image = '_assets/icons/HouseMarker.png';
	myIcon.shadow = '_assets/icons/HouseMarkerShadow.png';
	myIcon.iconSize = new GSize(36,30);
	myIcon.shadowSize = new GSize(51,30);
	myIcon.iconAnchor = new GPoint(18,30);
	myIcon.infoWindowAnchor = new GPoint(18,0);	
	myIcon.printImage = '_assets/icons/HouseMarkerPrint.png';
	myIcon.mozPrintImage = '_assets/icons/HouseMarkerMozPrint.png';
	myIcon.printShadow = '_assets/icons/HouseMarkerShadowPrint.png';
	myIcon.transparent = '_assets/icons/HouseMarkerTransparent.png';
	myIcon.imageMap = [14,0,18,1,21,2,23,3,27,4,29,5,30,6,32,7,33,8,34,9,35,10,35,11,35,12,33,13,33,14,33,15,33,16,33,17,33,18,33,19,33,20,33,21,33,22,33,23,33,24,33,25,32,26,30,27,26,28,23,29,15,29,11,28,8,27,4,26,3,25,2,24,2,23,2,22,2,21,2,20,2,19,2,18,2,17,2,16,2,15,2,14,1,13,0,12,0,11,0,10,1,9,2,8,3,7,4,6,4,5,5,4,6,3,7,2,8,1,9,0];
		
	return {icon:myIcon};
//	marker = new GMarker(center,markerOptions );
//	
//	GEvent.addListener(marker, "click", function () {
//		marker.openInfoWindowHtml(userHtml);
//	});
//		
//	//GEvent.addListener(marker, "dragstart", function() {
//		map.closeInfoWindow();
//	});
//		
//	//map.addOverlay(marker);
//	/marker.openInfoWindowHtml(userHtml);

}

function zoomToFit(overlay)
{
  var bounds = overlay.getBounds();
  var mapZoomLevel = map.getBoundsZoomLevel(bounds);
  map.setCenter(bounds.getCenter(), mapZoomLevel);
}
function initialize() {
  if (GBrowserIsCompatible()) {
  
    map = new GMap2(document.getElementById("map_canvas"));
    localSearch = new GlocalSearch();
    
    //map.addControl(new GLargeMapControl());
    map.addControl(new GeodesysZoomControl());
    //map.addControl(new GMapTypeControl());
    map.addControl(new GeodesysMapTypeControl());
    
    entryPostcode = gup('pcode');
    
    GEvent.addListener(map,"click",mapClick);
    
    hxRequester = new GRequester();
    hxRequester.proxyURL = 'Proxy.ashx?url=';
    hxRequester.onnewdata = XMLStringArrayReceived;
    hxRequester.onrequesterror = httpRequestError;
    hxRequester.loadingPanel = "loaderCentral";
    
    setEntryState();
  }
}

function setEntryState()
{
    //debugger;
    if(entryPostcode != null && entryPostcode != "" )
    {
        //Set frmPostcode and call search
        document.getElementById("frmPostcode").value = entryPostcode;
        if(entryPostcode.length < 6){
            alert('Please enter a full postcode');
            toggleDisplay(false); 
        }else{
            toggleDisplay(true);     
            addressSearch();
        }
    }
    else
    {
        toggleDisplay(false);
    }
}
function addressSearchOnReturnKey(e)
{
    //alert(getKeyNum(e));
    if(getKeyNum(e) == 13){
        addressSearch();
        return false;
     }else{
        return true;
     }
}
function addressSearch()
{
    //hide initial content
    changeVisibility('initialContent',false);
    //Display div containing possible multiple address results
    changeVisibility('addressResultsContainer',true);
    var sPostcode = document.getElementById("frmPostcode").value;
    if(sPostcode.length < 6){
        alert('Please provide a full postcode');
        return;
    }
    if (sPostcode != null & sPostcode != '') {
        //TODO - validate postcode
        if (sPostcode.indexOf(' ') == -1) {
            if (sPostcode.length > 4) {
                sPostcode = fixPostcode(sPostcode);                
            }
        }
        clearOverlay();
        requestAddressFromService(currentVersion.id,sPostcode);
    }
}
function fixPostcode(postcode) {
    if (isNumeric(postcode.charAt(4))) {
        return postcode.substring(0, 4) + ' ' + postcode.substring(4);
    }
    else {
        return postcode.substring(0, 3) + ' ' + postcode.substring(3);
    }        
}

function usePointFromPostcode(postcode, callbackFunction) {
  //debugger;
  localSearch.setSearchCompleteCallback(null, 
    function() {
      
      if (localSearch.results[0]) {    
        var resultLat = localSearch.results[0].lat;
        var resultLng = localSearch.results[0].lng;
        var point = new GLatLng(resultLat,resultLng);
        callbackFunction(point);
      }else{
        alert("The postcode you have entered could not be found.\r\nPlease call our customer helpline on 08457 145 145.");
      }
    });  
    
  localSearch.execute(postcode + ", UK");
}


function isNumeric(input) {
    var ref = '1234567890';
    if (ref.indexOf(input) == -1) {
        return false;
    } else {
        return true;
    }
}
function getKeyNum(e)
{
    var keynum;
    var keychar;
    var numcheck;
    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    return keynum;
}
function clearOverlay(overlay){
//debugger;
    if(overlay == null){
        addressResultZone = null;
        __polys.length=0;
        map.clearOverlays();
    }else{
    
    }
}

function bindAddressResults()
{
    //debugger;
   
    var results = document.getElementById("addressResults");
    var allAddresses = __addr.getAddresses();
    //If only 1 address returned then request zone immediately
    if(allAddresses.length == 1)
    {
        currentAddressWasSingular = true;
        getZoneFromAddressID(0);
    }
    else
    {
        currentAddressWasSingular = false;
        toggleDisplay(false);
        var message = document.getElementById("searchMessage");
        message.innerHTML = "";
        var sPostcode = document.getElementById("frmPostcode").value;
        message.innerHTML = sPostcode + " falls within 2 or more supply zone areas. Please choose your property from the list below to identify the correct zone to allow us to produce an accurate report."
        results.innerHTML = "";
        for(var i in allAddresses)
        {
            results.innerHTML += "<li>" 
            + "<a href='javascript:getZoneFromAddressID(" + allAddresses[i].id + ");'>" + allAddresses[i].address + "</a>"
            + "</li>";
        }
    }
}
function getZoneFromAddressID(addressID)
{
    //debugger;
    //alert('test');
    try
    {
        currentAddress = __addr.getAddresses()[addressID];
        currentAddress.ensureCoordsHaveLatLon();
        currentLat = currentAddress.latitude;
        currentLon = currentAddress.longitude;

        toggleDisplay(true,"");
        requestZoneFromService("PWSZ_WGS84",currentVersion.id,currentLon,currentLat,"WGS84");
        map.setCenter(new GLatLng(currentLat,currentLon),11);
        //Centre marker
        if(marker == null){
            marker = new GMarker(new GLatLng(currentLat,currentLon),getMarkerOptions() );
            map.addOverlay(marker);
            GEvent.addListener(marker, "click", function () {
		        //marker.openInfoWindowHtml(userHtml);
		        showInfo(new GLatLng(currentLat,currentLon));
	        });
        }else{
            marker.setLatLng(new GLatLng(currentLat,currentLon));
            map.addOverlay(marker);
        }
        if(currentAddress.source == "gms"){
            displayPostcodeInformation();
        }
    }
    catch(error)
    {
        alert('Error requesting zone ' + error.message);
    }
}

function requestZoneFromService(datasetID,version,x,y,coordSysID)
{
//debugger;
    requestWasAddress = false;
//    var url = 'http://geodevweb02:89/wqservice.asmx/GetPolyEncArray?datasetID=' + datasetID + '&version=' + version + '&x=' + x + '&y=' + y + '&coordSysID=' + coordSysID;
    var url = 'http://services.digdat.co.uk/wqservice.asmx/GetPolyEncArray?datasetID=' + datasetID + '&version=' + version + '&x=' + x + '&y=' + y + '&coordSysID=' + coordSysID;
    hxRequester.loadXMLDoc(url);
}
function requestAddressFromService(version,postcode){
    requestWasAddress = true;
    //HACK fail internal postcode check
    postcode = '__' + postcode;
//    var url = 'http://geodevweb02:89/wqservice.asmx/GetAddressesFromPostcode?Version=' + version + '&Postcode=' + postcode;
    var url = 'http://services.digdat.co.uk/wqservice.asmx/GetAddressesFromPostcode?Version=' + version + '&Postcode=' + postcode;
    hxRequester.loadXMLDoc(url);
}
function toggleDisplay(showMap, mapInfoMessage)
{
    changeVisibility('map_canvas',showMap);
    changeVisibility('search_canvas',!showMap);
    bMapVisible = showMap;
    updateMessage();
}
function showVersion(version){
//debugger;
    currentVersion = version == 'new'? vNew : vOld;
   
   // var elNew = document.getElementById('iNew');
    //var elOld = document.getElementById('iOld');
    if(currentVersion == vNew){
        document.getElementById('iNew').className = 'footer activeTab';
        document.getElementById('iOld').className = 'footer';
    }else{
        document.getElementById('iNew').className = 'footer';
        document.getElementById('iOld').className = 'footer activeTab';
    }
    updateMessage();
}
function updateMessage(){
    var msgElem = document.getElementById('mapMessage');
    if(bMapVisible == true){
        //msgElem.innerHTML = 'Viewing data for ' + currentVersion.description + '<br/>' + 'Click on the map to select another zone.';
        msgElem.innerHTML =  currentVersion.description + ' - click on the map to select another zone.';
    }else{
        msgElem.innerHTML =  currentVersion.description + ' - search address data.';
    }
}
function displayPostcodeInformation(message)
{
//debugger;
    var panel = document.getElementById("info_panel_top");
    if(message == null){
        if(currentAddressWasSingular == true) {
            if(currentAddress.pwsz.length == 4){
                panel.innerHTML = "<b>" + currentAddress.postcode + "</b> is in zone <b>" + currentAddress.pwsz
            + "</b>";
            }else{
                panel.innerHTML = "<b>" + currentAddress.postcode + "</b> is in <b>" + currentAddress.pwsz
            + "</b>";
            }
            //<br/><br/>Centre on <a href='javascript:map.panTo(new GLatLng(" + currentAddress.latitude + "," + currentAddress.longitude + "),15)'>" + currentAddress.postcode + "</a>" 
            //+ "<br/>Show <a href='javascript:centreOnOverlay(\"" + currentAddress.pwsz + "\")'>" + currentAddress.pwsz + "</a>" ;
        }
        else
        {
            panel.innerHTML = "<b>" + currentAddress.address + "</b> is in zone <b>" + currentAddress.pwsz
            + "</b>";//<br/><br/>Centre on <a href='javascript:map.panTo(new GLatLng(" + currentAddress.latitude + "," + currentAddress.longitude + "),15)'>" + currentAddress.address + "</a>" 
            //+ "<br/>Show <a href='javascript:centreOnOverlay(\"" + currentAddress.pwsz + "\")'>" + currentAddress.pwsz + "</a>" ;
        }
    }else{
        panel.innerHTML = message;
    }
    
}
function displayZoneInformation(overlay)
{
//debugger;
    var url = '';
    if(overlay != null){    
        if(overlay.customFields['AWOwned'] == 'True'){ //AW Zone
            url = 'ZoneInfoPanel.aspx?pwsz=' + overlay.customFields['PWSZShortName'] + '&version=' + currentVersion.id;
            if(currentAddressWasSingular == true){
                url += '&addr=' + currentAddress.postcode;
            }else{
                url += '&addr=' + currentAddress.address;
            }
            if(overlay == addressResultZone){
                url += '&d=1';
            }
        }else{//Other water co zone
            url = 'WaterCoInfoPanel.aspx?company=' + overlay.customFields['PWSZShortName'];
        }
    }else{
        url = 'blank.aspx';
    }    
    window.frames['zoneInformation'].location = url;
    
}

function getOverlayFromName(name)
{
//debugger;
    if(addressResultZone.customFields.PWSZShortName == name){
        return addressResultZone;
    }else{
        for(i=0;i< __polys.length; i++)
        {
            if(__polys[i].customFields.PWSZShortName == name)
            {
                return __polys[i];
            }
         }
    }
     
}

function mapClick(overlay,latlng,overlaylatlng)
{
    //debugger;
    if(overlay)
    {
        //Check that it's a valid polygon and not the info window
        if(overlay.customFields){
            highlightActiveOverlay(overlay,false);
            //debugger;
            displayZoneInformation(overlay);
        }
    }
    else
    {
        //alert(latlng.lng() + ',' + latlng.lat());
        requestZoneFromService("PWSZ_WGS84",currentVersion.id,latlng.lng(),latlng.lat(),"WGS84");
    }
}


function XMLStringArrayReceived()
{
//debugger;
    var aryResult = arrayFromXML(hxRequester.lastResponseText,"<string>");
    if(aryResult.length > 0){
        if(aryResult[0].toLowerCase() == "addressstringarray"){
            processAddressArray(aryResult);
        }
        else{
            //zone array;
            processZoneArray(aryResult);
        }
    }else{
        //Attempt Google's localsearch
        //Need to  check for last httprequest type. Could currently be being called by map click returning nothing
        //setTimeout( "alert('No address found/area not covered by Anglian Water.')",10);
        if(requestWasAddress == true){
            usePointFromPostcode(document.getElementById("frmPostcode").value,googleResultReceived);
        }else{
            //Google search has returned an area not covered by us
            //need to reset info panel and postcode info
            addressResultZone = -1;//Need to set this to something non null
            displayPostcodeInformation("<b>" + document.getElementById("frmPostcode").value + "</b> is outside the Anglian Water region and adjacent water companies.");
            setTimeout( "alert('No address found/area not covered by Anglian Water.')",10);
            displayZoneInformation(null);
        }
    }
}
function googleResultReceived(point)
{
    //debugger;
    //alert('Latitude: ' + point.lat() + '\nLongitude: ' + point.lng());
    //requestZoneFromService("PWSZ_WGS84",currentVersion.id,point.lng(),point.lat(),"WGS84");
    
    //build address to bind to
    __addr = new Addresses();
    addr = new Address();
    addr.id = 0;
    addr.address = document.getElementById("frmPostcode").value;
    addr.source = "google";
    addr.postcode = addr.address;
    addr.latitude = point.lat();
    addr.longitude = point.lng();
    __addr.addAddress(addr);
    bindAddressResults();
}
function processAddressArray(addressStringArray){
//debugger;
    var numFields = Number(addressStringArray[1])-2
    var addrCount = (addressStringArray.length - (2 + numFields))/numFields;
    __addr = new Addresses();
    var addr = null;
    for(var i = 0;i < addrCount;i++){
        addr = new Address();
        addr.id = i;
        addr.source= "gms";
        for(var j = 0; j< numFields; j++){
            addr[addressStringArray[j+2]] = addressStringArray[((i+1) * numFields) + 2+j];
        }
        __addr.addAddress(addr);
    }
    bindAddressResults();
}

function processZoneArray(zoneStringArray){
//debugger;
    var newOverlay = null;
    if(isAWZone(zoneStringArray)){  
        newOverlay = addPolyOverlayFromEncoded(map,zoneStringArray,"#007ABE","0.5",3,18,2 ,"#007ABE","0.5");
        if(addressResultZone == null) 
        {
            addressResultZone = newOverlay;
            showInfo(new GLatLng(currentLat,currentLon));
        }        
    }else{
        newOverlay = addPolyOverlayFromEncoded(map,zoneStringArray,"#071400","0.5",3,18,2 ,"#071400","0.5");
        //Try this
        if(addressResultZone == null) 
        {
            addressResultZone = newOverlay;
        }
    }
    __polys.push(newOverlay);
    highlightActiveOverlay(newOverlay, false);
    if(currentAddress.source == "google"){
        //TODO - get the PWSZShortName from the retrieved overlay
        if(addressResultZone != -1){
            currentAddress.pwsz = addressResultZone.customFields["PWSZShortName"];
            displayPostcodeInformation();
        }else{
            //displayPostcodeInformation();
        }
    }
    displayZoneInformation(newOverlay);
}

function httpRequestError()
{
    //alert(hxRequester.lastResponseText);
    alert('An error occurred\r\nPlease try again.');
}

function changeVisibility(elementID, bShow)
{
//debugger;
    var panel = document.getElementById(elementID);
    if(panel){
        if(bShow == true)
        {
            panel.style.display = "block";
            panel.style.visibility = "visible";
        }
        else
        {
            panel.style.display = "none";
            panel.style.visibility = "hidden";
        }
    }
}


function showInfo (latlng)
{
   // debugger;
  if (latlng && addressResultZone.customFields && addressResultZone.customFields["AWOwned"] == 'True') {
    var src = '?version=' + currentVersion.id;
    if(currentAddressWasSingular){
        src += '&addr=' + escape(currentAddress.postcode) + '&pwsz=' + escape(addressResultZone.customFields.PWSZShortName);
    }else{
        src += '&addr=' + escape(currentAddress.address) + '&pwsz=' + escape(addressResultZone.customFields.PWSZShortName);
    }
    
    var html1 = "<iframe src='ZoneInfoWindow.aspx" + src + "' frameBorder=0 width=400px scrolling=no height=140px></iframe>"
        + "<div><a href='javascript:void();' onclick='javascript:map.getInfoWindow().selectTab(1);'>Convert hardness to other units</a></div>";
     var html2 = "<iframe src='HardnessInfoWindow.aspx" + src + "' frameBorder=0 width=400px scrolling=no height=140px></iframe>"
        + "<div><a href='javascript:void();' onclick='javascript:map.getInfoWindow().selectTab(0);'>Back to Information</a></div>";

//    map.openInfoWindow(latlng, Html1);
    map.openInfoWindowTabs(latlng,[new GInfoWindowTab('Information',html1), new GInfoWindowTab('Hardness',html2)] );
  }
}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )    return "";
    else    return unescape(results[1]);
}
function centreOnOverlay (OverlayName)
{
    var overlay = getOverlayFromName(OverlayName);
    highlightActiveOverlay(overlay,true);
    displayZoneInformation(overlay);
}