/*	@uses dojo toolkit
	@uses formatGeld.js
*/ 
// De onderstaande require is opgenomen in de youw8frontend layer. 
//dojo.require("dijit.form.Form");
//dojo.require("dijit.form.NumberTextBox");

// Deze moeten worden ingesteld
var PRICE								= 0; // The price of one IBM
var PRICETWO							= 0; // The price of two IBM
var DELIVERY_COSTS_ONE_IBM				= 0; // The standard delivery costs
var DELIVERY_COSTS_MORE_THAN_ONE_IBM	= 0; // The delivery costs when more than one IBM is ordered	

var TXT_ERR_NEXT_STEP; 						// Error text that needs to be displayed if the user clicks 'next' without filling in the form correctly 
var BUSY;
var ACCEPTED;
var INVALID;
var EXPIRED;

var orderControl; // The one and only OrderControl object that will handle all of the screen logic 

var code;
var codeDiv;

// Creating the one and only OrderControl object when the page is loaded and setting the default amount
dojo.addOnLoad(
	function() { 
		orderControl = new OrderControl(PRICE, PRICETWO, DELIVERY_COSTS_ONE_IBM, DELIVERY_COSTS_MORE_THAN_ONE_IBM); 
	//	orderControl.redrawScreen();
	}
);

function OrderControl(price, priceTwo, deliveryCostsOneIBM, deliveryCostsMoreThanOneIBM) {
	// Definition of the methods of this object 
	OrderControl.prototype.redrawScreen				= ocRedrawScreen;
	OrderControl.prototype.nextStep					= ocNextStep;
	OrderControl.prototype.checkPromotionCode		= ocCheckPromotionCode;
	OrderControl.prototype.removePromotionCode		= ocRemovePromotionCode;
	this.promotionCode					= dojo.byId('promotionCode');
	
	this.price							= price;
	this.priceTwo						= priceTwo;
	this.deliveryCostsOneIBM			= deliveryCostsOneIBM;
	this.deliveryCostsMoreThanOneIBM	= deliveryCostsMoreThanOneIBM;
	this.promotionCodeTxt				= '';
	this.promotionCodeIsCorrect			= false;
	
	this.updateSmallCart				= true;
	
	this.pcPrice;
	this.pcPriceTwo;
	this.pcDeliveryCostsOneIBM;
	this.pcDeliveryCostsMoreThanOneIBM;
	
	this.codeInvalid					= dojo.byId('codeInvalid');
	return;
	// Fast references to the DOM objects	
	this.aantalInputWdg					= dijit.byId('amount'); // The widget, not the input object 
	this.priceObj						= dojo.byId('price');
	this.deliveryCostsObj				= dojo.byId('deliveryCosts');
	this.totalObj						= dojo.byId('total');
	
	
	


	// Making sure the calculation is done after the user changes the amount	
	dojo.connect(this.aantalInputWdg, "onkeyup", function(evt) { orderControl.redrawScreen(evt) });
	orderControlLoaded = true;
}

// Change the view after changing the amount input 
function ocRedrawScreen(evt) {
	// We cannot use innerHTML on this.codeInvalid because it will screw up in IE 
	while (this.codeInvalid.childNodes.length > 0) {
		this.codeInvalid.removeChild(this.codeInvalid.childNodes[0]);
	} 
	var div			= document.createElement("DIV");
	div.innerHTML	= this.promotionCodeTxt;
	this.codeInvalid.appendChild(div);
	
	div.style.color		= this.promotionCodeIsCorrect || this.promotionCodeTxt == BUSY? 'green': '#F76619';
	div.style.display	= this.promotionCodeTxt.length==0? 'none': 'block';	
}
     
function ocNextStep(form) {
	if (form.validate()){
		return true;
	} else{
		alert(TXT_ERR_NEXT_STEP);
		return false;
	}
}

function ocRemovePromotionCode(){
	this.promotionCode.value = "";
	dojo.xhrGet( {
        url: '/servlet/bestellen/promotionCodeCheck?promotionCode=' + code      
        ,load: evaluatePromotionData       
        ,handleAs: "json"        
	});		
			
		this.promotionCodeTxt		= '&nbsp;';	
		this.promotionCodeIsCorrect	= false;				
		this.redrawScreen(); 			
	
}

function ocCheckPromotionCode() {
	
	var code = this.promotionCode.value;
	if (code.length == 8){		
		dojo.xhrGet( {
	        url: '/servlet/bestellen/promotionCodeCheck?promotionCode=' + code      
	        ,load: evaluatePromotionData       
	        ,handleAs: "json"        
		});		
	} else if(code.length < 8) {		
		this.promotionCodeTxt		= code.length > 0? BUSY: '';	
		this.promotionCodeIsCorrect	= false;				
		this.redrawScreen(); 			
	}
}

function evaluatePromotionData(response, ioArgs) {
	var promotion = response[0];	
	
	if(orderControl.updateSmallCart){
		var prodCountElm = dojo.byId('amountFor_productNr'+promotion.productId);	
		var prodPriceElm = dojo.byId('price_productNr'+promotion.productId);
		if(prodPriceElm!=null){
			var prodPrice = parseInt(prodPriceElm.innerHTML);  	
			var prodCount = parseInt(prodCountElm.value);
		
			prodPriceElm.innerHTML = prodCount > 1 ? promotion.mulPrice : promotion.price;		
			calculateTotal(orderControl.updateSmallCart);
		}
	}
	if (response[0].error == undefined) {
		console.log(response[0].error == undefined);
		orderControl.promotionCodeIsCorrect			= true;
		orderControl.promotionCodeTxt				= ACCEPTED;	
		orderControl.pcPrice						= response[0].price;
		orderControl.pcPriceTwo						= response[0].priceTwo;
		orderControl.pcDeliveryCostsOneIBM			= response[0].deliveryCostOne;
		orderControl.pcDeliveryCostsMoreThanOneIBM	= response[0].deliveryCostMultiple;		
	
	} else if (response[0].error != undefined){	
		console.log('response[0].error != undefined');
		orderControl.promotionCodeIsCorrect	= false;
		//for the GUI
		if (response[0].error == "ordering.promotioncodechecker.promotioncodeinvalid") {
			orderControl.promotionCodeTxt = INVALID;
		} else if (response[0].error == "ordering.promotioncodechecker.promotionexpired") {		
			orderControl.promotionCodeTxt = EXPIRED;	
		} else if(response[0].error == "ordering.promotioncodechecker.insufficientorwrongparameters") {
			orderControl.promotionCodeTxt = INVALID;		
		}
	}
	orderControl.redrawScreen();
	console.log('response[0].price'+response[0].price+' response[0].product.id '+response[0].product.id);
	
}

/* formatGeld stuff */
var HTML_DATA_EURO = String.fromCharCode(8364);

function formatGeld(bedrag, groupingUsed, minFractionDigits, maxFractionDigits) {
	groupingUsed		=  groupingUsed?  groupingUsed: true;
	minFractionDigits	=  minFractionDigits?  minFractionDigits: 0;
	maxFractionDigits	=  maxFractionDigits?  maxFractionDigits: 2;

	if (bedrag != null && !isNaN(bedrag)) {
		var sp		= (new String(bedrag)).split('.');
		var div		= new String(sp[0]);
		var newDiv	= div;
		if (groupingUsed) {
			newDiv = '';
			for (var i=0; i < div.length; i++) {
				if (i%3 == 0 && i>0) { 
					newDiv = "." + newDiv; 
				}
				newDiv = div.charAt(div.length - (1 + i)) + newDiv;
			}
		}
		if (sp.length == 1) {
			return newDiv + (minFractionDigits == 0? '': ',' + createStringOfChars('0', minFractionDigits));
		} else {
			var mod		= new String(sp[1]);
			var newMod	= mod;
			if (maxFractionDigits < mod.length) {
				// Het maximaal af te beelden aantal decimalen is lager dan het beschikbare aantal: afronden!
				newMod = mod.substr(0, maxFractionDigits + 1);
				newMod = new String(Math.round(parseInt(newMod) / 10));
			} 
			newMod = newMod + createStringOfChars('0', minFractionDigits - newMod.length);
			return newDiv + ',' + newMod;
		}
	} else {
		return '-';
	}
}
function createStringOfChars(character, length) {
	var res = '';
	for (var i=0; i<length; i++) {
		res = res + character;
	}
	return res;
}


function addToCart(productId,updateSmallCart,updateCart,divIdName,productName,currency,productPrice,confirmText,successText,canBeRemoved,alsoRemove){
	//console.log('productId:'+productId);
	var allowedToBuyUpgrade = false;
	var getArgs		= {
			url			: "/open/shop/?addProduct="+productId
			,handleAs	: "json"
			,sync: true
			,load		: function(data){
				allowedToBuyUpgrade = eval(data.result == "true");
			}
		  };
	dojo.xhrGet(getArgs);

	
	if(!allowedToBuyUpgrade){
		dojo.byId('infoMsg').innerHTML = MSG_NOT_ALLOWED_TO_UPGRADE;
		dijit.byId('msgDialog').show();
		return false;
	}
	
	if(updateSmallCart){
		dojo.byId('gotToCartLink').style.display = 'block';
		if(dojo.byId(divIdName)!=null){
			// if cart already has product add to amount
			console.log('update');
			dojo.byId('amountFor_'+divIdName).value = parseInt(dojo.byId('amountFor_'+divIdName).value) + 1; 
			if(successText!=null && successText!=''&& canBeRemoved){
				dijit.byId('addedDialogRef').show();
			}
		} else {
			//add new product
			var cartDiv = document.getElementById('smallCartProducts');//dojo.byId('smallCartProducts');
			var newdiv = document.createElement('div');
			newdiv.setAttribute('id',divIdName);
			
			var newdiv2 = document.createElement('div');
			newdiv2.setAttribute('class', 'smallCartProduct');
			newdiv.appendChild(newdiv2);
			
			var newdiv3 = document.createElement('div');
			newdiv3.setAttribute('class', 'productTitleSmallCart');
			newdiv3.innerHTML = productName;
			newdiv2.appendChild(newdiv3);
			
			var newdiv5 = document.createElement('div');
			newdiv5.setAttribute('class', 'smallCartRemove');

			if(canBeRemoved){
				var removeStr = productId;
				if(alsoRemove.length > 0){						
				
					for(i = 0;i < alsoRemove.length ;i++){
						removeStr += ','+alsoRemove[i];
					}						
				
				} else {					
				//	newdiv5.innerHTML = '<a class="removeLink" href="javascript:removeFromCart(\''+productId+'\',\''+divIdName+'\',\''+confirmText+'\',true);">x</a>';
				}
				newdiv5.innerHTML = '<a class="removeLink" onClick="javascript:removeFromCart(['+removeStr+'],\''+divIdName+'\',CONFIRM_DELETE,true);"><img src="/youw8Custom/dmp/img/shop/trashbin.gif" border="0"/></a>';
			} else {
				newdiv5.innerHTML = '&nbsp';
			}
			
			newdiv2.appendChild(newdiv5);			
			
			var cartAmountSpan = document.createElement('span');
			cartAmountSpan.setAttribute('class', 'cartAmount');
			cartAmountSpan.innerHTML='&nbsp;';
			newdiv2.appendChild(cartAmountSpan);
			
			var extra = document.createElement('span');
			extra.setAttribute('class', 'cartAmountExtra')
			cartAmountSpan.appendChild(extra);
			
			var amountInputDivNode = document.createElement('div');
			dojo.attr(amountInputDivNode,"id", "amountInputDivNode" );
			extra.appendChild(amountInputDivNode);
			
			var amountInput=
				new dijit.form.TextBox(
					{name: 'amountFor_'+divIdName, maxLength:3, 'disabled': 'disabled','class': 'cartAmountInput', id: 'amountFor_'+divIdName, value: 1, style: 'width:20px'}
					, extra
				);
			
			amountInput.setAttribute('class','cartAmountInput');
			cartAmountSpan.appendChild(amountInput.domNode);
			
			var newLineDiv = document.createElement('div');
			newLineDiv.setAttribute('class', 'cartNewLine');
			newdiv2.appendChild(newLineDiv);		
			
			var newdiv6 = document.createElement('div');
			newdiv6.setAttribute('class', 'smallCartPrice');
			newdiv6.innerHTML = currency + '&nbsp;';			
			newLineDiv.appendChild(newdiv6);
			
			var priceSpan = document.createElement('span');
			priceSpan.setAttribute('id', 'price_'+divIdName);
			priceSpan.innerHTML = dojo.number.format(dojo.number.round(productPrice/100,2), {places:2});
			
			priceSpan.setAttribute('class', 'addition');
			priceSpan.setAttribute('name', 'addition');
			newdiv6.appendChild(priceSpan);			
			
			cartDiv.appendChild(newdiv);
			dijit.byId('addedDialogRef').show();
		}
		orderControl.checkPromotionCode();
		calculateTotal(updateSmallCart);
	} else {
		dijit.byId('addedDialogRef').show();
	}
}

function removeAllFromCart(confirmationTekst,updateSmallCart){
	if(!confirm(confirmationTekst)){
		return;
	}
	var getArgs		= {
			url			: "/open/shop/?action=removeAllProducts"
			,handleAs	: "json"
			,load		: function(data){
				dojo.byId('cartProducts').innerHTML='';
				dojo.byId('subtotaal').style.display = 'none';
				
				calculateTotal(updateSmallCart);
				if(!updateSmallCart){
					dojo.byId('removeAllLink').style.display = 'none';
				}
			}
		  };
	dojo.xhrGet(getArgs);	
}

function removeFromCart(productIds,containerId,confirmationTekst,updateSmallCart){
	if(!confirm(confirmationTekst)){
		return;
	}
	for(i = 0;i < productIds.length ;i++){
		containerId = 'productNr'+productIds[i];
		var getArgs		= {
				url			: "/open/shop/?removeProduct="+productIds[i]
				,handleAs	: "json"
				,sync		: true	
				,load		: function(data){
					if(updateSmallCart){
						if(dojo.byId('amountFor_'+containerId)!= null && parseInt(dojo.byId('amountFor_'+containerId).value) > 1){
							// if cart already has product add to amount
							dojo.byId('amountFor_'+containerId).value = parseInt(dojo.byId('amountFor_'+containerId).value) - 1; 
							
						} else {								
								dojo.byId('smallCartProducts').removeChild(dojo.byId(containerId));	
								dijit.byId('amountFor_'+containerId).destroy();
						}
						calculateTotal(updateSmallCart);
					} else {
						dojo.byId(containerId).innerHTML='';
					}
				}
			  };
		dojo.xhrGet(getArgs);	
	}
}

function calculateTotal(updateSmallCart){
	var total = 0;
	var nodes = dojo.query("[name=addition]");
	for(var x = 0; x < nodes.length; x++){
		
		if(nodes[x].id==null || nodes[x].id==''){
			continue;
			
		}
		var prodAmount = dojo.byId('amountFor_'+nodes[x].id.replace('price_','')).value;
		total += parseFloat(nodes[x].innerHTML.replace(',','.')) * prodAmount;			
	} 
	
	var show = (total==0 || total==0.0) ? 'none' : 'block';

	if(updateSmallCart){
		dojo.byId('gotToCartLink').style.display = show;		
		dojo.byId('checkOutLink').style.display = show;	
		dojo.byId('subtotaalSmallCart').style.display = show;	
		dojo.byId('subtotaalNumberSmallCart').innerHTML = dojo.number.format(dojo.number.round(total,2), {places:2});
	} else {			
		dojo.byId('cartStatus').style.display = (total==0 || total==0.0) ? 'block' : 'none';
		dojo.byId('removeAllLink').style.display = (total==0 || total==0.0) ? 'block' : 'none';
			//show;
	}
}


function checkForIBMEasy() {	 
	var hasRequiredProducts = false;
	dojo.xhrGet( {
        url: "/open/shop/?checkProduct&request=HasRequiredProducts",  
        handleAs: "json",     
        sync: true,
        load: function(data,ioargs){			
		   hasRequiredProducts = eval(data.result == "true");			
		}
	});		
	return hasRequiredProducts;
}

function allowedToOrder(msg){
	var result = checkForIBMEasy();
	if( !result ){
		dojo.byId('infoMsg').innerHTML = msg;
		dijit.byId('msgDialog').show();
		return false;
	} 
	return true;
}