﻿var MAYOR_LOADING = false;

function loadMainContent(URL, xmlRequest, containerId) {
    if (containerId == null)
        containerId = "mayor";

    if (containerId == "mayor") {
        showLoadingSign();
        //MAYOR_LOADING = true;
        //top.setInterval(, 3000);
    }
    
    if (URL == null)
        setNewMainContent("<root/>", containerId);
    else
        doXMLHttpRequest(URL, null,  
            function (result) {
                setNewMainContent(result, containerId);
                if (containerId == "mayor") {
                    //MAYOR_LOADING = false;
                    hideLoadingSign();
                }
            }
        );
    
    if (containerId == "mayor") {
        if(AHCHOR_INTERVAL_ID)
            clearInterval(AHCHOR_INTERVAL_ID);
        URL = getPageAnchor(URL);
        doXMLHttpRequest(URL, null, 
            function (result) {
                setNewAnchor(result);
                if(AHCHOR_INTERVAL_ID)
                    AHCHOR_INTERVAL_ID = window.setInterval(checkAchorsDiffers, 1000);
            }
        );
    }
    
}

function setNewAnchor(xml) {
    getXMLFromText(xml, 
        function (xmlDoc) {
            var anchor = selectSingleNodeValue(xmlDoc, "/response/location");
            if (anchor != null) {
                var url = anchor.substring(1, anchor.length);
                try {
                    if (_gat) {
                        var pageTracker=_gat._getTracker(G_AN_ID);
                        pageTracker._trackPageview("/" + url);
                    }
                }catch(ex){}
                
                anchor = "#hr:" + url;
                document.location.hash = anchor;
                CUR_ANCHOR = anchor;
                if (document.getElementById("__ID_856") != null) {
                    var switcher = document.getElementById("__ID_856");
                    var loc = switcher.contentWindow.location.href;
                    loc = loc.substring(0, loc.indexOf("myajax/") + 7) + url;
                    switcher.contentWindow.location = loc;
                }
            }
        }
    );
}

function getPageAnchor(URL) {
    if (URL.indexOf("?") >= 0)
        URL = URL + "&getRLocation";
    else
        URL = URL + "?getRLocation";
    return URL;
}

function gotoAchorPage(anchor) {
    if (anchor.indexOf("#hr:") == 0) {
        var url = anchor.substring(4, anchor.length);
        if (url.length > 0)
            loadMainContent(buildPHPURL(url), null, null);
    }
}

function setNewMainContent(content, containerId) {
    
    document.getElementById("ruler").style.height = "0px";
    var container = document.getElementById(containerId);
    setInnerHTML(container, content);
    if (containerId == "mayor") {
        var pageCodeContainer = document.getElementById("activeMMItem");
        if (pageCodeContainer != null && pageCodeContainer.value == "loginPage_0001") {
            document.getElementById("LM").style.display = "none";
            document.getElementById("LM").innerHTML = "";
            document.getElementById("BNRS").style.display = "none";
            document.getElementById("BNRS").innerHTML = "";
            document.getElementById("BNRS_ADV").style.display = "none";
            document.getElementById("BNRS_ADV").innerHTML = "";
            if (document.getElementById("SUF") != null) {
                document.getElementById("SUF").style.display = "none";
                document.getElementById("SUF").innerHTML = "";
            }
            document.getElementById("syncSplash").innerHTML = "";
            document.getElementById("syncSplash").style.display = "none";
        } else if (pageCodeContainer != null && pageCodeContainer.value.indexOf("001_admin_") == 0) {
            document.getElementById("LM").style.display = "none";
            document.getElementById("LM").innerHTML = "";
            document.getElementById("BNRS").style.display = "none";
            document.getElementById("BNRS").innerHTML = "";
            document.getElementById("BNRS_ADV").style.display = "none";
            document.getElementById("BNRS_ADV").innerHTML = "";
            if (document.getElementById("SUF") != null) {
                document.getElementById("SUF").style.display = "none";
                document.getElementById("SUF").innerHTML = "";
            }
        } else {
            document.getElementById("LM").style.display = "block";
            if (document.getElementById("LM").getElementsByTagName("P").length == 0)
                loadMainContent(buildPHPURL("leftMenu.php"), null, "LM");

            document.getElementById("BNRS_ADV").style.display = "block";
            if (document.getElementById("BNRS_ADV").getElementsByTagName("P").length == 0)
                loadMainContent(buildPHPURL("banners.php?tp=adv"), null, "BNRS_ADV");

            document.getElementById("BNRS").style.display = "block";
            if (document.getElementById("BNRS").getElementsByTagName("P").length == 0)
                loadMainContent(buildPHPURL("banners.php"), null, "BNRS");
            
            if (document.getElementById("SUF")) {
                document.getElementById("SUF").style.display = "block";
                if (document.getElementById("SUF").getElementsByTagName("P").length == 0)
                    loadMainContent(buildPHPURL("../HTML/sign_up_form.html"), null, "SUF");
            }
            
            loadSyncSplash();
        }
        
        scrollUp();
        activateLinckedMMItem();
        
    }
    checkHeights();
}

function doXMLHttpRequest(URL, xmlRequest, callBackFunction) {
    var request = createRequestObject();
    if (request != null) {
        request.onreadystatechange = 
            function() {
                if (request.readyState == 4 && callBackFunction != null) {
                    if (request.status == 200) {
                        callBackFunction(request.responseText);
                    } else {
                        callBackFunction("Не удалось получить данные:\n" + request.statusText);
                    }
                }
            }
        var method = (xmlRequest != null) ? "POST" : "GET";
        request.open(method, URL, true);
        if (method == "POST") 
            request.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded");
        
        var params = xmlRequest == null ? null : "requestXML=" + encodeURIComponent(getOuterXml(xmlRequest));
        request.send(params);
    }
}

function createRequestObject() {
    if (window.XMLHttpRequest) {
        try {return new XMLHttpRequest();} 
        catch (e){}
    } 
    else if (window.ActiveXObject) {
        try {return new ActiveXObject('Msxml2.XMLHTTP');} 
        catch (e) {
            try {return new ActiveXObject('Microsoft.XMLHTTP');} 
            catch (e){}
        }
    }
    return null;
}

function buildRootPath() {
    return document.location.protocol + "//" + document.location.host + "/propartner/";
}

function buildPHPURL(doc) {
    return buildRootPath() + "php/" + doc + (doc.indexOf("?", 0) >= 0 ? "&" : "?") + "guid=" + getGuid() + getDebugInfo();
}

function getDebugInfo() {
    var paramName = "XDEBUG_SESSION_START=";
    
    var s = new String(location.search);
    var i = s.lastIndexOf(paramName, 1);
    var sessionNumber = "";
    if (i > 0) {
        sessionNumber = s.substring(i + paramName.length, s.length);
    }
    var result = "";
    if (allTrim(sessionNumber).length > 0)
        result = "&XDEBUG_SESSION_START=" + sessionNumber;
    return result;
}

function buildXMLURL(doc) {
    var result = buildRootPath() + "xml/" + doc;
    if (doc.indexOf(".php") > -1)
        result = buildRootPath() + "php/" + doc;
    return result;
}

function getGuid() {
    var guid = "";
        for (var i = 0; i < 32; i++)
            guid += parseInt(Math.random() * 16).toString(16);
    return guid;
}

function leftTrim(sString) {
    if (sString != null && sString.substring)
        while (sString.substring(0,1) == ' ')
            sString = sString.substring(1, sString.length);
    return sString;
}

function rightTrim(sString) {
    if (sString != null && sString.substring)
        while (sString.substring(sString.length-1, sString.length) == ' ')
            sString = sString.substring(0,sString.length-1);
    return sString;
}

function allTrim(sString) {
    return leftTrim(rightTrim(sString));
}

function setStatesByCountry(countryControlId, stateControlId, tmpComtrolName) {

    var countryElement = document.getElementById(countryControlId);
    var stateElement = document.getElementById(stateControlId);

    if (countryElement == null || stateElement == null) {
    
    
    } else if (countryElement != null && countryElement.value != null && stateElement != null) {
    
        var wrWl = stateElement.parentNode.previousSibling.getElementsByTagName("SPAN")[0];
        if (countryElement.value == "USA" || countryElement.value == "AUS" || countryElement.value == "CAN") {
            wrWl.innerHTML = "&#xA0;*";
            stateElement.setAttribute("valueReq", "1");
        } else {
            wrWl.innerHTML = "";
            stateElement.setAttribute("valueReq", "");
        }
    

        var tempControlId = tmpComtrolName != null ? tmpComtrolName : "tmpdd";
        var tempControl = document.getElementById(tempControlId);
        
        if (tempControl == null) {
            tempControl = document.createElement("select");
            tempControl.setAttribute("id", tempControlId);
            tempControl.style.display = "none";
            document.body.appendChild(tempControl);
        }
        
        var current = stateElement.firstChild;
        while(current != null) {
            var next = current.nextSibling;
            if (current.attributes["selected"] && current.selected)
                current.setAttribute("sld", "1");
            current.parentNode.removeChild(current);
            tempControl.appendChild(current);
            current = next;
        }
        
        var countryCode = countryElement.value;
        
        var current = tempControl.firstChild;
        while(current != null) {
            var next = current.nextSibling;
            if ((current.attributes["country"] != null && current.attributes["country"].nodeValue == countryCode) || (current.attributes["empty"] != null)) {
                current.parentNode.removeChild(current);
                stateElement.appendChild(current);
                
                if (current.attributes["sld"] != null)
                    stateElement.value = current.attributes["value"].nodeValue;
            }
            current = next;
        }
   }
    
}

function getBin(URL, addToGoogleAnalitics) {
    
    if (addToGoogleAnalitics) {
        try {
            if (_gat) {
                var pageTracker = _gat._getTracker(G_AN_ID);
                pageTracker._trackPageview("/" + URL);
            }
        } catch(ex) {}
    }
    
    if (document.getElementById("__ID_867") != null) {
        document.getElementById("__ID_867").contentWindow.document.location = buildPHPURL(URL);
    }
}

function loadSyncSplash() {

    var URL = buildPHPURL("veeamSync.php?action=check");
    doXMLHttpRequest(URL, null, 
        function (answer) {
            getXMLFromText(answer, 
                function (doc) {
                
                    var empty = selectSingleNodeValue(doc, "/responce/empty");
                    if (empty == null && answer != null && answer != "") {
                       setNewMainContent(answer, "syncSplash"); 
                       document.getElementById("syncSplash").style.display = "block";
                    } else {
                       setNewMainContent("", "syncSplash"); 
                       document.getElementById("syncSplash").style.display = "none";
                    }
                    
                });
                
        });
}

function closeSyncSplash() {
    registrationComlete("veeamSyncSplashRequest.xml", "splashForm", "veeamSync.php?action=check", 
        function (answer){
            setNewMainContent("", "syncSplash"); 
            document.getElementById("syncSplash").style.display = "none";
        });
}

function showLoadingSign() {
    //if (MAYOR_LOADING == true) {
        var element = document.getElementById("loadingSign");
        element.style.display = "block";
        element.style.top = (document.body.scrollTop) + "px";
        element.style.left = (document.body.scrollLeft) + "px";
    //}
}

function hideLoadingSign() {
    var element = document.getElementById("loadingSign");
    element.style.display = "none";
}

function jsStringReplace(text,searchString, replaceString)
{
    lengthSearchString=searchString.length;
    lengthReplaceString=replaceString.length;
    rezultText=text;
    start_poz=0;//начальная позиция с которой начинаем поиск заданной подстроки
    while ((poz=rezultText.indexOf(searchString,start_poz))!=-1)
    {
        firstPart=rezultText.substring(0,poz);
        lengthRezultText=rezultText.length;
        endPart=rezultText.substring(poz+lengthSearchString, lengthRezultText );
        rezultText=firstPart+replaceString+endPart;
        start_poz=poz+lengthReplaceString;
    }
    return (rezultText);
}

//forms actions
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function registerCallBack(answer) {
    getXMLFromText(answer,
        function(xmlDoc) {
            var status = selectSingleNodeValue(xmlDoc, "/responce/reason");
            if (status != null) {
                alert(status);
            } else {
                setNewMainContent(answer, "mayor");
            }
        });
}


function onSelectKeyDown(event) {
    if(event.keyCode == 13) {
        event.cancelBubble = true;
        event.returnValue = false;
        registrationComlete('loginRequest.xml', 'loginForm', 'login.php', loginCallBack);
        return false;
    }
}

function checkSubmitAnswer(answer) {
    if (answer == "Registered")
        loadMainContent(buildPHPURL("profileViewer.php"));
    else
        alert(answer);
}

function checkSubmitAppAnswer(answer) {
    if (answer == "Registered")
        history.go(-1);
    else
        alert(answer);
}

function findCompanyCallBack(answer) {
    setNewMainContent(answer, "mayor");
    var anchor = document.getElementById("searchAnchorState").value;
    setNewAnchor(jsStringReplace(anchor, "&", "&amp;"));
}

function scrollUp() {
    if (document.body.scrollTop > 100)
        document.body.scrollTop = 0;
}

