﻿
function initialize2() {
    initMap();

    //get URL param value
    assetTypeId = getURLParam("param");
        
    //get list of asset types
    listAsset = getData("asset", "");

    //Populate By Asset select box
    var match = selAsset(listAsset);

    //Display All Assets by Type if parameter passed is valid
    if (assetTypeId != "" && match) { allByType($('#selAsset').val(), 'All'); } 

    //Get Admin Message
    adminMessage = getData("adminMessage", "");
    selMessage(adminMessage);
        
}

function initMap() {
    if (GBrowserIsCompatible()) {
        gmap = new GMap2(document.getElementById("gmapview"));
        
        //gmap.setCenter(new GLatLng(43.904819, -79.427032), 11);
        gmap.setCenter(new GLatLng(43.905000, -79.430000), 11);
        
        //Google Map view is Terrain...Default is Map view if commented
        //gmap.setMapType(G_PHYSICAL_MAP);
        gmap.enableScrollWheelZoom();

        var customUI = gmap.getDefaultUI();
        //customUI.controls.scalecontrol = false;
        customUI.maptypes.hybrid = false;
        customUI.maptypes.satellite = false;
        //if setMapType(G_PHYSICAL_MAP) is commented, set normal to true
        //if not commented, set to false
        customUI.maptypes.normal = true;
        customUI.maptypes.physical = false;
        customUI.controls.menumaptypecontrol = false;
        gmap.setUI(customUI);

        //Include condition if browser isn't Opera or IE 6.0:
        if ((navigator.appName != "Opera")&&(! navigator.appVersion.match("MSIE 6.0"))) {
            //Add polygon boundary to map
            addRHOverlay();
        }        
    }
}

function addRHOverlay() {

    //Define array of points for closed polygon of Richmond Hill
    var RHpolygon = new GPolygon([
        new GLatLng(43.9575084, -79.48571908),
        new GLatLng(43.97787439, -79.39228582),
        new GLatLng(43.94901268, -79.39206558),
        new GLatLng(43.94139792, -79.38927544),
        new GLatLng(43.92950526, -79.39009565),       
        new GLatLng(43.84734521, -79.37087409),
        new GLatLng(43.83851064, -79.40948988),
        new GLatLng(43.83757413, -79.4199806),
        new GLatLng(43.8337312, -79.42905217),
        new GLatLng(43.82758022, -79.45412806)
    ], "#CCCCCC", 0, 0.5, "#CCCCCC", 0.4);
    gmap.addOverlay(RHpolygon);

    //Listener event to remove overlay if zoomed in too far
    GEvent.addListener(gmap, "zoomend", function() {
        var currentZoom = gmap.getZoom();
        if (currentZoom > 13 && RHpolygon != null)
            gmap.removeOverlay(RHpolygon);

        if (currentZoom <= 13 && RHpolygon != null)
            gmap.addOverlay(RHpolygon);
    });
}

//Get data from service
function getData(service, param) {
    var list = [];
    $.ajax({
        type: "POST",
        url: "./Controller/SearchFor_Service.ashx?service=" + service + "&param=" + param,
        data: {},
        success: function(response) {
            list = (typeof response) == 'string' ? eval('(' + response + ')') : response;
        },
        failure: function(response) {
            list = null;
        },
        async: false
    });
    return list;
}

function selMessage(adminMessage) {
    
    //If there is no message, hide button
    if (adminMessage[0].Message == "") {
        $("#adminnotice").html('');
    }
    //Otherwise, display button and message to user
    else {
        var messageButton = "<input type=\"button\" id=\"btnMessage\" value=\"" + adminMessage[0].BtnValue + "\" onclick=\"alert(adminMessage[0].Message)\" />";
        //$("#adminnotice").html(messageButton);
        $("#adminnotice").html('');
        alert(adminMessage[0].Message);
    }
}

//Called to populate type, attribute and name, based on param passed to Search For.aspx 
function selAsset(assetList) {

    $("#selAsset").html('');
    var options = "";
    var selectedval = "";
    var match = false;

    options += "<option id=\"selBlank1\" value=\"\" name=\"\">-Select Facility Type-</option>";
    for (var i = 0; i < assetList.length; i++) {

        //Sets selected option to param type passed to main page
        if (assetTypeId.toUpperCase() == assetList[i].ID) {
            selectedval = assetList[i].Value;
            match = true;
            options += "<option id=\"" + assetList[i].ID + " value=\"" + assetList[i].Value + " name=\"" + assetList[i].Colour + "\" selected=\"selected\">" + assetList[i].Value + "</option>";
        }
        else {
            options += "<option id=\"" + assetList[i].ID + " value=\"" + assetList[i].Value + " name=\"" + assetList[i].Colour + "\">" + assetList[i].Value + "</option>";
        }
    }

    $("#selAsset").html(options);

    //Only populate attributes if seloptval has a value from the data list
    if (selectedval != "") {
        //Passes value based on passed code
        popAttributes(selectedval);

        assetIcon = $('#selAsset').val();
        iconColour = $('#selAsset option:selected').attr('name');
        //assetResult = assetIcon.toUpperCase();
        changeTitle();
    }
    return match;
}



//Call to populate attribute and name lists
function popAttributes(asset) {
    
    listAttribute = getData("attribute", asset);
    selAttribute(listAttribute);
  
    listName = getData("name", asset);
    selName(listName);    
}

//Populate list items, based on attributes returned
function selAttribute(attributeList) {
    
    //Display ByAttribute section
    $("#frmAttribute").html('');
    var fillForm = "<div class=\"searchTitles\">By Amenity</div> <div class=\"smallbreak\"></div> <div id=\"selAttDiv\"><ul id=\"selAttribute\"></ul></div>";
    $("#frmAttribute").html(fillForm);
    
    //Create list items
    $("#selAttribute").html(''); 
    //This option will select all facilities of 1 type, whether or not they have attributes   
    var options = "<li id=\"attAll\" onclick=\"allByType('" + $("#selAsset").val() + "','All');\"><a href=\"#\" >All</a></li>";
    
    //Only generate list if amenties are present
    //if (attributeList[0].Value != "None") {
    if (attributeList[0].Value != "_") {
        for (var i = 0; i < attributeList.length; i++) {
            options += "<li id=\"" + attributeList[i].Value + "\" onclick=\"byAttribute('" + $("#selAsset").val() + "','" + attributeList[i].Value + "');\"><a href=\"#\" >" + attributeList[i].Value + "</a></li>";
        }
    }
    
    $("#selAttribute").html(options);    
}

//Call to get data by attribute
function byAttribute(type, attribute) {

    var params = type + "&param2=" + attribute;
    loadAsset("byAttribute", params);
    
    //Call to change SearchResult Title
    displaySearchResult(attribute);

    //Clear focus in scbox1 if something selected from Amenity list
    removeSCboxFocus();

}

//Call to get all facilities of 1 type
function allByType(type, attribute) {

    var param = type;
    loadAsset("allByType", param);

    //Call to change SearchResult Title
    displaySearchResult(attribute);

    //Clear focus in scbox1 if something selected from Amenity list
    removeSCboxFocus();  

}

//Set up SearchResult title based on Attribute selected
function displaySearchResult(attribute) {

    var sResult = "BY: " + attribute.toUpperCase();
    
    //Make Attribute the SearchResult title
    $("#searchresult").html(sResult);

}

//remove focus from scbox1
function removeSCboxFocus() {
    //Resets value
    $("[name=selName_type]").val("");
    
    //Resets text in input box
    $("[name=selName_class]").val("-Type or Select Name-");    
}

//Populate combo box options, based on names returned
function selName(nameList) {

    //Display ByName section
    $("#ByName").html('');
    var fillForm = "<div class=\"searchTitles\">By Name</div> <div class=\"smallbreak\"></div> <div id=\"scbox1\"></div> <div id=\"scbox2\"></div>";
    $("#ByName").html(fillForm);
    
    var title = "";
    
    //HTML removed from box1 div to repopulate combobox
    $("#scbox1").html('');

    //Create drop down box options
    var select = "<select id=\"selName\" name=\"selName\">";    
    for (var i = 0; i < nameList.length; i++) {
        title = convertToTitle(nameList[i]);
        select += "<option id=\"" + i + " value=\"" + title + "\">" + title + "</option>";
        
    }
    select += "<option id=\"SCblank\" value=\"\" selected=\"selected\">-Type or Select Name-</option>";
    select += "</select>";
    
    //Create drop down box
    $("#scbox1").html(select);
    
    //Call to create combobox from drop down box
    createSC();
        
    //Create Search Name button
    $("#scbox2").html('');
    var buttonName = "<input type=\"button\" id=\"btnName\" onmouseover=\"changeBtnOver()\" onmouseout=\"changeBtnOut()\" onclick=\"validateName()\" value=\"Search Name\"/>";
    $("#scbox2").html(buttonName);

}

//Create Name combox box from select box
function createSC() {
    $("#selName").sexyCombo({
        dropUp: true,
        emptyText: "-Type or Select Name-",
        suffix: "_class",
        hiddenSuffix: "_type",
        skin: "custom"
    });
    
    //Make every odd list item a different colour
    $('div.custom li:nth-child(odd)').css("background-color", "#E2DDC2");
}

//Change the colour of Name and Go buttons on hover
function changeBtnOver() {
    //$("#btnName").css("background-color", "#D9E7E1");
    $("#btnName").css("background-color", "#F1EFD1");
    $("#btnGo").css("background-color", "#CCCCCC");
}

//Change the colour of Name and Go buttons on mouseout
function changeBtnOut() {
    //$("#btnName").css("background-color", "#C5DAD1");
    $("#btnName").css("background-color", "#DDDBBB");
    $("#btnGo").css("background-color", "#848484");
}

//Call to validate name entered in Name combox box before sending query
function validateName() {
    var params = "";
    if ($("[name=selName_type]").val() == "") {
        //If no matches, alert
        alert("Name is invalid. Please select a valid name from the list provided.");
    }
    else {
        params = $("[name=selName_type]").val().toUpperCase() + "&param2=" + assetIcon;
        loadAsset("byAssetName", params);

        //Call to change SearchResult Title
        displaySearchResult("NAME");
    }
    
}

//Get the URL parameter value passed to main page
function getURLParam(param) {
    
    var strReturn = "";
    var strHref = document.location.href;
    if (strHref.indexOf("?") > -1) {
        var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
        var aQueryString = strQueryString.split("&");
        for (var iParam = 0; iParam < aQueryString.length; iParam++) {
            if (aQueryString[iParam].indexOf(param + "=") > -1) {
                var aParam = aQueryString[iParam].split("=");
                strReturn = aParam[1];
                break;
            }
        }
    }
    return strReturn;
}

//Converts name to "first letter capitalized" format
//Taken from http://lawrence.ecorp.net/inet/samples/regexp-format.php
//Date accessed: 2010-04-26
function convertToTitle(name) {
    return name.toLowerCase().replace(/\b[a-z]/g, cnvrt);
    function cnvrt() {
        return arguments[0].toUpperCase();
    }
}

//No longer considers if the last character in asset type has plural exceptions
function changeTitle() {

    /*$("#searchasset").html('');

    var title = "";

    switch (assetIcon.charAt(assetIcon.length - 1)) {
    case 'y':
    switch(assetIcon.charAt(assetIcon.length - 2)) {
    case 'a': case 'e': case 'i': case 'o': case 'u':
    title = " " + assetIcon + "s";
    break;
    default:    
    title = " " + assetIcon.replace('y', "ies");
    break;
    }
    break;
    case 'o':
    title = " " + assetIcon + "es";
    break;
    case 's':
    title = " " + assetIcon;
    break;
    default:
    title = " " + assetIcon + "s";
    break;
    }

    if (assetIcon.toUpperCase().match(" OF ")) { title = " " + assetIcon; }
    
    $("#searchasset").html(title);*/
    $("#searchasset").html(assetIcon);

}


