var filter_panel_heights = [];
var filter_tabs;
var filter_panels;
var all_products;

var isPhotoLoaded=false;

$(function(){

	var bodyelem;
		
	if($.browser.safari || $.browser.chrome) bodyelem = $("body")
	else bodyelem = $("html");

	$('#site_nav a.disable').click(function(e){
		e.preventDefault();
		return false;
	});
	$('#site_nav a.disable').hover(
		function(){
			$(this).css({'cursor':'default'});
		},
		function(){ }
	);
	$("#television a.video").click(function() {
		$.fancybox({
			'overlayColor'		: '#000',
			'overlayOpacity'	: 0.9,
			'padding'			: 5,
			'autoScale'		: false,
			'transitionIn'	: 'none',
			'transitionOut'	: 'none',
			'title'			: this.title,
			'width'			: 640,
			'height'			: 390,
			'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			'type'			: 'iframe'
			});
		return false;
	});
	$("#outdoor a.gallery").fancybox({
			'overlayColor'		: '#000',
			'overlayOpacity'	: 0.9,
			'padding'			: 5,
			'autoScale'		: true
	});
	
	$('input[type=text], textarea').click(function () {
	    if (this.value == this.defaultValue) {
	        this.value = '';
	    }
	});
	$('input[type=text], textarea').blur(function () {
	    if (this.value === '') {
	        this.value = this.defaultValue;
	    }
	});
	
	if($('#featured_recipe').length != 0) {
		if (! $.browser.msie && $.browser.version > 8) {
			init_recipe_refresh();
		}
	}
	
	var search_results = $("#search_results li");
	search_results.css({"cursor":"pointer"});
	search_results.bind("click", function(e){
		window.location.href = $(this).find('a').attr('href');
	});

	/******************** HOME **********************/
	
	var target = $('#promotion_stage div.slide');
	var obj = target.children('img.product');
	
	obj.css({ 'right' : '-' + Math.round(obj.width()) + 'px' });
	obj.delay(300).animate({
		'right' : 0
	}, 800, 'easeOutCirc');

	/******************** Filter **********************/
	if($('#filtering_tool li').length != 0) { // test if a filter exists - if not, don't init
		setup_filtering();
		// on load clear product rollover
		$('.hover').hide();
	}

	/* ---------------------------------------
		WHERE TO FIND (RETAILERS)
	--------------------------------------- */
	
	if ($("#retailers").length != 0){
		
		$('#map_default, #retailers_map .map_marker, #retailers .map_region').hide();
		
		$('#retailers_map .map_marker').live({
			click: function(e) {
				e.preventDefault();
				var hash = $(this).find('a').attr('href');
					 hash = hash.replace('#','');
				$('#retailers .map_region').hide();
				$('#' + hash).fadeIn('500', function(){
					$('#' + hash).find('.toplink').css({'visibility':'visible'});
					bodyelem.animate({
						scrollTop : $('#' + hash).offset().top - 20
					}, 1200, 'easeOutCirc')
				})
			},
			mouseover: function() {
				$(this).css({'cursor':'pointer'});
				$(this).addClass("hover");
				$(this).find('img').stop(true,false).animate({
		    		'margin-top' : 0
		    	}, 300, 'easeOutCirc');
		    	$('#retailers_map_overlay img').css({
		    		'margin-top' : '-' + $(this).index()*465 + 'px'
		    	});
		    	$('#retailers_map_overlay').css({'visibility':'visible'}).show();
			},
			mouseout: function() {
				$(this).removeClass("hover");
				$(this).find('img').animate({
		    		'margin-top' : 65
		    	}, 300, 'easeOutCirc');
		    	$('#retailers_map_overlay').hide();
		  	}
		});
		
		$('#retailers .toplink').click(function(e){
			e.preventDefault();
			bodyelem.animate({
				scrollTop : 0
				}, 1200, 'easeOutCirc', function(){
					$('#retailers .map_region').hide();
				})
		});
		
		var map = $("img#map_default").attr("src",$("img#map_default").attr("src") + "?" + new Date().getTime());
		
		map.load(function() {
      	$(this).fadeIn('400', function(){
				$('img#map_default').addClass('loaded');
				$('#retailers_map .map_marker').fadeIn();
			});
   	});
		
	}

	/* ---------------------------------------
		Global Navigation Dropmenu
	--------------------------------------- */
	var drops = $('#site_nav li.navdrop span.dropmenu');
	var uls = $('#site_nav li.navdrop ul');
	var hovers = $('#site_nav li.navdrop');
	// attempt at fixing IE's performance issues with the menu
	$.each(hovers, function(index, value){
		$(this).data("ref",$(this).attr('id').split("-")[1]);
	});
	
	$('#site_nav li.navdrop').hover(
		function () {
			$(this).addClass('hover');
			//$(this).find('span.dropmenu').show();
			//$(this).find('span.dropmenu').show();
			var dropmenu = "span#drop"+$(this).data('ref');
			$(dropmenu).show();
			//drops.eq($(this).index()).show();
		}, 
		function () {
			//$('ul', this).stop(true, true);
			$(this).find('ul').stop(true, false);
			//uls.eq($(this).index()).stop(true, false);
			$(this).removeClass('hover');
			//$(this).find('span.dropmenu').hide();
			var dropmenu = "span#drop"+$(this).data('ref');
			$(dropmenu).hide();
			//drops.eq($(this).index()).hide();	
		}
	);
	
	if ($("#sort_recipes").length == 0){
		all_products = $("#product_sort_results div.item"); // on products page
	} else {
		all_products = $("#sort_recipes li"); // on recipes page
	}
	
	
	
	$('#faq_list div.faq_hdr, #content div.faq_hdr').click(function(){
		$(this).toggleClass('faq_expand');
		$(this).parent('div').children('.faq_answer').slideToggle('400', 'easeOutCirc');
	
	})
	$('#faq_list div.faq_hdr, #content div.faq_hdr').hover(
		function(){
			$(this).css({'cursor' : 'pointer'});
		},function(){
		
		}
	)
	
	// detect for homepage
	if ($("#promotion_stage").length != 0){
		homepage_slideshow_init(); // in another js file
		setup_bottom_promos();
	}
	
	setup_related_promos();
	align_product_images();
	align_dropmenu_panels();
});


function init_retailermap(){
	/*isPhotoLoaded=true;
	$('img#map_default').fadeIn('400', function(){
		$('img#map_default').addClass('loaded');
		$('#retailers_map .map_marker').fadeIn();
	});*/
}

function setup_related_promos(){
	setup_bottom_promos();
}

function setup_bottom_promos(){
	var blocks = $("#promotion_related div.block, #related_items div.block, #related_items div.block_noimg");
	blocks.css({"cursor":"pointer"});
	blocks.bind({
		click: function() {
			window.location.href = $(this).find('a').attr('href');
		},
		mouseenter: function() {
			$(this).find('.block_txt').addClass('hover');
		},
		mouseleave: function() {
			$(this).find('.block_txt').removeClass('hover');
		}
	});
}

function get_current_channel(){
	var url_segments = document.URL.split("#"); 
	url_segments = url_segments[0].split("/"); 
	url_segments = url_segments.clean("");
	var current_channel = url_segments[url_segments.length-1];
	return current_channel;
}

function check_for_filter_cookie(){
	var cook = $.cookie(get_current_channel());
	if (cook == null){
		//$.cookie(get_current_channel(), null);
	} else {
		repopulate_filter();
	}
}

function repopulate_filter(){
	var ids = $.cookie(get_current_channel());
	ids = ids.split(',');
	$.each(ids, function(index, value){
		//console.log(value);
		var elem = $("ul#filter_menu li.sortid[rel="+value+"]");
		//console.log(elem);
		elem.trigger('click');
	});
	// $(this).parent('li').trigger('click');
}

function setup_filtering(){
	//filter_tabs = $('#filteropts_menu li');
	//filter_panels = $('.filteropt_list');
	$('#product_sort_results .item').hover(
		function(){
			$(this).css({'cursor' : 'pointer'});
			//$(this).append('<div class="hover"></div>');
			$(this).find('.hover').hide().stop(true,false).fadeIn('normal');
		},function(){
			$(this).find('.hover').hide().fadeOut(300);
		}
	);
	
	filter_tabs = $('#filtering_tool li');
	filter_panels = $('#filtering_tool .panel');

	filter_panels.each(function(){
		var item_cnt = $(this).find('li').length;
		if(item_cnt > 6){
			$(this).css({ 'width' : '50%' });
			$(this).find('li').css({ 'width' : '48%' });
			$(this).find('li:eq(0)').addClass('top');
			$(this).find('li:eq(1)').addClass('top');
		} else {
			$(this).find('li:eq(0)').addClass('top');
		}
	});
	
	filter_tabs.hover(
    	function() {
    		$(this).css({'cursor' : 'pointer'});
    		$(this).addClass('hover');
    		$('.panel', this).slideDown(300);
    	},
    	function() {
    		$('.panel', this).stop(true, true);
			$(this).removeClass('hover');
			$('.panel', this).slideUp(200);	
   		}
   );


   // get panel heights
   filter_panels.each(function(){
		var tmp = $(this).outerHeight();
		filter_panel_heights.push(tmp)		
	});

	filter_tabs.mouseover(function() {
  		var tab_id = $(this).index();
		toggle_filter_menu(tab_id);
		toggle_filter_panel(tab_id);
		$('.sort_loader').hide();
	});

	
	$('#filtering_tool li li').click(function(e){

		e.preventDefault();	
		$(this).toggleClass('checkd');
		$('.sort_loader').stop(false,true).fadeIn().delay(1000).fadeOut();
		$('#filtering_tags').show();
		
		var existing_tags = $('#filtering_tags span.tag');
		var new_tag_text = $(this).children('span').text();
		var total_existing = 0;
		$.each(existing_tags, function(index, value) {
			if($(this).text() == new_tag_text){
				total_existing++;
			}
		});
		if (total_existing == 0){
			$('#filtering_tags').append('<span class="tag">' + $(this).children('span').text() + '</span>');
		}
		
		if ($(this).hasClass("checkd")){
		
		} else {
			var to_uncheck = $(this).children('span').text();
			var all_spans = $("#filtering_tags span.tag");
			$.each(all_spans, function(index, value) { 
				if($(this).text() == to_uncheck){
					$(this).trigger('click');
				}
			});
		}
		$("#filtering_tags span.tag").css({'cursor' : 'pointer'});
		filter_results();
	})

	$('#filtering_tags span.tag').live({
	  click: function() {
	    remove_tag($(this));
	  },
	  mouseover: function() {
	    $(this).addClass("hover");
	  },
	  mouseout: function() {
	    $(this).removeClass("hover");
	  }
	});
	
	setTimeout(check_for_filtering,600);
	//check_for_filtering();
}

function align_dropmenu_panels(){
	var shell_width = $("#content").width();
	var panels = $("#filter_menu span.panel");
	$.each(panels, function(index, value){
		$(this).show();
		var position = $(this).position();
		var width = $(this).width();
		if (Math.round(position.left + width) > Math.round(shell_width)){
			$(this).css({'left' : Math.round(shell_width-width-50)});
		}
		$(this).hide();
	});
}

function align_product_images(){

	if ($("#product_sort_results").length != 0){
		var img = $("#product_sort_results div.item div.thumb img");
		$.each(img, function(index, value){
			$(this).css({'marginLeft' : "-"+Math.round($(this).attr('width') / 2) + 'px'});
		});
	}
}

function check_for_filtering(){
	if ($("ul#filter_menu").length != 0){
		if (window.location.hash){
			var filters = $("ul#filter_menu li.sortid span");
			$.each(filters, function(index, value){
				var url_name = $.trim($(this).text().toLowerCase().replace(/[^a-zA-Z0-9_]/g,''));
				if (window.location.hash == "#"+url_name){
					//console.log($(this).parent('li'));
					$(this).parent('li').trigger('click');
				}
			});
		} else {
			
			setTimeout(check_for_filter_cookie, 700);
		}
	}
	
}

function remove_tag(element){
	var to_uncheck = element.text();
	//console.log(to_uncheck);
	var all_spans = $("#filter_menu li span");
	$.each(all_spans, function(index, value) { 
		if($(this).text() == to_uncheck){
			var checked_tag = $(this);
			var par = checked_tag.closest('li').removeClass('checkd');
		}
	});
	element.remove();
	var spans_left = $("#filtering_tags span.tag");
	if (spans_left.length == 0){
		$("#filtering_tags").hide();
	}
	filter_results();
}

function filter_results(){
	var applied_tags = $("#filter_menu li.sortid.checkd");
	var cook_ids = [];
	var ids = applied_tags.map(function() {
		cook_ids.push($(this).attr("rel"));
	  return $(this).attr("rel");
	});
	
	//console.log(cook_ids);
	//console.log("s");
	$.cookie(get_current_channel(), cook_ids, { path: '/' });
	//console.log($.cookie(get_current_channel()));
	
	var all_in;
	var active_products = [];
	$.each(all_products, function(index, value) { 
		var cat_ids = $(this).attr('rel').split(",");
		all_in = 0;
		$.each(ids, function(i, v) { 
			if(jQuery.inArray(v, cat_ids) != -1){
				all_in++;
			}
		});
		if (ids.length == all_in){
			active_products.push(all_products.get(index));
		}
	});
	
	all_products.hide();
	
	$.each(active_products, function(index, value) { 
		$(this).show();
	});
	if (active_products.length == 0){
		show_noresults();
	} else {
		hide_noresults();
	}
}

function show_noresults(){
	$("#noresults").remove();
	var str = "Sorry, we don't have anything that matches what you've requested.<br />Please either select fewer filters, or if you'd prefer, you can start over by <a href='' id='clickhere'>clicking here</a>.";
	var block = $("<div id='noresults'><p>"+str+"</p></div>");
	$("#filtering_tags").after(block);
	$("a#clickhere").bind('click', function(e){
		clear_all_filters();
		return false;
	});
}

function clear_all_filters(){
	$("#filter_menu span.panel li.checkd").removeClass('checkd');
	$("#filtering_tags span.tag").remove();
	$("#filtering_tags").hide();
	filter_results();
}

function hide_noresults(){
	$("a#clickhere").unbind("click");
	$("#noresults").remove();
	
}

function toggle_filter_menu(id) {
	var filter_menutabs = $('#filteropts_menu li');
		
	filter_menutabs.each(function(){
	
		var elem = $(this);
	
		if(elem.index() == id) {
		
			if(!elem.hasClass('open')){
				elem.addClass('open');
			} else {
				elem.removeClass('open');
			}
				
		} else {
		
			$(this).removeClass('open');
			
		}
	
	});

}

function toggle_filter_panel(id) {

	var filter_panels = $('.filteropt_list');
	
	filter_panels.not(':eq(' +id+ ')').animate({
		'height' : 0
		}, 200, 'easeOutCirc', function(){
			$(this).removeClass('expanded');
		});
	
	if(filter_panels.eq(id).hasClass('expanded')){
	
		filter_panels.eq(id).stop(true,true).animate({
			'height' : 0
			}, 200, 'easeOutCirc', function(){
				$(this).removeClass('expanded');
			});
	
	} else {
	
		filter_panels.eq(id).show().css({ 'height' : 0 }).stop(true,true).delay(200).animate({
				'height' : filter_panel_heights[id] + 'px'
			}, 500, 'easeOutCirc', function(){
				$(this).addClass('expanded');
			});
	
	}
		
}


/******************************** RECIPE REFRESH *********************************/

var recipes_total_cnt;
var recipes_next_slide;

function init_recipe_refresh(){

	recipes_next_slide = 0;
	recipes_total_cnt = $('#featured_recipe .slide').size();
	
	$('#featured_recipe .slide').css({ 'opacity' : 0 });
	
	$('#refresh_btn').click(function(){
		//$(this).children('span').addClass('ani');
		refreshSlide(recipes_next_slide);
	});
	
	refreshSlide(recipes_next_slide);

}

function refreshSlide(num) {

	var target = $('#featured_recipe .slide');

	target.not(':eq(' + num + ')').animate({
		'opacity' : 0
		}, 500, function(){
			$(this).hide();
		});
	target.eq(num).removeClass('hide').show().animate({
		'opacity' : 1.0
		}, 500, function(){
			$('#refresh_btn').children('span').removeClass('ani');
		});
	
	recipes_next_slide = num+1;
	
	if(recipes_next_slide == recipes_total_cnt){
		recipes_next_slide = 0;
	}
  	
}

Array.prototype.clean = function(deleteValue) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == deleteValue) {         
      this.splice(i, 1);
      i--;
    }
  }
  return this;
};

