/*! 
 *  BB Sports  Application Logic JS Version 5
 *  Written by: Dominic Wormald
 *  Last Update: Fri 16/Nov/2010 
 *  
 *  Added Size Select 		  		- 	Thurs 	11/Nov/2010
 *  problem with size values sorted 		- 	Tue  	16/Nov/2010 
 *  Added nested filter accordion   		- 	Fri 	26/Nov/2010
 *  Sorted Problem with filters causing 	-	Mon	30/Nov/2010
 *  extraneous page load.
 *  Tweaked Logic for accordians 
 */


var began_loading = (new Date()).getTime();
var preload_image_object = new Array();
var prev;
var roleover;
var prevsrc;
var swapid;
var whichbox;



$(document).ready(function()
{

$("<div/>",{id:'suggestionsBox'}).css({'position':'absolute','width':'200px','display':'none'}).appendTo('body');


/* FUNKY FADER  Lets get some funk on more funky fader logic later on */

if($('#funkyFader').length)
{
autoplay(funkyslideNum);

numtabs = $("#funkyFader li").length -1;

$("#funkyFader").hover(
  function () {
funkyslidepaused = 'paused';
  },
  function () {
    funkyslidepaused = 'go';
  }
);



}



	$('#teams a').hover(
	function (){
	$(this).siblings().stop().fadeTo(500, 0.33);
	},
	function (){
	$(this).siblings().stop().fadeTo(500, 1);
	}
	);


    if($('body').width() > 600)
    {
	$('.breadcrumbs a,.breadcrumbs span').after(' &#187; ');
    }

	$('#shopping_bag .quantity').append('<ul><li><img src="/assets/images/arrow-up.png" class="up" /></li><li><img src="/assets/images/arrow-down.png" class="down"  /</li></ul>');
	$('#shopping_bag .quantity .up').click(function(e){
	var x = $(this).parent().parent().parent().find('input:last').val();
	x++;
	$(this).parent().parent().parent().find('input:last').val(x);
	$(this).parent().parent().parent().find('input:last').change();
	});

	$('#shopping_bag .quantity .down').click(function(e){
	var x = $(this).parent().parent().parent().find('input:last').val();
	x--;
	if(x<=0){x=0}
	$(this).parent().parent().parent().find('input:last').val(x);
	$(this).parent().parent().parent().find('input:last').change();
	});
	

	$("#header .nav>.parent").hover(function () {
	pos = $(this).position();	
	$(this).next('.sub').css({left:pos.left-1});
	tmp= $(this).height();
	$(this).next('.sub').css({top:pos.top+tmp+9});
	$(this).next('.sub').fadeIn(200);
	});


	$('a.new_win').click(function(){
		window.open(this.href,'popup');
		return false;
	});




	// allow only numbers 

	$(".q, .quan, .num_only").live('keydown',function(event) {
        // Allow only backspace and delete
        if ( event.keyCode == 46 || event.keyCode == 8 ) {
            // let it happen, don't do anything
        }
        else {
            // Ensure that it is a number and stop the keypress
            if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
                event.preventDefault(); 
            }   
        }
	});




/* MAIN NAVIGATION */

htxt= $("#top .left").html();
$(" #nav > li.parent > a").append(' <img src="/assets/images/rd.gif" width="13" height="13" />');
$(" #nav ul ").css({display: "none"}); // Opera Fix
$(" #nav > li").hover(
function(){
hidezoom = true;
$(this).find('ul:first').css({visibility: "visible",display: "none"}).slideDown(400);
},function(){
hidezoom = false;
$(this).find('ul:first').css({visibility: "hidden"});
});


$("#nav ul li").hover(
function(){
hidezoom = true;
$(this).find('ul:first').css({visibility: "visible",display: "none"}).show(400);
},function(){
hidezoom = false;
$(this).find('ul:first').css({visibility: "hidden"});
});

$("#nav a").hover(
function () 
{
temp = this.title;
if(this.title !='')
{
this.title='';
$("#top .left").html(temp + ' | BB Sports');
}
}, 
function () 
{
this.title = temp;
temp = '';
$("#top .left").html(htxt);
});





	 $('a[href*=#]').live('click', function() {
	    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
	        && location.hostname == this.hostname) {
	            var $target = $(this.hash);
	            $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
	            if ($target.length) {
	                var targetOffset = $target.offset().top;
	                $('html,body').animate({scrollTop: targetOffset}, 1000);
	                return false;
	            }
	        }
	   });


	$('.autocomplete').keyup(function() 
	{	


		whichbox = $(this).attr('id');
		var autocomp_url = $(this).attr('autocomp_url');

		var search_string = $(this).val();
        if(search_string.length >= 1)
        {
			pos = $(this).position();	
			tmp= $(this).height();
			$('#suggestionsBox').html('');
			$('#suggestionsBox').css({left:pos.left+1});
			$('#suggestionsBox').css({top:pos.top+tmp+5});
			$('#suggestionsBox').fadeIn('slow');
			$('#suggestionsBox').load(autocomp_url+urlencode(search_string)+'&r='+Math.random(), function ()
			{
				$('#suggestionsBox a').click(function() 
				{
					text= $(this).html();
					$('#'+whichbox).val(text);
					$('#'+whichbox).change();
					$('#suggestionsBox').hide();
					return false;
				});
			});
        }
	});

	if ($('#listing').length) 
	{


		highlighter();




		
		var numItems = $('.sub').length
		if(numItems > 2)
		{


	     $('.sub').hide();
		 $('#listfilters .subhead').append('<span class="expand">&nbsp;</span> ');
		 $('#listfilters .subhead').live('click',function (){
	 	 var tmp_switch = $(this).find("span:first").attr('class');
		 var chckd = $(this).parent().find('input:checked');
		 chckd.removeAttr('checked');
		 if(tmp_switch == 'expand')
		 {
			
			$(this).parent().find('.sub').hide();
            $('#listfilters .subhead').css({'background':'#3E4754'})
			$(this).parent().find('.subhead').find("span:first").attr('class','expand');
			$(this).find("span:first").attr('class','collapse');
			$(this).css({'background':'#000','color':'#fff'});
			$(this).next('.sub').stop().show();
			var checkBxs = $(this).next('.sub').find('input[type=checkbox]');
			checkBxs.attr('checked',true);
		 }
		 else
		 {

			$(this).find("span:first").attr('class','expand');
			$(this).next('.sub').stop().hide();
		 }
		
		 parse_filters();
         return false;

		 });



		}
		bindListEvents();
        cool_image_loader('#grid');
	} 
});

$(window).load(function()
{ 
	$("#loadinfo").append(' and took '+ (((new Date()).getTime() - began_loading) / 1000)+' seconds to download.');
});


function urlencode (str) {
  str = (str+'').toString();
 return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28'). replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}

function parse_filters()
{
var l = $('#listfilters').serialize();
loadlist( window.location['pathname']+'?'+l);
}
  

function bindListEvents()
{
	$(window).load(function(){$("#grid img").stop().fadeTo(0,1);})

    $("#grid").touchwipe({
    preventDefaultEvents: false,
    wipeLeft:   function() {$('#nextpg').click(); return false},
    wipeRight:  function() {$('#prevpg').click(); return false},
    });

    $(document).keyup( function(e)
	{
	switch(e.which)
	{
	case 37:
	if(!e.ctrlKey)
	{
	if($('#prevpg').length){ $('#prevpg').click(); } 
	}	
	break;    
	case 39:			
	if(!e.ctrlKey)
	{
	if($('#nextpg').length){ $('#nextpg').click(); } 	
    }
	break;
	}
	});

	// attatch light box event 
	$('#grid a.icon').lightBox();

	$("#keywords").change(function(){
	$('input[type=checkbox]').removeAttr('checked')
	parse_filters();
	});
	
	$('.jqueryhideme').hide();
	
	$('#listfilters input[type=checkbox]').parent().hover(function() {
	$(this).css('cursor','pointer')
	});

	$('#listfilters input[type=checkbox]').click(function() {
	$(this).parent().parent().parent().find('input[type=checkbox]').attr('checked', false);
	$(this).attr('checked', true);		
	parse_filters();
	});

    $('#num_res, #sort_by').change(function() {
	parse_filters();
	});

	$('#current_filters a , .listbar a').click(function() {
	loadlist($(this).attr('href'));
	return false;
	});

    // PRODUCT JS

    $('.prod_slider_container').each(function(){
    $(this).data('current_slide', 0);
    var num_images = $(this).children('.prod_slider_slides:first').children('a').length;
    if(num_images > 1)
    {
    var emstr = '<em class="current">&nbsp;</em>';
    for (i=1;i < num_images;i++)
    {
            emstr = emstr + ' <em>&nbsp;</em>';
    }
    $(this).children('.prod_slider_current:first').append(emstr);
    $(this).append('<div class="slide_controlls"><div class="left"><a href="#" class="prev_slide" title="Click to see Previous Slide">&lt;</a></div><div class="right"><a href="#" class="next_slide" title="Click to see Next Slide">&gt;</a></div></div>');
    }
    });


    $('.slide_controlls a').click(
    function (){
    var slide_width = 0 - $(this).parent().parent().parent().width();
    var num_slides = $(this).parent().parent().parent().children('.prod_slider_slides:first').children('a').length -1;
    if($(this).attr('class') == 'prev_slide'){var x = -1;}else{var x = 1;}
    y=$(this).parent().parent().parent().data('current_slide') + x;
    if(y < 0){y=num_slides;}
    if(y > num_slides){y=0;}
    $(this).parent().parent().parent().data('current_slide',y);
    $(this).parent().parent().parent().children('.prod_slider_slides:first').animate({'margin-left':(y*slide_width)+'px'},800);
    $(this).parent().parent().parent().children('.prod_slider_current:first').children('em').removeClass("current");
    $(this).parent().parent().parent().children('.prod_slider_current:first').children('em:eq('+y+')').addClass("current");
    return false;
    }
    );

    $('.product').each(function() {
    if($(this).find('.description:first .features:first li').length > 4)
    {
    $(this).find('li:gt(3)').hide().end();
    $(this).find('.description:first .features:first').append('<li style="list-style:none"><a href="#" class="toggle_more">Read More</a></li>');
    }
    });

    $('.toggle_more').click(function(){
    if($(this).html()=='Read More')
    {
    $(this).html('Hide Details');
    $(this).parent().parent().find(':hidden').stop().slideDown(400);
    }
    else
    {
    $(this).parent().parent().find('li:gt(3)').stop().slideUp(400).end();
    $(this).parent().parent().find('li:last').stop().show(400).end();
    $(this).html('Read More');
    }
    return false
    });

    // ORDER PROCESS EVENTS

    $('.select_quan').click(function(){
	$('html,body').animate({scrollTop:0}, 100);
    $.get($(this).attr('href')+'&mode=ajax', function(data) {
    // Fade in background attach logic 
    fadeInBG(
    function(){
    $('#alert_bg').click(function(){
    $('#alert_bg,#funkyDialogue').fadeOut(400,function(){$(this).remove();})
    return false;
    });

    funkyDialogue('Select Size and Quantities',data,function(){
    // Events for quantity and size select dialogue 
    $('#funkyDialogue .bar a').click(function(){
    $('#alert_bg,#funkyDialogue').fadeOut(400,function(){$(this).remove();});
    return false;
    });
    
    $('.inStock .quantity').append('<ul><li><img src="/assets/images/arrow-up.png" class="up" /></li><li><img src="/assets/images/arrow-down.png" class="down"  /</li></ul>');
	$('.inStock .quantity .up').click(function(e){
	var x = $(this).parent().parent().parent().find('input:last').val();
	x++;
    if(x <= $(this).parent().parent().parent().find('input:last').attr('maxvalue'))
    {
	$(this).parent().parent().parent().find('input:last').val(x);
	$(this).parent().parent().parent().find('input:last').change();
    }
    else
    {
	$(this).parent().parent().parent().find('input:last').val($(this).parent().parent().parent().find('input:last').attr('maxvalue'));
	$(this).parent().parent().parent().find('input:last').change();
    }
	});

	$('.inStock .quantity .down').click(function(e){
	var x = $(this).parent().parent().parent().find('input:last').val();
	x--;
	if(x<=0){x=0}
	$(this).parent().parent().parent().find('input:last').val(x);
	$(this).parent().parent().parent().find('input:last').change();
	});
	

    $('.q').change(function(){
    if(parseInt($(this).val()) > parseInt($(this).attr('maxvalue')))
    {
    $(this).val(parseInt($(this).attr('maxvalue')));
    }
    });
    

    $('#selectSizeForm').submit(
    function (){
    $.get('/shopping-bag.php?'+ $(this).serialize()+'&mode=ajax', function(data) {
    $('#header .cart').load('/shopping-bag.php?task=display_small_cart&mode=ajax');
    $('#funkyDialogue').remove();
    funkyDialogue('Product(s) added to your Shopping Cart',data,function(){
    $('#funkyDialogue .bar a, #continue').click(function(){
    $('#alert_bg,#funkyDialogue').fadeOut(400,function(){$(this).remove();});
    return false;
    });
    });
    });
    return false;
    });



    });

    });

    });

    return false;
    });
}



function highlighter()
{   
    $("#listfilters .sub label:odd").css({"background-color": "#ccc"});
}


function loadlist(l)
{


$("#keywords").unbind('change');
$("#listfilters input[type=checkbox]").attr('disabled', true);
$("#list_results").html('<p style="text-align:center; font-size:3em; line-height:1em; font-weight:bold; color:#888">Loading, please wait...</p>');
$('#listfilters input').unbind('change');
$('#listfilters input[type=checkbox]').unbind('click');
$("#list_results").load(l+'&ajax=true', function ()
{
	

    cool_image_loader('#grid');
    $("#filters").load(l+'&filters=true #filters > *', function ()
	{
    if($('.sub').length > 2)
	{
 	$('#listfilters .subhead').append('<span class="expand">&nbsp;</span> ');
	$('.sub').each(
	function ()
	{

		if($(this).find("input[type=checkbox][checked]").length==0)
		{
			$(this).stop().hide();
		}
		else
		{
			$(this).prev('.subhead').find('span:first').attr('class','collapse');
			$(this).prev('.subhead').css({'background':'#000','color':'#fff'});
			$(this).stop().show();
		}

	}
	);
	}

	highlighter();
	bindListEvents();
	});

	
});
}





function scrollTo(Target)
{
	var targetOffset = Target.offset().top;
	$('html,body').animate({scrollTop: targetOffset}, 1000);

}




var funkyslideNum = 0,funkyslidepaused = 'go';

function display_funky_slide(tmp)
{
$('#funkyFader li:eq('+tmp+')').stop().fadeTo(3000, 1);
$('#funkyFader li:eq('+tmp+')').siblings().stop().fadeTo(3000, 0, function (){$('#funkyFader li:eq('+tmp+')').siblings().stop().hide()});
}


function autoplay(tnum)
{

if(funkyslidepaused != 'paused')
{
display_funky_slide(tnum);
}

slidertimer=setTimeout(function() {
tnum++;
if(tnum > numtabs)
tnum=0;
autoplay(tnum);
},6000);
}



// Fades out images within any div untill loaded, just give it a selecta and it will do the rest

function cool_image_loader(element_id)
{
$(element_id+' img').stop().fadeTo(0,0);
$(element_id+' img').load(function () {$(this).stop().fadeTo(600,1)})
// Some browsers fail to fire load event if image allready in cache  should fix this issue
$(element_id+' img').each(function(){
if(this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6)) 
{
	$(this).trigger("load");
}
});
}

// fades in background opaque background and gives you a call back
function fadeInBG(callback)
{
$("<div/>",{id:'alert_bg'}).css(
{
'background':'#3E4754',
'position':'absolute',
'top':'0',
'left':'0',
'width':'100%',
'height':'100%',
'z-index':'99999',
'opacity':'0'
}
).appendTo('body').animate(
{
opacity: 0.9
}, 200, function() 
{
callback();
});
}



// fades in background opaque background and gives you a call back
function funkyDialogue(messagestr,data,callback)
{
var content  ='<div class="bar"><h2 class="left">'+messagestr+'</h2><div class="right"><a href="#">X</a></div></div> <div class="content">'+data+'</div>';

$("<div/>",{id:'funkyDialogue'}).html(content).appendTo('body').animate(
{
opacity: 1,
}, 200, function() 
{
callback();
});
}

