// Coded by Coleman Stevenson
// cole@ImakeThe.com
// http://www.imakethe.com
//////////////////////////////
jQuery.ajaxSetup({
	cache: false
});

(function($){
	$.fn.collections = function(settings){
		
		
		$("#grid-container .productdisplay:nth-child(3n)").addClass('last');
		$("#grid-container .productdisplay:nth-child(3n+1)").addClass('c-left');
		
		
		/////////////////////////////
		// Set Top Level Variables //
		/////////////////////////////
		gridCont = $(this)
		gridItems = $(gridCont).find('.productdisplay')
		activeProducts = []
		runner = $("#static-right .details-cont .runner")
		zoomOptions = {
			zoomWidth: 435,
			zoomHeight: 422,
			xOffset: 50,
			yOffset: -100,
			position: "left",
			title: false,
			preloadPosition : 'bycss',
			hideEffect:'fadeout',
            fadeoutSpeed: 200
		};
		
		
		//////////////////////////
		// SET GLOBAL FUNCTIONS //
		//////////////////////////
		
		
		// Initiate each grid item's Click and Hover Functio
		function initGridItem(obj) {
			
			$(obj).click( function () {
				$('.productdisplay.selected').removeClass('selected');
				$(this).addClass('selected');
				$(".details-cont:hidden").fadeIn(200, function () {
					$(".about-collection-cont:visible").fadeOut(200);
				});
				//Send to Append Item Function
				 appendItem(this);
			});
			
			$(obj).hover( function () {
				$(this).find('.view-pop').stop(true,true);
				$(this).find('.view-pop').fadeIn(200);
			}, function () {
				$(this).find('.view-pop').fadeOut(200);
				
			});
		}
		
		// Determine if the obj has already been clicked by searching the activeProducts Array
		// If obj has been clicked it is shown if not send the obj to the ajax call
		function appendItem(obj) {
			var url = $(obj).attr('rel');
			var sku = $(obj).attr('sku');	
			var isInArray = $.inArray(sku, activeProducts );
			if (isInArray == -1) {
				$(obj).addClass('clicked');
				activeProducts.push(sku);
				getProductDetails(url,sku);				
			} else  {
				activeProducts.splice(isInArray,1);
				activeProducts.push(sku);
				runnerNext(sku);
				setSwatches(sku);
			}
		}
		
		
		function submitProduct() {
			///////////// SUBMIT PRODUCT FORM //////////////////
		  jQuery("form.product_form").submit(function(event) {
				  if($(this).find('.color-picker').val()) {
				  form_values = jQuery(this).serialize();
				  jQuery.post( 'index.php?ajax=true', form_values, function(returned_data) {
					  eval(returned_data);
				  });
				  wpsc_fancy_notification(this);
				  return false;
				  } else {
					  event.preventDefault();
					  alert('Please select a color before adding this item to your showroom.');
				  }
		  });
		}
		
		function wpsc_fancy_notification(parent_form){
		  if(typeof(WPSC_SHOW_FANCY_NOTIFICATION) == 'undefined'){
			WPSC_SHOW_FANCY_NOTIFICATION = true;
			}
			if((WPSC_SHOW_FANCY_NOTIFICATION == true) && (jQuery('#fancy_notification') != null)){
			var options = {
			  margin: 1 ,
			  border: 1 ,
			  padding: 1 ,
			  scroll: 1 
				};
		
			form_button_id = jQuery(parent_form).attr('id') + "_submit_button";

			var container_offset = {};

			   
			
			jQuery('#fancy_notification').css("display", 'block');
			jQuery('#loading_animation').css("display", 'block');
			jQuery('#fancy_notification_content').css("display", 'none'); 
			}
		}
		
		
	
		
		
		function showLoader() {
			$(".details-fade").fadeIn(200);
		}
		function hideLoader() {
			$(".details-fade").fadeOut(200);
		}
		function runnerNext(sku){
			var runnerPos = $(runner).position();
			var runnerChildren = $(runner).children().length
			$(runner).children().hide();
			$(".product-item[sku='" + sku + "']").fadeIn(200);
			initZoom($(".product-item[sku='" + sku + "'] .zoomer"));
		}
		function initZoom(obj) {
			$(obj).jqzoom(zoomOptions);
		}
		function initGalleryClicks(obj,sku) {
			$(obj).click( function (event) {
				showLoader();
				
				$("a.thickbox.selected").removeClass('selected');
				$(this).addClass('selected');
				event.preventDefault();
				var bigURL = $(this).attr('href');
				var imgTitle = $(this).find('img').attr('title');
				var imgID = $(this).find('img').attr('src').replace("width=30", "width=290").replace("height=30", "height=290");
				var newImage = "<a title='" + imgTitle + "' class='zoomer selected' href='" + bigURL + "'><img src='" + window.location.href + imgID + "' /></a>"
				
				$(".product-item[sku='" + sku + "'] .tab-box .image-container .image a").fadeOut(200, function() {
			
				if(!$(this).hasClass('clicked')) {
					$(this).addClass('clicked');
					$(".product-item[sku='" + sku + "'] .tab-box .image-container .image a.zoomer.selected").removeClass('selected');
					var imgComp = $(".product-item[sku='" + sku + "'] .tab-box .image-container .image").append(newImage);
				} else  {
					$(".product-item[sku='" + sku + "'] .tab-box .image-container .image a.zoomer.selected").removeClass('selected');
					$('a.zoomer[href="' + bigURL + '"]').addClass('selected').fadeIn(200);
					
				}
				$('a.zoomer[href="' + bigURL + '"]').jqzoom(zoomOptions);
				$(".product-item[sku='" + sku + "'] .tab-box .image-container .image .image-title").html("Shown in " + imgTitle)
				Cufon.set('fontFamily', 'gotham').replace('.image-title')
				$(imgComp).find('img').load( function() {
					hideLoader()
				});
				});
			});
		}
		
		
		function initColors(sku) {
			var colorSelect = $(".hidden[sku='" + sku + "']");
			var colorSwatches = $(colorSelect).find('.product-swatches');
			
			$(".product-item[sku='" + sku + "']").find('.options').append(colorSelect.html());
			Cufon.set('fontFamily', 'gotham').replace('.options .color-dropdown .item')('.options .qty')
			colorClick($(".product-item[sku='" + sku + "'] .color-dropdown"),sku);
			setSwatches(sku);
			
		}
		
		function setSwatches(sku) {
			var colorSelect = $(".hidden[sku='" + sku + "']");
			var colorSwatches = $(colorSelect).find('.product-swatches').clone();
			
			$('.right-title').empty().append(colorSwatches).find('.tooltip').colorTip();
			initSwatchClick();
			var outerW = $('.right-title').find('.swatches li')
			$('.right-title').find('.swatches').css({
				width: outerW.length * 23
			});
			$('right-title div:hidden, .right-title').fadeIn(200);
		}
		
		function openColors(obj,colorCount) {
				$(obj).css('position','absolute');
				$(obj).animate({
					height: colorCount * 15 + 'px'
				},150).addClass('open');
				;
		}
		
		function closeColors(obj) {
			$(obj).animate({
					height: '15px'
				},150, function() { $(obj).css('position','relative'); }).removeClass('open');				
		}
		
		function chooseColor(form) {
			
		}
		function colorClick(obj,sku) {
			var colorOptions = $(obj).children('.item')
			var colorCount = colorOptions.length
			var choice = $(obj).children('.item.choice')
			
			$(colorOptions).click( function() {
				var rel = $(this).attr('rel');
				var value = $(this).attr('value');
				$("input#" + rel + "").attr('value',value);
				if($(obj).hasClass('open')) {
					$(choice).html($(this).html());
					$(colorOptions).removeClass('selected');
					$(this).addClass('selected');
					
					closeColors(obj);
				} else {
					openColors(obj,colorCount);
				}
				Cufon.set('fontFamily', 'gotham').replace('.options .color-dropdown .item')
			});
		}
		//Initiate Tab Box by sending .tab-box to function
		function initTabBox(obj){
			var detailsTab = $(obj).find('.view-details');
			var viewbagTab = $(obj).find('.view-bag');
			var viewbag = $(obj).find('.box-content .image-container');
			var details = $(obj).find('.box-content .details');
			
			
			
			$(detailsTab).click( function() {
				$(detailsTab).css({
					'background-position': 'bottom'
				});
				$(viewbagTab).css({
					'background-position': 'bottom'
				});
				detailsSwitch(viewbag,details);
			});
			$(viewbagTab).click( function() {
				$(detailsTab).css({
					'background-position': 'top'
				});
				$(viewbagTab).css({
					'background-position': 'top'
				});
				viewbagSwitch(viewbag,details);
			});
		}
		
		function detailsSwitch(viewbag,details) {
			$(details,viewbag).stop(true,true);
			$(viewbag).fadeOut(200, function() {$(details).fadeIn(200)})
		}
		
		function viewbagSwitch(viewbag,details) {
			$(details,viewbag).stop(true,true);
			$(details).fadeOut(200, function() {$(viewbag).fadeIn(200)})
		}
		function hideError() {
			$(".ajax-error").fadeOut(200);
		}
		// MONSTER AJAX CALL and CALLBACK FUNCTIONS
		function getProductDetails(url,sku) {
			$.ajax({
						url: url /*+ "?ajax=true"*/,
						type: 'POST',
						beforeSend: function () {
							$('.about-collection-cont:visible').fadeOut(200);
							hideError();
							showLoader();
						},
						dataFilter: function(data,text) {
							data = $(data).find('.product-item');
							$(data).find('img').load( function() {
								hideLoader()
							});
							return data;
						},
						error: function (reqObj, text, error) {
							$(".ajax-error").html('Oh No!, There Was an Error Loading This Item.  Please Try Again').fadeIn(200);	
							hideLoader();
							//console.log(reqObj);
							//console.log(text);
							//console.log(error);
						},
						timeout: 30000,
						success: function(data,text) {ajaxSuccess(data,text,sku)},
						
						complete: function(obj,text) { 
									ajaxComplete(sku);
									submitProduct();
									
						 }
						
					})
					
		}
		// Success Callback for getproductdetails() AJAX 
		function ajaxSuccess (data, text, sku) {
			$(runner).append(data);
			
		}
		
		function ajaxComplete (sku) {
				
			runnerNext(sku);
			initColors(sku);
			Cufon.set('fontFamily', 'gotham').replace('.product-details .header')('.product-item .breadcrumb')('.product-item .addtocart')('.details')
			$(".product-item[sku='" + sku + "'] a.thickbox:first-child").addClass('clicked selected');
			initGalleryClicks($(".product-item[sku='" + sku + "'] a.thickbox"),sku);
			initTabBox($(".product-item[sku='" + sku + "'] .tab-box"));
			//console.log($(".product-item[sku='" + sku + "'] .tab-box"));
			//hideLoader();
			
			
		}

		
		/////////////////////////////////////////////////
		// Set Container to Scroll with jScroll Plugin //
		/////////////////////////////////////////////////
		$(gridCont).jScrollPane();
		
		
		////////////
		// EXTRAS //
		////////////
		$(".show-about").click( function () {
			$(".details-cont:visible, .right-title").fadeOut(200, function () {
				$(".about-collection-cont:hidden").fadeIn(200);
				})
			
		});
		function initSwatchClick() {
			
		
		
		$('.swatches li').toggle( function () {
			$(this).find('img').css({
				height: '75px',
				width: '75px',
				
			});
			$(this).find('a').css({
				height: '75px',
				width: '75px',
				'position': 'absolute',
				'z-index': '10000',
				marginTop: '-20px',
				marginLeft: '-20px'
			}).addClass('up');;
			
		}, function () {
			
			$(this).find('img').css({
				height: '20px',
				width: '20px',
				
			});	
			$(this).find('a').css({
				height: '20px',
				width: '20px',
				'position': 'relative',
				'z-index': '1800',
				marginTop: '0px',
				marginLeft: '0px'
			}).removeClass('up');			
		});
		
		}

		$(gridItems).each(function(i,e) { initGridItem(e) });
		
		return this
		
	}	
})(jQuery);
