﻿var g_aid = '';
var g_cmd = '';
var g_page = '';
var g_ref = '';
var xmlhttp;
var xmlDoc;
function keyDown(e) {
    var evt = e ? e : event;
    if (evt.keyCode == 13) {
        if (e && e.stopPropagation)
            e.stopPropagation();
        else
            event.cancelBubble = true;
        search();
        return false;
    }
    return true;
}							

function format(id) {
	return id+'='+escape(document.getElementById(id).value).replace(/%/gi,'*');
}

function format_value(value) {
	return escape(value).replace(/%/gi,'*');
}

function showProgress(msg) {
	var loading = document.getElementById("loading");
	if (loading) {
		var el = document.getElementById('loading_msg');
		if (el) el.innerText = msg+'\rVänligen vänta...';
		loading.style.left = 150+(document.body.clientWidth-150-300)/2+document.body.scrollLeft;
		loading.style.top = (document.body.clientHeight-loading.offsetHeight)/2+document.body.scrollTop;
		loading.style.display = "";
	}
}

function hideProgress() {
	var loading = document.getElementById("loading");
	if (loading) loading.style.display = "none";
}

function resizeImage(img) {
	if (img.src.substr(img.src.length-4,1)=='.') {
		img.style.display='';
		if (img && (img.width > 90 || img.height > 90)) {
			if (img.width > img.height) {
				img.height = img.height*90/img.width;
				img.width = 90;
			} else {
				img.width = img.width*90/img.height;
				img.height = 90;
			}
		}
	}
}

function addToCart(id,amount)
{
	if (!isNaN(parseInt(amount))) {
		xmlhttp = new XMLHttpRequest();
		xmlhttp.open('GET','/shop/ajax.asp?ID='+g_id+'&CMD=AC&PID='+id+'&A='+amount,true);
		xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4){ updateCart(); } };
		xmlhttp.send('');	
		if (document.frmProdCat && document.frmProdCat.amount && document.frmProdCat.amount.type == 'TEXT') document.frmProdCat.amount.focus();
	} else
		alert('Du har angivit ett felaktigt antal!');
}

function add_favourite(id) {
	xmlhttp = new XMLHttpRequest();
	xmlhttp.open('GET','/shop/ajax.asp?ID='+g_id+'&CMD=AFAV&PID='+id,true);
	xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4){ alert('Artikeln har lagts till dina favoriter!'); } };
	xmlhttp.send('');	
}

function add_favourites() {
	var list = '';
	for (var i=0; i<document.frmProdCat.elements.length; i++) {
		var item = document.frmProdCat.elements[i];
		if (item.id.substr(0,9) == 'chk_cart_' && item.checked)
			list += item.value+',';
	}
	if (list.length) {
		list = list.substr(0,list.length-1);
		xmlhttp = new XMLHttpRequest();
		xmlhttp.open('POST','/shop/ajax.asp?ID='+g_id+'&CMD=AFAVS',true);
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.setRequestHeader('CharSet', 'UTF-8');
		xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4){ alert('Markerade artiklar har lagts till dina favoriter!'); } };
		xmlhttp.send('LIST='+list);
	} else
		alert('Du har inte markerat några artiklar!');
}

function updateCart()
{
	xmlDoc = Sarissa.getDomDocument();
	xmlDoc = (new DOMParser()).parseFromString(xmlhttp.responseText, "text/xml");
	xmlDoc.setProperty("SelectionNamespaces", "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'");
	xmlDoc.setProperty("SelectionLanguage", "XPath");
	var objNode = xmlDoc.selectSingleNode("/copiax/cart_info/total");
	var strTotal = Number(objNode.getAttribute('total')).toFixed(2).replace(/\./g,',')+' SEK '+vat;
	var items = new Array();
	var name='';
	var objNodeList = xmlDoc.selectNodes("/copiax/cart/product");
	if(objNodeList.length) {
		for (i=0;i<objNodeList.length;i++) {
			name = objNodeList[i].getAttribute('name');
			if (!name.replace(/\s/g,'').length) name = objNodeList[i].getAttribute('name2');
			items[i] = objNodeList[i].getAttribute('quantity')+' st. '+name;
		}
	} else {
		objNodeList = xmlDoc.selectNodes("/copiax/cart/item");
		for (i=0;i<objNodeList.length;i++) {
			name = objNodeList[i].getAttribute('Inf4');
			if (!name.replace(/\s/g,'').length) name = objNodeList[i].getAttribute('Descr');
			items[i] = objNodeList[i].getAttribute('Amount')+' st. '+name;
		}
	}
	var footer = window.parent.frames('footer');
	footer.updateCart(strTotal, items);
	changecss('.basket_footer', 'background', color_ll);
	if (document.frmProdCat && document.frmProdCat.amount && document.frmProdCat.amount.type == 'TEXT') document.frmProdCat.amount.value = '';
}

function fetch_prices() {
	xmlhttp = new XMLHttpRequest();
	xmlhttp.open('POST','/shop/ajax.asp?ID='+g_id+'&CMD=FP',true);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4){ updatePrices(); } };
	xmlhttp.send('ALIST='+price_list);	
}

function updatePrices() {
	xmlDoc = Sarissa.getDomDocument();
	xmlDoc = (new DOMParser()).parseFromString(xmlhttp.responseText, "text/xml");
	xmlDoc.setProperty("SelectionNamespaces", "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'");
	xmlDoc.setProperty("SelectionLanguage", "XPath");
	var objNodeList = xmlDoc.selectNodes("/copiax/price_info/item");
	for (i=0;i<objNodeList.length;i++) {
		if(!branded || shop_enabled || show_price) document.getElementById(objNodeList[i].getAttribute('ProdNo')+'_balance').innerText = objNodeList[i].getAttribute('Balance');
		document.getElementById(objNodeList[i].getAttribute('ProdNo')+'_price').innerText = objNodeList[i].getAttribute('Price');
	}
}

function build_url() {
	var url;
	url = 'prodcat.asp?FRID=W&SF='+g_sf+(g_cmd.length > 0 ? '&CMD='+g_cmd : '')+'&ID='+g_id+'&SA='+g_sa;
	if (frmProdCat.SID) url += '&SID='+frmProdCat.SID.value;
	if (frmProdCat.S1.checked) url += '&S1='+frmProdCat.S1.value;
	if (frmProdCat.S2.checked) url += '&S2='+frmProdCat.S2.value;
	if (frmProdCat.S3.checked) url += '&S3='+frmProdCat.S3.value;
	if (frmProdCat.S4.checked) url += '&S4='+frmProdCat.S4.value;
	if (frmProdCat.S1.checked || frmProdCat.S2.checked || frmProdCat.S3.checked || frmProdCat.S4.checked) url += '&ST='+frmProdCat.ST.value.replace(/%/g,"|");
	if (g_page.length > 0) url += '&PAGE='+g_page;
	url += '&GID='+g_gid+(g_pid.length > 0 ? '&PID='+g_pid : '')+(g_aid.length > 0 ? '&AID='+g_aid : '')+(g_ref.length > 0 ? '#art_'+g_ref : '');
	return url;
}

function hl_btn(item,state) {
	item.style.cursor = (state ? 'pointer' : 'default');
}

function hl_menu(item,state) {
	item.style.backgroundColor = (state ? color_hl : color_ll);
	item.style.cursor = (state ? 'pointer' : 'default');
}

function hl_custom_menu(item,state,bgcolor) {
	item.style.backgroundColor = (state ? color_hl : bgcolor);
	item.style.cursor = (state ? 'pointer' : 'default');
}

function hl_link(item,state) {
    item.style.cursor = (state ? 'pointer' : 'default');
}

function hoover_link(item,state) {
    item.style.cursor = (state ? 'pointer' : 'default');
	item.style.textDecoration = (state ? 'underline' : 'none');
}

function hl_index(item,state) {
	item.style.color = (state ? '#ffffff' : '#000000');
	item.style.backgroundColor = (state ? '#0098dc' : '#ffffff');
	item.style.cursor = (state ? 'pointer' : 'default');
}

function toggle_invoice_address(state) {
	document.getElementById('div_invoice_address').style.display=(state?'':'none');
}

function toggle_delivery_address(state) {
    document.getElementById('div_delivery_address').style.display = (state ? '' : 'none');
    document.getElementById('delivery_mark_input').style.display = (state ? '' : 'none');
}

function home() {
    var url = '/shop/prodcat.asp?ID=' + g_id;
    if (parent.frames.length > 0)
        parent.location.href = url;
    else
        document.location.href = url;
}

function select_area(id) {
	g_sa = id;
	window.location = build_url();
}

function search() {
	if (frmProdCat.S1.checked || frmProdCat.S2.checked || frmProdCat.S3.checked || frmProdCat.S4.checked) {
		if (frmProdCat.ST.value.length >= 2 || (frmProdCat.SID && frmProdCat.SID.value.length > 0)) {
			if (frmProdCat.ST.value.length == 0) frmProdCat.ST.value = '*';
			g_cmd = 'SA';
			showProgress('Söker');
			window.location = build_url();
		} else
			alert('Du måste ange en söksträng om minst 2 tecken'+(frmProdCat.SID ? ' eller välja varumärke!' : '!'));
	} else
		alert('Du måste markera minst ett sökområde!');
}

function select_menu(gid,pid,ref) {
	g_cmd = (((g_gid.length > 0 && g_gid == gid && (g_pid.length == 0 && g_pid == pid)) || (g_pid.length > 0 && g_pid == pid)) && g_prev_cmd != 'CMI' && close_menu_item != '1') ? 'CMI' : '';
	g_gid = gid;
	g_pid = pid;
	g_ref = ref;
	showProgress('Laddar');
	window.location = build_url();
}

function goto_page(page) {
	g_page = page;
	g_cmd = 'GP';
	showProgress('Laddar');
	window.location = build_url();
}

function show_article(pid,aid) {
	g_pid = pid;
	g_aid = aid;
	showProgress('Laddar');
	window.location = build_url();
}

function show_cart() {
	g_cmd = 'SC';
	showProgress('Laddar');
	window.location = build_url();
}

function show_favourites() {
	g_cmd = 'SFAV';
	showProgress('Laddar');
	window.location = build_url();
}

function show_manual() {
	window.open('/shop/manual.htm', 'Handla', 'addressbar=no,menubar=no,scrollbars=yes,resizable=yes,width=900,height=550');
}

function show_abbreviations() {
	g_cmd = 'SABBR';
	showProgress('Laddar');
	window.location = build_url();
}

function show_prefix() {
	g_cmd = 'SPFIX';
	showProgress('Laddar');
	window.location = build_url();
}

function show_logon() {
	g_cmd = 'SL';
	showProgress('Laddar');
	window.location = build_url();
}

function check_logon() {
	if(event.keyCode==13 && document.getElementById("password").value && document.getElementById("username").value) logon();
}

function logon() {
	showProgress('Loggar in');
	xmlhttp = new XMLHttpRequest();
	xmlhttp.open('GET','/shop/ajax.asp?CMD=LOGON&PWD='+format_value(document.getElementById('password').value)+'&USR='+format_value(document.getElementById('username').value)+'&ID='+g_id,true);
	xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4){ logonStatus(); } };
	xmlhttp.send('');	
}

function logonStatus() {
	xmlDoc = Sarissa.getDomDocument();
	xmlDoc = (new DOMParser()).parseFromString(xmlhttp.responseText, "text/xml");
	xmlDoc.setProperty("SelectionNamespaces", "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'");
	xmlDoc.setProperty("SelectionLanguage", "XPath");
	var objNode = xmlDoc.selectSingleNode("/copiax/login");
	var strStatus = objNode.getAttribute('status');
	var strBrandID = objNode.getAttribute('brand_id');
	switch (strStatus) {
		case '0': {
		    g_id = strBrandID;
			home();
		} break;
		case '1': {
			var msg = document.getElementById("login_msg");
			if (msg) msg.style.display = "";
		} break;
	}
	hideProgress();
}

function logoff() {
	showProgress('Loggar ut');
	xmlhttp = new XMLHttpRequest();
	xmlhttp.open('GET','/shop/ajax.asp?CMD=LOGOFF&ID='+g_id,true);
	xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4){ logonStatus(); } };
	xmlhttp.send('');	
}

function show_register() {
	g_cmd = 'SR';
	showProgress('Laddar');
	window.location = build_url();
}

function register() {
	var strCompany = document.getElementById('company').value;
	var strFirstName = document.getElementById('first_name').value;
	var strLastName = document.getElementById('last_name').value;
	var strAddress = document.getElementById('address').value;
	var strZip = document.getElementById('zip').value;
	var strCity = document.getElementById('city').value;
	var strEmail = document.getElementById('email').value;
	var strPhone = document.getElementById('phone').value;
	var strUsername = document.getElementById('username').value;
	var strPassword = document.getElementById('password').value;
	var strPassword2 = document.getElementById('password2').value;
	if (!(strFirstName.length && strLastName.length && strAddress.length && strZip.length && strCity.length && strEmail.length && strPhone.length && strUsername.length && strPassword.length && strPassword2.length)) {
		alert('Alla inmatningsfält utom företag är obligatoriska!');
		return;
	}
	if (strUsername.length < 3 || strPassword.length < 6) {
		alert('Användarnamnet måste vara minst 3 tecken långt och lösenordet minst 6 tecken långt!');
		return;
	}
	if (strPassword != strPassword2) {
		alert('Bekräftelsen av lösenordet stämmer inte överens med lösenordet!');
		return;
	}
	showProgress('Registrerar');
	xmlhttp = new XMLHttpRequest();
	xmlhttp.open('POST','/shop/ajax.asp?CMD=REG&ID='+g_id,true);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp.setRequestHeader('CharSet', 'UTF-8');
	xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4){ regStatus(); } };
	xmlhttp.send(format('company')+'&'+format('first_name')+'&'+format('last_name')+'&'+format('address')+'&'+format('zip')+'&'+format('city')+'&'+format('email')+'&'+format('phone')+'&'+format('username')+'&'+format('password'));	
}

function regStatus() {
	xmlDoc = Sarissa.getDomDocument();
	xmlDoc = (new DOMParser()).parseFromString(xmlhttp.responseText, "text/xml");
	xmlDoc.setProperty("SelectionNamespaces", "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'");
	xmlDoc.setProperty("SelectionLanguage", "XPath");
	var objNode = xmlDoc.selectSingleNode("/copiax/reg");
	var strStatus = objNode.getAttribute('status');
	hideProgress();
	if (strStatus == '0') {
		document.getElementById('reg_info_1').style.display='none';
		document.getElementById('reg_info_2').style.display='block';
	} else
		alert('Användarnamnet är upptaget!\rVänligen ange att nytt användarnamn.');
}

function toggle_all(elem,id) {
	for (var i=0; i<document.frmProdCat.elements.length; i++) {
		var item = document.frmProdCat.elements[i];
		if (item.id.substr(0,id.length) == id)
			item.checked = elem.checked;
	}
}

function remove_cart_items() {
	var count = 0;
	for (var i=0; i<document.frmProdCat.elements.length; i++) {
		var item = document.frmProdCat.elements[i];
		if (item.id.substr(0,9) == 'chk_cart_' && item.checked)
			count++;
	}
	if (count>0) {
		if (confirm('Vill du ta bort markerade artiklar från kundvagnen?')) {
			g_cmd = 'DFC';
			document.frmProdCat.method = 'post';
			document.frmProdCat.action = build_url();
			showProgress('Raderar');
			document.frmProdCat.submit();
		}
	} else
		alert('Du har inte markerat några artiklar!');
}

function remove_favourites() {
	var list = '';
	for (var i=0; i<document.frmProdCat.elements.length; i++) {
		var item = document.frmProdCat.elements[i];
		if (item.id.substr(0,8) == 'chk_fav_' && item.checked)
			list+=item.value+',';
	}
	if (list.length) {
		if (confirm('Vill du ta bort markerade artiklar från dina favoriter?')) {
			list = list.substr(0,list.length-1);
			xmlhttp = new XMLHttpRequest();
			xmlhttp.open('POST','/shop/ajax.asp?CMD=DFAV&ID='+g_id,true);
			xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlhttp.setRequestHeader('CharSet', 'UTF-8');
			xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4){ show_favourites(); } };
			xmlhttp.send('LIST='+list);	
		}
	} else
		alert('Du har inte markerat några artiklar!');
}

function update_cart_items() {
	g_cmd = 'UC';
	document.frmProdCat.method = 'post';
	document.frmProdCat.action = build_url();
	showProgress('Sparar');
	document.frmProdCat.submit();
}

function show_delivery_info() {
	g_cmd = 'SDI';
	document.frmProdCat.method = 'post';
	document.frmProdCat.action = build_url();
	showProgress('Laddar');
	document.frmProdCat.submit();
}

function save_delivery_info() {
	g_cmd = 'UOH';
	document.frmProdCat.method = 'post';
	document.frmProdCat.action = build_url();
	showProgress('Sparar');
	document.frmProdCat.submit();
}

function order() {
	var go = (g_id.length);
	if (!go) {
		var re = /(\d{4})-(\d{2})-(\d{2})/g;
		var a = re.exec(document.frmProdCat.delivery_date.value);
		if (a && (a.length == 4)) {
			if (a[2].substr(0,1) == '0') a[2] = a[2].substr(1,1);
			if (a[3].substr(0,1) == '0') a[3] = a[3].substr(1,1);
			d = new Date(a[1], parseInt(a[2])-1, a[3]);
			if (d.getDate()!=a[3] || d.getMonth()!=(parseInt(a[2])-1) || d.getYear()!=a[1])
				d = new Date(1900,0,1);
		} else
			d = new Date();
		var now = new Date();
		if (Date.UTC(d.getYear(),d.getMonth(),d.getDate()) >= Date.UTC(now.getYear(),now.getMonth(),now.getDate()))
		{
			go = true;
			if (document.getElementById('packaging').selectedIndex==2) {
				if (!document.getElementById('mark').value.length) {
					go = false;
					alert('Du måste ange godsmärke!');
				}
			}
		} else
			alert('Ogiltigt leveransdatum!');
	}
	if (go && window.confirm('Din order att klar för beställning. Vill du fortsätta?')) {
		var card = document.getElementById('payment2');
		g_cmd = (branded && card && card.checked ? 'PAY' : 'SO');
		document.frmProdCat.method = 'post';
		document.frmProdCat.action = build_url();
		showProgress(branded && card && card.checked ? 'Förbereder kortbetalning' : 'Beställer');
		document.frmProdCat.submit();
	}
}

function zoom(pid,aid,print) {
	var x = (document.all) ? 'left=' : 'screenX=';
	var y = (document.all) ? 'top=' : 'screenY=';
	var w = 300;
	var h = 300;
	var popup = window.open('/shop/zoom.asp?ID=' + g_id + '&PID=' + pid + '&AID=' + aid + '&PRINT=' + print, 'zoom', 'scrollbars=1', 'width=' + w + ',height=' + h + ',' + (x + (screen.width - w) / 2) + ',' + (y + (screen.height - h) / 2));
	if (window.focus) popup.focus();
}

function print_confirmation(id) {
	var x = (document.all) ? 'left=' : 'screenX=';
	var y = (document.all) ? 'top=' : 'screenY=';
	var w = 300;
	var h = 300;
	window.open('/shop/prodcat.asp?ID='+g_id+'&FRID=W&CMD=PO&OID='+id,'print','width='+w+',height='+h+','+(x+(screen.width-w)/2)+','+(y+(screen.height-h)/2));
}

function download(filename) {
	window.open('/images/doc/'+filename, '');
}

function displayHitOfWeek() {
	window.open('/shop/hitofweek.asp', 'Veckans', 'addressbar=no,menubar=no,scrollbars=yes,resizable=yes,width=750,height=550');
}

function displayShowcase() {
	window.open('/shop/showcase.asp', 'Kampanj', 'addressbar=no,menubar=no,scrollbars=yes,resizable=yes,width=700,height=600');
}

function displayChristmasShowcase() {
	window.open('/shop/christmas.asp', 'Julkampanj', 'addressbar=no,menubar=no,scrollbars=yes,resizable=yes,width=750,height=550');
}

function getStyle(theClass,element) {
	var cssRules;
	if (document.all) {
		cssRules = 'rules';
	} else if (document.getElementById) {
		cssRules = 'cssRules';
	}
	for (var S = 0; S < document.styleSheets.length; S++) {
		for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {
			if (document.styleSheets[S][cssRules][R].selectorText == theClass) {
				return document.styleSheets[S][cssRules][R].style[element];
			}
		}
	}	
}

function changecss(theClass,element,value) {
	var cssRules;
	if (document.all) {
		cssRules = 'rules';
	} else if (document.getElementById) {
		cssRules = 'cssRules';
	}
	for (var S = 0; S < document.styleSheets.length; S++) {
		for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {
			if (document.styleSheets[S][cssRules][R].selectorText == theClass) {
				document.styleSheets[S][cssRules][R].style[element] = value;
			}
		}
	}	
}

function change_delivery() {
	var chk=document.getElementById('delstat');
	for (var i=1; i<5; i++) {
		var elem=document.getElementById('address'+i);
		elem.disabled=!chk.checked;
	}
}

function disableSelection(target){
if (typeof target.onselectstart!="undefined") //IE route
	target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
	target.style.MozUserSelect="none"
else //All other route (ie: Opera)
	target.onmousedown=function(){return false}
target.style.cursor = "default"
}
