﻿var DEFAULT_DATE_FORMAT = 'M/d/yyyy';

var _postMessageTypes = {
    PageLoaded: '1',
    Redirect: '2',
    SaveCookie: '3',
    ActionComplete: '4'
};

var _customFieldTypes = {
    NotAvailable: 0,
    NotRequired: 1,
    Required: 2
};

var _windowParams = {
    facebook: { width: 640, height: 340 },
    twitter: { oauth1: { width: 800, height: 450 }, oauth2: { width: 510, height: 500} },
    linkedin: { width: 600, height: 440 }
}

//-----------------------------------
//gets attributes needed to open facebook oauth dialog
//-----------------------------------
function facebookWindowParams() {
    return windowParams(_windowParams.facebook.width, _windowParams.facebook.height);
}
//-----------------------------------
//gets attributes needed to open twitter oauth dialog
//-----------------------------------
function twitterWindowParamsOauth1() {
    return windowParams(_windowParams.twitter.oauth1.width, _windowParams.twitter.oauth1.height);
}
//-----------------------------------
//gets attributes needed to open linkedin oauth dialog
//-----------------------------------
function linkedinWindowParams() {
    return windowParams(_windowParams.linkedin.width, _windowParams.linkedin.height);
}

//-----------------------------------------
//gets appropriate window parameters for windows.open function
//-----------------------------------------
function windowParams(w, h) {
    var wx = (typeof window.screenLeft != 'undefined') ? window.screenLeft : window.screenX;
    var wy = (typeof window.screenTop != 'undefined') ? window.screenTop : window.screenY;

    var x = ($(window).width() - w) / 2 + wx;
    var y = ($(window).height() - h) / 2 + wy;

    //return 'titlebar=0,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes,resize=yes,modal=yes,width=' + w + ',height=' + h + ',top=' + y + ',left=' + x;
    return 'titlebar=0,toolbar=0,location=1,directories=0,status=0,menubar=0,scrollbars=yes,resize=yes,modal=yes,width=' + w + ',height=' + h + ',top=' + y + ',left=' + x;
}

//-----------------------------------
//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) {

    var cookieString = getCookieString(name, value, expirationDate);
    if (isEmptyString(cookieString))
        return;

    try{ document.cookie = cookieString; }
    catch (e) { }

    /*try {
    var expires = '';
    try {
    var d = new Date(expirationDate);
    expires = ';expires=' + d.toUTCString();
    }
    catch (ed) { }

    document.cookie = name + "=" + value + expires + "; path=/";
    }
    catch (e) { }*/
}
function testCookie() {

    document.cookie = '"test=gil;expires=Sat, 27 Oct 2012 04:00:00 UTC; path=/"';
}
//-----------------------------------
//creates the string to apply to the cookies object
//-----------------------------------
function getCookieString(name, value, expirationDate) {
    try {
        var expires = '';
        try {
            var d = new Date(expirationDate);
            expires = ';expires=' + d.toUTCString();
        }
        catch (ed) { }

        var cookieString = name + "=" + value + expires + "; path=/";
        return cookieString;
    }
    catch (e) {return '' }
}
//-----------------------------------
//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 != '' && port != 80)
        url += ":" + port;

    //adds last forward slash
    url += "/";

    return url;
}
//formats the date to be accepted by the application as a url/ajax parameter
function getUrlParameterDateString(dt) {
    var dateString = dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate();
    return dateString;
}

// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// date. If it does not match, it returns null.
// ------------------------------------------------------------------
function getDateFromFormat(val, format) {
    val = val + "";
    format = format + "";
    var i_val = 0;
    var i_format = 0;
    var c = "";
    var token = "";
    var token2 = "";
    var x, y;
    var now = new Date();
    var year = now.getYear();
    var month = now.getMonth() + 1;
    var date = 1;
    var hh = now.getHours();
    var mm = now.getMinutes();
    var ss = now.getSeconds();
    var ampm = "";

    while (i_format < format.length) {
        // Get next token from format string
        c = format.charAt(i_format);
        token = "";
        while ((format.charAt(i_format) == c) && (i_format < format.length)) {
            token += format.charAt(i_format++);
        }
        // Extract contents of value based on format token
        if (token == "yyyy" || token == "yy" || token == "y") {
            if (token == "yyyy") { x = 4; y = 4; }
            if (token == "yy") { x = 2; y = 2; }
            if (token == "y") { x = 2; y = 4; }
            year = _getInt(val, i_val, x, y);
            if (year == null) { return 0; }
            i_val += year.length;
            if (year.length == 2) {
                if (year > 70) { year = 1900 + (year - 0); }
                else { year = 2000 + (year - 0); }
            }
        }
        else if (token == "MMM" || token == "NNN") {
            month = 0;
            for (var i = 0; i < MONTH_NAMES.length; i++) {
                var month_name = MONTH_NAMES[i];
                if (val.substring(i_val, i_val + month_name.length).toLowerCase() == month_name.toLowerCase()) {
                    if (token == "MMM" || (token == "NNN" && i > 11)) {
                        month = i + 1;
                        if (month > 12) { month -= 12; }
                        i_val += month_name.length;
                        break;
                    }
                }
            }
            if ((month < 1) || (month > 12)) { return 0; }
        }
        else if (token == "EE" || token == "E") {
            for (var i = 0; i < DAY_NAMES.length; i++) {
                var day_name = DAY_NAMES[i];
                if (val.substring(i_val, i_val + day_name.length).toLowerCase() == day_name.toLowerCase()) {
                    i_val += day_name.length;
                    break;
                }
            }
        }
        else if (token == "MM" || token == "M") {
            month = _getInt(val, i_val, token.length, 2);
            if (month == null || (month < 1) || (month > 12)) { return 0; }
            i_val += month.length;
        }
        else if (token == "dd" || token == "d") {
            date = _getInt(val, i_val, token.length, 2);
            if (date == null || (date < 1) || (date > 31)) { return 0; }
            i_val += date.length;
        }
        else if (token == "hh" || token == "h") {
            hh = _getInt(val, i_val, token.length, 2);
            if (hh == null || (hh < 1) || (hh > 12)) { return 0; }
            i_val += hh.length;
        }
        else if (token == "HH" || token == "H") {
            hh = _getInt(val, i_val, token.length, 2);
            if (hh == null || (hh < 0) || (hh > 23)) { return 0; }
            i_val += hh.length;
        }
        else if (token == "KK" || token == "K") {
            hh = _getInt(val, i_val, token.length, 2);
            if (hh == null || (hh < 0) || (hh > 11)) { return 0; }
            i_val += hh.length;
        }
        else if (token == "kk" || token == "k") {
            hh = _getInt(val, i_val, token.length, 2);
            if (hh == null || (hh < 1) || (hh > 24)) { return 0; }
            i_val += hh.length; hh--;
        }
        else if (token == "mm" || token == "m") {
            mm = _getInt(val, i_val, token.length, 2);
            if (mm == null || (mm < 0) || (mm > 59)) { return 0; }
            i_val += mm.length;
        }
        else if (token == "ss" || token == "s") {
            ss = _getInt(val, i_val, token.length, 2);
            if (ss == null || (ss < 0) || (ss > 59)) { return 0; }
            i_val += ss.length;
        }
        else if (token == "a") {
            if (val.substring(i_val, i_val + 2).toLowerCase() == "am") { ampm = "AM"; }
            else if (val.substring(i_val, i_val + 2).toLowerCase() == "pm") { ampm = "PM"; }
            else { return 0; }
            i_val += 2;
        }
        else {
            if (val.substring(i_val, i_val + token.length) != token) { return 0; }
            else { i_val += token.length; }
        }
    }
    // If there are any trailing characters left in the value, it doesn't match
    if (i_val != val.length) { return 0; }
    // Is date valid for month?
    if (month == 2) {
        // Check for leap year
        if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { // leap year
            if (date > 29) { return 0; }
        }
        else { if (date > 28) { return 0; } }
    }
    if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) {
        if (date > 30) { return 0; }
    }

    // Correct hours value
    if (hh < 12 && ampm == "PM") { hh = hh - 0 + 12; }
    else if (hh > 11 && ampm == "AM") { hh -= 12; }
    var newdate = new Date(year, month - 1, date, hh, mm, ss);
    return newdate;
}

// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
    var digits = "1234567890";
    for (var i = 0; i < val.length; i++) {
        if (digits.indexOf(val.charAt(i)) == -1) { return false; }
    }
    return true;
}
function _getInt(str, i, minlength, maxlength) {
    for (var x = maxlength; x >= minlength; x--) {
        var token = str.substring(i, i + x);
        if (token.length < minlength) { return null; }
        if (_isInteger(token)) { return token; }
    }
    return null;
}
// ------------------------------------------------------------------
// sends a message to parant (from iframe) using postmessage
// ------------------------------------------------------------------
function PostMessageNotifyParent(messageId, info) {
    var paramURl = 'url';

    try {

        if (!window.postMessage)
            return;

        var ftParams = ParseQuery(document.location.href.replace(/^[^\?]+\??/, ''));
        var ftParamsURL = ftParams[paramURl];

        var parentURL = decodeURIComponent(ftParamsURL.replace(/^#/, ''));

        var jsonParameters = new Object();
        jsonParameters.id = messageId;
        jsonParameters.info = info;

        $.postMessage(jsonParameters, parentURL, parent);

    }
    catch (e) { }
}
// ------------------------------------------------------------------
// Utility to parse query parameters
// ------------------------------------------------------------------
function ParseQuery(query) {
    var Params = new Object();
    if (!query) return Params; // return empty object
    var Pairs = query.split(/[;&]/);
    for (var i = 0; i < Pairs.length; i++) {
        var KeyVal = Pairs[i].split('=');
        if (!KeyVal || KeyVal.length != 2) continue;
        var key = unescape(KeyVal[0]);
        var val = unescape(KeyVal[1]);
        val = val.replace(/\+/g, ' ');
        Params[key] = val;
    }
    return Params;
}
// ------------------------------------------------------------------
// checks if parameter is defined
// ------------------------------------------------------------------
function isDefined(s) {
    return (typeof s != 'undefined');
}
// ------------------------------------------------------------------
// checks if parameter is defined and has a value (not null or blank)
// ------------------------------------------------------------------
function isEmptyString (str) {

    return (!isDefined(str) || str == null || str == '');
}
