var ERR_IFRAME_IS_NEEDED = -1;

var ajaxTarget = "DSRAJAX_TARGET";
var ajaxFrame = 'DSRAJAX_IFRAME';

function RequestObject()
{
    this.GetXMLHttpRequestObject = GetXMLHttpRequestObject;
    this.MakeRequestPOST = MakeRequestPOST;
    this.ProcessTarget = ProcessTarget;

    this.errors = new Array();

    function Error(error)
    {
    alert(error);
//        this.errors.push(error);
    }

    function GetLastError()
    {
        if (this.errors.length > 0)
            return this.errors[this.errors.length - 1];
    }
                       
    function GetXMLHttpRequestObject()
    {
        var http_request = false;

        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!http_request)
            Error("Browser doesn't support AJAX.");

        return http_request;
    }

    this.par = 0;
    function MakeRequestPOST(url, params, targetId, callback)
    {
        var HTTPRequest = this.GetXMLHttpRequestObject();
        
        HTTPRequest.onreadystatechange = function() { RequestDone(HTTPRequest, callback); };
//alert(url)
        HTTPRequest.open("POST", url, true);
        HTTPRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
  
        var content = "";

        if (targetId)
        {
            var oTarget = new Object();
            oTarget.key = ajaxTarget;//"DSRAJAX_TARGET"
            oTarget.value = targetId;
            params.push(oTarget);
        }

        for (var i = 0; i < params.length; i++ )
        {
            if (content.length > 0)
                content += "&";

            content += encodeURIComponent(params[i].key);
            content += "=";
            content += encodeURIComponent(params[i].value);
        }

//alert(content);
        HTTPRequest.send(content);
    }

    function RequestDone(HTTPRequest, callback)
    {
        if (HTTPRequest.readyState == 4) {
            if (HTTPRequest.status == 200) {

                var text = HTTPRequest.responseText;
//alert( text );

/*
var dbgNode = null;//document.getElementById("AJAX_DEBUG_NODE");
if (!dbgNode)
{    dbgNode = document.createElement('TEXTAREA');
    dbgNode = document.body.appendChild(dbgNode);
    dbgNode.id = "AJAX_DEBUG_NODE";
    dbgNode.rows = 20;
    dbgNode.style.width = "1000px";
}
dbgNode.value = text;
*/


                //Process scripts
                var scripts = new Array();
                var newText = "";
                do{
                    var s1 = text.search(/<script [^>]*dsrajax[^>]*>/);
                    if (s1 == -1)
                    {   
                        newText += text;
                        break;
                    }

                    newText += text.substr(0, s1);
                    text = text.substr(s1, text.length - s1);
                    var s2 = text.search('>');
                    var s3 = text.search(/<\/script[^>]*>/);
                    if (s2 == -1 || s3 == -1)
                        break;

                    var script = text.substr(s2 + 1, s3 - s2 - 1);
                    scripts.push(script);
                    //window.eval(script);

                    text = text.substr(s3, text.length - s3);
                    s2 = text.search('>');
                    if (s2 == -1)
                        break;

                    text = text.substr(s2 + 1, text.length - s2 + 1);
                }while(s1 != -1);

                text = newText;
                //End of scripts processing

                var container = document.createElement('div');
                container.innerHTML = text;

                var roots = container.getElementsByTagName("div");

                if (roots.length)
                {
                    var root = roots.item(0);
                    ProcessTarget(root);
                }
                else
                {
                    alert(text);
                    Error("Wrong response was received from server.");                    
                }

                for(var s = 0; s < scripts.length; s++)
                {
                    window.eval(scripts[s]);
                }

                if (callback)
                   callback();
            } else {
                Error('There was a problem with the request. Status: ' + HTTPRequest.status);
            }
        }
    }

    function ProcessTarget(node)
    {
//alert(node.id);
//        var error = root.getAttribute("error");
        //var targetId = root.getAttribute("target");
        if (!node)
            return;

        do {
            if (node.tagName != "DIV")
                continue;

            var targetId = node.id;
            //alert(error + " " + targetId + "\n " + root.innerHTML);
            if (!targetId)
                return;
    
            var target = document.getElementById(targetId);
    
            if (target)
            {
                if (!(target.innerHTML.length == 0 && node.innerHTML.length == 0))
                    target.innerHTML = node.innerHTML;
            }
        } while(node = node.nextSibling);
    }                      
}


function GetFormValues(node)
{
    var out = new Array();
    for(var i = 0; i < node.childNodes.length; i++)
    {
        var childNode = node.childNodes.item(i);
        if (childNode.tagName == "SELECT" || childNode.tagName == "INPUT" || childNode.tagName == "TEXTAREA")
        {
            var value = childNode.value;

            if (childNode.type == "file")
            {
                //alert("Error: Type file was found. \nUse iframe engine for this form.");
                //continue;
                return ERR_IFRAME_IS_NEEDED;
            }
            else if ((childNode.type == "checkbox" || childNode.type == "radio") && childNode.checked == false)
            {
                continue;
            }
            
            if (childNode.tagName == "SELECT" && childNode.multiple == true)
            {
                value = "";
                for(var o = 0; o < childNode.options.length; o++)    
                {
                    var opt = childNode.options.item(o);
                    if (opt.selected)
                    {
                        value += (value.length > 0 ? "," : "") + opt.value;
                    }
                }
            }   

            if (childNode.name.length)
            {
                descr = new Object();
                descr.key = childNode.name;
                descr.value = value;

                out.push(descr);
            }
        }
        else
        {
            var ret = GetFormValues(childNode);
            if (ret === ERR_IFRAME_IS_NEEDED)
                return ret;

            out = out.concat(ret);
        }
    }    

    return out;
}


function GetParamsFromForm(formId)
{
    var form = document.getElementById(formId);

    if (!form)
        return false;

    return GetFormValues(form);
}

function ProcessForm(formId, actionTarget, targetNodeId, callback, hide_loading)
{
    var form = document.getElementById(formId);
    
    if (!form)
	return false;
                
    var params = GetParamsFromForm(formId);
    if (params === false)
        return;

    if (params === ERR_IFRAME_IS_NEEDED)
    {
        form.action = actionTarget;
        MakeRequestIFRAME(form, targetNodeId, callback);
    }
    else
    {
        var request = new RequestObject();
        request.MakeRequestPOST(actionTarget, params, targetNodeId, callback);
    }

    if (!hide_loading)
    {
        //SetAjaxDivContent(targetNodeId, "Loading...");
        SetLoadingDivHTML(targetNodeId, "Loading...");
    }
}



function History()
{
    this.historyArr = new Array();
    this.AddToHistory = AddToHistory;
    this.Back = Back;
    this.Forward = Forward;
    this.CheckButtonsIcon = CheckButtonsIcon;
    this.LoadHistory = LoadHistory;


    this.current_index = 0;
    this.size = 0;    


    function GetWADiv()
    {
        return document.getElementById('DSR_AJAX_DIV_WorkArea');
    }


    function CheckButtonsIcon()
    {
        var back = document.getElementById('history_back');
        if (back)
        {
            if (this.current_index)
               back.src = "images/back_e.png";
            else
                back.src = "images/back_d.png";
        }       

        var forward = document.getElementById('history_forward');
        if (forward)
        {
            if (this.size > this.current_index + 1)
               forward.src = "images/forward_e.png";
            else
               forward.src = "images/forward_d.png";
        }       
    }


    function AddToHistory()
    {
        var waDiv = GetWADiv();
        if (waDiv)
        {
            var record = new Object();
            var instead_of_cache = document.getElementById('instead_of_cache');

            var no_cache = document.getElementById('no_cache_WorkArea');

            if (no_cache && no_cache.value == "pass")
                return;

            record.instead_of_cache = instead_of_cache ? instead_of_cache.value : null;
            record.content = waDiv.innerHTML;

            this.historyArr[this.current_index++] = record;
            this.size = this.current_index;

        }

        this.CheckButtonsIcon();
    }


    function LoadHistory(indx)
    {
        if (this.size == 0)
            return;

        if (this.size < indx)
            return;

        if (this.current_index == indx)
            return;


        this.current_index = indx;

        var waDiv = GetWADiv();
        if (waDiv)
        {
            RestoreContent(waDiv, this.historyArr[this.current_index]);
        }

    }


    function Back()
    {
        if (this.size == 0 || this.current_index == 0)
            return;

        var waDiv = GetWADiv();
        if (waDiv)
        {
            if (this.size == this.current_index)
            {
                this.AddToHistory();
                --this.current_index;
            }
            else
            {
                /*//Uncomment to save changes at button click
                var pr_size = this.size;
                this.AddToHistory();
                --this.current_index;
                this.size = pr_size;
                */
            }

            //waDiv.innerHTML = this.historyArr[--this.current_index].content;
            RestoreContent(waDiv, this.historyArr[--this.current_index]);
        }

        this.CheckButtonsIcon();
    }   

    function Forward()
    {
        if (this.size <= this.current_index + 1)
            return;

        var waDiv = GetWADiv();
        if (waDiv)
        {
            /*//Uncomment to save changes at button click
            var pr_size = this.size;
            this.AddToHistory();
            --this.current_index;
            this.size = pr_size;
            */ 

            RestoreContent(waDiv, this.historyArr[++this.current_index]);
            //waDiv.innerHTML = this.historyArr[++this.current_index].content;
        }

        this.CheckButtonsIcon();
    }


    function RestoreContent(waDiv, record)
    {
        if (record.instead_of_cache)
            SimpleRequest(record.instead_of_cache, 'WorkArea', null, null, null, true)
        else
            waDiv.innerHTML = record.content;
    }
}

//[simple history only
var g_history = new History();
var g_currentActionTarget = "";
var g_previosActionTarget = "";
var g_historyUsed = false;

function LoadHistory(loadParams)//actionTarget, targetNodeId, params, strCallback, hide_loading)
{
    targetNodeId = loadParams.targetNodeId;
    strCallback = loadParams.strCallback;
    hide_loading = loadParams.hide_loading;
    actionTarget = loadParams.actionTarget;
    params = loadParams.params;

//    if (window.self.g_params)
//        params = window.self.g_params;

    if (actionTarget == "")
    {
        if (g_historyUsed)
            actionTarget = window.self.location.href;
        else
        {
            g_historyUsed = true;
            return; //for first opened area from index page 
        }
    }

    var callback = null;
    if (strCallback)
    {
        eval ("if (window.self." + strCallback + ") callback = window.self." + strCallback);
    }

    g_historyUsed = true;

    var re = /.*[\\\\\\/]$/;
    if (re.test(actionTarget))
    {
        actionTarget = "index.php";
    }

    if (g_currentActionTarget != actionTarget)
    {
        g_currentActionTarget = actionTarget;
        SimpleRequest(actionTarget, targetNodeId, params, callback, hide_loading, true);
    }
}

window.self.document.LoadHistory = function _lh (indx){LoadHistory(indx)};


function RestoreWorkArea(direction)
{
    if (direction < 0)
        g_history.Back();
    else if (direction > 0)
        g_history.Forward();
    
}
//]simple history only


function MakeHistoryRequest(actionTarget, targetNodeId, params, callback, hide_loading)
{
    if (document.getElementById('is_admin_mode'))
        return;

    var re = /^cart\.php.*/i;
    if (re.test(actionTarget))
    {
        actionTarget = "cart_view.php"
        params = null;
    }

    var parStr = "actionTarget=" + encodeURIComponent(actionTarget);

    //check callback, if it is not global, then return false;
    if (callback)
    {
        var re = /^function ([^\s\(]+)[\s\S]+/i;

        var matches = callback.toString().match(re);
        if (matches)
        {
            var fname = matches[1];
            var global_callback = false;
            eval ("if (window.self." + fname + ") global_callback = true");
            
            if (!global_callback)
                return false;
            
            parStr += "&callback=" + encodeURIComponent(fname);
        }
    }

    if (targetNodeId)
        parStr += "&targetNodeId=" + encodeURIComponent(targetNodeId);
    if (hide_loading)
        parStr += "&hide_loading=" + encodeURIComponent(hide_loading);


    if (params)
    {
        for (var i = 0; i < params.length; i++)        
        {
            parStr += "&" + encodeURIComponent(params[i].key) + "=" + encodeURIComponent(params[i].value);
        }
    }

//alert(parStr);
    g_previosActionTarget = g_currentActionTarget;
    g_currentActionTarget = actionTarget;
    var his_fr = document.getElementById('AJAX_HISTORY');
    if (his_fr)
        his_fr.src = "history.php?" + parStr;

    g_historyUsed = true;

    return true;
}


function SimpleRequest(actionTarget, targetNodeId, params, callback, hide_loading, dont_cache)
{
    var savedTargetNodeId = targetNodeId;
    var targets = targetNodeId.split('|');

    var targetNodeId = "";
    var bIsWorkAreaPresent = false;
    for (var i = 0; i < targets.length; i++)
    {

//[simple history only
        if (targets[i] == 'WorkArea' && !dont_cache)
        {
            //g_history.AddToHistory();
            MakeHistoryRequest(actionTarget, savedTargetNodeId, params, callback, hide_loading);
            //return;
        }
//]simple history only

        targetNodeId += targetNodeId.length > 0 ? "|" : "";
        targetId = "DSR_AJAX_DIV_" + targets[i];        
        targetNodeId += targetId;
        
        if (targets[i] == "WorkArea")
            bIsWorkAreaPresent = true;
    }

    var request = new RequestObject();
    if (!params)
        params = new Array();

    request.MakeRequestPOST(actionTarget, params, targetNodeId, callback);

    if (!hide_loading)
    {
        //SetAjaxDivContent(targetNodeId, "Loading...");
        var text = "Loading...";
        if (bIsWorkAreaPresent)
            text += "<input type=\"hidden\" id=\"no_cache_WorkArea\" value=\"pass\">";
        SetLoadingDivHTML(targetNodeId, text);
    }
}


function MakeRequestIFRAME(form, targetNodeId, callback)
{
    var tFr = document.createElement('input');
    tFr.type = 'hidden';
    tFr.name = ajaxFrame;
    tFr.value = ajaxFrame;
    tFr.style.width = "0px";
    tFr.style.height = "0px";


    var tTr = document.createElement('input');
    tTr.type = 'hidden';
    tTr.name = ajaxTarget;//'DSRAJAX_TARGET';
    tTr.value = targetNodeId;
    tTr.style.width = "0px";
    tTr.style.height = "0px";

    if (callback)
        document.DSRAJAX_CALLBACK = callback;
    else
        document.DSRAJAX_CALLBACK = function() {};

    var tCb = document.createElement('input');
    tCb.type = 'hidden';
    tCb.name = 'DSRAJAX_CALLBACK';
    tCb.value = callback ? "1" : "0";
    tCb.style.width = "0px";
    tCb.style.height = "0px";


    tFr = form.appendChild(tFr);
    tTr = form.appendChild(tTr);
    tCb = form.appendChild(tCb);

    form.target = ajaxFrame;
    form.submit(); 

    tFr = form.removeChild(tFr);
    tTr = form.removeChild(tTr);
    tCb = form.removeChild(tCb);

    return;
} 

function SetAjaxDivContentP(divId, content)
{
//alert(1);
    return SetAjaxDivContent("DSR_AJAX_DIV_" + divId, content);
}


function SetLoadingDivHTML(divId, content)
{
    var targets = divId.split('|');

    var targetNodeId = "";
    for (var i = 0; i < targets.length; i++)
    {
        if (i + 1 == targets.length)
            SetAjaxDivContent(targets[i], content);
        else
            SetAjaxDivContent(targets[i], "");
    }
}

function SetAjaxDivContent(divId, content)
{
    var fullDivId = divId;
    var div = document.getElementById(fullDivId);

    if (div)
        div.innerHTML = content;
}


/*
function CopyForm(form_id)
{
    var iFrame = document.getElementById(ajaxFrame);
    iFrame.src = "copy_form.php?id=form_id";
}



function DuplicateFormFromParent(form_id)
{
    var form = window.self.parent.document.getElementById(form_id);
    var duplicate = form;//.cloneNode(true);
    //    form = document.body.appendChild(duplicate);
    form.submit();
}
*/




