var Faq = Class.create();
Faq.prototype = {
	initialize: function(container) {
		this.container = $(container);
		this.questions = this.container.getElementsBySelector('a.q');
		this.answers   = this.container.getElementsBySelector('p');
		this.setup();
	},
	setup: function() {
		this.questions.each(function(el, i) {
			el.onclick = function() {
				this.answers[i].toggle();
				return false;
			}.bind(this);
		}.bind(this));
		
		this.answers.each(function(el, i) {
			el.hide();
		});
	}
}

/*--------------------------------------------------------------------------*/

var Rating = Class.create();
Object.extend(Object.extend(Rating.prototype, PopUp.prototype), {
	initialize: function(trigger, popup, stars) {
		this.trigger = trigger;
		this.popup   = $(popup);
		this.stars   = $(stars);
		this.options = {
			onOpen: this.setup.bind(this)
		}
		this.start();
	},
	setup: function() {
		new Stars(this.stars)
		this.form = this.popup.getElementsByTagName('form')[0];
		this.validator = new Validation(this.form, {onSubmit: false});
		Event.observe(this.form, 'submit', this.validate.bindAsEventListener(this));
		Form.getElements(this.form).each(function(el) {
			Event.observe(el, 'focus', function() {
				el.addClassName('active');
				if (el.value == el.defaultValue) {
					el.value = '';
				}
			});
			
			Event.observe(el, 'blur', function() {
				if (el.value == '') {
					el.removeClassName('active');
					el.value = el.defaultValue;
				}
			});
		});
		
		Validation.add('validate-not-default', 'This field is required.', {
			notOneOf: ['Your First Name', 'Your Review']
		})
	},
	validate: function(event) {
		if (this.validator.validate()) {
			var myAjax = new Ajax.Updater('reviewResponse', '/ae/control/createProductReviewAjax',
				{method: 'post', parameters: Form.serialize(this.form)});
		}
		Event.stop(event);
	}
});

/*--------------------------------------------------------------------------*/

var Sample = Class.create();
Object.extend(Object.extend(Sample.prototype, PopUp.prototype), {
	initialize: function(trigger, popup, stars) {
		this.trigger = trigger;
		this.popup   = $(popup);
		this.field      = $('qty_sample');
		this.total      = $('sampleTotal');
		this.coupon     = $('sampleCouponAmount');
		this.price      = 1.00;
		this.max_coupon = 5.00;
		this.options = {
			onOpen: this.setup.bind(this)
		}
		this.start();
	},
	setup: function() {
		this.field.onkeydown = function() {
			this.validate($F(this.field));
		}.bind(this);
		
		this.field.onkeyup = function() {
			this.validate($F(this.field));
		}.bind(this);
	},
	validate: function(qty) {
		if (!qty.match(/^\d+$/)) {
			this.total.innerHTML   = 'Error!';
		} else {
			var amt = this.price * qty;
			this.total.innerHTML = Format.dollar(amt);
			this.total.style.color = "";
			
			if (amt > this.max_coupon) {
				this.coupon.innerHTML = Format.dollar(this.max_coupon);
			} else {
				this.coupon.innerHTML = Format.dollar(amt);
			}
		}
	}
});

/*--------------------------------------------------------------------------*/

var SendToFriend = Class.create();
Object.extend(Object.extend(SendToFriend.prototype, PopUp.prototype), {
	initialize: function(trigger, popup, stars) {
		this.trigger = trigger;
		this.popup   = $(popup);
		this.options = {
			onOpen: this.setup.bind(this)
		}
		this.start();
	},
	setup: function() {
		this.popup.removeClassName('successful');
		this.popup.removeClassName('failure');
		this.form = this.popup.getElementsByTagName('form')[0];
		this.validator = new Validation(this.form, {onSubmit: false});
		Event.observe(this.form, 'submit', this.validate.bindAsEventListener(this));
	},
	validate: function(event) {
		if (this.validator.validate()) {
			var myAjax = new Ajax.Request('/ae/control/sendToFriend',
				{method: 'post', parameters: Form.serialize(this.form), onComplete: this.respond.bind(this)});
		}
		Event.stop(event);
	},
	respond: function(request) {
		if (request.responseText) {
			var response = request.responseText.evalJSON();
			if (response.message == 'SUCCESS') {
				this.popup.addClassName('successful');
			} else {
				this.popup.addClassName('failure');
			}
		}
	}
});

/*--------------------------------------------------------------------------*/

var Stars = Class.create();
Stars.prototype = {
	initialize: function(container) {
		this.ratings = container;
		this.lockStar = false;
		this.rating = 0;
		this.setup();
	},
	setup: function(){
		if(this.ratings.length > 1){
			this.ratings.each(function(rating,i){
				var stars = rating.getElementsByTagName('a');
				stars.each(function(star,i){
					star.onmouseover = function(){
						Element.addClassName(star, 'on');
						return false;
					}
				});
			});
		} else {
			var stars = $A(this.ratings.getElementsByTagName('a'));
			stars.each(function(star,i){
				star.onmouseover = function(){
					for(var j=0; j<=i; j++){
						Element.addClassName(stars[j], 'on');
					}
					if(this.lockStar){
						for(var j=(i+1); j<stars.length; j++){
							Element.removeClassName(stars[j], 'on');
						}
					}
					return false;
				}.bind(this);
				
				star.onclick = function(){
					this.rating = (i+1);
					if(!this.lockStar) this.lockStar = true;
					if($('productRating') && this.lockStar)  {
						$('productRating').value = this.rating;
					}
					return false;
				}.bind(this);
			}.bind(this));
			
			this.ratings.onmouseout = function(){
				for(var i=0; i<stars.length; i++){
					Element.removeClassName(stars[i], 'on');
				}
				if(this.lockStar){
					for(var i=0; i<this.rating; i++){
						Element.addClassName(stars[i], 'on');
					}
				}
				return false;
			}.bind(this);
		}
	}
}


/*--------------------------------------------------------------------------*/

var Zoom = Class.create();
Object.extend(Object.extend(Zoom.prototype, PopUp.prototype), {
	initialize: function(trigger, popup) {
		this.trigger = $(trigger);
		this.popup   = $(popup);
		this.options = {
			onOpen: function() {
				var img = this.popup.down('td.content').down('img');
				img.src = this.trigger.href;
			}.bind(this)
		}
		this.start();
	}
});

/*--------------------------------------------------------------------------*/

var Pricing = Class.create();
Pricing.prototype = {
	initialize: function(form, container) {
		this.form      = $(form);
		this.container = $(container);
		this.tabs      = new Tabs(this.container, 0, { clickCallback: this.trackClick });
		this.more      = [];
		this.custom    = []
		this.setup();
	},
	setup: function() {
		Event.observe(this.form, 'submit', this.validate.bindAsEventListener(this));
		
		new Form.Element.RadioEventObserver(this.form, 'colorsFront', this.getPrices.bind(this));
		new Form.Element.RadioEventObserver(this.form, 'colorsBack', this.getPrices.bind(this));
		new Form.Element.RadioEventObserver(this.form, 'cuts', this.getPrices.bind(this));
		new Form.Element.RadioEventObserver(this.form, 'folds', this.getPrices.bind(this));
		new Form.Element.RadioEventObserver(this.form, 'prodTime', this.getPrices.bind(this));

		//this.highlight = new Pricing.Highlights(this.form);
		//this.highlight.setup();
	
		//for (var i = 0; i < this.tabs.tabs.length; i++) {
		//	this.more[i] = new Pricing.More(this.tabs.tabs[i]);
		//}
		
		for (var i = 0; i < this.tabs.tabs.length; i++) {
			this.custom[i] = new Pricing.Custom(this.form, this.tabs.tabs[i]);
		}
	},
	validate: function(event) {
		var sel_product_id = $RF(this.form, 'add_product_id');
		if (sel_product_id == null) {
			alert('Please select a quantity to continue.');
			Event.stop(event);
		}else{
			var valueOf = sel_product_id.indexOf("-CQ-");
			var customQtyPlain = "Enter Qty.";
			var customQtyPrint = "Enter Qty.";
			
			if(document.getElementById("custom_qty_plain")!=null){
				 customQtyPlain = document.getElementById("custom_qty_plain").value;
			}
			if(document.getElementById("custom_qty_print")!=null){
				 customQtyPrint = document.getElementById("custom_qty_print").value;
			}
			if(valueOf!=-1){
				if(customQtyPlain=="Enter Qty." && customQtyPrint=="Enter Qty."){
					alert('Please select a quantity to continue.');
					Event.stop(event);
				}
			}
		}
	},
	getPrices: function() {
		var params = Form.serialize(this.form, true);
		//params['showAll']  = this.more[1].active ? 'Yes' : 'No';
		params['priceAction']   = 'All';
		params['priceTab'] = 'Print';
		delete params['description'];
		delete params['orgProductId'];
		
		new Ajax.Updater('printedPricing', '/ae/control/calculateProductPrice',
			{ method: 'get', parameters: params, onComplete: function() {
				//this.more[1].setup();
				this.custom[1].setup();
			}.bind(this)});
	},
	trackClick: function(i) {
		if (i == 0) {
			GoogleAnalytics.trackEvent('Product Page', 'Pricing', 'Plain');
		} else {
			GoogleAnalytics.trackEvent('Product Page', 'Pricing', 'Printed');
		}
	}
}

Pricing.Custom = Class.create();
Pricing.Custom.prototype = {
	initialize: function(form, tab) {
		this.form = $(form);
		this.tab  = $(tab);
		this.kind = (this.tab.id == 'plain') ? 'plain' : 'print';
		this.min  = 500;
		this.max  = 100000;
		this.has_digital = false;
		this.setup();
	},
	setup: function() {
		var pagemin = this.kind + '_custom_qty_min';
		if (typeof (window[pagemin]) != 'undefined') {
			this.min = eval(pagemin);
		} else {
			return;
		}
		
		var digital = this.kind + '_offers_digital';
		if (typeof (window[digital]) != 'undefined') {
			this.has_digital = window[digital];
		}
		
		var fieldname = 'custom_qty_' + this.kind;
		if ($(fieldname)) {
			this.field = $(fieldname);
			Event.observe(this.field, 'focus', this.activate.bindAsEventListener(this));
			Event.observe(this.field, 'blur', this.deactivate.bindAsEventListener(this));
			Event.observe(this.field, 'keyup', this.validate.bindAsEventListener(this));
			
			if (this.field.value == 'Enter Qty.') {
				this.deactivate()
			} else {
				this.activate();
				this.validate(this.field.value); 
			}
		}
		
		this.output = {
			message: this.tab.down('div.custom_qty_message'),
			price:   this.tab.down('div.custom_qty_price'),
			amount:  this.tab.down('div.custom_qty_price h3')
		}
		this.output.radio = this.output.price.down('input');
	},
	validate: function() {
		val = this.field.value.replace(/,/g, '').strip();
		if ((val == "") || (val.length <= 1)) {
			this.respond('<p>Enter any quantity or select a price below. (Multiples of ' + this.min + ')</p>');
		} else if (!val.match(/^\d*$/)) {
			this.respond('<p class="error">The quantity you entered is invalid; enter a quantity over ' + this.min + '.</p>');
		} else if ((val < this.min) && (this.kind == 'print' && this.has_digital)) {
			this.respond('<p class="error">Please select 50, 100 or 250&nbsp;below.</p>');
		} else if (val < this.min) {
			this.respond('<p class="error">Sorry, our minimum is ' + this.min + '.</p></td>');
		} else if (val > this.max) {
			this.respond('<p class="error">Looking for over 100,000? <a href="/ae/control/customerservice">Please contact us.</a></p>')
		} else if ((val % this.min) != 0) {
			this.respond('<p class="error">Sorry, multiples of ' + this.min + ' only.</p>');
		} else {
			this.calculate();
		}
	},
	calculate: function() {
		var params = Form.serialize(this.form, true);
		params['priceAction']   = 'Custom';
		params['priceTab'] = this.kind;
		delete params['description'];
		delete params['orgProductId'];
		
		new Ajax.Request('/ae/control/calculateCustomPrice',
			{ method: 'get', parameters: params, onComplete: function(request, json) {
				this.respond(request.responseText, json);
			}.bind(this)})
	},
	respond: function(response, json) {
		if (!this.output) return;
		if (typeof json == 'object') {
			this.output.price.show();
			this.output.message.hide();
			this.output.radio.checked = true;
			this.output.radio.value = json.product_id;
			this.output.amount.innerHTML = Format.dollar(json.price);
		} else {
			this.output.message.show();
			this.output.price.hide();
			this.output.message.innerHTML = response;
		}
	},
	activate: function(evet) {
		this.field.removeClassName('inactive');
		if (this.field.value == 'Enter Qty.') {
			this.field.value = '';
		}
	},
	deactivate: function(event) {
		if (this.field.value == '') {
			this.field.addClassName('inactive');
			this.field.value = 'Enter Qty.';
		}
	}
}

/*
Pricing.Highlights = Class.create();
Pricing.Highlights.prototype = {
	initialize: function(form) {
		this.form = $(form);
	},
	setup: function() {
		this.radios = [];
		
		var elements = Form.getElements(this.form);
		for (var i = 0; i < elements.length; i++) {
			var element = elements[i];
			if ((element.type == 'radio') && (element.name = 'add_product_id')) {
				this.radios.push(element);
			}
		}
		new Form.Element.RadioEventObserver(this.form, 'add_product_id', this.highlight.bindAsEventListener(this));
	},
	highlight: function(sel) {
		this.radios.each(function(el) {
			var row = el.parentNode.parentNode;
			if (el == sel) {
				row.addClassName('selected');
			} else {
				row.removeClassName('selected');
			}
		});
	}
}
*/

Pricing.More = Class.create();
Pricing.More.prototype = {
	initialize: function(tab) {
		this.tab    = $(tab);
		this.active = false;
		this.setup();
	},
	setup: function() {
		this.link = this.tab.getElementsBySelector('a.more').first();
		this.link.onclick = function() {
			this.active ? this.hide() : this.show();
			return false;
		}.bind(this);
	},
	show: function() {
		this.active = true;
		this.link.addClassName('active');
		this.tab.getElementsByClassName('hidden').each(function(el) {
			el.removeClassName('hide');
		});
	},
	hide: function() {
		this.active = false;
		this.link.removeClassName('active');
		this.tab.getElementsByClassName('hidden').each(function(el) {
			el.addClassName('hide');
		});
	}
}

/*--------------------------------------------------------------------------*/

var MatchingProduct = Class.create();
MatchingProduct.prototype = {
	initialize: function(container) {
		this.row   = $(container);
		this.min   = 50;
		this.max   = 100000;
		this.error = false;
		this.setup();
	},
	setup: function() {
		var tds    = this.row.getElementsByTagName('td');
		var input  = this.row.getElementsByTagName('input');
		this.toggle = input[0];
		this.field  = input[1];
		this.answer = tds[tds.length - 1];
		
		if (this.toggle.checked) {
			this.row.addClassName('active');
		}
		
		Event.observe(input[0], 'click', this.highlight.bind(this));
		Event.observe(input[1], 'focus', this.activate.bind(this));
		Event.observe(input[1], 'blur', this.deactivate.bind(this));
		Event.observe(input[1], 'keyup', this.validate.bind(this));
	},
	highlight: function() {
		(this.toggle.checked) ? this.row.addClassName('active') : this.row.removeClassName('active');
	},
	activate: function() {
		if (!this.toggle.checked) {
			this.toggle.checked = true;
			this.highlight();
		}
	},
	deactivate: function() {
		if (this.field.value == '' || this.error) {
			this.toggle.checked = false;
			this.field.value = '';
			this.validate();
			this.highlight();
		}
	},
	validate: function() {
		var val = this.field.value.replace(/,/g, '').strip();
		if (val == '') {
			this.respond('Enter Qty.', false);
		} else if (!val.match(/^\d*$/)) {
			this.respond('Error', true);
		} else if (val < this.min) {
			this.respond('Minimum order of ' + this.min, true);
		} else if (val > this.max) {
			this.respond('Maximum order of ' + this.max, true);
		} else if ((val % this.min) != 0) {
			this.respond('Multiples of ' + this.min + ' only', true);
		} else {
			this.calculate();
		}
	},
	calculate: function() {
		var params = {
			product_id:  this.toggle.value,
			qty_plain:   this.field.value,
			priceAction: 'Custom',
			priceTab:    'Plain',
			printType:   'Plain'
		};
		delete params['description'];
		delete params['orgProductId'];
		
		new Ajax.Request('/ae/control/calculateCustomPrice',
			{ method: 'get', parameters: params, onComplete: function(request, json) {
				if (json.message == 'SUCCESS') {
					this.respond(Format.dollar(json.price));
				} else {
					alert(json.message);
				}
			}.bind(this)})
	},
	respond: function(message, isError) {
		this.error = isError;
		this.answer.innerHTML = '<div>' + message + '</div>';
		if (isError) {
			Element.addClassName(this.answer, 'error')
		} else {
			Element.removeClassName(this.answer, 'error');
		}
	}
}

var Matching = Class.create();
Matching.prototype = {
	initialize: function(container) {
		this.container = $(container);
		this.rows = this.container.getElementsBySelector('tbody tr');
		this.rows.each(function(row) {
			new MatchingProduct(row);
		});
	}
}

/*--------------------------------------------------------------------------*/

var PlainCal = Class.create();
Object.extend(Object.extend(PlainCal.prototype, PopUp.prototype), {
	initialize: function(trigger, popup) {
		this.trigger = $(trigger);
		this.popup   = $(popup);
		this.spinner = this.popup.down('.spinner');
		this.options = { onOpen: this.setup.bind(this), onClose: this.destroy.bind(this) }
		this.start();
	},
	setup: function() {
		this.listener = this.calculateShipping.bind(this);
		this.form = this.popup.getElementsByTagName('form')[0];
		Event.observe(this.form, 'submit', this.listener);
	},
	destroy: function() {
		Event.stopObserving(this.form, 'submit', this.listener);
	},
	calculateShipping: function(event) {
		if (!this.form['postalCode'].value.match(/^\d{3,5}/)) {
			alert('Please enter a valid zip code.');			
		} else {
			this.spinner.show();
			
			var params = {
				productId: this.findProductId(),
				postalCode: this.form['postalCode'].value
			}
			var myAjax = new Ajax.Request('/ae/control/calculateShippingCost',
				{method: 'get', parameters: params, onComplete: this.showShippingCost.bind(this)});
		}
		Event.stop(event);
	},
	showShippingCost: function(request, json) {
		this.spinner.hide();
		if (json.message == 'SUCCESS') {
			this.popup.down('.ZIP').innerHTML              = ' for Zip Code ' + json.postalCode;
			this.popup.down('.GROUND').innerHTML           = Format.dollar(json.estimates.GROUND);
			this.popup.down('.THREE_DAY_SELECT').innerHTML = Format.dollar(json.estimates.THREE_DAY_SELECT);
			this.popup.down('.SECOND_DAY_AIR').innerHTML   = Format.dollar(json.estimates.SECOND_DAY_AIR);
			this.popup.down('.NEXT_DAY_AIR').innerHTML     = Format.dollar(json.estimates.NEXT_DAY_AIR);
		} else {
			alert('No estimate found for ' + this.form['postalCode'].value + '.');
		}
	},
	findProductId: function() {
		var productId = $RF('addToCart', 'add_product_id');
		if (productId == null) {
			var radios = Form.getInputs('addToCart', 'radio', 'add_product_id');
			for (var i = 0; i < radios.length; i++) {
				if (!radios[i].value.match(/CQ/i)) {
					productId = radios[1].value;
					break;
				}
			}
		}
		return productId;
	}
});

/*--------------------------------------------------------------------------*/

var PrintCal = Class.create();
Object.extend(Object.extend(PrintCal.prototype, PlainCal.prototype), {
	initialize: function(trigger, popup) {
		this.trigger = $(trigger);
		this.popup   = $(popup);
		this.spinner = this.popup.down('.spinner');
		this.options = {
			onOpen:  this.setup.bind(this),
			onClose: this.destroy.bind(this)
		}
		
		if (Prototype.Browser.WebKit) {
			this.popup.style.overflow = 'hidden';
		}
		
		this.start();
	},
	setup: function() {
		this.rush = this.isRush();

		var opts = {
			approvaldays:   this.rush ? 0 : 1,
			productiondays: this.rush ? 2 : 5,
			shippingdays:   5
		}
		
		this.calendar = new scal('calendar', this.promptUpgrade.bind(this), opts);
		this.calendar.showCalendar();
		
		this.listener = this.calculateShipping.bind(this);
		this.form = this.popup.getElementsByTagName('form')[0];
		Event.observe(this.form, 'submit', this.listener);
		new Form.Element.RadioEventObserver(this.form, 'shipping', this.updateShippingDays.bindAsEventListener(this));

		this.note = this.popup.down('p.note');
		if (this.rush) {
			this.changeLegend();
			this.note.hide();
		} else {
			this.promptUpgrade();
			this.note.show();
		}
	},
	destroy: function() {
		Event.stopObserving(this.form, 'submit', this.listener);
		this.calendar.closeCalendar();
	},
	promptUpgrade: function() {
		if (!this.rush) {
			var d = this.calendar.shippingdates[this.calendar.shippingdates.length - 1];
			for (var i = 0; i < 4; i++) {
				d = this.calendar.skipweekendbackwards(d.prev());
			}
			var note = this.popup.down('p.note');
			note.innerHTML  = 'Upgrade to Rush Production and have this order on <br />';
			note.innerHTML += d.format('mm/dd') +  ' &ndash; 3 days earlier.';
		}
	},	
	isRush: function() {
		return ($RF('addToCart', 'prodTime') == 'Rush') ? true : false;
	},
	updateShippingDays: function(el) {
		switch (el.value) {
			case 'GROUND' :
				this.calendar.shippingdays = 5;
				break;
			case 'THREE_DAY_SELECT' :
				this.calendar.shippingdays = 3;
				break;
			case 'SECOND_DAY_AIR' :
				this.calendar.shippingdays = 2;
				break;
			case 'NEXT_DAY_AIR' :
				this.calendar.shippingdays = 1;
				break;
		}
		this.calendar.refresh();
		this.promptUpgrade();
	},
	changeLegend: function() {
		var legend = this.popup.getElementsBySelector('ul.legend li');
		for(var i = 0; i < legend.length; i++) {
			if (Element.hasClassName(legend[i], 'od')) {
				Element.remove(legend[i]);
			} else if (Element.hasClassName(legend[i], 'pa')) {
				legend[i].innerHTML = '<div></div>= Order Date/Proof Ready';
			}
		}
	}
});

/*--------------------------------------------------------------------------*/

Event.onDOMReady(function() {
	if ($('colorsContainer') && $('activeColorOpt')) {
		new Effect.MoveTo('colorsContainer', {to_element: $('activeColorOpt'), duration: 0.0});
	}

	if ($('colorSelect') && $('collectionSelect')) {
		var colorFilter = new Filter('colorSelect', 'colorPulldown', 'colors', {eventCat: 'Product Page', onChange: function() {
			collectionFilter.reset();
			ecoShopFilter.reset();
		}});
		var collectionFilter = new Filter('collectionSelect', 'collectionPulldown', 'colors', {eventCat: 'Product Page', onChange: function() {
			colorFilter.reset();
			ecoShopFilter.reset();
		}});
		var ecoShopFilter = new Filter('ecoShopSelect', 'ecoShopPulldown', 'colors', {eventCat: 'Product Page', onChange: function() {
			colorFilter.reset();
			collectionFilter.reset();
		}});
	}
	
	new Tabs('tabbed', 0, { eventCat: 'Product Page' });
	new Faq('faqs');
	
	new Pricing('addToCart', 'pricingOptions');
	new Rating('submitReview', 'review', 'starRating');
	new Sample('orderSample', 'sampleOrder');
	new SendToFriend('email', 'tellFriend');
	
	if ($('matching')) {
		new Matching('matching');
	}
	
	new Zoom('enlarge', 'zoom');
	$('gallery').getElementsBySelector('a').each(function(e){
		new Zoom(e, 'zoom');
	});

	/*
	if($('calculatePlain')){
		new PlainCal('calculatePlain', 'shipCal');
	}
	
	if($('calculatePrinted')){
		new PrintCal('calculatePrinted', 'shipCalPrinted');
	}
	*/

	$$('a.help').each(function(e){
		new Tip(e, e.rel, {title : ' ', fixed: true});
	});
});
