AJAX_DEBUG = false;
JS_DEBUG = false;
REQUEST_FIRST = new Array("/index", "", "")
AJAX_HISTORY = new Array(REQUEST_FIRST);
AJAX_HISTORY_ITEM = 1;

/**
 * Xms error handler 
 * @TODO: must load as early as possible
 */
ERROR_HANDLER = function(description, pagename, lineno, name) {
    if(JS_DEBUG) {
        type = (name) ? name + ': ':'Error: ';
        alert(
            type  + description
            +'\n in ' + pagename
            +'\n (line ' + lineno + ')'
        );
    }
    return true;
}
/**
 * setting window error handler 
 * @TODO: must load as early as possible
 */
onerror = ERROR_HANDLER;

Ajax.Responders.register({
  onCreate: function() {
    Xms.showThrobber();
  }, 
  onComplete: function(transport) {
    Xms.hideThrobber();
  },
  onFailure:  function() {
    alert('Request failure. Try repeat action.');
    Xms.hideThrobber();
  }
});

/**
 * xms ajax call function based on prototype AJAX.Request
 */
call = function(requestpath, args, callback, reghistory)
{
    if(reghistory == undefined) reghistory = true;
    if(reghistory){
        pushAjaxRequest(requestpath, args, callback);
    }
    new Ajax.Request(
        document.location.href, 
        {
            postBody: 'requestpath=' + requestpath + '&args[]=' + Object.toJSON(args),
            method: 'post',
            onComplete: function(transport) {
                //alert(transport.responseText);
                if (transport.responseText.charAt(0) != '[') {
                    Xms.hideThrobber();
                    (AJAX_DEBUG) ? debug(transport.responseText) : '';
                    return;
                }
                var jsonData = transport.responseText.evalJSON();
                if (jsonData == undefined) {
                    Xms.hideThrobber();
                    (AJAX_DEBUG) ? debug(transport.responseText) : '';
                    return;
                } 
                if(!callback) {
                    try {
                        executeFunctionsArray(jsonData);
                    } catch(err) {
                        ERROR_HANDLER(errorInfo, errorInfo.fileName, errorInfo.lineNumber);
                        return;
                    }
                } else {
                    try {
                        if(null != transport.responseText.match("<html")) {
                            Xms.hideThrobber();
                            debug(transport.responseText);
                        }
                        eval(callback + '(' + transport.responseText + ')');
                    } catch(err) {
                        ERROR_HANDLER(errorInfo, errorInfo.fileName, errorInfo.lineNumber);
                        return;
                    }
                    
                }
            }
        }
    );
};
function getBase()
{
  var baseTag = document.getElementsByTagName("base");
  for(var i=0; i<baseTag.length; i++)
  {
        var baseHref = baseTag[i].href;
  }
  return baseHref;
}
/* third generation of ajax implementation in xms */
ajaxCall = function(action, args, options)
{
    var method   = 'post';
    var callback = false;
    var history  = false;
    var parameters = 'requestpath=' + action;
    if(args != undefined) {
        parameters += '&args[]=' + encodeURIComponent(Object.toJSON(args));
    } else {
        args = {};
    }
    if(options != undefined) {
        if(undefined != options['callback']) {
            callback = options['callback'];
        }
        if(undefined != options['history']) {
            history = options['history'];
        }
        if(undefined != options['method']) {
            method = options['method'];
        }
    }
    if(method == 'get') { 
        var i = 0;
        var uri = '';
        for (i in args) {
            if (args[i] != undefined) {
                uri += i + '/' + encodeURIComponent(args[i]) + '/';
            }
        }
        var location = action + '/' + uri;
        if(Prototype.Browser.IE) {
            return document.location.assign(getBase() + location);
        } else {
            return document.location.href = location; 
        }
    }
    new Ajax.Request(
        document.location.href, 
        {
            parameters: parameters,
            method: method,
            onComplete: function(transport) {
                    if(!callback) {
                        if (transport.responseText.charAt(0) != '[') {
                        (AJAX_DEBUG) ? debug(transport.responseText) : '';
                        return;
                    }
                    var jsonData = transport.responseText.evalJSON();
                    if (jsonData == undefined) {
                        (AJAX_DEBUG) ? debug(transport.responseText) : '';
                        return;
                    }
                    try {
                        executeFunctionsArray(jsonData); 
                    } catch(err) {
                        ERROR_HANDLER(errorInfo, errorInfo.fileName, errorInfo.lineNumber);
                        return;
                    }
                } else {
                    try {
                        if(null != transport.responseText.match("<html")) {
                            debug(transport.responseText);
                        }
                        eval(callback + '(' + transport.responseText + ')');
                    } catch(err) {
                        ERROR_HANDLER(errorInfo, errorInfo.fileName, errorInfo.lineNumber);
                        return;
                    }
                }
            }
        }
    );
};

/* for old mode capatible */
makeCall = call;

/**
 * function to execute default xms json response - array of function with parametrs
 */
executeFunctionsArray = function(jsonData)
{
    if (jsonData == undefined) {
        debug(responseText); 
    } else {
        var i = 0;
        for(i=0; i < jsonData.length; i++) {
            var params = '';
            for(exec in jsonData[i]) {
                params = jsonData[i][exec];
                var arguments = '';
                var param = '';
                var m = 0;
                for(m=0; m < params.length; m++) {
                    param = params[m];
                    arguments += Object.toJSON(param) + ',';
                }
                arguments = arguments.substring(0, arguments.length-1);
                //alert(exec + '(' + arguments + ')');
                try {
                    eval(exec + '(' + arguments + ')');
                } catch(errorInfo) {
                    ERROR_HANDLER(errorInfo.message, errorInfo.fileName, errorInfo.lineNumber, errorInfo.name);
                }
            }
        }
        return;
    }
};

/**
 * xms debbuger for json response
 */
debug = function(message)
{
    if(null != message.match("<html")) {
        var iframe = document.createElement("iframe");
        iframe.id = 'debugWindow';
        iframe.allowTransparency = "true";
        iframe.src = '';
        iframed = document.body.appendChild(iframe);
        iframed.allowTransparency  = "true";
        var doc = iframe.document;
        if(iframe.contentDocument) {
            doc = iframe.contentDocument; // For NS6
        } else if(iframe.contentWindow) {
            doc = iframe.contentWindow.document; // For IE5.5 and IE6
        }
        // Put the content in the iframe
        doc.open();
        doc.writeln(message);
        doc.close();

        //doc.body.className = 'ajax';
        doc.getElementsByTagName("html")[0].className = 'ajax';
    } else {
        message = message.escapeHTML().gsub('\\\\n', '<br/>').gsub('\\n', '<br/>');

        var file = "";
        var windowName = 'Guru meditation'+new Date().getTime();
        var options = "toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no";
        var debugWindow = window.open(file, windowName, options);

        debugWindow.document.body.style.backgroundColor = '#000';
        debugWindow.document.body.style.color = '#07FF00';
        debugWindow.document.body.innerHTML = '<pre><code>' + message + '</code></pre>';
    }
 };
/**
 * xms debbuger for json response
 */
cleanDebug = function(message)
{
    document.body.removeChild($('debugWindow'));
};

/**
 * common function to update div on page
 */
update = function(response)
{
    if(response == '') return;
    var wrapperInnerHTML = '';
    var regularExpresion = new RegExp('id="([^"]*)"');
    var matched = regularExpresion.exec(response);
    var firstId = matched[1];
    if (firstId == null) {
        alert('Cannot decode response:\n' + response);
        return false;
    }

    var element = $(firstId);
    if (element == null) {
        alert('Element ' + firstId + ' not found');
        return false;
    }

    var wrapper = $(firstId).up();
    if(undefined == wrapper) {
        alert('Element ' + id + ' must be wrapped in other element e.g. div or span');
        return false;
    }

    var wrapperTagName = (wrapper.tagName).toLowerCase();
    if(wrapperTagName == 'span') {
        wrapperInnerHTML = response.replace(/^<span>(.*)/i, '$1').replace(/(.*)<\/span>$/i, '$1');/* non html4.1 standart */
    } else if(wrapperTagName == 'div') {
        wrapperInnerHTML = response.replace(/^<div>(.*)/i, '$1').replace(/(.*)<\/div>$/i, '$1');
    } else {
        alert('Check you wrapper - it must be single span (not doctype standart) or div without any attribute');
        return false;
    }
    wrapper.innerHTML = '';
    Element.insert(wrapper, wrapperInnerHTML);
};

reload = function()
{
    location.reload();
};

pushAjaxRequest = function (requestpath, args, callback)
{
    if(!callback){
        callback = "";
    }
    var request = new Array(requestpath, args, callback);
    if(AJAX_HISTORY_ITEM == AJAX_HISTORY.length){
        AJAX_HISTORY.push(request);
        AJAX_HISTORY_ITEM += 1;
    }else if(AJAX_HISTORY_ITEM < AJAX_HISTORY.length){
        AJAX_HISTORY = AJAX_HISTORY.slice(0, AJAX_HISTORY_ITEM);
        AJAX_HISTORY.push(request);
        AJAX_HISTORY_ITEM += 1;
    }
    ajaxSetButtons();
};

ajaxGoBack = function ()
{
    if(AJAX_HISTORY.length > 1){
        if(AJAX_HISTORY_ITEM > 1){
            var request = AJAX_HISTORY[AJAX_HISTORY_ITEM - 2];
            AJAX_HISTORY_ITEM -= 1;
            call(request[0],request[1],request[2], false);
        }
    }
    ajaxSetButtons();
};
ajaxGoForward = function ()
{
    if(AJAX_HISTORY.length > 1){
        var request = AJAX_HISTORY[AJAX_HISTORY_ITEM];
        if(AJAX_HISTORY_ITEM < AJAX_HISTORY.length){
            AJAX_HISTORY_ITEM += 1;
        }
        call(request[0],request[1],request[2], false);
    }
    ajaxSetButtons();
};

ajaxLastRequest = function ()
{
    if(AJAX_HISTORY.length > 0){
        var request = AJAX_HISTORY[AJAX_HISTORY_ITEM - 1];
        call(request[0], request[1], request[2], false);
    }
}

ajaxSetButtons = function ()
{
    if($('goBack') != null && $('goNext') != null){
        if(AJAX_HISTORY_ITEM > 1){
            $('goBack').removeClassName('x-top-taskbuttons-scroller-left-disabled');
            $('goBack').addClassName('x-top-taskbuttons-scroller-left');            
        }else{
            $('goBack').removeClassName('x-top-taskbuttons-scroller-left');
            $('goBack').addClassName('x-top-taskbuttons-scroller-left-disabled');
        }
        if(AJAX_HISTORY_ITEM < AJAX_HISTORY.length){
            $('goNext').removeClassName('x-top-taskbuttons-scroller-right-disabled');
            $('goNext').addClassName('x-top-taskbuttons-scroller-right');
        }else{
            $('goNext').removeClassName('x-top-taskbuttons-scroller-right');
            $('goNext').addClassName('x-top-taskbuttons-scroller-right-disabled');
        }
    }

}

