//** by coomsie **//


//debug me
var debug = false;
//var for search
var searchControl = null;

//vars for areas
var areas = new Array();
var gOverlays;
var ovs = [];
var clicktolerance = 15;
var querylevel = 17; //limits the query of bus stops at x level.
// ====== Array for decoding the failure codes in geo ======
var reasons = [];
var geo;

var UrlVars = getUrlVars();
var cookieAction;
var busstops = new Array();
var busstopstemp = new Array();
var autorefreshtag = 0;
var clockTimeoutID;

//bustop object
function busstop(tag, no, lat, lon, ordernum, road, routes)
{
    this.tag = tag;
    this.no = no;
    this.lat = lat;
    this.lon = lon;
    this.ordernum = ordernum;
    this.road = road;
    this.routes = routes;
}

areas['Northern Christchurch'] = "-43.297823082588195 , 172.63092041015625";
areas['West Christchurch'] = '-43.52241454298585 , 172.52225875854492';
areas['North Christchurch'] = "-43.46886761482923, 172.60602951049805";
areas['South Christchurch'] = "-43.566088579896906, 172.63555526733398";
areas['East Christchurch'] = "-43.53448716994501, 172.67967224121094";
areas['Central City'] = "-43.53137589928477 , 172.6365852355957";
areas['Ferry'] = "-43.61693949231988 , 172.7267074584961";
areas['Timaru'] = " -44.381600257540015 , 171.22793197631836";


var params = null;


var MaxETRows = 15;
//var BusStopTimesurl = "http://rtt.metroinfo.org.nz/RTT/Public/RoutePositionET.aspx?MaxETRows=" + MaxETRows + "&amp;PlatformTag=";
// bus time url and max rows
//bus schedules
var BusSchedulesurl = "http: //rtt.metroinfo.org.nz/rtt/public/Schedule.aspx?ProjectID=CHCMETRO";   ///&RouteNo=10&PlatformTag=1940";


//var proxy = "myproxy.aspx?MaxETRows=" + MaxETRows + "&PlatformTag=";
var proxy = "proxy.ashx?MaxETRows=" + MaxETRows + "&PlatformTag=";
var refreshrate = 5000;

var mapurl = "http://arcgis.ecan.govt.nz/ArcGIS/rest/services/Beta/Bus_Routes/MapServer";

var gmap = null;
var dynMapOv = null;
var mapext = null;

var minzoomlevel = 13;
var maxzoomlevel = 18;

var identifyOvs = [];

function initialize()
{
    ///   checkwindow();

    //check if cookies are enabled
    if (!cookiesON)
        $('#cookies').show("slow");

    // Find Parameters for Find operation ..
    params = new esri.arcgis.gmaps.FindParameters();
    params.layerIds = [0];
    params.searchFields = ["PlatformTag"];
    // Find Task Object
    findTask = new esri.arcgis.gmaps.FindTask(mapurl);

    checkMyBusStops();

    //Load Google Maps
    gmap = new google.maps.Map2($("#gmap")[0]);
    //gmap = new GMap2(document.getElementById("gmap"));
    var centerat = new google.maps.LatLng(-43.53137589928477, 172.6365852355957);

    // ====== Restricting the range of Zoom Levels =====
    // Get the list of map types
    var mt = gmap.getMapTypes();
    // Overwrite the getMinimumResolution() and getMaximumResolution() methods
    for (var i = 0; i < mt.length; i++)
    {
        mt[i].getMinimumResolution = function()
        {
            return minzoomlevel;
        };
        mt[i].getMaximumResolution = function()
        {
            return maxzoomlevel;
        };
    }

    gmap.addControl(new google.maps.LargeMapControl());
    gmap.addControl(new google.maps.MapTypeControl());
    gmap.setCenter(centerat, minzoomlevel);
    gmap.enableScrollWheelZoom();


    //add search control...
    var options = {
        searchFormHint: "Eg:Bus Exchange or Kilmore St",
        suppressZoomToBounds: false,
        suppressInitialResultSelection: true
    };
    var searchControl = new google.maps.LocalSearch(options);
    gmap.addControl(searchControl);
    searchControl.focus();



    //create mapextension to add identify results to map
    mapext = new esri.arcgis.gmaps.MapExtension(gmap);

    idtask = new esri.arcgis.gmaps.IdentifyTask(mapurl);



    // You can execute a task and listen for the complete event or use the callback to get the results
    GEvent.addListener(findTask, "complete", function()
    {
    });

    // Query Task
    qtask = new esri.arcgis.gmaps.QueryTask(mapurl + "/0");

    // You can execute a task and listen for the complete event or use the callback to get the results
    GEvent.addListener(qtask, "complete", function()
    {
        //console.debug("'query task complete' event fired!!!");
    });

    // Query
    query = new esri.arcgis.gmaps.Query();

    //create custom dynamic layer
    //esri.arcgis.gmaps.DynamicMapServiceLayer(url,esri.arcgis.gmaps.ImageParameters?,opacity?,callback?);
    var dynamicMap = new esri.arcgis.gmaps.DynamicMapServiceLayer(mapurl, null, '0.75', dynmapcallback);

    ///// ARCGIS CLICK STUFF
    GEvent.addListener(gmap, "click", function(overlay, point)
    {
        //   if (point != undefined)
        //       document.getElementById('controls').innerHTML = point.y + ', ' + point.x + '<br />' + gmap.getZoom();
        doIdentify(overlay, point);
    });

    GEvent.addListener(gmap, "moveend", function()
    {

        //dont do query if not zoomed in
        if (gmap.getZoom() < querylevel)
        {
            $("#busstopsonmapsection").hide("slow");
            return;
        }

        executeQuery();

    });

    ///listen for info window closing and set auto refresh to 0
    GEvent.addListener(gmap, "infowindowbeforeclose", function()
    {
        //get info tag to stop refresh
        clearTimeout(clockTimeoutID);
    });

    // remove bus loading gif
    $("#gmap").css("background", "");

    resizeMap();

//    $('#mysearchsection').show('slow');
//    $('#mysearchsection').draggable();

//    mylocalsearch();

}


function dynmapcallback(groundov)
{
    //Add groundoverlay to map using gmap.addOverlay()
    gmap.addOverlay(groundov);
    dynMapOv = groundov;

    //dont do query if not zoomed in
    if (gmap.getZoom() > querylevel)
    {
        $("#busstopsonmapsection").show("slow");
        $('#busstopsonmapsection').draggable('move');
        executeQuery();
    }


    //finsihed loading?
    endLoading();
}

// MY BUS STOP FIND STUFF
function executeFind(id, action)
{
    DebugLog('executeFind - ' + id + action , 'text');     //// debug
    
    cookieAction = action;
    //
    DebugLog('if id=="" ', 'text');     //// debug
    if (id == "") { return };
    
    DebugLog('set search text', 'text');     //// debug
    // set find parameters
    params.searchText = id;

    DebugLog('execute find task', 'text');     //// debug
    // execute find task
    findTask.execute(params, findCompleteCallback);

}



function findCompleteCallback(response)
{
    DebugLog('findCompleteCallback - no of:', 'text');     //// debug
    
    //if response is nothing
    if (response == null) return;

    // add the findresutls to google map without any style
    //gOverlays = mapext.addToMap(findResults);

    var findResults = response.findResults, findResult, geometry, attributes, geom, i, j, name, foundField;
    var table = "";
    var uniqueId = 0;
    listOfOverlays = [];
    var tag;


    for (i = 0; i < findResults.length; i++)
    { // process each result in the response
        findResult = findResults[i];
        geometry = findResult.feature.geometry;
        attributes = findResult.feature.attributes;
        name = findResult.layerName;
        foundField = findResult.foundFieldName;

        var road = "\'" + attributes["RoadName"] + "\'";
        tag = attributes["PlatformTag"];
        var routes = attributes["Routes"];

        //already exists?
        if (BusstopExists(tag) == true && cookieAction != "check") return;

        // add a row to the table of results
        table += "<div id='BS_" + tag + "' class='smallText'><a href='javascript:openBusStop(" + geometry[0].getLatLng().y + " , " + geometry[0].getLatLng().x + " , " + attributes["PlatformTag"] + " , " + attributes["PlatformNo"] + " , \"" + attributes["RoadName"] + "\" , \"" + routes + "\" ); '><img alt='bus icon' src='images/busIcon.png' />&nbsp;" + attributes["Name"] + "</a>&nbsp;-&nbsp;<a href='javascript:void(0);' onclick='javascript:removeCookie( " + attributes["PlatformTag"] + ");'><img class='closebtn' src='images/close.gif'  /></a></div>";
        $('#mybusstopssection').append(table);

        if (cookieAction != "check")
        {

            // doesnt exist so add to object
            busstops.push(new busstop(attributes["PlatformTag"], attributes["PlatformNo"], geometry[0].getLatLng().y, geometry[0].getLatLng().x, i, ("\'" + attributes["RoadName"] + "\'"), null));

            //set cookie
            DebugLog('set cookie', 'text');     //// debug
            setCookie('MetroBusStops', tag, 365);

        }

        //if start open my bus's if first one.
        if (cookieAction == "check" && tag == busstops[0].tag)
            openBusStop(geometry[0].getLatLng().y, geometry[0].getLatLng().x, attributes["PlatformTag"], attributes["PlatformNo"], attributes["RoadName"], routes);
    }
    // note that we are NOT using the MapExtension class here to add the FindResults


    //if results show
    $('#mybusstopssection').show("slow");
    $("#mybusstopssection").draggable();
    endLoading();
}


function createInfoWindow(LatLng, tag, no, road, routes)
{

    //start auto refresh of only the open window
    //autorefreshtag = tag;
    autorefresh(tag);

    var contentstreetview = "<div name='pano' id='pano' style='width:300px; height:300px;'></div>";
    var contentbustag = "<input id='clockTimeoutID' type='hidden' value='" + clockTimeoutID + "' />";

    var tabs = [];

    var myhtml = google.maps.DownloadUrl(proxy + tag, function(data)
    {

        //fill dom object so we can get only the bit we want.
        var newdiv = document.createElement('div');
        newdiv.innerHTML = data;

        var contentroutes = "<div>Stop No: " + no + "</div><div>Road: " + road + "</div><div>Routes: ";

        //create route html
        var routessaved = new Array();
        var routesdiv = "";
        var routesArray = routes.split('|');
        for (var i = 0; i < routesArray.length; i++)
        {
            var temp = routesArray[i].split(':');
            var exists = false;
            //check if exists
            for (var x = 0; x < routessaved.length; x++)
            {
                if (routessaved[x].split(':')[0] == routesArray[i].split(':')[0]) { exists = true; break };
            }
            if (exists == false)
            {
                routessaved.push(routesArray[i]);
                //routesdiv += "&nbsp;<a target='_blank' href='http://rtt.metroinfo.org.nz/rtt/public/Schedule.aspx?ID=" + temp[1] + "'>" + temp[0] + "</a>";
                routesdiv += "&nbsp;<a target='_blank' href='http://rtt.metroinfo.org.nz/rtt/public/Schedule.aspx?RouteNo=" + temp[0] + "'>" + temp[0] + "</a>";
                if (i + 1 != routesArray.length)
                    routesdiv += "&nbsp;|&nbsp;";
            }
        }
        routesdiv += "</div>";
        contentroutes += routesdiv;

        var contentbustimes = "<div id='bustimes'>" + newdiv.innerHTML + "</div>";
        var contentmybus = "<div id='addBtndiv'><a id='addMyBus' href='javascript:void(0);' onclick='javascript:btnadd(" + tag + ");'><img id='addMyBusImg' src='images/busIcon_add.png' /> add to 'my bus stops'</a></div>";
        var contentrefresh = "<div class='small' id='refreshtime'><i>(times refresh every 5 secs) - " + getTime() + "</i></div>";


        tabs.push(new GInfoWindowTab("Bus Times", contentroutes + contentbustag + contentmybus + contentbustimes + contentrefresh));
        tabs.push(new GInfoWindowTab("Street View", contentstreetview));
        var infoWindowOptionsTabs = { selectedTab: 0 };

        gmap.openInfoWindowTabsHtml(LatLng, tabs, infoWindowOptionsTabs);

    });                       //end of function(data)



    gmap.setCenter(LatLng, maxzoomlevel);

    endLoading();

    //start street view
    streetview(LatLng.y, LatLng.x);

    //start auto refresh
    //    autorefreshtag = tag;
    //    autorefresh(tag);

}


function doIdentify(overlay, point)
{
    DebugLog('doIdentify:' , 'text');     //// debug
   
    if (overlay)
    {
        return;
    }

    //clear old ones
    if (ovs[0] != undefined)
    {
        mapext.removeFromMap(ovs);
    }

    startLoading();

    var dim = gmap.getSize();
    var idparams = new esri.arcgis.gmaps.IdentifyParameters();
    idparams.geometry = point;
    idparams.tolerance = clicktolerance;
    idparams.bounds = gmap.getBounds();
    idparams.width = dim.width;
    idparams.height = dim.height;
    //idparams.layerIds = [0, 1, 6];
    idparams.layerIds = [0];
    idparams.layerOption = "all";
    idparams.wkid = 102113;

    idtask.execute(idparams, doIdentify_idcallback);
}

function doIdentify_idcallback(idresults)
{
    DebugLog('doIdentify_idcallback: no found - ' + idresults.identifyResults.length, 'text');     //// debug
    
    ///if no results from clicking & identity
    if (idresults.identifyResults[0] == undefined) { endLoading(); return; }
    var r = 0;
    //go through all the results.
    for (var x = 0; x < idresults.identifyResults.length; x++)
    {

        var geometry = idresults.identifyResults[x].feature.geometry[0];
        var attributes = idresults.identifyResults[x].feature.attributes;

        //only do the bus layers not routes for info windows
        if (idresults.identifyResults[x].layerId != 3)
        {
            //only do the first one
            if (x == 0)
                openBusStop(geometry.getLatLng().y, geometry.getLatLng().x, attributes["PlatformTag"], attributes["PlatformNo"], attributes["RoadName"], attributes["Routes"]);
        }
        else
        {
            //create highlighted area only for routes
            //hack to remove only the first route too!
            //            if (r == 0) {
            //                var overlayOptions = {
            //                    strokeColor: "#FF0000", strokeWeight: 3, strokeOpacity: 0.55,
            //                    fillColor: "#000066", fillOpacity: 0.4
            //                };
            //                var ov = mapext.addToMap(idresults.identifyResults[x], overlayOptions);
            //                ovs.push(ov);
            //                r = 1;
            //// removes the dynamic map aka routes stops etc.                gmap.removeOverlay(dynMapOv);
            //            }
        } //end if
    } //end for

    endLoading();
}

function checkwindow()
{
    var winW = 0, winH = 700;

    if (parseInt(navigator.appVersion) > 3)
    {
        try
        {            //if (navigator.appName == "Netscape")
            winW = window.innerWidth;
            winH = window.innerHeight;
        }
        catch (e) { };
        try
        {//if (navigator.appName.indexOf("Microsoft") != -1)
            winW = document.body.offsetWidth;
            winH = document.body.offsetHeight;
        }
        catch (e) { };
    }
    var h = winH;
    document.getElementById("gmap").style.height = h + 'px';
    // debug stuff
    //alert(winH);
}

function resizeMap()
{
    var height = document.getElementById("container").offsetHeight;
    var totalHeight = parseInt(height);
    document.getElementById("gmap").style.height = totalHeight + 'px';
    gmap.checkResize();
}

function streetview(y, x)
{

    try
    {
        var divid = document.getElementById("pano");
    }
    catch (e) { };

    //check to see if loaded
    if ((divid == null) || (typeof (divid) == "undefined"))
    {
        setTimeout("streetview('" + y + "', ' " + x + "')", 1000);
        return;
    }

    var gmylatlng = new google.maps.LatLng(y, x);
    panoramaOptions = { latlng: gmylatlng };
    panoClient = new GStreetviewClient();
    panoClient.getNearestPanorama(gmylatlng, showPanoData);
    myPano = new GStreetviewPanorama(document.getElementById("pano"));
    GEvent.addListener(myPano, "error", handleNoFlash);
}

function handleNoFlash(errorCode) {
    DebugLog('handleFlash error' + errorCode, 'text'); ////debug
    if (errorCode == 603)
    {
        var mydiv = document.getElementById('pano');
        mydiv.innerHTML = "Error: Flash doesn't appear to be supported by your browser";
        return;
    }
}

function showPanoData(panoData)
{
    if (panoData.code != 200)
    {
        ///    GLog.write('showPanoData: Server rejected with code: ' + panoData.code);
        //cope with infowindow closed
        try
        {
            mydiv.innerHTML = "Error: Can't find a street view on this spot? Try again.";
            return;
        }
        catch (e) { };
    }
    DebugLog('Viewer moved to' + panoData.location.latlng, 'text'); ////debug
    
    if (panoData.code = 200)
    myPano.setLocationAndPOV(panoData.location.latlng);
}

function openBusStop(y, x, tag, no, road, routes)
{

    //make sure the clos window event fires.
    gmap.closeInfoWindow();
    var point = new google.maps.LatLng(y, x);
    createInfoWindow(point, tag, no, road, routes);


}


//freshes the bus times info window
function refreshBustimes(id)
{

    //find bustimes div - replace data
    if ($("#bustimes") != null)
        try
    {
        $.get(proxy + id + "&unique=" + Math.random(), callbackofGET, "html");
    } ///end of try
    catch (e) { };

}

function callbackofGET(data, textStatus)
{

    DebugLog('callbackofGET', 'text'); //// debug
    DebugLog(data, 'html'); //// debug

    //update div
    $("#bustimes").html(data);
    //update time
    $('#refreshtime').html("<i>(times refresh every 5 secs) - " + getTime() + "</i>");
}


function downloadsucess(responseText, textStatus, XMLHttpRequest)
{
    //alert for error / debug
    this;
    return;
}

function btnadd(id)
{
    DebugLog('btnadd - ' + id, 'text');     //// debug

    executeFind(id, "set");

}

function checkMyBusStops()
{
    DebugLog('checkMyBusStops - ', 'text');     //// debug
    getCookie('MetroBusStops');
    //run code to get names & lat long etc ..

    for (var i = 0; i < busstops.length; i++)
    {
        executeFind(busstops[i].tag, "check");
    }



}


function autorefresh(tag)
{
    DebugLog('autorefresh - ' + tag, 'text');     //// debug
    //check if just about to open
    if (document.getElementById('clockTimeoutID') != null)
        refreshBustimes(tag);

    //        if (document.getElementById('clockTimeoutID') != null ) {
    //            document.getElementById('clockTimeoutID').value = clockTimeoutID;
    clockTimeoutID = setTimeout("autorefresh('" + tag + "')", refreshrate);
}

/// finds all the objects on the current map
function executeQuery()
{
    //dont do query if not zoomed in
    if (gmap.getZoom() < querylevel)
    {
        $('#busstopsonmapsection').hide("slow");
        return;
    }
    var bounds = gmap.getBounds();

    // clear map overlays and event listeners using MapExtension removeFromMap
    mapext.removeFromMap(gOverlays);

    // set query parameters
    query.queryGeometry = bounds;
    query.returnGeometry = true;
    query.outFields = "Name, PlatformTag  , RoadName , PlatformNo, Routes";

    // execute query task
    qtask.execute(query, false, mycallback);

}

function mycallback(response)
{
    // add the feature set to google map without any style
    //if response is nothing
    if (response == null) return;

    var findResults = response.features;
    var findResult, geometry, attributes, geom, i, j, foundField;
    listOfOverlays = [];
    var content = "";

    for (i = 0; i < findResults.length; i++)
    { // process each result in the response
        findResult = findResults[i];
        geometry = findResult.geometry;
        attributes = findResult.attributes;

        var tag = attributes["PlatformTag"];
        var no = attributes["PlatformNo"];
        var road = attributes["RoadName"];
        var name = attributes["Name"];
        var routes = attributes["Routes"];

        content += "<div class='smallText'><a href='javascript:openBusStop(\"" + geometry[0].getLatLng().y + "\" , \"" + geometry[0].getLatLng().x + "\" , \"" + tag + "\" , \"" + no + "\" , \"" + road + "\" , \"" + routes + "\" ); '><img alt='bus icon' src='images/busIcon.png' />&nbsp;" + name + "</a></div>";
    }

    try
    {
        $('#busstopsonmapdetails').html("");
        $('#busstopsonmapdetails').append(content);
        $('#busstopsonmapsection').show("slow");
        $('#busstopsonmapsection').draggable()
    } ///end of try
    catch (e) { };

}




///cookie stuff for j query
//$.cookie('the_cookie'); // get cookie
//$.cookie('the_cookie', 'the_value'); // set cookie
//$.cookie('the_cookie', 'the_value', { expires: 7 }); // set cookie with an expiration date seven days in the future
//$.cookie('the_cookie', '', { expires: -1 }); // delete cookie

function getCookie(c_name)
{

    var cookie = $.cookie(c_name);
    if (cookie != null)
    {
        //return array
        //get each bss (bus stop cookie)
        var bss = cookie.split(',');
        if (bss.length == 0) return;
        for (var i = 0; i < bss.length; i++)
        {
            //create new bus stop array with objects
            busstops[i] = new busstop(bss[i], null, null, null, null, null, null);
        }
    }
    return
}

function setCookie(c_name, value, expiredays)
{
    var values = "";  //create new bus stop array with objects
    for (var i = 0; i < busstops.length; i++)
    {
        if (busstops[i].tag != '')
            values += busstops[i].tag + ",";
    }

    $.cookie(c_name, value, { expires: expiredays });

    if (values != null)
    //return number of mybusstops
        return values.length;
    return 0;
}

function removeCookie(tag)
{

    //remove html div
    $('#BS_' + tag).remove();

    //remove object
    var i = BusstopExistsNo(tag);
    //remove the array entry
    busstops = busstops.slice(0, [i]).concat(busstops.slice(i + 1));

    // re-do cookie
    setCookie('MetroBusStops', tag, 0);
    if (busstops.length == 0 || busstops[0].tag == "")
        $('#mybusstopssection').hide("slow");

}


/// helper function to return if bus stop already exists
function BusstopExists(tag)
{
    for (var i = 0; i < busstops.length; i++)
    {
        if (busstops[i].tag == tag) return true;
    }
    return false;
}
/// helper function to return if bus stop already exists
function BusstopExistsNo(tag)
{
    for (var i = 0; i < busstops.length; i++)
    {
        if (busstops[i].tag == tag) return i;
    }
    return false;
}

function getTime()
{
    var currentTime = new Date();
    var hours = currentTime.getHours();
    var minutes = currentTime.getMinutes();
    var secs = currentTime.getSeconds();

    if (minutes < 10)
        minutes = "0" + minutes;
    if (secs < 10)
        secs = "0" + secs;

    return hours.toString() + ":" + minutes.toString() + ":" + secs;
}

//// LOGGGING DEBUGGING STUFF

function DebugLog(data, type)
{
    //check debug var
    if (debug == false) return;

    if (type == 'html')
        google.maps.Log.writeHtml(data);

    if (type == 'url')
        google.maps.Log.writeUrl(data);

    if (type == 'text')
        google.maps.Log.write(data, 'red');
}

///not currently used
///*******************************************

// gets the html variables passed in - returns array
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

///get all vars of type var
function GetMyVars(urlvar)
{
    // no variable
    if (UrlVars[urlvar] == null)
        return '';
    return UrlVars[urlvar];
}

function tidyUpUrlSpaces(input)
{
    return input.replace(/\%20/, " ");
}

function runurllocations()
{
    //check to see if ready?
    if (!geo)
    {
        setTimeout("runurllocations()", 1000);
        return;
    }

    //check my bus stops
    checkMyBusStops();

    var tag = "";
    try
    {
        tag = tidyUpUrlSpaces(trim(GetMyVars('tag')));
    }
    catch (e) { };

    if (tag != "")
    {
        executeFind(tag, "set");
    }
}


function mylocalsearch() {
    // create a search control 
    var newsearchControl = new google.search.SearchControl();
    var ls = new google.search.LocalSearch();
    ls.setCenterPoint("Christchurch, New Zealand");

    var options = new google.search.SearcherOptions();
    options.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
    newsearchControl.addSearcher(ls, options);
    // tell the searcher to draw itself and tell it where to attach

    // establish a keep callback 
  //  searchControl.setOnKeepCallback(this);

    var searchdiv = $('#localsearchresults');
    newsearchControl.draw(searchdiv);

    // execute an inital search 
    newsearchControl.execute("Bus Exchange");

}