/*

	SRC75 main.js
	Author: Antoine Girard (antoine.girard@gmail.com)

*/

jQuery(document).ready(function() {
	site.init();
});

site = {
	
	init : function() {
		
		video_player.init();
		
		// 
		$('#cooking a.start-video, #recipe a.start-video').each(function() {
			var url = $(this).attr('href');
			// correct url
			if(url.match(/watch\?v\=/)) {
				url = url.replace(/watch\?v\=/, 'embed/');
			}
			$(this).attr('href', url);
		});
		
		// overlay window containing youtube videos
		$('#cooking a.start-video, #recipe a.start-video').colorbox({
			iframe: true,
			innerWidth: 600,
			innerHeight: 400,
			opacity: 0.5,
			scrolling: false,
			transition: "none"
		});
		
		// info nutritive box
		$('a.nutrition').colorbox({
			innerWidth: 300,
			innerHeight: 500,
			opacity: 0.5,
			scrolling: false,
			transition: "none",
			// inline: true,
			// href:"#nutrition"
			html: $("#nutrition").html()
		});
		
		
		// triger product & recipe click event to parent link
		$(".image-mask").live('click', function() {
			var img = this;
			var a = $(this).parent().find('a');		
			var target = $(a).attr('target');
			
			if(a.length > 0 && target == "_blank") {
				window.open($(a).attr('href'));
			} else if(a.length > 0) {
				window.location = $(a).attr('href');
			} else {
				// do nothing
			}
		});
		
		// print link
		$('a.print').click(function() {
			window.print();
			return false;
		});
		
		// share by email box
		share_form.init();
	
		
		// roll over effect on masked items
		round_products_effects();
		
		// fix the abominable child
		if(jQuery.browser.msie && jQuery.browser.version < 9) {
			this.fix_ie();
			rounded_corners();
		}
	},	
	
	fix_ie : function() {
	}
		
}

home_recipes = {
	
	init : function() {		
		$("#featured-recipes ul").cycle({
				fx: 'scrollHorz',
				prev: '#featured-recipes-navigation a.prev', 
				next: '#featured-recipes-navigation a.next', 
				timeout: 0,
				speed: 500,
				before: function() {
					$("#featured-recipes-navigation article").fadeOut('fast');
				},
				after: function() {
					home_recipes.show_content(this);
				},
				onPrevNextEvent : function() {
					// home_recipes.reset_players();
					video_player.close_players();
				}
		});
				
		if($("#featured-recipes ul li").length == 1) {
			home_recipes.show_content($("#featured-recipes ul li")[0]);
			$("a.prev, a.next").hide();
		}
		
		// live triggers		
		$("#featured-recipes ul li a.player-icon, #featured-recipes-navigation article a.start-video").live('click', function() {
			var id = $(this).attr('data-recipe-id');
			var target = $("li[data-recipe^='"+id+"']");
			home_recipes.start_player(this, target);
			return false;
		});
	},
	
	show_content : function(e) {
		var content = $(e).find('article').html();
		var video_url = $(e).attr('data-video');
		if(video_url.length > 0) {
			$(e).addClass('has-video');;
		}
		$("#featured-recipes-navigation article").html(content).fadeIn(500);
	},
	
	start_player : function(a, e) {
		// video_player.reset_players();
		var player = $(e).find('.player');
		var video_url = $(e).attr('data-video');		
		video_player.insert_player(player, video_url);
	}
	
}

video_player = {
	
	init : function() {
		$("div.player a.close").live('click', function() {
			video_player.close_players();
		})
	},
	
	insert_player : function(e, url) {
		var inner = $(e).find('.inner');
		var options = "?version=3&autohide=1&showinfo=0&autoplay=1&hd=1";
		
		// correct url
		if(url.match(/watch\?v\=/)) {
			url = url.replace(/watch\?v\=/, 'embed/');
		}		
		
		var player_markup = '<iframe title="YouTube video player" width="520" height="263" src="' + url + options + '" frameborder="0" allowfullscreen></iframe>';

		// remove any exiting iframe
		$(inner).find('iframe').remove();

		// insert player
		$(e).fadeIn(500, function() {
			$(player_markup).prependTo(inner);			
		});	
	},
	
	close_players : function() {
		$("div.player iframe").remove();
		$("div.player").fadeOut();
	}
		
}

function init_video_player(e, url) {
	var inner = $(e).find('.inner');
	var options = "?version=1&autohide=1&showinfo=0&autoplay=1&hd=1";	
	var player_markup = '<iframe title="YouTube video player" width="520" height="263" src="' + url + options + '" frameborder="0" allowfullscreen></iframe>';
	$(e).fadeIn(500, function() {
		$(player_markup).prependTo(inner);			
	});	
}


// products selector on homepage
home_products = {

	init : function() {
		$("#product-categories .categories li a").click(function() {
			var a = this;
			var is_open = $('#product-categories').hasClass('open');
			if(!$(a).hasClass('active')) {
				if(!is_open) {
					home_products.open_products(a);	
				} else {
					home_products.change_products(a);	
				}				
				$("#product-categories .categories li a").removeClass('active');
				$(a).addClass('active');
				$("a.close").fadeIn();
			}
			return false;
		});
		
		$("#product-categories a.close").click(function() {
			$("#product-categories").animate({"height": 32}, function() {
				$("#product-categories a.close").fadeOut();
				$("#product-categories .categories li a").removeClass('active');
				$(this).removeClass("open");
				home_products.reset_carousel();
			});
			return false;
		})
		
	},
	
	open_products : function(e) {
		$("#product-categories").animate({"height": 280}, function() {
			home_products.filter_content(e);
			$(this).addClass("open");
			// round_products_effects();
		});		
	},
	
	change_products : function(e) {
		home_products.reset_carousel();
		home_products.filter_content(e);
	},
	
	filter_content: function(e) {
		var label = $(e).attr('data-label');
		var scope = $("ul.products-db li[data-label^='"+label+"']").clone();
		home_products.insert_carousel(scope);
	},
	
	insert_carousel : function(items) {
		this.reset_carousel();
		var carousel = $("<ul/>").addClass('products jcarousel-skin-canard').hide();
		$(items).appendTo(carousel);
		$(carousel).prependTo("#products-carrousel").fadeIn();
		if(items.length > 5) {
			this.start_carousel(carousel);	
		} else {
			// no need to start carousel, change container width to align it to center
			var total_width = $("#products-carrousel ul.products li").width() * items.length;
			$("#products-carrousel ul.products").width(total_width);
		}
	},
	
	start_carousel : function(e) {
		$(e).jcarousel({
			scroll: 5,
			wrap: "circular"
		});	
	},
	
	reset_carousel : function() {
		// remove any intance first
		$("#products-carrousel").find('.jcarousel-skin-canard').remove();
	}

}

// product selector on Find our product page
products_selector = {
	
	init : function() {
		var container = $("#products-selector");
		var trigger = $(container).find('a.select');
		var content = $(container).find('div.products');
		
		// toggle open/close on trigger element
		$(trigger).toggle(function() {
			products_selector.open_panel(content);
			return false;
		}, function() {
			products_selector.close_panel(content);
			return false;			
		});
		
		var a = $(content).find('ul.list-products a');
		$(a).click(function() {
			var e = this;
			var store_ids = $(e).attr('data-stores').split(',');
			var groceries_ids = $(e).attr('data-groceries').split(',');
			var text = $(e).text();

			// reset all items
			products_selector.reset();
			
			// change selector label value
			products_selector.change_selector(text);
			
			// active menu item
			$(this).addClass('active');

			// find related stores
			for (var i=0; i < store_ids.length; i++) {
				var id = store_ids[i];
				if(id.length > 0)
					var store = $("li[data-id='store-"+id+"']");
					products_selector.activate(store);
			};
			
			// find related groceries
			for (var i=0; i < groceries_ids.length; i++) {
				var id = groceries_ids[i];
				if(id.length > 0)
					var grocery = $("li[data-id='grocery-"+id+"']");
					products_selector.activate(grocery);
			};

			// close panel on click
			$(trigger).trigger('click');

			// prevent default on A
			return false;
		});		
		
		// find current product and trigger
 		var id = PRODUCT_ID;
		if (id !== 'False') {
			var a = $('.list-products a[data-id^="' + id + '"]');
			$(a).trigger('click').trigger('click');
			this.close_panel();
		}
		
	},
	
	reset : function() {
		$("ul.list-products a, ul.list-items li").removeClass('active');
	},
	
	init_scroll : function () {
		$('#products-selector .scrollable').jScrollPane({ 
			scrollbarWidth: 17,
			dragMaxHeight: 60,
			dragMinHeight: 60,
			topCapHeight: 0
		});
	},
	
	change_selector : function(val) {
		$("a.select").text(val).addClass("active");
	},
	
	activate : function(a) {
		$(a).addClass("active");
	},

	open_panel : function(e) {
		$(e).stop().animate({height: "300"}, 250, function() {
			products_selector.init_scroll();
		});
	},
	
	close_panel : function(e) {
		$(e).stop().animate({height: "0"}, 100);	
	}
	
}



// methods for jQuery cycle plugin
function cycle_total_pages(e, target) {
	var total = $(e).length;
	if(total > 1) {
		$(target).text(total);		
	} else {
		$("#pager, a.next, a.prev").hide();
	}

}


//  form share by email
share_form = {
	
	init : function() {
		var form_html = $("div#email-friend").html();
		
		$('a.email-friend').colorbox({
			innerWidth: 380,
			innerHeight: 410,
			opacity: 0.5,
			scrolling: false,
			html: form_html,
			transition: "none",
			onComplete: function() {
				// init form validation
				share_form.validates();
			}
		});
		
	},
	
	validates : function() {
		$("#cboxContent form").validate({
			submitHandler: function(form) {
				share_form.submit_form(form);
				return false;
			},
			messages: VALIDATION_MESSAGES
		});		
	},
	
	submit_form : function(form) {
		var url = $(form).attr('action');
		var parent = $(form).parent();
		var params = $(form).serialize();
		var share_url = window.location;
		params += "&is_ajax=1";

		$.ajax({
		  url: url,
		  dataType: 'json',
		  data: params,
			type: "POST",
		  success: function(response) {
				if(response.status === 'ok') {
					$(form).slideUp();
					$(parent).html('<p>'+response.message+'</p>');
					setTimeout($.colorbox.close, 3500);
				} else {
					$(parent).html('<p>'+response.message+'</p>');
				}
			},
			error : function(response) {
			 	$(form).slideUp();
			 	$(parent).html('<p>Erreur</p>');
			}
		});
	}	
}

function round_products_effects() {
	$(".product, .recipe").live('mouseenter',function() {
		var mask = $(this).find('div.image span.mask.black');
		var mask_over = $(this).find('div.image span.mask.black-hover');
		var img = $(this).find('img');
		var container = $(this).find('.image-mask');
		var img_over = $(img).clone().addClass('over-image').appendTo(container);

		$(this).addClass('over');

		if(jQuery.browser.msie) {
			$(mask_over).show();
			$(img_over).show();
		} else {
			$(mask_over).stop().animate({"opacity": 1}, 250);
			$(img_over).stop().animate({"opacity": 1}, 250);			
		}

	});	
	
	$(".product, .recipe").live('mouseleave',function() {
		var mask = $(this).find('div.image span.mask.black');
		var mask_over = $(this).find('div.image span.mask.black-hover');
		var img = $(this).find('img');
		var img_over = $(this).find('.over-image');
		$(this).removeClass('over');

		if(jQuery.browser.msie) {
			$(mask_over).hide();
			$(img_over).hide();
		} else {
			$(mask_over).stop().animate({"opacity": 0}, 250);
			$(img_over).stop().animate({"opacity": 0}, 250, function() {
				$(this).remove();
			});
		}
	});	
}


$.fn.clearOnFocus = function(){

	return this.focus(function(){
		var v = $(this).val();
		$(this).val( v === this.defaultValue ? '' : v );
	}).blur(function(){
		var v = $(this).val();
		$(this).val( v.match(/^\s+$|^$/) ? this.defaultValue : v );
	});

};

function add_title_span(e) {
	var html = $(e).html();
	if(!$(e).find('span')[0]) {
		replace = "<span>" + html + "</span>";
		$(e).html(replace);
	}
}

// apply rounded corners to old browsers
function rounded_corners() {
	$('#primary-nav li.left a, #primary-nav li.right a, .tabs a, body.home #content #product-categories ul.categories li a').corner('5px #fad02a');
}

function block_ui(message) {
	jQuery.blockUI({
		css: { 
	    border: 'none', 
	    padding: '25px', 
			width: "200px",
			'font-size': '18px',
			left: "37%",
	    backgroundColor: '#000', 
	    opacity: .95, 
	    color: '#fff'
		},
		message: message,
		baseZ: 400000
	});
}
