
/***********************************************************************************
 * GLOBAL FUNCTIONS
 ***********************************************************************************/

/**
 * Get element x and y coordinates
 */
function getXY(element)
{
    var result = new Object();

    result.x = element.offsetLeft;
    result.y = element.offsetTop;
    var p = element.offsetParent;
    while (p != null) {
           result.x += p.offsetLeft;
           result.y += p.offsetTop;
           p = p.offsetParent;
    }

    return result;
}


/**
 * Set element x and y coordinates
 */
function moveTo(element, x, y)
{
    element.style.left = x + "px";
    element.style.top = y + "px";
}


/**
 * Get mouse x and y coordinates
 */
function mouseXY(event)
{
    var result = new Object();
    if (event) {
        result.x = event.clientX + document.body.scrollLeft;
        result.y = event.clientY + document.body.scrollTop;
    }
    else {
        result.x = window.event.clientX + document.body.scrollLeft;
        result.y = window.event.clientY + document.body.scrollTop;
    }
    return result;
}


/**
 * Get element x and y coordinates
 */
function getWH(element) {
    var result = new Object();
    if (document.defaultView && document.defaultView.getComputedStyle) {
        result.w = parseInt(document.defaultView.getComputedStyle(element, "").getPropertyValue("width"));
        result.h = parseInt(document.defaultView.getComputedStyle(element, "").getPropertyValue("height"));
    } else {
        result.w = element.clientWidth;
        result.h = element.clientHeight;
    }

    return result;
}


/**
 * Get element width and height
 */
function setWH(element, w, h)
{
    element.style.width = w + "px";
    element.style.height = h + "px";
}


/**
 * Set opacity
 */
function setOpacity(target, value)
{
    if (page.HttpAgent.isIE()) {
        target.style.filter = 'alpha(opacity=' + value + ')';
    }
    else if (page.HttpAgent.isFirefox()) {
        target.style.opacity = value/100;
    }
    else if (page.HttpAgent.isMozilla()) {
        target.style.MozOpacity = value/100;
    }
    else {
        target.style.opacity = value/100;
    }
}


/**
 * Get element by id
 */
function e(eId)
{
    return document.getElementById(eId);
}


/**
 * setHtml
 */
function setHtml(element, html)
{
    if (typeof(element) == "string")
        element = document.getElementById(element);

    try {
        element.innerHTML = html;
    }
    catch(ex) {
        if (document.contentType == "application/xhtml+xml")
            setHtmlThroughDOM( element, "<span xmlns=\"http://www.w3.org/1999/xhtml\">" + html + "</span>" );
    }
}


/**
 * setHtmlThroughDOM
 */
function setHtmlThroughDOM(element, html)
{
    if (typeof(element) == "string")
        element = document.getElementById( element );

    try {
        var children = element.childNodes;
  
        for (var i = 0; i < children.length; i++)
             element.removeChild(children[i]);
  
        var nodes = new DOMParser().parseFromString( html, 'text/xml' ).documentElement;
        var range = document.createRange();
        range.selectNodeContents( element );
        range.deleteContents();
  
        for (var i = 0; i < nodes.childNodes.length; i++)
             element.appendChild(document.importNode(nodes.childNodes[i], true));
    }
    catch(ex) {
    }
}


/**
 * Get object functions
 */
function getFunctions(obj)
{
    var str = "";
    for (i in obj) {
         if (i != "selectionStart" && i != "selectionEnd" && i != "domConfig") {
             if (typeof(obj[i]) == "function") {
                 str = str + i + " => " + obj[i] + "\n";
             }
         }
    }

    return str;
}


/**
 * print_r
 */
function print_r(mixed)
{
    var innerHtml = "";
    if (typeof(mixed) == "object") {
        for (i in mixed) {
             if (i != "selectionStart" && i != "selectionEnd" && i != "domConfig" && mixed[i] && typeof(mixed[i]) != "function" && typeof(mixed[i]) != "unknown") {
                 innerHtml = innerHtml + i + " => " + mixed[i] + "\n";
             }
        }
    }
    else if (typeof(mixed) == "number") {
        innerHtml = "" + mixed;
    }
    else {
        innerHtml = mixed;
    }

    var elementTA = document.getElementById('print_r_TextArea');
    if (elementTA) {
        elementTA.value = elementTA.value + "\n\n============================ new entry ============================\n\n" + innerHtml;
        return;
    }

    var e = document.createElement("div");
    e.style.position = "absolute";
    e.id = page.createUID();
    document.body.appendChild(e);

    var btnCloseID = page.createUID();

    var html = "";
    html += "<table border='0' cellspacing='1' cellpadding='0' style='text-align:center;background-color:#286692;width:" + (page.windowWidth()-180) + "px;'>";
    html += "<tr><td style='background-color:#1D7CC0;padding:5 0 5 0;color:#FFFFFF;font-weight:bold;'>Debug Window</td></tr>";
    html += "<tr><td style='background-color:#D8EFFF'><textarea id='print_r_TextArea' style='width:100%;height:550px' readonly='readonly'>" + innerHtml + "</textarea></td></tr>";
    html += "<tr><td style='background-color:#D8EFFF;'><input id='" + btnCloseID + "' type='button' value='CLOSE' style='width:100%;height:28px;' /></td></tr>";
    html += "</table>";

    setHtml(e, html);
    page.centerElement(e);

    document.getElementById(btnCloseID).onclick = function() {
        document.body.removeChild(e);
    }
}


/**
 * httpBuildQuery
 */
function httpBuildQuery(obj, args)
{
    var str = "";
	  for (k in obj) {
	      var v = obj[k];
	      if (v) {
	          if (typeof(v) == "object" && v.type == "array") {
	              var arrstr = "";
	              for (var ind=0; ind<v.length; ind++) {
	              	   if (args && args['target'] && args['target']=='ajax') {
	              	       arrstr += k + "[]=" + encodeURIComponent(v[ind]) + "&";
	              	   }
	              	   else {
	              	       arrstr += k + "[]=" + escape(v[ind]) + "&";
	              	   }
	              }

	              if (arrstr.length > 0)
	                  arrstr = arrstr.substr(0, arrstr.length-1);

	              str += arrstr;
	          }
	          else {
            	  if (args && args['target'] && args['target']=='ajax') {
            	      str += escape(k) + "=" + encodeURIComponent(v) + "&";
            	  }
            	  else {
            	      str += escape(k) + "=" + escape(v) + "&";
            	  }
	          }
	      }
	      else
	          str += k + "=" + "&";
    }

    if (str.length > 0)
        str = str.substr(0, str.length-1);

    return str;
}


/**
 * httpParseQuery
 */
function httpParseQuery(str)
{
    var obj = {};
    var arr = str.split("&");
    for (var i=0; i<arr.length; i++) {
         var pairStr = arr[i];
         pairArr = pairStr.split("=");
         if (pairArr.length == 2) {
             var k = unescape(pairArr[0]);
             var v = pairArr[1];
             v = v.split("+").join(" ");
             v = unescape(v);
             obj[k] = v;
         }
    }

    return obj;
}


/**
 * Gets quotes safe string.
 */
function safequot(str)
{
    str = str.replace(/'/g, "&#039;");
    str = str.replace(/"/g, "&quot;");
    return str;
}


/**
 * Fetch form
 */
function fetchForm(formName)
{
    var result = new Object();
    var frm = document.forms[formName];
    for (i in frm) {
         var elem = frm[i];
         if (elem && elem.name && elem.tagName) {
             var tagName = elem.tagName.toLowerCase();
             if (tagName == "textarea") {
                 result[elem.name] = elem.value;
             }
             else if ( tagName == "input" ) {
                 var type = elem.type.toLowerCase();

                 if (type == "text" || type == "hidden")
                     result[elem.name] = elem.value;
                 else if (type == "checkbox" && elem.checked)
                     result[elem.name] = "on";
             }
             else if (tagName == "select") {
                 var arr = new Array();
                 for (var j=0; j<elem.options.length; j++)
                      if (elem.options[j].selected)
                          arr.push(elem.options[j].value);

                 result[elem.name] = arr;
             }
         }
    }

    return result;
}


/**
 * Add target event listener
 */
function addTargetEventListener(target, type, handler)
{
    if (target.attachEvent) {
        target.attachEvent('on'+type, function() {handler.call(this ,window.event.srcElement, window.event)});
    }
    else {
        target.addEventListener(type, function(evt) {handler.call(this, evt.target, evt)}, false);
    }
}




/***********************************************************************************
 * TClass definition
 ***********************************************************************************/
 
var TClass =
{
    create: function()
    {
        return function()
        {
            this.initialize.apply(this, arguments);
        }
    }
}


Object.extend = function(destination, source)
{
    for (property in source) {
         destination[property] = source[property];
    }

    return destination;
}


Object.extend( TClass,
{
    extend: function(source, additions)
    {
        var newclass = TClass.create();
        if ($C(source)) {
            Object.extend( $C(newclass),$C(source) );
        }
        Object.extend( $C(newclass), additions );
        return newclass;
    }
});


function $C(object)
{
    return object.prototype;
}




/***********************************************************************************
 * TWebControl definition
 ***********************************************************************************/

var TWebControl = TClass.extend({},
{
    /**
     * Constructor
     */
    initialize: function(name)
    {
       this.name = name;
       this.Name = name;
       this.fClassName = '';
       this.fStyle = '';
       this.fPluginPath = '';
       this.Attr = {};
       this.fI18N = {};
    },


    /**
     * Set class name
     */
    setClassName: function(aClassName)
    {
        this.fClassName = aClassName;
    },


    /**
     * Get class name
     */
    getClassName: function()
    {
        return this.fClassName;
    },


    /**
     * Set style
     */
    setStyle: function(aStyle)
    {
        this.fStyle = aStyle;
    },


    /**
     * Get style
     */
    getStyle: function()
    {
        return this.fStyle;
    },


    /**
     * Set plugin path
     */
    setPluginPath: function(pluginPath)
    {
        this.fPluginPath = pluginPath;
    },


    /**
     * Get plugin path
     */
    getPluginPath: function()
    {
        return this.fPluginPath;
    },


    /**
     * Add locale strings
     */
    addI18N: function(localeStrings)
    {
        for (var key in localeStrings) {
             this.fI18N[key] = localeStrings[key];
        }
    },


    /**
     * Get locale string
     */
    getI18N: function(localeString)
    {
        return (this.fI18N[localeString]!=null ? this.fI18N[localeString] : localeString);
    }
});


/***********************************************************************************
 * TPage definition
 ***********************************************************************************/
 
var TPage = TClass.extend(TWebControl,
{
    /**
     * Constructor
     */
    initialize: function()
    {
        $C(TWebControl).initialize.call(this, "");
        this.Ajax = null;
        this.Template = {};
        this.HttpAgent = new THttpAgent();

        this.LockId = "TPage_LockId";
        this.AvailableDialogs = 0;
        this.TopZIndex = 50;

        var blankImg = new Image();
        blankImg.src = "/system/assets/images/blank.gif";

        this.UID = 7235;
        this.scriptLoadingNumber = 0;

        this.dialogWait = null;
    },


    /**
     * Creates new unique identifier
     */
    createUID: function()
    {
        return "id" + this.UID++;
    },


    /**
     * Disables all buttons
     */
    disableAllButtons: function()
    {
      /*
        var arr = document.getElementsByTagName('a');
        for (i in arr) {
             if (arr[i].tagName && arr[i].tagName.toLowerCase() == "a" && arr[i].onclick) {
                 arr[i].onclick = null;
                 arr[i].style.color = "#CCCCCC";
             }
        }

        arr = document.getElementsByTagName('input');
        for (i in arr) {
             if (arr[i].tagName && arr[i].tagName.toLowerCase() == "input" && arr[i].type && arr[i].type=="button" && arr[i].onclick) {
                 arr[i].onclick = null;
                 arr[i].disabled = true;
             }
        }
          */

        this.setDisabled();
    },


    /**
     * Disables button
     */
    disableButton: function( id )
    {
        var elm = document.getElementById( id );
        if (elm && elm.onclick) {
            elm.onclick = null;

            if (elm.tagName.toLowerCase() == "input")
                elm.disabled = true;

            else if (elm.tagName.toLowerCase() == "a")
                elm.style.color = "#CCCCCC";
           
        }
    },


    /**
     * Enable data controls
     */
    enableDataControls: function( formName, flag )
    {
        var frm = document.forms[ formName ];
        for (i in frm) {
             var elem = frm[i];
             if (elem && elem.name && elem.tagName) {
                 var tagName = elem.tagName.toLowerCase();
                 if (tagName == "textarea" || tagName == "select" || (tagName == "input"&&(elem.type.toLowerCase()=="text"||
                                                                                           elem.type.toLowerCase()=="checkbox"||
                                                                                           elem.type.toLowerCase()=="radio")))
                     elem.disabled = !flag;
             }
        }
    },


    /**
     * Toggle enable/disable mode, flag = true means to disable
     */
    toggleEnableDisableMode: function(flag)
    {
        if (flag) {

            if (document.getElementById(this.LockId))
                return;

            var lockDiv = document.createElement("div");
            lockDiv.id = this.LockId;
            lockDiv.style.position = "absolute";

            var opacityStr = "opacity:0.6";
            if (page.HttpAgent.isIE()) opacityStr = "filter:alpha(opacity=60)";
            else if (page.HttpAgent.isMozilla()) opacityStr = "-moz-opacity:0.6";

            var html = "<img src=\"/system/assets/images/disablepage.gif\" style=\"width:{width};height:{height};"+opacityStr+";\" />";
            html = html.replace( "{width}", this.docWidth() );
            html = html.replace( "{height}", this.docHeight() );

            setHtml(lockDiv, html);
            document.body.appendChild(lockDiv);

            lockDiv.style.top = "0px";
            lockDiv.style.left = "0px";
        }
        else {
            if (document.getElementById(this.LockId))
                document.body.removeChild( document.getElementById( this.LockId ) );
        }
    },


    /**
     * Sets disabled
     */
    setDisabled: function()
    {
        this.toggleEnableDisableMode(true);
    },


    /**
     * Sets enabled
     */
    setEnabled: function()
    {
        this.toggleEnableDisableMode(false);
    },


    /**
     * Checks to see if page is disabled
     */
    isDisabled: function()
    {
        if (document.getElementById(this.LockId))
            return true;

        return false;
    },


    /**
     * Array of messages/errors to ordered list
     */
    objectToOrderedList: function(arr)
    {
        var str = "<ol style='margin-top:0px;margin-bottom:0px'>";

        var count = 0;
        var lastItem = null;
        for (var i in arr) {
             str += "<li>" + arr[i] + "</li>";
             lastItem = arr[i];
             count++;
        }

        str += "</ol>";

        return (count == 1 ? "<center>"+lastItem+"</center>" : str);
    },


    /**
     * Shows info messages
     */
    showInfos: function(obj, onCloseHandler)
    {
        var content = "";
        if (typeof(obj) == "string") {
            content = "<center>"+obj+"</center>";
        }
        else if (typeof(obj) == "array" || typeof(obj) == "object") {
            content = this.objectToOrderedList(obj);
        }

        var dialog = new TDialog();
        dialog.setClassName("cssDialogInfo");
        dialog.setDraggable(true);
        dialog.setTitle(this.getI18N("SYS_UI_PAGE_INFO_TITLE"));
        dialog.setContent(content);
        dialog.addButton(this.getI18N("BTN_CLOSE"), function () {
               dialog.close();
               if (onCloseHandler)
                   onCloseHandler.call();
        });

        dialog.openModal();
        dialog.bringToFront();
    },


    /**
     * Shows info message
     */
    showInfo: function(obj, onCloseHandler)
    {
        this.showInfos(obj, onCloseHandler);
    },


    /**
     * Shows errors
     */
    showErrors: function(obj, onCloseHandler)
    {
        var content = "";
        if (typeof(obj) == "string") {
            content = "<center>"+obj+"</center>";
        }
        else if (typeof(obj) == "array" || typeof(obj) == "object") {
            content = this.objectToOrderedList(obj);
        }

        var dialog = new TDialog();
        dialog.setClassName("cssDialogError");
        dialog.setDraggable(true);
        dialog.setTitle(this.getI18N("SYS_UI_PAGE_ERRORS_TITLE"));
        dialog.setContent(content);
        dialog.addButton(this.getI18N("BTN_CLOSE"), function () {
               dialog.close();
               if (onCloseHandler)
                   onCloseHandler.call();
        });

        dialog.openModal();
        dialog.bringToFront();
    },


    /**
     * Shows error message
     */
    showError: function(obj, onCloseHandler)
    {
        this.showErrors(obj, onCloseHandler);
    },


    /**
     * Wait
     */
    wait: function(message, targetElement)
    {
        if (targetElement) {
            var tagName = targetElement.tagName.toLowerCase();
            if (tagName == "span" || tagName == "div" || tagName == "td") {
                setHtml(targetElement, "<img src='/system/assets/images/loading.gif' border='0' />&nbsp;" + message );
            }
            return;
        }


        if (!this.dialogWait) {
            this.dialogWait = new TDialog();
            this.dialogWait.showTitle(false);
        }

        if (this.dialogWait.isOpen()) {
            //this.showError("Can't start another waiting dialog, one is already in progress");
            return;
        }

        if (message) {
            this.dialogWait.setClassName("cssDialogWait");
            this.dialogWait.setContent("<br/>" + message + "<br/><br/>");
            this.dialogWait.openModal();
        }
        else {
            this.dialogWait.openModal();
            this.dialogWait.getContentElement().style.position = "absolute";
            this.dialogWait.setContent("<img src='/system/assets/images/loading.gif' border='0' />");
        }
    },


    /**
     * Unwait
     */
    unwait: function()
    {
        if (this.dialogWait && this.dialogWait.isOpen()) {
            this.dialogWait.close();
        }
    },


    /**
     * Postback action
     */
    action: function(args, formName)
    {
        var targetForm;
        if (formName) {
            targetForm = document.forms[formName];
        }
        else {
            for (var formIndex in document.forms) {
                 var f = document.forms[formIndex];
                 if (f["__POSTBACK"] && f["__POSTBACK"].value == "true") {
                     targetForm = f;
                     break;
                 }
            }
        }

        if (targetForm) {
            targetForm["eventSource"].value = "__PAGE";
            targetForm["eventType"].value = "OnAction";
            targetForm["parameterA"].value = httpBuildQuery(args, {'target':'ajax'});
            targetForm.submit();
        }
        else {
            this.showError("No suitable html form was found");
        }
        
    },


    /**
     * Reloads
     */
    reload: function( milsec )
    {
        var uri = document.location.href;
        if (uri.indexOf("#") >= 0)
            uri = uri.substr(0, uri.indexOf("#"));

        if (milsec)
            setTimeout( function() { document.location.href = uri; }, milsec );
        else {
           document.location.href = uri;
        }
    },


    /**
     * Gets window height
     */
    windowHeight: function()
    {
        if (this.HttpAgent.isIE()) {
            return (document.body.offsetHeight ? document.body.offsetHeight : document.body.clientHeight);
        }
        else {
            return window.innerHeight;
        }
    },


    /**
     * Gets window width
     */
    windowWidth: function()
    {
        if (this.HttpAgent.isIE()) {
            return (document.body.offsetWidth ? document.body.offsetWidth : document.body.clientWidth);
        }
        else {
            return window.innerWidth;
        }
    },


    /**
     * Gets document height
     */
    docHeight: function()
    {
        return Math.max(document.body.scrollHeight,document.body.clientHeight);
    },


    /**
     * Gets document width
     */
    docWidth: function()
    {
        return document.body.scrollWidth;
    },


    /**
     * Bring to front
     */
    bringElementToFront: function(element)
    {
        if (!element.style.zIndex || element.style.zIndex < page.TopZIndex)
            element.style.zIndex = ++page.TopZIndex;
    },


    /**
     * Centers element
     */
    centerElement: function(element)
    {
        if (element.clientHeight < this.windowHeight()) {
            element.style.top = document.body.scrollTop + (this.windowHeight() - element.clientHeight)/2 + "px";
        }
        else {
            element.style.top = (this.docHeight() - element.clientHeight)/2 + "px";
        }

        if (element.clientWidth < this.windowWidth()) {
            element.style.left = document.body.scrollLeft + (this.windowWidth() - element.clientWidth)/2 + "px";
        }
        else {
            element.style.left = (this.docWidth() - element.clientWidth)/2 + "px";
        }
    },


    /**
     * Sets cookie
     */
    setCookie: function(name,value,expires)
    {
        var today = new Date();
        today.setTime( today.getTime() );

        if (expires != 0) {
            expires = expires * 1000;
            var expiresDate = new Date(today.getTime()+expires);
            document.cookie = name + "=" + escape(value) + ";expires=" + expiresDate.toGMTString();
        }
        else {
            document.cookie = name + "=" + escape(value);
        }
    },


    /**
     * Gets cookie
     */
    getCookie: function(name)
    {
        if (document.cookie.length>0) {
            var startIndex = document.cookie.indexOf(name + "=");
            if (startIndex != -1) {
                startIndex = startIndex+name.length+1; 
                var endIndex = document.cookie.indexOf(";",startIndex);
                if (endIndex == -1)
                    endIndex = document.cookie.length;

                return unescape(document.cookie.substring(startIndex,endIndex));
            }
        }

        return null;
    },


    /**
     * Removes cookie
     */
    removeCookie: function(name)
    {
        if (this.getCookie(name))
            document.cookie = name + "=;expires=Thu, 01-Jan-1970 00:00:01 GMT";

    },


    /**
     * Adds script file
     */
    addScript: function(uri, id)
    {
        var scriptElement;
        if (id && document.getElementById(id)) {
            scriptElement = document.getElementById(id);
        }
        else {
            scriptElement = document.createElement('script');
            scriptElement.type = 'text/javascript';
            document.getElementsByTagName('head')[0].appendChild(scriptElement);
            if (id)
                document.id = id;
        }

        if (scriptElement) {
            page.scriptLoadingNumber++;
            if (this.HttpAgent.isIE()) {
                scriptElement.onreadystatechange = function () {
                           if (this.readyState == 'loaded') {
                               page.scriptLoadingNumber--;
                           }
                       }
            }
            else {
                scriptElement.onload = function() {page.scriptLoadingNumber--;};
            }
            scriptElement.src = uri;
        }
    },


    /**
     * Adds script content
     */
    addScriptContent: function(content)
    {
        try {
           var scriptElement = document.createElement('script');
           scriptElement.type = 'text/javascript';
           scriptElement.text = content;
           document.getElementsByTagName('head')[0].appendChild(scriptElement);
        } catch(e) {
           alert(e);
        }
    },


    /**
     * Adds css
     */
    addCss: function(uri, id)
    {
        var linkElement;
        if (id && document.getElementById(id)) {
            linkElement = document.getElementById(id);
        }
        else {
            linkElement = document.createElement('link');
            linkElement.type = 'text/css';
            linkElement.rel = 'stylesheet';
            document.getElementsByTagName('head')[0].appendChild(linkElement);
            if (id)
                document.id = id;
        }

        if (linkElement) {
            linkElement.href = uri;
        }
    },


    /**
     * Safe execution of a script
     */
    safeExec: function(content)
    {
        if (page.scriptLoadingNumber == 0) {
            eval(content);
        }
        else {
            setTimeout(function() { page.safeExec(content); }, 200);
        }
        
    },


    /**
     * Redirect
     */
    redirect: function(url, params, args)
    {
        var frm = document.createElement("FORM");
        frm.action = url;
        
        if (args) {
            if (args['method']) {
                frm.method = args['method'];
            }
            if (args['target']) {
                frm.target = args['target'];
            }
        }

        if (params) {
            for (var i in params) {
                var hiddenElement = document.createElement("INPUT");
                hiddenElement.type = "hidden";
                hiddenElement.name = i;
                hiddenElement.value = params[i];
                frm.appendChild(hiddenElement);
            }
        }

        document.body.appendChild(frm);
        frm.submit();
        document.body.removeChild(frm);
    }

});





/***********************************************************************************
 * THttpAgent definition
 ***********************************************************************************/

var THttpAgent = TClass.extend( {},
{
    /**
     * Constructor
     */
    initialize: function()
    {
    },


    /**
     * isIE
     */
    isIE: function()
    {
        return (
                 navigator.userAgent.indexOf("MSIE") >= 0 
                 && navigator.userAgent.indexOf("Opera") == -1
                 && navigator.userAgent.indexOf("Konqueror") == -1
               );
    },


    /**
     * isMozilla
     */
    isMozilla: function()
    {
        return (
                 navigator.userAgent.indexOf( "Mozilla" ) >= 0 
                 && navigator.userAgent.indexOf( "Gecko" ) >= 0
                 && navigator.userAgent.indexOf( "MSIE" ) == -1
                 && navigator.userAgent.indexOf( "Firefox" ) == -1
                 && navigator.userAgent.indexOf( "Opera" ) == -1
                 && navigator.userAgent.indexOf( "Konqueror" ) == -1
                 && navigator.userAgent.indexOf( "Safari" ) == -1
                 && navigator.userAgent.indexOf( "Chrome" ) == -1
               );
    },


    /**
     * isFirefox
     */
    isFirefox: function()
    {
        return ( navigator.userAgent.indexOf( "Firefox" ) >= 0 );
    },


    /**
     * isOpera
     */
    isOpera: function()
    {
        return ( navigator.userAgent.indexOf( "Opera" ) >= 0 );
    },


    /**
     * isKonqueror
     */
    isKonqueror: function()
    {
        return ( navigator.userAgent.indexOf( "Konqueror" ) >= 0 );
    },


    /**
     * isSafari
     */
    isSafari: function()
    {
        return (navigator.userAgent.indexOf("Safari") >= 0 && navigator.userAgent.indexOf("Chrome") == -1);
    },


    /**
     * isChrome
     */
    isChrome: function()
    {
        return (navigator.userAgent.indexOf("Chrome") >= 0);
    },


    /**
     * isUnknown
     */
    isUnknown: function()
    {
        return ( !this.isIE()
                 && !this.isMozilla()
                 && !this.isFirefox()
                 && !this.isOpera()
                 && !this.isKonqueror()
                 && !this.isSafari()
                 && !this.isChrome()
               );
    }

});




/***********************************************************************************
 * TDialog definition
 ***********************************************************************************/

var TDialog = TClass.extend(TWebControl,
{
    /**
     * Constructor
     */
    initialize: function()
    {
        $C(TWebControl).initialize.call(this, page.createUID());
        this.fTitle = "";
        this.fContent = "";
        this.fTitleElementID = page.createUID();
        this.fContentElementID = page.createUID();
        this.fButtons = new Array();
        this.fButtonClickHandlers = new Object();

        this.fShowTitle = true;

        this.fShowSystemButtons = false;
        this.fSystemButton1 = page.createUID();
        this.fSystemButton2 = page.createUID();
        this.fSystemButton3 = page.createUID();
        this.fSystemCloseHandler = null;

        this.fModalDialog = false;
        this.fEnablePageOnClose = false;
        this.fContentBoxConstraints = null;
        this.fDraggableMode = false;
        this.fDragObject = null;
        this.fResizableMode = false;
        this.inResizeBox = false;
        this.fResizeObject = null;

        this.tmp = {'State':'normal'};
    },


    /**
     * Get dialog element
     */
    getDialogElement: function()
    {
        return document.getElementById(this.Name);
    },


    /**
     * Set title
     */
    setTitle: function(aTitle)
    {
        this.fTitle = aTitle;

        var titleElement = document.getElementById(this.fTitleElementID);
        if (titleElement)
            setHtml(titleElement, aTitle);
    },


    /**
     * Set content
     */
    setContent: function(aContent)
    {
        this.fContent = aContent;

        var contentElement = this.getContentElement();
        if (contentElement) {
            setHtml(contentElement, aContent);
            page.centerElement(contentElement);
        }
    },


    /**
     * Get content box id
     */
    getContentBoxId: function()
    {
        return this.fContentElementID;
    },


    /**
     * Get content element
     */
    getContentElement: function()
    {
        return document.getElementById(this.fContentElementID);
    },


    /**
     * Set content box constraints
     */
    setContentBox: function(aWidth, aHeight, aOverflow)
    {
        this.fContentBoxConstraints = {};
        this.fContentBoxConstraints['w'] = aWidth;
        this.fContentBoxConstraints['h'] = aHeight;

        if (aOverflow) {
            this.fContentBoxConstraints['overflow'] = aOverflow;
        }
        else {
            this.fContentBoxConstraints['overflow'] = "auto";
        }
    },


    /**
     * Set draggable mode
     */
    setDraggable: function(aDraggableMode)
    {
        this.fDraggableMode = aDraggableMode;
    },


    /**
     * Set resizable mode
     */
    setResizable: function(aResizableMode)
    {
        this.fResizableMode = aResizableMode;
    },


    /**
     * Show system buttons
     */
    showSystemButtons: function(flag)
    {
        this.fShowSystemButtons = flag;
    },


    /**
     * Show title
     */
    showTitle: function(flag)
    {
        this.fShowTitle = flag;
    },


    /**
     * Go to
     */
    goTo: function(x, y)
    {
        moveTo(document.getElementById(this.Name), x, y);
    },


    /**
     * Set system close handler
     */
    setSystemCloseHandler: function(aHandler)
    {
        this.fSystemCloseHandler = aHandler;
    },


    /**
     * Add button
     */
    addButton: function(aLabel, aHandler)
    {
        var id = page.createUID();
        this.fButtons.push({"id":id, "label":aLabel});
        this.fButtonClickHandlers[id] = aHandler;
        return id;
    },


    /**
     * Opens modal dialog
     */
    openModal: function()
    {
        if (document.getElementById(this.Name))
            return;

        if (!page.isDisabled()) {
            page.setDisabled();
            this.fEnablePageOnClose = true;
        }

        this.open();
        this.fModalDialog = true;
    },


    /**
     * Opens dialog
     */
    open: function()
    {
        if (document.getElementById(this.Name))
            return;

        var dialogElement = document.createElement("div");
        dialogElement.style.visibility = "hidden";
        
        // set id
        dialogElement.id = this.Name;

        // set class name
        if (this.getClassName())
            dialogElement.className = this.getClassName();

        // add element to document childs
        document.body.appendChild(dialogElement);

        setHtml(dialogElement, this.toHtml());

        if (this.fContentBoxConstraints) {
            dialogElement.style.width = this.fContentBoxConstraints['w'] + "px";
        }

        page.centerElement(dialogElement);
        var coordinates = getXY(dialogElement);
        moveTo(dialogElement, coordinates.x + 8*page.AvailableDialogs, coordinates.y + 8*page.AvailableDialogs);

        dialogElement.style.visibility = "visible";

        var _self = this;

        if (this.fShowSystemButtons) {
            document.getElementById(this.fSystemButton1).onclick = function() {_self.minimize()}
            document.getElementById(this.fSystemButton2).onclick = function() {_self.maximize()}

            document.getElementById(this.fSystemButton3).onclick = function() {
                if (_self.fSystemCloseHandler) {
                    _self.fSystemCloseHandler.call();
                }
                else {
                    _self.close();
                }
            }
        }


        // assign onclick event handler(s) to button(s)
        for (var index in this.fButtons) {
             var btnAttr = this.fButtons[index];

             var btnElement = document.getElementById(btnAttr["id"]);
             if (btnElement) {
                 btnElement.onclick = function() {
                                            var clickHandler = _self.fButtonClickHandlers[this.id];
                                            if (clickHandler)
                                                clickHandler.call();
                                      }
             }
        }


        // bring to top
        if (page.HttpAgent.isIE()) {
            dialogElement.attachEvent("onmousedown", function() {
                _self.bringToFront();
            });
        }
        else {
            dialogElement.addEventListener("mousedown", function(event) {
                _self.bringToFront();
            }, false);
        }


        if (this.fDraggableMode) {
            var targetElement = document.getElementById(this.fTitleElementID);

            if (page.HttpAgent.isIE()) {
                targetElement.attachEvent("onmousedown", function() {
                    var eXY = getXY(dialogElement); var mXY = mouseXY();
                    _self.fDragObject = {'off_x':mXY.x-eXY.x,'off_y':mXY.y-eXY.y};
                    document.body.style.cursor = "move";
                });
                document.attachEvent("onmousemove", function() {
                    if (!_self.fDragObject) return; var mXY = mouseXY();
                    moveTo(dialogElement, mXY.x-_self.fDragObject.off_x, mXY.y-_self.fDragObject.off_y);
                });
                document.attachEvent("onmouseup", function() {
                    _self.fDragObject = null;
                    document.body.style.cursor = "default";
                });
            }
            else {
                targetElement.addEventListener("mousedown", function(event) {
                    var eXY = getXY(dialogElement); var mXY = mouseXY(event);
                    _self.fDragObject = {'off_x':mXY.x-eXY.x,'off_y':mXY.y-eXY.y};
                    document.body.style.cursor = "move";
                }, false);
                document.addEventListener("mousemove", function(event) {
                    if (!_self.fDragObject) return; var mXY = mouseXY(event);
                    moveTo(dialogElement, mXY.x-_self.fDragObject.off_x, mXY.y-_self.fDragObject.off_y);
                }, false);
                document.addEventListener("mouseup", function() {
                    _self.fDragObject = null;
                    document.body.style.cursor = "default";
                }, false);
            }
        }

        if (this.fResizableMode) {
            var contentElement = document.getElementById(this.fContentElementID);

            if (page.HttpAgent.isIE()) {
                dialogElement.attachEvent("onmousedown", function() {
                    if (_self.inResizeBox) {
                        var eWH = getWH(dialogElement);
                        var cWH = getWH(contentElement);
                        var mXY = mouseXY(event);
                        _self.fResizeObject = {'dw':eWH.w,'ch':cWH.h,'mx':mXY.x,'my':mXY.y};
                    }
                });

                dialogElement.attachEvent("onmousemove", function() {
                    var mXY = mouseXY(event);
                    var eXY = getXY(dialogElement);
                    var eWH = getWH(dialogElement);
                    if (eXY.x + eWH.w - 10 < mXY.x && eXY.y + eWH.h - 10 < mXY.y) {
                        document.body.style.cursor = "nw-resize";
                        _self.inResizeBox = true;
                    }
                    else {
                        document.body.style.cursor = "default";
                        _self.inResizeBox = false;
                    }
                });

                document.attachEvent("onmousemove", function() {
                    if (!_self.fResizeObject) return; var mXY = mouseXY(event);
                    var dialogWidth = _self.fResizeObject.dw + mXY.x-_self.fResizeObject.mx;
                    var contentHeight = _self.fResizeObject.ch + mXY.y-_self.fResizeObject.my;

                    if (dialogWidth < 200 || contentHeight < 5) return;

                    dialogElement.style.width = dialogWidth + "px";
                    contentElement.style.height = contentHeight +"px";

                    if (_self.tmp['State'] == 'min' || _self.tmp['State'] == 'max') {
                        document.getElementById(_self.fSystemButton1).style.visibility = 'visible';
                        document.getElementById(_self.fSystemButton2).src = '/system/assets/images/tdialog/max.gif';
                        _self.tmp['State'] = 'normal';
                    }
                });

                document.attachEvent("onmouseup", function() {
                    _self.fResizeObject = null;
                    document.body.style.cursor = "default";
                });
            }
            else {
                dialogElement.addEventListener("mousedown", function(event) {
                    if (_self.inResizeBox) {
                        var eWH = getWH(dialogElement);
                        var cWH = getWH(contentElement);
                        var paddTop_px = document.defaultView.getComputedStyle(contentElement, "").getPropertyValue("padding-top");
                        var paddBottom_px = document.defaultView.getComputedStyle(contentElement, "").getPropertyValue("padding-bottom");
                        var paddTop = (paddTop_px?parseInt(paddTop_px.replace(/px/g, '')):0);
                        var paddBottom = (paddBottom_px?parseInt(paddBottom_px.replace(/px/g, '')):0);
                        var offsetHeight = paddTop+paddBottom;

                        var mXY = mouseXY(event);
                        _self.fResizeObject = {'dw':eWH.w,'ch':cWH.h,'mx':mXY.x,'my':mXY.y,'offsetHeight':offsetHeight};
                    }
                }, false);

                dialogElement.addEventListener("mousemove", function(event) {
                    var mXY = mouseXY(event);
                    var eXY = getXY(dialogElement);
                    var eWH = getWH(dialogElement);
                    if (eXY.x + eWH.w - 10 < mXY.x && eXY.y + eWH.h - 10 < mXY.y) {
                        document.body.style.cursor = "nw-resize";
                        _self.inResizeBox = true;
                    }
                    else {
                        document.body.style.cursor = "default";
                        _self.inResizeBox = false;
                    }
                }, false);

                document.addEventListener("mousemove", function(event) {
                    if (!_self.fResizeObject) return; var mXY = mouseXY(event);
                    var dialogWidth = _self.fResizeObject.dw + mXY.x-_self.fResizeObject.mx;
                    var contentHeight = _self.fResizeObject.ch + mXY.y-_self.fResizeObject.my;

                    if (dialogWidth < 200 || contentHeight < 5) return;

                    dialogElement.style.width = dialogWidth + "px";
                    contentElement.style.height = contentHeight - _self.fResizeObject.offsetHeight + "px";

                    if (_self.tmp['State'] == 'min' || _self.tmp['State'] == 'max') {
                        document.getElementById(_self.fSystemButton1).style.visibility = 'visible';
                        document.getElementById(_self.fSystemButton2).src = '/system/assets/images/tdialog/max.gif';
                        _self.tmp['State'] = 'normal';
                    }
                }, false);

                document.addEventListener("mouseup", function() {
                    _self.fResizeObject = null;
                    document.body.style.cursor = "default";
                }, false);
            }
        }

        this.fModalDialog = false;
        page.AvailableDialogs = page.AvailableDialogs+1;
    },


    /**
     * Checks to see if it is opened
     */
    isOpen: function()
    {
        if (document.getElementById(this.Name))
            return true;

        return false;
    },


    /**
     * Closes this dialog
     */
    close: function()
    {
        if (document.getElementById(this.Name)) {
            document.body.removeChild(document.getElementById(this.Name));
            if (this.fModalDialog && this.fEnablePageOnClose)
                page.setEnabled();
        }

        this.fEnablePageOnClose = false;
        page.AvailableDialogs = page.AvailableDialogs-1;
    },


    /**
     * Hides this dialog
     */
    show: function()
    {
        if (document.getElementById(this.Name)) {
            document.getElementById(this.Name).style.visibility = 'visible';

            if (this.fModalDialog && !page.isDisabled()) {
                page.setDisabled();
                page.bringElementToFront(document.getElementById(this.Name));
                this.fEnablePageOnClose = true;
            }
        }
    },


    /**
     * Hides this dialog
     */
    hide: function()
    {
        if (document.getElementById(this.Name)) {
            document.getElementById(this.Name).style.visibility = 'hidden';
            if (this.fModalDialog && this.fEnablePageOnClose)
                page.setEnabled();
        }

        this.fEnablePageOnClose = false;
    },


    /**
     * Bring to front
     */
    bringToFront: function()
    {
        var dialogElement = document.getElementById(this.Name);
        page.bringElementToFront(dialogElement);
    },


    /**
     * Minimize
     */
    minimize: function()
    {
        var dialogElement = this.getDialogElement();
        var contentElement = this.getContentElement();

        if (this.tmp['State'] == 'min') {
            return;
        }
        else {
            if (this.tmp['State'] == 'max') {
            }
            if (this.tmp['State'] == 'normal') {
                var dXY = getXY(dialogElement);
                var dWH = getWH(dialogElement);
                var cWH = getWH(contentElement);
                this.tmp['x'] = dXY.x; this.tmp['y'] = dXY.y; this.tmp['w'] = dWH.w; this.tmp['h'] = cWH.h;
            }
            this.tmp['State'] = 'min';
            document.getElementById(this.fSystemButton1).style.visibility = 'hidden';
            document.getElementById(this.fSystemButton2).src = '/system/assets/images/tdialog/restore.gif';
            contentElement.style.height = "1px";
        }
    },


    /**
     * Maximize
     */
    maximize: function()
    {
        var dialogElement = this.getDialogElement();
        var contentElement = this.getContentElement();

        if (this.tmp['State'] == 'normal') {
            var dXY = getXY(dialogElement);
            var dWH = getWH(dialogElement);
            var cWH = getWH(contentElement);
            this.tmp['x'] = dXY.x; this.tmp['y'] = dXY.y; this.tmp['w'] = dWH.w; this.tmp['h'] = cWH.h;
            this.tmp['State'] = 'max';
            document.getElementById(this.fSystemButton2).src = '/system/assets/images/tdialog/restore.gif';
            dialogElement.style.width = page.windowWidth()-16 + "px";
            contentElement.style.height = page.windowHeight()-70 + "px";
            dialogElement.style.left = "8px";
            dialogElement.style.top = "5px";
        }
        else if (this.tmp['State'] == 'min' || this.tmp['State'] == 'max') {
            this.restore();
        }
    },


    /**
     * Restore
     */
    restore: function()
    {
        var dialogElement = this.getDialogElement();
        var contentElement = this.getContentElement();
        if (this.tmp['State'] == 'min' || this.tmp['State'] == 'max') {
            this.tmp['State'] = 'normal';
            dialogElement.style.width = this.tmp['w'] + "px";
            contentElement.style.height = this.tmp['h'] + "px";
            document.getElementById(this.fSystemButton1).style.visibility = 'visible';
            document.getElementById(this.fSystemButton2).src = '/system/assets/images/tdialog/max.gif';
            moveTo(dialogElement, this.tmp['x'], this.tmp['y']);
        }
    },


    /**
     * To html
     */
    toHtml: function()
    {
        var html = "";
        html += "<table border='0' cellspacing='1' style='width:100%;'>";

        var systemButtons = "";
        var tdWidth = "1px;";
        if (this.fShowSystemButtons) {
            tdWidth = "50px;";
            systemButtons = 
              "<a id='" + this.fSystemButton1 + "Click' href='#'><img id='" + this.fSystemButton1 + "' src='/system/assets/images/tdialog/min.gif' border='0' /></a>&nbsp;" +
              "<a id='" + this.fSystemButton2 + "Click' href='#'><img id='" + this.fSystemButton2 + "' src='/system/assets/images/tdialog/max.gif' border='0' /></a>&nbsp;" +
              "<a id='" + this.fSystemButton3 + "Click' href='#'><img id='" + this.fSystemButton3 + "'src='/system/assets/images/tdialog/close.gif' border='0' /></a>&nbsp;";
        }

        if (this.fShowTitle) {
            var insideTable = "<table border='0' cellspacing='0' style='width:100%;'><tr><td style='width:" + tdWidth + ";text-align:left;'></td><td id='" + this.fTitleElementID + "' class='title'>" + this.fTitle + "</td><td style='width:" + tdWidth + ";text-align:right'>" + systemButtons + "</td></tr></table>";
            html += "<tr><td class='header'>" + insideTable + "</td></tr>";
        }
        
        var contentStyle = "";
        if (this.fContentBoxConstraints) {
            contentStyle = "height:" + this.fContentBoxConstraints['h'] + "px;overflow:" + this.fContentBoxConstraints['overflow'];
        }
        html += "<tr><td><div id='" + this.fContentElementID + "' class='content' style='" + contentStyle + "'>" + this.fContent + "</div></td></tr>";

        if (this.fButtons.length > 0) {
            html += "<tr><td style='text-align:center'>";
            for (var index in this.fButtons) {
                 var btnAttr = this.fButtons[index];
                 html += "<input id='" + btnAttr['id'] + "' type='button' value=\"" + btnAttr['label'] + "\" class='button' />&nbsp;";
            }
            html = html.substr(0, html.length-6);
            html += "</td></tr>";
        }

        html += "</table>";

        return html;
    }
});




/************************************************************************************
 * THttpAjaxData definition
 ************************************************************************************/

var THttpAjaxData = TClass.extend({},
{
    /**
     * Constructor
     */
    initialize: function()
    {
        this.clear();
    },


    /**
     * Add parameter
     */
    addParameter: function(key, value)
    {
        this.parameters[ key ] = value;
    },


    /**
     * Get parameter
     */
    getParameter: function(key, defaultValue)
    {
        var temp = this.parameters[ key ];

        if (!temp && defaultValue)
            temp = defaultValue;

        return temp;
    },


    /**
     * Get parameter
     */
    get: function(key, defaultValue)
    {
        return this.getParameter(key, defaultValue);
    },


    /**
     * Remove parameter
     */
    removeParameter: function(key)
    {
        if (this.parameters[key] != null) {
            delete this.parameters[key];
        }
    },


    /**
     * Get parameters
     */
    getParameters: function()
    {
        var temp = {};

        for (i in this.parameters)
             if (i != "response-type")
                 temp[i] = this.parameters[i];

        return temp;
    },


    /**
     * Add script file
     */
    addScript: function(scriptFile, id)
    {
        this.scriptFiles.push(scriptFile);
        if (id) this.tmp[scriptFile] = id;
    },


    /**
     * Add script content
     */
    addScriptContent: function(scriptContent)
    {
        this.scriptContents.push(scriptContent);
    },


    /**
     * Add css file
     */
    addCss: function(cssFile, id)
    {
        this.cssFiles.push(cssFile);
        if (id) this.tmp[cssFile] = id;
    },


    /**
     * Add script code for execution
     */
    addExecutionScriptCode: function(scriptCode)
    {
        this.executionScriptCodes.push(scriptCode);
    },


    /**
     * Get ok message
     */
    getOkMessage: function()
    {
        return this.parameters["0"];
    },


    /**
     * isOk
     */
    isOk: function()
    {
        var type = this.getParameter("response-type");
        return (type == "ok" ? true : false);
    },


    /**
     * Get error message
     */
    getErrorMessage: function()
    {
        return this.parameters["0"];
    },


    /**
     * isError
     */
    isError: function()
    {
        var type = this.getParameter("response-type");
        return ( type == "error" ? true : false );
    },


    /**
     * isType
     */
    isType: function(t)
    {
        return ( this.getParameter( "response-type" ) == t );
    },


    /**
     * Execute
     */
    execute: function()
    {
        for (i in this.cssFiles) page.addCss(this.cssFiles[i], this.tmp[this.cssFiles[i]]);
        for (i in this.scriptFiles) page.addScript(this.scriptFiles[i], this.tmp[this.scriptFiles[i]]);
        for (i in this.scriptContents) page.addScriptContent(this.scriptContents[i]);
        for (i in this.executionScriptCodes) page.safeExec(this.executionScriptCodes[i]);
        this.clear();
    },


    /**
     * Clear
     */
    clear: function()
    {
        this.parameters = {};
        this.scriptFiles = Array();
        this.scriptContents = Array();
        this.executionScriptCodes = Array();
        this.cssFiles = Array();
        this.tmp = {};
    },


    /**
     * Debug
     */
    debug: function()
    {
        var str = "Object (\n";

        for (i in this.parameters)
             str += "\t" + i + "=" + this.parameters[i] + "\n";

        str += ")";

        if (this.Text)
            str = this.Text + "\n\n" + str;

        print_r(str);
    }

});





/************************************************************************************
 * THttpAjax definition
 ************************************************************************************/

var THttpAjax = TClass.extend( {},
{
    /**
     * Constructor
     */
    initialize: function()
    {
        this.httpRequest = false;
        this.Initialized = false;
        this.callbacks = new Object();
        this.requestInProgress = false;
        this.requestQueue = new Array();
        this.TargetUri = null;
        this.TargetMethod = 'post';
        this.debugMode = false;
        this.fUidNumber = 73641;

        if (typeof XMLHttpRequest == "undefined") {
            try {
                this.httpRequest = new ActiveXObject("Msxml2.XMLHTTP.6.0");
            } catch(e) {
                try {
                    this.httpRequest = new ActiveXObject("Msxml2.XMLHTTP.3.0");
                } catch(e) {
                    try {
                        this.httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
                    } catch(e) {
                        try {
                            this.httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch(e) {
                        }
                    }
                }
            }
        }
        else {
            this.httpRequest = new XMLHttpRequest();
        }


        if (this.httpRequest) {
            this.Initialized = true;
        }
        else {
            alert("Ajax can't be instantiated");
        }
    },


    /**
     * Do http get
     */
    doHttpGet: function(text)
    {
        this.requestInProgress = true;

        this.httpRequest.open("GET", this.TargetUri + "?" + text, true);

        var self = this;
        this.httpRequest.onreadystatechange = function() {
            if (self.httpRequest.readyState == 4 && self.httpRequest.status == 200) {
                self.processResponse(self.httpRequest.responseText);
                self.requestInProgress = false;
                self.processPendingRequests();
            }
        }

        this.httpRequest.send(null);
    },


    /**
     * Do http post
     */
    doHttpPost: function(text)
    {
        this.requestInProgress = true;

        var url = this.TargetUri + "?" + (this.fUidNumber++);

        this.httpRequest.open("POST", url, true);
        this.httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        this.httpRequest.setRequestHeader("Content-length", text.length);
        this.httpRequest.setRequestHeader("Connection", "close");
        
        var self = this;
        this.httpRequest.onreadystatechange = function() {
            if (self.httpRequest.readyState == 4 && self.httpRequest.status == 200) {
                self.processResponse(self.httpRequest.responseText);
                self.requestInProgress = false;
                self.processPendingRequests();
            }
        }

        this.httpRequest.send(text);
    },


    /**
     * Free
     */
    free: function()
    {
        this.httpRequest = null;
    },


    /**
     * Make request
     */
    makeRequest: function(data, aHandler, method)
    {
        data["eventSource"] = "Ajax";
        data["eventType"] = "OnRequest";

        if (aHandler) {
            var trackID = page.createUID();
            data["_data_trackID"] = trackID;
            this.callbacks[trackID] = aHandler;
        }

        if (method && method.toLowerCase() == 'get') {
            this.TargetMethod = 'get';
        }

        this.requestQueue.push(httpBuildQuery(data, {'target':'ajax'}));
        this.processPendingRequests();

        this.TargetMethod = 'post';
    },


    /**
     * Make url request
     */
    makeURLRequest: function(url, data, aHandler, method)
    {
        var tmp = this.TargetUri;
        this.TargetUri = url;
        this.makeRequest(data, aHandler, method);
        this.TargetUri = tmp;
    },


    /**
     * Process pending requests
     */
    processPendingRequests: function()
    {
        if (!this.requestInProgress) {
            if (this.requestQueue.length > 0) {
                if (this.TargetMethod == 'post') {
                    this.doHttpPost(this.requestQueue.shift());
                }
                else {
                    this.doHttpGet(this.requestQueue.shift());
                }
            }
        }
    },


    /**
     * Process response
     */
    processResponse: function(text)
    {
        if (this.debugMode) {
            print_r(text);
        }

        var result = new THttpAjaxData();
        var temp = httpParseQuery(text);

        var trackID;

        for (var key in temp) {
             if (key.indexOf("setcookie:;:") == 0) {
                 var rawstr = key; rawstr = rawstr.replace("setcookie:;:", "");
                 var name = rawstr.substr(0,rawstr.indexOf(":;:"));
                 var expires = rawstr.substr(rawstr.indexOf(":;:")+3);
                 if (expires == -1 && temp[key] == "removeme") {
                     page.removeCookie(name);
                 }
                 else {
                     page.setCookie(name,temp[key],expires);
                 }
             }
             else if (key.indexOf("___addscript:;:") == 0) {
                 var rawstr = key; rawstr = rawstr.replace("___addscript:;:", "");
                 var tmp = rawstr.split(':;:'); var id = (tmp.length == 2 && tmp[1] ? tmp[1] : null);
                 result.addScript(temp[key], id);
             }
             else if (key.indexOf("___addscript_c") == 0) {
                 result.addScriptContent(temp[key]);
             }
             else if (key.indexOf("___addcss:;:") == 0) {
                 var rawstr = key; rawstr = rawstr.replace("___addcss:;:", "");
                 var tmp = rawstr.split(':;:'); var id = (tmp.length == 2 && tmp[1] ? tmp[1] : null);
                 result.addCss(temp[key], id);
             }
             else if (key.indexOf("___safe_exec") == 0) {
                 result.addExecutionScriptCode(temp[key]);
             }
             else if (temp[key].indexOf("Array[Y0hf5T23eDsFglO3Tyl]=") == 0) {
                 result.addParameter(key, httpParseQuery(temp[key].substr(27)));
             }
             else if (key.indexOf("_data_trackID") == 0) {
                 trackID = temp[key];
             }
             else {
                 result.addParameter(key, temp[key]);
             }
        }

        if (trackID && this.callbacks[trackID]) {
            this.callbacks[trackID].call(this, result);
            delete this.callbacks[trackID];
        }
    },


    /**
     * Before populate
     */
    beforePopulate: function(controlNames, loadingSign)
    {
    	  for (var i in controlNames) {
    	       var controlName = controlNames[i];
    	       var targetElement = document.getElementById(controlName);
    	       if (targetElement) {
    	           var tagName = targetElement.tagName.toLowerCase();
    	           if (tagName == "select") {
    	               targetElement.options.length = 0;
    	           }
    	           else if (tagName == "span" || tagName == "div" || tagName == "td") {
    	               setHtml(targetElement, "");
    	               if (loadingSign && loadingSign == true) {
    	                   setHtml(targetElement, "<img src='/system/assets/images/loading.gif' border='0' />");
    	               }
    	           }
    	           else if (tagName == "img") {
    	               targetElement.src = "/system/assets/images/loading.gif";
    	           }
    	           else if ((tagName == "input" && targetElement.type == "text") || tagName == "textarea") {
    	               targetElement.value = "";
    	           }
    	           else if (tagName == "input" && targetElement.type == "hidden") {
    	               var targetElement2 = document.getElementById(controlName + "Iframe");
    	               if (targetElement2 && targetElement2.tagName.toLowerCase() == "iframe") {
    	                   targetElement.value = "";
    	                   eval(controlName + ".onHiddenFieldChanged()");
   	                 }
    	           }
    	       }
    	  }
    },


    /**
     * Process pending requests
     */
    populate: function(data, aOkHandler, aErrorHandler)
    {
        var self = this;
    	  this.makeRequest(data,
	  	             function (dataEvent) {
	  	                 if (dataEvent.isOk()) {
	  	                     dataEvent.removeParameter("response-type");
	  	                     self.sendDataToControls(dataEvent);
	  	                     dataEvent.execute();
	  	                     if (aOkHandler)
	  	                         aOkHandler.call(this, dataEvent.getOkMessage());
	  	                 }
	  	                 else if (dataEvent.isError() && aErrorHandler) {
	  	                     dataEvent.removeParameter("response-type");
	  	                     aErrorHandler.call(this, dataEvent.getErrorMessage());
	  	                 }
	  	             });
    },


    /**
     * Process pending requests
     */
    sendDataToControls: function(ajaxData)
    {
    	  for (var controlName in ajaxData.getParameters()) {
    	       var controlData = ajaxData.getParameter(controlName);

    	       var targetElement = document.getElementById(controlName);
    	       if (targetElement) {
    	           var tagName = targetElement.tagName.toLowerCase();
    	           if (tagName == "select" && typeof(controlData) == "object") {
    	               targetElement.options.length = 0;

                     for (key in controlData)
                          targetElement.options[targetElement.options.length] = new Option(controlData[key], key);

    	           }
    	           else if (tagName == "span" || tagName == "div" || tagName == "td") {
    	               setHtml(targetElement, controlData);
    	           }
    	           else if (tagName == "img") {
    	               targetElement.src = controlData;
    	           }
    	           else if ((tagName == "input" && targetElement.type == "text") || tagName == "textarea") {
    	               targetElement.value = controlData;
    	           }
    	           else if (tagName == "input" && targetElement.type == "hidden") {
    	               var targetElement2 = document.getElementById(controlName + "Iframe");
    	               if (targetElement2 && targetElement2.tagName.toLowerCase() == "iframe") {
    	                   targetElement.value = controlData;
    	                   eval(controlName + ".onHiddenFieldChanged()");
    	               }
    	           }
    	       }
    	  }
    }

});