// Tree data
var mnm='lmnu';
var lmnugrpid=0;
var lmnuselected=null;

function lmnuhaveChilds(id) {
    if (lmnuisroot(id)) return true;
    return (document.getElementById('d' + mnm + id) != null);
}
function lmnuisroot(id) {
    var nDiv = document.getElementById("s" + mnm + id);
    if (!nDiv) return false;
    return nDiv.className.indexOf('root') != -1;
}
function lmnuisopen(id) {
    var eDiv = document.getElementById('d' + mnm + id);
    if (eDiv) return eDiv.style.display != 'none';
    return false;
}
function getnodeid(htmlobj) {
    var htmlid = htmlobj.id;
    return htmlid.substr(mnm.length + 1);
}

// Toggle Open or Highlights the selected node
function lmnuo(id) {
	var eNew = document.getElementById("s" + mnm + id);
	var cnpid = getnodeid(eNew.parentNode);
    
	//Close same level.
	var childs = eNew.parentNode.childNodes; //vi vill ha d noden som denna ligger i.
	for (var n=0; n<childs.length; n++) {
	    if (childs[n].id) {
	        var cid = getnodeid(childs[n]);
	        if (cid != id) lmnunodeStatus(false, cid);
	    }
	}

	//Försök ladda ner contenten via ajax.
	var isopen = lmnuisopen(id);
	if (lmnuhaveChilds(id)) {
	    lmnunodeStatus(!isopen, id);
	    //var g2d=Get2Div('maincontent', 'Produkt.aspx?aja&T1I=' + id);
	    return false;
	} else if (lmnuselected != id) { //behöver inte köras, laddar alltid om sidan?
		eNew.className = "nodeSel"; //denna ska även köras på de som har barn men inte root.
		if (lmnuselected && !lmnuisroot(lmnuselected)) {
		    var eOld = document.getElementById("s" + mnm + lmnuselected);
		    var selisopen = lmnuisopen(lmnuselected);
		    if (eOld) eOld.className = "node" + (selisopen ? " isOpen" : "");
		}
		lmnuselected = id;
	}
	//Kör en vanlig hämtning när vi byter grupp (tills vidare)
	//if (g2d != null) return false; //om vi inte misslyckades med Ajaxen 
	return true; //annars ladda om hela sidan.
}

// Change the status of a node(open or closed)
function lmnunodeStatus(status, id) {
    var cnisroot = lmnuisroot(id);
    var eSel = document.getElementById('s' + mnm + id);
    if (eSel) eSel.className = (cnisroot ? (status ? 'rootnodeSel' : 'rootnode') : (status ? 'nodeSel isOpen' : 'node'));
    var eDiv = document.getElementById('d' + mnm + id); //om den här finns så har den barn annars inte?
	if (eDiv) {
	    eDiv.style.display = (status) ? 'block': 'none';
        eDiv.className = (cnisroot ? (status ? 'rootclipSel':'rootclip'):'clip');
    } else if (status) {
        var grp = '';
        if (lmnugrpid >0) grp = 'grp=' + lmnugrpid + '&';
        Get2Div('menutree', 'Menu.aspx?aja&' + grp + 'T1I=' + id);
    }
}

//The following functions can be removed when codebehind have been changed.
function lmnuinit(selected, grpid) {
    if (typeof selected == "undefined") lmnuselected=null;
    if (typeof grpid != "undefined") lmnugrpid=grpid;
    //document.getElementById("menutree").innerHTML+=dbgs;
}


function togtabinode(id, o) {
    o=o.parentNode;
    var po=o;
    while (po.childNodes.length == 1) {
        //alert('gp parent ' + po.innerHTML);
        po=po.parentNode;
    }

    //fix info shown or not.
    var odivs=document.getElementsByTagName('div');
    for (var x=0; x<odivs.length; x++) {
        if (odivs[x].id=='pitn'+id) {
            setpinode(id, true);
        } else if (odivs[x].id.indexOf('pitn_p')==0) {
            setpinode(odivs[x].id.substring(4), false);
        }
    }

    //fix link background blue or not
   	for (var n=0; n<po.childNodes.length; n++) {
   	    var cn = po.childNodes[n];
   	    if (cn==o) {
   	        cn.className="prodvaltextblue";
   	    } else {
   	        if (cn.className=="prodvaltextblue") cn.className="";
   	    }
    }
}

function togpinode(id) {
    var eDiv = document.getElementById('pitn' + id);
    var notvisible = (eDiv.style.display == 'none'); //Gammla värdet sparas direkt inverterat.
    setpinode(id, notvisible);
    fixProdMin(); //recalc height.
}
function setpinode(id, visible) {
    var eDiv = document.getElementById('pitn' + id);
    //if (eDiv == null) alert('Hittar inte div med id ' + id + ' När den försökte sättas ' + visible)
    if (eDiv) eDiv.style.display = (visible) ? 'block' : 'none';
    
    var eImg = document.getElementById('piti' + id);
    if (eImg) {
        eImg.src='images/layout/pi_' + (visible ? 'minus' : 'plus') + '.png';
        eImg.alt=(visible ? '-' : '+');
        eImg.className = "imgpadding";
    }
}

function resetpinodes() {
    var imgs=document.getElementsByTagName('img');
    for (x=0; x<imgs.length; x++) {
        if (imgs[x].id.indexOf('piti')==0) {
            if (imgs[x].alt=="-") {
                //Forced open?
                setpinode(imgs[x].id.substring(4), true);
            } else {
                setpinode(imgs[x].id.substring(4), false);
            }
        }
    }
    
    //fix info shown or not.
    var odivs=document.getElementsByTagName('a');
    var selPane="info";
    var firstPane=null;
    var firstObj=null;
    var removes=new Array();
    for (x=0; x<odivs.length; x++) {
        var o=odivs[x];
        var href=o.getAttribute('href');
        if (href && href.indexOf('#prod')==0) {
            var pane=href.substring(5);
            if (!firstPane || pane==selPane) {
                firstPane=pane;
                firstObj=o;
                //if (pane==selPane) break;
            }
        }
        if (o.name && !href && (o.name=="prodinfo" || o.name=="proddesc")) {
            removes[removes.length]=o;
        }
    }
    for (var x=0; x<removes.length; x++) {
        removes[x].parentNode.removeChild(removes[x]);
    }
    if (firstPane) togtabinode('_p'+firstPane, firstObj);

}

function shid(id, visible) {
//	if (document.layers) document.layers[''+id+''].visibility=(visible?"show":"hide")
//	else if (document.all) document.all[''+id+''].style.visibility=(visible?"visible":"hidden")
//	else if (document.getElementById) document.getElementById(''+id+'').style.visibility=(visible?"visible":"hidden")
	var eDiv = document.getElementById(id);
	eDiv.style.visibility = (visible) ? 'visible': 'hidden';
};

function shbid(id, status) {
	var eDiv = document.getElementById(id);
	if (eDiv) eDiv.style.display = (status) ? 'block': 'none';
}
function hidid(id, status) {
    var eDiv = document.getElementById(id);
    if (eDiv) {
	    eDiv.style.display = (status) ? 'block': 'none';
	    eDiv.style.visibility = (status) ? 'visible' : 'hidden';
	}
}

var rexSSNPrivat = /^(?:[1-2][0|9]){0,1}([0-9]{2}[0-1][0-9][0-3][0-9])[-]{0,1}([0-9]{4})$/ ;
var rexSSNComp = /^([0-9]{6})[-]{0,1}([0-9]{4})$/ ;
var rexEmail = /^[A-Z\+0-9._%-]+@(?:[A-Z0-9-]+\.)+([A-Z0-9]+)$/ ;
//Todo, add phonenbr valid.
var rexCheckNumKK = /^([0-9]{9})$/;
var rexCheckNumPass = /^([0-9]{8})$/;
var rexCheckNum = /^([0-9]{9,30})$/;

function nowstr() {
    return 'now=' + urlencode(new Date().getTime());
}
/* input type=text stuffs */
function endsWith(heystack, needle) {
    var heyend = heystack.substring(heystack.length - needle.length);
    return heyend == needle;
}
function startsWith(heystack, needle) {
    var heystart = heystack.substring(0, needle.length);
    return heystart == needle;
}
function GisDef(ob) { /*hantera egen variabel som är unik för de olika objekten*/
    if (ob.isDefault == null || ob.isDefault == 'undefined') {
        ob.isDefault = true;
        if (!endsWith(ob.value, '...')) ob.isDefault = false;
    }
    return ob.isDefault;
}
function trim(s) {
    return s.replace(/^\s+|\s+$/g, '') ;
}
function s_submit(ob, err) {
    if (GisDef(ob) || trim(ob.value).length == 0 ) {
        alert(err);
        //Lägg in en ajax som loggar felmed och value.
        return false;
    };
    return true;
}
function focusUser() {
    var tbLUser = document.getElementById('tbLUser');
    if (tbLUser) tbLUser.focus(); 
}
function showLoginBox(val) {
    if (typeof val == "undefined") val=true;
    if (val != true) val=false;
    shbid('qloginbox', val);
    if (val) {
        window.scrollTo(0, 0); //go home
        setTimeout("focusUser();", 500);
    }
    return true;
}

function l_submit(ob, err) {
    var tbLUser = ob.tbLUser;
    if (tbLUser == null) tbLUser = document.getElementById('tbLUser');
    if (tbLUser == null) return false;
    var tbLPass = ob.tbLPass;
    if (tbLPass == null) tbLPass = document.getElementById('tbLPass');
    if (tbLPass == null) return false;
    if (trim(tbLUser.value).length == 0 || trim(tbLPass.value).length == 0 ) {
        alert(err);
        return false;
    }
    return true;
}
function s_focus(ob, checkdef, dvalue) {
    if (typeof checkdef == "undefined") checkdef=true;
    if (ob.onkeyup == undefined) ob.onkeyup = function onkeyup(event) { this.isDefault = false; };
    if (ob.onblur == undefined) ob.onblur = function onblur(event) { s_blur(this, dvalue); };
    if( checkdef && GisDef(ob) ) ob.value='';
    ob.select();
}
function s_blur(ob, dvalue) {
    if (typeof dvalue != "undefined") {
        if (ob.value=='' && ob.value != dvalue) {
            ob.value=dvalue;
            ob.isDefault = true;
        }
    }
}
var searchAjax = null;
function s_keyup(ob) {
    ob.isDefault = false;
    if (ob.value.length >= 2) {
        shbid('qsearchres', 1);
        if (searchAjax) searchAjax.abort();
        searchAjax = Get2Div('qsearchres', 'Search.aspx?aja&' + nowstr() + '&Search=' + urlencode(ob.value), "S&ouml;ker ...");
        setTimeout("window.scrollTo(0, 0);", 250); //we are displayed wrong if we are not home. wait a bit until we go home
    } else {
        shbid('qsearchres', 0);
    }
}

function Buy(o, Art, r) {
    if (o.blur) o.blur();
    if (typeof r == "undefined") r="";
    if (r != "") r = '&r=' + r;
    var url = 'ajaCart.aspx?aja&' + nowstr() + r + '&Buy=' + urlencode(Art);
    var loc = location.pathname.toLowerCase();
    if (loc == '/shopcart.aspx') {
        Get2Div('maincontent', url.replace(/ajaCart.aspx/i, 'ShopCart.aspx'));
    } else {
        Get2Div('ddcartcontent', url);
        Tip("Artikelnummer <b>" + Art + "</b> L&auml;ggs i varukorgen.<br /> Se varukorgen l&auml;ngst upp p&aring; sidan f&ouml;r detaljer.", DURATION, 3000, FADEOUT, 1000 );
    }
    return false;
}

function createCookie(name, value, days) {
    var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	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 eraseCookie(name) {
	createCookie(name,"",-1);
}

function gcSort() {
    return readCookie('Sort');
}

function scSort(sort) {
    createCookie('Sort', sort);  //session only.
}

function Produkt(url) {
    try{
        var sort = 0; //only one number in sort for now.
        if (url.indexOf('Sort=')>0) sort = url.substr(url.indexOf('Sort=',1) + 5);
        if (gcSort() != sort) scSort(sort);
        var nurl = url.replace(/produkt.aspx\?/i, 'Produkt.aspx?aja&' + nowstr() + '&');
        //Tip('Debug url: ' + nurl, DURATION, 10000);
        Get2Div('maincontent', nurl);
        return false;
    }catch(e){
        window.location = url;
        return true;
    }
}

function urlencode(str) {
    var ret = str;
    ret = ret.toString();
    ret = encodeURIComponent(ret);
    ret = ret.replace(/%20/g, '+');
    return ret;
}
function getNumbers(sText) {
    var ValidChars='01234567890';
    var ret = '';
    for (var i=0; i<sText.length; i++) {
        var Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) >= 0) ret += Char;
    }
    return ret;
}
function numberFormat(nStr){
  var x = Math.round(nStr) + '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x))
    x = x.replace(rgx, '$1' + ' ' + '$2');
  return x;
}
function Pmt(Rate, NPer, PV) {
        if (Rate == 0) return (0 - PV) / NPer;
        var num3 = Math.pow(Rate + 1, NPer);
        return -PV * num3 / (num3 - 1) * Rate;
}
function center(width,height){
	var x=parseInt((screen.width-width-10)/2);
	var y=parseInt((screen.height-height-56)/2);
	return (",width="+width+",height="+height+",top="+y+",left="+x);
}
function helpusPop(page) {
    return(!window.open('helpus.aspx?p=' + page, 'alina_helpus', 'dependant' + center(640, 380) + ', resizable=yes, status=no, toolbar=no, location=no, directories=no, menubar=no, scrollbars=yes'));
}

function CartPayMethodPostback() {
    var url = 'ShopCart.aspx?aja&paymethodbox&' + nowstr();
    try {
        //Tip('Debug url: ' + url, DURATION, 10000);
        Get2Div('paymethodbox', url);
        return false;
    } catch(e) {
        window.location=url.replace('?aja&paymethodbox&', '?');
        return true;
    }
}
function CartDelWayPostback(Itm, Data) {
    var url = 'ShopCart.aspx?aja&delwaybox&' + nowstr();
    try {
        if (typeof Itm != "undefined" && typeof Data != "undefined") {
            url += '&' + urlencode(Itm) + '=' + urlencode(Data);
        }
        //Tip('Debug url: ' + url, DURATION, 10000);
        Get2Div('delwaybox', url);
        return false;
    } catch(e) {
        window.location=url.replace('?aja&delwaybox&', '?');
        return true;
    }
}
function CartPricePostback(Itm, Data) {
    var url = 'ShopCart.aspx?aja&pricebox&' + nowstr();
    try {
        if (typeof Itm != "undefined" && typeof Data != "undefined") {
            url += '&' + urlencode(Itm) + '=' + urlencode(Data);
        }
        //Tip('Debug url: ' + url, DURATION, 10000);
        Get2Div('pricebox', url);
        return false;
    } catch (e) {
        window.location = url.replace('?aja&pricebox&', '?');
        return true;
    }
}
function CartInsureLoad(crc, Itm, Data) {
    var url = 'ShopCart.aspx?aja&insartcrc=' + crc + '&' + nowstr();
    try {
        if (typeof Itm != "undefined" && typeof Data != "undefined") {
            url += '&' + urlencode(Itm) + '=' + urlencode(Data);
        }
        //Tip('Debug url: ' + url, DURATION, 10000);
        Get2Div('insure_' + crc, url);
        return false;
    } catch (e) {
        window.location = url.replace('?aja&', '?');
        return true;
    }
}
function setCartLine(crc, Quantity, inc, exc, addi) { //only valid if not insurance.
    if (typeof addi == "undefined") addi = 0;
    var incspan = document.getElementById('linc_' + crc);
    incspan.innerHTML = numberFormat(inc * Quantity + addi);
    var excspan = document.getElementById('lexc_' + crc);
    excspan.innerHTML = numberFormat(exc * Quantity + addi);
}
function remCartLine(Art, crc) {
    var qtyinp = document.getElementById('qty_' + crc);
    qtyinp.value=0;
    var ediv = document.getElementById('cartrow_' + crc);
    if (ediv) ediv.style.display = 'none';
    ediv = document.getElementById('cartrowspace_' + crc);
    if (ediv) ediv.style.display = 'none';
    return CartPricePostback(Art, 0);
}
function setQty(Art, Quantity, crc, inc, exc, insdata) {
    //Something needs to be done here to only do the ajax on an actual value change.
    Quantity = getNumbers(Quantity);
    if (Quantity == '') return false;
    if (Quantity == 0) {
        if (confirm('Ta bort varan?')) remCartLine(Art, crc);
        return false;
    }
    CartPricePostback(Art, Quantity);
    //todo, gör bara insurecallback om vi ändrade antal, vi måste alltså veta gammla quantityn.
    if (insdata) {
        //alert(Art + ' handle insurance we still need to fix line price!\n' + insdata); //if insurable, we need to update insure_CRC load with ajax.
        //todo: this line calc needs to be done on ajax load callback, since we might get new insurance.
        var addi = getInsLinePrice(crc, Quantity, insdata); //new line price
        setCartLine(crc, Quantity, inc, exc, addi); //recalc prices with insurance
        if (Quantity == this.oldvalue) return false;
        this.oldvalue = Quantity;
        return CartInsureLoad(crc, Art, Quantity); //lets handle the quantity change here as well just in case (race condition)
    }
    this.oldvalue = Quantity;
    setCartLine(crc, Quantity, inc, exc); //recalc prices
    return false;
}
function getInsLinePrice(crc, Quantity, insdata) {
    if (typeof insdata == "undefined") insdata = [[36, 100], [48, 2000]]; //temp insurance data
    //create usable array
    var _insdata = new Array();
    _insdata[0] = 0;
    for (var _ind in insdata) _insdata[insdata[_ind][0]] = insdata[_ind][1]; //new list
    //walk and add prices
    var addi = 0;
    var eInsDiv = document.getElementById('insure_' + crc);
    var cINs = eInsDiv.getElementsByTagName('input');
    var srchNodeId = 'ins_' + crc + '_';
    for (var nidx = 0; nidx < cINs.length; nidx++) {
        var cNod = cINs[nidx];
        if (cNod.type == 'radio' && cNod.checked && startsWith(cNod.id, srchNodeId) && !endsWith(cNod.id, '_0')) {
            var idxType = cNod.id.substring(srchNodeId.length);
            var uscrPos = idxType.indexOf('_');
            if (uscrPos != -1) {
                var insidx = idxType.substring(0, uscrPos);
                if (Quantity > 0 && insidx > Quantity - 1) break; //not more rows then quantity.
                var instype = idxType.substring(uscrPos + 1);
                addi += _insdata[instype];
            }
        }
    } // for
    return addi;
}
function setIns(Art, crc, idx, type) {
    CartPricePostback('_ins_' + Art + '_' + idx, type);
    //var addi = getInsLinePrice(crc, 0, insdata); //new line price
    var qtyinp = document.getElementById('qty_' + crc);
    qtyinp.oldvalue = qtyinp.value;
    qtyinp.onkeyup(); //calc price but we need some limiting... and now we dont need insdata here.
    //setCartLine(crc, Quantity, inc, exc, addi); //recalc prices with insurance, need to call the quantity onkeyup
    return true;
}
function setPayMethod(ob) {
    if (ob.checked) {
        CartPricePostback('payment', ob.value);
        /* Numera så visar vi den även vid leverans. Därimot så ska den laddas om ibland!!!
        
        var showdelway = true;
        if (ob.value == "hb") {
            showdelway = false;
        } 
        hidid('DelWay', showdelway);*/
    }
}
function setDelWay(ob) {
    if (ob.checked) {
        CartPricePostback('delway', ob.value);
    }
}
function setDelAdd(ob) {
    if (ob.checked) {
        CartDelWayPostback('deladd', ob.value);
    }
}
function DelAddPop(deladdid) {
    return(!window.open('DelAdress.aspx?id=' + deladdid, 'alina_deladd', 'dependant' + center(460, 275) + ', resizable=yes, status=yes, toolbar=no, location=yes, directories=no, menubar=no, scrollbars=yes'));
}
function imposeMaxLen(tArea, max) {
    if (tArea.value.length > max) {
        Tip('<div class="err">Maxl&auml;ngd &auml;r ' + max + ' tecken, nu ' + tArea.value.length + '</div>', DURATION, 3000, FADEOUT, 1000 );
        //return false;
        //vi måste göra så att delete och backspace fortfarande går att använda! ;)
    } else UnTip();
    return true;
}
function sendOrderTip(startText) {
    Tip(startText + ' ordern till oss, samtidigt skickas ett informations mail till dig att vi mottagit ordern.</div>' +
    '<div>Vi kontrollerar att allt st&auml;mmer samt att best&auml;llda varor finns att tillg&aring;, d&auml;refter skickar vi dig en orderbekr&auml;ftelse.</div>', FADEOUT, 700 );
}
function dlSCartTip() {
    Tip('H&ouml;gerklicka p&aring; l&auml;nken och v&auml;lj Kopiera l&auml;nkadress, s&aring; kan du skicka den till n&aring;gon annan genom att v&auml;lja klistra in i MSN eller liknande.<br />Eller klicka p&aring; den och skapa sedan ett bokm&auml;rke f&ouml;r att senare kunna komma tillbaka till denna korg.', FADEOUT, 500 );
}
var submitobj = undefined;
function submitani(cnt) {
    var dots = "......";
    submitobj.value = "Skickar " + dots.substring(0, cnt);
    var ncnt = cnt + 1;
    if (ncnt > 4) ncnt = 1;
    setTimeout('submitani(' + ncnt + ');', 500);
}
function hsubmitorder(eobj) {
    //eobj.disabled = true; //inactivate the button to avoid double orders. we shuld have a transparent layer on top. disables the send as well.
    if (submitobj) {
        alert('Vi arbetar just nu med att skicka din order ...\n\n');
        return false;
    }
    eobj.value = "Skickar ...";
    submitobj = eobj;
    submitani(1);
    return true;
}
/**
 * Bridge XMLHTTP to XMLHttpRequest in pre-7.0 Internet Explorers
 * Code and info from Wikipedia
 */
if (typeof XMLHttpRequest == "undefined") XMLHttpRequest = function () {
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) { }
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) { }
    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { }
    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { }
    throw new Error("This browser does not support XMLHttpRequest or XMLHTTP.");
};

function Get2Div(divid, uri, altloadtext) {
    var xmlO = new XMLHttpRequest();
    if (xmlO == null) return false;
    if (typeof xmlO == "undefined") return false;
    if (typeof altloadtext == "undefined") altloadtext = "Laddar ...";
    //if (xmlO == false) return false; //orsakar fel i IE6

    xmlO.onreadystatechange = function() {
        /* 0 = uninitialized - open() has not yet been called.
        1 = open - send() has not yet been called.
        2 = sent - send() has been called, headers and status are available. 
        3 = receiving - Downloading, responseText holds partial data (although this functionality is not available in IE) 
        4 = loaded - Finished. */
        //alert('readyChange ' + xmlO.readyState + ' ' + xmlO.status)
        if (xmlO.readyState == 4) {
            var eddiv = document.getElementById(divid);
            if (!eddiv) {
                xmlO = null;
            } else {
                var ajaxtext = xmlO.responseText;
                ediv.innerHTML = ajaxtext;
                if (ajaxtext.indexOf('-CartPayMethodPostback();-') > 0) CartPayMethodPostback();
                if (ajaxtext.indexOf('-CartDelWayPostback();-') > 0) CartDelWayPostback();
                if (ajaxtext.indexOf('-CartPricePostback();-') > 0) CartPricePostback();
                if (divid == 'maincontent') resetpinodes();
            }
        }
    };

    var ediv = document.getElementById(divid);
    //maybe we should get the size of the ediv, and crate a div that fills that.
    ediv.innerHTML='<div style="margin-left:auto;margin-right:auto;float:left;width:415px;"><img src="images/layout/loading.gif" height="10px"  alt=""> ' + altloadtext + ' </div';

    xmlO.open("GET", uri, true);
    xmlO.send();
    
    if (xmlO == null) return false;
    return xmlO;
}

/* Code from http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html
*/

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

var ResizeCnt=0;
var hasFocusSearch = false;
var fixedtop = false;
function doResize(onscroll) {
    var cyoff = f_scrollTop();
    var setfixedtop = (cyoff > 72); /* top72scrl */
    if (onscroll && setfixedtop == fixedtop) return; //no need to do anything else.
    //document.title= 'Debug: ' + f_clientWidth() + 'x' +  f_clientHeight();
    var eNew = document.body; //document.getElementById("topcont");
    var chei = f_clientHeight();
    if (eNew) {
        //alert(eNew.className);
        var wclass='';
        if (chei > 700) wclass += 'hmt700 '; //used for fixed values. use this for topbanner visibility:hidden as well.
        if (setfixedtop) {
            wclass += 'top72scrl ';
            fixedtop = true;
        } else fixedtop = false;
        var cwid = f_clientWidth();
        if (cwid >= 997 + 8 + 200) wclass += 'wmt1205 '; //used for fixed values. use this for annons fixed
        if (cwid < 997 + 8 + 200 * 2) wclass += 'wlt1405 '; //used for fixed values. use this for set left justify
        if (cwid >= 997 + 8 + 200 * 2) wclass += 'wmt1405 '; //used for fixed values. use this for set center
        /*if (cwid <= 1012) { //note we need to adjust all these! to handle annons div we can set class on body where we use the sub parts to change settings.
            //hide annons div om vi har precis tillräckligt för att visa sidan.. då ska vi till och med vara centrerade.
            wclass+='divmainymin '; //wo annons?
        } else if (cwid <= 1265) {
            //i mellanläget här visar vi annonser men är vänster justerade, vi räknar med att vi får scrolla
            wclass+='divmainyc ';
        } else if (cwid > 248 * 2 + 1024) {
            //här centrerar vi sidan och låter annonserna flyta till höger om main.
            wclass+='divmainy1024 ';
        } else if (cwid > 1300) {
            wclass+='divmainys ';
        } else {
            wclass+='divmainy ';
        }*/
        if (eNew.className != trim(wclass)) eNew.className=trim(wclass);
        ResizeCnt=0;
        //document.title = 'Debug: ' + cwid + 'x' + chei + ' + ' + cyoff + ' class: ' + eNew.className;
    } else {
        ResizeCnt++;
        if (ResizeCnt < 10) setTimeout("doResize();", 500);
    }
    if (window.onresize == undefined) window.onresize = function () { doResize(); }
    if (window.onscroll == undefined) window.onscroll = function () { doResize(true); }
    if (!hasFocusSearch) {
        var eSearch = document.getElementById('tbSearch');
        if (eSearch) {
            eSearch.focus();
            hasFocusSearch = true;
        }
    }
}
try {
    doResize(); //try fix body classes quickely
} catch (e) { }

function fixProdMin() { //shuld be called on all right changes.
    try {
        var prodMain = document.getElementById("produktmain");
        if (prodMain) {
            var oHeight = 40; //default to 20 high.
            var prodR = document.getElementById("prodrightmenu");
            if (prodR) oHeight = prodR.offsetHeight;
            if (oHeight <= 20) oHeight = 40; //just in case we get a low value from above.
            prodMain.style.minHeight = (oHeight - 20) + "px"; // how high is 1.5em? for now lets say 20px.
        }
    } catch (e) {
    }
}

function done_loading() {
    resetpinodes();
    var ldoc = document.location.toString().toLowerCase();
    if (ldoc.indexOf('produkt.aspx?') > 0 && ldoc.indexOf('sort=') == -1) {
        //Set sort on ajax.
        var cSort = gcSort();
        if (cSort) {
            var Sort = document.getElementsByName('Sort');
            if (Sort && Sort.length == 1) {
                Sort = Sort[0];
                if (Sort && (Sort.value != cSort || !Sort.options[Sort.selectedIndex].defaultSelected))
                    Produkt(document.location + '&Sort=' + cSort);
            }
        }
    }
    (new Image()).src = 'ajaCart.aspx?aja&t=' +
        (((new Date()).getTime() - began_loading) / 1000) +
            '&r=' + f_clientWidth() + 'x' + f_clientHeight() + '&u=' + urlencode(self.location);

    fixProdMin();
    doResize();
}

//window.setInterval('Reconnect()'," & (My.Session.Timeout * 60000 - 30000) & ");

//Function for flashsupport detection, for now it is a dirty MSIE hack but works fine in firefox.
function enabledFlash() {
    return (navigator.mimeTypes && (navigator.mimeTypes["application/x-shockwave-flash"] || navigator.mimeTypes["application/futuresplash"]))
        || (navigator.plugins && navigator.plugins["Shockwave Flash"])
        || (navigator.userAgent && navigator.userAgent.indexOf("MSIE") >= 0);
}

