

/*
01/14/09 Chandra.Bhumireddy
- Use this plugin file to include any reusable functions developed by projectmates
*/


/* this function returns client area available on the page. Use this to function to  adjust 
the layout height and width based on client screen resolution */
/*Usage  : 
var size = $.GetClientSize();
alert("width:"+size.width + "  height:"+size.height); 
*/


/* This method returns the list of selected values in the checkbox list with the specified name, separated by the specified separator*/
jQuery.GetCheckBoxListSelectedValues = function (checkboxListName, Separator) {
    var Result = "";
    if (Separator == "" || Separator == null) Separator = ",";
    $("input[name='" + checkboxListName + "'] ").each(function () { if (this.checked) Result = Result + this.value + Separator; });
    if (Result.length > 0) Result = Result.substr(0, (Result.length - 1)); //remove the extra separator
    return Result;
}

jQuery.GetClientSize = function () {
    var dimensions = { width: 0, height: 0 };
    if (document.documentElement) {
        dimensions.width = document.documentElement.offsetWidth;
        dimensions.height = document.documentElement.offsetHeight;
    } else if (window.innerWidth && window.innerHeight) {
        dimensions.width = window.innerWidth;
        dimensions.height = window.innerHeight;
    }
    return dimensions;
};

//Validates the file extension to given list of filters
jQuery.MatchesFileExtenstion = function (srcFileName, file_ext_list) {
    if (srcFileName == null || srcFileName == "") return false;
    var list = srcFileName.split(".");
    if (list == null) return false;

    var filter_list = file_ext_list.split(",");


    for (var i = 0; i < filter_list.length; i++) {
        if (list[list.length - 1].toUpperCase() == filter_list[i].toUpperCase())
            return true;

    }
    return false;

}




//////////////////////////////////////// ShowInlinePopup ////////////////////////////////////////////////////////
/*  Use this method to show small inline popup that shows up few sec after focusing the element and closes autmatically.
helpful in a repeater or gridview where more info needs to be shown after focusing on a row

Call this method on 'MouseOver' event of SPAN or Anchor elements
Usage: 
el: source element
main_contentId : id of html element that is shown as popup
wait_time : time in ms to wait before showing the popup
display_time : time in ms the popup is shown before closing automatically
w : width of popup
h : height of popup
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
jQuery.ShowInlinePopup = function (el, main_contentId, wait_time, display_time, w, h, showClose, doNotUnbindClick) {
    if (hs == 'undefined')
    { alert('Please include Highslide script '); return; }

    $(el).attr('mouseout', 'false');
    //bind mouseout event
    $(el).bind('mouseout', function () { $(this).attr('mouseout', 'true'); });
    //bind onclick to ignore the popup request
    if (!doNotUnbindClick)
        $(el).bind('click', function () { $(this).attr('mouseout', 'true'); });

    var i = 0;
    (function () {
        if (i <= 10 && wait_time > 0) {
            setTimeout(arguments.callee, (wait_time / 10));
            i++;
        }
        else if ($(el).attr('mouseout') == 'false') {
            //close all open expanders
            ClosePopup();
            hs.dimmingOpacity = 0; // do not dim background
            //Create a reusable popup wrapper
            var wrapperId = CreateInlinePopupWrapper(showClose);
            hs.htmlExpand(el, { contentId: wrapperId, maincontentId: main_contentId, width: w, height: h });
            if (display_time > 0)
                setTimeout(function () { ClosePopup(el) }, display_time);
        }
    })();

    return false;
}

// for the iPad provide onclick event handler
if (navigator.userAgent.indexOf('iPad') != -1) {
    $(document).ready(function () {
        $('[onmouseover*="ShowInlinePopup"]').each(function (idx) {
            this.addEventListener('touchstart', function () { $(this).mouseover(); });
        });
    });
}

//////////////////////////////////////// ShowInlinePopup END /////////////////////////////////////////////////////


//////////////////////////////////////// ShowPopup  //////////////////////////////////////////////////////////////

//Usage 
// el : anchor element with href set to target url to be shown as popup
// w  : width
// h  : height
// main_contentId : Content id of element to be loaded
// align : Where the popup will be aligned.  Possible values are 'auto' or 'center'
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////

jQuery.ShowPopup = function (el, w, h, main_contentId, pAlign) {

    var align;
    if (hs == 'undefined')
    { alert('Please include Highslide script '); return; }

    align = pAlign;
    if (align == undefined)
        align = 'auto';

    if (main_contentId != undefined) {
        //var wrapperId = CreateInlinePopupWrapper();
        hs.htmlExpand(el, { contentId: main_contentId, maincontentId: main_contentId, width: w, height: h, align: align });
        CloseOnBlur(el)
    }


    hs.dimmingOpacity = 0.25; // slightly dim background
    //Create a reusable popup wrapper
    if (typeof (w) != "undefined" && typeof (h) != "undefined")
        return hs.htmlExpand(el, { objectType: 'iframe', width: w, height: h, align: align });
    else if (typeof (w) == "undefined")
        return hs.htmlExpand(el, { objectType: 'iframe', height: h, align: align });
    else if (typeof (h) == "undefined")
        return hs.htmlExpand(el, { objectType: 'iframe', width: w, align: align });
    else
        return hs.htmlExpand(el, { objectType: 'iframe', align: align });

}
//////////////////////////////////////// ShowPopup END ////////////////////////////////////////////////////////////



//Creates wrapper with close button and Move handle
function CreateExternalPopupWrapper() {

    var wrapper_id = "my-external-popup-content-wrapper";
    if ($("#" + wrapper_id).length == 0) {

        var wrapperDIV = "<div class=\"highslide-html-content\" id=\"" + wrapper_id + "\">";
        wrapperDIV += " <div align=\"right\" style=\"height:20px; padding: 2px;\"> "
        wrapperDIV += "<a href=\"#\" onclick=\"return hs.close(this)\" class=\"control\"><img src=\"../resources/icons/close_popup.gif\" border=\"0\" alt=\"Close\" /></a>";
        wrapperDIV += "<a href=\"#\" onclick=\"return false\" class=\"highslide-move control\"><img src=\"../resources/icons/move.gif\" border=\"0\" alt=\"Click and drag to move around\" /></a>";
        wrapperDIV += "</div>";
        wrapperDIV += "<div class=\"highslide-body\" style='padding:0px 10px 0px 10px;'>";
        wrapperDIV += "</div></div>";
        $(wrapperDIV).appendTo("body");
    }
    return wrapper_id;
}




function CreateInlinePopupWrapper(showClose, bodyContent) {
    if (typeof (showClose) == "undefined") showClose = true;

    var wrapper_id = "my-popup-content-wrapper";
    var wrapper_body_id = "my-popup-content-wrapper-body";
    if ($("#my-popup-content-wrapper").length == 0) {
        var wrapperDIV = "<div class=\"highslide-html-content\" id=\"" + wrapper_id + "\">";
        if (showClose) {
            wrapperDIV += " <div align=\"right\"> "
            wrapperDIV += " <img src=\"../resources/icons/close_popup.gif\" style=\"cursor:hand\" onclick=\"hs.close(this)\" alt=\"Close\" width=\"16\" height=\"16\" border=\"0\" />";
            wrapperDIV += "</div>";
        }
        wrapperDIV += "<div id=\"" + wrapper_body_id + "\"  class=\"highslide-body\" style='padding:0px 10px 0px 10px;'>";
        if (bodyContent)
            wrapperDIV += bodyContent;

        wrapperDIV += "</div></div>";
        $(wrapperDIV).appendTo("body");
    }

    if (bodyContent)
        $("#" + wrapper_body_id).html(bodyContent);


    return wrapper_id;
}


//use this for creating new wrapper for each 'id'

function CreateInlineWrapper(id, bodyContent) {
    var showClose = true;

    var wrapper_id = "my-popup-content-wrapper" + id;
    var wrapper_body_id = "my-popup-content-wrapper-body" + id;


    if ($("#my-popup-content-wrapper").length == 0) {
        var wrapperDIV = "<div class=\"highslide-html-content\" id=\"" + wrapper_id + "\">";
        if (showClose) {
            wrapperDIV += " <div align=\"right\"> "
            wrapperDIV += " <img src=\"../resources/icons/close_popup.gif\" style=\"cursor:hand\" onclick=\"hs.close(this)\" alt=\"Close\" width=\"16\" height=\"16\" border=\"0\" />";
            wrapperDIV += "</div>";
        }
        wrapperDIV += "<div id=\"" + wrapper_body_id + "\"  class=\"highslide-body\" style='padding:0px 10px 0px 10px;'>";
        if (bodyContent)
            wrapperDIV += bodyContent;

        wrapperDIV += "</div></div>";
        $(wrapperDIV).appendTo("body");
    }

    return wrapper_id;
}






//Close all highslide popups or a given popup
function ClosePopup(el) {
    for (var i = 0; i < hs.expanders.length; i++) {
        if (el) {
            if (hs.expanders[i] && hs.expanders[i].a && hs.expanders[i].a == el)
                hs.expanders[i].close();
        }
        else {
            if (hs.expanders[i])
                hs.expanders[i].close();
        }
    }
}



function CloseOnBlur(el) {
    for (var i = 0; i < hs.expanders.length; i++) {
        if (el) {
            if (hs.expanders[i] && hs.expanders[i].a && hs.expanders[i].a == el) {

                $(hs.expanders[i]).blur(function () { alert('on blur'); });
            }
        }

    }
}


//01/16/2009 Chandra.B
//Use this function to lock a section of UI from user interaction
//Usage:
//target_el_id : id of the element that needs to be locked 
//background: background color for overlay
var blocking_div_class = "blockingdiv";

jQuery.CreateBlockingOverlay = function (target_el_id, msg, background) {

    if (typeof (msg) == "undefined")
        msg = "For display only.  User interaction is not allowed in this mode.";

    if (!background)
        background = "#777";
    var target_el = $("#" + target_el_id);
    if (target_el.length == 0) return;
    var blocking_el_id = target_el_id + "_blocking_div";
    //Remove blocking overlay if its already added
    if ($("#" + blocking_el_id).length > 0)
        $("#" + blocking_el_id).remove();
    //Create overlay DIV
    var transperantDIV_HTML = "<DIV id='" + blocking_el_id + "'  class='" + blocking_div_class + "'> </DIV>";
    $(transperantDIV_HTML).appendTo("body")
                         .css({ "width": target_el.width() + 4,
                             "height": target_el.height() + 4,
                             "top": target_el.position().top - 2,
                             "left": target_el.position().left - 2,
                             "position": "absolute",
                             "background": background,
                             "filter": "alpha(opacity=55)",
                             //"filter":"progid:DXImageTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75",
                             "opacity": "0.1",
                             "zIndex": "10000"
                         });

    //Add onclick event
    //debug;
    var blocking_msg_id = "blocking_div_msg";
    if ($('#' + blocking_msg_id).length == 0)
        $("<div id='" + blocking_msg_id + "' class='\"highslide-maincontent\"' style='padding:10px 10px 0px 10px;'>" + msg + " </div>").appendTo("body");

    $("#" + blocking_el_id).click(
            function () {
                //debug;
                $.ShowInlinePopup($('#' + blocking_el_id)[0], blocking_msg_id, 0, 5000, 200, 50, false);
            });

}

//function to remove all blocking overlays on page
jQuery.RemoveAllBlockingOverlays = function () { $("." + blocking_div_class).remove(); }



//02/04/09 Chandra.B
// Highlight the rows on mouseover and optionally selects a row when a child element is clicked
//Usage:
// target_table_id : table element Id
// child_select_el : jquery object for child elements in the table, On clicking the element its parent row is highlighted
//    $("#" + SelectAllCheckBoxId).live("click", function() {


jQuery.HighlightOnMouseOver = function (target_table_id, child_select_el, target_tr_name) {

    var style = "alternatelisthighlighted";
    if (typeof (target_tr_name) != "undefined") {
        $("#" + target_table_id + " tr[name='" + target_tr_name + "']").live("mouseover", function () { $(this).addClass(style); }).live("mouseout", function () { $(this).removeClass(style); });
    }
    else {
        $("#" + target_table_id + " tr").live("mouseover", function () { $(this).addClass(style); }).live("mouseout", function () { $(this).removeClass(style); });
    }


    //bold on click
    if (typeof (child_select_el) != "undefined") {

        $(child_select_el).live("click", function () {
            $("#" + target_table_id + " tr").removeClass("highlight2Bold");
            //highlight selected row
            $(this).parents("tr").filter(':first').addClass("highlight2Bold");
        });
    }
};


//02/08/09 Chandra.B
//simple toggle
jQuery.ToggleItem = function (target_el_prefix, num) {
    if ($("#" + target_el_prefix + num).css("display") == "none") {
        $("#" + target_el_prefix + num).show();
        $("#" + target_el_prefix + "Image" + num).attr("src", "../resources/icons/minus.gif");
    }
    else {
        $("#" + target_el_prefix + num).hide();
        $("#" + target_el_prefix + "Image" + num).attr("src", "../resources/icons/plus.gif");
    }
};



//02/08/09 Chandra.B
//Resize Highslide Popup
//This script is helpful for resizing iframe popup 
jQuery.ResizeHighslide = function (w, h) {
    var exp = hs.getExpander();
    exp.iframe.style.height = h;
    exp.reflow();
};


//02/11/09 Chandra.B
// Show Client messages , 
// useful for AJAX pages that need to use javascript to display messages
// Usage:
// target_el_id     : id of the container element for displaying the messag (DIV or SPAN)
// msg              : message to be displayed
// display_duration (optional) : after this duration message is hidden
// cssClass (optional)         : css class to be applied to the container element
// img_src  (optional)         : icon to prefix the message

//Generic message
jQuery.ShowMessage = function (target_el_id, msg, display_duration, cssClass, img_src) {
    if (typeof (img_src) != "undefined")
        msg = "<img src='" + img_src + "' border=0/> &nbsp;" + msg;

    $("#" + target_el_id).html(msg);
    $("#" + target_el_id).addClass(cssClass);
    $("#" + target_el_id).css({ "padding-top": "10px", "padding-bottom": "5px" });

    $("#" + target_el_id).hide();
    $("#" + target_el_id).fadeIn();


    $(document).click(function () {
        $("#" + target_el_id).hide();
    });

    if (typeof (display_duration) != "undefined" && display_duration > 0)
        setTimeout(function () { $("#" + target_el_id).fadeOut(); }, display_duration);
}


jQuery.ShowInfo = function (target_el_id, msg, display_duration) {
    $.ShowMessage(target_el_id, msg, display_duration, "success", "../resources/icons/ActionResultMessage.gif");
}
jQuery.ShowWarning = function (target_el_id, msg, display_duration) {
    $.ShowMessage(target_el_id, msg, display_duration, "warning", "../resources/icons/ActionResultMessageWarning.gif");
}
jQuery.ShowError = function (target_el_id, msg, display_duration) {
    $.ShowMessage(target_el_id, msg, display_duration, "error", "../resources/icons/ActionResultMessageError.gif");
}

//Need to test this
jQuery.Sleep = function (DelayIn_ms) {
    var exitSleep = false;
    (function () {
        if (!exitSleep) {
            exitSleep = true;
            setTimeout(arguments.callee, DelayIn_ms);
        }
    })();
}


//Find image size on client side                
jQuery.GetImageSize = function (url) {
    var dimensions = { width: 0, height: 0 };
    //create a hidden DIV with image url
    var hiddenDiv = "<div id='divImageSize' style='visibility: hidden;position:absolute;'>";
    hiddenDiv += "<img  src=\"" + url + "\">";
    hiddenDiv += "</div>";
    $(hiddenDiv).appendTo("body");

    //wait 100ms to let the image load
    //Make Async request to load the new items
    //  jQuery.Sleep(100);

    var exitSleep = false;
    (function () {
        if (!exitSleep) {
            exitSleep = true;
            setTimeout(arguments.callee, 50);
        }
    })();



    //now find DIV dimension give the image size.
    dimensions.width = $("#divImageSize").width();
    dimensions.height = $("#divImageSize").height();
    //remove the DIV from document
    $("#divImageSize").remove();
    return dimensions;
};

// highlights the row with focus on a input form
// usage : 
// parentClass : css class of the container element
jQuery.HighlightContextRow = function (parentClass) {

    var selector = "." + parentClass + " input ," + "." + parentClass + " textarea," + "." + parentClass + " select";

    $(selector).focus(function () {
        $(this).parents('tr').addClass("normallisthighlighted");
    }).blur(function () {
        $(this).parents('tr').removeClass("normallisthighlighted");
    });

};


var firstClick = 0;
var checkboxStatus;


//////////////////////////////// 4/01/09 HighlightSelectedRow //////////////////////////////
//4/01/09 VB
//Highlights a row with checkbox when selected
//Usage: $.HighlightSelectedRow("InventoryIds");
jQuery.HighlightSelectedRow = function (checkboxName, delegateValidationFunction) {

    $("input[name='" + checkboxName + "']").live("click", function () {

        //check delegate
        if (delegateValidationFunction != null && this.checked) {
            if (!delegateValidationFunction(this)) {
                this.checked = false;
                return;
            }
        }

        $(this).parents('TR:first').removeClass("highlight2Bold");


        $("input[name='" + checkboxName + "']:checked").each(function () {
            $(this).parents('tr:first').addClass("highlight2Bold");
        });

        //Add shift key code here.............................................
        if (window.event) {
            var shift = window.event.shiftKey;

            if (firstClick == 0) {
                firstClick = getIndexByNameAndValue(this.name, this.value);
                checkboxStatus = this.checked;
            } else {
                if (shift) {
                    CheckAllItemsInRange(firstClick, getIndexByNameAndValue(this.name, this.value), delegateValidationFunction, this.checked);
                }
                firstClick = 0;
            }
        }

    });
};
//////////////////////////////// 4/01/09 HighlightSelectedRow END //////////////////////////////




//////////////////////////////// 5/3/2011 ValidateDeleteOnButtonClick //////////////////////////////
//5/3/2011 VB
//Confirms delete on selected items.
//Usage: $.ValidateDeleteOnButtonClick("ItemIds", "<%=lnkDelete.ClientID %>");
jQuery.ValidateDeleteOnButtonClick = function (checkboxName, buttonId) {

    $("#" + buttonId).live("click", function () {
        if ($(":checkbox[name='" + checkboxName + "']:checked").length == 0) {
            alert("Please select item(s) to delete.");
            return false;
        }
        else if (!confirm("Are you sure you want to delete selected items?"))
            return false;

        return true;

    });
};
//////////////////////////////// 5/3/2011 ValidateDeleteOnButtonClick END ///////////////////////////


function getIndexByNameAndValue(name, value) {
    var numItems = document.getElementsByName(name).length;
    var checkboxes = document.getElementsByName(name);

    for (var i = 0; i < numItems; i++) {
        if (checkboxes[i] && checkboxes[i].name == name && checkboxes[i].value == value) {
            return (i);
        }
    }
}

function CheckAllItemsInRange(startIndex, endIndex, delegateValidationFunction, onOrOff) {
    var temp;
    var CurrentIndex;
    if (endIndex < startIndex) { temp = startIndex; startIndex = endIndex; endIndex = temp; } //lesser index first

    $(":checkbox").each(function () {
        CurrentIndex = getIndexByNameAndValue(this.name, this.value);
        if (CurrentIndex >= startIndex && CurrentIndex <= endIndex && this.checked != checkboxStatus) {
            //check validation delegate
            if (delegateValidationFunction != null) {
                if (!delegateValidationFunction(this)) {
                    return false; //break out of the each loop
                }
            }
            this.checked = checkboxStatus;
            $(this).parents('tr:first').addClass("highlight2Bold");
        }
    });
}

//4/01/09 VB
//Select all checkboxes
//Usage: $.ToggleSelectAll("chkSelectAll", "InventoryIds");
jQuery.ToggleSelectAll = function (SelectAllCheckBoxId, ChildCheckBoxName) {
    $("#" + SelectAllCheckBoxId).live("click", function () {

        var checked_status = this.checked;
        $("input[name='" + ChildCheckBoxName + "']").each(function () {
            if (!$(this).attr("disabled")) {
                this.checked = checked_status;
                if (this.checked) {
                    $(this).parents('tr:first').addClass("highlight2Bold");
                }
                else {
                    $(this).parents('tr:first').removeClass("highlight2Bold");
                }
            }
        });
    });
}

//04/02/09 Chandra.B
// Use this function to restrict user from selecting same values 
// for two dropdown boxes.
//Usage:
// id1 : client id of first dropdown
// id2 : client id of second dropdown
// ex : Core/MaintainUser.aspx

var lastselectedItems = new Array();
jQuery.ValidateDropdownDistinctValues = function (id1, id2, msg) {
    var key = id1 + "_" + id2;

    //store last selected item in an array
    $("#" + id1 + ",#" + id2).click(function () {
        lastselectedItems[key] = $("option:selected", this);
    });

    //if selected values in both dropdowns match, restore the last selected value
    $("#" + id1 + ",#" + id2).change(function () {
        if ($("#" + id1 + " option:selected").val() == $("#" + id2 + " option:selected").val() && $("#" + id2 + " option:selected").val() != "0") {
            alert(msg);
            $(this).val(lastselectedItems[key].val());
        }
    });
};


//////////////////////////////// 04/02/09 ValidateDuplicate /////////////////////////////////////////////////
//04/02/09 Chandra.B
// Use this function to warn user of duplicate value while entering data into
// textbox that should contain unique value.
// Implement a static webmethod in code-behind page that returns a boolean value
//  true: Textbox value is duplicate
//  false: Textbox value is not duplicate
// 
// Usage:
// textbox_id : client id of textbox that need to be validated 
// ajax_url   : url to the static webmethod
// json_params : parameter,value pair for above method in array  ex : {'param1':value1,'param2':value2}
// value_param_name : name of the static method parameter that takes the value entered in textbox
// fn_callback : callback method with  return value from the server static webmethod as input parameter
// ex : Core/MaintainUser.aspx
//

jQuery.ValidateDuplicate = function (textbox_id, ajax_url, json_params, value_param_name, fn_callback, custom_validator) {

    $("#" + textbox_id).bind("keyup change blur", function () {

        json_params[value_param_name] = $("#" + textbox_id).val();

        $.ajax({
            type: "POST",
            url: ajax_url,
            data: SerializeJson(json_params),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                var return_flag = (msg.d.length ? msg.d[0] : msg.d);
                if (fn_callback != 'undefined')
                    fn_callback.call(msg.d, return_flag, msg.d);

                if (return_flag) {
                    $("#" + textbox_id).addClass("highlighterror");
                    $("#" + textbox_id).parents("tr").find(".error").show();
                }
                else {
                    $("#" + textbox_id).removeClass("highlighterror");
                    $("#" + textbox_id).parents("tr").find(".error").hide();
                }
            }
        });
    });

}

var AjaxValidationResult = new Array();

jQuery.AjaxValidateControl = function (textbox_id, ajax_url, json_params, value_param_name, fn_callback) {

    var control_parameter_marker = "$$$!!!";
    $("#" + textbox_id).bind("keyup change blur", function () {

        var json_string = "";
        var control_value = $("#" + textbox_id).val();
        // control_value = control_value.replace(/'/g, "\'");
        // alert(control_value);
        if (value_param_name != undefined) {
            json_params[value_param_name] = control_value;
            json_string = SerializeJson(json_params);
        }
        else {
            json_string = SerializeJson(json_params);
            //replace control parameter position holder with actual value
            json_string = json_string.replace(control_parameter_marker, control_value);
        }

        $.ajax({
            type: "POST",
            url: ajax_url,
            data: json_string,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                var return_flag = (msg.d.length ? msg.d[0] : msg.d);
                AjaxValidationResult[textbox_id] = return_flag;
                if (fn_callback != undefined)
                    fn_callback.call(msg.d, return_flag, msg.d);

                if (return_flag) {
                    $("#" + textbox_id).addClass("highlighterror");
                    $("#" + textbox_id).parents("tr").find(".error").show();
                }
                else {
                    $("#" + textbox_id).removeClass("highlighterror");
                    $("#" + textbox_id).parents("tr").find(".error").hide();
                }
            }
        });
    });

}
//////////////////////////////// 04/02/09 ValidateDuplicate END //////////////////////////////////////////////



function SerializeJson(json_obj) {

    if (window && window.JSON && window.JSON.stringify) {
        return JSON.stringify(json_obj);
    }

    var json_string = "";
    for (var key in json_obj) {
        json_string += (json_string == "" ? "" : ",");
        json_string += '"' + key + '":' + SerializeArrayToJson(json_obj[key]);
    }
    return "{" + json_string + "}";

}

function SerializeArrayToJson(jsObject) {

    if (jsObject.length && jsObject[0] != undefined) {
        var tempstring = "";
        for (var i = 0; i < jsObject.length; i++) {
            tempstring += (tempstring == "" ? "" : ",");
            tempstring += '"' + jsObject[i] + '"';
        }
        return "[" + tempstring + "]";
    }
    else
        return '"' + jsObject + '"';
}



//////////////////////////////////// DATE FUNCTIONS ////////////////////////////////////////////

var m_names = new Array("Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec");


jQuery.FormatJsonDate = function (jsonDate) {
    var d = new Date(parseInt(jsonDate.replace("/Date(", "").replace(")/", ""), 10));
    var curr_date = d.getDate();
    var curr_month = d.getMonth();
    var curr_year = d.getFullYear();

    return curr_date + "-" + m_names[curr_month] + "-" + curr_year

}


//Converts a Projectmates Date format to JavaScript Date object
jQuery.ConvertProjectmatesDateToClientDate = function (serverDate) {
    var dateTokens = serverDate.split("-");
    if (dateTokens.length >= 3) {
        if (dateTokens[0].length == 2 && dateTokens[0].substring(0, 1) == "0") {
            dateTokens[0] = dateTokens[0].substring(1, 2);
        }
        var day = parseInt(dateTokens[0]);
        var year = parseInt(dateTokens[2]);
        var month = GetMonth(dateTokens[1]);
        return new Date(year, month, day);
    } else
        return null;
}

//Formats javascript Date Object into Projectmates Date (ex: 01-Jan-2009)
jQuery.ConvertClientDateToProjectmatesDate = function (clientDate) {
    var curr_date = clientDate.getDate();
    var curr_month = clientDate.getMonth();
    var curr_year = clientDate.getFullYear();
    return curr_date + "-" + m_names[curr_month] + "-" + curr_year
}

//Converts month string into a number from 0-11
function GetMonth(month) {
    for (var i = 0; i < 12; i++)
        if (m_names[i].toLowerCase() == month.toLowerCase())
            return i;
}
//////////////////////////////////// DATE FUNCTIONS END ////////////////////////////////////////

//Disable ASP.NET client validation.
//Useful when cancelling an insert
jQuery.DisableClientValidation = function () {
    for (var i = 0; i < Page_Validators.length; i++) {
        ValidatorEnable(Page_Validators[i], false);
    }

}

//Enable ASP.NET client validation
jQuery.EnableClientValidation = function () {
    for (var i = 0; i < Page_Validators.length; i++) {
        ValidatorEnable(Page_Validators[i], true);
    }

}

//////////////////////////////////// 05/04/09 ComputeTotal ////////////////////////////////////////////
//05/04/09 - Chandra.Bhumireddy
// Use this function automatically calculate and populate a total field
// Sum is re-calculated and populated into Total field on 'blur' event of each input textbox
// 
//Parameters:
// inputIds : Comma separated client ids of input textboxes whose sum needs to be calculated.
// targetid: Client Id of the Total field.
// Usage :Check  InitializeTotalCalculation() method in  Timesheet/TimesheetInsertTemplate.ascx.cs file
///////////////////////////////////////////////////////////////////////////////////////////////////////

jQuery.ComputeTotal = function (inputIds, targetid) {
    var idsArray = inputIds.split(",");
    for (var i = 0; i < idsArray.length; i++) {
        $("#" + idsArray[i]).keyup(function () {
            HandleComputeTotal(idsArray, targetid);
        });
    }
};

//helper function for ComputeTotal() plugin method
function HandleComputeTotal(idsArray, targetId) {
    var total = 0;
    for (var i = 0; i < idsArray.length; i++) {
        var val = $("#" + idsArray[i]).val();
        val = parseFloat(val);
        if (val != "" && !isNaN(val))
            total += val;
    }
    $("#" + targetId).val(total);
};
//////////////////////////////////// 05/04/09 ComputeTotal End /////////////////////////////////////////


//Displays project profile in a highslide popup
//el : element to click
//ProjectId : ProjectId

jQuery.ShowProjectProfile = function (el, ProjectId) {

    $.ajax({
        type: "POST",
        url: "../Core/AjaxUIHelper.aspx/GetProjectProfileHTML",
        data: "{'ProjectId':" + ProjectId + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            // Populate master budget details
            var highslideWrapper = CreateInlineWrapper(ProjectId, msg.d)
            hs.htmlExpand(el, { contentId: highslideWrapper, width: 350 });
        }
    });
}




jQuery.ShowModuleCommentsLink = function (spanId) {
    $.ajax({
        type: "POST",
        url: "../Core/AjaxUIHelper.aspx/GetModuleCommentsLinkHTML",
        data: "{'PageUrl':'" + document.location.toString() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            // Populate master budget details
            $("#" + spanId).html(msg.d);
        }
    });
}



//use this to force all links to open in a new window
jQuery.ForceLinksInNewWindow = function () {
    $("a").each(function () { $(this).attr('target', '_blank'); });
}


jQuery.RemoveAllImages = function () {
    $("img").each(function () { $(this).remove() });
}


///////////////////////////////////// QUERYSTRING MANIPULATION //////////////////////////////////////////

jQuery.GetQSValue = function (name) {
    var qs_string = window.location.search.substring(1);
    var qs_tokens = qs_string.split("&");
    for (i = 0; i < qs_tokens.length; i++) {
        var qs_token = qs_tokens[i].split("=");
        if (qs_token[0] == name) {
            return qs_token[1];
        }
    }
}

/*  Replaces single QS value
      ADDED BY: VB 06/24/2011
      USAGE: $.ReplaceQSValue("http://www.google.com?q1=aaa&q2=bbb", "q1", "ccc")
      This will replace "aaa" with "ccc"
*/
jQuery.ReplaceQSValue = function (url, key, value) {
    var re = new RegExp("([?|&])" + key + "=.*?(&|$)", "i");
    if (url.match(re))
        return url.replace(re, '$1' + key + "=" + value + '$2');
    else if (url.indexOf("?") == -1)
        return url + '?' + key + "=" + value;
    else
        return url + '&' + key + "=" + value;
}

/*  Removes single QS Key and value
ADDED BY: VB 06/24/2011
USAGE: $.RemoveQSKey(http://www.google.com?q1=aaa&q2=bbb, "q1");
This will remove "q1" key and value.  Useful when posting URL repeatedly.
*/
jQuery.RemoveQSKey = function (url, key) {
    if (url.indexOf(key) > 0) {
        var q = "";
        var pos1 = url.indexOf(key);

        if (url.indexOf("&", pos1) > 0) {
            var pos2 = url.indexOf("&", pos1);
            q = url.substring(pos1, pos2 + 1);
        }
        else {
            q = url.substring(pos1-1);
        }
        url = url.replace(q, "");
    }
    return url;
}

//Reloads current page with new QS value
jQuery.ReloadWithQSValue = function (name, value) {

    var qs_string = window.location.search.substring(1);
    var qs_found = false;
    var new_qs_string = "";

    if (qs_string != "") {
        var qs_tokens = qs_string.split("&");
        for (i = 0; i < qs_tokens.length; i++) {
            var qs_token = qs_tokens[i].split("=");
            if (qs_token[0] == name) {
                qs_token[1] = encodeURIComponent(value);
                qs_tokens[i] = qs_token[0] + "=" + qs_token[1];
                qs_found = true;
                break;
            }
        }
        //now build new query string
        for (i = 0; i < qs_tokens.length; i++)
            new_qs_string += (new_qs_string == "" ? "" : "&") + qs_tokens[i];
    }

    if (!qs_found)
        new_qs_string += (new_qs_string == "" ? "" : "&") + name + "=" + value;

    var href_original = document.location.href;
    var fullpath = href_original.replace("?" + qs_string, "");

    //reload page with new QS
    window.location.href = fullpath + "?" + new_qs_string;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////// 05/06/2011 UnSaveCheck ////////////////////////////////////////////
// Use this function automatically detect if any changes were made on the page and not saved.
// Works on Select, TextArea, TextBox controls.
// The function also detects if any changes were made in tinyMCE.
// 
// Autors:  VB, Naresh
//Parameters:
// elementId:   Any element that has child form elements with input parameters.
//
// Usage:       $.UnSaveCheck("aspnetForm");
// INCOMPLETE:  DOES NOT WORK FOR SAFARI
///////////////////////////////////////////////////////////////////////////////////////////////////////

function ResetFieldValueWatcher() {
    $('#FieldValueWatcher').val(0);
}

function SetFieldValueWatcher() {
    $('#FieldValueWatcher').val(1);
}

jQuery.UnSaveCheck = function (elementId) {
    var $inputFld = $('<input type="hidden" id="FieldValueWatcher" />');
    $('body').append($inputFld);

    $(document).ready(function () {
        $('#FieldValueWatcher').val(0);


        $("#" + elementId).live("change", function () {
            $('#FieldValueWatcher').val(1);
        });

    });

    $(window).bind('beforeunload', function () {
        if (typeof tinyMCE != "undefined") {
            $(tinyMCE.editors).each(function () {
                if (this.isDirty()) { $('#FieldValueWatcher').val(1); };
            });
        }

        if ($('#FieldValueWatcher').val() == 1) {
            return "You have changed form data. All of your changes will be lost if you click OK.";
            $('#FieldValueWatcher').val(0);
            setTimeout("SetFieldValueWatcher()", "100");
        }
    });
}
/////////////////////////////////////05/06/2011 UnSaveCheck END /////////////////////////////////////////

//////////////////////////////////// 11/01/2011 Uncheck radio button ////////////////////////////////////////////
// Use this function to automatically uncheck an already checked radio button
jQuery.UncheckRadioButton = function () {
    $("input[type='radio']:checked").addClass('IsCheckedClass');
    $("input[type='radio']").click(function (event) {
        if ($(this).hasClass('IsCheckedClass')) {//.attr('checked')
            $(this).attr('checked', false);
            $(this).removeClass('IsCheckedClass');
        }
        else {
            $(this).attr('checked', true);
            $("input[name='" + $(this).attr('name') + "']").removeClass('IsCheckedClass');
            $(this).addClass('IsCheckedClass');
        }
    });
}

///////////////////////////////////////////////////////////////////////////////////////////////////////

