function parseDate(selector) {
	var date, months, currentTime;
	currentTime = new Date();
	date = selector.text().split("/", 2);
	months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];
	
	if (date[0].charAt(0) === "0") {
		date[0] = date[0].charAt(1);
	}
	if (date[1].charAt(0) === "0") {
		date[1] = date[1].charAt(1);
	}
	
	return months[parseInt(date[0], 10) - 1] + ' ' + date[1];
}


function validCardNum(cardType, cardNum) {
	var iin, parity, numlen, i, digit, total = 0;
	
	// Strip any non-digits
	cardNum = cardNum.replace(/\D/g, '');
	
	// Set length and parity
	numlen = cardNum.length;
	parity = numlen % 2;
	
	// Check the IIN and number length
	if (cardType === 'VISA') {
		// iin: 4
		iin = /^4/;
		if (!(iin.test(cardNum) && numlen === 16)) {
			return false;
		}
	} else if (cardType === 'MASTERCARD') {
		// iin: 51-55
		iin = /^5[1-5]/;
		if (!(iin.test(cardNum) && numlen === 16)) {
			return false;
		}
	} else if (cardType === 'DISCOVER') {
		// iin: 6011, 622126-622925, 644-649, 65 
		iin = /^6(?:011|2212[6-9]|221[3-9][\d]|22[2-8][\d]{2}|229[0-1][\d]|2292[0-5]|4[4-9]|5)/;
		if (!(iin.test(cardNum) && numlen === 16)) {
			return false;
		}
	} else if (cardType === 'AMEX') {
		// iin: 34, 37
		iin = /^3[47]/;
		if (!(iin.test(cardNum) && numlen === 15)) {
			return false;
		}
	}
	
	// Loop the digits and get a total
	for (i = 0; i < numlen; i++) {
		digit = parseInt(cardNum.charAt(i), 10);
		// Multiply alternate digits by 2
		if (i % 2 === parity) {
			digit *= 2;
			// If the sum is 2 digits, add them together (in effect)
			if (digit > 9) {
				digit -= 9;
			}
		}
		// Total the digits
		total += digit;
	}
	
	// If we've made it here and the total divided by 10 has no remainder, the number is valid
	if (total % 10 === 0) {
		return true;
	} else {
		return false;
	}
}

function validExp(expDate) {
	var month, year, now, nowMonth, nowYear, dateFormat;
	now = new Date();
	nowMonth = now.getMonth() + 1;
	nowYear = parseInt(now.getFullYear().toString().substr(2), 10);
	
	dateFormat = /^(0[1-9]|1[012])[\- \/.][\d]{2}$/;
	// Make sure date is in the format MM/YY with a valid month
	if (!(dateFormat.test(expDate))) {
		return false;
	}
	
	expDate = expDate.split(/[\- \/.]/);
	month = parseInt(expDate[0], 10);
	year = parseInt(expDate[1], 10);
	
	if ((nowYear > year) || (nowYear === year && nowMonth > month)) {
		return false;
	} else {
		return true;
	}
}

function validCVV(cardType, cvv) {
	if (cardType === 'VISA' && cvv.length !== 3) {
		return false;
	} else if (cardType === 'MASTERCARD' && cvv.length !== 3) {
		return false;
	} else if (cardType === 'DISCOVER' && cvv.length !== 3) {
		return false;
	} else if (cardType === 'AMEX' && cvv.length !== 4) {
		return false;
	}
	
	return true;
}

$(function () {
	// Tabs
	var randomTab = Math.floor( Math.random() * ($('#slides > ul').children('li').size()) );
	$('#slides').tabs({ fx: {opacity: 'toggle', duration:'normal'}, selected: randomTab }).tabs("rotate", 5000, true);
	$("#slides").hover(
		function () {
			$("#slides").tabs("rotate", 0, true);
		},
		function () {
			$("#slides").tabs("rotate", 5000, true);
		}
	);
	$('#news').tabs();
	$('#brands').tabs();
	$('#desctabs').tabs();
	$('#morevideos').tabs({
	    select: function(event, ui) {
	        var url = $.data(ui.tab, 'load.tabs');
	        if( url ) {
	            location.href = url;
	            return false;
	        }
	        return true;
	    },
	    cookie: {}
	});

	// Pretty Search
	$('#searchtext').addClass('pretty');
	$('#searchtext').before('<span class="left"></span>');
	$('#searchtext').after('<span class="right"></span>');
	$('.icon').prepend('<span></span>');
	
	// Video Play Button Overlay
	if ( $('.play').length ) {
		$('.play').prepend('<img src="http://img.tacklewarehouse.com/fp10/icon-playbutton.png" alt="Play" class="playbutton">');
	}
	
	// Finders on landing pages
	if ( $('.finderwide').length ) {
		$('.finderwide > div').hide();
		$('.finderwide h2').addClass('fl togglebutton findertoggle');
		$('.finderwide h2').click(function (e) {
			$('.finderwide > div').slideToggle();
			$('.finderwide h2').toggleClass('findertoggle');
		});
	}
	
	// Pop ups
	$('#menu-list a, .popup').live('click', function (e) {
		e.preventDefault();
		window.open($(this).attr('href'), '', 'left=50,top=50,width=450,height=350');
	});
	// Rod Diagram
	$('.rod-diagram').click(function (e) {
		e.preventDefault();
		window.open($(this).attr('href'), '', 'left=50,top=50,width=800,height=350');
	});
	$('#tool-video, .video').click(function (e) {
		e.preventDefault();
		window.open($(this).attr('href'), 'video', 'left=50,top=50,width=680,height=450');
	});
	
	// Description tabs height alignment
	if ($('#multiview').length && $('#multiview.rod').length === 0) {
		$('#desctabs .ui-tabs-panel').height($('#multiview').height() - $('#desctabs ul').height() - 26);
		if ( ($.browser.msie && $.browser.version.substr(0,1) <= 7) ) {
			$('#desctabs').css({'height': 'auto', 'overflow': 'visible'})
		}
	}
	
	// Big Image
	$('#product-image .zoom').hover(
		function () {
			var srcBig = $('#product-image').find('img').attr('src'), imgPat;
			imgPat = /(http:\/\/img\.tacklewarehouse\.com)\/new_product\/([\w]+)(-[\w]+)?(-[\w]+)?(-[\d]{1,2})\.(jpg|gif|png)/i;
			srcBig = srcBig.replace(imgPat, '$1/new_big/$2$3$4$5.$6');
			$('#product-image').append('<div id="big"><img src="' + srcBig + '" alt="" /></div>');
		},
		function () {
			$('#big').detach();
		}
	);

	
	// Multiview
	$('#multithumbs a').each(function (i) {
		$(this).click(function (e) {
			// Disable Link
			e.preventDefault();
			
			var swapImg, imgPat;
			swapImg = $(this).children('img').attr('src');
			imgPat = /(http:\/\/img\.tacklewarehouse\.com)\/new_thumbs\/([\w]+)(-[\w]+)?(-[\w]+)?(-[\d]{1,2})?-thumb\.(jpg|gif|png)/i;
			
			// Use the regex to modify the thumb src
			swapImg = swapImg.replace(imgPat, '$1/new_product/$2$3$4$5.$6');

			
			$('#product-image').find('img').attr('src', swapImg);
		});
	});
	
	// Style Swapper
	$('.style').each(function (i) {
		// Disable Link...or...um...change it to an anchor link.
		// e.preventDefault();
		$(this).attr('href', '#multiview');

		$(this).click(function (e) {
			var swapImg, swapThumb, imgPat;
			swapImg = $(this).children('img').attr('src');
			if ($('#lure-orderbox').length) {
				imgPat = /(http:\/\/img\.tacklewarehouse\.com)\/new_thumbs\/([\w]+)(-[\w]+)?(-[\w]+)?-thumb\.(jpg|gif|png)/i;
				swapImg = swapImg.replace(imgPat, '$1/new_product/$2$3$4-1.$5');
			} else {
				imgPat = /(http:\/\/img\.tacklewarehouse\.com)\/new_thumbs\/([\w]+)(-[\w]+)?(-[\w]+)?(-[\d]{1,2})-thumb\.(jpg|gif|png)/i;
				swapImg = swapImg.replace(imgPat, '$1/new_product/$2$3$4-1.$6');
			}
			
			$('#product-image').find('img').attr('src', swapImg);
			
			if ($('#multithumbs a').length) {
				$('#multithumbs a').each(function (j) {
					swapThumb = $('.style').eq(i).children('img').attr('src');
					if ($('#lure-orderbox').length) {
						swapThumb = swapThumb.replace(imgPat, '$1/new_thumbs/$2$3$4-' + (j + 1) + '-thumb.$5');
					} else {
						swapThumb = swapThumb.replace(imgPat, '$1/new_thumbs/$2$3$4-' + (j + 1) + '-thumb.$6');
					}
					$(this).children('img').attr('src', swapThumb);
				});
			}
			
			if ($('.blade').length) {
				$('.current').html('<strong>Lure Color:</strong><br />' + $('.lure-color').eq(i).text());
				$('.blade').html('<strong>Blade Style &amp; Color:</strong><br />' + $('.lure-blade').eq(i).text());
			} else if ($('.current').length) {
				$('.current').html('<strong>Color:</strong><br />' + $('.lure-color').eq(i).text());
			}
		});
	});
	
	// Lure Ordering Total...will not work in IE6 or IE7, performance issues in old versions
	if ( ($.browser.msie && $.browser.version.substr(0,1) > 7) || (!$.browser.msie) ) {
		$('#lure-orderbox .qty input').each(function () {
			var interval, i, x, numFields, total;
			numFields = $('#lure-orderbox .qty input').length;
			$(this).focus(function () {
				interval = setInterval(function () {
					total = 0;
					for (i = 0; i < numFields; i++) {
						x = parseInt($('#lure-orderbox .qty input').eq(i).val(), 10) ? $('#lure-orderbox .qty input').eq(i).val() : 0;
						total += parseInt(x, 10);
					}
					$('#lure-totals').text("Total selected: " + total);
				}, 100);
			}).blur(function () {
				clearInterval(interval);
			});
		});
		$('#lure-orderbox .qty input').eq(0).focus();
	}
	
	// Apparel stock updater
	$('#apparel-orderbox li select').each(function (i) {
		$(this).change(function (e) {
			var code = $(this).val();
			if ($('#apparel-orderbox .price').length) {
				$('.price').eq(i).load('/ajax/info.html .price > *', { pcode: code });
			}
			$('.available').eq(i).load('/ajax/info.html .available > *', { pcode: code });
		}).change();
	});
	
	// Handle type viewer
	$('.handle').hide();
	if ($('.subdesc').length) {
		$('.subdesc').toggleClass('hide-handle');
	}
	$('.show-handle').each(function (i) {
		var count = 0;
		$(this).click(function (e) {
			count++;
			// Disable Link
			e.preventDefault();
			// Show the hidden image
			if (count % 2 === 0) {
				$('.handle').eq(i).toggle('blind', 500).queue(function () {
					if ($('.subdesc').length) {
						$('.subdesc').eq(i).toggleClass('hide-handle');
					} else {
						$('.handle').eq(i).toggleClass('handle-border');
					}
					$(this).dequeue();
				});
			} else {
				$('.handle').eq(i).queue(function () {
					if ($('.subdesc').length) {
						$('.subdesc').eq(i).toggleClass('hide-handle');
					} else {
						$('.handle').eq(i).toggleClass('handle-border');
					}
					$(this).dequeue();
				}).toggle('blind', 500);
			}
		});
	});
	
	// Cart Item Status
	$('#backorder, #pending').hide().removeClass('fr');
	$('.itemstatus').each(function () {
		var rex = /^[\d]{2}\/[\d]{2}$/i;
		if ($(this).text() === 'Yes') {
			$(this).text('In Stock');
			$(this).addClass('stock-in');
		} else if ($(this).text() === 'Out') {
			$(this).text('Out of Stock');
			$(this).addClass('stock-out');
		} else if ($(this).text() === 'Pending') {
			$(this).html('<span class="more-info">Pending</span>');
			$(this).addClass('stock-backorder');
		} else if ( rex.test($(this).text()) ) {
			$(this).html('<span class="more-info">Backorder</span><br />' + parseDate($(this)));
			$(this).addClass('stock-backorder');
		}
	});
	// Hover boxes for statuses with more info
	$('.more-info').each(function () {
		if ($(this).text() === 'Pending') {
			$(this).hover(
				function () {
					var w = parseInt($(this).outerWidth(), 10);
					$(this).append($('#pending'));
					$('#pending').css({
						position: 'absolute',
						left: function () {
							return 0 - (parseInt($(this).outerWidth(), 10) / 2) + (w / 2);
						},
						top: function () {
							return 0 - (parseInt($(this).outerHeight(), 10) + 10);
						},
						'-moz-box-shadow': '0 0 20px #666',
						'-webkit-box-shadow': '0 0 20px #666',
						'box-shadow': '0 0 20px #666'
					}).toggle();
				},
				function () {
					$('#pending').toggle();
				}
			);
		} else if ($(this).text() === 'Backorder') {
			$(this).hover(
				function () {
					var w = parseInt($(this).outerWidth(), 10);
					$(this).append($('#backorder'));
					$('#backorder').css({
						position: 'absolute',
						left: function () {
							return 0 - (parseInt($(this).outerWidth(), 10) / 2) + (w / 2);
						},
						top: function () {
							return 0 - (parseInt($(this).outerHeight(), 10) + 10);
						},
						'-moz-box-shadow': '0 0 20px #666',
						'-webkit-box-shadow': '0 0 20px #666',
						'box-shadow': '0 0 20px #666'
					}).toggle();
				},
				function () {
					$('#backorder').toggle();
				}
			);
		}
	});
	
	// Electronic Gift Card Input Restriction
	$("#egift").keypress(function(e) {
		var controlKeys = [8, 9, 13, 35, 36, 37, 39];
		var isControlKey = controlKeys.join(",").match(new RegExp(e.which));
		if (!e.which || (49 <= e.which && e.which <= 57) || (48 == e.which && $(this).attr("value")) || isControlKey) {
			return;
		} else {
			e.preventDefault();
		}
	});
	
	// Giftcard Redeem
	if ($('#gnumb').length && $('#gc').length) {
		$('#gnumb').change(function () {
			$('#gc').attr('name', function () {
				return $('#gnumb').val() + '-CRED-REDEEM';
			});
		});
	}
	
	// Cancel Order Confirmation
	if ($('#cancelorder').length) {
		$('#cancelorder').submit(function () {
			return confirm("Are you sure you wish to cancel your order?");
		});
	}
	
	// Promo Price Free
	$('.promo-price').each(function () {
		if ($(this).text() === '$0.00') { 
			$(this).text('FREE');
		}
	});
	
	if ($('.deldate').length) {
		$('.deldate td').html(parseDate($('.deldate td')));
	}
	
	// Customer State Input Restriction
	$("#bt_state, #st_state").keypress(function(e) {
		var controlKeys = [8, 9, 13, 35, 36, 37, 39];
		var isControlKey = controlKeys.join(",").match(new RegExp(e.which));
		if (!e.which || (65 <= e.which && e.which <= 90) || (97 <= e.which && e.which <= 122) || isControlKey) {
			return;
		} else {
			e.preventDefault();
		}
	});
	
	// Credit Card Validation
	if ($('#creditcard').length) {
		var cardType, cardNum, expDate, cvv;
		
		$('#cctype').change(function () {
			cardType = $('#cctype').val().toUpperCase();
			cardNum = $('#cardnum').val();
			cvv = $('#cvv2').val();
			
			if (cardNum === '') {
				$('#numcheck').attr('class', 'input-info').html('');
			} else if (validCardNum(cardType, cardNum)) {
				$('#numcheck').attr('class', 'aok').html('');
			} else {
				$('#numcheck').attr('class', 'carderr').html('Please enter a valid card number.');
			}
			
			if (cvv === '') {
				$('#cvvcheck').attr('class', 'input-info').html('<a href="http://www.tacklewarehouse.com/cvv2.html" class="popup">What\'s This?</a>');
			} else if (validCVV(cardType, cvv)) {
				$('#cvvcheck').attr('class', 'aok').html('');
			} else {
				$('#cvvcheck').attr('class', 'carderr').html('Please enter a valid card security code.');
			}
		});
		
		$('#cardnum').change(function () {
			cardType = $('#cctype').val().toUpperCase();
			$('#cardnum').val(function (i, value) {
				return value.replace(/\D/g, '');
			});
			cardNum = $('#cardnum').val();
			
			if (cardNum === '') {
				$('#numcheck').attr('class', 'input-info').html('');
			} else if (validCardNum(cardType, cardNum)) {
				$('#numcheck').attr('class', 'aok').html('');
			} else {
				$('#numcheck').attr('class', 'carderr').html('Please enter a valid card number.');
			}
		}).change();
		
		$('#expdate').change(function () {
			expDate = $('#expdate').val();
			
			if (expDate === '') {
				$('#expcheck').attr('class', 'input-info').html('MM/YY');
			} else if (validExp(expDate)) {
				$('#expcheck').attr('class', 'aok').html('');
			} else {
				$('#expcheck').attr('class', 'carderr').html('Please enter a valid expiration date in the format MM/YY.');
			}
		}).change();
		
		$('#cvv2').change(function () {
			cardType = $('#cctype').val().toUpperCase();
			cvv = $('#cvv2').val();
			
			if (cvv === '') {
				$('#cvvcheck').attr('class', 'input-info').html('<a href="http://www.tacklewarehouse.com/cvv2.html" class="popup">What\'s This?</a>');
			} else if (validCVV(cardType, cvv)) {
				$('#cvvcheck').attr('class', 'aok').html('');
			} else {
				$('#cvvcheck').attr('class', 'carderr').html('Please enter a valid card security code.');
			}
		}).change();
		
		$('#creditcard').submit(function (e) {
			if (!(validCardNum(cardType, cardNum) && validExp(expDate) && validCVV(cardType, cvv))) {
				alert('Please correct the errors in order to proceed.');
				e.preventDefault();
			}
		});
	}
	
	//Sets height of all direct children to tallest child
	$(".equalheight").each(function () {
		var hmax = 0;
		$(this).children().each(function(){
			if ($(this).height() > hmax) { hmax = $(this).height(); }
		});
		$(this).children().each(function(){
			$(this).height(hmax);
		});
	});
	
	//Removes and sorts list of all brands and loads them into the element with ID=sortedbrands 
	if($("#allbrands").length)
	{
		var brandlist = $("#allbrands li a").get();
		var navstring = "<ul id=\"brandalpha\" class=\"clearfix\">";
		var letter;
		var charcode;
		var resultstring = "";
		var letterarray = new Array();
		var letterlength;
		var total;
		var column1; var column2; var column3;

		for(letter = 65; letter < 91; letter++)
		{
			for(i = 0; i < brandlist.length;i++)
			{
				charcode = brandlist[i].innerHTML.charCodeAt(0);
				if(charcode == letter | charcode == letter + 32)
				{
					letterarray.push([brandlist[i],brandlist[i].innerHTML]);
					brandlist.splice(i,1);
					i--;
				}
			}
			
			letterlength = letterarray.length;
			total = letterarray.length;
			column1 = Math.ceil(total/4); total -= column1;
			column2 = Math.ceil(total/3); total -= column2;
			column3 = Math.ceil(total/2); total -= column3;
			column2 += column1; column3 += column2; column1--; column2--; column3--;
			navstring += "<li><a href=\"#Brand" + String.fromCharCode(letter) + "\">" + String.fromCharCode(letter) + "<\/a><\/li>";
			resultstring += "<div id=\"Brand"+ String.fromCharCode(letter) +"\" class=\"brandtable\"><h2 class=\"h2bar\">"+ String.fromCharCode(letter) +"<\/h2><div class=\"clearfix\"><ul>";
			
			for(i = 0; i < letterlength; i++)
			{
				resultstring += "<li><a href=\"" + letterarray[i][0] + "\">" + letterarray[i][1] + "<\/a><\/li>";
				if(i == column1 | i == column2 | i == column3 )
				{
					resultstring += "<\/ul><ul>";
				}
			}
			resultstring += "<\/ul><\/div><\/div><p class=\"small text-right\"><a href=\"#wrapper\">Back to Top<\/a><\/p>";
			letterarray.length = 0;
		}
		letterlength = brandlist.length;
		total = brandlist.length;
		column1 = Math.ceil(total/4); total -= column1;
		column2 = Math.ceil(total/3); total -= column2;
		column3 = Math.ceil(total/2); total -= column3;
		column2 += column1; column3 += column2; column1--; column2--; column3--;
		navstring += "<li><a href=\"#Brandnum\">#<\/a><\/li><\/ul>";
		resultstring += "<div id=\"Brandnum\" class=\"brandtable\"><h2 class=\"h2bar\">#<\/h2><div class=\"clearfix\"><ul>";
		for(i = 0; i < brandlist.length;i++)
		{
			resultstring += "<li><a href=\"" + brandlist[i] + "\">" + brandlist[i].innerHTML + "<\/a><\/li>";
			if(i == column1 | i == column2 | i == column3 )
			{
				resultstring += "<\/ul><ul>";
			}
		}
		resultstring += "<\/ul><\/div><\/div><p class=\"small text-right\"><a href=\"#wrapper\">Back to Top<\/a><\/p>";
		
		$("#allbrands").remove();
		$("#sortedbrands").html(navstring + resultstring);
	}
});

