﻿
function encode(input) {
    return $('<div/>').text(input).html();
}

function decode(input) {
    return $('<div/>').html(input).text();
}

/*====== disable/enable Buttons function =============*/
function disableButtonTimer(buttonID, secs) {
    disableButton(buttonID);
    setTimeout("enableButton('" + buttonID + "')", secs);
}

function enableButtonTimer(buttonID, secs) {
    setTimeout("enableButton('" + buttonID + "')", secs);
}

function disableButton(buttonID) {
    $("#" + buttonID).css("opacity", "0.4");
    $("#" + buttonID).css("filter", "alpha(opacity=40)");
    $("#" + buttonID).attr("disabled", "disabled");
}

function disableButtonByItem(button) {
    $(button).css("opacity", "0.4");
    $(button).css("filter", "alpha(opacity=40)");
    $(button).attr("disabled", "disabled");
}

function enableButton(buttonID) {
    $("#" + buttonID).css("opacity", "1");
    $("#" + buttonID).css("filter", "alpha(opacity='100')");
    $("#" + buttonID).attr("disabled", "");
}

function disableButtonClass(classID) {
    $("." + classID).css("opacity", "0.4");
    $("." + classID).css("filter", "alpha(opacity=40)");
    $("." + classID).attr("disabled", "disabled");
}

function enableButtonClass(classID) {
    $("." + classID).css("opacity", "1");
    $("." + classID).css("filter", "alpha(opacity='100')");
    $("." + classID).attr("disabled", "");
}

//new jquery style disable/enable buttons
$.fn.disableButton = function() {
    $(this).attr("disabled", "disabled");
    $(this).css("opacity", "0.4");
    $(this).css("filter", "alpha(opacity=40)");
}

$.fn.enableButton = function() {
    $(this).attr("disabled", "");
    $(this).css("opacity", "1");
    $(this).css("filter", "alpha(opacity=100)");
}


//===========================================//
function disableButtonWithCover(buttonID) {
    //we don't set disable attr to disable as this may 
    //prevent the actual form submission
    $(".cover").css("z-index", "9999");
    $("#" + buttonID).css("opacity", "0.4");
    $("#" + buttonID).css("filter", "alpha(opacity=40)");
}

function enableButtonWithCover(buttonID) {
    //we don't set disable attr to disable as this may 
    //prevent the actual form submission
    $(".cover").css("z-index", "-1");
    $("#" + buttonID).css("opacity", "1");
    $("#" + buttonID).css("filter", "alpha(opacity='100')");
}

/*======================================================*/


/*=============== trim functions =======================*/
//id = element id
// widthPixel = desired pixel width
// numChars = number of chars to be trimmed before checking the pixel width of the string again
//note this also adds "..." to the end of string after trimming
function trimByPixelWidth(id, widthPixel, numChars) {
    if ($("#" + id).width() > widthPixel) {
        var newID = "";
        while ($("#" + id).width() > widthPixel) {
            var uid = $("#" + id).html();
            newID = uid.substr(0, uid.length - numChars);
            $("#" + id).html(newID);
        }
        $("#" + id).html(newID + "...");

    }
}

//can potentially add another trim function for reducing font-size of 1 px per loop and check pixel width

/*======================================================*/

/*============== Pop Up Blocker Detector ===============*/
function isPopUpBlocked() {
    var mine = window.open('', '', 'width=1,height=1,left=0,top=0,scrollbars=no');
    if (mine)
        var popUpsBlocked = false
    else
        var popUpsBlocked = true
    mine.close();
    return popUpsBlocked;
}
/*======================================================*/


/*============== add thousands seperater (js version) ===============*/

function addThousandSeperator(intAmt) {
    intAmt = Math.round(intAmt);
    //convert to string            
    intAmt += '';
    var returnString = "";
    var sepCounter = 0;
    for (var i = intAmt.length; i >= 0; i--, sepCounter++) {
        if (sepCounter == 4) {
            sepCounter = 1;
            returnString = "," + returnString;
        }
        returnString = intAmt.charAt(i) + returnString;
    }
    return returnString;
}

/*=========================================================*/

/*==== restrict input fields to allow numbers only ====*/
function numbersonly(myfield, e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;

    keychar = String.fromCharCode(key);

    // numbers, key==0 is arrows,F1-12, del etc, key==8 is backspace
    if (("0123456789").indexOf(keychar) > -1 || key == 8 || key == 0)
        return true;
    else
        return false;

}

function numbersonlyWithDecimalPoint(myfield, e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;

    keychar = String.fromCharCode(key);

    // numbers, key==0 is arrows,F1-12, del etc, key==8 is backspace
    if (("0123456789\.").indexOf(keychar) > -1 || key == 8 || key == 0)
        return true;
    else
        return false;

}

/*========================================================*/

/*==== bookmark ====*/
//no support chrome???
function bookmark(title, url) {
    // Mozilla
    if (window.sidebar) {
        window.sidebar.addPanel(title, url, "");
    }
    // IE
    else if (window.external) {
        window.external.AddFavorite(url, title);
    }
    else if (window.opera && window.print) {
        var elem = document.createElement('a');
        elem.setAttribute('href', url);
        elem.setAttribute('title', title);
        elem.setAttribute('rel', 'sidebar');
        elem.click();
    }
    else
        return true;
}



/*===== jquery function define =====*/

//call this with element eg. $("#inputFormWrapper").sendAjaxWithStatusReturn(controller, action, method, extraparams)
//This method automatically assign each <input> to data that can be found within this wrapper 
//eg <input type="text" id="username" /> will become data="username=" + $("#username").val()
$.fn.sendAjaxWithStatusReturn = function() {
    var ajaxURL = "/" + arguments[0] + "/" + arguments[1];
    var method = arguments[2];
    var extraQueryParams = arguments[3];
    var returnValue = false;

    var querydata = getQueryData(this, extraQueryParams)

    $.ajax({
        url: ajaxURL,
        type: method,
        data: querydata,
        async: false,
        //TO BE IMPLEMENTED: dataType: "json",
        success: function(data) {
            returnValue = true;
        },
        error: function(xhr, error) {
            //alert("error = " + error); 
            //alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
            //alert("responseText: " + xhr.responseText);
            //shouldnt normally fall here, fall here just disable state function
            returnValue = false;
        }
    });
    return returnValue;
}

//call this with element eg. $("#inputFormWrapper").sendAjaxWithStatusReturn(controller, action, method, expect_return_type, extraparams)
//This method automatically assign each <input> to data that can be found within this wrapper
//extraparams is strings like "a=55&b=44"
// ==> sucess: return {status:0, data: { data returned from action call } }
// ==> failed: return {status:-1, errorMessage:"errormsg"}
//eg <input type="text" id="username" /> will become data="username=" + $("#username").val()
$.fn.sendAjaxWithExpectDataTypeReturn = function() {
    var ajaxURL = "/" + arguments[0] + "/" + arguments[1];
    var method = arguments[2];
    var dataType = arguments[3];
    var extraQueryParams = arguments[4];
    var returnValue;

    var querydata = getQueryData(this, extraQueryParams);

    $.ajax({
        url: ajaxURL,
        type: method,
        data: querydata,
        async: false,
        dataType: dataType,
        success: function(data) {
            returnValue = data;
        },
        error: function(xhr, error) {
            //alert("error = " + error); 
            //alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
            //alert("responseText: " + xhr.responseText);
            returnValue = -1;
        }
    });
    /*
    $.ajax({
    url: ajaxURL,
    type: method,
    data: querydata,
    async: false,
    dataType: dataType,
    success: function(data) {
    if (dataType == "json") {
    processedData = processData(data);
    returnValue = eval("({\"status\":\"0\",\"data\":" + processedData + "})");
    }
    else
    returnValue = data;
    },
    error: function(xhr, error) {
    //alert("error = " + error); 
    //alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
    //alert("responseText: " + xhr.responseText);
    if (dataType == "json") {
    //create new json object
    //THIS IS VERY FRAGILE, DIES EASILY IF ERRORMESSAGE CONTAINS SYMBOLS, newlines etc
    var msg = eval("(" + xhr.responseText + ")").ErrorMessage;
    msg = msg.replace(/;/g, ".");
    msg = msg.replace(/'/g, "");
    msg = msg.replace(/(\r\n|[\r\n])/g, " ");
    returnValue = eval("({\"status\":\"-1\",\"errorMessage\":\"" + msg + "\"})");
    }
    else
    returnValue = -1;
    }
    });*/
    return returnValue;
}

function getQueryData(thisObj, extraQueryParams) {
    //retreive and create data
    var querydata = "";
    var inputQuantity = $(thisObj).find("input, select, textarea").length;
    var counter = 1;
    $.each($(thisObj).find("input, select, textarea"), function() {
        //handle radio inputs because radio inputs have same name but will only be 1 input value
        //to determine, we only find checked radio input to add to query data
        if ($(this).attr("type") == "radio" || $(this).attr("type") == "checkbox" ) {
            if ($(this).attr("checked")) {
                querydata += $(this).attr("class") + "=" + $(this).val();
                if (inputQuantity != counter)
                    querydata += "&";
            }
        }
        else {
            var insertValue = $(this).val();

            if ($(this).attr("type") == "textarea") {
                //if its textarea, we always encode before we submit
                insertValue = escape(insertValue);
            }

            if ($(this).attr("id").length > 0)
                querydata += $(this).attr("id") + "=" + insertValue;
            else
                querydata += $(this).attr("class") + "=" + insertValue;

            if (inputQuantity != counter)
                querydata += "&";
        }
        counter++;
    });

    if (extraQueryParams != null && extraQueryParams.length > 0) {
        if (querydata.length > 0)
            querydata += "&";
        querydata += extraQueryParams;
    }
    return querydata;
}

function processData(data) {
    //create new json object
    var processData = "{";
    var counter = 0;
    data.toJSON = function(key) {
        for (var val in this) {
            if (val != "toJSON") {
                if (counter != 0)
                    processData += ",";
                if (typeof (this[val]) == "object") {
                    if (isArray(this[val])) {
                        processData += "\"" + val + "\":" + processArrayToJsonText(this[val]);
                    }
                    else {
                        //else its not an array object
                        //processData += "\"" + val + "\":\"" + this[val] + "\"";
                    }
                }
                else if (typeof (this[val]) == "boolean") {
                    processData += "\"" + val + "\":" + this[val];
                }
                else
                    processData += "\"" + val + "\":\"" + this[val] + "\"";
            }
            counter++;
        }
        processData += "}";
    }
    var jsonText = JSON.stringify(data);
    return processData;
}

function processArrayToJsonText(array) {
    var jsonText = "[";
    for (var i = 0; i < array.length; i++) {
        if (i != 0)
            jsonText += ",";
        if (typeof (array[i]) == "object") {
            if (isArray(array[i])) {
                jsonText += processArrayToJsonText(array[i]);
            }
            else {
                //else its not an array object
                jsonText += processData(array[i]);
            }
        }
        else if (typeof (array[i]) == "boolean") {
            jsonText += array[i];
        }
        else {
            jsonText += "\"" + array[i] + "\"";
        }
    }
    jsonText += "]";
    return jsonText;
}

function isArray(obj) {
    return obj.constructor == Array;
} 



