// JavaScript Document
var calculateOnOne = false;

// Colours
var BLACK = 0;
var TWOCOLOUR = 1;
var FULLCOLOUR = 2;

// Quantities
var TWOFIFTY = 0;
var FIVEHUNDRED = 1;
var ONETHOUSAND = 2;
var MULTIPLE1K = 3;

var DEFAULT_QUANTITY = 20000;
//var DEFAULT_QUANTITY = 50;
var NO_PRICE = "-";

// Discounts
var DISCOUNT10K = 0;
var DISCOUNT20K = 1;

// Help Box
var helpBox = document.createElement("div");
var mouseCoords = new Array();

var IE = document.all ? true : false;
//if (!IE) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;

var calBase = 1000;
if(calculateOnOne == true) calBase = 10;

/******************************************
SET ATTRIBUTES AND CONTROL DISPLAY OF LINKS
******************************************/
function setAttr(element, attr, value) {
	switch(attr) {
		case 'folding':
			folding = (folding == 	true) ? folding = false: folding = true;
		break;
		case 'perforating':
			perforating = (perforating == 	true) ? perforating = false: perforating = true;
		break;
		case 'numbering':
			numbering = (numbering == 	true) ? numbering = false: numbering = true;
		break;
		case 'drilling':
			drilling = (drilling == 	true) ? drilling = false: drilling = true;
		break;
		case 'reverseColour':
			reverseColour = value;
			var aArray = document.getElementById('reverseColour').getElementsByTagName('a');
		break;
		case 'reversePrinting':
			reversePrinting = value;
			var aArray = document.getElementById('reversePrinting').getElementsByTagName('a');
		break;
		case 'mattLaminate':
			mattLaminate = (mattLaminate ==	true) ? mattLaminate = false: mattLaminate = true;
		break;
		case 'oneLaminate':
			oneLaminate = (oneLaminate == true) ? oneLaminate = false: oneLaminate = true;
		break;
		case 'signLaminate':
			signLaminate = (signLaminate == true) ? signLaminate = false: signLaminate = true;
		break;
		case 'size':
			size = value;
			var aArray = document.getElementById('size').getElementsByTagName('a');
		break;
		case 'colour':
			colour = value;
			var aArray = document.getElementById('colour').getElementsByTagName('a');
		break;
	}

	// Clear 'toggle' links
	switch(attr) {
		case 'reverseColour':
		case 'reversePrinting':
		case 'size':
		case 'colour':
			for(i = 0; i < aArray.length; i++) {
				aArray[i].style.fontWeight = 'normal';
				aArray[i].style.color = 'black';
			}
		break;
	}

	element.style.fontWeight = (element.style.fontWeight == 'bold') ? 'normal' : 'bold'; // Toggle appropriate link
	element.style.color = (element.style.color == 'red') ? 'black' : 'red';
	updatePrices(); // Update price table

	return false;
}

/****************************
UPDATE DISPLAY OF PRICE TABLE
****************************/
function updatePrices(customQuantity) {
	writeOut = '<table><tr><th>Qty</th>';
	for(var i = 0; i < weights.length; i++) {
		writeOut += '<th class="weight">' + weights[i];
		if(labelSuffix != null) writeOut += labelSuffix;
		writeOut += '</th>';
	}
	writeOut += '</tr>';

	for(var q = 0; q < quantities.length; q++) {
		var oddClass = (oddClass == ' class="odd"') ? '' : ' class="odd"';
		writeOut += '<tr' + oddClass + '><th' + oddClass + '>' + quantities[q] + '</th>';

		for(i = 0; i < weights.length; i++) {
			price = calculatePrice(size, colour, q, i, false);
			if (price != "-")
			{
				price = parseInt(price.replace("&pound;", ""));
				newPrice = Math.round(price + ((price / 100) * 3));
				writeOut += '<td>&pound;' + newPrice + '</td>';
			}
			else
			{
				newPrice = price;
				writeOut += '<td>' + newPrice + '</td>';
			}
		}
		writeOut += '</tr>';
	}
	if(customQuantity == null) customQuantity = DEFAULT_QUANTITY;

	if((customQuantity < DEFAULT_QUANTITY) || (isNaN(customQuantity))) {
		alert("Please enter a quantity greater than " + DEFAULT_QUANTITY + ".");
		customQuantity = DEFAULT_QUANTITY;
	}

	/*if((customQuantity == 250) || (customQuantity == 500) || (customQuantity == 1000) || (customQuantity == 2000) || (customQuantity == 3000) || (customQuantity == 4000) || (customQuantity == 5000) || (customQuantity == 10000) || (customQuantity == 20000)) {
		alert("The quantity you entered is already displayed.");
		customQuantity = DEFAULT_QUANTITY;
	}*/

	if(doCustom == true) {
		writeOut += '<tr id="customRow"><th><form method="" action="" onsubmit="updatePrices(getElementById(\'customQty\').value); return false;"><input type="text" id="customQty" value="' + customQuantity + '" onChange="updatePrices(this.value);"/></form></th>';
	
		for(j = 0; j < weights.length; j++) {
			price = calculatePrice(size, colour, customQuantity / calBase, j, true);
			if (price != "-")
			{
				price = parseInt(price.replace("&pound;", ""));
				newPrice = Math.round(price + ((price / 100) * 3));
				writeOut += '<td>&pound;' + newPrice + '</td>';
			}
			else
			{
				newPrice = price;
				writeOut += '<td>' + newPrice + '</td>';
			}
			/*var arg = calculatePrice(size, colour, customQuantity / calBase, j, true);
			arg = arg.substr(7);
			arg = parseInt(arg);
			arg = arg + 1;
			arg = "&pound;" + arg;
			writeOut += '<td>' + arg + '</td>';*/
		}
	} else {
		document.getElementById("customQtyHint").style.display = "none";
	}
	document.getElementById('priceTable').innerHTML = writeOut + '</table>';
}
	
/*******************************
CALCULATE PRICE OF CURRENT FIELD
*******************************/
function calculatePrice(size, colour, quantity, weight, custom) {
	// See if static price exists
	try { // Yep, it exists
		if(staticPrices[size][colour][quantity][weight] == 0) return NO_PRICE;
		amount = calculateOptionals(size, quantity, staticPrices[size][colour][quantity][weight]);
		var returnValue = '&pound;' + amount.toPrecision(4);
		if(!isPosters) {
			return returnValue.split(".")[0];
		} else {
			var testVal = returnValue.split(".");
			if(testVal[1].length > 2) {
				testVal[1] = testVal[1].substr(0, 2);
				return testVal[0] + "." + testVal[1];
			} else {
				return returnValue;
			}
		}
	} catch (e) { // Doesnt exist; generate from equation
		var qty;
		var percentage = 0;
		var kValue = staticPrices[size][colour][ONETHOUSAND][weight]; // First, get value of quantity 1000

		if(kValue == 0) return NO_PRICE;
		
		if(custom == false) {
			qty = quantities[quantity] / calBase;
		} else {
			qty = quantity;
		}

		var amount = qty; // Then, divide the quantity by 1000 to find the number of 1000's in the quantity
		
		amount -= 1; // Subtract 1 from the quantity - i.e. we are starting at 2 (2000), but the multipler needs to start at 1 (1000)
		amount = amount * dynamicPrices[size][colour][weight]; // Multiple that by the '1000 multiplier' price
		amount += kValue; // Then add it to the price of 1000

		// DISCOUNTS
		if((qty >= 10) && (qty < 20)) percentage = discounts[size][colour][DISCOUNT10K][weight] / 100; // If the quantity is 10k or above but less than 20k, give a 3% discount	
		if(qty >= 20) percentage = discounts[size][colour][DISCOUNT20K][weight] / 100; // If the quantity is 20k or above, give a 5% discount

		var discount = percentage * amount;
		amount -= discount;

		amount = calculateOptionals(size, quantity, amount, custom);
		var returnValue = '&pound;' + amount.toPrecision(4);
		if(!isPosters) {
			return returnValue.split(".")[0];
		} else {
			var testVal = returnValue.split(".");
			if(testVal[1].length > 2) {
				testVal[1] = testVal[1].substr(0, 2);
				return testVal[0] + "." + testVal[1];
			} else {
				return returnValue;
			}
		}
	}
	// Otherwise, return this...
	return '_';
}

/***********************************************
ADD OPTIONAL EXTRA PRICES TO TOTAL FOR THE FIELD
***********************************************/
function calculateOptionals(size, quantity, amount, custom) {

	if(custom == false) {
		qty = quantities[quantity] / calBase;
	} else {
		qty = quantity;
	}
	
	var revCream = 0;
	// Work out what 'added value' to use for the 'reverse printing' option, depending on the colour / size used
	if(reversePrinting == true) {
		switch(colour) {
			case BLACK:
				switch(size) {
					case DL: revCream = 26; break;
					case A5: revCream = 28; break;
					case A4: revCream = 32; break;
					case A3: revCream = 41; break;
				}
			break;
			case TWOCOLOUR:
				switch(size) {
					case DL: revCream = 29; break;
					case A5: revCream = 32; break;
					case A4: revCream = 41; break;
					case A3: revCream = 59; break;
				}
			break;
			case FULLCOLOUR:
				switch(size) {
					case DL: revCream = 35; break;
					case A5: revCream = 41; break;
					case A4: revCream = 59; break;
					case A3: revCream = 95; break;
				}
			break;
		}
	}

	// Only apply to multiples of 1000...
	// This same equation can be used for all optional extras as their price is the same
	var baseExtra = ((qty - 1) * 6) + 10;
	var revExtra = ((qty - 1) * 18) + revCream;

	if(folding == true) 	{ amount += baseExtra; } // Add folding cost
	if(perforating == true)	{ amount += baseExtra; } // Add perforating cost
	if(numbering == true)	{ amount += baseExtra; } // Add numbering cost
	if(drilling == true)	{ amount += baseExtra; } // Add drilling cost

	mattPercent = (amount / 100) * 30;
	onePercent = (amount / 100) * 10;
	lamExtra = 4 * (qty + 1);

	if(reverseColour == true) { amount += mattPercent; }
	if(mattLaminate == true) { amount += mattPercent; }
	if(oneLaminate == true) { amount += onePercent; }
	if(signLaminate == true) { amount += lamExtra; }
	if(reversePrinting == true) { amount += revExtra; }

	return amount;
}

/***********************************************
HELP BOX CODE
***********************************************/
function doHelpBox(element) {	
	helpBox.style.position = "absolute";
	helpBox.style.display = "block";

	helpBox.style.left = (mouseCoords[0] - 100) + "px";
	helpBox.style.top = (mouseCoords[1] - 75) + "px";

	helpBox.style.color = "#00853f";
	helpBox.id = "bubble";

	helpBox.innerHTML = "<p>" + element.title + "</p>";
	document.body.appendChild(helpBox);
}

function getMouseXY(e) {
	if(IE) {
		tempX = event.clientX + document.body.scrollLeft;
		tempY = event.clientY + document.body.scrollTop;
	} else {
		tempX = e.pageX;
		tempY = e.pageY;
	}
	if(tempX < 0) { tempX = 0;}
	if(tempY < 0) { tempY = 0;}

	mouseCoords[0] = tempX;
	mouseCoords[1] = tempY;
}

function removeHelpBox() {
	helpBox.style.display = "none";
}
