var buyOver = 1;

function ChangeBuyBtn(ProdNo){
	document.getElementById('BuyProdLink').href = "javascript:SubmitProducts('"+ProdNo+"')"

}
function SubmitProducts(ProdNr) 
{	
	//ProdNr = document.getElementById('ProdNr').value
	var url = '/shop/basket.asp?Add=1&ProductID='+ProdNr+'&amount=1&uniqid='+ new Date().getTime();
	var expires = new Date();
	expires.setTime(expires.getTime()+(1000*60*30));
	document.cookie = "RabatBanner=hide; expires="+expires.toGMTString()+"; path=/";
	$.ajax({
		type: "GET",
		url: url,
		success: function() {
			//alert("ok")
			location.href = location.href;
			
		},
		error: function(textStatus, errorThrown){
			//alert(textStatus+"\n\n"+errorThrown)
		}
	});
} 

function forget(){
	var expires = new Date();
	expires.setTime(expires.getTime()-1);
	document.cookie = "RabatBanner=; expires="+expires.toGMTString()+"; path=/";
	//Loc = location.href;
	//location.href = Loc;
}

function AJAXResponse(){ 
    if (req.readyState == 4) { // Complete 
    	if (req.status == 200) { // OK response
			location.href = location.href;
		} else { 
    		//document.getElementById('showresult').innerHTML = 'Der opstod en fejl, pr&oslash;v igen.'; 
			//alert("Der opstod en fejl prøv venligst igen")
		} 
    } 
}

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 exist(){
	var dc = document.cookie;

	if(dc.length > 0){
		begin = dc.indexOf("RabatBanner");
		if(begin != -1){
			begin += "RabatBanner".length+1;
			end = dc.indexOf(";", begin);
			
        	if(end == -1){
				end = dc.length;
			}
			
			str = dc.substring(begin, end);
			
			if(str.length > 0){
				return(str);
			}else{
				return(false);
			}
		}else{
			return(false);
		}
	}else{
		return(false);
	}
}


////////////////// Beregn Total Rabat ////////////////////
	var BasketXML=null;
	var PageArray = new Array;
	var ProdLinks = new Array;
	var TotalProdRabat = 0
	var timer = new Date();
	
	function GetTotalRabat(ProductLinks){
	if(ProductLinks.length > 0){
		for (i=0; i<ProductLinks.length; i++){
			$.ajax({
				type: "GET",
				url: ProductLinks[i]+"?rawxml=1&_="+ timer.getTime(),
				dataType: "xml",
				success: function(xml) {
					var SpecielOffer = $(xml).find("SpecialOffer:first").text()
					if(SpecielOffer == "true"){
						TotalProductRabat += parseFloat($(xml).find("UnitPrice:first").text())
					}
					
					return TotalProductRabat
					
				}
			});
		}
	} else {
		TotalProductRabat = 0
		return TotalProductRabat
	}
}

/////////////////////////////////////////////////////////////
$(function(){
	if($("#FreeProdBanner").length > 0){
		
		$.ajax({
			type: "GET",
			url: "/shop/showbasket.html?rawxml=1&_="+ timer.getTime(),
			dataType: "xml",
			success: function(xml) {
				var Count = 0;
				var TotalPrice = 0
				$(xml).find("Product").each(function(){
					if($(this).find("ProductName").text().search("strømpe") == -1){
						tmp = $(this).find("TotalPrice").text().replace(".", "")
						tmp2 = tmp.replace(",", ".")
						if(parseFloat(tmp2) > 0){
							Count += parseFloat($(this).find("Amount").text().nodeValue)
						}
						if(parseFloat(tmp2) > 0){
							TotalPrice += parseFloat(tmp2)
						}
					}
				});
				Price = TotalPrice
				if(Price == 0){
					forget();
				}
				
				check = readCookie("RabatBanner");
				if(check != "hide"){
					Price = Price-TotalProdRabat
					price = Math.round(Price*Math.pow(10,2))/Math.pow(10,2)
					var mangel = buyOver-price
					mangel = Math.round(mangel*100)/100
					mangel = number_format(parseFloat(mangel), 2, ",", ".")
					mangel += ''
					if(mangel.indexOf(",00") != -1){
						mangel = mangel.split(",")
						PriceLeft = mangel[0]
					} else {
						PriceLeft = mangel
					}
					$.ajax({
						type: "GET",
						url: "/shop/gratis-produkt-75c1.html?rawxml=1&_="+ timer.getTime(),
						dataType: "xml",
						success: function(xml) {
							var ProdList = $(xml).find("ProductList:first");
							var HasVariants = ProdList.find("Product:first").attr("HasVariants");
							var StockCount = ProdList.find("StockCount:first").text();
							var date = new Date()
							if(HasVariants == "False"){
								$("#FreeProdBanner").load("/includes/rabatBanner.asp?_="+date.getTime(), function(){
									if(Price < buyOver){
										$("#longDesc").html("Ved hver ordre kan du vælge at få <span>"+ProdList.find("LongDescription:first").text()+"</span> med til din ordre.");
									} else {
										$("#longDesc").html("Du kan nu ligge <span>"+ProdList.find("LongDescription:first").text()+"</span> med til din ordre.");
										$("#buyBtn").html('<input type="image" src="/includes/freeProdBtn.png" onclick="SubmitProducts(\''+ProdList.find("ProductNo").text()+'\')"><input type="hidden" value="'+ProdList.find("ProductNo").text()+'" id="ProdNr">')
									}
									$("#shortDesc").html(ProdList.find("ShortDescription:first").text());
									$("#prodImg").attr("src", ProdList.find("PictureLink:first").text());
									//$("#stockCounter").html("<b>Skynd dig - der er kun "+Math.round(StockCount)+" tilbage!</b>");
								});
								
							} else {
								var ReqVariantSelect = 'true'; 
								var avNumVariants = 0;
								var svNumVariants = 1;
								var loaded = false;
								
								if (avNumVariants > 0) {
									avInitialize();
									avSelect('1');
								}
								loaded = true;
								
								$.ajax({
									type: "GET",
									url: ProdList[0].getElementsByTagName("FramelessProductLnk")[0].childNodes[0].nodeValue+"?rawxml=1&_="+ timer.getTime(),
									dataType: "xml",
									success: function(xml) {
										var ProdCard = $(xml).find("ProductInfo");
										var VariantType = ProdCard.find("Variants:first").attr("Type");
										
										if(VariantType == "Simple"){
											var tmp = ""
											ProdCard.find("Option").each(function(){
												tmp += "<option value='"+$(this).text()+"'>"+$(this).text()+"</option>";
											});
										} else {
											var ProdVariants = ProdCard[0].getElementsByTagName("Combination")
											var tmp = ""
											ProdCard.find("Combination").each(function(){
												tmp += "<option value='"+$(this).attr("ProductNumber")+"'>"+$(this).attr("ProductNumber")+"</option>";
											});
										}
										
										var Formsubmit = "return BuyProduct(this,'1','0','False')"
								
										var Tmp_HTML = "<FORM action='/shop/basket.asp' onSubmit=\"return BuyProduct(this,'1','0','False')\" name='myform' method='POST'>";
										Tmp_HTML	 += 	"<INPUT type='hidden' value='' name='VerticalScrollPos'>";	
										Tmp_HTML	 += 	"<INPUT type='hidden' value='"+location.href+"' name='BuyReturnUrl'>";
										Tmp_HTML	 += 	"<INPUT type='hidden' value='1' name='Add'>";
										Tmp_HTML	 += 	"<INPUT type='HIDDEN' value='1' name='ProductID'>";
										Tmp_HTML	 += 	"<INPUT type='hidden' name='PostOrigin' value='productinfo'>";
										Tmp_HTML	 += 	"<INPUT type='hidden' value='1' maxlength='6' size='3' name='AMOUNT' class='TextInputField_ProductInfo' id='amount'>";
										Tmp_HTML	 += 	"<table cellspacing='0' cellpadding='0' border='0' bgcolor='#f6f6f6' width='753px' style='margin:10px 0px 0px 0px'>";
										Tmp_HTML	 += 	"<tr>";
										Tmp_HTML	 += 		"<td style='padding:2px 0px 2px 2px'>";
										Tmp_HTML	 += 			"<img src='"+ProdList.find("PictureLink:first").text()+"' border='0' height='130px'>";
										Tmp_HTML	 += 		"</td>";
										 if(Price < buyOver){
										 Tmp_HTML	 += 		"<td style='padding:20px 0px 20px 20px;vertical-align:top;'>";
										 Tmp_HTML	 += 			"<div style='color:#df4297;font-size:22px;'>Køber du for <font color='#000000'>"+PriceLeft+" DKK</font> mere får du "+ProdList.find("ShortDescription:first").text()+"</div>";
										 } else {
										 Tmp_HTML	 += 		"<td style='padding:10px 0px 15px 20px;vertical-align:top;'>";
										 Tmp_HTML	 += 			"<div style='color:#df4297;font-size:22px;'>Du har købt for mere end <font color='#000000'>"+buyOver+" DKK</font> og kan få "+ProdList.find("ShortDescription:first").text()+"</div>";
										 }
										if(Price <= buyOver){
										if(VariantType == "Simple"){
										Tmp_HTML	 += 			"<div style='color:#000000;font-size:12px;'><b>Skynd dig - der er kun "+Math.round(StockCount)+" tilbage!</b></div>";
										} else{
										Tmp_HTML	 += 			"<div style='color:#000000;font-size:12px;'><b>Skynd dig - der er kun få tilbage!</b></div>";
										}
										}
										if(Price > buyOver){
										Tmp_HTML	 += 			"<div style='color:#484848;font-size:12px;padding:10px 0px 0px 0px;'>";
										Tmp_HTML	 += 				"Vælg variant<br><INPUT type='HIDDEN' value='"+ProdCard.find("Group:first").attr("Title")+"' name='Variantgroup1'>";
										if(VariantType == "Simple"){
										Tmp_HTML	 += 				"<SELECT id='variant1' name='variant1' class='OptionSelect_ProductInfo'><option value=''>vælg variant</option>"+tmp+"</select>&nbsp;&nbsp;&nbsp;<INPUT border='0' type='IMAGE' src='/Images/Design/Da/Btn_JaTak.gif' style='position:relative;top:4px;'></div>";
										} else {
										Tmp_HTML	 += 				"<SELECT id='variant1' name='variant1' class='OptionSelect_ProductInfo' onchange='ChangeBuyBtn(this.value)'><option value=''>vælg variant</option>"+tmp+"</select>&nbsp;&nbsp;&nbsp;";
										Tmp_HTML	 +=					"<a href='javascript:SubmitProducts()' id='BuyProdLink'><img border='0' src='/Images/Design/Da/Btn_JaTak.gif' style='position:relative;top:4px;'></a></div>";
										}
										}
										Tmp_HTML	 += 		"</td>";
										Tmp_HTML	 += 		"<td width='200px' style='vertical-align:top;'>&nbsp;";
										Tmp_HTML	 += 			"<div style='position:absolute;'>";
										if (navigator.appName == "Microsoft Internet Explorer"){
										Tmp_HTML	 += 				"<div align='center' style='padding:25px 0 2px 5px;color:#000000;font-size:14px;text-align:center;background-image:url(/includes/MereSalgStar.png);background-repeat:no-repeat;height:148px;position:relative;top:-6px;width:175px;'>";
										Tmp_HTML	 += 					"<div style='width:120px;font-weight:bold;'>"+ProdList.find("LongDescription:first").text()+"</div>";
										Tmp_HTML	 += 				"</div>";
										} else {
										Tmp_HTML	 += 				"<div align='center' style='padding:25px 0 2px 30px;color:#000000;font-size:14px;text-align:center;background-image:url(/includes/MereSalgStar.png);background-repeat:no-repeat;height:148px;position:relative;top:-25px;width:175px;'>";
										Tmp_HTML	 += 					"<div style='width:120px;font-weight:bold;'>"+ProdList.find("LongDescription:first").text()+"</div>";
										Tmp_HTML	 += 				"</div>";
										}
										Tmp_HTML	 += 			"</div>";
										Tmp_HTML	 += 		"</td>";
										Tmp_HTML	 += 	"<tr>";
										Tmp_HTML	 += "</table></FORM>";
									
										$("#FreeProdBanner").html(Tmp_HTML);
										
									}
								});
							}						
						}
					});
				}
			}
		});
	}
});
