﻿var _map;
var _showProximity = true;
var _postCode = "";
var _geoRssLayer = null;
var _searchFilter = new Array();
var _objSchools = null;
var _zoomedView = false;
var _drawCircles = false;
var _searchDone = false;
var _homeLat = "";
var _homeLong = "";

// added by clement
var _zoomLevelEventTriggered = false;

function WireUpClientUIHandlers() 
{
    _searchFilter.push("PRI");
    
    $addHandler($get("ctl16__chkELPR"), "click", OnLevelPrimarySelected);
    $addHandler($get("ctl16__chkELSE"), "click", OnLevelSecondarySelected);
    $addHandler($get("ctl16__chkELFS"), "click", OnLevelFullSchoolSelected);
    $addHandler($get("ctl16__chkELJC"), "click", OnLevelJuniorCollegeSelected);
    $addHandler($get("ctl16__chkELIP"), "click", OnLevelIntegratedProgSelected);
}

function OnLevelPrimarySelected() 
{
    var srchPR = $get("ctl16__chkELPR").checked;
    if (srchPR) 
        Array.add(_searchFilter,"PRI");
    else
        Array.remove(_searchFilter,"PRI");
}
function OnLevelSecondarySelected() 
{
    var srchSE = $get("ctl16__chkELSE").checked;
    if (srchSE) 
        Array.add(_searchFilter,"SEC");
    else
        Array.remove(_searchFilter,"SEC");
}
function OnLevelFullSchoolSelected() 
{
    var srchFS = $get("ctl16__chkELFS").checked;
    if (srchFS) 
        Array.add(_searchFilter,"FUL");
    else
        Array.remove(_searchFilter,"FUL");    
}
function OnLevelJuniorCollegeSelected() 
{
    var srchJC = $get("ctl16__chkELJC").checked;
    if (srchJC) 
        Array.add(_searchFilter,"JCI");
    else
        Array.remove(_searchFilter,"JCI");    
}
function OnLevelIntegratedProgSelected() 
{
    var srchIP = $get("ctl16__chkELIP").checked;
    if (srchIP) 
        Array.add(_searchFilter,"IPS");
    else
        Array.remove(_searchFilter,"IPS");    
}

function OnProximityChecked()
{
    _showProximity = !_showProximity;
}

function searchClickHandler()
{
    _searchDone = true;

    MessageBox(true, "Please wait while we search for the schools...");
    // strange -- not sure why the ctl16_ is prepended...
    var txtbox = $get("ctl16__txtPostCode");
    if (txtbox!=null) 
    {
        _postCode = (txtbox.value=="Enter postal code")? "" : txtbox.value;
    }
    
    // Remove current shapes
    _map.DeleteAllShapes();
    
    // Logic: if postal code is unspecified, return all schools, otherwise show schools near postal code
    // 1. retrieve schools data
    if (_objSchools==null) 
        SchoolsDirectoryService.GetSchools(getSchools_success, getSchools_failed);
    else
    {
        // 2. populate the map
        AddSchoolsToMap(0);
    }
    // 3. THEN, if postal code specified, and 1km proximity required, draw circle and zoom
    if (_postCode!="")
        ShowSchoolsNearPostalCode(_postCode, _showProximity);
}

function getZoomedSchools_success(e)
{
    var schoolsData = Sys.Serialization.JavaScriptSerializer.deserialize(e);
    _objSchools = schoolsData.schools.school;
    
    AddSchoolsToMap(1);
}


function getSchools_success(e)
{
    var schoolsData = Sys.Serialization.JavaScriptSerializer.deserialize(e);
    _objSchools = schoolsData.schools.school;
    
    AddSchoolsToMap(0);
}

function getSchools_failed(e)
{
    _objSchools = null;
    alert("error invoking web service");
}


function MessageBox(show, message, timeout)
{
    var balloon = $get('messageBalloon');
    if (!show)
        balloon.style.display = 'none';
    else
    {
        balloon.style.display = 'block';
        balloon.innerHTML = message;
        if (timeout)
            setTimeout('MessageBox(false)', timeout);
    }
}

function LoadMap()
{
    _map = new VEMap('_mapArea');
    _map.LoadMap(new VELatLong(1.34296, 103.816),11,'r',false);
    _map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
    _map.AttachEvent("onendzoom", OnMapZoomed);
    
    _geoRssLayer = new VEShapeLayer();
}

function DoRoute(schLat, schLong)
{
    if (_homeLat!="" && _homeLong!="") {        
        _map.GetRoute(new VELatLong(_homeLat, _homeLong), new VELatLong(schLat, schLong));
    } else {
        alert("Please enter your postal code first!");
    }
} 

function OnMapZoomed(me)
{
    // threshold zoom level = 13
    $get("_dbgTxt").innerHTML = me.zoomLevel;
    // Refresh icon if zoom level is now different
    z = (me.zoomLevel>=13);
    if (z!=_zoomedView) 
    {
        _zoomedView = z;
        if (_searchDone){
           _zoomLevelEventTriggered = true;
           searchClickHandler();
        } 
    }
}

function AddSchoolsToMap(bit) 
{
    var found = 0;

    if (_objSchools && _objSchools.length > 0)
    {
        Array.forEach(_objSchools, AddSchoolToMap);
        found = _objSchools.length;
    }
    
    if (bit==0) {
        if (found > 0)
        {
            var m = String.format("Total {0} schools were found.", found);
            MessageBox(true, m, 2000);
        }
        else
        {
            MessageBox(true, "No schools were found. Please try again later.", 5000);
        }
    } else if (bit==1) {
            MessageBox(true, "Zooming into school", 2000);
    }
}

function AddSchoolsToMap2(xmlDataPath)
{
    var veLayerSpec = new VEShapeSourceSpecification(
                            VEDataType.GeoRSS,
                            xmlDataPath,
                            _geoRssLayer);
                            
    _map.ImportShapeLayerData(veLayerSpec, onFeedLoad, false);
}

function AddSchoolToMap(school)
{
    if (!Array.contains(_searchFilter, school.level)) 
        return;
        
    var icon;
    var schLevel;
    var schType;
    
    switch (school.level)
    {
        case "PRI":
            icon = "1";
            schLevel = "Primary";
        break;
        case "SEC":
            icon = "2";
            schLevel = "Secondary";
        break;
        default:
            icon = "3";
            schLevel = "Junior College";
        break;
    }

    switch (school.schType)
    {
        case "GOV":
            schType = "Government";
        break;
        case "GOA":
            schType = "Government Assisted";
        break;
        case "IDP":
            schType = "Independent";
        break;
        case "FUL":
            schType = "Full School";
        break;
        default:
            schType = "Integrated Programme";
        break;
    }
    
    var newSchoolName = (school.name).split("'").join(""); //remove apostrophes
    
    var html = "<b>Code:</b> {0}<br/><b>Address:</b> {1}<br/>" +
               "<b>Level:</b> {2}<br/><b>School Type:</b> {3}<br/><a href='javascript:addToFav(escape(\"{4}\"),{5},{6},escape(\"{7}\"),escape(\"{8}\"),escape(\"{9}\"))'>Add to Favourites</a> | <a href='javascript:DoRoute({10},{11})'>Plot Route</a><p/>";       
               
    var details = String.format(html,
            school.code, school.address, schLevel, schType, newSchoolName, school.lat, school.long, school.address, schLevel, schType, school.lat, school.long);
            
    var url = (school.url==null)? "" : school.url;
    
    if (url!="") 
        details = details+"<b>Web site:</b> <a href='" + url + "'>" + url + "</a>";
        
    if (!_zoomedView)
        icon = String.format("images/ss{0}.png", icon);
    else
        icon = String.format("images/sc{0}.png", icon);
    AddPushpin(school.lat, school.long, school.name, details, icon);
}

function zoomSchool(lat, lon) {
    // Remove current shapes
    _map.DeleteAllShapes();

    // Add schools
    SchoolsDirectoryService.GetSchools(getZoomedSchools_success, getSchools_failed);
    
    var point = new VELatLong(lat, lon);


    _map.SetCenterAndZoom(point, 14);  
    _zoomedView = true;
}

function AddPushpin(lat, lon, title, description, icon)
{
    var point = new VELatLong(lat, lon);
    var shp = new VEShape(VEShapeType.Pushpin, point);
    shp.SetTitle(title);
    shp.SetDescription(description);
    if (icon)
    {
        shp.SetCustomIcon(icon);
    }
    _map.AddShape(shp);
}

function onFeedLoad(layer) 
{
    var ns = layer.GetShapeCount();
    for(var i=0; i < ns; ++i)
    {
        var s = layer.GetShapeByIndex(i);
        if (!_zoomedView)
            s.SetCustomIcon("images/ss1.png");
        else
            s.SetCustomIcon("images/sc1.png");
    }
}

function ShowSchoolsNearPostalCode(postcode, drawCircles)
{
    _drawCircles = drawCircles;
    // Hard code for now - we should be getting the following values from 
    // the postal code->la-long web service
    SchoolsDirectoryService.GetGPSFromPostCode(postcode, 
        getGPSFromPostCode_success, 
        getGPSFromPostCode_failed, null);
}

function getGPSFromPostCode_success(rc)
{
    var lat, lng;
    var add = "";
    var postcode = "";
    
    // Parse the response code
    var a = rc.split(",");
    if (a.length<4) 
        return;
        
    postcode = a[0];
    lat = a[1];
    lng = a[2];
    add = a[3];
    
    //PATCH
    //set global vars for home lat long
    _homeLat = lat;
    _homeLong = lng;
    //PATCH - end

    var shp = null;
    var point = new VELatLong(lat, lng);
    
    if (_drawCircles) 
    {
        DrawDistanceCircle(lat,lng,add,1);
        shp = DrawDistanceCircle(lat,lng,add,2);
    }
    else 
    {
        shp = new VEShape(VEShapeType.Pushpin, point);
        _map.AddShape(shp);
    }
    
    // Set the shape's title
    shp.SetTitle("Postal Code: " + postcode);
    var html = "<b>Address</b>: {0}<br/><b>Latitude</b>: {1}<br/><b>Longitude</b>: {2}";
    var desc = String.format(html, add, Math.round(lat * 100)/100, Math.round(lng * 100)/100);
    shp.SetDescription(desc);
    
   if(!_zoomLevelEventTriggered){
        _map.SetCenterAndZoom(point, 14);
        _zoomedView = true;
   }
    _zoomLevelEventTriggered = false;
    
}

function getGPSFromPostCode_failed(e, rc)
{
    alert("failed: " + e);
}

function DrawDistanceCircle(center_lat, center_lng, address, distance)
{
    /// center_lat
    /// center_lng
    var R = 6371; // earth's mean radius in km
    var lat = (center_lat * Math.PI) / 180; //rad
    var lon = (center_lng * Math.PI) / 180; //rad
    var d = parseFloat(distance) / R;  // d = angular distance covered on earth's surface

    myCirclePoints = new Array();

    for (x = 0; x <= 360; x++) 
    { 
	    var p2 = new VELatLong(0,0)            
	    brng = x * Math.PI / 180; //rad
	    p2.Latitude = Math.asin(Math.sin(lat)*Math.cos(d) + Math.cos(lat)*Math.sin(d)*Math.cos(brng));
	    p2.Longitude = ((lon + Math.atan2(Math.sin(brng)*Math.sin(d)*Math.cos(lat), Math.cos(d)-Math.sin(lat)*Math.sin(p2.Latitude))) * 180) / Math.PI;
	    p2.Latitude = (p2.Latitude * 180) / Math.PI;
	    myCirclePoints.push(p2);
    }

    // We now build the circle's Shape object
    var circleShape;
    circleShape = new VEShape(VEShapeType.Polygon, myCirclePoints);
    
    // We add the circle to the map
    _map.AddShape(circleShape);
    
    return circleShape;
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();