﻿//browser detection
var strUserAgent = navigator.userAgent.toLowerCase(); 
var isIE = strUserAgent.indexOf("msie") > -1; 
var isNS6 = strUserAgent.indexOf("netscape6") > -1; 
var isNS4 = !isIE && !isNS6  && parseFloat(navigator.appVersion) < 5; 

// Manage window.onload scripts
var onloadScripts = new Array();

function onloadProcess()
{
   for(var i = 0;i < onloadScripts.length;i++) {
        eval(onloadScripts[i]);
    }
}

function onloadAdd(func){
   onloadScripts[onloadScripts.length] = func;
}

// Add onload
window.onload = onloadProcess;

/*
    Tools
*/
function showtools(o) {
    // Show the tools container
    o = o.nextSibling;
    while (o.tagName != "UL") {
        o = o.nextSibling;
    }
    o.className = "";
}

var toolsTimeout, toolsobj;
function hidetools(o, forced) {
    if (forced == 'true') {
        // Forcing closed so close the tools container now and ensure timeout is null (in ie the tools container stays open when we open a new tab)
        o = o.firstChild.nextSibling;
        while (o.tagName != "UL") {
            o = o.nextSibling;
        }
        o.className = "hidden";
        toolsTimeout = undefined;
    }
    else {
        // Set a timeout to close if the container is not already closed
        if (toolsTimeout == undefined && o.firstChild.nextSibling.className != "hidden") {
            toolsobj = o;
            toolsTimeout = window.setTimeout(function(){
                o = o.firstChild.nextSibling;
                while (o.tagName != "UL") {
                    o = o.nextSibling;
                }
                o.className = "hidden";
                toolsTimeout = undefined;
            }, 500);
        }
    }
}

function keeptools(o) {
    // Keep the tools container open
    if (toolsTimeout != undefined && o == toolsobj) {
        window.clearTimeout(toolsTimeout);
        toolsTimeout = undefined;
    }
}

// Diable form items
function disableform(o) {

    var inputs = o.getElementsByTagName("INPUT");
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].readOnly = true;
        inputs[i].disabled = true;
    }
    var texts = o.getElementsByTagName("TEXTAREA");
    for (var j = 0; j < texts.length; j++) {
        texts[j].readOnly = true;
        texts[j].disabled = true;
    }
    var selects = o.getElementsByTagName("SELECT");
    for (var k = 0; k < selects.length; k++) {
        selects[k].readOnly = true;
        selects[k].disabled = true;
    }
}
// Enable form items
function enableform(o) {

    var inputs = o.getElementsByTagName("INPUT");
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].readOnly = false;
        inputs[i].disabled = false;
    }
    var texts = o.getElementsByTagName("TEXTAREA");
    for (var j = 0; j < texts.length; j++) {
        texts[j].readOnly = false;
        texts[j].disabled = false;
    }
    var selects = o.getElementsByTagName("SELECT");
    for (var k = 0; k < selects.length; k++) {
        selects[k].readOnly = false;
        selects[k].disabled = false;
    }
}

// Sign out
function signout() {
    PageMethods.User_Signout(signoutsuccess, ajaxfailure);
}

function signoutsuccess(value, ctx, methodName) {
    window.location.href = "/sign-in.aspx?so=True";
}

/*
    Cookie scripts
*/
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

// Paging
function paging(cpage, clist) {
    eval(clist + "(" + cpage + ")");
}

/* Key Press */
function keypressmanager(func, e) {

    var iKeyCode, strKey;
    
    if (!e) var e = window.event;

    if (isIE) {
        iKeyCode = e.keyCode;
    }
    else {
        iKeyCode = e.which;
    }

    if (iKeyCode == 13) {
        eval(func);
        return false;
    }
    
    return true;

}

/*
    AJAX
*/

function ajaxfailure(ex, ctx, methodName) { 
    if (ex.get_message() == "Session Timeout" || ex.get_message() == "Authentication failed.") {
        window.location.href = "/default.aspx?to=true";
        return false;
    }
    // If this is a server method failed message do not alert the user. Occurs in FF when changing pages before data loads
    //if (!(ex.get_message().startswith("The server method '") && ex.get_message().endswith("' failed."))) {
        alert(ex.get_message()); 
    //}
    // get_stackTrace(), get_message(), 
    // get_statusCode(), get_timedOut() 

    // show lists and tools and hide add form
    /*
    switch (methodName) {
        case "Signin_User":
            enableform(document.getElementById("signinform"));
    }
    */
    // Hide any passed loader animations
    if (ctx) {
        if (ctx.greyoutcontent == "true") {
            greyoutContent(false);
        }
        if (ctx.greyout) {
            greyOut(false,ctx.greyout);
        }
        if (ctx.divid) {
            enableform(document.getElementById(ctx.divid));
        }
        if (ctx.animid) {
            document.getElementById(ctx.animid).className = "hidden";
        }
    }
} 

// Grey out page
function greyoutContent(vis) {

  var cdark = document.getElementById('greyoutcontent');
  var ldark = document.getElementById('greyoutlinks');

  if (vis) {
    //set the shader to cover the entire page and make it visible.
    cdark.style.opacity = 0.7;                      
    cdark.style.MozOpacity = 0.7;                   
    cdark.style.filter = 'alpha(opacity=' + 70 + ')'; 
    cdark.className = 'greyout';		
    		 
    ldark.style.opacity = 0.7;                      
    ldark.style.MozOpacity = 0.7;                   
    ldark.style.filter = 'alpha(opacity=' + 70 + ')'; 
    ldark.className = 'greyout';		
  } else {
     cdark.className = 'hidden';
     ldark.className = 'hidden';
  }
}

function greyoutScreen(vis) {

  var cdark = document.getElementById('greyoutscreen');

  if (vis) {
    //set the shader to cover the entire page and make it visible.
    cdark.style.opacity = 0.7;                      
    cdark.style.MozOpacity = 0.7;                   
    cdark.style.filter = 'alpha(opacity=' + 70 + ')'; 
    cdark.className = 'greyout';		
  } else {
     cdark.className = 'hidden';
  }
}

function greyOut(vis, divid) {

    if (!divid) {
        divid = "greyout";
    }

    var cdark = document.getElementById(divid);

    if (vis) {
        //set the shader to cover the entire page and make it visible.
        cdark.style.opacity = 0.7;                      
        cdark.style.MozOpacity = 0.7;                   
        cdark.style.filter = 'alpha(opacity=' + 70 + ')'; 
        cdark.className = 'greyout';		
    } else {
        cdark.className = 'hidden';
    }
}

// Positioning
// get the object position
function getPosition (o, pid)
{
    // Get the passed object
    var cobj = o;
    
    // Find the left position
	var curleft = 0;
	if (o.offsetParent)
	{
		while (o.offsetParent && o.id != pid)
		{
			curleft += o.offsetLeft;
			o = o.offsetParent;
		}
	}
	else if (o.x) {
		curleft += o.x;
    }

    // reset the object to the passed object
    o = cobj;
    
    // Find the top position
	var curtop = 0;
	if (o.offsetParent)
	{
		while (o.offsetParent && o.id != pid)
		{
			curtop += o.offsetTop
			o = o.offsetParent;
		}
	}
	else if (o.y) {
		curtop += o.y;
	}

    // return the position
	return {x:curleft, y:curtop}
}

/*
    Form scripts
*/
// Submit form keypress
function submitform(objEvent, btnid)
{

    var iKeyCode, strKey;

    if (isIE) {
        iKeyCode = objEvent.keyCode;
    }
    else {
        iKeyCode = objEvent.which; 
    }

    if (iKeyCode == 13) {
        document.getElementById(btnid).click();
        return false;
    }
    
    return true;

}

// Ends With
if (!String.prototype.endswith) {
  String.prototype.endswith = function(suffix) {
    var startPos = this.length - suffix.length;
    if (startPos < 0) {
      return false;
    }
    return (this.lastIndexOf(suffix, startPos) == startPos);
  };
}
// Starts With
if (!String.prototype.startswith) {
  String.prototype.startswith = function(prefix) {
    return (this.indexOf(prefix) == 0);
  };
}

// Trim
if (!String.prototype.trim) {
    String.prototype.trim = function () {
        return this.replace(/^\s*/, "").replace(/\s*$/, "");
    };
}
if (!String.prototype.trimend) {
    String.prototype.trimend = function (suffix) {
        if (this.endswith(suffix)) {
            return this.substring(0, this.length - 1);
        }
        else {
            return this;
        }
    };
}

/*
    Google
*/

var map, geocoder;
var dunit = 'km';
function showAddress(alat, along, aname, mapname, enableDrag, du) {
    dunit = du;
    if (GBrowserIsCompatible()) {
        geocoder = new GClientGeocoder();
        map = new GMap2(document.getElementById(mapname));
        //Get address        
        point = new GLatLng(alat, along);
        map = new GMap2(document.getElementById(mapname));
        map.setCenter(point, 15);
        //map.setUIToDefault();
        
        var marker = new GMarker(point, {draggable: enableDrag});
        map.addOverlay(marker);
        marker.openInfoWindowHtml("<span>" + aname + "</span>", {maxWidth:200});
        map.setCenter(point);

        // Enable Dragging if necessary
        if (enableDrag) {
            GEvent.addListener(marker, "dragstart", function() {
                map.closeInfoWindow();
            });

            if (enableDrag) {
                GEvent.addListener(marker, "dragend", function(dpoint) {
                    geocoder.getLocations(dpoint, function(response) {
                        showDragAddress(response, true, dunit);
                    })
                });
                // set the coords
                document.getElementById("hdn" + map.getContainer().getAttribute("dtype") + "latitude" + map.getContainer().getAttribute("itemid")).value = alat;
                document.getElementById("hdn" + map.getContainer().getAttribute("dtype") + "longitude" + map.getContainer().getAttribute("itemid")).value = along;
                // get the distance
                if (!map.getContainer().getAttribute("nodistance")) {
                    getJDistance(map.getContainer().getAttribute("dtype"), map.getContainer().getAttribute("itemid"), alat + ", " + along, map.getContainer().getAttribute("fromloc"));
                }
            }
            else {
                GEvent.addListener(marker, "dragend", function(dpoint) {
                    geocoder.getLocations(dpoint, function(response) {
                        showDragAddress(response, false, dunit);
                    })
                });
            }

        }

    }

}

function showMultiAddress(origin, destination, mapname, enableDrag, du) {
    dunit = du;
    if (GBrowserIsCompatible()) {
        geocoder = new GClientGeocoder();
        map = new GMap2(document.getElementById(mapname));
        //Get address        
        opoint = new GLatLng(origin.lat, origin.lng);
        dpoint = new GLatLng(destination.lat, destination.lng);
        //map.setCenter(opoint, 15);
        //map.setUIToDefault();

        var bounds = new GLatLngBounds();
        bounds.extend(opoint)
        bounds.extend(dpoint)

        map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

        var omarker = new GMarker(opoint, { draggable: enableDrag });
        map.addOverlay(omarker);
        //omarker.openInfoWindowHtml("<span>" + origin.title + "</span>", { maxWidth: 200 });
        //map.setCenter(dpoint, 12);

        var dmarker = new GMarker(dpoint, { draggable: enableDrag });
        map.addOverlay(dmarker);
        //dmarker.openInfoWindowHtml("<span>" + destination.title + "</span>", { maxWidth: 200 });

        // set the coords
        document.getElementById("hdn" + map.getContainer().getAttribute("dtype") + "latitude" + map.getContainer().getAttribute("itemid")).value = origin.lat;
        document.getElementById("hdn" + map.getContainer().getAttribute("dtype") + "longitude" + map.getContainer().getAttribute("itemid")).value = origin.lng;
        document.getElementById("hdn" + map.getContainer().getAttribute("dtype") + "destinationlatitude" + map.getContainer().getAttribute("itemid")).value = destination.lat;
        document.getElementById("hdn" + map.getContainer().getAttribute("dtype") + "destinationlongitude" + map.getContainer().getAttribute("itemid")).value = destination.lng;
        // get the distance
        if (!map.getContainer().getAttribute("nodistance")) {
            getJDistance(map.getContainer().getAttribute("dtype"), map.getContainer().getAttribute("itemid"), origin.lat + ", " + origin.lng, destination.lat + ", " + destination.lng);
        }

    }

}

function showDragAddress(response, enableDrag) {
    map.clearOverlays();
    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 marker = new GMarker(point, {draggable: enableDrag});

        if (enableDrag) {
            GEvent.addListener(marker, "dragstart", function() {
                map.closeInfoWindow();
            });

            GEvent.addListener(marker, "dragend", function(dpoint) {
                geocoder.getLocations(dpoint, function(response) {
                    showDragAddress(response, true, dunit);
                })
            });

            // set the coords
            document.getElementById("hdn" + map.getContainer().getAttribute("dtype") + "latitude" + map.getContainer().getAttribute("itemid")).value = place.Point.coordinates[1];
            document.getElementById("hdn" + map.getContainer().getAttribute("dtype") + "longitude" + map.getContainer().getAttribute("itemid")).value = place.Point.coordinates[0];
            // get the distance
            if (!map.getContainer().getAttribute("nodistance")) {
                getJDistance(map.getContainer().getAttribute("dtype"), map.getContainer().getAttribute("itemid"), place.Point.coordinates[1] + ", " + place.Point.coordinates[0], map.getContainer().getAttribute("fromloc"));
            }

        }

        map.addOverlay(marker);
        marker.openInfoWindowHtml("<span>" + place.address + "</span>", {maxWidth:200});
        map.setCenter(point);
    }
}

var gdir, dirdiv;
var disid;

function getJDistance(dtype, itemid, toLoc, fromLoc) {
    disid = "txt" + dtype + "distance" + itemid;
    dirdiv = document.createElement("DIV");
    gdir = new GDirections(dirdiv);
    GEvent.addListener(gdir, "load", onGDirectionsLoad);
    gdir.load("from: " + fromLoc + " to: " + toLoc,
                { "locale": "en_GB" });

}

function onGDirectionsLoad() {
    var distObj = gdir.getDistance()
    if (distObj) {
        if (dunit == "m") {
            document.getElementById(disid).value = Math.round(distObj.meters / 16.09344) / 100;
        }
        else {
            document.getElementById(disid).value = Math.round(distObj.meters / 10) / 100;
        }
    }
}

function expandcollapse(o) {
    // Get container div
    var cdiv = o.parentNode;
    
    while (cdiv.tagName != "DIV") {
        cdiv = cdiv.parentNode;
    }
    // Record the original height
    var oHeight = cdiv.offsetHeight;
    if (!o.getAttribute("oheight")) {
        o.setAttribute("oheight", oHeight.toString());
    }
    
    if (o.getAttribute("src").indexOf("arrow-up") > -1) {
        cdiv.style.height = (oHeight - 65) + "px";
    }
    else {
        cdiv.className = cdiv.className.replace(" collapsed", "");
        cdiv.style.height = (oHeight + 65) + "px";
    }

    window.setTimeout(function () { easeinout(cdiv, o); }, 3);

}


function easeinout(cdiv, o) {
    // Resize the divs
    if (o.getAttribute("src").indexOf("arrow-up") > -1) {
        // Collapse
        if (parseInt(cdiv.style.height.replace("px", "")) > 65) {
            if (parseInt(cdiv.style.height.replace("px", "")) - 65 > 65) {
                cdiv.style.height = (parseInt(cdiv.style.height.replace("px", "")) - 65) + "px";
            }
            else {
                cdiv.style.height = "65px";
            }
            window.setTimeout(function () { easeinout(cdiv, o); }, 3);
        }
        else {
            cdiv.className = cdiv.className + " collapsed";
            o.setAttribute("src", o.getAttribute("src").replace("-up", "-down"));
        }
    }
    else {
        // Collapse
        if (parseInt(cdiv.style.height.replace("px", "")) < o.getAttribute("oheight")) {
            if (parseInt(cdiv.style.height.replace("px", "")) + 65 < o.getAttribute("oheight")) {
                cdiv.style.height = (parseInt(cdiv.style.height.replace("px", "")) + 65) + "px";
            }
            else {
                cdiv.style.height = o.getAttribute("oheight") + "px";
            }
            window.setTimeout(function () { easeinout(cdiv, o); }, 3);
        }
        else {
            cdiv.style.height = "auto";
            o.setAttribute("src", o.getAttribute("src").replace("-down", "-up"));
        }
    }
}

function toggleprintablechart(o, cid) {
    /*/ Get parent div
    var pdiv;
    pdiv = o.parentNode;
    while (pdiv.tagName != "DIV") {
        pdiv = pdiv.parentNode;
    }
    if (o.innerHTML == "Printable version") {
        var ohtml = pdiv.innerHTML//.replace(/chartWidth=925/g, "chartWidth=600").replace(/chartHeight=600/g, "chartHeight=400").replace(/width="925"/g,'width="600"').replace(/height="600"/g,'height="400"');
        pdiv.innerHTML = ohtml//.replace("Printable version", "Full version");
    }
    else {
        var ohtml = pdiv.innerHTML.replace(/chartWidth=600/g, "chartWidth=925").replace(/chartHeight=400/g, "chartHeight=600").replace(/width="600"/g,'width="925"').replace(/height="400"/g,'height="600"');
        pdiv.innerHTML = ohtml.replace("Full version", "Printable version");
    }
    */
    if (o.innerHTML == "Printable version") {
       document.getElementById(cid).className = "hidden";
       document.getElementById(cid.replace("full", "printable")).className = "";
       o.innerHTML = "Full version";
    }
    else {
       document.getElementById(cid).className = "";
       document.getElementById(cid.replace("full", "printable")).className = "hidden";
       o.innerHTML = "Printable version";
    }

}

function printreport(o) {
    while (o.className != "report") {
        o = o.parentNode;
    }
    var links = o.getElementsByTagName("A");

    for (var i = 0; i < links.length; i++) {
        if (links[i].innerHTML == "Printable version") {
            var fireOnThis = links[i];
            if (document.createEvent) {
                var evObj = document.createEvent('MouseEvents');
                evObj.initEvent('click', true, false);
                fireOnThis.dispatchEvent(evObj);
            } else if (document.createEventObject) {
                fireOnThis.fireEvent('onclick');
            }
        }
    }
}

/*
    Auto Suggestion
*/
function suggestitems(t, o, i) {
    var ctx = { o: o };
    PageMethods.Suggest_Items(t, o.value, i, suggestitemssuccess, suggestitemsfailure, ctx);
}

function suggestitemssuccess(value, ctx, methodName) {

    // remove current options
    if (ctx.o.parentNode.getElementsByTagName("UL").length > 0) {
        ctx.o.parentNode.removeChild(ctx.o.parentNode.getElementsByTagName("UL")[0]);
    }

    var self = this;
    this.suggestitemselect = function (e) {
        // get the src object
        var o;
        var ie_var = "srcElement";
        var moz_var = "target";
        // target for Moz, et al. - srcElement for IE 
        e[moz_var] ? o = e[moz_var] : o = e[ie_var];

        // Add value
        ctx.o.setAttribute("text", o.getAttribute("text"));
        ctx.o.value = o.innerHTML.split(",")[0];
    }

    if (value != "") {
        var ul = document.createElement("UL");

        for (var i = 0; i < value.length; i++) {
            var liopt = document.createElement("LI")
            liopt.appendChild(document.createTextNode(value[i].Text));
            liopt.id = value[i].ID;
            liopt.setAttribute("text", value[i].Value);
            if (isIE) {
                liopt.attachEvent("onclick", self.suggestitemselect)
            }
            else {
                liopt.addEventListener("click", self.suggestitemselect, false);
            }
            ul.appendChild(liopt);
        }

        // Show and position the list
        ctx.o.parentNode.appendChild(ul);
    }
}

function suggestitemsfailure(ex, ctx, methodName) {
    hidesuggestions(ctx.o);
}

function hidesuggestions(o) {
    // hide the list
    if (o.parentNode.getElementsByTagName("UL").length > 0) {
        window.setTimeout(function () { o.parentNode.removeChild(o.parentNode.getElementsByTagName("UL")[0]); }, 200);
    }
    // Check for deleted content
    if (o.value == "") {
        o.setAttribute("text", "");
    }
}

