﻿//-----------------------------------
//makes a jsonp request against the specified url
//-----------------------------------
function sendJsonpRequest(url) {
    url += '&' + new Date().getTime().toString(); // prevent caching

    var script = document.createElement("script");
    script.setAttribute("src", url);
    script.setAttribute("type", "text/javascript");
    document.body.appendChild(script);
}
//-----------------------------------
//makes a call to a webg service on the current page
// functionName - the function to call
// jsonParameters - an object with the appropriate parameters
//-----------------------------------
function CallWebService(functionName, jsonParameters) {
    var pagePath = window.location.pathname;
    Sys.Net.WebServiceProxy.invoke(pagePath, functionName, false, jsonParameters, OnPageMethodComplete, OnPageMethodsError);
}
//-----------------------------------
//makes a call to a web service on the current page + allows to specify the complete function
// functionName - the function to call
// jsonParameters - an object with the appropriate parameters
// completeMethod - method to call upon completion
//-----------------------------------
function CallWebServiceEx(functionName, jsonParameters, completeMethod) {
    var pagePath = window.location.pathname;
    Sys.Net.WebServiceProxy.invoke(pagePath, functionName, false, jsonParameters, completeMethod, OnPageMethodsError);
}
//-----------------------------------
//makes a call to a web service on the current page + allows to specify the complete function
// url - the url the web service on
// functionName - the function to call
// jsonParameters - an object with the appropriate parameters
//-----------------------------------
function CallWebServiceUrl(url, functionName, jsonParameters) {
    Sys.Net.WebServiceProxy.invoke(url, functionName, false, jsonParameters, OnPageMethodComplete, OnPageMethodsError);
}
//-----------------------------------
//makes a call to a web service on the current page + allows to specify the complete function
// url - the url the web service on
// functionName - the function to call
// jsonParameters - an object with the appropriate parameters
// completeMethod - method to call upon completion
//-----------------------------------
function CallWebServiceUrlEx(url, functionName, jsonParameters, completeMethod) {
    Sys.Net.WebServiceProxy.invoke(url, functionName, false, jsonParameters, completeMethod, OnPageMethodsError);
}
//-----------------------------------------
//creates the HttpRequest, and return it back
//-----------------------------------------
function getXMLHttpRequestObject() {
    try {
        var xhr = null;
        if (window.XMLHttpRequest)     // Object of the current windows
        {
            xhr = new XMLHttpRequest();     // Firefox, Safari, ...
        }
        else if (window.ActiveXObject)   // ActiveX version
        {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");  // Internet Explorer 
        }

        return xhr;
    }
    catch (e) {
        return null;
    }
}

//-----------------------------------------
//clears the text on the specified field
//-----------------------------------------
function ClearTextField(id) {
    var f = document.getElementById(id);
    if (f == null || !f.value)
        return;

    f.value = '';
}
//---------------------
//general function to handle page method complete call
//---------------------
function OnPageMethodComplete(jsonResult, userContext, methodName) {

    var PAGE_METHOD_ACTION_ALERT = 1;
    var PAGE_METHOD_ACTION_REDIRECT = 2;
    var PAGE_METHOD_ACTION_EXECUTE_JAVASCRIPT = 3;

    try {
        var result = Sys.Serialization.JavaScriptSerializer.deserialize(jsonResult, true);
        //var result = JSON.parse(jsonResult);

        //var result = eval('(' + jsonResult + ')');
        var action = result.Action;
        var info = result.Info;

        switch (action) {
            case PAGE_METHOD_ACTION_ALERT:
                alert(info);
                break;

            case PAGE_METHOD_ACTION_REDIRECT:
                window.location = info;
                break;

            case PAGE_METHOD_ACTION_EXECUTE_JAVASCRIPT:
                eval(info);
                break;
        }
    }
    catch (e) { }
}
//---------------------
//called upon a page method failing to execute or returning an exception
//---------------------
function OnPageMethodsError(error, userContext, methodName) {
    if (error != null) {
        alert(error.get_message());
    }
}
//----------------------------------
//returns an object if supplied or
//gets the object if an id is given
//----------------------------------
function GetObject(o) {
    /// <summary>tries to extract the object from the dom</summary>
    /// <param name="o">object or id</param>
    /// <returns>the object from the DOM or null if object was not found</returns>
    if (typeof (o) == 'object')
        return o;
    else
        return document.getElementById(o);
}
//----------------------------
//generates a delimited string with all selected ids under the div specified
//----------------------------
function getSelectedCheckboxesIds(list, delimiter) {

    var divList = GetObject(list);
    if (divList == null)
        return '';

    var checkboxNodes = divList.getElementsByTagName('input');

    var selectedIds = '';
    for (var j = 0; j < checkboxNodes.length; j++) {
        var childNode = checkboxNodes[j];
        try {
            if (childNode.checked == true) {
                if (selectedIds != '')
                    selectedIds += delimiter;

                selectedIds += childNode.id;
            }
        }
        catch (e) { }
    }

    return selectedIds;
}
//----------------------------
//gets the value of the selected radio button on the div specified
//----------------------------
function getSelectedRadioButtonId(list) {

    var divList = GetObject(list);
    if (divList == null)
        return '';

    var checkboxNodes = divList.getElementsByTagName('input');

    var selectedIds = '';
    for (var j = 0; j < checkboxNodes.length; j++) {
        var childNode = checkboxNodes[j];
        try {
            if (childNode.checked == true) {
                return childNode.id;
            }
        }
        catch (e) { }
    }

    return selectedIds;
}
//----------------------------
//removes control border upon control becomes in focus
//----------------------------
function RmvBrd(obj) {
    try {
        if (obj.blur) obj.blur();
    }
    catch (e) { }
}
//----------------------------------
//shows an object 
//----------------------------------
function Show(o) {
    var obj = GetObject(o);
    if (obj != null)
        obj.style.display = 'block';
}
//----------------------------------
//hides an object 
//----------------------------------
function Hide(o) {
    /// <summary>
    /// hides an object specified
    /// </summary>
    /// <param name="0">object or id</param>
    var obj = GetObject(o);
    if (obj != null)
        obj.style.display = 'none';
}
//----------------------------------
//hides all of the child elements
//within an object
//----------------------------------
function HideAll(o) {
    var obj = GetObject(o);
    for (var index = 0; index < obj.childNodes.length; index++) {
        try { Hide(obj.childNodes[index].id); } catch (e) { }
    }
}
//----------------------------
//refreshes the specified div html
//----------------------------
function refreshDivHTML(divId, html) {
    var div = document.getElementById(divId);
    if (div != null)
        div.innerHTML = html;
}
//---------------------------
//creates a hidden iframe and set the url on it - primarily used to export files
//---------------------------
function createHiddenIFrame(parentId, url) {
    var div = document.getElementById(parentId);
    var iframe = document.createElement('IFRAME');
    iframe.src = url;
    iframe.style.display = 'none';
    div.appendChild(iframe);
}
//---------------------------
//allows to trim strings
//---------------------------
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
}
//---------------------------
//gets the value of a text field and make sure it's not same as title
//---------------------------
function GetTextControlValue(id) {
    try {
        var field = document.getElementById(id);
        var val = field.value;
        var title = field.title;
        if (val == title)
            return '';
        else
            return val;

    }
    catch (e) { return ''; }
}

//-----------------------------------
//creates or override a cookie
//value should be used with escape whenever needed
//-----------------------------------
function SetCookieValue(name, value, expirationDate) {
    try {
        var expires = '';
        try {
            var d = new Date(expirationDate);
            expires = ';expires=' + d.toUTCString();
        }
        catch (ed) { }

        document.cookie = name + "=" + value + expires + "; path=/";
    }
    catch (e) { }
}
//-----------------------------------
//gets current domain url address
//-----------------------------------
function GetDomainUrl() {
    var ur = window.location;

    var protocol = ur.protocol;
    var hostname = ur.hostname;
    var port = ur.port;

    var url = protocol + "//" + hostname;
    if (port != 80)
        url += ":" + port;

    //adds last forward slash
    url += "/";

    return url;
}
