
$(document).ready(function(){
	var onimage = new Array();
	i = 0;
 	var domain = $('body').attr('id');
	$("img.rollover").each(function() {
		onimage[i] = (domain) ? domain + "/images/" + this.name + "-over.gif" : "/images/" + this.name + "-over.gif";
		i++;
	});
	$.each(onimage,function(e) {
		$(new Image()).load(function() {
		}).attr('src',this);
	});
  	$("a.rollover").livequery(function(){
  		$(this).hover(onState,offState);
  	});
  	
	$('#addtocartlink').click(function() {
		var problem = 'no';
		var somethingselected = 'no';
		var i = 0;
		var thisform = document.addtocartform;
		$('#addtocart :input[name=selection]').each(function() {
			if (this.type == "select-one") {
				var thisitem = this.options[this.selectedIndex].value;
				var thisItemArray = thisitem.split('$');
				if (this.selectedIndex > 0 && parseInt(thisform.quantity[i].value,10) == 0) {
					alert("Please enter a quantity.");
					thisform.quantity[i].focus();
					problem = 'yes';
					return false;
				} else if (this.selectedIndex == 0 && parseInt(thisform.quantity[i].value,10) != 0) {
					alert("Please select an item.");
					this.focus();
					problem = 'yes';
					return false;
				} else if (this.selectedIndex > 0 && parseInt(thisform.quantity[i].value,10) > 0) {
					if (parseInt(thisform.quantity[i].value,10) > parseInt(thisItemArray[4],10) && parseInt(thisItemArray[4],10) > 0) {
						alert("Only " + thisItemArray[4] + " units of this item are available.");
						thisform.quantity[i].value = thisItemArray[4];
						problem = "yes"
					}
					somethingselected = 'yes';
				};
			} else if (parseInt(thisform.quantity[i].value,10) > 0) {
				var thisItemArray = this.value.split('$');
				if (parseInt(thisform.quantity[i].value,10) > parseInt(thisItemArray[4],10) && parseInt(thisItemArray[4],10) > 0) {
					alert("Only " + thisItemArray[4] + " units of this item are available.");
					thisform.quantity[i].value = thisItemArray[4];
					problem = "yes"
				}
				somethingselected = 'yes';
			};
			i++;
			});
		if (somethingselected == 'no' && problem != 'yes') {
			alert("Please select an item and enter a quantity.");
			problem = 'yes';
		};
		if (problem == 'no') {
			var newimages = ['/images/viewcart-over.gif','/images/proceed-over.gif'];
			$.each(newimages,function(e) {
				$(new Image()).load(function() {
				}).attr('src',this);
			});
			var params = $('#addtocart :input').serializeArray();
			$.post('/addtocart.lasso',params,function(data) {
				$('#detailFormContainer').html(data).css({display: 'block', border: 'none'});
			});
		};
		return false;
	});
	$('#itemadded').livequery(function(){
		var qarray = $(this).attr('alt').split(' ');
		var oldq = $('#counter').text();
		var newq = parseInt(qarray[0],10) + (oldq == '' ? 0 : parseInt(oldq.replace('(','').replace(')',''),10));
		$('#counter').html('<div class="small" style="color: #666666">(' + newq + ')<' +'/div>');
	});
 	$('.shipping').livequery('change',function() {
 		$('#shippingcheck').attr('checked',false);
 	});
 	$('.billing').livequery('change',function() {
 		$('#shippingcheck').attr('checked',false);
 	});
 	$('select[name$=country]').bind('change',function() {
 		swapInputs(this);
 	});
 	 $('#shippingcheck').bind('click',function() {
 	 	if (this.checked) {
 	 		$('input.shipping').each(function() {
	 	 		var a = $(this).attr('name').split('_');
 	 			var sourceInput = 'input[name=billing_' + a[1] + ']';
 	 			var newVal = $(sourceInput).val();
 	 			$(this).val(newVal);
 	 		});
 	 		$('select.shipping').each(function() {
	 	 		var a = $(this).attr('name').split('_');
 	 			var sourceSelect = eval('document.signIn.billing_' + a[1]);
 	 			var destinationSelect = eval('document.signIn.shipping_' + a[1]);
 	 			destinationSelect.selectedIndex = sourceSelect.selectedIndex;
 	 		});
 	 		if (document.signIn.billing_state.type != document.signIn.shipping_state.type) {
 	 			swapInputs(document.signIn.shipping_country);
 	 		}
 	 	} else {
 	 		$('input.shipping').each(function() {
 	 			$(this).val('');
 	 		});
 	 		$('select.shipping').each(function() {
	 	 		var a = $(this).attr('name').split('_');
 	 			var destinationSelect = eval('document.signIn.shipping_' + a[1]);
 	 			destinationSelect.selectedIndex = 0;
 	 		});
 	 	}
 	});
 	$('.stores a').livequery('click',function() {
 		var a = $(this).attr('href').split('?');
		var newString = '/storelocator.lasso?' + a[1] + '&keystores=' + $('#keystores').val();
		$.get(newString,function(data) {
			$('#mainstorescontent').html(data);
		});
		return false;
 	});
 	$('.stores select').removeAttr('onchange').livequery('change',function() {
 		var params = $('#stores :input').serializeArray();
		$.post('/storelocator.lasso',params,function(data) {
			$('#mainstorescontent').html(data);
		});
		return false;
 	});
 	$('.styleDropdown').bind('change',function() {
		var thisitem = this.options[this.selectedIndex];
		var thisItemArray = $(thisitem).val().split('$');
		var thisclass = $(thisitem).attr('class');
		if (thisclass == "backorder") {
			$('.info').html("<div class='small' style='margin: 10px'>This item is available for pre-order.  The expected delivery date is " + thisItemArray[5] + ".<" + "/div>").css({display: 'block', border: '1px solid black'});
		}
		return false;
	});
	$('a.backorder').bind('click',function() {
		var thisItemArray = $(this).attr('id').split(',');
		$('.info').html("<div class='small' style='margin: 10px'>This item is available for pre-order.  The expected delivery date is " + thisItemArray[5] + ".<" + "/div>").css({display: 'block', border: '1px solid black'});
		return false;
 	});
	$('div.checkout').each(function() {
		var ccList = $('input[name=ccList]').val();
		var expList = $('input[name=expList]').val();
		if (ccList != '') {
			makeList(ccList,expList);
		};
	});
	$('#shippingMessage').change(function() {
		var salestax = parseFloat($('#originalsalestax').text());
		var subtotal = parseFloat($('input[name=sum]').val()) - parseFloat($('input[name=discount]').val());
		$('input[name=test1]').val('hello');
		if (this.selectedIndex > 0) {
			$('#submitlink').unbind('click');
			var thisitem = this.options[this.selectedIndex];
			var a = $(thisitem).attr('label');
			var b = a.split(' ');
			var re = /\$/;
			var shipping = (b[b.length-1] == 'FREE') ?  0.001 : b[b.length-1].replace(re,'');
			var shippingsalestax = (salestax>0.00) ? Math.round((parseFloat(shipping)*0.08875)*100)/100 : 0.00;
			var totaltax = salestax + shippingsalestax;
			var newtotal = subtotal + parseFloat(shipping) + totaltax;
			$('#salestax').html('$' + dollarformat(totaltax));
			$('input[name=x_tax]').val(totaltax);
			$('#total').html('$' + dollarformat(newtotal));
			$('input[name=shippingMethod]').val(shipping);
		} else {
			$('#total').html('$' + dollarformat(subtotal));
			$('input[name=shippingMethod]').val('');
			$('#submitlink').click(function() {
				alert("Please select a shipping method.");
				return false;
			});
		};
	});
	$('#request').click(function() {
		var problem = "no";
		var re = / /g;
		var re1 = /:/;
		var re2 = /\*/;
		$('input[alt=required]').each(function() {
			if ($(this).attr("type") == "radio") {
				var label = $(this).attr("class");
				var temp = 'input[name=' + $(this).attr("name") + ']:checked';
				var checked = $(temp);
				if (checked.length == 0) {
					alert ("Please select a " + label);
					problem = "yes";
					$(this).focus();
					return false;
				};
			} else {
				var thisName = '#' + $(this).attr("name");
				var label = $(thisName).text().replace(re1,"").replace(re2,"");
				var test = $(this).val().replace(re,"");
				if (test == "") {
					alert ("Please enter your " + label);
					problem = "yes";
					$(this).focus();
					return false;
				};
			};
		});
		if (problem == "no") {
			$('select').each(function() {
				var thisSelect = $(this).get(0);
				if (thisSelect.selectedIndex == 0) {
					alert ("Please select a " + thisSelect.name);
					problem = "yes";
					thisSelect.focus();
					return false;
				};
			});
		};
		if (problem == "no") {
			$('input:first').val('yes');
			$('form').submit();
		};
	});
	$('input[id=shipping]').click(function() {
		var checked = $(this).attr('checked');
		$('input[type=text]').each(function() {
			var newID = '#billing_' + $(this).attr('name');
			var element = $(newID)[0];
			if( element ) {
				if (checked) {
					$(this).val($(newID).text());
				} else {
					$(this).val("");
				};
			};
		});
	});
	$('#signature').click(function() {
		var checked = $(this).attr('checked');
		var instructions = $('textarea[name=instructions]').val();
		if (checked) {
			$('textarea[name=instructions]').val(instructions.replace(new RegExp("Ship with no signature required\\n\\n","g"), ""));
		} else {
			$('textarea[name=instructions]').val('Ship with no signature required\n\n' + instructions);
		}
	});
	$('#checkout input').not('[name=deliveryDate]').focus(function() {
		if($('input[name=deliveryDate]').val() != '') {
			var newtext = populate($('textarea[name=instructions]').val(), '1Preferred Ship Date: ', $('input[name=deliveryDate]').val());
			$('#instructions').val(newtext);
		};
	});
	$('input[name=deliveryDate]').change(function() {
		var newtext = populate($('textarea[name=instructions]').val(), '1Preferred Ship Date: ', $(this).val());
		$('#instructions').val(newtext);
	});
	$('#checkout input').not('[name=cancelDate]').focus(function() {
		if($('input[name=cancelDate]').val() != '') {
			var newtext = populate($('textarea[name=instructions]').val(), '2Cancel Date: ', $('input[name=cancelDate]').val());
			$('#instructions').val(newtext);
		};
	});
	$('input[name=cancelDate]').change(function() {
		var newtext = populate($('textarea[name=instructions]').val(), '2Cancel Date: ', $(this).val());
		$('#instructions').val(newtext);
	});
	$('input[name=ship_option]').click(function() {
		var val = $(this).attr('value');
		var temp = splitter($('textarea[name=instructions]').val());
		var text = translate(temp[0]);
		var textstring = text.split('\n');
		var counter = 0;
		var length = textstring.length;
		var firstone = 'no';
		for (var i=0; i < length; i++) {
			if(textstring[counter].indexOf('3Ship as available')> -1 || textstring[counter].indexOf('3Ship order complete')> -1) {
				if(firstone == 'no') {
					textstring[counter]='3Ship ' + val;
					firstone = 'yes';
					counter++;
				} else {
					textstring.splice(counter,1);
				};
			} else {
				counter++;
			};
		};
		if(firstone == 'no') {
			textstring.unshift('3Ship ' + val);
		};
		textstring.sort();
		if(textstring[0] == ''){
			textstring.splice(0,1);
		};
		$('#instructions').val(untranslate(textstring.join('\n')) + '\n\n' + temp[1]);
	});
	$('.begin').click(function(){
		var thisform = document.giftregistrybegin;
		var problem = "no";
		var re = / /g;
		$('form[name=giftregistrybegin] input[class~=required]').each(function() {
			var test = $(this).val().replace(re,"");
			var thisinput = $(this).attr('name');
			if (test == "" || (thisinput.indexOf("password")==0&&test.length<6)) {
				alert ("Please " + $(this).attr('alt'));
				problem = "yes";
				$(this).focus();
				return false;
			};
		});
		if(problem=="no"){
			if(thisform.password.value!=thisform.passwordConfirm.value){
				alert ("The password confirmation did not match.  Please try again.");
				problem = "yes";
				thisform.passwordConfirm.value="";
				thisform.passwordConfirm.focus();
			};
		};
		if(problem=="no"){
			thisform.giftAction.value="create";
			thisform.submit();
		};
		return false;
	});
	$('.create').click(function(){
		var problem = "no";
		var re1 = / /g;
		var re2 = /\d{2}\/\d{2}\/\d{2}/;
		$('.required').each(function() {
			if (this.type == "select-one") {
				if (this.selectedIndex == 0) {
					alert ("Please select " + $(this).attr('alt'));
					problem = "yes";
					$(this).focus();
					return false;					
				};
			} else {
				var thisinput = $(this).attr('name');
				var test = $(this).val().replace(re1,"");
				if (test == "") {
					alert ("Please enter " + $(this).attr('alt'));
					problem = "yes";
					$(this).focus();
					return false;
				};
				if (thisinput.indexOf("Date")>0) {
					if (re2.exec($(this).val()) == null){
						problem = true;
						alert("Please enter the date as mm/dd/yy.");
						$(this).focus();
						return false;
					};
				};
			};
		});
		if(problem=="no"){
			document.giftregistry.giftAction.value="create";
			document.giftregistry.submit();
		};
		return false;
	});
	$('.find').click(function(){
		var problem = "no";
		var re = /[A-Za-z]{3,}/;
		var thisform = document.giftregistryfind;
		if(thisform.first_name.value.search(re)==-1&&thisform.last_name.value.search(re)==-1){
			alert("Please enter at least the first three letters of the first name or last name of the registrant.");
			problem="yes";
			thisform.first_name.focus();
		};
		if(problem=="no"){
			thisform.giftAction.value="search";
			thisform.submit();
		};
		return false;
	});		
	$('.retrieve').click(function(){
		var problem = "no";
		var re = / /g;
		var thisform = document.giftregistry;
		var test = thisform.email.value.replace(re,"");
		if(test==""){
			alert("Please enter " + thisform.email.alt);
			problem="yes";
			thisform.email.focus();
		};
		if(problem=="no"){
			document.giftregistry.giftAction.value="retrieve";
			document.giftregistry.submit();
		};
		return false;
	});		
	$('.login').click(function(){
		var problem = "no";
		var re = / /g;
		$('form[name=giftregistry] input[class~=required]').each(function() {
			var test = $(this).val().replace(re,"");
			if (test == "") {
				alert ("Please " + $(this).attr('alt'));
				problem = "yes";
				$(this).focus();
				return false;
			};
		});
		if(problem=="no"){
			document.giftregistry.giftAction.value="login";
			document.giftregistry.submit();
		};
		return false;
	});
	$('.remove').click(function(){
		if(confirm("Are you sure you want to delete this registry?")){
			document.giftregistry.giftAction.value="remove";
			document.giftregistry.submit();
		};
		return false;
	});
	$('#updateregistrybyowner').click(function(){
		var counter=1;
		$('.quantity').each(function(){
			var purchased='#purchased_'+counter;
			var quantity='#quantity_'+counter;
			if(parseInt($(quantity).val(),10)<parseInt($(purchased).text(),10)){
				$(quantity).val(parseInt($(purchased).text(),10));
			};
			$('input[name=requested]').val("yes");
			counter+=1;
		});
	});
	if($('form[name=giftregistry]').length>0){
		var counter=1;
		$('.requested').each(function(){
			var purchased='#purchased_'+counter;
			if(parseInt($(this).text(),10)<=parseInt($(purchased).text(),10)){
				var quantity='#quantity_'+counter;
				$(quantity).attr('readonly',true);
			};
			counter+=1;
		});
	};
	$('#updateregistry').click(function(){
		var counter=1;
		$('.quantity').each(function(){
			var requested='#requested_'+counter;
			var purchased='#purchased_'+counter;
			var quantity='#quantity_'+counter;
			if(parseInt($(quantity).val(),10)>parseInt($(requested).text(),10)-parseInt($(purchased).text(),10)){
				$(quantity).val(parseInt($(requested).text(),10)-parseInt($(purchased).text(),10));
			};
			$('input[name=requested]').val("yes");
			counter+=1;
		});
	});
	$('#proceed').click(function(){
		var href=$(this).attr('href');
		var counter=1;
		var zero='yes';
		if($('#counter').text()!=''){
			zero='no';
		};
		if(zero=='yes'){
			alert("Please select at least one item and click \"Update Registry\" before proceeding to checkout.");
			return false;
		};
		$('#specialmessage').css('display','block');
		$('#messagecontinue').click(function(){
			var message = $('#registrymessage').val();
			$.post('/registrymessage.lasso',{registrymessage:message});
			$('#messagecontinue').attr('href',href);
			return true;
		});
		return false;
	});
	$('#changeregistryaddress').livequery('click',function(){
		$('#newshiptoaddress').css('display','block');
		var problem = "no";
		var re1 = / /g;
		$('#sendnewaddress').click(function(){
			$('#newshiptoaddress .shipping').each(function(){
				if (this.type == "select-one") {
					if (this.selectedIndex == 0) {
						alert ("Please select the " + $(this).attr('alt'));
						problem = "yes";
						$(this).focus();
						return false;					
					};
				} else {
					var thisinput = $(this).attr('name');
					var test = $(this).val().replace(re1,"");
					if (test == "" && thisinput!="address2") {
						alert ("Please enter the " + $(this).attr('alt'));
						problem = "yes";
						$(this).focus();
						return false;
					};
				};
			});
			if(problem=="no"){
				var inputarray =  new Array();
				var counter = 0;
				$('#newshiptoaddress .shipping').each(function(){
					var todo = "input[name=x_ship_to_"+$(this).attr('name')+"]";
					if (this.type == "select-one") {
						var thisval = this.options[this.selectedIndex].value;
					} else {
						var thisval = this.value;
					};
					$(todo).val(thisval);
					inputarray[counter]=thisval;
					counter+=1;
				});
				var newstring = inputarray[0]+" "+inputarray[1]+"<br />"+inputarray[2]+"<br />";
				(inputarray[3]!="") ? newstring+=inputarray[3]+"<br />" : newstring+="";
				newstring+=inputarray[4]+", "+inputarray[5]+" "+inputarray[6]+"<br />"+inputarray[7];
				$('#shiptoaddress').html(newstring);
				if($('select[name=state]').val()=='NY' && parseFloat($('#originalsalesTax').text())==0){
					var subtotal = parseFloat($('input[name=sum]').val()) - parseFloat($('input[name=discount]').val());
					var salestax = Math.round((parseFloat(subtotal)*0.08875)*100)/100;
					if($('select[name=shippingMessage]').get(0).selectedIndex>0){
						var thisitem = $('select[name=shippingMessage]').get(0).options[$('select[name=shippingMessage]').get(0).selectedIndex];
						var a = thisitem.label;
						var b = a.split(' ');
						var re = /\$/;
						var shipping = (b[b.length-1] == 'FREE') ?  0.001 : b[b.length-1].replace(re,'');
						var shippingsalestax = Math.round((parseFloat(shipping)*0.08875)*100)/100;
					} else {
						var shippingsalestax = 0.00;
						var shipping = 0.00;
					};
					var totaltax = salestax + shippingsalestax;
					var newtotal = subtotal + parseFloat(shipping) + totaltax;
					$('#salestax').html('$' + dollarformat(totaltax));
					$('input[name=x_tax]').val(totaltax);
					$('#total').html('$' + dollarformat(newtotal));
				};
				$('#newshiptoaddress').css('display','none');
				$('input[name=altaddress]').val('yes')
			};
			return false;
		});
		$("#useregistry").click(function(){
		   if( $(this).is(':checked') ) {
				$('#newshiptoaddress').css('display','none');
				$('#shiptoaddress').html($('#registryinfo').text());
				var subtotal = parseFloat($('input[name=sum]').val()) - parseFloat($('input[name=discount]').val());
				var salestax = parseFloat($('#originalsalestax').text());
				if($('select[name=shippingMessage]').get(0).selectedIndex>0){
					var thisitem = $('select[name=shippingMessage]').get(0).options[$('select[name=shippingMessage]').get(0).selectedIndex];
					var a = thisitem.label;
					var b = a.split(' ');
					var re = /\$/;
					var shipping = (b[b.length-1] == 'FREE') ?  0.001 : b[b.length-1].replace(re,'');
				} else {
					var shipping = 0.00;
				};
				if(salestax>0){
					var shippingsalestax = Math.round((parseFloat(shipping)*0.08875)*100)/100;
				} else {
					var shippingsalestax = 0.00;
				};
				var totaltax = salestax + shippingsalestax;
				var newtotal = subtotal + parseFloat(shipping) + totaltax;
				$('#salestax').html('$' + dollarformat(totaltax));
				$('input[name=x_tax]').val(totaltax);
				$('#total').html('$' + dollarformat(newtotal));
				$('input[name=registryflag]').val('')
			};
		});

	});
	$('a.off').hover(
		function() { 
			$(this).attr('class', 'on'); 
			var message = $(this).text();
			window.status=message;
		},
		function() { 
			$(this).attr('class', 'off');
			window.status='';
		}
	);
	
	$(window).load(function() {
		$('.loader').css({'display':'none'});
		$('.slideshow').each(function() {
			var prev = $(this).parent().prev();
			var timeout = $(prev).text();
			var speed = $(prev).prev().text();
			$('div:first', this).fadeIn(speed, function() {
				$('.slideshow').cycle({
					fx:'fade',
					speed: speed,
					timeout: timeout
				});
			});
		});
	});
});


