/// <reference path="/msbuild/jquery-1.6-vsdoc.js" />

/*
*	OnSport
*	Author: Pete Rawlings, Calvin Chong @ http://www.reactive.com
*   Copyright © 2011, http://www.reactive.com
*   All rights reserved.
*/

var REACTOR = REACTOR || {};

$(function(){
	REACTOR.init();

	// General UI
	REACTOR.tabs();
	REACTOR.expcol();
	REACTOR.fancybox();
	REACTOR.highlight();
	REACTOR.accordian();
	REACTOR.selectParam();
	REACTOR.placeholders();

	// Product list filters
	REACTOR.filterHeaders();
	REACTOR.priceSlider();
	
	// Product detail
	REACTOR.productImages();
	REACTOR.productSpecs();
	
	// Checkout
	REACTOR.cartTable();
	REACTOR.paypalSlide();
	
	// Carousels
	REACTOR.bigCarousel();
	REACTOR.quotesList();
});

REACTOR.init = function() {
	
	// Style input
	$("select, input:checkbox, input:radio:not(.spec)").uniform();
	$("select, input:checkbox, input:radio:not(.spec)").live("click", function() {
		$.uniform.update();
	});

	// Style tooltips
	$('.tTip').betterTooltip();

	$('.scrollbar').scrollbar({
		arrows: false
	});


	/*
	$(function() {
  		if (window.PIE) {
     		 $('.cart_details').each(function() {
	         	 PIE.attach(this);
			});
	 	}
	});
	*/
}

/*
	Tabs
*/
REACTOR.tabs = function() {
	var $tabs = $(".tabs");
	if (!$tabs.length) return;

	$tabs.each(function() {
		var $li = $tabs.find("li");
		var $links = $tabs.find("a");
		var $content = $tabs.next().find(".tab_content");

		$tabs.delegate("a", "click", function(e) {
			e.preventDefault();
			var index = $links.index($(this));
			$li.removeClass("active").eq(index).addClass("active");
			$content.removeClass("tab_content_active").eq(index).addClass("tab_content_active");
		});
	});
}

/*
	Expand/collapse fieldset
*/
REACTOR.expcol = function() {
	var $expcolButton = $(".button_expcol");
	if (!$expcolButton.length) return;

	$expcolButton.each(function() {
		var $button = $(this);
		var $fields = $button.next();
		var defaultText = $button.text();

		$button.bind("click", function(e) {
			e.preventDefault();
			// Show/hide fields
			$fields.toggle();

			// Update button text
			if ($button.text() == defaultText) $button.text("Expand");
			else $button.text(defaultText);
		});
	});
}

/*
	Fancybox overlays
	Requires "fancybox" plugin on page
*/
REACTOR.fancybox = function() {
	var fancybox_opt = {
		overlayColor: "#000",
		padding:0,
		type: "inline",
		scrolling: "no",
		transitionIn: "none",
		transitionOut: "none",
		centerOnScroll: true
	};

	(function() {
		// Show size chart popup
		var $sizeChartLink = $(".fancy_sizechart");
		if (!$sizeChartLink.length) return;

		$sizeChartLink.bind("click", function(e) {
			e.preventDefault();
			$.fancybox($.extend({}, fancybox_opt, {
				content: "#sizeChart"
			}));
		});
	})();

	(function() {
		// Show sign in prompt for wishlist
		var $wishlistButton = $(".fancy_signin_wishlist");
		if (!$wishlistButton.length) return;

		$wishlistButton.bind("click", function(e) {
			e.preventDefault();
			$.fancybox($.extend({}, fancybox_opt, {
				content: "#signIn"
			}));
		});
	})();
}

/*
	Highlight on hover
*/
REACTOR.highlight = function() {
	var $target = $(".products_list_items, .cat_land_list");
	if (!$target.length) return;

	$target.removeClass('highlight').delegate('.product_wrap, .cat_land_list li', 'hover', function(){
		$(this).toggleClass('highlight');
		$(this).find('.not_button').toggleClass('offpage');
	});
}

/*
	Accordian
*/
REACTOR.accordian = function() {
	var $target = $(".slider, .filter_col");
	if (!$target.length) return;

	$('.slider div.slider_container').hide();
	$('.container:first').show().parent().addClass('current'); 
	$('.slider a.slider_header, .filter_col .filter_headers').toggle(function(){
		  $(this).parent().addClass('current');
		  $(this).next().slideDown(100);
	return false;	
	}, function(){
		  $(this).parent().removeClass('current');
		  $(this).next().slideUp(100);
	});
}

/*
	Select dropdowns that auto reload page on click,
	then sets itself to the new selected value
*/
REACTOR.selectParam = function() {
	var $select = $(".selectParam");
	if (!$select.length) return;

	$select.each(function() {
		var $this = $(this);
		var param = $this.data("param");
		if (param == undefined) return;

		$this.bind("change", function() {
			window.location = "?" + param + "=" + $this.val();
		});
	})
}

/*
	Product filters
*/
REACTOR.filterHeaders = function() {
	var $target = $(".filter_col .filter_headers");
	if (!$target.length) return;

	$target.parent().addClass('current');
	$target.toggle(function(){
		  $(this).parent().removeClass('current');
		  $(this).next().slideUp(100);
	return false;	
	}, function(){
		  $(this).parent().addClass('current');
		  $(this).next().slideDown(100);
	});
}

/*
	Price slider
*/
REACTOR.priceSlider = function() {
	// this is now in faceted library
}

/*
	Product image viewer and thumbnail carousel
	Requires "carouFredSel" and "Cloud Zoom" plugin on page
*/
REACTOR.productImages = function() {
	var $largeImageWrap = $(".prod_image_large");
	var $thumbImageWrap = $(".prod_image_thumbs");

	if (!$largeImageWrap.length || !$thumbImageWrap.length) return;

	var $zoomImageLink = $largeImageWrap.find(".cloud-zoom");
	var $zoomImageIns = $largeImageWrap.find(".prod_image_large_ins");

	// Hide zoom instructions by default (needed when there are no images)
	$zoomImageIns.hide();

	var $largeImage = $largeImageWrap.find("img");

	var $thumbImageList = $thumbImageWrap.find("ul");
	var $thumbImageLink = $thumbImageList.find("a");

	var opt = {
		anim: {
			fadeDuration: 600,
			fadeOpacity: 0.7
		}
	};

	// Set up carousel
	$thumbImageList.carouFredSel({
		auto: {
			play: false
		},
		scroll: {
			items: 1,
			onBefore: function($oldItems, $newItems) {
				// Before carousel scrolls, trigger click on item that will appear first in list
				var $firstLink = $newItems.eq(0).find("a");
				$firstLink.trigger("click");
			}
		},
        items: {
            visible: 4
        },
        next: {
        	button: ".thumbs_link_more"
        }
    });

    // Set up thumb clicks
    $thumbImageLink.bind("click", function(e) {
    	e.preventDefault();
    	
    	var $link = $(this);
    	var linkIndex = $thumbImageLink.index($link);

    	// Slide to thumb
    	$thumbImageList.trigger("slideTo", linkIndex);

    	// Update thumb opacity
    	selectAndShowProductImage($link);

    	// Trigger click on first thumb on page load
    }).eq(0).trigger("click");

    function selectAndShowProductImage($link) {
    	// Fade out all thumbnail links except for selected
		$thumbImageLink.not($link).animate({ opacity: opt.anim.fadeOpacity }, opt.anim.fadeDuration);
		// Fade in selected thumbnail link
		$link.animate({ opacity: 1.0 }, opt.anim.fadeDuration);

		// Get path to large image
		var imagePath = $link.attr("href");
		// Get path to zoom image
		var zoomPath = $link.data("zoom");

		// Update large image
		$largeImage.attr("src", imagePath);

		// If there's a path to zoom image
		if (zoomPath) {
			// Update zoom image
			$zoomImageLink.attr("href", zoomPath);

			// Apply awesome Cloud Zoom plugin
			$zoomImageLink.CloudZoom();

			// Show zoom instructions
			$zoomImageIns.fadeIn();
		} else {
			// Remove link to previous zoom image
			$zoomImageLink.removeAttr("href");

			// Remove Cloud Zoom mouse event catcher
			$(".mousetrap").remove();

			// Hide zoom instructions
			$zoomImageIns.fadeOut();
		}
    }
}

/*
	Styled radio buttons for product specs
*/
REACTOR.productSpecs = function() {
	var $groups = $(".prod_spec_group");
	if (!$groups.length) return;

	// Cache spec options groups
	var $groupColor = $groups.filter(".prod_spec_group_color");
	var $groupSize = $groups.filter(".prod_spec_group_size");

	// Cache DOM elements for dynamic update
	var $titlePrice = $(".prod_price");
	var $finalPrice = $(".prod_x strong");
	var $listThumbs = $(".prod_image_thumbs ul");
	var $hfColourCode = $("#hfColourCode");
	var $hfSizeCode = $("#hfSizeCode");

	// Reference inline JSON
	var prodImagesSizes = ons_prod;
	var prodPrices = ons_prod_price;

	// Last selected color
	var lastSelectedColor = "";

	// Clonable spans
	var $specColor = $("<span />", { "class": "spec_color" });
	var $specSize = $("<span />", { "class": "spec_size" });

	// For each group of spec options
	$groups.each(function() {
		var $group = $(this);

		// Get all inputs in group
		var $input = $group.find("input");

		// Is group color selection?
		var groupIsColor = $group.hasClass("prod_spec_group_color");

		$input.each(function() {
			var $i = $(this);
			var isDisabled = $i.is(":disabled");
			var isChecked = $i.is(":checked");

			// Hide input, get label, hide label, get label text
			var title = $i.hide().next().hide().text();

			// Create span
			var $span;

			if (groupIsColor) {
				$span = $specColor.clone();
				$span.css("background-color", $i.data("hex"));
			} else {
				$span = $specSize.clone();
				$span.text(title);
			}

			// Set initial states
			if (isChecked) $span.addClass("spec_selected");
			if (isDisabled) {
				$span.addClass("spec_disabled");
				title += " - Not available";
			}
			$span.attr("title", title);

			// Add span before input
			$i.before($span);
		});

		// Bind clicks to new spans
		var $spans = $group.find("span");
		$spans.bind("click", function() {
			// Update selected states
			$spans.removeClass("spec_selected");
		 	$(this).addClass("spec_selected").next(":not(:disabled)").attr("checked", "checked");

		 	// Get selected color and size
		 	var selectedColor = $groupColor.find("input:checked").data("title");
		 	var selectedSize = $groupSize.find("input:checked").data("title");
		 	var selectedCombined = selectedColor + "_" + selectedSize;

		 	// Save options to hidden fields
		 	saveToHiddenFields(selectedColor, selectedSize);

		 	// Update images based on color
		 	updateImages(selectedColor, prodImagesSizes[selectedColor]);

		 	// Update size availability based on color
		 	updateSizes(prodImagesSizes[selectedColor]);

		 	// Updating prices requires both color and size selected
		 	if (!selectedColor || !selectedSize) return;
		 	updatePrices(prodPrices[selectedCombined]);
		});
	});

	// Attempt to trigger click on first color
	$groupColor.find("span:eq(0)").trigger("click");

	function saveToHiddenFields(selectedColor, selectedSize) {
		$hfColourCode.val(selectedColor);
		$hfSizeCode.val(selectedSize);
	}

	function updateImages(selectedColor, product) {
		// If selected color is (1) undefined or (2) == last selected, don't update images
		if (!selectedColor || selectedColor == lastSelectedColor) return;

		// Save selected color
		lastSelectedColor = selectedColor;

		var images = product.images;

	 	// Create new thumb list
	 	var li = "";
	 	$(images).each(function() {
	 		var image = this;
	 		li += '<li><a href="' + this.list + '" data-zoom="' + this.zoom + '"><img src="' + this.cart + '" height="130" width="144" alt="" /></a></li>'
	 	});
	 	$listThumbs.html(li);

	 	// Recreate product images
	 	REACTOR.productImages();
	}

	function updateSizes(product) {
		// Unable to find product sizes, don't update sizes
		if (!product) return;

		var availableSizes = product.sizes;

	 	$groupSize.find("input").each(function() {
	 		var $i = $(this);
	 		// Get size title as string
	 		var title = "" + $i.data("title");
	 		// Enable/Disable size options
 			setOptionState($i, ($.inArray(title, availableSizes) > -1));
	 	});
	}

	function updatePrices(product) {
		$titlePrice.html(product.price)
	 	$finalPrice.text(product.finalPrice);
	}

	function setOptionState($input, enable) {
		// Get input title from label
		var title = $input.next().text();
		// Get span
		var $span = $input.prev();

		if (enable) {
			// Enable input
			$input.removeAttr("disabled");
			// Remove "disabled" class from span
 			$span.removeClass("spec_disabled");
		} else {
			// Disable input, uncheck it
			$input.attr("disabled", "disabled");
			$input.removeAttr("checked");
			// Add "disabled" class to span
 			$span.addClass("spec_disabled");
 			// Option not available
 			title += " - Not available";
		}

		// Update title in span
		$span.attr("title", title);
	}
}

/*
	Row highlight on hover for cart table
*/
REACTOR.cartTable = function() {
	var $cartTable = $(".cart_table");
	if (!$cartTable.length) return;

	$cartTable.find("tbody tr").hover(function() {
		$(this).addClass("hover");
	}, function() {
		$(this).removeClass("hover");
	});
}

REACTOR.paypalSlide = function(){
	var $paypalSlide = $('.payment_types');
	if(!$paypalSlide.length) return;

	$paypalSlide.each (function(){
			
		$($paypalSlide).delegate('input[type="radio"]','click',function(e){
	       var $checked = $('#payment_type_paypal').is(':checked')
	     	if($checked === true){
	             $('.paypal_wrap').slideUp(100);
	            console.log('yo');
	    	 }
	    	else {
	          $('.paypal_wrap').slideDown(100);
	       console.log('dawg');
	         }
	    });   
	});
}

/*
	Big carousel used in homepage and category landing pages
	Requires "carouFredSel" plugin on page
*/
REACTOR.bigCarousel = function() {
	var $bigCarousel = $(".big_carousel");
	if (!$bigCarousel.length) return;

	var opt = {
		anim: {
			cycleEvery: 7000,
			fadeDuration: 240,
			fadeOpacity: 0,
			syncBackground: ($bigCarousel.data("bgsync") == true)
		}
	};

	var $bigCarouselList = $bigCarousel.find("ul");
	var $bigCarouselListItems = $bigCarouselList.find("li"); // Save copy of original carousel items
	var $backgroundItems = (opt.anim.syncBackground) ? $(".bg_rotate_item") : undefined;

	// Set up carousel
	$bigCarouselList.carouFredSel({
		circular: false,
		auto: {
			pauseDuration: opt.anim.cycleEvery
		},
		scroll: {
			items: 1,
			onBefore: function($oldItems, $newItems) {
				// Fade items in/out during scroll
				var $visibleItem = $newItems.eq(0);
				$oldItems.not($visibleItem).animate({ opacity: opt.anim.fadeOpacity }, opt.anim.fadeDuration);
				$visibleItem.animate({ opacity: 1.0 }, opt.anim.fadeDuration);
				// If syncing to background, show background at index
				if (opt.anim.syncBackground) showBackgroundAt($bigCarouselListItems.index($visibleItem));
			},
			pauseOnHover: true
		},
        items: {
            visible: 1
        },
        next: {
        	button: ".big_carousel_nav_next"
        },
        prev: {
        	button: ".big_carousel_nav_prev"
        },
        pagination: {
        	container: ".big_carousel_pagn"
        }
    });

    function showBackgroundAt(index) {
    	// Fade out background items
    	$backgroundItems.animate({ opacity: 0 }, opt.anim.fadeDuration, function() {
    		// Then show background at index
    		$backgroundItems.eq(index).css({ visibility: "visible" }).stop(true).animate({ opacity:1 }, opt.anim.fadeDuration * 3);
    	});
    }
}

/*
	Quotes carousel
	Requires "carouFredSel" plugin on page
*/
REACTOR.quotesList = function() {
	var $quotesList = $(".quotes_list");
	if (!$quotesList.length) return;

	var opt = {
		anim: {
			cycleEvery: 10000
		}
	};

	// Set up carousel
	$quotesList.carouFredSel({
		circular: false,
		auto: {
			pauseDuration: opt.anim.cycleEvery
		},
		scroll: {
			items: 1,
			pauseOnHover: true
		},
        items: {
            visible: 1
        },
        pagination: {
        	container: ".quotes_list_pagn"
        }
    });
}

