$(document).ready(function() {
	
	$( "#tabs" ).tabs();
	
	$("#tandc").live('click', function() {
		
		$('#terms-holder').slideToggle('slow');
		$('html,body').animate({scrollTop: $('#terms-holder').offset().top},'fast');

		return false;
	});
	if($("#fm-widget-product-scroller-inner a").length > 5) {
		
		$("#fm-widget-product-scroller-inner").jCarouselLite({
			 auto: false,
			speed: 200,
			visible: 5,
			circular: true,
			btnNext: "#fm-widget-product-scroller-right",
			btnPrev: "#fm-widget-product-scroller-left"
	
		 });
	} else {
		$('#fm-widget-product-scroller .fm-widget-product-scroller-control a').fadeTo('slow', 0.5);
		$('#fm-widget-product-scroller .fm-widget-product-scroller-control a').click(function(){
			return false;
		})
	}
	
	if($("#fm-widget-banner a").length > 1) {
		
		$('#fm-widget-banner').cycle({ 
		fx:     'fade', 
		speed:  'fast', 
		timeout: 4000
	});
	}
	
	
	
	
	
	/* Handle Popups for compeitions */
	$( "#popups" ).dialog({
		modal:true, 
		width:750, 
		height:304, 
		draggable:false, 
		resizable:false,
		buttons: {
				
				"No thanks": function() {
					
					var self = $( this );
					var params = new Object();
					var banner_id = $('.popuplink').attr('id');
					var banner_id_arr = banner_id.split("-");
					params.banner_id = banner_id_arr[1];
					
					$.ajax({
						type: "POST",
						url: '/default/customer/competition/',
						data: params,
						success: function(response) {
							
							self.dialog( "close" );
						}
					});
					
					//
					
				},
				"Show me more": function() {
					
					
					var href = $( "#popups a:first").attr('href');
					document.location.href = href;
					return false;
				}
			},
		open: function(event, ui) {
			 
			  // Get the dialog 
				var dialog = $(event.target).parents(".ui-dialog.ui-widget"); 

				// Get the buttons 
				var buttons = dialog.find(".ui-dialog-buttonpane").find("button"); 


			 
				 var cancelButton = buttons[0]; 
				 var moreButton = buttons[1]; 
				 
				  //$(cancelButton).addClass("cancel"); 
                  $(moreButton).addClass("more"); 

				 

		}
		
		});
	
	$('#signup-newsletter').live('click', function() {
		var params = new Object();
		params.email = $('#newsletter-email').val();
		
		if(params.email == 'Email Address') {
			params.email = '';
		}
		
	
		$.ajax({
			type: "POST",
			url: '/default/customer/newsletter/',
			data: params,
			success: function(response) {
				
				if (response == 'SUCCESS') {
					$('#newsletter-email').val('');
					//$('#newsletter-msg').html('<p class="nm-msg nm-success">Success!</p>');
					window.location.href = '/competition/campaign/holiday2012?status=newslettersignup';
					//alert('SUCCESS! Thank you for signing up');
					
				} else {
					if (response == 'EXISTS') {
						alert('that email already exists');
						//$('#newsletter-msg').html('<p class="nm-msg nm-warning">Already Registered</p>');
					}
					
					if (response == 'INVALID') {
						alert('that email is invalid please retype');
						//$('#newsletter-msg').html('<p class="nm-msg nm-warning">Invalid Email</p>');
					}
					
				}
			}
		});
	});
	
	
	
	$('.fm-minibasket-summary').css('cursor', 'pointer');
	$('.fm-minibasket-summary').live('click', function() {
		window.location.href = '/basket/';
	});
	
	
	$('#keyword').focus(function() {
		if($(this).val() == 'Search') {
			$(this).val('');
		}
		
		$(this).addClass('active');
	});
	
	$('#keyword').blur(function() {
		if($(this).val() == '') {
			$(this).val('Search');
			$(this).removeClass('active');
		}
		
		
	});
	
	
	$('.minisearch-btn').click(function(){
		var btn = $(this);
		var key = $('#keyword').val();
		
		if(key == 'Search') {
			return false;
		}
		return true;
	});
	
	
	$('#newsletter-email').focus(function() {
		if($(this).val() == 'Email Address') {
			$(this).val('');
		}
		
		$(this).addClass('active');
	});
	
	$('#newsletter-email').blur(function() {
		if($(this).val() == '') {
			$(this).val('Email Address');
			$(this).removeClass('active');
		}
		
		
	});
	
	
	$('.click-row').live('mouseover mouseout click', function(event) {
	  if (event.type == 'mouseover') {
		$(this).addClass('active');
		
		
               $(this).find('.offer')
                .animate({top:"-6px"}, 200).animate({top:"0px"}, 200);;
            
				$(this).find('.sale')
                .animate({top:"-6px"}, 200).animate({top:"0px"}, 200);
				
				$(this).find('.new')
                .animate({top:"-6px"}, 200).animate({top:"0px"}, 200);
		
	  } else {
		$(this).removeClass('active');
		if(event.type == 'click') {
			var href = $(this).find('a:first').attr('href');
			
			window.location.href = href;
			return false;
		}  
	  }
	});
	
	startBanners();
	

	
	
	function megaHoverOver(){
		
		$(this).addClass('active');
		
		$(this).find(".sub").stop().fadeTo('fast', 1).show();
		$(this).find(".sub-brands").stop().fadeTo('fast', 1).show();
		//Calculate width of all ul's
		(function($) { 
			jQuery.fn.calcSubWidth = function() {
				rowWidth = 0;
				//Calculate row
				$(this).find("ul").each(function() {					
					rowWidth += $(this).width(); 
				});	
			};
		})(jQuery); 
		
		if ( $(this).find(".row").length > 0 ) { //If row exists...
			var biggestRow = 0;	
			//Calculate each row
			$(this).find(".row").each(function() {							   
				$(this).calcSubWidth();
				//Find biggest row
				if(rowWidth > biggestRow) {
					biggestRow = rowWidth;
				}
			});
			//Set width
			$(this).find(".sub").css({'width' :biggestRow});
			$(this).find(".sub-brands").css({'width' :biggestRow});
			$(this).find(".row:last").css({'margin':'0'});
			
		} else { //If row does not exist...
			
			$(this).calcSubWidth();
			//Set Width
			$(this).find(".sub").css({'width' : rowWidth});
			$(this).find(".sub-brands").css({'width' : rowWidth});
		}
	}
	
	function megaHoverOut(){
		$(this).removeClass('active');
		$(this).find(".sub").stop().fadeTo('fast', 0, function() {
		  $(this).hide();
		});
		$(this).find(".sub-brands").stop().fadeTo('fast', 0, function() {
		  $(this).hide();
		});
		
		
	}
 
 
	var config = {    
		 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
		 interval: 100, // number = milliseconds for onMouseOver polling interval    
		 over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
		 timeout: 200, // number = milliseconds delay before onMouseOut    
		 out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};
 
	$("ul.fm-nav-tree li .sub").css({'opacity':'0'});
	$("ul.fm-nav-tree li").hoverIntent(config);
 
 	
	$('#fm-minibasket').fmBasket();
	
	// delivery and returns dialog
	$('.delivery_returns_link').click(function(){
				
		var dialog_id = 'delivery_returns_dialog';
		var params = new Object();
		$.ajax({
			type: "POST",
			url: '/pages/dialog/slug/delivery-returns-policy',
			data: params,
			success: function(response) {
				GenericDialog(dialog_id, 800, 600);
				$('#'+dialog_id).html(response);
				Cufon.replace('.cufon');
			}
		});
		
		return false;

	});
	
	// terms dialog
	$('.terms_link').click(function(){
				
		var dialog_id = 'terms_dialog';
		var params = new Object();
		$.ajax({
			type: "POST",
			url: '/pages/dialog/slug/terms-conditions/',
			data: params,
			success: function(response) {
				GenericDialog(dialog_id, 800, 600);
				$('#'+dialog_id).html(response);
				Cufon.replace('.cufon');
			}
		});
		
		return false;

	});
	
	// privacy dialog
	$('.privacy_link').click(function(){
				
		var dialog_id = 'privacy_dialog';
		var params = new Object();
		$.ajax({
			type: "POST",
			url: '/pages/dialog/slug/privacy-policy/',
			data: params,
			success: function(response) {
				GenericDialog(dialog_id, 800, 600);
				$('#'+dialog_id).html(response);
				Cufon.replace('.cufon');
			}
		});
		
		return false;

	});
	
	// delivery and returns dialog
	$('.global_banner_link').click(function(){
				
		var dialog_id = 'delivery_returns_dialog';
		var params = new Object();
		$.ajax({
			type: "POST",
			url: '/pages/dialog/slug/delivery-returns-policy',
			data: params,
			success: function(response) {
				GenericDialog(dialog_id, 800, 600);
				$('#'+dialog_id).html(response);
				Cufon.replace('.cufon');
			}
		});
		
		return false;

	});
	
	// measure graphic dialog
	$('.measure_guide').click(function(){
		var dialog_id = 'measure_guide';
		GenericDialog(dialog_id, 830, 650);
		$('#'+dialog_id).html($('#measure_guide_img').html());
		return false;
	});
	
	//faqs
	$('.acc_div h4').click(function() {
		$('.acc_div div').not($(this).next()).slideUp();				 
		$(this).next().slideToggle();
		
		//$(this).css('','');
		$('.acc_div h4').not(this).toggleClass('faq_on',false);
		$(this).toggleClass('faq_on');
		
		return false;
	}).next().hide();
	
	
	

});


function startBanners() {
	
	$('.fm-banners').cycle({ 
		fx:     'fade', 
		speed:  'fast', 
		timeout: 6000, 
		pager:  '.banner-nav-inner',
		next:   '#next2', 
		prev:   '#prev2' 

	});

}

function GenericDialog(str1, w, h){

	var dialog = '';
	dialog = dialog + '<div class="gen_dialog" id="'+str1+'">';
	dialog = dialog + '<div class="gen_dialog_inner" id="'+str1+'_inner">';
	dialog = dialog + '</div>';
	dialog = dialog + '</div>';
	
	$('body').append(dialog);
	
	$('#'+str1).dialog({
		modal: true,				
		autoOpen: false,
		dialogClass: "gen_dialog",
		width: w,
		height :h,
		draggable:false,
		resizable:false,
		close: function(event, ui){
			$('.gen_dialog').remove();
		},
		closeOnEscape: true,
			buttons: {
				'Close': function() {
					$( this ).dialog( "close" );
				}
			}
	});
		
	$('#'+str1).dialog('open');

}


function GenericDialog_buttons(str1, w, h){

	var dialog = '';
	dialog = dialog + '<div class="gen_dialog" id="'+str1+'">';
	dialog = dialog + '<div class="gen_dialog_inner" id="'+str1+'_inner">';
	dialog = dialog + '</div>';
	dialog = dialog + '</div>';
	
	$('body').append(dialog);
	
	$('#'+str1).dialog({
		modal: true,				
		autoOpen: false,
		dialogClass: "gen_dialog",
		width: w,
		height :h,
		draggable:false,
		resizable:false,
		close: function(event, ui){
			$('.gen_dialog').remove();
		},
		closeOnEscape: true,
		buttons: {
			'Submit': function() {
				$("#ask_a_question_form").submit();
			},
			'Cancel': function() {
				$( this ).dialog( "close" );
			}
		}
	});
		
	$('#'+str1).dialog('open');

}

// ask a question
function AskAQuestion() {
			
	var dialog_id = 'ask_a_question_dialog';
	var params = new Object();
	$.ajax({
		type: "GET",
		url: '/pages/dialog/slug/ask-a-question/product_title/'+$('#product-title-hidden').val(),
		data: params,
		success: function(response) {
			GenericDialog_buttons(dialog_id, 450, 600);
			$('#'+dialog_id).html(response);
			Cufon.replace('.cufon');
			
			// ask a question form
			$("#ask_a_question_form").validate({
				errorPlacement: function(error, element) {
					error.appendTo(element.parents(".nf-block-row").find("label"));
				}
			});
			
			
		}
	});
	
	return false;

};

