var inventory = {};
$(document).ready(function() {

	///
	/// fix all IE6 issues.
	///
	if(IE6) {
/*		/// PNGs
		$("img[src$='.png']").each(function() {
			var src = $(this).attr('src');
			$(this).attr("src", "/img/spacer.gif").attr("style", "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "');");
		});
*/
		/// lack of CSS selector support
		$('input[type="text"]').addClass('text');
		$('input[type="password"]').addClass('password');
		$("ul#utility-nav li:first-child").addClass('first-child');
		$("div#nav ul li:last-child").addClass('last-child');
		$("div#home-feature ul li:first-child").addClass('first-child');
		$("div#home-feature ul li:last-child").addClass('last-child');
		$("table#condition-browse tr:last-child").addClass('last-child');
		$("table#products-browse tr:first-child").addClass('first-child');
		$("table#products-browse tr:last-child").addClass('last-child');

		// lack of hover for non-anchors
		$('div#article-side ul.article-products li').hover(
			function(){ $(this).addClass('hover'); },
			function(){ $(this).removeClass('hover'); }
		);
		$('div#home-feature ul li').hover(
			function(){ $(this).addClass('hover'); },
			function(){ $(this).removeClass('hover'); }
		);

	}

	///
	/// search box focus/blur effect
	///
	$('input#sq').focus(function() {
		var init = $(this).attr('init');
		if(!init || init.length == 0) {
			init = $(this).val();
			$(this).attr('init', init);
		}
		if($(this).val() == init) $(this).val('');
	}).blur(function() {
		var init = $(this).attr('init');
		if($(this).val() == '') $(this).val(init);
	});

	///
	/// search box search on keyup
	///
	$('input#sq').keyup(function(){
		smartSearch( $(this).val(), 'false' );
	});

	///
	/// hide search box when click outside
	///
	$(document).click(function(){
	    $('div#search-results:visible').hide();
	});
	$('div#search-results').click(function(e){
	    e.stopPropagation();
	});

	///
	/// resize search box and reposition quick cart on small window resize
	///
	if($('div#search-input').width() < 343) {
		size = $('div#search-input').width() - 42;
		$('input#sq').css('width', size);
	} else {
		$('input#sq').css('width', 301);
	}
	if($('div#header-content').width() < 901) {
		cartright = ($('div#header-content').width() / 2) + 12;
		$('div#qcart').css('margin-right', '-'+cartright+'px');
	} else {
		$('div#qcart').css('margin-right', '-462px');
	}
	$(window).resize(function(){
		if($('div#search-input').width() < 337) {
			size = $('div#search-input').width() - 42;
			$('input#sq').css('width', size);
		} else {
			$('input#sq').css('width', 295);
		}
		if($('div#header-content').width() < 901) {
			cartright = ($('div#header-content').width() / 2) + 12;
			$('div#qcart').css('margin-right', '-'+cartright+'px');
		} else {
			$('div#qcart').css('margin-right', '-462px');
		}
	});

	///
	/// Add "You have" for notifications if room
	///
	if($('div#taskbar-welcome').width() < 172) {
		$('span#taskbar-notify a').prepend('You have ');
	}

	///
	/// Reveal quick cart on hover
	///
	$('div#qcart').hover(showMiniCart, hideMiniCart);

	///
	/// Home page Carousels
	///
	$('div#home-banner-images ul').dynamItCarousel({
		next: '#home-banner-next',
		prev: '#home-banner-prev',
		indexnav: 'div#home-banner-controls ul',
		width: 706,
		slideshow: true,
		wraparound: true,
		slideshowtimeout: 10000
	});
	$('div#home-feature ul').dynamItCarousel({
		next: '#home-feature-next',
		prev: '#home-feature-prev',
		width: 119,
		inview: 5
	});

	///
	/// Login buttons call dialog
	///
	$('a.login').click(function() {
		dynamItLoad('/login/dialog', null, 382, 'auto', null);
		return false;
	});

	///
	/// Signup buttons call dialog
	///
	$('a.signup').live('click', function(){
		dynamItLoad('/register/register', null, 382, 'auto', null);
		return false;
	});

	///
	/// Tabbed panel functionality
	///
	$('ul.tabs>li').live('click', function() {
		var index = $(this).parent('ul.tabs').children('li').index(this);
		$content = $(this).parent().next('ul.tabs-content');
		$content.children('li').hide();
		$content.children('li').eq(index).show();
		$(this).siblings('li').removeClass('on');
		$(this).addClass('on');
		return false;
	});

	///
	/// Product detail photo change
	///
	var zoomOptions = {
		zoomWidth: 236,
		zoomHeight: 236,
		xOffset: 34,
		yOffset: 0,
		position: 'right',
		title: false
            };
	$('div#detail-thumbs ul li').live('click', function() {
		var index = $(this).parent('ul').children('li').index(this);
		$('#detail-image-view ul').children('li').hide().removeClass('on').css('display', 'none');
		$('#detail-image-view ul').children('li').show().eq(index).addClass('on').css('display', 'block').children('a').loupe();//.jqzoom(zoomOptions);
		$(this).siblings('li').removeClass('on');
		$(this).addClass('on');
		return false;
	});


	///
	/// Product detail photo zoom
	///
	$('#detail-image-view ul').children('li').children('a').loupe();//.jqzoom(zoomOptions);

	///
	/// Checkout show/hide shipping info
	///
	$('input#ship_same').click(function(){
		if($(this).is(':checked')) {
			$('.ship-hide').add('.ship-show').hide();
			$('.ship-hide').add('.ship-show').find('input').each( function() {
				if( $(this).attr('error') && $(this).attr('error').length )
					$(this).attr('verify', 'none');
			});
		} else {
			$('.ship-hide').add('.ship-show').show();
			$('.ship-hide').add('.ship-show').find('input').each( function() {
				if( $(this).attr('error') && $(this).attr('error').length )
					var ver = 'nonempty';
					if( $(this).attr('altverify') ) ver = $(this).attr('altverify');
					$(this).attr('verify', ver);
			});
		}
	});


	$('input.qty').blur( function() {
		val = parseInt( $(this).val() );
		if( isNaN(val) ) val = 0;
		$(this).val(val);
	});


//	$(".productoption select").live('change', nextVar); // does NOT work in IE
	$(".productoption select").change(nextVar);


	///
	/// recommendation check on submit
	///
	$('#recom_checkout_button').click(function() {
		if( $('.recomoptions').length ) {
			dynamItOpenDialog();
			dynamItConfDialog('One or more products must be customized before they can be added to your order. Please select the desired size, color, etc. to continue.');
			return false;
		}
		return true;
	});
});

function smartSearch(sq, save) {
	if(sq) {
		$('input#sq').val(sq);
	}
	$('div#search-results-mid').html('Searching...');
	$('div#search-results:hidden').show();
	var searchurl = '/search?sq=' + sq + '&save=' + save;
	_gaq.push(['_trackPageview', searchurl]);
	dynamItSend(searchurl);
}

function reminderDelete(id) {
	dynamItSendOnConfirm('/myaccount/reminders/delete?id='+id, 'Are you sure you wish to remove this reminder?')
}

function cartRemoveItem(sku) {
	dynamItSend('/cart/remove?sku=' + sku);
}

function cartRemoveItemR(pid, sku) {
	dynamItSend('/cart/remove?sku=' + sku + '&product=' + pid + '&recommendation=1');
}

function cartRecalculate() {
	var total = 0;
	$('.itemprice').each( function() {
		var id = $(this).attr('id');
		var price = $(this).val();
		var qty = $('#' + id + '_qty').val();

		var linetotal = (price * qty);
		total += linetotal;
		$('#' + id + '_line').html(linetotal.toFixed(2));
	});

	tax = 0;
	tax += total * $('#taxrate').val();

	shipSel = $('#shippingamount').get(0);
	shipping = 0;
	if( shipSel ) {
		shipIndex = shipSel.selectedIndex;
		if( shipIndex )
			shipping = parseFloat(shipSel.options[shipIndex].title);
		else
			shipping = parseFloat(shipSel.value);
	}

	tax += shipping * $('#taxrate_shipping').val();
	tax = Math.ceil(tax*100)/100; //round the tax up
	grandtotal = total + tax + shipping;

	$('#cart-subtotal').html('$' + total.toFixed(2));
	$('#cart-tax').html('$' + tax.toFixed(2));
	$('#cart-grandtotal').html('$' + grandtotal.toFixed(2));
}

var miniCartOn = false;
function showMiniCart() {
	if( !miniCartOn ) {
		distance = $('div#qcart-list').height() + 21 + 17;
		$('div#qcart').stop().animate({ bottom: "-"+distance+"px" }, 750);
		miniCartOn = true;
	}
}

function hideMiniCart() {
	$('div#qcart').stop().animate({ bottom: "-17px" }, 750);
	miniCartOn = false;
}

function addToCart(product, qty, source) {
	dynamItSend('/cart/add?product=' + product + '&qty=' + qty + '&source=' + source);
}

function addItemToCart(product, qty, source) {
	dynamItLoad('/cart/additem?product=' + product + '&source=' + source, null, 382, 'auto', null);
}

function loadSoleScience( ss ) {
	dynamItLoad('/solescience/view.dT/' + ss, null, 382, 'auto', null);
}

function removeReminderItem(o) {

	$(o).closest('tr').remove();

	var items = $("tbody#items").children("tr").length;
	if( items > 0 )
		$("#cartsize").val(items);
	else
		$("#cartsize").val('');

}

function reminderTurnOff(rid) {
	dynamItSend('/myaccount/reminders/turnoff?rid=' + rid);
}

function showSizing(product) {
	dynamItLoad('/products/viewsizing?product=' + product, null, 382, 'auto', null);
}

function recomOptionsSubmit() {

	if( !$(this).parent().next().length
		|| !$(this).parent().next().find('select').length
		|| $(this).parent().next().find('select').val().length) {

		if( dynamItVerify(this.form)) {
			dynamItPublish(this.form);
			$(this).closest('div.actions').replaceWith('<img src="/img/admin/ajax-loader-sm.gif" alt="" class="loading" />');
		}
	} else {
		if( $(this).parent().next().find('select').attr('name') != 'qty' )
	                 $(this).parent().next().show();
	}
}

function checkRecomCompletion() {
	return false;
//	if( $("div.actions").length == 0 ) {
//		$("#checkout_button").fadeIn('slow');
//	}
}

function changeShipping() {
	dynamItLoad('/cart/shipping/', null, 382, 'auto', null);
}


var selectedFields = {};
var lastProduct = 0;
function nextVar() {
	var pid = $(this).closest('fieldset').attr('id').split('_')[2];
	var inventorydata = inventory[pid];

	if(pid != lastProduct) selectedFields = {};
	lastProduct = pid;

	var currentField = $(this).attr('id').split('_')[2];
	var currentValue = this.options[this.selectedIndex].value;
	selectedFields[currentField] = currentValue;

	var $nextSelect = $(this).parent('div.productoption').next('div.productoption').children('select');
	if( !$nextSelect.length ) return;
	var nextField = $nextSelect.attr('id').split('_')[2];

	$nextNextSelect = $nextSelect;
	while( $nextNextSelect.length ) {
		nextNextField = $nextNextSelect.attr('id').split('_')[2];
		selectedFields[nextNextField] = null;
		$nextNextSelect.children().not("option[value='']").addClass('disabled'); //.attr('disabled', 'disabled');
		$nextNextSelect.get(0).selectedIndex = 0;
		$nextNextSelect = $nextNextSelect.parent().next('div.productoption').children('select');
	}

	var nextOptions = [];
	var matches = [];
	var isMatch;
	var inventoryId;
	for( var j in inventorydata ) {
		isMatch = true;
		for( var k in selectedFields ) {
			if( selectedFields[k] != null && inventorydata[j][k] != selectedFields[k] ) {
				isMatch = false;
				break;
			}
		}
		if( isMatch ) {
			matches.push(j);
			nextOptions.push(inventorydata[j][nextField]);
			inventoryId = j;
		}
	}

	optionsAdded = [];
	if( nextField == 'qty' ) {
		var inStock = (nextOptions[0] > 0);
		var optionHtml = '<option value="">SELECT</option>';
		if(inStock) {
			max = (nextOptions[0] > 10) ? 10 : nextOptions[0];
			for( var i = 1; i <= max; i++ ) {
				optionHtml += '<option value="' + i + '">' + i + '</option>';
			}

			$('#inventory_' + pid).val(inventoryId);
			$nextSelect.html(optionHtml);
			if( $nextSelect.hasClass('recommendationqty') ) {
				var sel = $nextSelect.get(0);
				sel.selectedIndex = 1; // this should trigger the "change" event, thus submitting the form.
			} else {
				$nextSelect.parent().show();
				$('fieldset#product_options_' + pid + ' div.submitbtn').show();
			}
			$('fieldset#product_options_' + pid + ' div.backorder').hide();
		} else {
			$nextSelect.html(optionHtml);
			$nextSelect.parent().hide();
			$('fieldset#product_options_' + pid + ' div.backorder').show();
			$('fieldset#product_options_' + pid + ' div.submitbtn').hide();
		}
	} else {
		for( var i = 0; i < nextOptions.length; i++ ) {
			$nextSelect.children("option[value='" + nextOptions[i] + "']").removeClass('disabled'); //.removeAttr('disabled');
		}
	}
}

function initVars(pid) {
	var $firstSelect = $("fieldset#product_options_" + pid).children(".productoption").eq(0).children("select");
	var firstFieldID = $firstSelect.attr('id');
	if(firstFieldID) var firstField = firstFieldID.split('_')[2];
	$firstSelect.not('#field_'+pid+'_qty').children().not("option[value='']").addClass('disabled'); //.attr('disabled', 'disabled');

	for( var j in inventory[pid] ) {
		var firstValue = inventory[pid][j][firstField];
		$firstSelect.children("option[value='" + firstValue + "']").removeClass('disabled'); //.removeAttr('disabled');
	}
}

function recommendationRemoveItem(o) {
	$("#item_" + o).remove();
}

