var buyPopupConter = 0;
var gfxDir = '/_s/psykiatrifonden/css/';

var overLayOpacity = 0.3;
var overLayColor = '#000';

// Global vars
var productName;
var productImage;
var productListPrice;
var productPrice;
var productStockStatus;
var productInStock;
var productDeliveryMsg;
var productOffer;
var productPriceText;
var productBuyable;



function CloseModal(){
	var thisOverlay = $('#cartloaderoverlay').data('overlay');
	$('#modalcontentwrapper').html('');
	thisOverlay.close();
}

function AddItemToCart(theForm, idSite){
	var isFF = false;
	if (navigator.userAgent.indexOf("Firefox")!=-1) isFF = true;
	var requestUrl = '/cms2k/modules/shop/storefront/ajax/add.asp?siteID='+ idSite ;
   
	var idProduct = theForm.pid.value;
	var origFrmAction = theForm.action;
	var bntStatus = $('#btnadd'+ idProduct ).attr('disabled');

	if(bntStatus == true){
	   return false;
	}
	
	// Show status indicator ...
	var objStatusIndicator = document.getElementById('statusindicator'+ idProduct );
	objStatusIndicator.style.display = 'inline';
	
	$('#btnadd'+ idProduct ).attr('disabled', 'disabled');
	
	// TRACK WITH GA!
	try{pageTracker._trackEvent('OnePageCheckout', 'AddToCart');}
	catch(ex){}
	
	var topPos = $(window).height()/2-200;

	var exContent = '<div class="modal" id="cartloaderoverlay">';
		exContent = exContent + '<h2 id="modalboxheader"> Tilføjer produkt til indkøbskurven ...</h2>';
		exContent = exContent + '<div id="modalboxcontent">';
		exContent = exContent + '<p>Vent venligst mens vi tilføjer produktet til din indkøbskurv ...<br><br><img src="'+ gfxDir +'transloader.gif" /></p>';
		exContent = exContent + '	<div style="padding-left:45px;margin-bottom:30px;">';
		exContent = exContent + '		<div><!-- <a href="#" class="buttongreen"><span>Download</span></a> <a href="javascript:void(0);" class="buttonneutral close"><span>Annuller</span></a> --></div>';
		exContent = exContent + '		<div class="clearfix"></div>';
		exContent = exContent + '	</div>';
		exContent = exContent + '</div>';
		exContent = exContent + '<div id="modalboxloader"></div>';
		exContent = exContent + '</div>';
			
	$('#modalcontentwrapper').html(exContent);
			
	$("#cartloaderoverlay").overlay({
		top: topPos,
		mask: {
			color: overLayColor,
			loadSpeed: 200,
			opacity: overLayOpacity
		},
		closeOnClick: false,
		load: true
	});
	
	
	var formData = $(theForm).serialize();
			
			$.ajax({
                type: "POST",
                url: requestUrl,
                dataType:"xml",
                data:formData,
                success:function(xml){
					
					theForm.action = origFrmAction;
					
					$(xml).find('cart').each(function(){
				
						// var id = $(this).attr('id');
						var status = $(this).find('status').text();
						// var cnt = $(this).find('content').text();
						// var action = $(this).find('action').text();
						
						var errmsg = $(this).find('errormessage').text();
						// var msngfields = $(this).find('missingfields').text();
						
						// var redirurl = $(this).find('redirurl').text();
						
						
						var totalItems = $(this).find('items').text();
						var totalAmount = $(this).find('total').text();
					
					
					
						if(status == 'success'){
							
							
							try{
								var productName = $(this).find('name').text();
								var productImage = $(this).find('image').text();
							} catch(ex){
								var productName = '';
								var productImage = '';
							}
							
							try{
								var divTotalItems = document.getElementById('cart-top-total-items');
								var divTotalAmount = document.getElementById('cart-top-total-amount');
								
								divTotalItems.innerHTML = totalItems;
								divTotalAmount.innerHTML = totalAmount;
							} 
							catch(ex){}
							
							var innerDIV = "<div><div style=\"height:30px\"></div><br>"
										+"<div style=\"margin-left:100px; width:370px; height:60px; float:left; font-size:21px;color:#FFF;\">Varen er nu lagt i din indkøbskurv</div>"
										+"<div style=\"margin-right:30px; width:30px; height:60px; float:right; cursor:pointer; color:#FFF;\" onclick=\"HideBuyPopup()\">X</div>"
										+"</div><br>"
										+"<br><div style=\"margin-left:100px; width:370px;;color:#FFF;\">Din indkøbskurv indeholder "+ totalItems +" varer til en samlet pris på "+ totalAmount +"</div><br>"
										+"<div style=\"float:left; margin:70px 0 0 100px\"><img onclick=\"HideBuyPopup()\" style=\"cursor:pointer\" src=\"/gfx/btn_added_continue_shopping.gif\" onMouseOver=\"this.src='/gfx/btn_added_continue_shopping.gif'\" onMouseOut=\"this.src='/gfx/btn_added_continue_shopping.gif'\"></div>"
										+"<div style=\"float:left; margin:70px 0 0 30px\"><a href=\"/cart/\"><img style=\"cursor:pointer\" src=\"/gfx/btn_added_gotocart.gif\" onMouseOver=\"this.src='/gfx/btn_added_gotocart.gif'\" onMouseOut=\"this.src='/gfx/btn_added_gotocart.gif'\" style=\"border:none;\"></a></div>"
										+ "<br /><br /><div style=\"clear:both\"></div>"
										+"<div style=\"clear:left; padding-left:100px; margin-top:10px; color:#fff\"><p style=\"padding-top:0px\"><div style=\"color:#FFF;\">Vinduet lukker automatisk om 5 sekunder</div></p></div>";
							
							// DISPLAY RESULT IN MODAL BOX!!!
							$('#modalboxheader').css("background-image", "url("+ gfxDir +"success_tick_22.png)"); 
							$('#modalboxheader').html('Produkt tilføjet til indkøbskurv!');
							
							var cnt = '<p>';
							cnt += '<div class="productframe"><div style="width:65px;float:left;">';
							
							if(productImage.length > 0){
								cnt += '<img src="/images/50x50'+ productImage +'">';
							} else {
								cnt += '&nbsp;';
							}
							
							
							cnt += '</div><div style="width:270px;float:left;xxxbackground-color:#CCC;"><div style="font-size:16px;font-weight:bold;color:#5c8a27;margin-bottom:5px;">'+ productName +' blev tilføjet til din indkøbskurv.</div><div style="margin-bottom:10px;">Din indkøbskurv indeholder nu <strong>'+ totalItems +'</strong> produkter til en samlet pris på DKK <strong>'+ totalAmount +'</strong></div>';
							cnt += '';
							cnt += '';
							cnt += '</div><div class="clearfix"></div><br>';
							cnt += '<div style="float:left;"><a href="javascript:CloseModal();"><img src="'+ gfxDir +'cart-pop-btn-buy-more.png" border="0" /></a></div><div style="float:right;"><a href="/cart/"><img src="'+ gfxDir +'cart-pop-btn-checkout.png" border="0" /></a></div><div class="clearfix"></div></div>';
							cnt +='</div>';
							cnt += '</p>';
							
							$('#modalboxcontent').html(cnt);
		
							objStatusIndicator.style.display = 'none';
							
							$('#btnadd'+ idProduct ).removeAttr('disabled');
							
							buyPopupConter ++;
							var myCounter = buyPopupConter;
							
							setCartVars(totalItems, totalAmount);
							
							
							
						} else {
							
							alert('Der opstod en fejl: '+ errmsg );
					
							theForm.action = origFrmAction ;
							objStatusIndicator.style.display = 'none';
							
							$('#btnadd'+ idProduct ).removeAttr('disabled');
							CloseModal();
							
						}
						
					});
					

				},
                error:function (xhr, ajaxOptions, thrownError){
                    
					alert('Der opstod en fejl: '+ xhr.status +' '+ thrownError );
					
					theForm.action = origFrmAction ;
					objStatusIndicator.style.display = 'none';
					
					$('#btnadd'+ idProduct ).removeAttr('disabled');
                }    
            });

   return false;
}

function HideBuyPopup(){
	$('#buypopup').fadeOut();
}

function SilentHideBuyPopup(icount) {
	if(buyPopupConter +'' == icount +''){
		$('#buypopup').fadeOut();
   } else { 
   }
}


function resetProduct(idProduct){
	$('#headline').html(productName);
	$('#productimage'+ idProduct ).attr("src", "/images/450x320"+ productImage);
	$('#productimagelink'+ idProduct ).attr("href", productImage );
	$('#productimagelink'+ idProduct ).attr("title", productName );
	$('#divnopricetext'+ idProduct ).hide();
	$('#variantpriceshow'+ idProduct).hide();
	$('#spanlistprice'+ idProduct ).html(productListPrice);
	$('#spanprice'+ idProduct ).html(productPrice);
	
	if(productOffer == '1'){
		$('#divlistprice'+ idProduct).show();
		$('#divprice'+ idProduct).show();
	} else {
		$('#divlistprice'+ idProduct).hide();
		$('#divprice'+ idProduct).hide();
		$('#variantpriceshow'+ idProduct).show();
	}
	
	$('#selectsadd').val("0");	
	$('#productstockmessage'+ idProduct ).html(productStockStatus);
	$('#deliverytimemessage'+ idProduct ).html(productDeliveryMsg);
	$('#divbtnadd'+ idProduct ).hide();
	$('#btnadd'+ idProduct ).attr('disabled', 'disabled');
	
}


function changeVariant(idProduct, idVariantSelected, idSite){
	var optionsQuantity = $('#optionsQuantity').val();
	var strOptions = '';
	var strOptionValues = '';

	for(var i = 1; i <= optionsQuantity; i++){
		if(i > 1 ){
			strOptions = strOptions +'&';
		}
		strOptions = strOptions +'idOption'+ i +'='+ $('#idOption'+ i ).val() +'';
	}
	
	var isFF = false; if (navigator.userAgent.indexOf("Firefox")!=-1) isFF = true;
	
	try{pageTracker._trackEvent('ProductActions', 'ChangeVariant');}catch(ex){}
	
	var requestUrl = '/cms2k/modules/shop/storefront/ajax/changevariant.asp?siteID='+ idSite +'&pid='+ idProduct +'&'+ strOptions ;
	var objStatusIndicator = document.getElementById('statusindicator'+ idProduct );
	objStatusIndicator.style.display = 'inline';
	
	$('#btnadd'+ idProduct ).attr('disabled', 'disabled');
   
   var strContent = ''
			
			var formData = ''; // $(theForm).serialize();
			
			$.ajax({
                type: "POST",
                url: requestUrl,
                dataType:"html",
                data:formData,
                success:function(response){
					var responseText = response;
					if (window.DOMParser){
						parser = new DOMParser();
						xmlDoc = parser.parseFromString(responseText,"text/xml");
					} else { // Internet Explorer
						xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
						xmlDoc.async = "false";
						xmlDoc.loadXML(responseText); 
					}

					var totalItems = ''; // xmlDoc.getElementsByTagName("items")[0].childNodes[0].nodeValue; // cart -> items
					var totalAmount = ''; // xmlDoc.getElementsByTagName("total")[0].childNodes[0].nodeValue; // cart -> total
					var product = xmlDoc.getElementsByTagName("product")[0];
					var productID = product.getAttribute("id");
					productName = product.getAttribute("name");
					productImage = product.getAttribute("image");
					productListPrice = product.getAttribute("listprice");
					productPrice = product.getAttribute("price");
					productStockStatus = product.getAttribute("stockstatus");
					productInStock = product.getAttribute("instock");
					productDeliveryMsg = product.getAttribute("deliverymessage");
					productOffer = product.getAttribute("offer");
					productPriceText = product.getAttribute("pricetext");
					productBuyable = product.getAttribute("buyable");
					
					// Get variant groups .... product -> variantgroups -> group
					var variantGroups = product.getElementsByTagName("variantgroups")[0];
					// Get matched variant, if any product -> variantmatch
					var variantMatch = xmlDoc.getElementsByTagName("variantmatch")[0];
					var idVariantMatch = variantMatch.getAttribute("id");
					var variantGroupsTotal = variantGroups.getAttribute("total");
					var variantGroupsSelected = variantGroups.getAttribute("selected");
					
					if(variantGroupsTotal == variantGroupsSelected){
						
						if(idVariantMatch == "0"){
							alert('Intet produkt matchede den valgte kombination!!');
							resetProduct(productID);
						} else {
				
							// Get variant price ...
							var variantMatchPrice = variantMatch.getAttribute("price");
							var variantMatchListPrice = variantMatch.getAttribute("listprice");
							var variantOffer = variantMatch.getAttribute("offer");
							var variantSoldOut = variantMatch.getAttribute("soldout");
							
							var variantImage = variantMatch.getAttribute("image");
							var variantSku = variantMatch.getAttribute("sku");
							var variantName = variantMatch.getAttribute("name");
							
							var variantStockStatus = variantMatch.getAttribute("stockstatus");
							var variantInStock = variantMatch.getAttribute("instock");
							var variantDeliveryMsg = variantMatch.getAttribute("deliverymessage");
							
							
							var variantPriceText = variantMatch.getAttribute("pricetext");
							var variantBuyable = variantMatch.getAttribute("buyable");
							
							$('#headline').html(variantName);
							$('#divnopricetext'+ productID ).hide();
							$('#variantpriceshow'+ productID).hide();
						
							// Change productimage
							if(variantImage == ''){
									
									$('#productimage'+ idProduct ).attr("src", "/images/450x320"+ productImage);
									$('#productimagelink'+ idProduct ).attr("href", productImage );
									$('#productimagelink'+ idProduct ).attr("title", productName );
								
								} else {
								
									$('#productimage'+ idProduct ).attr("src", "/images/450x320"+ variantImage);
									// Change image link!!!! productimagelink{@@productID@@}
									$('#productimagelink'+ idProduct ).attr("href", variantImage );
									$('#productimagelink'+ idProduct ).attr("title", productName +" - "+ variantName );
								}

							$('#productstockmessage'+ productID ).html(variantStockStatus);
							$('#deliverytimemessage'+ productID ).html(variantDeliveryMsg);
							$('#variantpriceshow'+ productID).hide();
							
							
							// pDivListPrice{@@productID@@}
							if(parseInt(variantMatchListPrice)>0){
								$('#spanlistprice'+ productID ).html(variantMatchListPrice);
								$('#divlistprice'+ productID ).show();
							} else {
								$('#spanlistprice'+ productID ).html('');
								$('#divlistprice'+ productID ).hide();
							}
					
							// pDivOfferPrice{@@productID@@}
							$('#spanprice'+ productID ).html( variantMatchPrice );
							$('#divprice'+ productID ).show();
							$('#selectsadd').val( idVariantMatch );
							if(variantBuyable == '1'){
									$('#divbtnadd'+ idProduct ).show();
									$('#btnadd'+ idProduct ).removeAttr('disabled');
								} else {
									$('#divbtnadd'+ idProduct ).hide();	
									$('#btnadd'+ idProduct ).attr('disabled', 'disabled');
								}
						}
					} else {
						resetProduct(productID);
					}
					
					objStatusIndicator.style.display = 'none';
                },
                error:function (xhr, ajaxOptions, thrownError){
                    
					alert('Der opstod en fejl: '+ xhr.status +' '+ thrownError );
					
					objStatusIndicator.style.display = 'none';
					objSbtBtn.disabled = false;
					
                }    
            });
}


$(function() {
	var tmp = parseInt(cartItemsTotal);
	adjustCart(tmp);
});


function adjustCart(iItems){
	if (iItems > 0){
		$('#cartboxsimpleheader').css('backgroundImage','url('+ gfxDir +'arrow-big-blue.png)');
		$('#cartboxsimpleempty').hide();
		$('#cartboxsimplecontent').show();
	 
	} else {
		$('#cartboxsimpleheader').css('backgroundImage','url('+ gfxDir +'arrow-big-grey.png)');
		$('#cartboxsimpleempty').show();
		$('#cartboxsimplecontent').hide();
	}
}

function setCartVars(iItems, iAmount){
	$('#cart-top-total-items').html(iItems);
	$('#cart-top-total-amount').html(iAmount);
	adjustCart(parseInt(iItems));
}

