var MAYOR_LOADING = false;

function loadMainContent(URL, xmlRequest, containerId, callback) {
    if (URL.toString().indexOf('learningCenter.php') > -1) 
        hideRightMenu = true;
    else if (URL.toString().indexOf('homePage.php') > -1) 
        hideRightMenu = true;
    else
        hideRightMenu = false;
    if (containerId == null)
        containerId = "mayor";

    if (containerId == "mayor") {
        showLoadingSign();
        //MAYOR_LOADING = true;
        //top.setInterval(, 3000);
    }
    
    if (URL == null){
        setNewMainContent("<root/>", containerId, hideRightMenu);
	}else{
        doXMLHttpRequest(URL, null,
            function (result) {        		
                setNewMainContent(result, containerId, hideRightMenu);
                if (containerId == "mayor") {
                    //MAYOR_LOADING = false;
                    if (URL.indexOf('learningCenter.php') > -1) {
                        showLoadingSign();
                        top.setInterval(hideLoadingSign, 3000);
                    }
                    else {
                        hideLoadingSign();
                    }
                }
                if (typeof callback == 'function') {
            		callback();
            	}
            }
        );
	}
	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);
				if (hideRightMenu !== true) {
					var vspageCodeContainer = document.getElementById("activeMMItem");
					//if (vspageCodeContainer != null && (vspageCodeContainer.value == "loginPage_0001" || vspageCodeContainer.value.indexOf("001_admin_") == 0)){
					if (vspageCodeContainer != null && (vspageCodeContainer.value.indexOf("001_admin_") == 0)){
					}else{
						document.getElementById("LM").style.display = "block";
						loadMainContent(buildPHPURL("leftMenu.php?cur_anch="+encodeURIComponent(CUR_ANCHOR.substring(4,CUR_ANCHOR.length))), null, "LM");
						//document.getElementById("BNRS_ADV").style.display = "block";
            			//loadMainContent(buildPHPURL("banners.php?tp=adv&cur_anch="+encodeURIComponent(CUR_ANCHOR.substring(4,CUR_ANCHOR.length))), null, "BNRS_ADV");
						document.getElementById("BNRS").style.display = "block";
        				loadMainContent(buildPHPURL("banners.php?cur_anch="+encodeURIComponent(CUR_ANCHOR.substring(4,CUR_ANCHOR.length))), null, "BNRS");
					}
				}
            }
        );
    }
}

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);
                    }
                    mktoMunchkin("870-LBG-312");
                }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;
                }
            }else{
				document.location.hash = 
				CUR_ANCHOR = "#hr:not_found";
			}
        }
    );
}

function getPageAnchor(URL) {
    if (URL.indexOf("?") >= 0)
        URL = URL + "&getRLocation";
    else
        URL = URL + "?getRLocation";
    return URL;
}

function gotoAchorPage(anchor) {
    //debugger;
    if (anchor == null) {
        var anch = new String(document.location.href);
        if (anch.indexOf("#hr:") >= 0) {
            anch = anch.substring(anch.indexOf("#hr:"), anch.length);
            anchor = decodeURI(anch);
        }
    }
    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, hideRightMenu) {
    
    document.getElementById("ruler").style.height = "0px";
    var container = document.getElementById(containerId);
    setInnerHTML(container, content);
    if (containerId == "mayor") {
        hideDialog();
        var pageCodeContainer = document.getElementById("activeMMItem");
//        var collapseSignElement = document.getElementById("collapseMMitems");
//        
//        if (pageCodeContainer != null) {
//            if (collapseSignElement != null && collapseSignElement.value == "1") {
//                collapseMenu(pageCodeContainer.value);
//            } else {
//                expandMenu();
//            }
//        }
        normalizeSubMenu();
        if ((pageCodeContainer != null && pageCodeContainer.value == "loginPage_0001") || document.getElementById("activeMMIE9").value == 1) {
			document.getElementById("activeMMIE9").value = 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 = "";
            }
            document.getElementById("syncSplash").innerHTML = "";
            document.getElementById("syncSplash").style.display = "none";
            document.getElementById("leadAlertSplash").innerHTML = "";
            document.getElementById("leadAlertSplash").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 if (hideRightMenu === true) {
        	$('#LM').hide();
        	$('#BNRS').hide();
        	$('#BNRS_ADV').hide();
        	$('#SUF').hide();
        	$('#rollbookIframe').css('width', '100%');
        	/*
            document.getElementById("LM").style.display = "none";
            document.getElementById("LM").innerHTML = "";
            document.getElementById("LM").style.width = "0px";
            document.getElementById("BNRS").style.display = "none";
            document.getElementById("BNRS").innerHTML = "";
            document.getElementById("BNRS").style.width = "0px";
            document.getElementById("BNRS_ADV").style.display = "none";
            document.getElementById("BNRS_ADV").innerHTML = "";
            document.getElementById("BNRS_ADV").style.width = "0px";
            document.getElementById("SUF").style.display = "none";
            document.getElementById("SUF").innerHTML = "";
            document.getElementById("SUF").style.width = "0px";
            document.getElementById('rollbookIframe').style.width = '100%';
            */
        } else {
            document.getElementById('mayor').style.width = 680;
            //document.getElementById("LM").style.display = "block";
            //if (document.getElementById("LM").getElementsByTagName("P").length == 0)
                //loadMainContent(buildPHPURL("leftMenu.php?cur_anch="+encodeURIComponent(CUR_ANCHOR.substring(4,CUR_ANCHOR.length))), 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?cur_anch="+encodeURIComponent(CUR_ANCHOR)), 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();
            loadLeadAlertSplash();
        }
        
        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("It was not possible to find the data:\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");
        
        request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        
        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, notStandardUse) {

    var countryElement = document.getElementById(countryControlId);
    var stateElement = document.getElementById(stateControlId);

    if (countryElement == null || stateElement == null) {
    
    
    } else if (countryElement != null && countryElement.value != null && stateElement != null) {
    
        if(notStandardUse != true){
			var wrWl = stateElement.parentNode.previousSibling.getElementsByTagName("SPAN")[0];
			var fedGov = document.getElementById('fedGov');
        	if (countryElement.value == "USA" || countryElement.value == "AUS" || countryElement.value == "CAN") {
				// амерским компаниям самим нужно выбрать, продают ли они
				// правительству
				if (fedGov != null) {
					fedGov.value = -1;
				}
            	wrWl.innerHTML = "&#xA0;*";
            	stateElement.setAttribute("valueReq", "1");
        	} else {
				// неамерские комании по умолчанию не продают правительству
				if (fedGov != null) {
					fedGov.value = 0;
				}
            	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).attr('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).attr('sld'))
                    stateElement.value = current.attributes["value"].nodeValue;
                else
                    $(current).removeAttr('selected');
            }
            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);
		//window.open(buildPHPURL(URL),'bygetBin');
    }
}

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 loadLeadAlertSplash() {
    return false;
    var URL = buildPHPURL("partnerLeads.php?action=alert");
    doXMLHttpRequest(URL, null, 
        function (answer) {
            getXMLFromText(answer, 
                function (doc) {
                    var empty = selectSingleNodeValue(doc, "/responce/empty");
                    if (empty == null && answer != null && answer != "") {
                       setNewMainContent(answer, "leadAlertSplash"); 
                       document.getElementById("leadAlertSplash").style.display = "block";
                    } else {
                       setNewMainContent("", "leadAlertSplash"); 
                       document.getElementById("leadAlertSplash").style.display = "none";
                    }
                });

        });
}

function closeSyncSplash() {
    registrationComlete("veeamSyncSplashRequest.xml", "splashForm", "veeamSync.php?action=check", 
        function (answer){
            setNewMainContent("", "syncSplash"); 
            document.getElementById("syncSplash").style.display = "none";
        });
}

function closeLeadAlertSplash() {
    registrationComlete("leadAlertSplashRequest.xml", "leadAlertSplashForm", "partnerLeads.php?action=close_alert", 
        function (answer){
            setNewMainContent("", "leadAlertSplash"); 
            document.getElementById("leadAlertSplash").style.display = "none";
        });
}

function showLoadingSign() 
{
    $('#loadingSign')
	    .show()
	    .css({
	        top  : $(document).scrollTop(),
	        left : $(document).scrollLeft()
	    });
    /*
    var element = document.getElementById("loadingSign");
    element.style.display = "block";
    element.style.top = ; + "px";
    element.style.left = (document.body.scrollLeft) + "px";
    */
}

function hideLoadingSign() 
{
	$('#loadingSign').hide();
	/*
    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;
}

function checkRelatedDropDownItems(parentId, childId, advAtr, setReq, hideChild) {
    var tmpId = childId + "_tmp0001";
    
    var parent = document.getElementById(parentId);
    var child = document.getElementById(childId);
    var tmp = document.getElementById(tmpId);
    
    if (tmp == null) {
        tmp = document.createElement("SELECT");
        tmp.setAttribute("id", tmpId);
        tmp.style.display = "none";
        document.getElementById("mayor").appendChild(tmp);
        
        var curOpt = child.firstChild;
        while(curOpt != null) {
            var next = curOpt.nextSibling;
            if (curOpt.tagName == "OPTION") {
                curOpt.parentNode.removeChild(curOpt);
                tmp.appendChild(curOpt);
            }
            curOpt = next;
        }
    }
    
    if (parent != null && child != null && tmp != null) {
        
        var curOpt = child.firstChild;
        while(curOpt != null) {
            var next = curOpt.nextSibling;
            curOpt.parentNode.removeChild(curOpt);
            curOpt = next;
        }

        var curParentValue = parent.value;
        var curOpt = tmp.firstChild;
        while(curOpt != null) {
            var atr = curOpt.attributes[advAtr];
            if (atr != null && atr.nodeValue == curParentValue) {
                var clonedOpt = curOpt.cloneNode(true);
                child.appendChild(clonedOpt);
            }
            curOpt = curOpt.nextSibling;
        }
    }
    
    if (setReq) {
        var span = child.parentNode.previousSibling.getElementsByTagName("SPAN")[0];
        var reqSign = "";
        var reqView = "";
        if (child.firstChild != null) {
            var reqSign = "1";
            var reqView = " *";
        }
        child.setAttribute("valueReq", reqSign);
        if (span != null)
            span.innerHTML = reqView;
    }
    
    if (hideChild)
        child.parentNode.parentNode.style.display = child.getElementsByTagName("OPTION").length == 0 ? "none" : "";
}

