$(document).ready(function() {

	// /////////////////////////////////////////////
	// Template Design Helpers
	// /////////////////////////////////////////////

	// Handle screen resizes
	$(window).resize( resizeScreen );
	resizeScreen();

	// Gradient on H2 tags
	$('#content h2, #content h1.pagetitle').FontEffect({
		gradient: true,
		gradientColor: "#1e2a36"
	});

	// /////////////////////////////////////////////
	// Shopping Cart AJAX
	// /////////////////////////////////////////////

	// Show cart dropdown
	/*
	$('#topnavi_cart a').hover(
		function(){
			$('#module_cart').clearQueue().slideDown('fast').show();
		},
		function(){
			$('#module_cart').clearQueue().delay(500).slideUp('fast');
		}
	);
	*/
	$('#topnavi_cart a').click(function(){
		$('#module_cart').clearQueue().slideDown('fast').show();
		$(this).blur();
		return false;
	});

	/*
	$('#module_cart').hover(
		function(){
			$(this).clearQueue().stop().css('height','auto');
		},
		function(){
			$(this).clearQueue().slideUp('fast');
		}
	);
	*/

	// Add to cart without leaving page

	ajaxFormAddProduct = function(responseText, statusText){
		// Update minicart drop-down with new minicart
		$('#module_cart').html(responseText);
		if( $('#module_cart_quantity_new').length > 0 )
			$('#module_cart_quantity').html($('#module_cart_quantity_new').html());

		// Slide down minicart drop-down
		$('#module_cart').clearQueue().stop().css('height','auto').slideDown('fast');//.delay(15000).slideUp('fast');

		// Animate an image of the product flying into the minicart drop-down
		var imageEle = $('#image');
		var imageOffset = imageEle.offset();
		var cartOffset  = $('#module_cart').offset();

		// Create temp copy of product image
		$('#content_wrapper').before('<img src="' + imageEle.attr('src') + '" id="imagetemp" style="position: absolute; top: ' + imageOffset.top + 'px; left: ' + imageOffset.left + 'px;z-index:5000;" />');

		// Animate temp copy of product image flying into minicart drop-down
		params = {
			top : cartOffset.top + 'px',
			left : cartOffset.left + 'px',
			opacity : 0.10,
			width : 64,  
			height : 64
		};

		$('#imagetemp').width(imageEle.width()).height(imageEle.height()).animate(params, 'slow', false, function () {
			$('#imagetemp').remove();
		});
	};

	// Handler for ensuring that a selection has been made for each product option, then adding via a callback to the widget
	$('form.product_form').attr('action','/index.php?route=module/cart/callback').ajaxForm({
		'beforeSubmit': function(arr, form, options){
			var form_valid = true;
    
			form.find('select').each(function(){
				if( this.selectedIndex == 0 ) {
					$(this).addClass('form_error').change(function(){
						$(this).removeClass('form_error');
					});
					form_valid = false;
				} else {
					$(this).removeClass('form_error');
				}
			});
    
			if( !form_valid ) {
				alert('Please select all product options before adding to your cart.');
				return false;
			}

			// Add jsDesigner data to form
			if( typeof(JSDESIGNER_ACTIVE) != 'undefined' && JSDESIGNER_ACTIVE ) {
				// Go through each page and ensure that if it has design elements added to it, it's been viewed
				for( var i = 0; i < JSDESIGNER_SCHEMA.pages.length; i++ ) {
					if( JSDESIGNER_SCHEMA.pages[i].viewed )
						continue;
					if( JSDESIGNER_SCHEMA.pages[i].widgets.length == 0 )
						continue;

					alert('Side '+(i+1)+' of this custom product has a design which has not been viewed. Click OK to go back and view side '+(i+1)+'.');
					jsDesignerSelectPage( i );
					return false;
				}

				// Save design and add to cart
				jsDesignerSaveDesign( $('#tab_products a.product_garment.selected').attr('product_id'), 'New Design', function( data ) {
					G_DATA = data;
					if( !data || !data.designid ) {
						return;
					}
					form.find('._jsdesignerdesignid').val( data.designid );
					form.ajaxSubmit({
						'success': ajaxFormAddProduct
					});
				});
				return false;
			}
    
			return form_valid;
		},
		'success': ajaxFormAddProduct
	});

	// /////////////////////////////////////////////
	// Frontpage Slideshow
	// /////////////////////////////////////////////

	if( document.getElementById('showcase') ) {
		// Allow tabs to be clicked
		$('#showcase .showcase_tab').click(function(){
			// Select next tab
			var tabCur = $('#showcase .showcase_tab_active');
			tabCur.removeClass('showcase_tab_active');
			var tabNext = $(this);// tabCur.parent().find('.showcase_tab:nth-child('+idx+')');

			// Advance to next tab
			tabCur.removeClass('showcase_tab_active');
			tabNext.addClass('showcase_tab_active').blur();

			// Show appropriate slide for selected tab
			$('#showcase .showcase_slide_active').removeClass('showcase_slide_active');
			$('#showcase .showcase_tab_active').each(function(){
				$( this.href.replace(/^.*#/,'#') ).addClass( 'showcase_slide_active' );
			});
    
			// Stop advancing to next tab/slide every interval
			if( sfgSlideshowTimeout != null ) {
				clearTimeout( sfgSlideshowTimeout );
				sfgSlideshowTimeout = null;
			}

			return false;
		});

		// Advance to next tab/slide every interval
		sfgSlideshowTimeout = setTimeout( sfgSlideshowNext, sfgSlideshowInterval );
	}

	// /////////////////////////////////////////////
	// OpenCart-basic
	// /////////////////////////////////////////////

	route = getURLVar('route');
	
	if (!route) {
		$('#tab_home').addClass('selected');
	} else {
		part = route.split('/');
		
		if (route == 'common/home') {
			$('#tab_home').addClass('selected');
		} else if (route == 'account/login') {
			$('#tab_login').addClass('selected');	
		} else if (part[0] == 'account') {
			$('#tab_account').addClass('selected');
		} else if (route == 'checkout/cart') {
			$('#tab_cart').addClass('selected');
		} else if (part[0] == 'checkout') {
			$('#tab_checkout').addClass('selected');
		} else {
			$('#tab_home').addClass('selected');
		} style="width:549px;height:241px;"
	}
});

function bookmark(url, title) {
	if (window.sidebar) { // firefox
    window.sidebar.addPanel(title, url, "");
	} else if(window.opera && window.print) { // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} else if(document.all) {// ie
   		window.external.AddFavorite(url, title);
	}
}

function getURLVar(urlVarName) {
	var urlHalves = String(document.location).toLowerCase().split('?');
	var urlVarValue = '';
	
	if (urlHalves[1]) {
		var urlVars = urlHalves[1].split('&');

		for (var i = 0; i <= (urlVars.length); i++) {
			if (urlVars[i]) {
				var urlVarPair = urlVars[i].split('=');
				
				if (urlVarPair[0] && urlVarPair[0] == urlVarName.toLowerCase()) {
					urlVarValue = urlVarPair[1];
				}
			}
		}
	}
	
	return urlVarValue;
} 

function resizeScreen() {
	// Resize top search bar
	var w = $('#topnavi_search_form').width();
	$('#topnavi_search_form').children().not('#filter_keyword').each(function(){
		w -= $(this).width();
	});
	$('#filter_keyword').css('width',w-70);

	// Show only the home modules we can fit
	if( $(document).width() <= 1655 )
	{
		$('.module_featured_half .module_featured_product:first-child').show();
		$('.module_featured_half .module_featured_product').not(':first-child').hide();
	}
	else
	{
		$('.module_featured_half .module_featured_product').show();
	}

	var featuredProductVertWidth = 162;
	var featuredProductVertCount = Math.floor( $('.module_featured_full .module_featured_inner').innerWidth() / featuredProductVertWidth );
	$('.module_featured_full .module_featured_product_vertical:lt('+featuredProductVertCount+')').show();
	$('.module_featured_full .module_featured_product_vertical:gt('+(featuredProductVertCount-1)+')').hide();
}

var sfgSlideshowTimeout = null;
var sfgSlideshowInterval = 9000;
function sfgSlideshowNext() {
	// Select next tab
	var tabCur = $('#showcase .showcase_tab_active');
	var tabNext = tabCur.next();
	if( tabNext.length == 0 )
		tabNext = $( tabCur.parent().children()[0] );
	else
		tabNext = tabNext;

	// Advance to next tab
	tabCur.removeClass('showcase_tab_active');
	tabNext.addClass('showcase_tab_active');

	// Show appropriate slide for selected tab
	$('#showcase .showcase_slide_active').removeClass('showcase_slide_active');
	$('#showcase .showcase_tab_active').each(function(){
		$( this.href.replace(/^.*#/,'#') ).addClass( 'showcase_slide_active' );
	});

	// Advance to next tab/slide every interval
	sfgSlideshowTimeout = setTimeout( sfgSlideshowNext, sfgSlideshowInterval );
}

$('#search input').keydown(function(e) {
	if (e.keyCode == 13) {
		moduleSearch();
	}
});

function moduleSearch() {
	url = '/index.php?route=product/search';
	
	var filter_keyword = $('#filter_keyword').attr('value')
	
	if (filter_keyword) {
		url += '&keyword=' + encodeURIComponent(filter_keyword);
	}
	
	var filter_category_id = $('#filter_category_id').attr('value');
	
	if (filter_category_id) {
		url += '&category_id=' + filter_category_id;
	}
	
	location = url;
}

$('.switcher').bind('click', function() {
	$(this).find('.option').slideToggle('fast');
});

$('.switcher').bind('mouseleave', function() {
	$(this).find('.option').slideUp('fast');
});


