var EC_LithoCalc = {
	product_name: '',
	product_id: 41,
	flag_form: true,
	opts: false,
	skus: false,
	area: 0,
	selectedArea: 0,
	widthText: 0,
	heightText: 0,
	weights: false,
	extra: false,
	prices: false,
	printRate: 0,
	currentSku: '',
	currentName: '',
	currentTitle: '',
	formContents: '',
	sizeID: 0,
	timer: 0,
	selWeight: 0,
	localText: false,
	shipOpts: false,
	shipRates: [],
	shipTimes: [],
	foldRate: 0,
	names: false,
	titles: false,
	shipVals: false,
	foldingOpts: false,
	formContents: '',
	international: 1,
	country_code: '<select id=\"country_code\" name=\"country_code\" class=\"textInput\" onchange=\"EC_LithoCalc.updatePrice()\"><option value=\"CA\">Canada</option><option value=\"MX\">Mexico</option><option value=\"US\" selected>United States</option></select>',
	handling_fee: 0,
	order_action: '',
	green: false,	
	minimum_price: 22.50,
	minimum_area_for_price: 3,
	quarter_inch_increments: true,
	mailingCanUseUV: false,

folding: false,
additional: false,

	setOpts: function() {
		this.opts = [];
		this.opts['product'] = [];
		this.opts['product'][41] = 'White Canvas';
	  	this.opts['area'] = [];
	  	this.opts['coating'] = [];
	 	this.opts['color'] = [];
	       	this.opts['paper'] = [];
	  	this.opts['turnaround'] = [];
	 		
	 
			this.opts['min_height'] = '1';
		 
			this.opts['min_width'] = '1';
		 
			this.opts['max_height'] = '4.417';
		 
	 
	 
			this.opts['max_width'] = '40';
		 
	 
	 
	 
			this.opts['color'][8] = '4/0 (Full Color Front Side)';
		 
			this.opts['coating'][291] = 'No Lamination';
		 
			this.opts['turnaround'][282] = '2-4 Day';
		 
			this.opts['turnaround'][292] = '3-5 Day';
		 
			this.opts['area'][153] = '1000000.00';
		 
			this.opts['paper'][295] = '15mil. White Canvas';
		 
		},

	setSkus: function() {
		this.skus = new Hash(); 
								this.addSKU([41,'1000000.00',295,8,291,292], 5429);
							}, 

	setWeights: function() {
		this.weights = [];
				this.weights[5429] =0.40;
			
	},

	setPrices: function() {
		this.prices = new Hash();
				var pr = [];
		var i;
						pr.push({i:5429, ii:21683851, q:1, p:7.80});
				pr.push({i:5429, ii:21684203, q:2, p:7.80});
				pr.push({i:5429, ii:21684204, q:3, p:7.80});
				pr.push({i:5429, ii:21684205, q:4, p:7.80});
				pr.push({i:5429, ii:21684206, q:5, p:7.62});
				pr.push({i:5429, ii:21684207, q:6, p:7.62});
				pr.push({i:5429, ii:21684208, q:7, p:7.62});
				pr.push({i:5429, ii:21684209, q:8, p:7.62});
				pr.push({i:5429, ii:21684210, q:9, p:7.62});
				pr.push({i:5429, ii:21684211, q:10, p:7.50});
				pr.push({i:5429, ii:21684212, q:11, p:7.50});
				pr.push({i:5429, ii:21684213, q:12, p:7.50});
				pr.push({i:5429, ii:21684214, q:13, p:7.50});
				pr.push({i:5429, ii:21684215, q:14, p:7.50});
				pr.push({i:5429, ii:21684216, q:15, p:7.50});
				pr.push({i:5429, ii:21684217, q:16, p:7.50});
				pr.push({i:5429, ii:21684218, q:17, p:7.50});
				pr.push({i:5429, ii:21684219, q:18, p:7.50});
				pr.push({i:5429, ii:21684220, q:19, p:7.50});
				pr.push({i:5429, ii:21684221, q:20, p:7.20});
				pr.push({i:5429, ii:21684222, q:21, p:7.20});
				pr.push({i:5429, ii:21684223, q:22, p:7.20});
				pr.push({i:5429, ii:21684224, q:23, p:7.20});
				pr.push({i:5429, ii:21684225, q:24, p:7.20});
				pr.push({i:5429, ii:21684226, q:25, p:7.20});
				pr.push({i:5429, ii:21684227, q:26, p:7.20});
				pr.push({i:5429, ii:21684228, q:27, p:7.20});
				pr.push({i:5429, ii:21684229, q:28, p:7.20});
				pr.push({i:5429, ii:21684230, q:29, p:7.20});
				pr.push({i:5429, ii:21684231, q:30, p:6.90});
				pr.push({i:5429, ii:21684232, q:31, p:6.90});
				pr.push({i:5429, ii:21684233, q:32, p:6.90});
				pr.push({i:5429, ii:21684234, q:33, p:6.90});
				pr.push({i:5429, ii:21684235, q:34, p:6.90});
				pr.push({i:5429, ii:21684236, q:35, p:6.90});
				pr.push({i:5429, ii:21684237, q:36, p:6.90});
				pr.push({i:5429, ii:21684238, q:37, p:6.90});
				pr.push({i:5429, ii:21684239, q:38, p:6.90});
				pr.push({i:5429, ii:21684240, q:39, p:6.90});
				pr.push({i:5429, ii:21684241, q:40, p:6.60});
				pr.push({i:5429, ii:21684242, q:41, p:6.60});
				pr.push({i:5429, ii:21684243, q:42, p:6.60});
				pr.push({i:5429, ii:21684244, q:43, p:6.60});
				pr.push({i:5429, ii:21684245, q:44, p:6.60});
				pr.push({i:5429, ii:21684246, q:45, p:6.60});
				pr.push({i:5429, ii:21684247, q:46, p:6.60});
				pr.push({i:5429, ii:21684248, q:47, p:6.60});
				pr.push({i:5429, ii:21684249, q:48, p:6.60});
				pr.push({i:5429, ii:21684250, q:49, p:6.60});
				pr.push({i:5429, ii:21684251, q:50, p:6.00});
						for (i = 0; i < pr.length; i++) {
			if (this.prices.get(pr[i]['i']) == null) {
				this.prices.set(pr[i]['i'], new Hash());
			}
			this.prices.get(pr[i]['i']).set(pr[i]['q'], new Hash());
			this.prices.get(pr[i]['i']).get(pr[i]['q']).set('i', pr[i]['ii']);
			this.prices.get(pr[i]['i']).get(pr[i]['q']).set('p', pr[i]['p']);
		}
	},

	init: function() {	
		if ($('myForm')) {
			this.order_action = $('myForm').action;
			$('myForm').addEvent('submit', function(event){ if (EC_LithoCalc.flag_form) { new Event(event).stop(); }});
		}
		this.setLocalVars();
		this.setOpts();
		this.setSkus();
		this.setWeights();
		this.setPrices();		
						if (window.EC_Mailing) { EC_Mailing.init(); }
		this.updateForm();
	},
	
	setLocalVars: function() {
		this.localText 										= [];
		this.localText['titleText'] 				= 'Pricing Calculator';
		this.localText['headingText'] 			= 'Select A Product';
		this.localText['priceText'] 				= 'Printing Total';
		this.localText['productText'] 			= 'Product';	
		this.localText['dieShapeText'] 			= 'Die Shape';		
		this.localText['sizeText'] 					= 'Size';		
		this.localText['trimSizeText'] 			= 'Custom Trim Size (Not Required)';	
		this.localText['widthText'] 				= 'Width';
		this.localText['heightText'] 				= 'Height';
		this.localText['paperText'] 				= 'Paper';
		this.localText['colorText'] 				= 'Color';
		this.localText['coatingText'] 			= 'Coating';
		this.localText['pageText'] 					= 'Pages';
		this.localText['turnaroundText'] 		= 'Turnaround';
		this.localText['foldingText'] 			= 'Folding';
		this.localText['quantityText'] 			= 'Quantity';
		this.localText['orderText'] 				= 'Place Order';
		this.localText['estimateText'] 			= 'Print Estimate';
		this.localText['chooseText'] 				= 'Choose Here...';
		this.localText['shippingText'] 			= 'Estimate Shipping';
		this.localText['zipcodeText'] 			= 'Zip / Postal Code';
		this.localText['countrycodeText'] 	= 'Country';
		this.localText['ratesText'] 				= 'Get Rates';
		this.localText['shipmethodText'] 		= 'Ship Method';
		this.localText['shiprateText'] 			= 'Shipping Rate';
		this.localText['shiptimeText'] 			= 'Shipping Time';
		this.localText['pleaseclickText'] 	= '<p>Please Click &quot;Get Rates&quot;</p>';
		this.localText['ziperrorText'] 			= 'Please Enter A 5 Digit Zip Code.';
		this.localText['pleasewaitText'] 		= 'Please Wait';
		
				this.localText['custom_green_paperText'] = 'Eco Friendly Paper';

		if (window.CustomCalcText) {
			for (var key in CustomCalcText) {
				this.localText[key] = CustomCalcText[key];
			} 
		}
		
		/*
		// define custom labels by adding the following in the page content:

		var CustomCalcText = {paperText: 'Material'};

		*/

		this.names = [];
		this.titles = [];
		this.names = ['product', 'width', 'height', 'paper', 'color', 'coating', 'turnaround'];		this.titles = [this.localText['productText'], this.localText['widthText'], this.localText['heightText'], this.localText['paperText'], this.localText['colorText'], this.localText['coatingText'], this.localText['turnaroundText']];		shipOpts = new Hash({'03': 'UPS Ground', '12': 'UPS Three-Day Select', '02': 'UPS Second Day Air', '59': 'UPS Second Day Air A.M.', '01': 'UPS Next Day Air', '14': 'UPS Next Day Air Early A.M.', '65': 'UPS Worldwide Saver', '11': 'UPS Worldwide Standard', '08': 'UPS Worldwide Expedited', '07': 'UPS Worldwide Express', '54': 'UPS Worldwide Express Plus', 'FEDEX_GROUND': 'FedEx Ground', 'FEDEX_EXPRESS_SAVER': 'FedEx Express Saver', 'FEDEX_2_DAY': 'FedEx 2Day', 'STANDARD_OVERNIGHT': 'FedEx Standard Overnight', 'PRIORITY_OVERNIGHT': 'FedEx Priority Overnight', 'FIRST_OVERNIGHT': 'FedEx First Overnight', 'WC': 'Will Call', 'FR': 'Freight', 'DL': 'Delivery', 'RO': 'Recycle Overages'});		
	},
	
	createForm: function(contents) { 
		var design_id = 0;
		if ($('eondesigner_id')) {
			design_id = $('eondesigner_id').value;
		}
		
		this.formContents = '<h3 class="formTitle">' + this.localText['titleText'] + '</h3>';
		/*
		if (this.green == true) {
			this.formContents += '<div id="greenBadge" style="display:none">&nbsp;</div>';
		}
		*/
		this.formContents += '<table>';
		this.formContents += calcFI_TPL('', '<h4 class="formHeading">' + this.localText['headingText'] + '</h4>', '');
		this.formContents += contents;	
		this.formContents += '</table>';
		this.formContents += '<input type="hidden" name="price_id" value="" />';
		this.formContents += '<input type="hidden" name="quote" value="" />';
		this.formContents += '<input type="hidden" id="totals" name="totals" value="" />';
		this.formContents += '<input type="hidden" id="design_id" name="design_id" value="' + design_id + '" />';
		$('myForm').setHTML(this.formContents);
		if (window.datePickerController) datePickerController.create();
	},

	createSelect: function(title, name, func, obj, addition) {
		if (window.EC_Mailing && name == 'quantity') {
			func = 'EC_Mailing.setQuantity();' + func;
		}
		var select = '<select id="' + name + '" name="' + name + '" onchange="' + func + '">';
		if (name == 'quantity')
			select += this.createQuantityOptions(obj);
		else if (name == 'folding' && this.folding == true)
			select += this.createFoldingOptions(obj);
		else if (addition)
			select += this.createOptions(obj, true);
		else
			select += this.createOptions(obj);
		select += '</select>';
		
		var className = '';
		var addTD = '';
		
		if ((this.green == true && (this.additionalOpts == undefined || this.additionalOpts.get('custom_green_paper') == undefined) && name == 'paper') || name == 'custom_green_paper') {
			addTD = calcFI_TPL('', '', '', 'greenBadgeTD');
		}
		
		return addTD + calcFI_TPL(title, select, name, className);
	},

	createSizeInput: function(title, name, func) {
		var value = (name == 'width') ? this.widthText : this.heightText;		
		var fractValue = 0;
		var selectedIndex = 0;
	

	
		if (this.quarter_inch_increments != false) {
			var options = [	{value: '0', label: '0"'},
										{value: '.021', label: '0.25"'},
										{value: '.042', label: '0.5"'},
										{value: '.063', label: '0.75"'},
										{value: '.083', label: '1"'},
										{value: '.104', label: '1.25"'},
										{value: '.125', label: '1.5"'},
										{value: '.146', label: '1.75"'},
										{value: '.166', label: '2"'},
										{value: '.188', label: '2.25"'},
										{value: '.208', label: '2.5"'},
										{value: '.229', label: '2.75"'},
										{value: '.25', label: '3"'},
										{value: '.271', label: '3.25"'},
										{value: '.292', label: '3.5"'},
										{value: '.313', label: '3.75"'},
										{value: '.33', label: '4"'},
										{value: '.354', label: '4.25"'},
										{value: '.375', label: '4.5"'},
										{value: '.396', label: '4.75"'},
										{value: '.416', label: '5"'},
										{value: '.438', label: '5.25"'},
										{value: '.458', label: '5.5"'},
										{value: '.479', label: '5.75"'},
										{value: '.5', label: '6"'},
										{value: '.521', label: '6.25"'},
										{value: '.542', label: '6.5"'},
										{value: '.563', label: '6.75"'},
										{value: '.583', label: '7"'},
										{value: '.604', label: '7.25"'},
										{value: '.625', label: '7.5"'},
										{value: '.646', label: '7.75"'},
										{value: '.667', label: '8"'},
										{value: '.688', label: '8.25"'},
										{value: '.708', label: '8.5"'},
										{value: '.729', label: '8.75"'},
										{value: '.75', label: '9"'},
										{value: '.771', label: '9.25"'},
										{value: '.792', label: '9.5"'},
										{value: '.813', label: '9.75"'},
										{value: '.833', label: '10"'},
										{value: '.854', label: '10.25"'},
										{value: '.875', label: '10.5"'},
										{value: '.896', label: '10.75"'},
										{value: '.917', label: '11"'},
										{value: '.938', label: '11.25"'},
										{value: '.958', label: '11.5"'},
										{value: '.979', label: '11.75"'}];
		} else {
			var options = [{value: '.0', label: '0"'},
										{value: '.083', label: '1"'},					
										{value: '.166', label: '2"'},
										{value: '.25', label: '3"'},
										{value: '.33', label: '4"'},
										{value: '.416', label: '5"'},
										{value: '.5', label: '6"'},
										{value: '.583', label: '7"'},
										{value: '.667', label: '8"'},
										{value: '.75', label: '9"'},
										{value: '.833', label: '10"'},
										{value: '.917', label: '11"'}];
		}
		
		if (name == 'width' && value < 1) {
			if (this.opts['min_width']) {
				var w = Number(this.opts['min_width']);
				if (w > Math.floor(w)) {
					fractValue = w - Math.floor(w);
					w -= fractValue;
				}
				value = w;
				
			var w = Number(this.opts['min_width']);
			var h = Number(this.opts['min_height']);
			
			var n = Math.round(w - 0.000001);
			w = (n < w) ? n + .5 : Math.ceil(w);
			n = Math.round(h - 0.000001);
			h = (n < h) ? n + .5 : Math.ceil(h);
				this.area = w * h;
				
			} else {
				value = 1;
			}
		}
		
		if (name != 'width' && value < 1) {
			if (this.opts['min_height']) {
				var h = Number(this.opts['min_height']);
				if (h > Math.floor(h)) {
					fractValue = h - Math.floor(h);
					h -= fractValue;
				}
				value = h;
				
			var w = Number(this.opts['min_width']);
			var h = Number(this.opts['min_height']);
			
			var n = Math.round(w - 0.000001);
			w = (n < w) ? n + .5 : Math.ceil(w);
			n = Math.round(h - 0.000001);
			h = (n < h) ? n + .5 : Math.ceil(h);
				this.area = w * h;

			} else {
				value = 1;
			}
		}

		if ($(name + 'Fract')) {
			selectedIndex = $(name + 'Fract').selectedIndex;
		}
		
		var input = '<input type="text" id="' + name + '" name="' + name + '" value="' + value + '" onchange="' + func + '" class="sizeInput" />&nbsp;&nbsp;';
		input += '<select id="' + name + 'Fract" name="' + name + 'Fract" onchange="' + func + '" class="sizeInput">';
		
		for (var i = 0; i < options.length; i++) {
			var option = options[i];
			if (selectedIndex == 0 && fractValue > 0) {
				if (Number(option.value) == fractValue) {
					selectedIndex = i;
				}
			}
			
			var selected = (selectedIndex == i) ? ' selected' : '';
			input += '<option value="' + option.value + '"' + selected + '>' + option.label + '</option>';
		}	
		
		input += '</select>';
		
		return calcFI_TPL(title, input, name);
	},
	
	createDieShapeInput: function(title, name, func) {
		var opts = [];
		var value = false;
		
		for (var key in this.opts['die_shapes']) {
		    if (value == false) {
		    	value = key;
		    }
		    opts.push(key);
		}
		
		if ($(name)) { value = $(name).getValue(); }
		
		
		var select = '<select id="' + name + '" name="' + name + '" onchange="' + func + '">';
		
		for (var i = 0; i < opts.length; i++) {
			var selected = (opts[i] == value) ? ' selected' : '';
			select += '<option value="' + opts[i] + '"' + selected + '>' + opts[i] + '</option>';
		}
		
		select += '</select>';
		
		
		return calcFI_TPL(title, select, name, '');
	},
	
	createTrimSizeInput: function(title, name, func) {
		var value = this.opts['size'][this.sizeID];
		
		if ($(name)) { value = $(name).getValue(); }
		var input = '<input type="text" id="' + name + '" name="' + name + '" value="' + value + '" onblur="' + func + '" class="textInput" />';
		return calcFI_TPL(title, input, name, 'custom_trim_size');
	},

	createOptions: function(obj, addition) { 
		var a, i, len;
		var idArray = [];
		var options = '';
		var choose = '';
		var selected = '';
		var allowed_keys = false;
			
		if (this.currentName == 'size' && this.product_name == 'Roll Labels') {
			var die_shape_value = false;
			for (var key in this.opts['die_shapes']) {
		    if (die_shape_value == false) {
		    	die_shape_value = key;
		    }
			}
			
			if ($('die_shape')) { die_shape_value = $('die_shape').getValue(); }
			
			var tmp_keys = this.opts['die_shapes'][die_shape_value];
			allowed_keys = new Hash();
			
			for (i = 0; i < tmp_keys.length; i++) {
				allowed_keys.set(tmp_keys[i], true);
			}
		}
		
		idArray = obj.keys();
		len = idArray.length; 

		for(i = 0; i < len; i++) {
			a = idArray[i];
			
			if (allowed_keys != false && allowed_keys.hasKey(a) == false) {
				a = false;
			}
		
			if (! isNaN(a) && a != false) { 
				selected = ($(this.currentName) && a == $(this.currentName).getValue()) ? ' selected' : ''; 
				if (this.currentName == 'size' && i == 0) { this.sizeID = a; }
				if (! addition) {
/*
					
// COMMENTED CODE PREVENTS AUTOLOADING
					if ((len > 1 && i == 0 && !$(this.currentName)) || (len > 1 && i == 0 && $(this.currentName).getValue() == 0))
						options += '<option value="0"' + choose + '>' + this.localText['chooseText'] + '</option>';
*/
				} 
				
				var name = (addition) ? this.additionalOpts.get(this.currentName).get(a).get('name') : this.opts[this.currentName][a];
				
				if (this.currentName == 'coating' && name != undefined && name.indexOf('UV 2') != -1 && window.EC_Mailing && this.mailingCanUseUV == false) {
				
				} else {
					options += '<option value="' + a + '"' + selected + '>' + name + '</option>';
				}
				
			};
		};
		
		if (this.currentName == 'custom_green_paper') {
			this.currentName = 'paper';
		}
		
		return options;
	},

	createQuantityOptions: function(obj) { 
		var a;
		var options = '';
		var choose = '';
		var selected = ''; 
		if (obj.length > 0) {
			obj.each(function(a){ 
				if (!isNaN(a)) {
					selected = ($('quantity') && a == $('quantity').getValue()) ? ' selected' : '';
					options += '<option value="' + a + '"' + selected + '>' + a + '</option>'; 
				};
			});
		};
		return options;
	},

	createFoldingOptions: function(obj) { 
		var options = '';
		var selected = '';
		var coverStock = false;
		var indexStock = false;
		if ($('paper')) { 
			var selPaper = $('paper').options[$('paper').selectedIndex].text;
			if (selPaper.indexOf('Cover') != -1)
				coverStock = true;
			if (selPaper.indexOf('Index') != -1)
				indexStock = true;
		}

		obj.each(function(item, index){
			($('folding') && index == $('folding').getValue()) ? selected = ' selected' : selected = '';			
			if (coverStock) {
				if (item.get('name').indexOf('Cover') != -1 || item.get('name').indexOf('None') != -1) 
					options += '<option value="' + index + '"' + selected + '>' + item.get('name') + '</option>';
			} else if (indexStock) {
				if (item.get('name').indexOf('Index') != -1 || item.get('name').indexOf('None') != -1) 
					options += '<option value="' + index + '"' + selected + '>' + item.get('name') + '</option>';
			} else {
				if (item.get('name').indexOf('Cover') == -1 && item.get('name').indexOf('Index') == -1) 
					options += '<option value="' + index + '"' + selected + '>' + item.get('name') + '</option>'; 
			} 
		
		});

		return options;
	},

	updateForm: function() {
		var i = 0;
		var a;
		var func;
		this.formContents = '';
		this.currentSku = this.skus; 
			
		var done = false;
		
					this.updateArea();
			
		for (var i = 0; i < this.names.length; i++) { 
			this.currentName = this.names[i];
			this.currentTitle = this.titles[i]; 
			
			if (this.currentName == 'width' || this.currentName == 'height') {
				this.formContents += this.createSizeInput(this.currentTitle, this.currentName, 'EC_LithoCalc.updateForm()');
				if (this.currentName == 'width')
					continue;
					
			} else if (this.currentName == 'green_paper') {
			
			} else {
				if (this.currentName == 'size' && this.product_name == 'Roll Labels') {
					this.formContents += this.createDieShapeInput(this.localText['dieShapeText'], 'die_shape', 'EC_LithoCalc.updateForm()');
				}
				func = (this.currentName == 'size' && this.product_name != 'Roll Labels') ? 'EC_LithoCalc.resetTrimSize();' : '';
				this.formContents += this.createSelect(this.currentTitle, this.currentName, func + 'EC_LithoCalc.updateForm()', this.currentSku);
				if (this.currentName == 'size' && this.product_name != 'Roll Labels') {
					this.formContents += this.createTrimSizeInput(this.localText['trimSizeText'], 'trim_size', 'EC_LithoCalc.updateTrimSize()');
				}

				if (this.currentName == 'paper' && this.additionalOpts != undefined && this.additionalOpts.get('custom_green_paper') != undefined) {
					this.additionalOpts.each(function(item, key) {
						if (key == 'custom_green_paper') {
							EC_LithoCalc.currentName = key; 
							EC_LithoCalc.formContents += EC_LithoCalc.createSelect(EC_LithoCalc.localText[key + 'Text'], key, 'EC_LithoCalc.updatePrice()', item, true);
						}
					});
				}

			}

			var j = 0;	
			var retainA = '';
						
			this.currentSku.each(function(val, key) {
				j++;
				if(j == 1)
					retainA = key;
			});
			
			if (this.currentName == 'height') {
				var keys = this.currentSku.keys();
				keys.sort(EC_Base.sortNumber);
				keys.reverse(); 
				keys.each(function(val) { 
					if (EC_LithoCalc.area <= val) {
						retainA = val.toString(); 
						EC_LithoCalc.selectedArea = val;
					}
				});
			}
/*
// COMMENTED CODE PREVENTS AUTOLOADING

			if (j > 1 && !$(this.currentName))
				break;
			else if (j > 1 && $(this.currentName) && $(this.currentName).getValue() == 0)
				break;
				
			else {
*/			
				if ($(this.currentName) && this.currentSku.hasKey($(this.currentName).getValue()))
					this.currentSku = this.currentSku.get($(this.currentName).getValue());
			
				else if (this.currentSku.hasKey(retainA)) 
					this.currentSku = this.currentSku.get(retainA);
			
				else break;
//			};
		};

		if(this.currentSku > 0)
			this.setupQuantities();
		else
			this.createForm(this.formContents);
	},
	
	updateArea: function() {
		if ($('width') && $('height')) {
			var fractValue;
			this.widthText = Math.floor(Number($('width').getValue())).toString();
			this.heightText = Math.floor(Number($('height').getValue())).toString();
			if (this.widthText == 'NaN' || this.widthText < 1) {
				if (this.opts['min_width']) {
					var w = Number(this.opts['min_width']);
					if (w > Math.floor(w)) {
						fractValue = w - Math.floor(w);
						w -= fractValue;
					}
					this.widthText = w;
					fractValue = 0;
				} else {
					this.widthText = 1;
				}
			}
			
			if (this.heightText == 'NaN' || this.heightText < 1) {
				if (this.opts['min_height']) {
					var h = Number(this.opts['min_height']);
					if (h > Math.floor(h)) {
						fractValue = h - Math.floor(h);
						h -= fractValue;
					}
					this.heightText = h;
					fractValue = 0;
				} else {
					this.heightText = 1;
				}
			}
			
			var w = Math.floor(Number(this.widthText)) + Number($('widthFract').getValue());
			var h = Math.floor(Number(this.heightText)) + Number($('heightFract').getValue());

			if (isNaN(w)) {
				w = $('width').value = 0;
				$('widthFract').selectedIndex = 0;
			}
			if (isNaN(h)) {
				h = $('height').value = 0;
				$('heightFract').selectedIndex = 0;
			}
					
			fractValue = 0;

			if (w < Number(this.opts['min_width']) && w > 0) {
				alert('The minimum width is ' + this.opts['min_width']);
				this.resetToMinMx('width', this.opts['min_width']);
				return;
			}
			if (h < Number(this.opts['min_height']) && h > 0) {
				alert('The minimum height is ' + this.opts['min_height']);
				this.resetToMinMx('height', this.opts['min_height']);			
				return;
			}
			
			if (w > Number(this.opts['max_width'])) {
				alert('The maximum width is ' + this.opts['max_width']);
				this.resetToMinMx('width', this.opts['max_width']);
				return;
			}
			if (h > Number(this.opts['max_height'])) {
				alert('The maximum height is ' + this.opts['max_height']);
				this.resetToMinMx('height', this.opts['max_height']);
				return;
			}
			
			var n = Math.round(w - 0.000001);
			w = (n < w) ? n + .5 : Math.ceil(w);
			n = Math.round(h - 0.000001);
			h = (n < h) ? n + .5 : Math.ceil(h);

			this.area = w * h;
		}
	},
	
	updateTrimSize: function() {
		if ($('trim_size')) {
			var val = $('trim_size').getValue();
			val = val.replace(/([^0-9. Xx])/g, '');
			var size = $('size').options[$('size').selectedIndex].text;
			size = size.replace(/([^0-9. Xx])/g, '');
			
			var cW = Number(val.replace(/(\d+[.]*\d{0,4})([ Xx]+)(\d+[.]*\d{0,4})/, '$1'));
			var cH = Number(val.replace(/(\d+[.]*\d{0,4})([ Xx]+)(\d+[.]*\d{0,4})/, '$3'));
			var sW = Number(size.replace(/(\d+[.]*\d{0,4})([ Xx]+)(\d+[.]*\d{0,4})/, '$1'));
			var sH = Number(size.replace(/(\d+[.]*\d{0,4})([ Xx]+)(\d+[.]*\d{0,4})/, '$3'));

			cW = (cW > sW) ? sW : cW;
			cH = (cH > sH) ? sH : cH;
			
			if (isNaN(cW) || isNaN(cH) || cW == 0 || cH == 0) {
				$('trim_size').value = size;
			} else {
				$('trim_size').value = cW + ' X ' + cH;
			}
		}
	},
	
	resetTrimSize: function() {
		if ($('trim_size')) {
			$('trim_size').value = $('size').options[$('size').selectedIndex].text;
		}
	},

	setupQuantities: function() {
		var i = 0;
		var price = 0;

		if (this.folding) {					
			this.formContents += this.createSelect(this.localText['foldingText'], 'folding', 'EC_LithoCalc.updatePrice()', this.foldingOpts);
		};

		if (this.additional) { 
			this.additionalOpts.each(function(item, key) {
				if (key != 'custom_green_paper') {
					if (key == 'custom_finishing' && window.EC_Mailing) {
					
					} else {
						EC_LithoCalc.currentName = key; 
						EC_LithoCalc.formContents += EC_LithoCalc.createSelect(EC_LithoCalc.localText[key + 'Text'], key, 'EC_LithoCalc.updatePrice()', item, true);
					}
				}
			});
		};
	
		var quantities = this.prices.get(this.currentSku).keys();
		
		quantities.sort(this.numOrdA);
		
		this.formContents += this.createSelect(this.localText['quantityText'], 'quantity', 'EC_LithoCalc.updatePrice()', quantities);
	
		if ($('quantity')) {
			var q = $('quantity').getValue();		
			
						
						
							var sqFootPrice = this.prices.get(this.currentSku).get($('quantity').getValue()).get('p');
				price = sqFootPrice * this.area * q;
						
		} else { 
			var keys = this.prices.get(this.currentSku).keys();
			price = this.prices.get(this.currentSku).get(keys[0]).get('p');
		}
		
		if (window.EC_Mailing) {
			this.formContents += EC_Mailing.updateForm();
		} else {
			this.formContents += calcHR_TPL();
		}

		this.formContents += calcTotalFI_TPL(this.localText['priceText'], '<div id="printRate" class="price">' + EC_Base.moneyFormat(price)+'</div>', '');	
		
		
		if (window.EC_Mailing) {
			this.formContents += EC_Mailing.totalsForm();
		} else {
			this.formContents += calcHR_TPL();
		}
		
		this.formContents += calcFI_TPL('', calcBTN_TPL(this.localText['orderText'], 'EC_LithoCalc.placeOrder()'), '');
		this.formContents += calcFI_TPL('', calcBTN_TPL(this.localText['estimateText'], 'EC_LithoCalc.printEstimate()'), '');
		
		if (! window.EC_Mailing) {
			this.formContents += this.setupShipping();
		} else {			
			this.formContents += postageWarning();
		}
		
		this.createForm(this.formContents);
		
					this.updateArea();
				
		this.updatePrice();
	},

	updateFolding: function() {
		var myForm = $('myForm'); 
		
		var foldVal = $('folding').getValue();
		if (foldVal == undefined) {
			var vals = this.foldingOpts.keys();
			foldVal = vals[0];
		} 		
		 
		var fp = this.foldingOpts.get(foldVal).get('price');
		var fs = this.foldingOpts.get(foldVal).get('setup');
		var q = ($('quantity').options) ? $('quantity').options[$('quantity').selectedIndex].text : $('quantity').getValue();
				var multiplier = parseInt(q);		
				this.foldRate = (Number(fp) * multiplier) + Number(fs);
	},

	updatePrice: function() { 
		this.foldRate = 0;
		if ($('folding') && this.folding == true)
			this.updateFolding();

		if ($('quantity')) {
			this.currentSku = this.skus;

			for (var i = 0; i < EC_LithoCalc.names.length; i++) {			
				this.currentName = EC_LithoCalc.names[i];
				
				if ($(this.currentName) && this.currentName != 'width' && this.currentName != 'height') {
					var lastSku = this.currentSku;
					this.currentSku = this.currentSku.get($(this.currentName).value);	 
					
					if (this.currentSku == undefined) {
						EC_LithoCalc.updatePrice.delay(200);return;
					}
				}
				if ($(this.currentName) && this.currentName == 'height') { 
					this.currentSku = this.skus.get($('product').value).get(this.selectedArea);
				}
			}
			
						
						
							var sqFootPrice = this.prices.get(this.currentSku).get($('quantity').value).get('p');

				// Use this if you want to calculate real area * price
				var tmpPrice = sqFootPrice * this.area * $('quantity').value;
				
				if (this.area < this.minimum_area_for_price) {
					var tmpPrice = sqFootPrice * this.minimum_area_for_price * $('quantity').value;
				}

				// Use this if you want to calculate price at the max area
				//var tmpPrice = sqFootPrice * this.selectedArea * $('quantity').value;				
						
			if (tmpPrice < this.minimum_price) {
				tmpPrice = this.minimum_price;
			}
			
			var additionalMap = new Hash({hole_punch: 1000, numbering: 1000, perforation: 1000, print_type: 1000, pms_ink: 1000, lamination: 1, mounting: 1, finishing: 1, grommets: 1, hemming: 1, pole_pockets: 1});
			
			if (this.additional) { 
				this.additionalOpts.each(function(item, key) {
					if ($(key)) { 
						var divide = 1000;
						var short_key = key.replace(/custom_/, '');
						if (additionalMap.hasKey(short_key)) {
							divide = Number(additionalMap.get(short_key));
						}

						var price = Number(EC_LithoCalc.additionalOpts.get(key).get($(key).value).get('price'));
						var setup = Number(EC_LithoCalc.additionalOpts.get(key).get($(key).value).get('setup'));
						
						if (short_key == 'lamination' || short_key == 'mounting') {
							tmpPrice += (price * EC_LithoCalc.area * ($('quantity').value / divide)) + setup;
						} else {
							tmpPrice += (price * ($('quantity').value / divide)) + setup;
						}
					};
				});
			};
			
			this.printRate = tmpPrice + this.foldRate;
			$('printRate').setHTML(EC_Base.moneyFormat(this.printRate));
			
			if (window.EC_Mailing) {
				EC_Mailing.updatePrice();
			}
			
			if ($('zipcode')) {
				var zip = $('zipcode').getValue();
				if (zip.length == 5) 
					this.getShipRates();
			}
			var totals = {print: this.printRate, folding: this.foldRate, shipping: this.shipRates};
			if (window.EC_Mailing) {				
				totals.setup = Number($('setupRate').getText().replace(/([^0-9.])/, ''));
				totals.inkjet = Number($('inkjetRate').getText().replace(/([^0-9.])/, ''));
				totals.tabbing = Number($('tabbingRate').getText().replace(/([^0-9.])/, ''));
				totals.postage = Number($('postageRate').getText().replace(/([^0-9.])/, ''));
				if ($('listRate')) {
					totals.list = Number($('listRate').getText().replace(/([^0-9.])/, ''));
				}
				totals.total = Number($('totalRate').getText().replace(/([^0-9.])/, ''));
			}
			if ($('totals')) {
				$('totals').value = Json.toString(totals);
			} else {
				EC_LithoCalc.updatePrice.delay(100);
			}
		}
	},

	printEstimate: function() {
		if (this.order_action == '') {
			alert('This feature is not available right now. Please try again later.');
			return;	
		}
		$('myForm').action = estimateURL;
		$('myForm').target = 'estimatepopup';
		estimatePopup($('myForm').target); 
		
		setTimeout(function () { $('myForm').submit(); }, 100);
	},

	placeOrder: function() { 		
		$('myForm').target = '_self';
		if (this.order_action != '') {
			$('myForm').action = this.order_action;
		}
		
		if (this.currentSku != null)
			var priceid = this.prices.get(this.currentSku).get($('quantity').getValue()).get('i');
		else {
			var keys = this.prices.keys();
			var priceid = this.prices.get(keys[0]).get($('quantity').getValue()).get('i');
		}
		var myForm = $('myForm');	
		myForm['price_id'].value = priceid;
		
		this.flag_form = false;
		
		if (window.confirmText && confirmText != '') {
			if (!$('disallow_popups') || ($('disallow_popups') && $('disallow_popups').getValue() != '1')) {
				var answer = confirm(confirmText);
				if (answer){
					myForm.submit();
				}
			}
		} else {		
			myForm.submit();
		}
	},

	addSKU: function(ids, val) {
		var a;
		var i;
		var aSku;
		var len = ids.length;

		ids.each(function(item, index) {
   		if (index > 0) {
				aSku = aSku.get(ids[index - 1]);
			} else {
				aSku = EC_LithoCalc.skus;
			}
			
			if (!aSku.hasKey(item)) 
				aSku.set(item, new Hash());			

			if (index == len - 1) 
				aSku.set(item, val);
		});
	},

	setupShipping: function() {
		var ship = calcHR_TPL();
		ship += calcFI_TPL('', '<h4 class="formHeading">' + this.localText['shippingText'] + '</h4>', '');
		if (this.international == 1)
			ship += calcFI_TPL(this.localText['countrycodeText'], this.country_code, '');
		else
			ship += this.country_code;
			
		ship += calcFI_TPL(this.localText['zipcodeText'], '<input type="text" class="zipTI" id="zipcode" name="zipcode" onkeyup="EC_LithoCalc.checkEnter(event, \'EC_LithoCalc.getShipRates()\')" /><input id="getRatesBTN" type="button" class="rateBTN" value="' + this.localText['ratesText'] + '" onclick="EC_LithoCalc.getShipRates()" />', '');
/*
// THIS IS FOR SHIPPING SELECT

		ship += calcFI_TPL(this.localText['shipmethodText'], this.shipSelect(), '');
		ship += calcFI_TPL(this.localText['shiprateText'], '<div id="shipRate" class="price" />', '');
		
*/
		ship += calcShipGrid_TPL('<br />');
		return ship;
	},
	
	shipSelect: function() {
/*
// THIS IS FOR SHIPPING SELECT

		var sel = '<select id="shipMethod" name="shipMethod" onchange="EC_LithoCalc.changeShipRates()">';
		shipOpts.each(function(val, key) {
			sel += '<option value="' + key + '">' + val + '</option>';
		});
		sel += '</select>';
		return sel;
*/
	},

	getShipRates: function() {
		if (! this.currentSku) {
			this.updateForm();
		}
		var button = $('getRatesBTN');
		var zip = $('zipcode').getValue();
		if (button.disabled)
			return;
			
		var country = $('country_code').getValue();
		
// FIX THIS FOR countries::postal_code_format

		if ((zip.length != 5 || isNaN(zip)) && country == 'US') {
			alert(this.localText['ziperrorText']);
			return;
		}
		button.value = this.localText['pleasewaitText'];
		button.disabled = true;
		this.timer = setTimeout('EC_LithoCalc.stopRates()', 10000); 
		
				
				
		
					this.selWeight = Math.round((Number($('quantity').getValue()) * this.weights[this.currentSku] * this.area) * 10) / 10;
				
	
		var url = '/ws/shipping/getRates/zip/' + zip + '/country/' + country + '/weight/' + this.selWeight + '/handling_fee/' + this.handling_fee + '/product_id/' + this.product_id;
		
		if (this.free_ground_shipping) {
			url += '/fgs/1';
		}
		
		var myAjax = new Ajax(url, {method: 'get', onSuccess: function(rates) {
			EC_LithoCalc.shipRates = Json.evaluate(rates);
			EC_LithoCalc.stopRates();
			EC_LithoCalc.changeShipRates();
			if (EC_LithoCalc.shipRates.error) {
				alert(EC_LithoCalc.shipRates.error);
			}
			
			if ($('totals')) {
				var totals = Json.evaluate($('totals').getValue());
				totals.shipping = EC_LithoCalc.shipRates;
				$('totals').value = Json.toString(totals);
			}
		}}).request();
	},

	stopRates: function() {
		var button = $('getRatesBTN');
		button.value = this.localText['ratesText'];
		button.disabled = false;
		clearTimeout(this.timer);
	},

	changeShipRates: function() {
/*
// THIS IS FOR SHIPPING SELECT

		var rate = this.shipRates[$('shipMethod').getValue().toString()];
		if (rate >= 0) {
			$('shipRate').setHTML(EC_Base.moneyFormat(rate));
			var myForm = $('myForm');
			myForm['quote'].value = rate;
		} else { 
			$('shipRate').setHTML(this.localText['pleaseclickText']);
		}
*/

/**/
// THIS IS FOR SHIPPING GRID

		var checked = ' checked';
		$$('input[name=shipMethod]').each(function(item) {
			if (item.checked != false)
				checked = item.value.toString();
		});
		
		$('shipGrid').setHTML('<br />' + this.shipGrid(checked));
		
/**/
	},
	
	shipGrid: function(first) {
		var grid = '<table width="100%">';
		var rate = '';
		var country = $('country_code').getValue();
		var free_delivery = false;
		
		if ($('delivery') && $('delivery_zipcode') && $('delivery_countrycode')) {
			if ($('delivery').getValue() == 1 && 
					($('delivery_zipcode').getValue() == $('zipcode').getValue() || $('delivery_zipcode').getValue() == 'ANY') && 
					country == $('delivery_countrycode').getValue()) {
				free_delivery = true;
			}
		}
		
		shipOpts.each(function(val, key) { 
			if (! val.match(/Recycle/)) {
				var rate = EC_LithoCalc.shipRates[key.toString()];
				if (first == key.toString())
					first = ' checked';
				
				if (rate !== false && !isNaN(rate)) { rate = EC_Base.moneyFormat(rate); }

				if (rate !== false && rate != undefined) { 
					
					if ((key != 'DL' || (key == 'DL' && free_delivery == true)) && key != 'FR') {
						grid += '<tr><td class="ship_desc"><input type="radio" name="shipMethod" value="' + key.toString() + '"' + first + ' />';
						grid += val + '</td><td class="ship_price">' + rate + '</td></tr>';
					}
					else if(key == 'FR') {
												grid += '<tr><td class="ship_desc"><input type="radio" name="shipMethod" value="' + key.toString() + '"' + first + ' />';
						grid += val + '</td><td class="ship_price">' + rate + '</td></tr>';
											}
					if (first == ' checked') first = '';	
				}
			}
		});
		grid += '</table>';

		return grid;
	},

	checkEnter: function(event, func) {
		event = new Event(event);
    if (event.key == 'enter') {
			if (func) { eval(func); }
    	event.stop();
    	this.flag_form = true;
		}
	},
	
	selectByValue: function(el, val) {
		if (typeof(el) === 'string') {
			el = $(el);
		}
		if (el && el.options) {
			for (var i = 0; i < el.options.length; i++) {
				if (el.options[i].value == val) {
	        el.options[i].selected = true;
	        el.options.selectedIndex = i;
	      }
			}
		}
	},
	
	resetToMinMx: function(dimension, value) {
		var fractValue = 0;
		value = Number(value);
		if (value > Math.floor(value)) {
			fractValue = value - Math.floor(value);
			value -= fractValue;
		}
					
		this[dimension + 'Text'] = value;
		$(dimension).value = value;
		if (fractValue == 0) { fractValue = '.0'; }
		this.selectByValue(dimension + 'Fract', fractValue);
		
		var w = Math.floor(Number(this.widthText)) + Number($('widthFract').getValue());
		var h = Math.floor(Number(this.heightText)) + Number($('heightFract').getValue());
		
			var n = Math.round(w - 0.000001);
			w = (n < w) ? n + .5 : Math.ceil(w);
			n = Math.round(h - 0.000001);
			h = (n < h) ? n + .5 : Math.ceil(h);
		
		this.area = w * h;
		this.updatePrice();
	},

	numOrdA: function(a, b){ return (a-b); },

	numOrdD: function(a, b){ return (b-a); },
	
	debug: function(obj, recursive) {
		var out = '';
		if (recursive)
			out = EC_Base.dumpObj(obj, true);
		else
			out = obj;
			
		$('calcDebug').setHTML(out + '<br />=======================================<br /><br />');
	}

};

window.addEvent('domready', function() {
	EC_LithoCalc.init();
});
	