﻿//Google map related script - START
var map;
var baseIcon;
var PostalLatLngPoint = new Array();
var xmlDoc;

function InitializeGMap()
{
    if (window.DOMParser)
    {
      parser=new DOMParser();
      xmlDoc=parser.parseFromString(strAllLocInfo,"text/xml");
    }
    else // Internet Explorer
    {
      xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
      xmlDoc.async="false";
      xmlDoc.loadXML(strAllLocInfo);
    }
    
    //Initialize the map canvas
    map = new GMap2(document.getElementById("map_canvas"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    
    // Create a base icon for all of our markers that specifies the
    // shadow, icon dimensions, etc.
    baseIcon = new GIcon(G_DEFAULT_ICON);
    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(20, 32);
    baseIcon.shadowSize = new GSize(37, 34);
    
    //Iterate through each element and find the lat lng for the postal code of each location
    var strTempPostalCode;
    var strName;
    var strIconUrl;
    var LocationNodes = xmlDoc.documentElement.getElementsByTagName("node");
    for(nLoop = 0;nLoop < LocationNodes.length; nLoop++)
    {
   
        strTempPostalCode = LocationNodes[nLoop].attributes.getNamedItem("pcode").nodeValue;
        strName = LocationNodes[nLoop].attributes.getNamedItem("name").nodeValue;
        strIconUrl = LocationNodes[nLoop].attributes.getNamedItem("iconurl").nodeValue;
        
        FindLatLngForPostalCode(CreateMarker,strTempPostalCode,strName,strIconUrl,nLoop,LocationNodes.length);
    }
}

function SetZoomAndCenterPoint(PostalLatLngPoint)
{   
    //Find the max and min points
    var MaxLat;
    var MaxLng;
    var MinLat;
    var MinLng;
    var point
    
    for(nLoop = 0;nLoop < PostalLatLngPoint.length;nLoop++)
    {
        point = PostalLatLngPoint[nLoop];
        
        if(MaxLat != null)
        {
            if(MaxLat < point.lat())
            {
                MaxLat = point.lat();
            }
        }
        else        
        {
            MaxLat = point.lat();
        }
        if(MaxLng != null)
        {
            if(MaxLng < point.lng())
            {
                MaxLng = point.lng();
            }
        }
        else        
        {
            MaxLng = point.lng();
        }
        if(MinLat != null)
        {
            if(MinLat > point.lat())
            {
                MinLat = point.lat();
            }
        }
        else        
        {
            MinLat = point.lat();
        }
        if(MinLng != null)
        {
            if(MinLng > point.lng())
            {
                MinLng = point.lng();
            }
        }
        else        
        {
            MinLng = point.lng();
        }
    }
    
    //Get the center and the correct zoom level of the map canvas 
    var Center = new GLatLng((MaxLat + MinLat)/2,(MaxLng + MinLng)/2);        
    var ZoomLevel = map.getBoundsZoomLevel(new GLatLngBounds(new GLatLng(MinLat,MinLng),new GLatLng(MaxLat, MaxLng)));
    
    //This is to make sure that the map is not too much zoomed inside
    if(ZoomLevel > 9)
    {
        ZoomLevel = 9;
    }
    
    map.setCenter(Center,ZoomLevel);
}

function CreateMarker(PostalCode,Name,IconUrl,nLoop,TotalLength,PostalLatLngPoint)
{
    //Create marker
    var myIcon = new GIcon(baseIcon);
    myIcon.image = IconUrl;
    markerOptions = { icon:myIcon};
    map.addOverlay(new GMarker(PostalLatLngPoint[nLoop], markerOptions));
    
    if(nLoop == TotalLength - 1)
    {
        //Set the correct zoom level and center point for the map canvas
        SetZoomAndCenterPoint(PostalLatLngPoint);
    }
}

function FindLatLngForPostalCode(FunctionToCall,PostalCode,Name,IconUrl,nLoop,TotalLength)
{
    var localSearch = new GlocalSearch();	
     
    localSearch.setSearchCompleteCallback(null, 
	    function() {    			
		    if (localSearch.results[0])
		    {		
			    var resultLat = localSearch.results[0].lat;
			    var resultLng = localSearch.results[0].lng;
			    PostalLatLngPoint[nLoop] = new GLatLng(resultLat,resultLng);
			    FunctionToCall(PostalCode,Name,IconUrl,nLoop,TotalLength,PostalLatLngPoint);
		    }else{
			    alert("Postcode not found!");
		    }
	    });	
		
    localSearch.execute(PostalCode + ", UK");
}

function FindLatLngForSinglePostalCode(FunctionToCall,PostalCode,CharityIconUrl,MarsIconUrl)
{    
    var localSearch = new GlocalSearch();	
     
    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);
			    FunctionToCall(point,PostalCode,CharityIconUrl,MarsIconUrl);
		    }else{
			    alert("Postcode not found!");
		    }
	    });	
		
    localSearch.execute(PostalCode + ", UK");
}

function ValidatePostalCode()
{
    var strPostalCode = document.getElementById("PostCodeBox").value;
    
    strPostalCode = strPostalCode.trim();
     
    if(strPostalCode != null && strPostalCode != '')
    {
        if(ValidatePostCodeFormat(strPostalCode))
        {
            FindLatLngForSinglePostalCode(FindPostalCodeDistance,strPostalCode,"./App_Themes/MITC/images/pinup_icon.png","./App_Themes/MITC/images/ballon_dot.png");
        }
    }
   
    return false;
}

function FindPostalCodeDistance(point,PostalCode,CharityIconUrl,MarsIconUrl)
{
    //Iterate through all the plotted points and find the one that is at the minimum distance from this point
    var ValidDistance = xmlDoc.documentElement.getElementsByTagName("distance")[0].attributes.getNamedItem("val").nodeValue;
    var ValidDistanceMile = xmlDoc.documentElement.getElementsByTagName("distance")[0].attributes.getNamedItem("valMile").nodeValue;
    var ValidDistance15 = xmlDoc.documentElement.getElementsByTagName("distance")[0].attributes.getNamedItem("val15").nodeValue;
    var ValidDistanceMile15 = xmlDoc.documentElement.getElementsByTagName("distance")[0].attributes.getNamedItem("valMile15").nodeValue;
    var CurrentPostIndex = 0;
    var CurrentDistance = point.distanceFrom(PostalLatLngPoint[0]);
    for(nLoop = 1;nLoop < PostalLatLngPoint.length;nLoop++)      
    {   
        if(CurrentDistance > point.distanceFrom(PostalLatLngPoint[nLoop]))
        {
            CurrentPostIndex = nLoop;
            CurrentDistance = point.distanceFrom(PostalLatLngPoint[nLoop]);
        }
    }

    //Assign correct address for nearest office and the given postal code
    AssignAddressOutsideMap(CurrentPostIndex, point);
    
    //Mark the distance with a circle on the map
    var ValidFinalDistance;
        var LocationNodes = xmlDoc.documentElement.getElementsByTagName("node");
	if(LocationNodes[CurrentPostIndex].attributes.getNamedItem("locname").nodeValue=="Slough")
    {
        ShowCircleOnMap(PostalLatLngPoint[CurrentPostIndex], MarsIconUrl, point, CharityIconUrl, ValidDistanceMile);
        ValidFinalDistance = ValidDistance;
    }
    else    
    {
        ShowCircleOnMap(PostalLatLngPoint[CurrentPostIndex], MarsIconUrl, point, CharityIconUrl, ValidDistanceMile15);
        ValidFinalDistance = ValidDistance15;
    }
    
    //Now depending on the distince decide whether or not the organisation is eligible for finds
    var PassMessage = document.getElementById("divPass");
    var FailMessage = document.getElementById("divFail");
    
    if(CurrentDistance <= ValidFinalDistance)
    {
        //Handle success
        //Put the location details in the hidden server variable
        var hdnLocDetails = document.getElementById("ctl00_ContentPlaceHolder1_hdnLocDetails");
        
        hdnLocDetails.value = LocationNodes[CurrentPostIndex].attributes.getNamedItem("id").nodeValue+";"+PostalCode;
        
        PassMessage.className = "Show";
        FailMessage.className = "Hide";
    }
    else        
    {
        //Handle Failure
        if(LocationNodes[CurrentPostIndex].attributes.getNamedItem("locname").nodeValue=="Slough")
        {
            var SorryMessage = document.getElementById("lblSorryMessage");        
            var SorryMsg = document.getElementById("hdnSorryMsg").value;
        }
        else
        {
             var SorryMessage = document.getElementById("lblSorryMessage");        
             var SorryMsg = document.getElementById("hdnSorryMsg15").value;
        }

        SorryMsg = SorryMsg.replace("#officename#",LocationNodes[CurrentPostIndex].attributes.getNamedItem("locname").nodeValue);
        
//        SorryMessage.textContent = SorryMsg + LocationNodes[CurrentPostIndex].attributes.getNamedItem("locname").nodeValue;
//        SorryMessage.innerText = SorryMsg + LocationNodes[CurrentPostIndex].attributes.getNamedItem("locname").nodeValue;

        SorryMessage.innerHTML = SorryMsg;
        
        PassMessage.className = "Hide";
        FailMessage.className = "Show";
    }
}

function ShowCircleOnMap(MarsOfficePoint,MarsIconUrl,CharityPoint,CharityIconUrl,ValidDistance)
{
    //Clear all overlays
    map.clearOverlays();
    
    //Clear all overlay points from the global array and add the two new points
    var PostalLatLngPoint = new Array();
    PostalLatLngPoint[0] = MarsOfficePoint;
    PostalLatLngPoint[1] = CharityPoint;
    
    CreateMarker(null,null,MarsIconUrl,0,2,PostalLatLngPoint);
    CreateMarker(null,null,CharityIconUrl,1,2,PostalLatLngPoint);
    
    //Now create the circle on the map to show the valid radius
    //Calculating GlatLngBounds
    var d2r = Math.PI / 180;        
    // Convert statute miles into degrees latitude. First Number is circle radious and 2nd is the constant
    var circleLat = Math.sqrt((2*ValidDistance*ValidDistance)) * 0.014483;
    var circleLng = circleLat / Math.cos(MarsOfficePoint.lat() * d2r);
    
    var theta = Math.PI / 4;
    var vertexLat = MarsOfficePoint.lat() + (circleLat * Math.sin(theta)); 
    var vertexLng = MarsOfficePoint.lng() + (circleLng * Math.cos(theta));
    var vertextLatLngNE = new GLatLng(vertexLat, vertexLng);
    
    theta = Math.PI * (5 / 4);
    vertexLat = MarsOfficePoint.lat() + (circleLat * Math.sin(theta)); 
    vertexLng = MarsOfficePoint.lng() + (circleLng * Math.cos(theta));
    var vertextLatLngSW = new GLatLng(vertexLat, vertexLng);
    
    //Showing the circle on the map
    var boundaries = new GLatLngBounds(vertextLatLngSW, vertextLatLngNE);
    var oldmap = new GGroundOverlay("./App_Themes/MITC/images/circle.png", boundaries);        
    map.addOverlay(oldmap);        
}

function AssignAddressOutsideMap(CurrentPostIndex, UserPostCodePoint)
{
    var OfficeName;
    var OfficeAdd;
    
    //Assign the mars office address
    var LocationNodes = xmlDoc.documentElement.getElementsByTagName("node");
    OfficeName = document.getElementById("divNearestOfficeName");
    OfficeAdd = document.getElementById("divNearestOfficeAdd");        
    
    OfficeName.textContent = LocationNodes[CurrentPostIndex].attributes.getNamedItem("name").nodeValue;
    OfficeName.innerText = LocationNodes[CurrentPostIndex].attributes.getNamedItem("name").nodeValue;
    
    OfficeAdd.textContent = LocationNodes[CurrentPostIndex].attributes.getNamedItem("address").nodeValue + ", " +
    LocationNodes[CurrentPostIndex].attributes.getNamedItem("pcode").nodeValue;
    OfficeAdd.innerText = LocationNodes[CurrentPostIndex].attributes.getNamedItem("address").nodeValue + ", " +
    LocationNodes[CurrentPostIndex].attributes.getNamedItem("pcode").nodeValue;
    
    //Assign the address of the post code entered by the user
    var geocoder = new GClientGeocoder();
    geocoder.getLocations(UserPostCodePoint, GetUserAddress);
    
    //Show the address section
    var AddSecToShow = document.getElementById("divSelectedLocInfo");
    var StaticAddToHide = document.getElementById("divStaticLocInfo");
    
    AddSecToShow.className = "Show";
    StaticAddToHide.className = "Hide";
}

function GetUserAddress(response)
{          
      if (!response || response.Status.code != 200)
      {
        alert("Status Code:" + response.Status.code);
      }
      else
      {
        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
        
        var OfficeName = document.getElementById("lblCharityName");
        var OfficeAdd = document.getElementById("lblCharityAddress");
        
        OfficeAdd.textContent = place.address;
        OfficeAdd.innerText = place.address;
      }
}
//Google map related script - END

function ShowHideLoginCntrlDiv(DivToShow, DivToHide)
{
    var ToShow = document.getElementById(DivToShow);
    var ToHide = document.getElementById(DivToHide);  
       
    
    ToHide.className="Hide";
    ToShow.className="Show";
}

function ValidateFileUpload(ErrorLabelID, UploadFileID, RegExHdnField)
{   
    var ErrorLabel = document.getElementById(ErrorLabelID);
    var UploadFile = document.getElementById(UploadFileID);
    var RegxExp = document.getElementById(RegExHdnField);
    
    if(UploadFile.value != '' && UploadFile.value.length > 0)
    {        
        var strExpression = RegxExp.value;
        
        var re5digit = new RegExp(strExpression);
        
        if (UploadFile.value.search(re5digit)==-1)
        {
            ErrorLabel.innerText = "Selected file is not a document type file";
            ErrorLabel.textContent = "Selected file is not a document type file";
            return false;
        }
        else            
        {
            return true;
        }        
    }
    else
    {   
        ErrorLabel.innerText = "Please select a file to be uploaded";
        ErrorLabel.textContent = "Please select a file to be uploaded";
        return false;       
    }    
}

function ValidatePostCodeFormat(PostCode)
{    
    var strExpression = "^[A-Za-z]{1,2}[0-9]{1,2}([a-zA-Z]{1})?\ [0-9]{1}[a-zA-Z]{2}$";    
    
    var re5digit = new RegExp(strExpression);       
    if(re5digit.test(PostCode))
    {        
        return true;
    }
    else            
    {
        alert("Postcode not found!");
        return false;
    }
}

function LoginSubmit(e) 
{
 	if(e.keyCode==13 ||e.which ==13)
	{	

	     //window.close();
		if (navigator.appName.indexOf('Microsoft') != -1)
	    {
		    document.getElementById("ctl00_Header1_Login_Control1_Button_Login").focus();
	    }
		else
	    {
		    document.getElementById("ctl00_Header1_Login_Control1_Button_Login").click();		    
	    }
	}
}
function PostCodeSubmit(e) 
{
 	if(e.keyCode==13 ||e.which ==13)
	{	

	     //window.close();
		if (navigator.appName.indexOf('Microsoft') != -1)
	    {
		    document.getElementById("GoButton").focus();
	    }
		else
	    {
		    document.getElementById("GoButton").click();		    
	    }
	}
}
function SearchSubmit(e) 
{
//alert('pinaki');

 	if(e.keyCode==13 ||e.which ==13)
	{
	
	     //window.close();
		if (navigator.appName.indexOf('Microsoft') != -1)
	{
		document.getElementById("ctl00_ContentPlaceHolder1_SrchButton").focus();
	}
		else
	{
		document.getElementById("ctl00_ContentPlaceHolder1_SrchButton").click();
	}
	}
}
function InActivateLogin()
{
    document.getElementById("ctl00_Header1_Login_Control1_Button_Login").disabled = true;
}
function ActivateLogin()
{
    document.getElementById("ctl00_Header1_Login_Control1_Button_Login").disabled = false;
}
function CallPrint(strid)
    {        
        var prtContent = document.getElementById(strid);

        var WinPrint = window.open('', '', 'left=0,top=0,width=700,height=700,toolbar=1,scrollbars=1,status=0');        

        WinPrint.document.write(prtContent.innerHTML);

        WinPrint.document.close();

        WinPrint.focus();

        WinPrint.print();

        WinPrint.close();

        //prtContent.innerHTML=strOldOne;

    }     

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
