﻿$.fn.ToggleElement = function () {
    if ($(this).hasClass("displayNone"))
        $(this).removeClass("displayNone");
    else
        $(this).addClass("displayNone");
}


//position element to the center of the window if the window size is larger than the element size
//element's position property must be set to "absolute"
$.fn.positionCenter = function() {
    var newOverlayTop = 0;
    var newOverlayLeft = 0;

    //calculate css "Top" property
    var windowHeight = $(window).height();
    var overlayHeight = $(this).height();
    if (windowHeight > overlayHeight) {
        newOverlayTop = ((windowHeight - overlayHeight) / 2);
    }
    //calculate css "Left" property
    var windowWidth = $(window).width();
    var overlayWidth = $(this).width();
    if (windowWidth > overlayWidth) {
        newOverlayLeft = ((windowWidth - overlayWidth) / 2);
    }
    newOverlayTop = newOverlayTop + $(window).scrollTop();

    $(this).css("top", newOverlayTop + "px");
    $(this).css("left", newOverlayLeft + "px");
}

/*============ js validation ==============*/

function checkInputContainsSymbol(targetField) {
    var fieldVal = targetField.val();
    if (fieldVal.match(/[\!\@\#\$\%\^\&\*\(\)\=\+\[\]\{\}\;\:\'\"\,\/\<\?]/)) {
        var errorField = $("<span></span>").append("Only symbols allowed are . and _").addClass("field-validation-error");
        targetField.after(errorField);
    }
}

function checkInputLength(targetField, minLength) {
    var fieldVal = targetField.val();
    if (fieldVal.length < minLength) {
        var errorField = $("<div></div>").append("Minimum of " + minLength + " character(s) is required").addClass("field-validation-error");
        targetField.after(errorField);
        targetField.addClass("input-validation-error");
        return false;
    }
    return true;
}

function checkInputExist(targetField) {
    var fieldVal = targetField.val();
    if (fieldVal.length == 0) {
        var errorField = $("<div></div>").append("This field is required").addClass("field-validation-error");
        targetField.after(errorField);
        targetField.addClass("input-validation-error");
        return false;
    }
    return true;
}

function checkIsValidEmail(targetField) {
    var fieldVal = targetField.val();
    if (!fieldVal.match(/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_-])+([.]([a-zA-Z])+([a-zA-Z])+)+$/)) {
        var errorField = $("<div></div>").append("Email address invalid").addClass("field-validation-error");
        targetField.after(errorField);
        targetField.addClass("input-validation-error");
        return false;
    }
    return true;
}
/*=================================================*/

/*=============== 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;
}
/*======================================================*/

/*=========================================================*/

/*==== 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;

}

/*========================================================*/

/*==== 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;
}


/*============== 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;
}

function removeThousandSeperator(stringValue) {
    return stringValue.replace(/,/g, "");
}


/*=========================================================*/

$.fn.scaleImage = function() {
    var mode = arguments[0];
    var target = arguments[1];

    var imgHeight = this.height();
    var imgWidth = this.width();

    if (imgHeight != 0 && imgWidth != 0) {
        if (mode == "width") {
            var ratio = target / imgWidth;
            this.width(target);
            this.height(imgHeight * ratio);
        }
        else if (mode == "height") {
            var ratio = target / imgHeight;
            this.height(target);
            this.width(imgWidth * ratio);
        }
        else
            alert("Mode not found");
    }
    else
        alert("Error: Height or Width = 0");
}

/*===== jquery function define =====*/

/*
-- Call this with element eg. $("#inputFormWrapper").sendAjaxWithExpectDataTypeReturn(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" or can be objs like var extraParam = { a:"1", b: true};
-- Expected Responses from Destinations:
=> When dataType is "html" 
Expected Response from call destination is...          
-- if action performed successfully, return ActionResult of View()
-- if action performed failed (eg Exceptions etc), return a JsonEntity with { status: false, message: errorMsg }       
=> When dataType is "json" 
Expected Response from call destination is...          
-- if action performed successfully, return a JsonEntity with { status: true, message: msgIfAny }  
-- if action performed failed (eg Exceptions etc), return a JsonEntity with { status: false, message: errorMsg }       
-- Return:
=> When dataType is "html" 
Expected Response from call destination is...          
-- Success: { status: true, html: htmlData }
-- Failed: { status: false, message: errorMsg }      
=> When dataType is "json"    
-- Success: json object from response
-- Failed: { status: false, message[]: errorMsgs }   
*/

$.fn.sendAjaxWithExpectDataTypeReturn = function () {
    var ajaxURL = "/" + arguments[0] + "/" + arguments[1];
    var method = arguments[2];
    var dataType = arguments[3];
    var extraQueryParams = arguments[4];
    var asyncType = arguments[5] == null ? false : arguments[5];

    var returnValue;
    var querydata = getQueryData(this, extraQueryParams);
    //    var a = "";
    //    for (var k in querydata)
    //        a += k + ",";

    $.ajax({
        url: ajaxURL,
        type: method,
        cache: false,
        data: querydata,
        async: asyncType,
        dataType: dataType,
        success: function (data, textStatus, xmlHttpRequest) {
            //because we want to standardise this ajax call returning objects from server,
            //we have to specificly checks for different expected dataTypes return
            if (dataType.toUpperCase() == "HTML") {
                var contentType = xmlHttpRequest.getResponseHeader("Content-Type");

                if (contentType.indexOf("application/json") >= 0) {
                    //error, because we expecting html
                    //we parse the json and return
                    returnValue = { status: false, jsonVal: eval('(' + data + ')') };
                }
                else if (contentType.indexOf("text/html") >= 0) {
                    //html retreive success
                    returnValue = { status: true, html: data };
                }
            }
            else {
                //other expected dataType return
                returnValue = { status: true, jsonVal: data };
            }
        },
        error: function (xhr, error) {
            //                    alert("error = " + error);
            //                     alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.statusText);
            //                       alert("responseText: " + xhr.responseText);
            returnValue = { status: false, message: "Could not reach destination or Request failed, please try again" };
        }
    });

    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") {
            if ($(this).attr("checked")) {
                if ($(this).attr("name").length > 0)
                    querydata[$(this).attr("name")] = $(this).val();
                else
                    querydata[$(this).attr("class")] = $(this).val();
            }
        }
        else if ($(this).attr("type") == "checkbox") {

            var insertValue;
            if ($(this).is(":checked")) {
                if ($(this).attr("value").length == 0)
                    insertValue = $(this).is(":checked");
                else
                    insertValue = $(this).val();

                //we append using ',' if previously a same element name found
                if ($(this).attr("name").length > 0) {
                    if (querydata[$(this).attr("name")] == null)
                        querydata[$(this).attr("name")] = insertValue;
                    else
                        querydata[$(this).attr("name")] = querydata[$(this).attr("name")] + "," + insertValue;
                }
                else if ($(this).attr("id").length > 0) {
                    if (querydata[$(this).attr("id")] == null)
                        querydata[$(this).attr("id")] = insertValue;
                    else
                        querydata[$(this).attr("id")] = querydata[$(this).attr("id")] + "," + insertValue;
                }
                else {
                    if (querydata[$(this).attr("class")] == null)
                        querydata[$(this).attr("class")] = insertValue;
                    else
                        querydata[$(this).attr("class")] = querydata[$(this).attr("class")] + "," + insertValue;
                }
            }
        }
        else {
            var insertValue = $(this).val();

            if ($(this).attr("type") == "textarea" || $(this).attr("type") == "text") {
                //if its textarea, we always encode before we submit
                insertValue = escape(insertValue);
            }

            if ($(this).attr("name").length > 0) {
                querydata[$(this).attr("name")] = insertValue;
            }
            else if ($(this).attr("id").length > 0)
                querydata[$(this).attr("id")] = insertValue;
            else
                querydata[$(this).attr("class")] = insertValue;
        }
    });

    if (extraQueryParams != null) {
        if (typeof (extraQueryParams) == "string" && extraQueryParams.length > 0) {
            var params = extraQueryParams.split("&");
            for (var i = 0; i < params.length; i++) {
                var tempSplit = params[i].split("=");
                if (tempSplit.length == 2) {
                    //correct format
                    querydata[tempSplit[0]] = tempSplit[1];
                }
                else if (tempSplit.length > 2)
                    querydata[tempSplit[0]] = "Error in JS level";
            }
        }
        else {
            for (var key in extraQueryParams) {
                querydata[key] = extraQueryParams[key];
            }
        }
    }
    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;
} 


