var countrycode = readCookie("ruckstuhl_cc");
var appHandle = "/";
var queryString = window.top.location.search.substring(1);
var urlSelector = document.URL.substring(document.URL.indexOf(".")+1);
var langHandle = "";
var locations = new Array();
var countrySecificAddresses = new Array();
var countCountryItems = 0;
var countryLangMatch = new Array();
var languageHandles = new Array();
var redirecthandle = null;

function resetCountryItems(){
    locations = new Array();
    countCountryItems = 0;
}

function addToLocation(ccname, link, language, dealerlink, productfoot, pagefoot, pdffoot, navigation){
    locations[ccname] = new Array();
    locations[ccname][0] = link;
    locations[ccname][1] = language;
    locations[ccname][2] = dealerlink;
    locations[ccname][3] = productfoot;
    locations[ccname][4] = pagefoot;
    locations[ccname][5] = pdffoot;
    locations[ccname][6] = navigation;
    countCountryItems++;
    var ssi = link.indexOf(getAppHandle())+getAppHandle().length+1;
    var tmplang = link.substring(ssi,ssi+2);
    countryLangMatch[ccname] = tmplang;
}
function addToLanguageHandles(lang, handle){
    languageHandles[lang].push(handle);
}

function addToCountrySecificAddresses(ccname, address){
    countrySecificAddresses[ccname] = address;
}

function gotoLangPage(){
    gotoLink = getLocationsArrayValue(0);
    if(gotoLink != null && gotoLink != "" && gotoLink != undefined){
        document.location.href=gotoLink;
    }
}

function displayCountryChooser(){
    showPopWin('hiddenCountryChooserDialog', 500, 300);
}

function checkCountryCodeCookie(){
    var countrycode = readCookie("ruckstuhl_cc");
    if(countrycode==null||countrycode==""){
        createCookie("ruckstuhl_cookie_test", "check", 1);
        var testRead = readCookie("ruckstuhl_cookie_test");
        if(testRead=="check"){
            //cookies accepted - display chooser

            window.onload=function(){
                setTimeout("displayCountryChooser()", 300);
            }
        }else{
            //cookies NOT accepted - no sense to display chooser
        }
    }
    //client has a lang cookie so redirect
    checkLangHandleWithCC();
}

function createCountryChooserContent(){
    var ll = -1;
    var ccarr = new Array();
    var output="<table>";
    for (i in locations){
        ccarr[++ll] = i;
    }
    var offset = Math.ceil(ll/2);
    for(var i=0; i <= offset; i++){
        output+='<tr><td style="width: 150px"><a onclick="createCookie(\'ruckstuhl_cc\', \''+ccarr[i]+'\', 3560)" href="">'+locations[ccarr[i]][6]+'</a></td>';
        if(i+offset <= ll){
            output+='<td><a onclick="createCookie(\'ruckstuhl_cc\', \''+ccarr[i+offset]+'\', 3560)" href="">'+locations[ccarr[i+offset]][6]+'</a></td></tr>';
        }else{
            output+='<td></td></tr>';
        }
    }
    /*
     */
    return output+="</table>";

}

function checkCountryCodeDeletion(){
    if(queryString.indexOf("kc")!=-1 || urlSelector.indexOf("kc")!=-1){
        if(countrycode!=null||countrycode!=""){
            deleteCookie("ruckstuhl_cc");
            countrycode = "";
        }
    }
}

function writeGoogleMapsLink(link){
    var tmplang = getLocationsArrayValue(1);
    if(tmplang.length > 0){
        link = link+"&hl="+tmplang;
    }
    return '<a href="'+link+'" target="_blank">';
}

function getProductFoot(){
    var returnText=getLocationsArrayValue(3);
    if(returnText.length > 0){
        returnText = '<p class="rs_content_entry">'+returnText+'</p>';
    }
    return returnText;
}
function getPageFooter(){
    return getLocationsArrayValue(4);
}
function getLocationsArrayValue(subarrayindex){
    var returnVal = "";
    if (countryCodeSet && locations[countrycode] != null && typeof locations[countrycode] != "undefined" && locations[countrycode].length >= subarrayindex){
        returnVal = locations[countrycode][subarrayindex];
    }
    return returnVal;
}
function getCountrySecificAddress(){
    if(countryCodeSet && countrySecificAddresses[countrycode] != "undefined"){
        return countrySecificAddresses[countrycode];
    }
}

function countryCodeSet(){
    return (countrycode != null && typeof countrycode != "undefined" && countrycode!="");
}
function getProductFoot(){
    return '<p class="rs_content_entry">'+getLocationsArrayValue(3)+'</p>';
}

function displayDealerLink(linktext, product){
    var feedback = "";
    if(countrycode != null && typeof countrycode != "undefined" && countrycode!=""){
        if(product.length > 2){product = "."+product;}
        var tmphandle = getLocationsArrayValue(2)+product+".html";
        if(tmphandle.length > 13){
            if(linktext.length > 2){
                feedback = '<a href="'+tmphandle+'">'+linktext+'</a>';
            }else{
                feedback = tmphandle;
            }
        }
    }
    return feedback;
    
}

function checkLanguage(ah){
    appHandle = ah;
    var p1 = document.URL.substring(document.URL.indexOf(appHandle)+1+appHandle.length)
    langHandle = p1.substring(0, p1.indexOf("/"));
    languageHandles['en'] = new Array();
    languageHandles['de'] = new Array();
    languageHandles['fr'] = new Array();
    languageHandles['it'] = new Array();
}

function checkLangHandleWithCC(){
    var targetlang = getLangFromCountryCode();
//    if(window.languageHandles[targetlang]){
        var currenturl = location.href;
        var currentpath = location.pathname;
        currentpath = currentpath.substring(appHandle.length+1);
        choosenlang = currentpath.substring(0,2);
        if(targetlang != choosenlang && window.languageHandles[choosenlang]){
            //forward to page
            //var firstLevelItem = currentpath.substring(3);
            var firstLevelItem = currentpath.substring(0,currentpath.indexOf("/", 3));
            //check if current page is first level item 
            if(firstLevelItem.length<1){
                firstLevelItem = currentpath.substring(0,currentpath.indexOf(".", 3));
            }
            var restHandle = currentpath.substring(currentpath.indexOf("/")+1);
            if(restHandle.indexOf("/")==-1){
                restHandle = restHandle.substring(restHandle.indexOf("."));
            }else{
                restHandle = restHandle.substring(restHandle.indexOf("/"));
            }
            var index = getItemRow("/"+firstLevelItem, languageHandles[choosenlang]);
            //alert(currentpath+" ** "+targetlang +"|"+ choosenlang+"|"+firstLevelItem+"|"+restHandle);
            if(index!=-1){
                var redirecthandle = appHandle+languageHandles[targetlang][index]+restHandle;
                setRedirecthandle(redirecthandle);
                redirectIfValidPage(redirecthandle);
            }
        }
  //  }
}

function setAppHandle(ah){
    appHandle = ah;
}
function getAppHandle(){
    return appHandle;
}

function createCookie(name,value,days) {
    if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/; domain=.ruckstuhl.com";
    //document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function deleteCookie(name) {
    createCookie(name, '', 0);
    var expires = "Thu, 01-Jan-1970 00:00:01 GMT";
    //document.cookie = name+"="+";"+expires+"; path=/; domain="+escape ( '.ruckstuhl.com' );
    //document.cookie = name+"="+";"+expires+"; path=/; domain=ruckstuhl.com";
    //document.cookie = name+"="+";"+expires+"; path=/";
}

var priceList = new Array();
function addToPriceList(cc, cur, amt){
    priceList[cc] = new Array();
    priceList[cc][0] = cur;
    priceList[cc][1] = amt;
}

function showPrice(defaultcountrycode){
    if(!window.countrycode){
        countrycode = defaultcountrycode;
    }
    if(window.priceList[countrycode]){
        document.write("/ "+priceList[countrycode][0]+" "+priceList[countrycode][1]+" m&sup2; *");
    }
}
var multiplePriceList = new Array();
function addToMultiplePriceList(cc, cur, amt){
    multiplePriceList[cc] = new Array();
    multiplePriceList[cc][0] = cur;
    multiplePriceList[cc][1] = amt;
}

function showMultiplePrice(me){
    if(window.countrycode && window.multiplePriceList[me+countrycode]){
        document.write(multiplePriceList[me+countrycode][0]+" "+multiplePriceList[me+countrycode][1]+" m&sup2; *");
    }
}
function getLangFromCountryCode(){
    var r = 'en';
    if(countryCodeSet && countryLangMatch[countrycode] != null && typeof countryLangMatch[countrycode] != "undefined" && countryLangMatch[countrycode].length >= 1){
        r = countryLangMatch[countrycode];
    }
    return r;
}
function setRedirecthandle(rh){
    redirecthandle = rh;
}
function getRedirecthandle(){
    return redirecthandle;
}

//* helper methods *//
function getItemRow(thevalue, thearray) {
    var myPosition=-1
    for (i=0;i<thearray.length;i++) {
        if(thearray[i]==thevalue) {
            myPosition = i;
            break;
        }
    }
    return myPosition;
}

function AJAXInteraction(url, callback) {
    alert(url);
    var req = init();
    req.onreadystatechange = processRequest;
        
    function init() {
      if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
    
    function processRequest () {
      // readyState of 4 signifies request is complete
      if (req.readyState == 4) {
            alert(req.readyState);
	// status of 200 signifies sucessful HTTP call
        if (req.status == 200) {
          if (callback) callback(req.responseXML);
        }
      }
    }

    this.doGet = function() {
      // make a HTTP GET request to the URL asynchronously
      req.open("GET", url, true);
      req.send(null);
    }
}

function redirectIfValidPage(redirecthandle){
    var success = false;
    try {
      request = new XMLHttpRequest();
    } catch (trymicrosoft) {
      try {
        request = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (othermicrosoft) {
        try {
          request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (failed) {
          request = false;
        }
      }
    }
    if (request){
        request.open("GET", redirecthandle, true);
        request.onreadystatechange = checkAndRedirect;
        request.send(null);
    }
    
}
    function checkAndRedirect(container){
        if(request.readyState == 4){
            if(request.status == 200){
                if(request.responseText.indexOf('200')!=-1){
                    location.href = getRedirecthandle();
                }
            }
        }
    }
