


var web_path='/';

/**
 * Global Onload Method
 * 
 * currently this sets up the tell a friend popup in a lightbox as well as sets up the bookmark site link.
 */
$(function() {
	
	
	// kelli doesnt want the top links to actually go anywher just to work as a flyout menu
	$('.sf-menu>li>a').each(function() {

		if (!$(this).parents('ul').hasClass('sf-menu-staff')) {
			var href = $(this).attr('href');
			var basename = href.replace(/^.*[\/\\]/g, '');
			
			// we want home to be clickable but not anything else
			if (basename != 'index.php' && basename != 'contact.php') {
				//$(this).attr('href', 'javascript:void(0);');
				
				$(this).removeAttr('href');
			    $(this).css('cursor', 'default');
			}
		}
	});
	
	
	// attach validation to the bike forms and allow it to resize fancybox when error occurs
	if ($('.bike-form').length) {
		// attach class validation
		applyValidation($('.bike-form'));
		var resized = false;
		
		// bind resize event to handle fancybox resize animation
		$('#go-fancybox-inner').bind('resize', function() {
			//get parent and resize box
			var wrap = $('#fancybox-wrap', parent.window.document);
			var inner = $('#fancybox-inner', parent.window.document);
			wrapHeight = wrap.height();
			innerHeight = inner.height();
			if (!resized) {
				 wrap.animate({
				        height: wrapHeight+44
				 }, 350);
				 inner.animate({
				        height: innerHeight+44
				 },350);

				 resized = true;
			}
		});
	}
	

	// flyout menu (superfish & supersubs) '
	// i've applyed this menu to the top-menu
	if ($('ul.sf-menu').length) {
		$('ul.sf-menu').supersubs({ 
            	minWidth:    8,   // minimum width of sub-menus in em units 
            	maxWidth:    27,   // maximum width of sub-menus in em units 
            	extraWidth:  1  
        	}).superfish({                       // one second delay on mouseout
        		speed: 		'fast', 						 // speed up the menu eh :)
				autoArrows:  false, 
            	animation:   {opacity:'show',height:'show'}  // fade-in and slide-down animation 
		});
	}
	
	
	
	// attach fancybox to the send to friend link in the footer if both exist
	if ($.fancybox) // && $('#tellAFriend').length >= 1) {
	{
		// set up defaults for fancybox
		var defaultIframeConfig = {
			'autoScale'			: false,
			'scrolling'			: 'no',
			'centerOnScroll'	: true,
			'overlayOpacity'	: 0.5,
			'overlayColor'		: '#000', 
			'showNavArrows'   	: false,
			'transitionIn'		: 'elastic',
			'transitionOut'   	: 'elastic',
			'type'				: 'iframe'
		};
		
		// set up calendar config
		calendarLightboxConf = $.extend({}, defaultIframeConfig, {
			width: '90%',
			height: '90%',
			scrolling: 'yes'
		});
		
		//console.log(calendarLightboxConf);
		
		eventLightboxConf = $.extend({}, defaultIframeConfig, {
			width: 600,
			height: 400,
			scrolling: true
		});
		
		//console.log(calendarLightboxConf);
		
		$('a[rel=event-lightbox]').fancybox(eventLightboxConf);
		
		$('a[rel=calendar-lightbox]').fancybox(calendarLightboxConf);

		
		
		$('a[rel=book-ride]').fancybox({
			'autoScale'			: false,
			'scrolling'			: 'no',
			'centerOnScroll'	: true,
			'overlayOpacity'	: 0.5,
			'overlayColor'		: '#000', 
			'showNavArrows'   : false,
			'width'           : 526,
			'height'          : 490,
			'transitionIn'		: 'elastic',
			'transitionOut'   : 'elastic',
			'type'				: 'iframe'
		});
		
		$('a[rel=request-info]').fancybox({
			'autoScale'			: false,
			'scrolling'			: 'no',
			'centerOnScroll'	: true,
			'overlayOpacity'	: 0.5,
			'overlayColor'		: '#000', 
			'showNavArrows'   : false,
			'width'           : 526,
			'height'          : 420,
			'transitionIn'		: 'elastic',
			'transitionOut'   : 'elastic',
			'type'				: 'iframe'
		});
		
		$('#tellAFriend,#emailThisItem').fancybox({
			'autoScale'			: false,
			'scrolling'			: 'no',
			'centerOnScroll'	: true,
			'overlayOpacity'	: 0.5,
			'overlayColor'		: '#000', 
			'showNavArrows'   : false,
			'width'           : 480,
			'height'          : 310,
			'transitionIn'		: 'elastic',
			'transitionOut'   : 'elastic',
			'type'				: 'iframe'
		});
	}

	$('a.store-variant-link').fancybox({
		'autoScale'			: false,
		'scrolling'			: 'vertical',
		'centerOnScroll'	: true,
		'overlayOpacity'	: 0.5,
		'overlayColor'		: '#000', 
		'showNavArrows'   : false,
		'width'           : 640,
		'height'          : 400,
		'transitionIn'		: 'elastic',
		'transitionOut'   : 'elastic',
		'type'				: 'iframe',
		'titleShow'       : false
	});

	$('a#password-recovery-link').fancybox({
		'autoScale'			: false,
		'scrolling'			: 'vertical',
		'centerOnScroll'	: true,
		'overlayOpacity'	: 0.5,
		'overlayColor'		: '#000', 
		'showNavArrows'   : false,
		'width'           : 500,
		'height'          : 250,
		'transitionIn'		: 'elastic',
		'transitionOut'   : 'elastic',
		'type'				: 'iframe',
		'titleShow'       : false
	});

	// attach jquery bookmark plugin to the bookmark site link.
	if ($('#bookmarkSite').length >= 1) {
		$('#bookmarkSite').jFav();
	}
	
	// attach a fancybox to our google map link , also apply a tipsy to the link itself.
	if ($.fancybox && $('#gmap').length >= 1) {
		$('#gmap').fancybox({
                'autoScale'             : false,
                'scrolling'             : 'no',
                'centerOnScroll'        : true,
                'overlayOpacity'        : 0.5,
                'overlayColor'          : '#000',
                'showNavArrows'         : false,
                'width'                 : 640,
                'height'                : 480,
                'transitionIn'          : 'elastic',
                'transitionOut'         : 'elastic',
                'type'                  : 'iframe'
        });

		$('#gmap-div').tipsy({
			gravity: 'n', fade: true
		});
	}

	// Init home page slider; if not on home page then do nothing.
	if ($('div#home-slideshow').length >= 1) {
		$('div#home-slideshow').cycle({
			fx: 'scrollLeft',
			timeout: 5000,
			speed: 700,
			pager: '#home-slideshow-pager',
			pagerAnchorBuilder: function(num, img){
				return '<a href="#">&nbsp;</a>';
			}
		});
	}


	// Rotating featured items!

	/*
	$('#store-featured-items').each(function()
	{
		$(this).css('height', 230);
		$(this).css('overflow', 'hidden');

		setTimeout('SlideFeaturedItemsUp()', 5000);
	});
	*/

});

function SlideFeaturedItemsUp()
{
	$('#store-featured-items').animate(
	{
		'scrollTop': '+=230px'
	}, 250);
	setTimeout('SlideFeaturedItemsDown()', 5250);
}

function SlideFeaturedItemsDown()
{
	$('#store-featured-items').animate(
	{
		'scrollTop': '-=230px'
	}, 250);
	setTimeout('SlideFeaturedItemsUp()', 5250);
}

/*This function adds the page to a bookmark.*/

function addToFavourites()
{
	title = document.title;
	url = location.href;

	if (window.sidebar) // Mozilla Firefox Bookmark
	{
		window.sidebar.addPanel(title, url,"");
	}
	else if (window.external) // IE Favorite
	{
		window.external.AddFavorite( url, title); 
	}
	else if (window.opera && window.print) // Opera Hotlist
	{
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	}
}

/**
 * This is a jquery plugin that I use to preload a bunch of images, its easy to use, just call 
 * 
 * $.preLoadImages("image1.jpg", "image2.jpg")
 * 
 */
(function($) {
	var cache = [];
	// Arguments are image paths relative to the current page.
	$.preLoadImages = function() {
		var args_len = arguments.length;
		for (var i = args_len; i--;) {
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			cache.push(cacheImage);	
		}
	};
})(jQuery);




/* EMAIL FUNCTIONS NEED TO BE PUT INTO AN OVERLAY - REMOVE WHEN DONE */
/*function email_this_item(i) {
	var win, ht;
	ht=310;
	win=window.open(web_path+'pages/email_this_page.php?item='+escape(i)+'&use_lb', 'email_this_item','resizable,width=480,height='+ht+',left=200,top=120,status');
}

function email_this_page(i) {
	var win, ht;
	ht=310;
	win=window.open(web_path+'pages/email_this_page.php?page='+escape(i)+'&use_lb', 'email_this_item',
	                'resizable,width=480,height='+ht+',left=200,top=120,status');
}*/


function changePerPage(osel) {

	var val = osel[osel.selectedIndex].value;
	url = new Url(location.href);
	url.setVar('perpage', val);
	url.go();

}

function changeOrder(osel) {
   var val = osel[osel.selectedIndex].value;
   url = new Url(location.href);
   url.setVar('order', val);
   url.go();
}

function toggleDirection(dir) {
   var set = (dir == 'ASC') ? 'DESC' : 'ASC';
   url = new Url(location.href);
   url.setVar('dir', set);
   url.go();
} 

function showHide(element) 
{
	if (jQuery(element).css('display') == "none")
	{
		jQuery(element).slideDown(200);
	}
	else
	{
		jQuery(element).slideUp(200);
	}
}

function over(obj) {
	// first lets see if the src of this image is blank.gif and if its IE6 - Based on these conditions
	// we know that its a png fix so we need to alter the method of changing the image background as oposed
	// to the image source.
	var filename = obj.src.substring(obj.src.lastIndexOf('/')+1);

	// first lets check to see if its IE6 and if the image in a png file
	if(filename == 'blank.gif' && $.browser.msie && $.browser.version == '6.0') {
		var newFilter = (obj.style.filter.replace('.png', '-over.png'));
		obj.style.filter = newFilter;
	} else {
		obj.src=obj.src.replace('.gif', '-over.gif');
		obj.src=obj.src.replace('.jpg', '-over.jpg');
		obj.src=obj.src.replace('.png', '-over.png');
	}
}
 
function out(obj) {
	var filename = obj.src.substring(obj.src.lastIndexOf('/')+1);
	if(filename == 'blank.gif' && $.browser.msie && $.browser.version == '6.0') {
		obj.style.filter = obj.style.filter.replace('-over', '');
	} else {
		obj.src=obj.src.replace('-over', '');
	}
}


/**
* Switch item tabs on the item detail page.
*/

function SwitchItemTab(tab_num)
{
	var sp=200;

	if (tab_num<=0)
		return;

	// Update tabs

	// if using only A tags for tabs
	//$('#store-item-tabs .store-tab-a-over').addClass('store-tab-a');
	//$('#store-item-tabs .store-tab-a-over').removeClass('store-tab-a-over');
	//$('#store-item-tabs #store-info-tab'+tab_num).addClass('store-tab-a-over');

	// using DIV enclosing other DIVs and A tags
	$('#store-item-tabs div.store-hdr-tab-over').removeClass('store-hdr-tab-over');
	$('#store-item-tabs div#store-info-tab'+tab_num).addClass('store-hdr-tab-over');

	// Show/hide content

	$('#store-item-tabs-body .store-tab-body').each(function()
	{
		if (this.style.display=='block')
		{
			//$(this).slideUp(sp);
			$(this).hide();
		}
	});

	//setTimeout(function() { $('#store-item-tabs-body #store-info-tab-body'+tab_num).slideDown(sp); }, sp);
	$('#store-item-tabs-body #store-info-tab-body'+tab_num).show();
	$('#store-item-tabs-body #store-info-tab-body'+tab_num).css('display','block');
}

/**
* Questions & Reviews
*/

var review_tab_num=0, question_tab_num=0;

function SwitchItemReviewsTab()
{
	SwitchItemTab(review_tab_num);
}

function SwitchItemQuestionsTab()
{
	SwitchItemTab(question_tab_num);
}

/**
* Set up the images on the item detail page. Add fancy box, 
* carousel, etc.
*/

var item_detail_current_img='';

function SetupItemDetailImages()
{
	var str;

	str="a.store-image-thumbnails-link";
	if ($("a.store-image-thumbnails-link").length<=0)
		str=str+', #store-item-large-image a';

	$(str).fancybox(
	{
		"transitionIn"	   :  "fade",
		"transitionOut"   :  "fade",
		"overlayOpacity"	:  0.8,
		"overlayColor"		:  "#000",
		"zoomSpeedIn"		:  300,
		"zoomSpeedOut"    :  300,
		"speedIn"         :  300,
		"speedOut"        :  300,
		"changeSpeed"     :  300
	});

	$("#store-item-large-image a").click(function()
	{
		var n=0, use_n=-1;

		if ($("a.store-image-thumbnails-link").length<=0)
			return;

		$("a.store-image-thumbnails-link").each(function()
		{
			var tmp_href=''+this.href;

			tmp_href=tmp_href.substring(tmp_href.indexOf('/images/pictures/'))

			if (use_n>=0)
				;
			else if (item_detail_current_img=='' && n==0)
			{
				use_n=n;
			}
			else if (item_detail_current_img==tmp_href)
			{
				use_n=n;
			}
			n++;
		});

		if (use_n<0)
			use_n=0;
		else
			$("a.store-image-thumbnails-link").eq(use_n).click();
		
		return false;
	});

	$("#store-item-thumbnails a").click(function()
	{
		var the_img=$(this).attr("href"); //children("img")[0].src;

		if ($("#store-item-large-image img").attr("src")!=the_img)
		{
			$("#store-item-large-image img").animate(
			{
				opacity: 0.05
			}, 200, 
			function()
			{
				$("#store-item-large-image img").attr("src", the_img);
				//alert( $("#store-item-large-image img").css('height') );

				setTimeout(function()
				{
					$("#store-item-large-image img").animate(
					{
						opacity: 1.0
					}, 200);
				}, 50);
			});
		}

		$("#store-item-large-image a").attr("href", the_img);

		item_detail_current_img=''+the_img;
		item_detail_current_img=escape(item_detail_current_img.substring(item_detail_current_img.indexOf('/images/pictures/')));

		return false;
	});

	$('#store-images-carousel').jcarousel(
	{
		scroll: 4
	});
}


function CalcQuickPostage(in_amt, item_id)
{
	var pcode='', amt=0.00, ptype='';

	if ($('#calc_postage_type1').attr('checked'))
		ptype=$('#calc_postage_type1').attr('value');
	else if ($('#calc_postage_type2').attr('checked'))
		ptype=$('#calc_postage_type2').attr('value');
	else
		return;

	if (in_amt=='')
		in_amt=$('#_item_price_box').html();

	amt=parseFloat(in_amt);
	pcode=''+$('#calc_postage_postcode').attr('value');
	if (pcode=='')
		return;
	if (pcode.length>4)
		pcode=pcode.substring(0,4);

	$('#store-item-postage-result').slideDown(100);
	$('#store-item-postage-result').html('<img src="'+web_path+'images/pictures/large/system-files/progress-bar.gif">');

	$.get(web_path+'products/'+
	   '?_auto_calc_postage&amt='+escape(amt)+
		'&item_id='+escape(item_id)+
		'&pcode='+escape(pcode), 
		'&postage_type='+escape(ptype), 
	function(data)
	{
		if (data!='')
		{
			var str=''+data;
			if (str.indexOf('error:')>=0)
				;
			else
				data='Delivery to '+escape(pcode)+': <b>'+data+'</b>';
			$('#store-item-postage-result').html(data);
			$('#store-item-postage-result').slideDown(100);
		}
		else
		{
			$('#store-item-postage-result').html('');
			$('#store-item-postage-result').slideUp(100);
		}
	});
}


/**
 * Apply class bassed validation
 * @param {Object} form
 */
function applyValidation(form) {
	$('div.error').hide();
	
	/**
	 * attach our custom validation to the form
	 */
	$(form).submit(function(e) {

		var focus = null;

		// check required fields
		$(this).find('[class*=required]').each(function() {
			// attach onchange to recheck on the fly
			var onChange = function() {
				if ($(this).val().trim() != '') {
					$(this).css('borderBottom', '');
					$(this).css('background','');
				}
			};
			
			$(this).change(onChange);
			$(this).blur(onChange);
			
			if ($(this).val().trim() == '') {
				$(this).css('borderBottom', 'solid 1px darkred');
				if (focus === null) {
					focus = $(this);
				}
			} else {
				$(this).css('borderBottom', '');
				$(this).css('background','');
			}
		});
		
		// we had validtion error
		if (focus !== null) {
			$('div.error').slideDown();
			focus.css('background', '#efefef');
			focus.focus();
			
			//call binded resize event
			$('#go-fancybox-inner').resize();
			return false;
		} 
		return true;
		
	});
}

