// the maximum number of products that can be added to the compare widget
var compare_products_max = 4;
var cancel_delivery_hide;

JQ= jQuery.noConflict();

JQ.fn.digits = function(){ 
    return this.each(function(){ 
        JQ(this).text( JQ(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
    })
};

JQ(document).ready(function() {
	JQ('#category_menu').superfish();							
	JQ('#main_menu').superfish(); 		
	
	
	animatedcollapse.addDiv('fancy-panel')
	//additional addDiv() call...
	//additional addDiv() call...
	animatedcollapse.init()

	// Product Search Widget
	JQ('#search-bar form div.form-container input').focus(function() {
	  JQ('#search-bar div.arrow').removeClass('arrow-up')
	  JQ('#search-bar div.arrow').addClass('arrow-down')
	});

	JQ("#search-bar label#search_label").inFieldLabels();

	JQ('#search-bar').mouseleave(function() {           
		JQ('#search-bar div.arrow').removeClass('arrow-down')
	  	JQ('#search-bar div.arrow').addClass('arrow-up')
	});

	// Delivery Postcode Widget
	JQ('#delivery-bar a#delivery_widget').click(function() {
	  JQ('#delivery-bar div.delivery-panel').fadeIn('fast');
	  JQ('#delivery-bar div.arrow').removeClass('arrow-up')
	  JQ('#delivery-bar div.arrow').addClass('arrow-down')	  
	  JQ('#delivery-bar-result').html('').slideUp();
	  // focus the postcode field
	  JQ('#delivery-bar input[name=postcode]').focus();
	});

	JQ('#delivery-bar').mouseleave(function() {            
		cancel_delivery_hide = setTimeout(function() {
			JQ('#delivery-bar div.delivery-panel').fadeOut('fast');
			JQ('#delivery-bar div.arrow').removeClass('arrow-down');
			JQ('#delivery-bar div.arrow').addClass('arrow-up');
		},800 /* the value to wait before hiding the delivery bar */);
	});

	JQ('#delivery-bar').mouseenter(function() {
		if ( cancel_delivery_hide )
			clearTimeout(cancel_delivery_hide);
	});

	
	// Rounded Corners
	JQ("li#nav-fragment-1 a").corner("tr");
	JQ("li#nav-fragment-5 a").corner("br");
	JQ("div.ui-tabs-panel").corner("tl,bl");	

	// Brands Slider	
	JQ("#brands-slider").easySlider({
		controlsBefore:	'<p id="controls2">',
		controlsAfter:	'</p>',	
		prevId: 'prevBtn2',
		nextId: 'nextBtn2',
		auto: 'true',
		continuous: 'true'
	});			
	
	// Compare List Widget
	JQ('#btn_comparison a').click(function() {
		var isActive = JQ(this).hasClass('active');
		if ( ! isActive )
		{
			var product_count = JQ('#compare_list li').length;
			if ( product_count >= compare_products_max )
			{
				alert('A maximum of four products can be compared at one time.');
				return false;
			}
		}

		setup_btn_comparison(this);
		if ( isActive )
			compare_product_remove('compare_list', JQ(this).attr('rel'),true);
		else
			compare_product_add('compare_list',JQ(this).attr('rel'),true);
	});	

	// Datepicker
	JQ('#datepicker').datepicker( { dateFormat:'dd/mm/yy', minDate: "+2D" } );
	JQ('#campaign_date_of_birth').datepicker( { dateFormat:'dd/mm/yy', changeMonth: true, changeYear: true, yearRange: '-100:-0' } );

	// Cufon		
	Cufon.replace('h2.impact_grey');
	Cufon.replace('h3.impact_lightgrey');
	Cufon.replace('span.impact_black');
	Cufon.now();	
	
	//JQ("div.float-panel1").sidecontent({speed:750});
	//JQ("div.float-panel2").sidecontent({speed:750});
	//JQ("div.float-panel3").sidecontent({speed:750});
	
	// Lightbox
	JQ('#gallery a').lightBox();
	JQ('a.product_view_image').lightBox();
	
	JQ("#checkout_wrapper form").validate();
	JQ("#user_form form").validate();
	JQ("#contact_form form").validate();
	
	// Misc Functions
	JQ('a[href$=.pdf]').addClass("pdf_link")
	
});


function setup_btn_comparison(elem)
{
	if ( elem )
	{
		JQ(elem).text( JQ(elem).hasClass('active') ? 'Add to Compare List' : 'Remove - Compare List');
		JQ(elem).toggleClass('active')
	}
	else
	{
		elem = JQ('#btn_comparison a');
		JQ(elem).toggleClass('active')
		JQ(elem).text( !JQ(elem).hasClass('active') ? 'Add to Compare List' : 'Remove - Compare List');
	}

}

function checkEmail(email) {
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email)) {
		return false;
	}
	else {
		return true;
	}
}

	
function clearText(field){
	if (field.defaultValue == field.value) field.value = '';
	else if (field.value == '') field.value = field.defaultValue;
}



function checkForm() {
	if((document.getElementById('name').value == "") || (document.getElementById('name').value == "name")) {
		alert('Please enter your name');
		return false;
	}
	if((document.getElementById('email').value == "") || (document.getElementById('email').value == "email address")) {
		alert('Please enter your email address');
		return false;
	}
	 if ( !checkEmail(document.getElementById('email').value) ) {
		alert("Please enter a valid Email Address.");
		return false;
	 }
	return true;
}
	
function check_postcode_delivery()
{
	JQ('#delivery-bar input[name=postcode]').addClass('postcode-working');
	JQ.post('./cart/shippingpostcode', jQuery('#delivery-bar form').serializeArray(), function(response) {
		// this is an array of shipping options
		var options = response.shipping_options;
		var message;
		if ( options && options .length > 0 )
			message = 'Yes, we deliver to that area';//options[0].title;
		else
			message = 'Sorry, we do not deliver to this address, Please <a href="mailto:kol@kambos.com.au?subject=KOL: special delivery quote">contact us</a> for a special delivery quote';

		JQ('#delivery-bar-result').html(message).filter(':not(:visible)').slideToggle();
		JQ('#delivery-bar input[name=postcode]').removeClass('postcode-working');
	},'json');

	return false;
}


function compare_products()
{
	var product_count = JQ('#compare_list li').length;

	if ( product_count < 2 )
	{
		alert('Not enough products to compare');
		return;
	}

	JQ('#product_compare').load('./shop/productcomparison');
	// JQ.blockUI({ message : JQ('#product_compare_container') , css: { cursor:'default',width:'990px',margin:'0',top:'20%',showOverlay:true} });
	JQ.blockUI({ message : JQ('#product_compare_container'), css: {
				cursor:'default',
	            top:  '100px', 
                left: (JQ(window).width() - 980) /2 + 'px', 
                width: '980px',
				height: (JQ(window).height() - 120) + 'px',
				margin: '0',
				showOverlay:true
	            },
				overlayCSS: { cursor: 'default' }
				
    });
	
}


function compare_product_remove(element_id,product_id,ignorebutton)
{
	JQ.blockUI( {message:'<h1>Removing product from compare list</h1>',css:{padding:'2em'}});
	// remove product
	JQ.post('./shop/removecompareproduct','product_id='+encodeURIComponent(product_id),function(response) {
		// failure means product is probably already in compare widget
		if ( ! response.success ) return;
		// reload widget
		JQ('#'+element_id).load('./shop #'+element_id+' > *',function() {
			// run after load completes
			JQ.unblockUI();
			JQ.scrollTo('#compare_list',600,{});
		});
		if ( ! ignorebutton)
			setup_btn_comparison();
	},'json');

	return false;
}

function compare_product_add(element_id,product_id,ignorebutton)
{

	JQ.blockUI( {message:'<h1>Adding product to compare list</h1>',css:{padding:'2em'}});
	// add product
	JQ.post('./shop/addcompareproduct','product_id='+encodeURIComponent(product_id),function(response) {
		// failure means product probably wasn't in compare widget
		if ( ! response.success ) return;
		// reload widget
		JQ('#'+element_id).load('./shop #'+element_id+' > *',function() {
			//run after load completes
			JQ.unblockUI();
			JQ.scrollTo('#compare_list',600,{});
		});
		if ( ! ignorebutton )
			setup_btn_comparison();
	},'json');

	return false;
}

function play_video(video_id)
{
	JQ.get('./videogallery/getembed/'+video_id,null,function(response) {
		if ( ! response.html )
			return;
		JQ('#video_container h2').text( response.title );
		var w = response.width+20;
		var h = response.height+58;
		JQ('#video_content').html( response.html );
		JQ.blockUI({
			message : JQ('#video_container'),
			cursor : 'pointer',
			css : {width:w+'px',height:h+'px'},
			overlayCSS: { cursor: 'default' }
		 });
	},'json');
}

