// JavaScript Document

function customProductObject(inputCtrl, maintenanceCtrl, currencyCtrl, customerTypeCtrl, renewalCtrl, discountCtrl, InternalId){
	this.inheritFrom = productObject;	
	this.inheritFrom(inputCtrl, maintenanceCtrl, currencyCtrl, customerTypeCtrl, renewalCtrl, discountCtrl, InternalId);
	this.name = "customProductObject";

}



function customCalculatorObject(controls, targetDivId){
	this.inheritFrom = calculatorObject;	
	this.inheritFrom(controls, targetDivId);
	this.otherControls = new Array();
	this.oldDiscount = 0;				// value of recent discount
	this.oldDiscountCoupon = '';		// value of non zero discount coupon
	this.defaultDiscount = '';			// default discount for zero discount
	this.defaultDiscountCoupon = '';	// default discount coupon for zero discount
	this.ctrlDiscountCoupon = '';		// id to Discount coupon control
	this.onlineStore = "https://secure.element5.com/esales/cart.html";
	this.lblSolutionSelectedConf = "<h2>Solution for selected configuration</h2>";
	this.lblSolutionRecomended = "<h2>Our recommendation - you will save <span style='color:red;'>{0} %<span></h2>";
	this.lblSolutionOther = "<h2>Other solutions </h2>";
	this.lblCurrentCutomerLicenses= "<h2>Current customer licenses: </h2>";
	this.lblProduct	= "Product";

	this.getProductObject = function(inp, internalId){
		var product = new customProductObject(this.ctrlInputList[inp], this.maintenanceCtrl, this.currencyCtrl, this.customerTypeCtrl, this.renewalCtrl, this.discountCtrl, internalId);
		product.calculator = this;
		return product
	}

	this.beforeGenerateControl = function(ctrl){
		var retval = false;
		
		if (ctrl.getAttribute('type') != null ){
			var type  = ctrl.getAttribute('type');
			if (type == "break") {  this.w("<br />"); retval = true; }
			if (type == "horizontalRule") {this.w("<hr />");retval = true; }
			if (type == "discountCoupon") { this.writeTextControl(); retval = true; }
			if (type == 'label') {	this[ctrl.getAttribute('name')] = ctrl.getAttribute('value');	/*alert(ctrl.getAttribute('value'));*/ retval = true; }
		}
		return retval;
	}
	this.writeTextControl = function(){
		var onclick = "";
		var onkeyup = "";
		var defaultVal = "";
		if (this.ctrl.getAttribute('onclick') != null) onclick = " onclick='" + this.ctrl.getAttribute('onclick') + "'";
		if (this.ctrl.getAttribute('onkeyup') != null) onkeyup = " onkeyup='" + this.ctrl.getAttribute('onkeyup') + "'";
		if (this.ctrl.getAttribute('default') != null){  defaultVal = " value='" + this.ctrl.getAttribute('default') + "'"; this.defaultDiscountCoupon = this.ctrl.getAttribute('default'); }
		this.ctrlDiscountCoupon = this.ctrl.getAttribute('id');
		this.w("<div id='div"+this.ctrl.getAttribute('id')+"'><label>"+this.ctrl.getAttribute('label')+"<input type='text' id='"+this.ctrl.getAttribute('id')+"' "+defaultVal+" "+onkeyup+" "+onclick+" /></label></div>");
		this.otherControls.push(this.ctrl.getAttribute('id'));
		this.defaultDiscount = 0;
		if (this.ctrl.getAttribute('defaultDiscount') != null)
			this.defaultDiscount = this.ctrl.getAttribute('defaultDiscount') ;
			
	}
	
	this.afterInitControls = function(){
		for(var k  in this.otherControls) {
			var tmp = document.getElementById(this.otherControls[k]);
			tmp.calculator = this;	
		}
	}
	
	this.beforeCallCalculate = function(){
		var currDis = parseInt(this.getDiscount());
		var dis = document.getElementById(this.ctrlDiscountCoupon);
		if (currDis != this.oldDiscount)	{
			if (currDis == this.defaultDiscount)	 { 
				if (dis.value != this.defaultDiscountCoupon) this.oldDiscountCoupon = dis.value;
				dis.value = this.defaultDiscountCoupon;
			} else {
				var tmp = dis.value;
				if (this.oldDiscount == this.defaultDiscount) dis.value = this.oldDiscountCoupon;
				if (tmp != this.defaultDiscountCoupon) this.oldDiscountCoupon = tmp;
			}
			this.oldDiscount = currDis;
		}
		//if (currDis !=  0) this.oldDiscountCoupon = dis.value;
	}
	this.updateExports = function(){
		var target = document.getElementById(this.exportButtons);
		target.innerHTML = "";
		this.targetDiv = target;
		var pdfUrl = new Array();
		var printUrl = new Array();
		var onlineStoreUrl = new Array();

		pdfUrl.push("discount=" + this.getDiscount());
		pdfUrl.push("Maintenance="+ this.getMaintenanceContract());
		pdfUrl.push("currencies=" + this.getCurrency());
		onlineStoreUrl.push("currencies=" + this.getCurrency());
		var dis = document.getElementById('discountCoupon');
		if (dis) {
			onlineStoreUrl.push("COUPON1=" + dis.value);
		}
		var doOnlineStore = this.suiteCollection.bestSuite == null;
		for(ix in this.productsRequest){
			var prod = this.productsRequest[ix];
			var licNo = prod.getLicenceNumber();
			pdfUrl.push("SELECTED["+prod.InternalId+"]="+licNo);
			pdfUrl.push("PRISE["+prod.InternalId+"][1]="+this.pricelist.getPricePerLicense(prod.InternalId, this.getCurrency(), licNo, 1));
			pdfUrl.push("PRISE["+prod.InternalId+"][2]="+this.pricelist.getPricePerLicense(prod.InternalId, this.getCurrency(), licNo, 2));
			pdfUrl.push("PRISE["+prod.InternalId+"][3]="+this.pricelist.getPricePerLicense(prod.InternalId, this.getCurrency(), licNo, 3));
			pdfUrl.push("PNAME["+prod.InternalId+"]="+prod.productLabel);
			pdfUrl.push("RENEWAL["+prod.InternalId+"]="+prod.renewalDiscount);
			if (doOnlineStore) onlineStoreUrl.push("PRODUCT["+this.pricelist.getShareitId(prod.InternalId,this.getMaintenanceContract() )+"]=" + licNo);
		}
		doOnlineStore = !doOnlineStore;
		var bc = this.suiteCollection.bestSuite;
		for(ix in bc){
			var prod = bc[ix];
			var licNo = prod.configuration;
			pdfUrl.push("SUITE["+ix+"]="+licNo);
			pdfUrl.push("sPRISE["+ix+"][1]="+this.pricelist.getPricePerLicense(ix, this.getCurrency(), licNo, 1));
			pdfUrl.push("sPRISE["+ix+"][2]="+this.pricelist.getPricePerLicense(ix, this.getCurrency(), licNo, 2));
			pdfUrl.push("sPRISE["+ix+"][3]="+this.pricelist.getPricePerLicense(ix, this.getCurrency(), licNo, 3));
			pdfUrl.push("PNAME["+ix+"]="+this.pricelist.getName(ix));
			pdfUrl.push("RENEWAL["+ix+"]="+prod.renewalDiscount);
			if (doOnlineStore) {
				onlineStoreUrl.push("PRODUCT["+this.pricelist.getShareitId(ix,this.getMaintenanceContract() )+"]=" + licNo);
				if (ix == "PFP") onlineStoreUrl.push("COUPON1=AVASTFORWHS");
				if (ix == "WHSE") onlineStoreUrl.push("COUPON1=AVASTFORWHS");
				if (ix == "MC") onlineStoreUrl.push("COUPON2=AVASTFORMAC");
				if (ix == "MP") onlineStoreUrl.push("COUPON2=AVASTFORMAC");
			}
			
		}
		for(var i in pdfUrl) {
			printUrl.push(pdfUrl[i]);			
		}

		printUrl.push("quotefnc=export");
		printUrl.push("fnc=print");
		pdfUrl.push("quotefnc=export");
		pdfUrl.push("fnc=price_quote");

		//pdf = "<a href='"+this.pdfUrl+"?"+pdfUrl.join("&")+"' target='_blank'><img src='"+RootPath+"eng/images/calculator-pdf.jpg'><br>Save as PDF</a>";
		//printQuote = "<a href='"+this.pdfUrl+"?"+printUrl.join("&")+"' target='_blank'><img src='"+RootPath+"eng/images/calculator-print.jpg'><br>Print this quote</a>";
		shareit = "<a href='"+this.onlineStore+"?"+onlineStoreUrl.join("&")+"' onclick='javascript:__utmLinker(this.href);'><img src='"+RootPath+"eng/images/calculator-purchase.jpg'><br>"+this.lblPurchaseButton+"</a>";
		var otherSolution = "<a href='#' onclick='var os = document.getElementById(\"otherSuites\"); if (os.style[\"display\"] == \"block\") os.style[\"display\"] = \"none\"; else os.style[\"display\"] = \"block\"; return false;'><br><h3>"+this.lblOtherSolutionButton+"</h3></a>";
		this.w("<table class='resultToolbar'><tr><td></td><td>"+ otherSolution+"</td></tr></table>");
	}


	this.writeResultTable = function(bc){
		var lines = "";
		var separatorLine = false;
		var selectedPrice = 0;
		var currency = this.getCurrency();
		this.w("<p><b>"+this.lblLengthOfMaintenanceContract+"</b>: "+this.getMaintenanceContract()+" "+this.lblYears+"</p>");
		lines+=  "<table class='finalResult'>";
		lines+=  "<tr><thead><td class='productLabel'>"+this.lblProductLabel+"</td><td class='middleCounting'>"+this.lblLicences+"</td><td class='result'>"+this.lblPrice+"</td></thead></tr>";
		for(var internalId in bc){
			//alert(internalId );
			if (bc[internalId].configuration) {
				lines+=  "<tr><td class='productLabel'>"+this.pricelist.getName(internalId)+"</td>";
				var licNo = 	bc[internalId].configuration ;
				if (typeof(this.unlimitedFromList[internalId])!= 'undefined'){
					if (licNo >= this.unlimitedFromList[internalId]) 
						lines+=  "<td class='middleCounting' > " + this.textUnlimited +"</td>";
					else
						lines+=  "<td class='middleCounting' > "+ licNo  +" x "+ this.makeDecimals(bc[internalId].pricePerLicense) + " "  + currency+"</td>";
				}else {
					if (licNo >= this.unlimitedFromList[internalId]) 
						lines+=  "<td class='middleCounting' > "+ licNo+"</td>";
					else
						lines+=  "<td class='middleCounting' > "+ bc[internalId].configuration  +" x "+ this.makeDecimals(bc[internalId].pricePerLicense) + " "  + currency+"</td>";
				}
				lines+=  "<td class='result'> "+ this.makeDecimals(bc[internalId].originalPrice )  + " "  + currency + "</td></tr>";
				lines+= "</tr>";
				originalPrice = bc[internalId].originalPrice;
				var renewal = bc[internalId].renewalDiscount ;
				if (renewal){
					lines+= "<tr><td class='productLabel'>"+this.lblRenewal+"</td> <td class='middleCounting' > "+" <span style='color:red;'>-"+bc[internalId].renewalDiscount+"%</span></td><td class='result'> <span style='color:red;'>-"+this.makeDecimals(bc[internalId].renewalDiscountPrice)+" "+currency+"</span></td></tr>";
					lines+= "<tr><td colspan='2'  class='middleCounting'>"+this.lblSubtotal+"</td><td class='result'>"+this.makeDecimals(bc[internalId].originalPrice-bc[internalId].renewalDiscountPrice)+" "+currency+"</td></tr>";
					originalPrice = bc[internalId].originalPrice-bc[internalId].renewalDiscountPrice;
					separatorLine = true;
				}
				var discount = bc[internalId].productDiscount ;
				if (discount > 0){
					lines+= "<tr><td class='productLabel'><b>Discount</b>: "+bc[internalId].productDiscountDescription+"</td> <td class='middleCounting' > "+" <span style='color:red;'>-"+discount+"%</span></td><td class='result'> <span style='color:red;'> -"+this.makeDecimals(bc[internalId].productDiscountPrice)+" "+currency+"</span></td></tr>";
					lines+= "<tr><td colspan='2'  class='middleCounting'>"+this.lblSubtotal+"</td><td class='result'>"+this.makeDecimals(originalPrice-bc[internalId].productDiscountPrice)+" "+currency+"</td></tr>";
					originalPrice = originalPrice-bc[internalId].productDiscountPrice;
					separatorLine = true;
				}
				if (separatorLine) { 
					lines+= "<tr><td colspan='2'  class='middleCounting'><b>"+this.lblFinalProductPrice+":</b></td><td class='result'><b>"+this.makeDecimals(originalPrice)+" "+currency+"</b></td></tr>";
					lines+= "<tr><td colspan='3'>&nbsp;</td></tr>";
				}
				selectedPrice+=bc[internalId].finalPrice;
			}
		}
		lines+= "<tr><td colspan='2'  class='middleCounting' ><b>"+this.lblFinalPrice+"</b>: </td><td class='result'><b>"+this.makeDecimals(selectedPrice)+" "+currency+"</b></td></tr>";
		lines+=  "</table>";
		lines+=  "<hr>";
		this.w(lines);
		return selectedPrice;
	}

/**
	* printf function written in Javascript<br>
	* <pre>var test = "You are viewing messages {0} - {1} out of {2}";
	* YAHOO.Tools.printf(test, '5', '25', '500');</pre><br>
	* This will return a string like:<br>
	* "You are view messages 5 - 25 out of 500"<br>
	* Patched provided by: Peter Foti <foti-1@comcast.net><br>
	* @param {String} string
	* @returns Parsed String
	* @type String
	*/
	this.printf = function() {
		var num = arguments.length;
		var oStr = arguments[0];
		for (var i = 1; i < num; i++) {
			var pattern = "\\{" + (i-1) + "\\}";
			var re = new RegExp(pattern, "g");
			oStr = oStr.replace(re, arguments[i]);
		}
		return oStr;
	}
	this.writeResults = function(){
		var target = document.getElementById(this.calculatorResults);
		target.innerHTML = "";
		this.targetDiv = target;
		var lines = "";
		this.w(this.lblSolutionSelectedConf);
		if (this.selectedConfiguration) var selectedPrice = this.writeResultTable(this.selectedConfiguration);
		this.targetDiv = document.getElementById(this.suiteTarget );
		this.targetDiv.innerHTML = "";
		var lines = "";
		var saveInPercent = parseFloat(1- (this.suiteCollection.bestPrice / selectedPrice))*100
		if (this.suiteCollection.bestSuite) {
			this.w(this.printf(this.lblSolutionRecomended, this.makeDecimals(saveInPercent)));
			var bc = this.suiteCollection.bestSuite;
			if (bc) this.writeResultTable(bc);
		}
		this.targetDiv = document.getElementById(this.otherSuites );
		this.targetDiv.innerHTML = "";
		var lines = "";
		var saveInPercent = parseFloat(1- (this.suiteCollection.bestPrice / selectedPrice))*100
		this.w(this.lblSolutionOther);
		for(var oS in this.suiteCollection.otherSolutions ) {
			var bcCollection = this.suiteCollection.otherSolutions[oS];
			this.writeResultTable(bcCollection);	
		}
	}
	
}
