var currency = '€';
var crate = 0;
var locadiCalcUrl = 'http://www.locadi.com/shipcalc_step1.asp?receivercountryid=2&action=Import&vps=38&odata=';
var check_out = 1;

function loadfromcookie(productid, productname, package, price, count)
{
	count = (!count) ? 1:parseInt(count);

	if (basketItems[productid])
		basketItems[productid][0] = parseInt(basketItems[productid][0])+count;
	else
		basketItems[productid] = new Array(count, productname, price, package);
}

function locadiCalc(zipCode){

	var tempUrl = locadiCalcUrl;

	for (var n = 0; n < basketItems.length; n++)
		if (basketItems[n]){
			if (document.getElementById('input.price.'+n)) {
				basketItems[n][2] = round(parseFloat(document.getElementById('input.price.'+n).value));
				basketItems[n][0] = round(parseFloat(document.getElementById('input.count.'+n).value));
				weight = round(parseFloat(document.getElementById('input.weight.'+n).value));
				tempUrl += escape(basketItems[n][0] + ';www.bodegashop.com;' + weight + ';' + basketItems[n][2] + '#');
			}
		}
	tempUrl = tempUrl.substr(0,tempUrl.length-1) + '&ReceiverZip=' + zipCode;
	var iWidth = 500;
	var iHeight = 290;
	var w = (top.document.body.clientWidth / 2) + top.window.screenLeft;
	var h = (top.document.body.clientHeight / 2) + top.window.screenTop;
	var xpos = w - (iWidth / 2);
	var ypos = h - (iHeight / 2);
	win = window.open(tempUrl,'locadiCalc','toolbar=no,location=no,directories=no,status=no,width='+iWidth+',height='+iHeight+',resize=no,scrollbars=no,top='+ ypos +',left='+ xpos);
	if (!win)
		alert(popupblocked);
}

function openLocadi(cc)
{
	win = window.open('/'+cc+'/shippment/locadi');
	if (!win)
		alert(popupblocked);
	else {
		document.getElementById('otherlink').style.display = 'none';
		document.getElementById('locadilink').style.display = 'none';
	}
	return false;
}

function add2basket2( productid, productname, package, price, count )
{
	alert('Din kundkorg har uppdaterats');
	add2basket( productid, productname, package, price, count );
}

function add2basket( productid, productname, package, price, count )
{
	loadfromcookie(productid, productname, package, price, count);

	saveBasket();

	if (crate) {
		var cprice = Math.round((basketItems[productid][0]*basketItems[productid][2])*crate);
	} else {
		var cprice = round(basketItems[productid][0]*basketItems[productid][2]);
	}

	var basket = $("#shoppingBasket");

	if (basket.childNodes.length == 0) {
		document.getElementById('basket.is.empty').style.display = 'none';
		document.getElementById('basket.total').style.display = '';
	}

	if (basket.childNodes.length > 0) {
		var itemCount = document.getElementById('basket.product.id.'+productid+'.count');
		if (itemCount) {
			itemCount.childNodes[0].nodeValue = basketItems[productid][0]*basketItems[productid][3];
			document.getElementById('basket.product.id.'+productid+'.price').childNodes[0].nodeValue = cprice + ' ' + currency + ' ';
			updatePrice();
			return;
		}
	}

	basketRowHTML( productid );

	if (count > 1) {
		document.getElementById('basket.product.id.'+productid+'.count').childNodes[0].nodeValue = basketItems[productid][0]*basketItems[productid][3];
		document.getElementById('basket.product.id.'+productid+'.price').childNodes[0].nodeValue = cprice + ' ' + currency + ' ';
	}
	
	updatePrice();
}

function removeItemFromBasket( id ) {
	var itemCount = document.getElementById('basket.product.id.'+id+'.count');
	var itemPrice = document.getElementById('basket.product.id.'+id+'.price');

	if (itemCount) {

		if (basketItems[id]) {
			if (basketItems[id][0] >= 2) {
				basketItems[id][0]--;
			} else {
				basketItems[id] = null;
			}
		}

		if ((basketItems[id]) && (basketItems[id][0])) {
			itemCount.childNodes[0].nodeValue = basketItems[id][0]*basketItems[id][3];
			if (crate) {
				itemPrice.childNodes[0].nodeValue = Math.round((basketItems[id][0]*basketItems[id][2])*crate) + ' ' + currency + ' ';
			} else {
				itemPrice.childNodes[0].nodeValue = round(basketItems[id][0]*basketItems[id][2]) + ' ' + currency + ' ';
			}
		} else {
			itemCount.parentNode.parentNode.removeChild(itemCount.parentNode);
		}

		saveBasket();
	}

	if (document.getElementById('shoppingBasket').childNodes.length < 1) {
		document.getElementById('basket.is.empty').style.display = '';
		document.getElementById('basket.total').style.display = 'none';
	}
	updatePrice();
}

// view basket page
function updateBasket()
{
	var totprice = 0;
	var totcount = 0;
	var totweight = 0;
	var sbcount = 0;
	var singelBottles = new Array();

	for (var n = 0; n < basketItems.length; n++)
		if (basketItems[n]){
			if (document.getElementById('input.price.'+n)) {
				basketItems[n][2] = round(parseFloat(document.getElementById('input.price.'+n).value));
				if (document.getElementById('input.count.'+n))
					basketItems[n][0] = round(parseFloat(document.getElementById('input.count.'+n).value));
				if (document.getElementById('input.weight.'+n))
					weight = round(parseFloat(document.getElementById('input.weight.'+n).value));
	
				if (document.getElementById('td.weight.'+n))
					document.getElementById('td.weight.'+n).childNodes[0].nodeValue = (basketItems[n][0]*weight)+' kg ';
				if (document.getElementById('span.price.'+n)) {
					if (crate) {
						document.getElementById('span.price.'+n).childNodes[0].nodeValue = Math.round((parseFloat(basketItems[n][0]*basketItems[n][2]).toFixed(2))*crate);
					} else {
						document.getElementById('span.price.'+n).childNodes[0].nodeValue = parseFloat(basketItems[n][0]*basketItems[n][2]).toFixed(2);
					}
				}
	
				if (parseInt(document.getElementById('input.bottles.'+n).value) == 1) {
					sbcount += basketItems[n][0];
					singelBottles.push(n);
				}else
					totcount += basketItems[n][0];
				totweight += basketItems[n][0]*weight;
				totprice += basketItems[n][0]*basketItems[n][2];
			}
		}
	
	for(n=0;n<singelBottles.length;n++)
 		document.getElementById('input.count.'+singelBottles[n]).style.borderColor = (sbcount%6) ? 'red':'#cccccc';
	
	
	if (sbcount%6) {
		document.getElementById('div.packagecount').childNodes[0].nodeValue = String(document.getElementById('input.dtxt').value).replace(/#minus#/g,(6 - (sbcount%6)));
		document.getElementById('div.packagecount').childNodes[0].nodeValue = String(document.getElementById('div.packagecount').childNodes[0].nodeValue).replace(/#plus#/g, sbcount%6);
	} else {
	    if ( document.getElementById('div.packagecount') )
    		document.getElementById('div.packagecount').childNodes[0].nodeValue = ' ';
	}

 	totcount += sbcount/6;
    totcount = Math.ceil(totcount);
    
 	check_out = (sbcount%6);

	if ( document.getElementById('total.count') ) {
		document.getElementById('total.count').childNodes[0].nodeValue = totcount;
		document.getElementById('total.weight').childNodes[0].nodeValue = totweight;
		//alert(document.forms['campaign']);
		if ( document.forms['campaign'] ) {
			if ( (document.forms['campaign'].percent.value > 0)) {
				discount = totprice * document.forms['campaign'].percent.value;
				document.getElementById('discount.price').childNodes[0].nodeValue = discount.toFixed(2);
				totprice = totprice - discount;
			}
		}
		if (crate) {
			document.getElementById('total.price').childNodes[0].nodeValue = Math.round((totprice.toFixed(2))*crate);
		} else {
			document.getElementById('total.price').childNodes[0].nodeValue = totprice.toFixed(2);
		}
	}

	saveBasket();
}

// view basket page
function deleteFromBasket( id ) // , price, weight
{
	var row = document.getElementById('table.row.'+id);
	var table = document.getElementById('table.basket');

	basketItems[id] = null;
	row.parentNode.removeChild(row);
	var rows = table.tBodies[0].rows;
	var l = rows.length-3;

	if (l == 1) {
		table.parentNode.removeChild(table);
		document.getElementById('basket.is.empty').style.display = 'block';
		basketItems =  new Array();
	}

	for (var i = 1; i < l; i++) {
		removeClassName(rows[i], i % 2 ? "even" : "odd");
		addClassName(rows[i], i % 2 ? "odd" : "even");
	}
	updateBasket();
}

function updatePrice() {
	var priceDiv = document.getElementById('basket.total.price');
	var total = 0;
	var packages = 0;
	for (var n = 0; n < basketItems.length; n++){
		if (basketItems[n]) {
	 		total += basketItems[n][0] * basketItems[n][2];
	 		if (basketItems[n][3] == 1)
	 			packages += basketItems[n][3] * basketItems[n][0];
		}
	}

	if ( priceDiv.childNodes.length == 0) {
		if (crate) {
			priceDiv.appendChild(document.createTextNode(Math.round((total)*crate) + ' ' + currency));
		} else {
			priceDiv.appendChild(document.createTextNode(round(total) + ' ' + currency));
		}
	} else {
		if (crate) {
			priceDiv.childNodes[0].nodeValue = Math.round((total)*crate) + ' ' + currency;
		} else {
			priceDiv.childNodes[0].nodeValue = round(total) + ' ' + currency;
		}
	}

 	//if (document.getElementById('submit.checkout'))
 	//    document.getElementById('submit.checkout').disabled = (packages%6);
	check_out = (packages%6);
 	    
	if (document.getElementById('shoppingBasket').childNodes.length < 1) {
        //document.getElementById('submit.checkout').disabled = true;
		check_out = false;
	}
}

function round(fl){
	return Math.round(fl*100)/100;
}

function saveBasket(){
	var cookieStr = '';
	for (var n = 0; n < basketItems.length; n++) {
		if (basketItems[n])
			cookieStr += n + '|' + basketItems[n].join('|') + ';';
	}

	if (cookieStr) {
		var expires = new Date();
		expires.setTime(expires.getTime() + 1293836400);
		document.cookie = 'basket' + '=' + encode64(cookieStr) + '; expires=' + expires.toGMTString() + '; path=/';
	} else
		document.cookie = 'basket=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/';
}

function basketRowHTML( productid ) {
    var basket = document.getElementById('shoppingBasket');
    var newBasketRow = document.createElement("DIV");

	newBasketRow.className = (basket.childNodes.length % 2) ? 'odd':'even';

    var newCell = document.createElement("DIV");
	newCell.className = 'col1';
	var newDeleteLink = document.createElement("A");
	newDeleteLink.title = detailtxt + basketItems[productid][1];
	newDeleteLink.href = '/' + language + '/product/details/'+productid;
	newDeleteLink.onclick = function() { this.blur(); }
	newDeleteLink.appendChild(document.createTextNode(basketItems[productid][1]));
    newCell.appendChild(newDeleteLink);
    newBasketRow.appendChild(newCell);

	newCell = document.createElement("DIV");
	newCell.className = 'col2';
	newCell.id = 'basket.product.id.'+productid+'.count';
    newCell.appendChild(document.createTextNode(basketItems[productid][3]));
    newBasketRow.appendChild(newCell);

	newCell = document.createElement("DIV");
	newCell.className = 'col3';
	newCell.id = 'basket.product.id.'+productid+'.price';
	if (crate) {
		newCell.appendChild(document.createTextNode( Math.round( (basketItems[productid][2])*crate ) +' '+currency+' '));
	} else {
		newCell.appendChild(document.createTextNode( round( basketItems[productid][2] ) +' '+currency+' '));
	}

	newDeleteLink = document.createElement("A");
	newDeleteLink.className = 'del';
	newDeleteLink.title = deltxt;
	newDeleteLink.onclick = function() { this.blur(); }
	newDeleteLink.href = "javascript:removeItemFromBasket("+productid+");";
	newDeleteLink.appendChild(document.createTextNode('x'));

	//Remove(x) button
	//newCell.appendChild(newDeleteLink);

    newBasketRow.appendChild(newCell);

	newCell = document.createElement("DIV");
	newCell.className = 'breaker';
    newBasketRow.appendChild(newCell);

    basket.appendChild(newBasketRow);
}

var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function encode64(input) {
   var output = "";
   var chr1, chr2, chr3 = "";
   var enc1, enc2, enc3, enc4 = "";
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output +
         keyStr.charAt(enc1) +
         keyStr.charAt(enc2) +
         keyStr.charAt(enc3) +
         keyStr.charAt(enc4);
      chr1 = chr2 = chr3 = "";
      enc1 = enc2 = enc3 = enc4 = "";
   } while (i < input.length);

   return output;
}

function addClassName(el, sClassName) {
	var s = el.className;
	var p = s.split(" ");
	var l = p.length;
	for (var i = 0; i < l; i++) {
		if (p[i] == sClassName)
			return;
	}
	p[p.length] = sClassName;
	el.className = p.join(" ").replace( /(^\s+)|(\s+$)/g, "" );
}

function removeClassName(el, sClassName) {
	var s = el.className;
	var p = s.split(" ");
	var np = [];
	var l = p.length;
	var j = 0;
	for (var i = 0; i < l; i++) {
		if (p[i] != sClassName)
			np[j++] = p[i];
	}
	el.className = np.join(" ").replace( /(^\s+)|(\s+$)/g, "" );
}


function check_out_now() {
	if (check_out == 0)
		return true;
	else {
		alert ("Antalet flaskor måste gå att packa i paket om sex.\nDvs 6, 12, 18 osv...");
		return false;
	}
}

//var sendTo;
function pay_popup(source, addr) {
	
	//sendTo = source + "&cb=true";
	var iWidth = 850;
	var iHeight = 600;
	var iTop = 300;
	var iLeft = 300;
	win = window.open(addr,'CVCInfo','toolbar=no,location=no,directories=no,status=no,width='+iWidth+',height='+iHeight+',resize=yes,scrollbars=yes,top='+iTop+',left='+iLeft);
	if (!win) {
		
		alert('Din webbläsare stoppade denna popup');
	} else
		setTimeout("sendAway()", 150000);
}

function sendAway() {
	//window.location = 'http://www.bodegashop.com/se/shippment?payed=ok';
	window.location = 'http://www.bodegashop.com/';
}
