﻿/* A general function that associates an object instance with an event
handler. The returned inner function is used as the event handler.
The object instance is passed as the - obj - parameter and the name
of the method that is to be called on that object is passed as the -
methodName - (string) parameter.
*/
function GISPlanning_MapUtilities_AssociateObjWithEvent(obj, methodName, args) {
    /* The returned inner function is intended to act as an event
    handler for a DOM element:-
    */
    return (function(e) {
        /* The event object that will have been parsed as the - e -
        parameter on DOM standard browsers is normalised to the IE
        event object if it has not been passed as an argument to the
        event handling inner function:-
        */
        e = e || window.event;
        /* The event handler calls a method of the object - obj - with
        the name held in the string - methodName - passing the now
        normalised event object and a reference to the element to
        which the event handler has been assigned using the - this -
        (which works because the inner function is executed as a
        method of that element because it has been assigned as an
        event handler):-
        */
        return obj[methodName](e, this, args);
    });
};


//attaches an event listener
function AddEventHandler(obj, eventName, handler) {
    //add event handlers
    if (obj.addEventListener == undefined) {//this occurs when using IE
        obj.attachEvent(eventName, handler);
    }
    else {//hopefully everything else
        obj.addEventListener(eventName, handler, false);
    }; //end attaching events
};


//adds a click handler (specialized version of AddEventHandler)
function AddClickHandler(obj, handler) {
    //add event handlers
    if (obj.addEventListener == undefined) {//this occurs when using IE
        obj.attachEvent("onclick", handler);
    }
    else {//hopefully everything else
        obj.addEventListener("click", handler, false);
    }; //end attaching events
};




function GISPlanning_MapUtilities_CreateXMLHttpRequestObject() {
    var myXMLHttpRequestObject = null; //create XMLobject

    // Provide the XMLHttpRequest class for IE 5.x-6.x:
    if (typeof XMLHttpRequest == "undefined") {
        myXMLHttpRequestObject = function() {
            try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch (e) { }
            try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch (e) { }
            try { return new ActiveXObject("Msxml2.XMLHTTP") } catch (e) { }
            try { return new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { }
            throw new Error("This browser does not support XMLHttpRequest.")
        };
    } //end if XMLHttpRequest is not directly supported
    else {
        myXMLHttpRequestObject = new XMLHttpRequest();
    };  //end if XMLHttpRequest is supported natively

    return myXMLHttpRequestObject;
};  //end function

function GISP_MapUtilities_PrintMap() {
    var myMapGuid = GISPlanning_MapUtilities_GUID();

    //NOTE: Must use jquery clone in order to remove the event references so that removing the nonexportable and nonpopout methods
    //doesnt destroy the events
    var myMapClone = $("#map").clone()[0];
    //GISP_RemoveNonExportable(myMapClone);
    //GISP_RemoveNonPopout(myMapClone);
    var myMapContent = myMapClone.innerHTML;
    
    alert('test');
    _popupTracker.AddContent(myMapGuid, myMapContent);

    GISPlanning_Popup_Window('main/reportViewers/map.aspx?id=' + myMapGuid, { width: 960, height: 420 });

}; //end function


function GISP_RemoveNonExportable(pDomElement) {
    $(pDomElement).find(".nonexportable").remove();
    $(pDomElement).find("#__VIEWSTATE").remove();
}; //end function

function GISP_RemoveNonPopout(pDomElement) {
    $(pDomElement).find(".nonpopout").remove();
}; //end function

function GISP_RemoveFunctionHyperlinks(pDomElement) {
    //modify all hyperlinks to remove JS Functions
    $(pDomElement).find("a").each(function() {
        if (this.href.indexOf("javascript:") != -1) {
            this.setAttribute("href", "");
        }; //end if function link
    });
}; //end function



//This function takes a collection of attributes and sets each one on the HTML element
function GISPlanning_MapUtilities_SetHTMLAttributes(element, attributeCollection) {
    for (var attribute in attributeCollection) {
        element[attribute] = attributeCollection[attribute];
    } //end for each attribute
} //end function




//------------------------ Tooltip Service --------------------------------------------------------------------------


function GISPlanning_MapUtilities_TooltipService(map) {
    this._map = map;
    this.tooltip = document.createElement("div");
    this.tooltip.className = "GISPlanning_MapUtilities_Tooltip";
    this._map.getPane(G_MAP_MARKER_PANE).appendChild(this.tooltip);

    //methods
    this.HideTooltip = function() {
        this.tooltip.innerHTML = '';
        this.tooltip.style.display = "none";
    };  //end function

    this.DisplayTooltip = function(latlng, tooltipText) {
        if (typeof latlng != "undefined") {
            this.tooltip.innerHTML = tooltipText;
            this.tooltip.style.display = "block";

            // Tooltip transparency specially for IE
            if (typeof (this.tooltip.style.filter) == "string") {
                this.tooltip.style.filter = "alpha(opacity:70)";
            };

            var currtype = this._map.getCurrentMapType().getProjection();
            var point = currtype.fromLatLngToPixel(this._map.fromDivPixelToLatLng(new GPoint(0, 0), true), this._map.getZoom());
            var offset = currtype.fromLatLngToPixel(latlng, this._map.getZoom());
            var width = 10;
            var height = 10;
            var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x + width, offset.y - point.y - height));
            pos.apply(this.tooltip);
        };
    };     //end function
}; //end function class



function GISPlanning_MapUtilities_OptionCollection(pOptions) {
    /// <summary>
    ///	Provides generic wrapper for working with the object literal collection
    /// </summary>
    /// <returns type="Object"></returns>
    /// <param name="Option Collection" type="Literal" optional="false">The Javascript object literal to wrap</param>
    var me = this;
    //FIELDS*******************************************************************
    this._options = pOptions;

    //FUNCTIONS****************************************************************
    this._getOption = function(option) {
        ///<summary>Returns the option or null if it doesnt exist</summary>
        return typeof me._options[option] != "undefined" ? me._options[option] : null;
    };  //end function getOption
    this._setOption = function(option, value) {
        ///<summary>Sets the option even if it doesnt exist</summary>
        me._options[option] = value;
    }; //end function setOption

    //CONSTRUCTOR**************************************************************
    return new function() {
        this.GetOption = me._getOption;
        this.SetOption = me._setOption;
    }; //end constructor
};


function GISPlanning_MapUtilities_latLonInMapBounds(map, lat, lon) {
    var bounds = map.getBounds();
    if (lat < bounds.minY || lat > bounds.maxY ||
         lon < bounds.minX || lon > bounds.maxX) {
        return false;
    } else {
        return true;
    }; //end if/else
}; //end function

function GISPlanning_MapUtilities_RegisterCSSFile(pURL) {
    var myHead = document.getElementsByTagName("head").item(0);
    var myCSSLink = document.createElement("link");
    myCSSLink.setAttribute("href", pURL);
    myCSSLink.setAttribute("rel", "stylesheet");
    myCSSLink.setAttribute("type", "text/css");
    myHead.appendChild(myCSSLink);
}; //end function register CSS

function GISPlanning_MapUtilities_RegisterScript(pURL) {
    //append the script
    var myHead = document.getElementsByTagName("head").item(0);
    var myLink = document.createElement("script");
    myLink.setAttribute("src", pURL);
    myLink.setAttribute("type", "text/javascript");
    myHead.appendChild(myLink);
}; //end method



function GISPlanning_MapUtilities_GUID() {
    this._R4 = function() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }; //end function R4
    this._GetNewRequestID = function GetRequestID() {
        return (this._R4() + this._R4() + "-" + this._R4() + "-" + this._R4() + "-" + this._R4() + "-" + this._R4() + this._R4() + this._R4());
    }; //end function GetNewRequestID

    return this._GetNewRequestID();
}; //end



//Creates a clone of an objects properties and values
function GISPlanning_CloneObject(pObject) {
    for (i in pObject) {
        this[i] = pObject[i];
    }; //end for each property of object
}; //end method CloneObject


function GISPlanning_AddMouseOverToImage(pImageElement) {
    //This little jquery makes addes mouseovers to our save buttons
    $(pImageElement).mouseover(function() {
        var myImageName = $(this).attr("src");
        var myIndexOfLastDot = myImageName.lastIndexOf('.');
        myImageName = myImageName.substr(0, myIndexOfLastDot) + "_over" + myImageName.substr(myIndexOfLastDot, myImageName.length - myIndexOfLastDot);
        $(this).attr({ src: myImageName });
    }).mouseout(function() {
        var myImageName = $(this).attr("src");
        myImageName = myImageName.replace("_over", "");
        $(this).attr({ src: myImageName });
    });
}; //end function

function GISPlanning_SetImageActive(pImageElement) {
    //This little jquery changes the image to -on
    var myImageName = $(pImageElement).attr("src");
    if(myImageName != undefined){
        myImageName = myImageName.replace("_inactive", "_active");
        $(pImageElement).attr({ src: myImageName });
    }
    
}; //end function

function GISPlanning_SetImageInactive(pImageElement) {
    //This little jquery removes the -on
    var myImageName = $(pImageElement).attr("src");
    if(myImageName != undefined){
         myImageName = myImageName.replace("_active", "_inactive");
        $(pImageElement).attr({ src: myImageName });
    }
   
}; //end function


function GISPlanning_GetListboxOptionsAsList(pListbox, pDelimiter) {
    var myReturnString = '';
    for (var i = 0; i < pListbox.options.length; i++) {
        myReturnString = myReturnString + pListbox.options[i].value;
        if (i < pListbox.options.length - 1) {
            myReturnString = myReturnString + pDelimiter;
        }; //end if not last option
    }; //end for each option

    return myReturnString;
};

function GISPlanning_GetListboxDisplayItemsAsList(pListbox, pDelimiter) {
    var myReturnString = '';
    for (var i = 0; i < pListbox.options.length; i++) {
        myReturnString = myReturnString + pListbox.options[i].text;
        if (i < pListbox.options.length - 1) {
            myReturnString = myReturnString + pDelimiter;
        }; //end if not last option
    }; //end for each option

    return myReturnString;
};

function GISPlanning_GetListboxItemsAsIncludeExcludeList(pListbox, pDelimiter) {
    var myReturnString = '';
    for (var i = 0; i < pListbox.options.length; i++) {
        var myOption = pListbox.options[i];
        var myAddOrRemove = myOption.text.substring(1, 2);

        myReturnString = myReturnString + myAddOrRemove + myOption.value;
        if (i < pListbox.options.length - 1) {
            myReturnString = myReturnString + pDelimiter;
        }; //end if not last option
    }; //end for each option

    return myReturnString;
};

function GISPlanning_Popup_Window(pURL, pOptions) {
    var myWindowOptions = { toolbar: "0", scrollbars: "1", location: "0", statusbar: "0", menubar: "0", resizable: "1", width: "970", height: "650", left: "300", top: "0" };
    pOptions = pOptions != null ? pOptions : {};
    for (var o in myWindowOptions) {
        if (typeof (pOptions[o]) != "undefined") {
            myWindowOptions[o] = pOptions[o];
        }; //end if option was passed in
    }; //end for each option
    var myDay = new Date();
    var myId = myDay.getTime();
    window.open(pURL, myId, 'toolbar=' + myWindowOptions["toolbar"] + ',scrollbars=' + myWindowOptions["scrollbars"] + ',location=' + myWindowOptions["location"] + ',statusbar=' + myWindowOptions["statusbar"] + ',menubar=' + myWindowOptions["menubar"] + ',resizable=' + myWindowOptions["resizable"] + ',width=' + myWindowOptions["width"] + ',height=' + myWindowOptions["height"] + ',left =' + myWindowOptions["left"] + ',top = ' + myWindowOptions["top"]);
}; //end function

function GISPlanning_PopupTracker() {
    this.Container = {};
    this.GetContent = function(pKey) {
        return this.Container[pKey];
    }; //end method
    this.AddContent = function(pKey, pContent) {
        this.Container[pKey] = pContent;
    }; //end method
}; //end class GISPlanning_PopupTracker



function GISPlanning_AddPopup(pElement, pEM_HTML) {
    $(pElement).append(pEM_HTML);

    $(pElement).click(function() {
        $(this).find("em").animate({ opacity: "show" }, "slow");
    });
    $(pElement).hover(function() { }, function() {
        $(this).find("em").animate({ opacity: "hide" }, "fast");
    });
}; //end function

function GISPlanning_HidePopup(pID) {
    var myPopup = $get(pID);
    $(myPopup).find("em").animate({ opacity: "hide" }, "fast");
}; //end function


function GISPlanning_CreateGCircle(pLat, pLng, pRadius) {
    var myRadiusX = pRadius / (69.1);
    var myRadiusY = pRadius / (69.1 * Math.cos(pLat / 57.3));
    var myCirclePoints = [];


    for (var k = 0; k < 6.28; k += 0.10) {
        var myPoint = new GLatLng(
			    pLat + (myRadiusX * Math.sin(k)), pLng + (myRadiusY * Math.cos(k))
			);

        myCirclePoints.push(myPoint);
    }; //end for

    myCirclePoints.push(myCirclePoints[0]);

    var myCircle = new GPolyline(myCirclePoints);

    return myCircle;

}; //end function

function GISP_NullOrInputValue(pElementID) {
    var myInputElement = $get(pElementID);
    var myReturnValue = null;
    switch (myInputElement.type) {
        case "text":
            myReturnValue = myInputElement.value; break;
        case "select-one":
            for (var i = 0; i < myInputElement.options.length; i++) {
                if (myInputElement.options[i].selected) {
                    myReturnValue = myInputElement.options[i].value;
                    break;
                }; //end if selected
            }; //end for
            break;
        case "checkbox":
            myReturnValue = myInputElement.checked; break;
    }; //end switch
    return myReturnValue != "" ? myReturnValue : null;
};


function GISP_GetDropDownSelectedDisplayValue(pDropDown) {
    var myReturnValue = null;
    for (var i = 0; i < pDropDown.options.length; i++) {
        if (pDropDown.options[i].selected) {
            myReturnValue = pDropDown.options[i].text;
            break;
        }; //end if selected
    }; //end for
    return myReturnValue;
}; //end function

function DisplayInlineTable(pTableID) {
    if ($.browser.msie) {
        $get(pTableID).style.display = "inline";
    } else {
        $get(pTableID).style.display = "inline-table";
    }; //end ifelse IE
}; //end function