/*
 * jQuery JSON Plugin
 * version: 1.0 (2008-04-17)
 *
 * This document is licensed as free software under the terms of the
 * MIT License: http://www.opensource.org/licenses/mit-license.php
 *
 * Brantley Harris technically wrote this plugin, but it is based somewhat
 * on the JSON.org website's http://www.json.org/json2.js, which proclaims:
 * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
 * I uphold.  I really just cleaned it up.
 *
 * It is also based heavily on MochiKit's serializeJSON, which is
 * copywrited 2005 by Bob Ippolito.
 */
/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var displayErrorMessage = false;

function encode(str) {
str = str.replace('+', '%2B');
return str;
}

(function($) {
    function toIntegersAtLease(n)
    // Format integers to have at least two digits.
    {
        return n < 10 ? '0' + n : n;
    }

    Date.prototype.toJSON = function(date)
    // Yes, it polutes the Date namespace, but we'll allow it here, as
    // it's damned usefull.
    {
        return date.getUTCFullYear()   + '-' +
             toIntegersAtLease(date.getUTCMonth() + 1) + '-' +
             toIntegersAtLease(date.getUTCDate());
    };

    var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
    var meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        }

    $.quoteString = function(string)
    // Places quotes around a string, inteligently.
    // If the string contains no control characters, no quote characters, and no
    // backslash characters, then we can safely slap some quotes around it.
    // Otherwise we must also replace the offending characters with safe escape
    // sequences.
    {
        if (escapeable.test(string))
        {
            return '"' + string.replace(escapeable, function (a)
            {
                var c = meta[a];
                if (typeof c === 'string') {
                    return c;
                }
                c = a.charCodeAt();
                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) + '"'
        }
        return '"' + string + '"';
    }

    $.toJSON = function(o)
    {
        var type = typeof(o);

        if (type == "undefined")
            return "undefined";
        else if (type == "number" || type == "boolean")
            return o + "";
        else if (o === null)
            return "null";

        // Is it a string?
        if (type == "string")
        {
            return $.quoteString(o);
        }

        // Does it have a .toJSON function?
        if (type == "object" && typeof o.toJSON == "function")
            return o.toJSON();

        // Is it an array?
        if (type != "function" && typeof(o.length) == "number")
        {
            var ret = [];
            for (var i = 0; i < o.length; i++) {
                ret.push( $.toJSON(o[i]) );
            }
            return "[" + ret.join(", ") + "]";
        }

        // If it's a function, we have to warn somebody!
        if (type == "function") {
            throw new TypeError("Unable to convert object of type 'function' to json.");
        }

        // It's probably an object, then.
        ret = [];
        for (var k in o) {
            var name;
            var type = typeof(k);

            if (type == "number")
                name = '"' + k + '"';
            else if (type == "string")
                name = $.quoteString(k);
            else
                continue;  //skip non-string or number keys

            val = $.toJSON(o[k]);
            if (typeof(val) != "string") {
                // skip non-serializable values
                continue;
            }

            ret.push(name + ": " + val);
        }
        return "{" + ret.join(", ") + "}";
    }

    $.evalJSON = function(src)
    // Evals JSON that we know to be safe.
    {
        return eval("(" + src + ")");
    }

    $.secureEvalJSON = function(src)
    // Evals JSON in a way that is *more* secure.
    {
        var filtered = src;
        filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
        filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
        filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');

        if (/^[\],:{}\s]*$/.test(filtered))
            return eval("(" + src + ")");
        else
            throw new SyntaxError("Error parsing JSON, source is not valid.");
    }
})(jQuery);

function StartHandling(controlName,waitText)
{
    $("#"+controlName+'_validationMsg').removeClass('validatingObjectOK');
    $("#"+controlName+'_validationMsg').removeClass('validatingObjectError');
    $("#"+controlName+'_validationMsg').text(waitText);
    $("#"+controlName+'_validationMsg').addClass('validatingObjectProcess');
}

function StopHandling(controlName)
{
    $("#"+controlName+'_validationMsg').removeClass('validatingObjectProcess');
    $("#"+controlName+'_validationMsg').text('');
}

function HandleAsError(controlName,errorMsg)
{
    $("#"+controlName+'_validationMsg').removeClass('validatingObjectOK');
    $("#"+controlName+'_validationMsg').removeClass('validatingObjectProcess');
    $("#"+controlName+'_validationMsg').addClass('validatingObjectError');
    $("#"+controlName+'_validationMsg').text(errorMsg);
}

function HandleAsOK(controlName,okMsg)
{
    $("#"+controlName+'_validationMsg').removeClass('validatingObjectProcess');
    $("#"+controlName+'_validationMsg').removeClass('validatingObjectError');
    $("#"+controlName+'_validationMsg').addClass('validatingObjectOK');
    $("#"+controlName+'_validationMsg').text(okMsg);
}


function showMessageBox(caption,title,message,err_codes)
{

 content ='<table id="ajax_window" width="100%" cellpadding="0" cellspacing="0">'

    +'<tr><td colspan="3" style="padding-top:65px">'+message+'<br><ul>'+err_codes+'</ul></td> </td></tr><tr><td height="6" width="6"  valign="top"></td>'
    +'<td height="6"></td><td height="6" width="6" align="right" valign="top"></td>'
    +'</tr> </table><br><input type="button" value="Zavriet" class="ajaxbtn" onclick="$.unblockUI(); return false;" />';

jQuery.blockUI({
         message: content,
         overlayCSS: { backgroundColor: 'white' },
         css: {
            border: 'none',
            padding: '15px',
            backgroundColor: '#F5F5F5',
            width:'600px',
            top:"3%",
            left:"50%",
            margin:"0 0 0 -300px",
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px'
        }
        });
}




function showMessageBoxError(caption,title,message,err_codes)
{

 var content ='<table id="ajax_window_error" width="100%" cellpadding="0" cellspacing="0">'
    +'<tr><td colspan="3" height="70" valign="top"><img style="float:right;" src="modules/FrontendController/images/chyba.png" alt="" /></td></tr>'
    +'<tr><td colspan="3" ><span class="red"><strong>'+caption+'</strong></span><br /><span class="red">'+message+'</span><br /><br>'+err_codes+'</td> </td></tr><tr><td height="6" width="6"  valign="top"></td>'
    +'<td height="6"></td><td height="6" width="6" align="right" valign="top"></td>'
    +'</tr> </table><br><input type="button" value="Zavriet" class="ajaxbtn" onclick="$.unblockUI(); return false;" />';

jQuery.blockUI({
         message: content,
         overlayCSS: { backgroundColor: 'white' },
         css: {
            border: 'none',
            padding: '15px',
            top:"3%",
            backgroundColor: '#F5F5F5',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px'
        }
        });
}

function userNotLogged()
{
    showMessageBoxError('', '', lang['serviceAvailableForLogged'],'');
    return false;
}


function HandleSimpleFormEventResponse(response)
{
    var err_codes = '';

    $(response.syncData).each(
        function(i,item){
            StopHandling(item.name);
            var aaaa = $("#"+item.name).type;
            if(!item.disabled)
            {
                $("#"+item.name).removeAttr('disabled');
            }
            if(item.options != -1 && typeof(item.options) != "undefined")
            {
                $("#"+item.name).removeOption(/./);
                $(item.options).each(
                    function (j, option)
                    {
                        $("#"+item.name).addOption(option.value, option.name);
                    }
                );
            }
            if($("#"+item.name).type=='checkbox')
            {
                if(item.value==true)
                {
                    $("#"+item.name).attr('checked','checked');
                    $("#"+item.name).val('on');
                }
                else
                {
                    $("#"+item.name).removeAttr('checked');
                }
            }
            else
            {
                $("#"+item.name).val(item.value);
            }


            if(item.validationObject.status!=null)
            {
                $("#"+item.name+'_validationMsg').text(item.validationObject.status);
                if(item.validationObject.status=="OK")
                    HandleAsOK(item.name,item.validationObject.msg);
                if(item.validationObject.status=="ERROR")
                {
                    HandleAsError(item.name,item.validationObject.msg);
                    err_codes += item.validationObject.msg+"<div class='line_short'></div>" ;
                }
            }

            if(item.disabled)
            {
                $("#"+item.name).attr({disabled:"disabled"});
            }
    });

    var unblock = true;
    $(response.actions).each(
        function(i,item)
        {
           if(item.performAction!=null)
           {
           actPcs = item.performAction.split('||');
           switch (actPcs[0])
           {
              case 'submit':
              {
                unblock = false;
                $("#" + item.controlName).submit();
                break;
              }
              case 'displayErrorMessage':
              {
               unblock=false;
               showMessageBox(actPcs[1],actPcs[2],actPcs[3],err_codes);
               break;
              }

              case 'displayErrorMessageError':
              {
               unblock=false;
               showMessageBoxError(actPcs[1],actPcs[2],actPcs[3],err_codes);
               break;
              }
           }
           }
    });
    if(unblock==true)
    {
        jQuery.unblockUI();
    }
}


function ModalDialogButtonClick(callbackFunction)
{
    $.unblockUI();
     if (callbackFunction && Function == callbackFunction.constructor)
     {
       callbackFunction();
   }
    return false;

}

function ShowYesNoDialog(caption,message,callbackYes,callbackNo)
{
  content ='<table width="100%" cellpadding="0" cellspacing="0">'
    +'<tr><th height="23" width="6"  valign="top"><img src="data/design/reg_lt.gif" width="6" height="23" alt=""></th>'
    +'<th align="left"width="100%" ><h2>'+caption+'</h2></th><th height="23" width="6" align="right" valign="top"><img src="data/design/reg_rt.gif" width="6" height="23" alt=""></th></tr>'
    +'<tr><td colspan="3" style="padding:10px">'+message+'<br></td> </td></tr><tr><td height="6" width="6"  valign="top"><img src="data/design/reg_lb.gif" width="6" height="6" alt=""></td>'
    +'<td height="6"><img src="data/design/reg_bg_bottom.gif" width="6" height="6" alt=""></td><td height="6" width="6" align="right" valign="top"><img src="data/design/reg_rb.gif" width="6" height="6" alt=""></td>'
    +'</tr> </table><br><input type="button" value="YES" class="regbtn" id="mdYesBtn_X" onclick="ModalDialogButtonClick('+callbackYes+')" />'
    +'<input type="button" value="NO" id="mdNoBtn_X" class="regbtn" onclick="ModalDialogButtonClick('+callbackNo+')" />';

    $('#mdYesBtn_X').click(function()
            {
                $.unblockUI();
            }
    );

    $('#mdNoBtn_X').click(function()
            {
                $.unblockUI();
            }
    );

jQuery.blockUI({
         message: content,
         overlayCSS: { backgroundColor: '#000' },
         css: {
            border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px'
        }
        });

}

function ShowOkDialog(caption,message,callbackOk)
{
  content ='<table width="100%"cellpadding="0" cellspacing="0">'
    +'<tr><th height="23" width="6"  valign="top"><img src="data/design/reg_lt.gif" width="6" height="23" alt=""></th>'
    +'<th align="left"width="100%" ><h2>'+caption+'</h2></th><th height="23" width="6" align="right" valign="top"><img src="data/design/reg_rt.gif" width="6" height="23" alt=""></th></tr>'
    +'<tr><td colspan="3" style="padding:10px">'+message+'<br></td> </td></tr><tr><td height="6" width="6"  valign="top"><img src="data/design/reg_lb.gif" width="6" height="6" alt=""></td>'
    +'<td height="6"><img src="data/design/reg_bg_bottom.gif" width="6" height="6" alt=""></td><td height="6" width="6" align="right" valign="top"><img src="data/design/reg_rb.gif" width="6" height="6" alt=""></td>'
    +'</tr> </table><br><input type="button" value="'+ lang["ok"] +'" class="regbtn" id="mdOkBtn_X" onclick="ModalDialogButtonClick('+callbackOk+')" />';

    $('#mdOkBtn_X').click(function()
            {
                $.unblockUI();
            }
    );

jQuery.blockUI({
         message: content,
         overlayCSS: { backgroundColor: '#000' },
         css: {
            border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px'
        }
        });
}

function lockTheScreen()
{
jQuery.blockUI({
        message: '<b>'+ lang["checking"] +'</b><br><br><img src="./application/images/loader.gif" alt="'+ lang["please wait"] +'">',
        css: {
            border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
           // opacity: '.5',
            color: '#fff'
        } });
}

function unlockTheScreen()
{
  jQuery.unblockUI();
}

function handleSimpleFormEvent(event,handler,dependentControls,dependentControlsWaitMessages,preventDefault,waitMessage,lang)
{
    splitedMessage = waitMessage.split('||');
    if(splitedMessage[1]=='LOCKSCREEN')
    {
        waitMessage = splitedMessage[0];
            jQuery.blockUI({
        message: '<b>'+waitMessage+'</b><br><br><img src="./application/images/loader.gif" alt="'+ lang["please wait"] +'">',
        css: {
            border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
           // opacity: '.5',
            color: '#fff'
        } });
    }



    myEvent = Object();
    myEvent.type        = event.type;
    if(event.shiftKey)
        myEvent.shiftKey    = true;
    else
        myEvent.shiftKey    = false;

    if(event.ctrlKey)
        myEvent.ctrlKey    = true;
    else
        myEvent.ctrlKey    = false;

    var key = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if(key)
        myEvent.keyCode = key;
    else
        myEvent.keyCode = 0;

    myEvent.cancelled   = false;

    eventHandleRequest = Object();
    eventHandleRequest.event        = myEvent;
    eventHandleRequest.eventTarget  = event.target.id;
    eventHandleRequest.handler      = handler;


    dependentControlsData = Object();
    $(dependentControls).each(
        function(i,item){
            var checkbox = $("#"+item).is("input[@type='checkbox']");
            if (checkbox)
            {
            var value = (document.getElementById(item).checked) ? "on" : "off";
            dependentControlsData[item] =
                {name:item,
                 value: value,
                 disabled : $("#"+item).attr("disabled")};
            }
            else
            {
            dependentControlsData[item] =
                {name:item,
                 value: $("#"+item).val(),
                 disabled : $("#"+item).attr("disabled")};
            }
            StartHandling(item,dependentControlsWaitMessages[i]);
    });

    dependentControlsData[event.target.id] =
        {name:event.target.id,
         value: $("#"+event.target.id).val(),
         disabled : $("#"+event.target.id).attr("disabled")};

    eventHandleRequest.dependentControlsData = dependentControlsData;

    if(preventDefault)
        event.preventDefault();


    StartHandling(event.target.id,waitMessage);

    $.ajax({
   type: "POST",
   url: domain+"index.php?system=ajax&handleEvent=1&lang="+lang,//&DBGSESSID=395966229524700001;d=1,p=0,c=1",
   data: "jsonRequest="+encode($.toJSON(eventHandleRequest)),
   success: function(msg){
       HandleSimpleFormEventResponse($.evalJSON(msg));
   }
 });
}

function callServerAction(moduleName, functionName, parameters, callbackFunction, lockScreen)
{
  if ( lockScreen === undefined ) { }
  else
  {
    lockTheScreen();
  }

  ActionObject = Object();
  ActionObject.moduleName = moduleName;
  ActionObject.functionName = functionName;
  ActionObject.parameters = parameters;

  //alert(parameters);
  $.ajax({
   type: "POST",
   url: domain+"index.php?system=ajax&handleFunction=1",
   data: "jsonRequest="+encode($.toJSON(ActionObject)),
   success: function(msg){
    response = $.evalJSON(msg);
    if(response.console.showMessageBox==1)
    {
        if(response.console.messageBox.msgtype == 'error')
            showMessageBoxError(response.console.messageBox.caption,'',response.console.messageBox.message,'');
        else
            showMessageBox(response.console.messageBox.caption,'',response.console.messageBox.message,'');
    }
    else
    {
        unlockTheScreen();
    }
   if (callbackFunction && Function == callbackFunction.constructor) {
       callbackFunction(response.data);
   }
   }
 });
}


function openPopup(url) {
            window.open(url,"popup","width=800,height=600,status=no,top=200,left=400,scrollbars=1");
        }

        function NewWindow(mypage){
            var w = 800;
            var h = 600;

            var winl = (screen.width-w)/2;
            var wint = 100;

            var settings ='height='+h+',';
                settings +='width='+w+',';
                settings +='left='+winl+',';
                settings +='top='+wint+',';
                settings +='resizable=yes';

            wiwindow.open(mypage,'popup',settings);
        }
