﻿// This file is intented to be a centralized place to introduce customizations for jQuery and its addons

// some useful GN code which uses jQuery addons
GNscript.BlockedElements = new Object();

// blocks UI element
GNscript.BlockElement = function(elementToBlock, message, delay) {
    if (!delay && message && !isNaN(message)) {
        delay = message;
    }

    if (message == null || !isNaN(message)) {
        message = "Processing...";
    }

    var blockUIHtml = "<div class='blockElement'><h1>" + message + "</h1></div>";

    if (!delay) {
        $(elementToBlock).block({ message: $(blockUIHtml) });
    }
    else {
        GNscript.BlockedElements[elementToBlock] = elementToBlock;

        setTimeout(function() {
        if (GNscript.BlockedElements[elementToBlock]) {
            $(elementToBlock).block({ message: $(blockUIHtml) });
            }
        }, delay);
    }
}

// unblock UI element
GNscript.UnblockElement = function(elementToBlock) {
    GNscript.BlockedElements[elementToBlock] = null;
    $(elementToBlock).unblock();
}

// callback result analyzer
// returns false if an error was found in server response
GNscript.CallbackResultAnalyzer = function(serverResponse) {
    if (serverResponse && serverResponse != "") {
        result = JSON.parse(serverResponse);

        // check if operation was successfull
        if (result.ErrorMessage) {
            GNscript.ShowErrorMessageDialog(result.ErrorMessage, result.ErrorDetails);
            return false;
        }

        // check if server passed a notification to user
        if (result.MessageToUser) {
            GNscript.ShowPopupMessage({ message: result.MessageToUser, timeout: 5, className: 'notificationMessage' });
        }
    }
    
    return true;
}

GNscript.ShowPopupMessage = function(parameters) {
    $.achtung(parameters);
}

// callback chain
// after response comes from server it gets analyzed by GNscript.CallbackResultAnalyzer
// call example:
//GNscript.CallbackChain
//            (
//                {
//                    onSuccess: someFunction, // or functions array like [function1, function2]
//                    onServerError: someFunction, // or functions array like [function1, function2]
//                    executeAfter: someFunction, // or functions array like [function1, function2]
//                }
//            )
// * onSuccess function is executed if server call was successfull
// * onServerError function is executed if server call was unsuccessfull
// * executeAfter function is executed after onSuccess or onServerError functions
// * none of the onSuccess, onServerError and executeAfter parameters is obligatory, you just specify those you need
//      remember that response is always analyzed by GNscript.CallbackResultAnalyzer which displays error message to user
//      if call was unsuccessfull, so you do not need to specify onServerError parameter to show error message to user,
//      you only specify onServerError parameter if you need to perform some additional actions
// * executeAfter is a nice place to put code which should be executed regardless of was server call successfull of unsuccessfull,
//      like unblocking user interface
GNscript.CallbackChain = function(options)
{
    var chain =
        {
            Callback: function(serverResponse)
            {
                var callWasSuccessfull = GNscript.CallbackResultAnalyzer(serverResponse); // call standard callback handler

                if (options)
                {
                    if (callWasSuccessfull && options.onSuccess) // call additional callback handlers
                    {
                        if (options.onSuccess instanceof Array)
                        {
                            for (var i = 0; i < options.onSuccess.length; i++)
                            {
                                if (options.onSuccess[i])
                                {
                                    options.onSuccess[i](serverResponse);
                                }
                            }
                        }
                        else
                        {
                            options.onSuccess(serverResponse);
                        }
                    }

                    if (!callWasSuccessfull && options.onServerError) // see if we have registered error handler
                    {
                        if (options.onServerError instanceof Array)
                        {
                            for (i = 0; i < options.onServerError.length; i++)
                            {
                                if (options.onServerError[i])
                                {
                                    options.onServerError[i](serverResponse);
                                }
                            }
                        }
                        else
                        {
                            options.onServerError(serverResponse);
                        }
                    }

                    if (options.executeAfter) // see if we have registered error handler
                    {
                        if (options.executeAfter instanceof Array)
                        {
                            for (i = 0; i < options.onServerError.length; i++)
                            {
                                if (options.onServerError[i])
                                {
                                    options.onServerError[i](serverResponse);
                                }
                            }
                        }
                        else
                        {
                            options.executeAfter(serverResponse);
                        }
                    }
                }
            }
        };

    return chain;
}

// show error message dialog
GNscript.ShowErrorMessageDialog = function(message, errorDetails)
{
    $('<div id="errorMessageDialog"></div>')
	    .html('<p class="errorMessage" id="errorMessage"><span class="errorIcon"/>' + message + "</p>")
	    .dialog(
	    {
	        title: "An error occurred during processing your request",
	        modal: true,
	        width: 550,
	        buttons:
	            {
	                "Ok": function()
	                {
	                    $(this).dialog("close");
	                    $("#errorMessageDialog").remove();
	                },
	                "Show error details": function(id)
	                {
	                    if (!GNscript.ErrorDetailsShown)
	                    {
	                        $("<div id='errorDetails' class='errorDetails'>" + errorDetails + "</div>")
	                                .insertAfter("#errorMessage");
	                    }
	                    else
	                        $("#errorDetails").remove();

	                    GNscript.ErrorDetailsShown = !GNscript.ErrorDetailsShown;
	                    id.currentTarget.children[0].innerHTML = (GNscript.ErrorDetailsShown ? "Hide" : "Show") + " error details";
	                } 
	            }
	    });

    GNscript.ErrorDetailsShown = false;
}

// jqGrid customization
$.fn.extend({
	/*
	*  
	* The toolbar has the following properties
	*	id of top toolbar: t_<tablename>
	*	id of bottom toolbar: tb_<tablename>
	*	class of toolbar: ui-userdata
	* elem is the toolbar name to which button needs to be added. This can be 
	*		#t_tablename - if button needs to be added to the top toolbar
	*		#tb_tablename - if button needs to be added to the bottom toolbar
	*/
	toolbarButtonAdd: function(elem,p){
		p = $.extend({
		caption : "newButton",
		title: '',
		buttonicon : 'ui-icon-newwin',
		onClickButton: null,
		position : "last"
	}, p ||{});
	var $elem = $(elem);
	var tableString="<table style='float:left;table-layout:auto;' cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class='ui-toolbar-table'>";
	tableString+="<tbody> <tr></tr></table>";
	//console.log("In toolbar button add method");
		/* 
		* Step 1: check whether a table is already added. If not add
		* Step 2: If there is no table already added then add a table
		* Step 3: Make the element ready for addition to the table 
		* Step 4: Check the position and corresponding add the element
		* Step 5: Add other properties 
		*/
		//step 1 
		return this.each(function() {
			if( !this.grid)  { return; }
			if(elem.indexOf("#") != 0) { 
				elem = "#"+elem; 
			}
			//step 2
			if($(elem).children('table').length === 0){
				$(elem).append(tableString);
			}	
			//step 3
			var tbd = $("<td style=\"padding-left:1px;padding-right:1px\"></td>");
			$(tbd).addClass('ui-toolbar-button ui-corner-all').append("<div class='ui-toolbar-div'><span class='ui-icon "+p.buttonicon+"'></span>"+"<span>"+p.caption+"</span>"+"</div>").attr("title",p.title  || "")
			.click(function(e){
				if ($.isFunction(p.onClickButton) ) { p.onClickButton(); }
				return false;
			})
			.hover(
				function () {$(this).addClass("ui-state-hover");},
				function () {$(this).removeClass("ui-state-hover");}
			);
			if(p.id) {$(tbd).attr("id",p.id);}
			if(p.align) {$(elem).attr("align",p.align);}
			var findnav=$(elem).children('table');
			if(p.position ==='first'){
				if($(findnav).find('td').length === 0 ) {
					$("tr",findnav).append(tbd);
				} else {
					$("tr td:eq(0)",findnav).before(tbd);
				}
			} else {
				$("tr",findnav).append(tbd);
			}
		});
	}
});

// string prototype customization

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

