//0,1,2,3,4,5,6,7,8,9,left,up,right,down,backspace,delete,-,tab,end,home
var validKeysForPhoneField = [47,48,49,50,51,52,53,54,55,56,57,37,38,39,40,8,46,45,9,35,36];
//left,up,right,down,backspace,delete,tab,shift,end,home
var dontJumpKeys = [37,38,39,40,8,46,9,16,35,36];

var today = new Date();
var currentAdsDisplayed = 0;
var numOfAdsTwoCol = 24; //On production we want no more than 24 ads to be shown if the column becomes too small
var loadedImage = null;
$(document).ready(function() {
	$('#orderForm').livequery(function() {
		$(this).validate({
			errorClass: 'return-message-alert',
			rules: {
				cardnumber: {
					creditcard2: function(){return $('#pymtCardType').val();}
				},
				expmo: {
					creditcarddate: function(){return $('#pymtExpYr').val();}
				}
			},
			//This custom defined function searches for a div with a specific format,
			//if it's found, the label is placed within that div. Otherwise it's simply placed after like normal.
			//The format is: formError[element ID here].
			//This is useful for expMonth / expYear field pairs that are not meant to be broken up
			errorPlacement: function(label, element) {
				if($('div#formError' + $(element).attr('id')).size() > 0) {
					//We found an error div defined for this input
					$('div#formError' + $(element).attr('id')).html(label);
				} else {
					//No error div defined, just insert after
					label.insertAfter(element);
				}
			},
			submitHandler: function() {
				submitButton = false;
				//Check if we have either a submit button, or an image submit under this form, never one of each.
				//Grab that input and use it to pass to the faceBox popup
				if($(':submit', $('#orderForm')).size() > 0)
					submitButton = $(':submit', $('#orderForm'))[0];
				else if($(':image', $('#orderForm')).size() > 0)
					submitButton = $(':image', $('#orderForm'))[0];
				if(submitButton)
					createAndShowForcedFacebox(submitButton, 'orderProcessing');
				return true;
			}
		});
	});
	
	$('.facebox-image-container').livequery(function() {
		$(this).click(function(event) {
			try {
				//Pre-load the image so we can limit the height if necessary
				var productImage = new Image();
				productImage.src = $(this).attr('href');
				
				//Don't let the full sized image display larger than 700 pixels tall
				var imageHeight = productImage.height > 700 ? 700 : productImage.height;
				
				//Calculate the percentage reduced and apply it to the width
				if(imageHeight != productImage.height) {
					var percentReduced = imageHeight / productImage.height;
					productImage.width = productImage.width * percentReduced;
				}
				
				//Assign the product height
				productImage.height = imageHeight;
				
				if(navigator.appName == 'Netscape') {
					productImage.onload = function() {
						loadedImage = this;
						setTimeout(function() {$.facebox(loadedImage);}, 500);
					};
				} else {
					$.facebox(productImage);
				}
				
				//Pass the image tag src into the facebox
				//$.facebox(productImage);
				//$.facebox("<div style='width: " + productImage.width + "; height: " + productImage.height + ";'><img src='" + productImage.src + "' width='" + productImage.width + "' height='" + productImage.height + "' /></div>");
				//$.facebox("<img src='" + $(this).attr('href') + "' height='" + imageHeight + "' />");
				
				//Stop the link from processing as normal.
				event.preventDefault();
				event.stopImmediatePropagation();
				return false;
			} catch(e) {
				return true;
			}
		});
	});
	
	// helper function to fire validation on cardNum when cardType changes
	$('#pymtCardType').livequery(function() {
		$(this).change(function(){
			$("#orderForm").validate().element('#pymtCardNumber');
		});
	});
	
	// helper function to fire validation on expMo when expYear changes
	$('#pymtExpYr').livequery(function() {
		$(this).change(function(){
			$("#orderForm").validate().element('#pymtExpMo');
		});
	});

	//If we have a captcha form we want to verify the captcha
	$('form.captchaForm').livequery(function() {
		$(this).submit(function() {
			var retVal = true;
			$.ajax({
				type: 'POST',
				url: '/_cfcs/globalFunctions.cfc?method=checkCaptchaRmt',
				async: false, //We have to make this post synchronous so... well, I don't really know why. CF was blowing up though.
				data: $(this).serialize(),
				success: function(data) {
					//After we check the captcha string
					if(data.indexOf('true') == -1) {
						$('div#captcha').load('/_shared/captchaImage.cfm');
						alert('We could not verify the captcha, please try again.');
						retVal = false;
					}
				}
			});
			return retVal;
		});
	});

	$('a#aboutCaptcha').livequery(function() {
		$(this).click(function() {
			$.facebox({ajax: '/_shared/captchaImage.cfm?captchaAction=about'});
			return false;
		});
	});
	
	//If this page has more than the maximum allowed for a two column layout, load the event
	if($('div.col1 table.bannerAd:visible').size() > numOfAdsTwoCol) {
	  	//Limit the ads displayed if the window is already too small
		currentAdsDisplayed = $('div.col1 table.bannerAd:visible').size();
		if($('div.col1').width() < 711 && currentAdsDisplayed > numOfAdsTwoCol) {
			$('div.col1 table.bannerAd:gt(' + (numOfAdsTwoCol - 1) + ')').css('display', 'none');
			currentAdsDisplayed = $('div.col1 table.bannerAd:visible').size();
		}
		
		//Bind the resize event to our window
		window.onresize = function() {
			//711px is the minimum width 3 columns can fit in.
			//If the center column goes below that drop the amount of ads shown to 24 max.
			if($('div.col1').width() < 711) {
				if(currentAdsDisplayed > numOfAdsTwoCol) {
					$('div.col1 table.bannerAd:gt(' + (numOfAdsTwoCol - 1) + ')').css('display', 'none');
					currentAdsDisplayed = $('div.col1 table.bannerAd:visible').size();
				}
			} else {
				if(currentAdsDisplayed <= numOfAdsTwoCol) {
					$('div.col1 table.bannerAd').css('display', 'block');
					currentAdsDisplayed = $('div.col1 table.bannerAd:visible').size();
				}
			}
		};
	}
	
	$('div#customerService div#subscriptions').livequery(function() {
		if($("input[name='custEmail']", this).size() > 0) {
			if($("input[name='custEmail']", this).val().length > 0)
				$("input[name='custEmail2']", this).focus();
		}
	});
	
	$('div#email-list-quick input#email-from-quick-form').livequery(function() {
		$(this).focus(function() {
			if($(this).val() == 'Email Address') {
				$(this).val('').removeClass('ghost-text');
			}
		}).blur(function() {
			if($(this).val() == '') {
				$(this).val('Email Address').addClass('ghost-text');
			}
		});
	});
	
	//On the email subscriptions page if they loaded it WITH a box checked bind some unsubscribe code for if they choose to
	$('form#email-subscriptions input.checked-on-load').change(function() {
		var subscriptionForm = $(this).closest('form');
		var listRecid = $(this).val();
		var listRow = $(this).closest('tr');
		if(!$(this).attr('checked')) {
			//Unchecked it. Display the unsubscribe details
			$('td.description', listRow).append($('div#hidden-unsubscribe-reasons').clone().attr('id', '').addClass('unsubscribe-reasons'));
			
			//Append the recid to the text inputs and radio inputs that will be checked server side
			$('td.description :input', listRow).each(function() {
				//Update the form input name
				$(this).attr('name', $(this).attr('name') + listRecid);
				
				//Update the ID for the inputs to make them unique
				$(this).attr('id', $(this).attr('id') + listRecid);
				
				//Update the ID for the label associated
				var label = $(this).next('label');
				$(label).attr('for', $(label).attr('for') + listRecid);
			});
			
			//Check the first radio option so there is always a default to go up
			$("input[type='radio']:first", listRow).attr('checked', 'checked');
			
			//Bind the 'other' field to toggle display of the other reason field / empty it out.
			$("input[type='radio']", listRow).click(function(event) {
				if($(this).val() == 'other') {
					$('input.reason-field', listRow).css('display', 'inline').val('').focus();
				} else {
					$('input.reason-field', listRow).css('display', 'none').val('');
				}
			});
		} else {
			//Checked it. Remove the unsubscribe details
			$('td.description div.unsubscribe-reasons', listRow).remove();
		}
	});

	//Any input with the 'validkeys' marker in the rel tag will trigger a key check
	$(":input[rel*='validkeys:']").keypress(function(event) {
		var code = event.keyCode ? event.keyCode : event.which;
		return (eval($(this).attr('rel').split('validkeys:')[1].split(']')[0]).indexOf(code) >= 0);
	});
	
	//On the edit account info page we want to add some scripting happiness to the phone number fields
	$(":input[rel*='moveto:']").each(function(event) {
		//If this input also has a max input size, after each keystroke find out if we've maxed out. If so, trigger the change.
		if($(this).attr('maxlength')) {
			$(this).keyup(function(event) {
				var code = event.keyCode ? event.keyCode : event.which;
				if($(this).val().length == $(this).attr('maxlength') && dontJumpKeys.toString().indexOf(code) == -1 && $(this).val().length > 0)
					$(this).blur().change();
			});
		}
		
		//When changed move to the correct field
		$(this).change(function(event) {
			$('#' + $(this).attr('rel').split('moveto:')[1].split(']')[0]).focus();
		});
	});

	//Each keystroke on the phone number fields need to automatically insert a hyphen when the length is >= 3 and there is no hyphen present
	$('input#custPhone1,input#custPhone2,input#custshipPhone').keypress(function(event) {
		var code = event.keyCode ? event.keyCode : event.which;
		return (validKeysForPhoneField.toString().indexOf(code) >= 0);
	}).keyup(function() {
		var code = event.keyCode ? event.keyCode : event.which;

		if($(this).val().length >= 3 && $(this).val().indexOf('-') == -1 && code != 8 && code != 46) {
			var tempNumber = $(this).val();
			$(this).val(formatPhoneNumber($(this).val()));
		}
	}).blur(function(event) {
		$(this).val(formatPhoneNumber($(this).val()));
	});
});

function formatPhoneNumber(number) {
	var tempNumber = number.replace(/-/g, '');
	if(number.length > 0)
		return tempNumber.substring(0,3) + '-' + tempNumber.substring(3);
	else
		return '';
}