//dojo.require("dojo.fx");
dojo.declare("PriceCalc", null, {
	printShipping: ['UPS Ground', 'UPS 2-Day Air', 'UPS Next Day', 'Pickup'],
    mailShipping: ['UPS 2-Day Air', 'Pickup'],
	constructor: function(rootNode) {
		if (!dojo.byId(rootNode)) {
			return;
		}
		this.sections = {};
		var _t = this;
		this.rootNode = dojo.byId(rootNode);
		this.form = dojo.query(".js_form_calc", rootNode)[0];
		dojo.query(".js_section", rootNode).forEach(function(item) {
			var aSection = new CalcSection(item, _t);
			if (aSection.name == 'mailing') {
				aSection.mailingServicesFeeNode = dojo.query(".js_mailingservices_fee", item)[0];
			}
			_t.sections[aSection.name] = aSection;
		});
		this.connectFormElement();
		this.totalNode = dojo.query(".js_total", rootNode)[0];
		this.unitPriceNode = dojo.query(".js_unitprice", rootNode)[0]
		this.setShippingText();
		this.quantityChanged();
	},
	
	connectFormElement: function() {
		var _t = this;
		dojo.connect(dojo.byId('js_order_button'), "onclick", this, this.oosOrder);
		
		dojo.query("select", this.form).forEach(function(item){
			if (item.name == 'product') {
				_t.productSelect = item;
			} else if (item.name == 'quantity') {
				_t.quantitySelect = item;
			} else if (item.name == 'shipping') {
				_t.shippingSelect = item;
			} else if (item.name == 'turnaround') {
				_t.turnaroundSelect = item;
			} else if (item.name == 'prod_cat') {
				_t.productCategorySelect = item;
				return; // no connect for this one
			}
			
			dojo.connect(item, "onchange", _t, _t.updatePrice);
		});
		this.setSelectedCategory();
		dojo.query("input", this.rootNode).forEach(function(item){
			if (item.type == "text") {
				dojo.connect(item, "onkeydown", _t, _t.inputKeydown);
				dojo.connect(item, "onblur", _t, _t.updatePrice);
				if (item.name == 'mailingQty') {
					_t.mailingQtyField = item;
				}
			}
		});
	},
	
	setSelectedCategory: function() {
		this.selectedCategory = this.productCategorySelect.options[this.productSelect.selectedIndex].text;
		if (this.selectedCategory == 3) {
			this.sections["mailing"].hideSection();
			this.sections["list"].hideSection();
			this.sections["mailing"].hideRoot();
			this.sections["list"].hideRoot();
		} else {
			this.sections["mailing"].showRoot();
			this.sections["list"].showRoot();
		}
	},
	
	hasMailing: function() {
		 return this.sections["mailing"].visible && typeof (this.mailingQtyField) != "undefined" && this.mailingQtyField.value > 0;
	},
	
	mailingQty: function() {
		if (!this.sections["mailing"].visible) {
			return 0;
		} else if (this.mailingQtyField.value == '') {
			return 0;
		} else {
			var qty = parseInt(this.mailingQtyField.value);
			if (isNaN(qty)) {
				return 0;
			}
			return qty;
		}
		
	},
	
	printQty: function() {
		return parseInt(this.quantitySelect.options[this.quantitySelect.selectedIndex].text);
	},
	
	inputKeydown: function(e) {
		if (e.keyCode == dojo.keys.ENTER) {
			e.preventDefault();
			this.updatePrice(e);
		}
	},
	
	sectionVisible: function(name) {
		var aSec = this.sections[name];
		if (!aSec) {
			return false;
		}
		return aSec.visible;
	},
	
	cookieForEstimator: function() {
		var f = this.form;
		var cookieValue;
 		cookieValue = f.product.selectedIndex + ":";
 		var qty = f.quantity;
		cookieValue += qty[qty.selectedIndex].text + ":";
		cookieValue += f.color.selectedIndex + ":";
		cookieValue += this.sectionVisible("mailing") + ":";
		if ( typeof (f.mailingQty) != "undefined" ) {
   			cookieValue += f.mailingQty.value + ":";
    		cookieValue += f.postage.selectedIndex + ":";
      	} else {
    		cookieValue += "::";
      	}
      	cookieValue += this.sectionVisible("list") + ":";
      	if ( typeof (f.listQty) != "undefined" ) {
    		cookieValue += f.listQty.value + ":";
   	 		cookieValue += f.listType.selectedIndex + ":";
    		cookieValue += f.usage.selectedIndex + ":";
      	} else {
         	cookieValue += ":::";
      	}
      	cookieValue += this.sectionVisible("production_time") + ":";
      	if ( typeof (f.turnaround) != "undefined" ) {
       		cookieValue += f.turnaround.selectedIndex + ":";
      	} else {
      		cookieValue += ":";
      	}
      	cookieValue += this.sectionVisible("shipping") + ":";
      	if (typeof(f.shipping) != "undefined") {
	    	cookieValue += f.shipping.selectedIndex + ":";
	    	if ( typeof ( f.zipcode) != "undefined" )
	    		cookieValue += f.zipcode.value + ":";
      	} else {
      		cookieValue += "::";
      	}
    	document.cookie = "MPEstimator=" + cookieValue+"; path=/";
      	return cookieValue;
    },
	updateShippingOptions: function(sender) {
  		var shippingOpt = this.form.shipping.options;
  		if ( this.hasMailing() ) {
   			if ( shippingOpt.length == 3 ) {
   				return;
   			}
   		} else {
   			if ( shippingOpt.length != 3 ) {
   				return;
   			}
   		}
  		this.form.shipping.selectedIndex = 0;
  		for ( i = shippingOpt.length - 1; i > 1; i-- )
  			shippingOpt[i] = null;
  			if ( this.hasMailing()) {
  				for ( i = 0; i < this.mailShipping.length; i++ ) {
  					shippingOpt[i+1] = new Option(this.mailShipping[i], i+1);
  				}
  				this.setShippingText();		
  			} else {
   				for ( i = 0; i < this.printShipping.length; i++ ) {
  				shippingOpt[i+1] = new Option( this.printShipping[i], i+1);
  			}		
   		}
	},
	
	setShippingText: function() {
		if ( this.hasMailing() ) {
			if ( this.form.turnaround.selectedIndex == 0 ) {
				this.form.shipping.options[1].text = 'UPS Next Day';
      		} else  {
				this.form.shipping.options[1].text = 'UPS 2-Day Air';
     		}
     	}
    },
	
	toggleChanged: function(sender) {
		if (sender.name == 'mailing') {
			this.updateShippingOptions();
			if (!this.mailingQtyChanged()) {
				return;
			}
			if (!sender.visible && this.sections["list"].visible) {
				this.sections["list"].toggle();
			}
		} else if (sender.name == 'list') {
			if (sender.visible && !this.sections["mailing"].visible) {
				this.sections["mailing"].toggle();
			}
		} else if (sender.name == 'production_time') {
			if (!this.turnAroundChanged()) {
				return;
			}
		}
		this.updatePrice();
	},
	
	canExpand: function(sender) {
		if (sender.name == 'mailing' || sender.name == 'list') {
			if (this.selectedCategory == 3) {
				this.sections["products"].showAlert('Oops','Mailing services and List purchase not available for specialty products');
				return false;
			}
		}
		return true;
	},
	
	productChanged: function() {
		this.sections["products"].hideAlert();
		this.setSelectedCategory();
		if (this.sections["production_time"].visible) {
			ok = this.turnAroundChanged();
			if (!ok) {
				return false;
			}
		}
		return true;
	},
	
	turnAroundChanged: function() {
		if (this.selectedCategory == 2) {
			var selIndex = this.turnaroundSelect.selectedIndex;
			if (selIndex < 3) {
				this.sections["production_time"].showAlert("Oops", "Online orders of Tri-Fold products are currently only available with our 4 business day production time. For expedited options, please contact an Account Representative at 888-946-7335.");
				this.turnaroundSelect.selectedIndex = 3;
				return true;
			}
		} 
		this.sections["production_time"].hideAlert();
		this.setShippingText();
		return true;
	},
	
	quantityChanged: function() {
		if (this.printQty() < this.mailingQty()) {
			//this.sections["products"].showAlert("Oops", "Your mailing quantity can't be greater than your print quantity");
			//this.sections["mailing"].hideAlert();
			return true;
		} 
		var printQty = this.printQty();
		if (printQty > 50000  ) {
			this.sections["products"].showAlert("Contact us for the best price!", "Please contact our Corporate Sales Team and weÕll help your program to be as successful as possible. We will help you secure the lowest price as well as getting you the right list, advice you on content, and help with design to boost results and maximize your return on investment.<span class=\"phone\">800.406.1705</span>");
		} else if (printQty > 35000) {
			this.sections["products"].showAlert("Plan your direct mail project with an expert.", 'Please call an account representative so we can help you with your current project including information on mailing services, lists and quantity printing.<span class="phone">888.959.8365 x7500</span>');
		} else if (printQty >= 25000) {
			this.sections["products"].showAlert("Contact us for the best price!", "Please contact a representative to receive the lowest possible price quote. The calculator reflects our list pricing and does not include any current offers or specials. Our representatives are ready to help you with all aspects or your project including printing, design, lists and mailing.<span class=\"phone\">888.946.7335</span>");
		} else {
			this.sections["products"].hideAlert();
		}
		return true;
	},
	
	mailingQtyChanged: function(e) {
		if (this.printQty() < this.mailingQty()) {
			//this.sections["products"].hideAlert();
			//this.sections["mailing"].showAlert("Oops", "Your print quantity can't be greater than your mailing quantity");
			return true;
		} 
		this.updateShippingOptions();
		return true;
	},
	loadData: function(response, ioargs) {
		this.sections["products"].subtotalNode.innerHTML = response.printSubtotal;
		this.sections["mailing"].mailingServicesFeeNode.innerHTML = response.mailingServicesFee;
		this.sections["mailing"].subtotalNode.innerHTML = response.mailingSubtotal;
		this.sections["list"].subtotalNode.innerHTML = response.listSubtotal;
		this.sections["production_time"].subtotalNode.innerHTML = response.turnaroundSubtotal;
		this.sections["shipping"].subtotalNode.innerHTML = response.shippingPrice;
		if (response.qtyAdjusted) {
			var options = this.quantitySelect.options;
			var i;
			for (i = 0; i < options.length; i++) {
				if (options[i].text == response.quantity) {
					this.quantitySelect.selectedIndex = i;
					break;
				} 
			}
			this.sections["mailing"].showAlert("Oops", "Your mailing quantity can't be greater than your print quantity. Your print quantity has been adjusted");
		}
		this.totalNode.innerHTML = response.total;
		this.unitPriceNode.innerHTML = response.unitPrice;
		if (response.shippingHasError) {
			this.sections["shipping"].showAlert("Oops", "The zipcode you entered isn't valid");
		}
	},
	
	oosOrder: function(e) {
		e.preventDefault();
 		var cookie = this.cookieForEstimator();
  
  		var url = 'https://order.modernpostcard.com';
  		url = url.replace(/^(http[s]?:\/\/[^\/]*)\/.*$/, '$1');
 		url += '/cgi-bin/WebObjects/OrderOnline.woa/wa/setCalcOrder?data='+cookie;
  		document.location.href = url;
    },
    
	updatePrice: function(e) {
		var ok = true;
		if (e) {
			var sender = e.currentTarget;
			if (sender == this.productSelect) {
				ok = this.productChanged();
			} else if (sender == this.quantitySelect) {
				ok = this.quantityChanged();
			} else if (sender == this.mailingQtyField) {
				ok = this.mailingQtyChanged();
			} else if (sender == this.turnaroundSelect) {
				ok = this.turnAroundChanged();
			}
		}
		if (!ok) {
			return;
		}
		//this.sections["products"].hideAlert(true);
		this.sections["mailing"].hideAlert(true);
		//this.sections["production_time"].hideAlert();
		this.sections["shipping"].hideAlert(true);
		var cookie = this.cookieForEstimator();
		dojo.xhrPost({
			url: this.form.action,
			content: {
				"cookie": cookie
			},
			sync: false,
			handleAs: 'json',
			load: dojo.hitch(this, this.loadData),
			error: function(response, ioargs) {
				console.dir(ioargs);
				alert(response);
			}
		
		});
	}
});

dojo.declare("CalcSection", null, {
	constructor: function(sectionRoot, calcCtr) {
		this.rootNode = sectionRoot;
		this.name = sectionRoot.id;
		this.calcCtr = calcCtr;
		this.alert = dojo.query(".js_row_alert", this.rootNode)[0];
		dojo.connect(this.alert, "onclick", this, this.hideAlert);
		this.alertText = dojo.query(".alert_text", this.alert)[0];
		this.contentNode = dojo.query(".js_toggle_content", this.rootNode)[0];
		this.visible = (dojo.style(this.contentNode, "display") != "none");
		this.toggleButton = dojo.query(".js_toggle_button", this.rootNode)[0];
		dojo.style(this.toggleButton, "cursor", "pointer");
		this.subtotalNode = dojo.query(".js_subtotal", this.rootNode)[0];
		dojo.connect(this.toggleButton, "onclick", this, this.toggle);
		/* 
		this.toggler = new dojo.fx.Toggler({
							node: this.contentNode,
							showDuration: 500,
							hideDuration: 500,
							showFunc: dojo.fx.wipeIn,
							hideFunc: dojo.fx.wipeOut
							}
						);
		this.alertToggler = new dojo.fx.Toggler({
							node: this.alert,
							showDuration: 500,
							hideDuration: 500,
							showFunc: dojo.fx.wipeIn,
							hideFunc: dojo.fx.wipeOut
							}
						);
		*/
		this.toggler = jQuery(this.contentNode);
		this.alertToggler = jQuery(this.alert);
	},
	
	toggle: function(e) {
		if (e) {
			e.preventDefault();
		}
		if (!this.calcCtr.canExpand(this)) {
			return;
		}
		if (this.visible) {
			//this.toggler.hide();
			this.toggler.slideUp('slow');
			this.toggleButton.src = "/modern/calc/images/icon_show.gif";
			this.visible = false;
		} else {
			//this.toggler.show();
			this.toggler.slideDown('slow');
			this.toggleButton.src = "/modern/calc/images/icon_hide.gif";
			this.visible = true;
		}
		this.calcCtr.toggleChanged(this);
	},
	
	hideSection: function(e) {
		this.toggler.hide();
	}, 
	
	htmlForAlert: function(title, text) {
		return '<h6>'+ title +'</h6><p>' + text +'</p>'
	},
	
	showAlert: function(title, text) {
		this.alertText.innerHTML = this.htmlForAlert(title, text);
		if (dojo.style(this.alert, "display") == "none") {
			//this.alertToggler.show();
			this.alertToggler.slideDown('fast');
		}
	},
	
	hideAlert: function(noAnimate) {
		if (dojo.style(this.alert, "display") == "block") {
			//this.alertToggler.hide();
			if (noAnimate) {
				this.alertToggler.hide();
			} else {
				this.alertToggler.slideUp('fast');
			}
		}
	},
	
	hideRoot: function() {
		dojo.style(this.rootNode, "display", "none");
	},
	
	showRoot: function() {
		dojo.style(this.rootNode, "display", "block");
	} 
});

dojo.addOnLoad(function(){
	new PriceCalc('calc');
});

