var giftChoice = null  ;
(function($) {
	
	$.fn.quickview = function(options){
		var opts = $.extend({}, $.fn.quickview.defaults, options);
		
		var quickview = $(this);
		var productId = quickview.find('input[name = productId]').val();
		var JSONInventoryURL = quickview.find('input[name = JSONInventory-link]').val();
		var JSONItemPricingURL = quickview.find('input[name = JSONItemPricing-link]').val();
		var ValidSizeOptionsURL = quickview.find('input[name = ValidSizeOptions-link]').val();
		giftChoice =$("#giftChoice").val() ;
		// var form = quickview.find('form'); don't use this, ajax calls may replace form content
		
		quickview.find('#tabs').tabs(); //the product description tabs
		
		// cart form submission
		quickview.find('.add-to-cart-button').livequery('click', function(e) {
			e.preventDefault();
			var action = quickview.find('form').attr('action');
			var errorFunction = function() {
				$.fn.colorbox.resize();
				
				var sizeSelectBox = quickview.find('.attribute-size select');
				if (sizeSelectBox.length) {
					$.fn.loadFilteredSizeOptions(productId, sizeSelectBox, ValidSizeOptionsURL);
				}
				
				if(!giftChoice){
					$.fn.inventory(productId, false, quickview, JSONInventoryURL);
					
				}else{
					if($("#attrValue_1").val() !=''){
						$.fn.inventory(productId, false, quickview, getInventoryUrl($("#attrValue_1").val()));
						
					 }			
				}
			}
			var successFunction = function() {
				if ($('div.OrderItemDisplayViewShiptoAssoc').length) { // if this is the cart page
					location.reload();
				} else {
					$.fn.colorbox.close()
					$('html, body').animate({scrollTop: 0}, 'slow');
					refreshAndDisplayMiniCart(); // display the minicart on success.
				}
			};
			$.fn.submitCartForm(quickview, action, errorFunction, successFunction);
		});
		
		quickview.find('#purchase-gift-add-to-cart-button').livequery('click', function(e) {
			e.preventDefault();
			var isErrorExits = false;
			if($("#attrValue_1").val() == ''){
				$("#error_Color").show();
				quickview.find('.attributes .attribute-color').addClass("formError");
				isErrorExits = true;
			}
			if($("#attrValue_2").val() == ''){
				$("#error_Size").show();
				quickview.find('.attributes .attribute-size').addClass("formError");
				isErrorExits = true;
			}
			if(isErrorExits){
				return;
			}
			var action = quickview.find('form').attr('action');
			var errorFunction = function() {
				$.fn.colorbox.resize();
				
				var sizeSelectBox = quickview.find('.attribute-size select');
				if (sizeSelectBox.length) {
					$.fn.loadFilteredSizeOptions(productId, sizeSelectBox, ValidSizeOptionsURL);
				}
				
				if(!giftChoice){
					$.fn.inventory(productId, false, quickview, JSONInventoryURL);
					
				}else{
					if($("#attrValue_1").val() !=''){
						$.fn.inventory(productId, false, quickview, getInventoryUrl($("#attrValue_1").val()));
						
					 }			
				}
			}
			var successFunction = function() {
				if ($('div.OrderItemDisplayViewShiptoAssoc').length) { // if this is the cart page
					location.reload();
				} else {
					$.fn.colorbox.close()
					$('html, body').animate({scrollTop: 0}, 'slow');
					refreshAndDisplayMiniCart(); // display the minicart on success.
				}
			};
			$.fn.submitCartForm(quickview, action, errorFunction, successFunction);
		});
		
		// wishlist form submission
		quickview.find('.add-to-wishlist-link').livequery('click', function(e) {
			e.preventDefault();
			var action = $(this).attr('href');
			var wishLink = quickview.find('#wishlistUrl').val();
			var errorFunction = function() {
				$.fn.colorbox.resize();
				
				var sizeSelectBox = quickview.find('.attribute-size select');
				if (sizeSelectBox.length) {
					$.fn.loadFilteredSizeOptions(productId, sizeSelectBox, ValidSizeOptionsURL);
				}
				
				if(!giftChoice){
					$.fn.inventory(productId, false, quickview, JSONInventoryURL);
					
				}else{
					if($("#attrValue_1").val() !=''){
						$.fn.inventory(productId, false, quickview, getInventoryUrl($("#attrValue_1").val()));
						
					 }			
				}
			}
			var successFunction = function() {
				window.location = wishLink;
			};
			$.fn.submitCartForm(quickview, action, errorFunction, successFunction);
		});
		
		// inventory notification form submission
		quickview.find('a.unavailable-message').livequery('click', function(e) {
			e.preventDefault();
			var action = $(this).attr('href');
			$.fn.submitInventoryForm(productId, quickview, action, JSONInventoryURL); // see jquery.addtocart.js
		});
		
		// close button for the inventory notification success message
		quickview.find('.close-button').livequery('click', function(e) {
			e.preventDefault();
			$(this).parent().remove();
			$.fn.colorbox.resize();
		});
		
		// defining attribute button
		quickview.find('button.option, button.color-swatch').livequery('click', function(e) {
			e.preventDefault();
			$(this).attributeButton(); // see jquery.addtocart.js
			var iJSONInventoryURL = JSONInventoryURL;
			giftChoice =$("#giftChoice").val() ;
			if(giftChoice){
			 iJSONInventoryURL = getInventoryUrl("attrValue_1");
			}
			
			//if this is a color swatch, change the product photo and filter the size options
			if ($(this).hasClass('color-swatch')) {
				//var colorcode = $(this).val(); can't use this because IE7/IE6 does not support it
				var colorcode = $(this).find('span').text();
				var sizeSelectBox = quickview.find('.attribute-size select');
				if(!giftChoice){							
				  $.fn.togglePrice(productId, quickview, JSONItemPricingURL);
				}
				$.fn.quickview.photoswap(colorcode, quickview.find('.product-display'));
				
				if (sizeSelectBox.length) {
					var size = sizeSelectBox.find('option:selected').val();
					$.fn.filterSizeOptions(productId, colorcode, size, sizeSelectBox, ValidSizeOptionsURL);
				}
			}
			$.fn.inventory(productId, true, quickview, iJSONInventoryURL);
		});
		
		// defining attribute selection box option
		quickview.find('.attribute select').livequery('change', function(e) {
			e.preventDefault();			
			var iJSONInventoryURL = JSONInventoryURL;
			
			if(giftChoice ){
				var attrValue;
				if($(this).attr("id")){
					attrValue = $(this).attr("id");
				}
				var iJSONInventoryURL = getInventoryUrl(attrValue);
			
			  	if(attrValue == 'attrValue_2'){
				  	// retrieve itemId
				  	var itemUrl = getItemUrl();
				  	var ts= new Date().getTime();
					$("#catEntryIdDiv").load(itemUrl,{ajaxDate:ts}, function(){
					});
			  	}
			  	$.fn.inventory.showUnavailableButton(quickview,'unavailable', 'nostock');
			}
			
			$(this).attributeSelectOption(); // see jquery.addtocart.js
			
			if ($(this).hasClass('color-swatch')) {
				var sizeSelectBox = quickview.find('.attribute-size select');
				var colorcode = $(this).val();
				if(!giftChoice){
				$.fn.togglePrice(productId, quickview, JSONItemPricingURL);
				}
				//if this is a color selection and is not null, change the product photo
				if ($(this).val()) {					
					$.fn.quickview.photoswap(colorcode, quickview.find('.product-display'));
				}
				
				//if this is a color selection and multiple sizes are available, filter the size options
				if (sizeSelectBox.length) {
					var size = sizeSelectBox.find('option:selected').val();
					$.fn.filterSizeOptions(productId, colorcode, size, sizeSelectBox, ValidSizeOptionsURL);
				}
			}
			if( ( !giftChoice) || (giftChoice && attrValue=='attrValue_1') ){
				
			  $.fn.inventory(productId, true, quickview, iJSONInventoryURL);
			}
		});
		
		var sizeSelectBox = quickview.find('.attribute-size select');
		if (sizeSelectBox.length) {
			$.fn.loadFilteredSizeOptions(productId, sizeSelectBox, ValidSizeOptionsURL);
		}
		
		if(!giftChoice){
			$.fn.inventory(productId, false, quickview, JSONInventoryURL);
			
		}else{
			if($("#attrValue_1").val() !=''){
				$.fn.inventory(productId, false, quickview, getInventoryUrl($("#attrValue_1").val()));
				
			 }
	
		}
	};
	
	//THIS FUNCTION IS DUPLICATED IN jquery.productDetail.js
	//ajax refresh and display of mini cart
	var refreshAndDisplayMiniCart = function() {
	   var miniCartUrl = $("#ajaxMiniCartURL").attr('href');
	   $("#miniCart").load(miniCartUrl, function() {
		   $("#miniCart").addClass('miniCartExpanded');
			var updatedFreeShipping = "";
			var eSpotURL= $('#header').find('input[name = eSpotImportURL-link]').val();
			var targetAmount= $('#header').find('input[name = targetAmount]').val();
			var orderSubtotal= $('#unformattedOrderSubtotal').val();
			//var orderSubtotal= $('#header').find('input[name = orderSubtotalNoDiscount]').val();
			var remainingAmount = targetAmount - orderSubtotal;
			remainingAmount = "$" + remainingAmount.toFixed(2);
			eSpotURL = eSpotURL.replace('RemainingAmountReplace', remainingAmount);
			
			updatedFreeShipping = $.ajax({
					url: eSpotURL,
					dataType: 'html',
					success: function(data, textStatus, jqXHR)
					{
				 		$('#header').find('#headerEspot').html(data);
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						//alert(textStatus + errorThrown);
						//alert(XMLHttpRequest.responseText);
						return;
					}
				});	
	   });
	};
	
	var getInventoryUrl = function(attrValue){
		var iJSONInventoryURL = $("#JSONInventory-link").val();
		giftChoice =$("#giftChoice").val() ;
		if(giftChoice == 'true' ){
			if( attrValue== 'attrValue_1'){
				iJSONInventoryURL = iJSONInventoryURL +"&"+ getAttributeNVP()+"&retrieveOtherOptions=true";
			}else{
				iJSONInventoryURL = iJSONInventoryURL +"&"+ getAttributeNVP()+"&giftChoice=true";
			}
		}
		return iJSONInventoryURL;
	};
	
	var getItemUrl = function(){
		var itemURL = $("#AjaxGetItemIdURL").val();
			itemURL = itemURL +"&"+ getAttributeNVP()+"&giftChoice=true";
		return itemURL;
	};
	
	var getAttributeNVP = function(){
		var attrValue1 = $("#attrValue_1").val();
		var attrValue2 = $("#attrValue_2").val();
		var attrName1 = $("#attrName_1").val();
		var attrName2 = $("#attrName_2").val();
		
		// need to take care other stuff
		var nvp="attrName_1="+attrName1+"&"+"attrValue_1="+attrValue1;
		if(attrValue2 !=''){
			attrValue2 = encodeURIComponent(attrValue2);
		  nvp = nvp +"&"
		            +"attrName_2="+attrName2+"&"+"attrValue_2="+attrValue2;
	     }
		//console.info(nvp);
		return nvp;

	};
	
	// photo swapping for the quickview, product detail page uses different logic
	$.fn.quickview.photoswap = function(colorcode, imageContainer) {
		var image = imageContainer.find('img#' + colorcode);
		if (image.attr('complete')) { // FF returns true even if the image is not loaded
			imageContainer.find('img').css('z-index', '0');
			image.css('z-index', '1');
			image.show();
		}
	};
	
})(jQuery)

