/* Preloading and Rollovers */
var tnavCurrent = 0;
var showCart = false;
function rolloversInit(){
	$('.rollover').each(function(index){
		$(this).data('onsrc', rolloversGetOnSrc($(this).attr('src')));
		$(this).data('offsrc', $(this).attr('src'));

		var preloadImage = new Image();
		preloadImage.src = $(this).data('onsrc');
	});
	
	$('.rollover').hover(function(){
		$(this).attr('src', $(this).data('onsrc'));
	}, function(){
		$(this).attr('src', $(this).data('offsrc'));
	});
}

function rolloversGetOnSrc(offSrc) {
    var regEx = new RegExp(".png");
    return offSrc.replace(regEx, "-over.png");
}

function topnavInit(tnavCurrent){
	if (tnavCurrent > 0){
		$('.tnav').eq(tnavCurrent - 1).addClass('selected');
	}
	$('.tnav').hover(function(){
		$(this).addClass('over');
	}, function(){
		$(this).removeClass('over');
	});
}

function emailSignUpInit(){
	var emailTextBox = $('#masthead-signup .textbox');
	var emailSubmitBtn = $('#masthead-signup .submit');
	var defaultText = "email address";
	var errorText = "invalid email address";
 	var emailReg = /^([\w-\.\+]+@([\w-]+\.)+[\w-]{2,4})?$/;
	
	emailTextBox.focus(function(){
		if (emailTextBox.val() == defaultText){
			emailTextBox.val('');
		} else if (emailTextBox.val() == errorText){
			emailTextBox.val(emailTextBox.data('entry'));
		}
	});
	
	emailTextBox.blur(function(){
		if (emailTextBox.val() == ''){
			textboxToggleError(emailTextBox, false);
			emailTextBox.val(defaultText);
		}
	});
	
	emailSubmitBtn.click(function(){
		if ((emailTextBox.val() == '') || !emailReg.test(emailTextBox.val())){
			textboxToggleError(emailTextBox, true);
			emailTextBox.data('entry', emailTextBox.val());
			emailTextBox.val(errorText);
			return false;
		} else {
			textboxToggleError(emailTextBox, false);
			return true;
		}
	});
	
	emailTextBox.val(defaultText);
}

function cartOverlayInit(){
	$('#masthead-cart-open-btn,#masthead-cart-open').hover(function(){
		cartOverlayOpen();
	}, function(){
		cartOverlayClose();
	});
	
	$('#masthead-cart-close-btn').click(function(){
		cartOverlayClose();
	});
}

function cartOverlayOpen(){
	$('#masthead-cart-closed').hide();
	$('#masthead-cart-open').show();
	$('#masthead-cart-open-btn').addClass('over');
}

function cartOverlayClose(){
	$('#masthead-cart-closed').show();
	$('#masthead-cart-open').hide();
	$('#masthead-cart-open-btn').removeClass('over');
}

function siteSearchInit(){
	$('.search-form').each(function(){
		var searchTextBox = $('.textbox', this);
		var searchSubmitBtn = $('.submit', this);
		var defaultText = $('.textbox', this).attr('defaulttext');
		var errorText = "Enter some keywords";
		
		searchTextBox.focus(function(){
			if ((searchTextBox.val() == defaultText) || (searchTextBox.val() == errorText)){
				textboxToggleError(searchTextBox, false);
				searchTextBox.val('');
			}
		});
		
		searchTextBox.blur(function(){
			if (searchTextBox.val() == ''){
				textboxToggleError(searchTextBox, false);
				searchTextBox.val(defaultText);
			}
		});
		
		searchSubmitBtn.click(function(){
			if ((searchTextBox.val() == '') || (searchTextBox.val() == defaultText)){
				textboxToggleError(searchTextBox, true);
				searchTextBox.val(errorText);
				return false;
			} else {
				textboxToggleError(searchTextBox, false);
				return true;
			}
		});
		
		searchTextBox.val(defaultText);
	});
}

function giftCardLookupInit(){
	$('.gift-card-lookup').each(function(){
		var searchTextBox = $('.textbox', this);
		var searchSubmitBtn = $('.rollover', this);
		var defaultText = $('.textbox', this).attr('defaulttext');
		var errorText = "Please enter a valid Gift Card Number";
		
		searchTextBox.focus(function(){
			if ((searchTextBox.val() == defaultText) || (searchTextBox.val() == errorText)){
				textboxToggleError(searchTextBox, false);
				searchTextBox.val('');
			}
		});
		
		searchTextBox.blur(function(){
			if (searchTextBox.val() == ''){
				textboxToggleError(searchTextBox, false);
				searchTextBox.val(defaultText);
			}
		});
		
		searchSubmitBtn.click(function(){
			if ((searchTextBox.val() == '') || (searchTextBox.val() == defaultText)){
				textboxToggleError(searchTextBox, true);
				searchTextBox.val(errorText);
				return false;
			} else {
				textboxToggleError(searchTextBox, false);
				return true;
			}
		});
		
		searchTextBox.val(defaultText);
	});
}

function orderStatusLookupInit(){
	var searchTextBox = $('.order-status .hdrbox .textbox');
	var searchSubmitBtn = $('.order-status .hdrbox .rollover');
	var defaultText = searchTextBox.attr('defaulttext');
	var errorText = "Please enter a valid Order Number";
	
	searchTextBox.focus(function(){
		if ((searchTextBox.val() == defaultText) || (searchTextBox.val() == errorText)){
			textboxToggleError(searchTextBox, false);
			searchTextBox.val('');
		}
	});
	
	searchTextBox.blur(function(){
		if (searchTextBox.val() == ''){
			textboxToggleError(searchTextBox, false);
			searchTextBox.val(defaultText);
		}
	});
	
	searchSubmitBtn.click(function(){
		if ((searchTextBox.val() == '') || (searchTextBox.val() == defaultText)){
			textboxToggleError(searchTextBox, true);
			searchTextBox.val(errorText);
			return false;
		} else {
			textboxToggleError(searchTextBox, false);
			return true;
		}
	});
	
	searchTextBox.val(defaultText);
}

function textboxToggleError(textbox, hasError){
	var defaultColor = "#666666";
	var defaultBorderColor = "#ACACAC";
	var errorColor = "#C3487B";
	if (hasError){
		textbox.css('color', errorColor);
		textbox.css('border-color', errorColor);
	} else {
		textbox.css('color', defaultColor);
		textbox.css('border-color', defaultBorderColor);
	}
}

function gridsInit(){
	for (var numCols = 2; numCols <= 7; numCols++){
		$('.gridcol' + numCols).each(function(){
			gridsFormat($('.gridcell', this), numCols);
		});
	}
}

function gridsFormat(cells, numCols){
	var cellCount = cells.length;
	var lastRowStart = (Math.ceil(cellCount / numCols) - 1) * numCols;
	var rowHeights = new Array();
	var maxHeight = 0;
	var maxProductSummaryHeight = 0;
	var row;
	var col;
	cells.each(function(index){
		row = Math.floor(index / numCols);
		col = index % numCols;
		if ($(this).height() > maxHeight){
			maxHeight = $(this).height();
		}
		var productSummaryHeight = $(this).find("div.product-summary").height();
		var picHeight = $(this).find("a.cell-pic").height();
		if (productSummaryHeight > maxProductSummaryHeight){
			maxProductSummaryHeight = productSummaryHeight;
		}
		/* adjust heights if learn more button doesn't fit under product summary */
		if (maxHeight - (productSummaryHeight + picHeight) < 25) {
			var oldMaxHeight = maxHeight;
		    maxHeight = productSummaryHeight + picHeight + 25;
			maxProductSummaryHeight += maxHeight - oldMaxHeight;
		}
	});
	if ($.browser.msie && $.browser.version <= 7) { maxProductSummaryHeight -= 10; } 
	cells.each(function(index){
		row = Math.floor(index / numCols);
		$(this).height(maxHeight);
		$(this).find("div.product-summary a.learn-more").css('top', maxProductSummaryHeight + 'px');
		if (((index + 1) % numCols) == 0){
			$(this).css('border-right', 'none');
		}
		if (index >= lastRowStart){
			$(this).css('border-bottom', 'none');
		}
	});
}

function quickViewInit(){
	if (($('#content').hasClass('product-subcategory')) || ($('#content').hasClass('search-results'))){
		$('#content').append('<div id="quickview-overlay"></div>');
		$('#quickview-overlay').width($('.product .cell-pic IMG').width());
		$('#quickview-overlay').height($('.product .cell-pic IMG').height());
		
		$('.product .cell-pic IMG').mouseover(function(){
			$('#quickview-overlay').css('top', $(this).position().top + 'px');
			$('#quickview-overlay').css('left', $(this).position().left + 'px');
			$('#quickview-overlay').data('productID', $(this).attr('productID'));
			$('#quickview-overlay').toggle();
		});
		
		$('#quickview-overlay').mouseout(function(){
			$(this).toggle();
		});

		$('#quickview-overlay').click(function() {
		    $.fancybox({
		        padding: 0,
		        margin: 0,
		        width: 775,
		        height: 455,
		        scrolling: 'no',
		        centerOnScroll: true,
		        overlayOpacity: 0.8,
		        overlayColor: '#000000',
		        titleShow: false,
		        type: 'iframe',
		        onStart: function() { 
		            showCart = false; 
		        },
		        onClosed: function() {
		            if (showCart) {
		                // show minicart
                        if (typeof (aspdnsf.Controls.Minicart) != "undefined") {
                            var miniCart = aspdnsf.Controls.Minicart.getInstance();
                            if (miniCart) {
                                var req = Sys.WebForms.PageRequestManager.getInstance();
                                var fx = function () {
                                    miniCart.show();
                                    miniCart.set_suppressAutoHide(false);
                                    req.remove_endRequest(fx);
                                }
                                req.add_endRequest(fx);

                                miniCart.refresh();
                            }
                        }
		            }
		        },
		        href: '/showproductbare.aspx?productid=' + $(this).data('productID')
		    });
		});
	}
}

function tabsInit(){
	$('.tab-buttons').each(function(){
		var tabWidth = Math.floor($(this).width() / $('SPAN', this).length);
		var tabWidthRemainder = $(this).width() - (tabWidth * $('SPAN', this).length);
		$('SPAN', this).css('width', tabWidth);
		$('SPAN:last', this).css('width', (tabWidth + tabWidthRemainder));
	});
	$('.tab-set').each(function(){
		$('.tab-buttons SPAN', this).hover(function(){
			$(this).toggleClass('over');
	   	}, function(){
			$(this).toggleClass('over');
		});
		$('.tab-buttons SPAN', this).click(function(){
			if (!$(this).hasClass('selected')){
				$(this).siblings().removeClass('selected');
				$(this).parent().parent().children('.tab').hide();
				$(this).addClass('selected');
				$(this).parent().parent().children('.tab').eq($(this).index()).show();
			}
		});
		$('.tab-buttons SPAN:first', this).addClass('selected');
		$('.tab:first', this).show();
	});
}

function scrollbarsInit(){
	$('.scroll-pane').jScrollPane({
		verticalDragMinHeight:15,
		verticalDragMaxHeight:15
	});
}

function productVariantsInit(){
	if ($('#product-swatch-thumbs').length > 0){
		$('#product-swatch-thumbs IMG').hover(function(){
			productVariantsMouseover($(this));
		}, function(){
			productVariantsMouseout($(this));
		});
	
		$('#product-swatch-thumbs IMG').click(function(){
			productVariantsSelect($(this));
		});
	
		$('#product-color-select').change(function(){
			var variant = $('#product-swatch-thumbs IMG').eq($(this).prop('selectedIndex'));
			productVariantsMouseover(variant);
			productVariantsSelect(variant);
		});
		
		productVariantsSelect($('#product-swatch-thumbs IMG:first'));
	}
}

function productVariantsMouseover(variant){
	var pathRegEx = new RegExp('/icon/', 'gi');
	var fileTypeRegEx = new RegExp('\.png', 'gi');
	var fullSizePath = variant.attr('src').replace(pathRegEx, '/medium/');
	var fullSizePath = fullSizePath.replace(fileTypeRegEx, '.jpg');
	$('#product-swatch-large IMG').attr('src', fullSizePath);
	$('#product-swatch-name').html(variant.attr('alt'));
}

function productVariantsMouseout(variant){
	productVariantsMouseover(variant.siblings('.selected'));
}

function productVariantsSelect(variant){
	$('#product-color-select').prop('selectedIndex', variant.index());
	variant.siblings().removeClass('selected');
	variant.addClass('selected');
	
	// aspdotnetstorefront ajax 
	var select_id = document.getElementById("product-color-select");
	SetCartVariant(select_id.value);
}

function productViewerInit(){
	$('#product-view-thumbs IMG').hover(function(){
		$(this).toggleClass('over');
	}, function(){
		$(this).toggleClass('over');
	});
	
	$('#product-view-thumbs IMG').click(function(){
		$(this).siblings().removeClass('selected');
		$(this).addClass('selected');
		$('#product-view-large IMG').attr('src', $(this).attr('src'));
	});
	
	$('#product-view-thumbs IMG:first').click();
}


function productRatingsInit(){
	$('.ratings').each(function(){
		for (var i = 1; i <= 5; i++){
			$(this).append('<span></span>');
		}
		productsRatingReset($(this));
	});
	$('.ratings.active').each(function(){
		$('SPAN', this).hover(function(){
			$(this).siblings().removeClass('over');
			$(this).siblings().removeClass('selected');
			$(this).addClass('over');
			$(this).prevAll().addClass('over');
		}, function(){
			productsRatingReset($(this).parent());
		});
		
		$('SPAN', this).click(function(){
			$(this).parent().attr('rating', $(this).index() + 1);
			productsRatingReset($(this).parent());
		});
	});
}

function productsRatingReset(ratings){
	if (ratings.attr('rating')){
		var ratingValue = parseInt(ratings.attr('rating'));
		var lastStar = ratings.children().eq(ratingValue - 1);
		ratings.children().removeClass('over');
		lastStar.addClass('selected');
		lastStar.prevAll().addClass('selected');
	}
}

function ccvPopupInit(){
	$('#ccv-info-link').hover(function(){
		$('#ccv-info-popup').toggle();
	}, function(){
		$('#ccv-info-popup').toggle();
	});
}

function orderListingInit(){
	$('.order').each(function(){
		$('.order-hdr', this).hover(function(){
			$(this).toggleClass('over');
		}, function(){
			$(this).toggleClass('over');
		});
		$('.order-hdr', this).click(function(){
			$(this).toggleClass('order-expanded');
			if ($(this).hasClass('order-expanded')){
				$('.order-toggle', this).html('-');
				$(this).siblings('.order-panel').slideDown();
			} else {
				$('.order-toggle', this).html('+');
				$(this).siblings('.order-panel').slideUp();
			}
		});
	});
	$('.order:first .order-hdr').click();
}

function myAccountOptinsInit(){
	$('#account-email-optins [type="checkbox"]').click(function(){
		$('#account-email-optins [type="checkbox"]').attr('checked', false);
		$(this).attr('checked', true);
	});
}

function popupsInit(){
	$('.popup-link').click(function(e){
		e.preventDefault();
		$.fancybox({
			padding:0,
			margin:0,
			width:485,
			height:520,
			scrolling:'no',
			centerOnScroll:true,
			overlayOpacity:0.8,
			overlayColor:'#000000',
			titleShow:false,
			type:'iframe',
			href:$(this).attr('href')
		});
	});

	$('.popup-link-small').click(function(e){
		e.preventDefault();
		$.fancybox({
			padding:0,
			margin:0,
			width:440,
			height:225,
			scrolling:'no',
			centerOnScroll:true,
			overlayOpacity:0.8,
			overlayColor:'#000000',
			titleShow:false,
			type:'iframe',
			href:$(this).attr('href')
		});
	});

	$('.popup-link-wide').click(function(e){
		e.preventDefault();
		$.fancybox({
			padding:0,
			margin:0,
			width:830,
			height:525,
			scrolling:'no',
			centerOnScroll:true,
			overlayOpacity:0.8,
			overlayColor:'#000000',
			titleShow:false,
			type:'iframe',
			href:$(this).attr('href')
		});
	});

	$('.popup-close').click(function(){
		parent.$.fancybox.close();
	});
}

/* AddThis Configuration */
var addthis_header_color = "#FFFFFF"; // AddThis Popup Header Text Color
var addthis_header_background = "#C3487B"; // AddThis Popup Header Background Color

var addthis_localize = {
    share_caption: '<span style="font:bold 12px Arial,Helvetic,sans-serif;">Share Trish McEvoy</span>'
}; // AddThis Popup Header Text

var addthis_share = {
}; // AddThis URL to Share

var addthis_config = {
    data_ga_property: 'UA-7863866-1',
	data_track_clickback:true
}; // AddThis Google Analytics Integration

function errorInit()
{
    $(".fancyError").each(function() {
        $(this).attr("href", "#" + this.id);
    });
    $(".fancyError").fancybox();
    $(".fancyError").trigger('click');
}
function topicChanger() {
	$('.topic').click(function() {
		currentTopic = $(this).attr('id');
		$('#' + currentTopic).addClass('selected').siblings().removeClass('selected');
		$('#' + currentTopic + 'Content').addClass('selected').siblings().removeClass('selected');
	});
}

$(document).ready(function(){
	rolloversInit();
	topnavInit(tnavCurrent);
	emailSignUpInit();
	cartOverlayInit();
	siteSearchInit();
	quickViewInit();
	tabsInit();
	scrollbarsInit();
	productVariantsInit();
	productViewerInit();
	productRatingsInit();
	ccvPopupInit();
	orderListingInit();
	myAccountOptinsInit();
	giftCardLookupInit();
	orderStatusLookupInit();
	popupsInit();
	errorInit();
	topicChanger();
});

$(window).load(function() {
	gridsInit();
});
