/*
 * primary JavaScript file for AllBran.com
 * requires: $.js (written and tested against version 1.6.2)
 * requires: bgc.js, PIE.htc, plugins.js, jquery.ui
 *
*/

Function.prototype.method = function (name, func) {
	this.prototype[name] = func;
	return this;
};
String.prototype.cleanLabel = function () {
	return this.replace(/\W/g, "");
};
if (typeof Object.create !== 'function') {
	Object.create = function (o) {
		var F = function () {};
		F.prototype = o;
		return new F();
	};
}

var AllBran = AllBran || {};

/*self executing portion */
$(function () {
	/*add ie and version hooks to html*/
	var classList, browVer;
	if ($.browser.msie) {
		browVer = parseInt($.browser.version, 10);
		classList = "ie "+ $("html").attr("class");
	} else {
		classList = "not-ie " + $("html").attr("class");
	}
	$("html").attr('class', classList);

	// prevent background image flicker in IE
	try {
		if (!window.opera) {
			document.execCommand("BackgroundImageCache", false, true);
		}
	} catch (err) {
	}
	AllBran.UI.init();
	AllBran.Tracking.init();
	AllBran.Testimonials.init();
});

AllBran.UI = {
	init: function () {
		AllBran.UI.Nav();
		AllBran.UI.Overlay.init();
	},
	Stars: function () {
		$(".stars-wrapper, .stars-enabled").children().not(":radio").hide();
		//non-interactive
		$(".stars-wrapper").hide().each(function () {
			var $this = $(this);
			var selected = $this.attr('data-rating') - 1;
			if (selected > 0) {
				$this.find('.star').eq(selected).attr('checked', 'checked').attr('defaultChecked', true);
			}
			$(this).stars({
				disabled: true
			}).show();
		});
	},
	Carousel: {
		settings : {
			delay : 5500,
			roses : $('#mini-carousel div.rose'),
			dir : 'right',
			sel : 0,
			old : 0
		},
		init : function (options) {
			var self = this;
			if (options) {
				$.extend(AllBran.UI.Carousel.settings, options);
			}

			//start timer call next//
			this.redir = function () {
				this.next();
			};
			var interval = setInterval(function () {self.redir(); }, AllBran.UI.Carousel.settings.delay);

			$('#leftArrow').bind('click', function () {
				clearInterval(interval);
				AllBran.UI.Carousel.settings.dir = 'left';
				self.previous();
			});

			$('#rightArrow').bind('click', function () {
				//if timer active : kill it
				clearInterval(interval);
				AllBran.UI.Carousel.settings.dir = 'right';
				self.next();
			});

			AllBran.UI.Carousel.settings.roses.click(function () {
				AllBran.UI.Carousel.settings.old = 0;
				AllBran.UI.Carousel.settings.sel = 0;
				AllBran.UI.Carousel.settings.dir = "";
				//if timer active: kill it
				clearInterval(interval);

				//get the previous/current
				AllBran.UI.Carousel.settings.old = AllBran.UI.Carousel.settings.roses.filter('.selected').index() - 1;

				//get the clicked on item index
				AllBran.UI.Carousel.settings.sel = AllBran.UI.Carousel.settings.roses.index(this);

				//change
				if (AllBran.UI.Carousel.settings.old > AllBran.UI.Carousel.settings.sel) {
					AllBran.UI.Carousel.settings.dir = 'left';
				}
				if (AllBran.UI.Carousel.settings.old < AllBran.UI.Carousel.settings.sel) {
					AllBran.UI.Carousel.settings.dir = 'right';
				}
				if (AllBran.UI.Carousel.settings.old === AllBran.UI.Carousel.settings.sel) {
					return false;
				}
				self.update();
			});
		},

		next : function () {
			AllBran.UI.Carousel.settings.old =  AllBran.UI.Carousel.settings.roses.filter('.selected').index() - 1;
			AllBran.UI.Carousel.settings.sel = AllBran.UI.Carousel.settings.old + 1;

			//wrapping
			if (AllBran.UI.Carousel.settings.sel >= AllBran.UI.Carousel.settings.roses.size()) {
				AllBran.UI.Carousel.settings.sel = 0;
			}
			this.update();
		},

		previous: function () {
			AllBran.UI.Carousel.settings.old = AllBran.UI.Carousel.settings.roses.filter('.selected').index() - 1;
			AllBran.UI.Carousel.settings.sel = AllBran.UI.Carousel.settings.old - 1;

			//wrapping
			if (AllBran.UI.Carousel.settings.sel >= AllBran.UI.Carousel.settings.roses.size()) {
				AllBran.UI.Carousel.settings.sel = AllBran.UI.Carousel.settings.roses.size() - 1;
			}
			this.update();
		},

		update : function () {
			var content = $('#gallery div');
			//find the old
			AllBran.UI.Carousel.settings.roses.eq(AllBran.UI.Carousel.settings.old).removeClass('selected');
			$(content).eq(AllBran.UI.Carousel.settings.old).css('z-index', 100);
			$(content).eq(AllBran.UI.Carousel.settings.sel).css('z-index', 99);
			//move the old
			if (AllBran.UI.Carousel.settings.dir === 'left') {
				$(content).eq(AllBran.UI.Carousel.settings.old).stop().animate(
					{
						left: '-348px'
					},
					{
						duration: 'slow',
						easing: 'swing',
						complete: function () {
							$(this).addClass('hide').css('left', 0);
						},
						queue: 'false'
					}
				);
			} else {
				$(content).eq(AllBran.UI.Carousel.settings.old).stop().animate(
					{
						left: '348px'
					},
					{
						duration: 'slow',
						easing: 'swing',
						complete: function () {
							$(this).addClass('hide').css('left', 0);
						},
						queue: 'false'
					}
				);
			}
			//make the next one visible
			$(content).eq(AllBran.UI.Carousel.settings.sel).removeClass('hide');
			//housekeeping
			AllBran.UI.Carousel.settings.roses.eq(AllBran.UI.Carousel.settings.sel).addClass('selected');
		}
	},
	Nav: function () {
		//add faux element to end of the nav
		if (window.location.href.match(/com\/fiber-facts/g)) {
			$('.nfacts').removeClass('last').parent().append("<li class=\"last\" style=\"width: 70px;\">&nbsp;</li>");
		}
		/*add  .move for recipe tab in all but recipes inverse logic for chrome*/
		if (!window.location.href.match(/fiber-menu|fiber-rich-recipes|fiber-add-ins|my-saved-recipes|\/recipes\//g)) {
			$('.nrecipes').addClass('move');
		}
	},
	Overlay: {
		init : function () {
			$('a.trigger-modal').fancybox({
				'type': 'iframe',
				'scrolling': 'yes',
				'autoScale' : false,
				'hideOnOverlayClick' : false,
				'titleShow': false,
				'transitionIn'	: 'elastic',
				'transitionOut': 'elastic',
				'overlayColor': '#fff',
				'padding': '15',
				'width': 655,
				'height': 455,
				'onClosed': function () {
					if ($('html').hasClass('ie8')) {
						parent.location.reload(true);
					}
				}
			});//end fancybox

			$('a.trigger-signup').fancybox({
				'type': 'iframe',
				'scrolling': 'yes',
				'autoScale' : false,
				'hideOnOverlayClick' : false,
				'titleShow': false,
				'transitionIn'	: 'elastic',
				'transitionOut': 'elastic',
				'overlayColor': '#fff',
				'padding': '0',
				'width' : 760,
				'height' : 550,
				'onClosed': function () {
					BGC.track(parent.str);
					if ($('html').hasClass('ie8')) {
						parent.location.reload(true);
					}
				}
			});	//end fancybox

			$('a.trigger-nutrition').fancybox({
				'type': 'iframe',
				'scrolling': 'no',
				'autoScale' : false,
				'hideOnOverlayClick' : true,
				'titleShow': false,
				'transitionIn'	: 'elastic',
				'transitionOut': 'elastic',
				'overlayColor': '#fff',
				'padding': '0',
				'width' : 655,
				'height' : 550,
				'onClosed': function () {
					if ($('html').hasClass('ie8')) {
						parent.location.reload(true);
					}
				}
			});//end fancybox

			if ($('html').hasClass('ie7')){
					$('a.trigger-video').fancybox({
					'type': 'iframe',
					'autoScale' : false,
					'hideOnOverlayClick' : false,
					'titleShow': false,
					'transitionIn'	: 'elastic',
					'transitionOut': 'elastic',
					'overlayColor': '#fff',
					'padding': '20px',
					'width': 665,
					'height': 390
				});//end fancybox
			} else{
				$('a.trigger-video').fancybox({
					'type': 'iframe',
					'autoScale' : false,
					'hideOnOverlayClick' : false,
					'titleShow': false,
					'transitionIn'	: 'elastic',
					'transitionOut': 'elastic',
					'overlayColor': '#fff',
					'padding': '20px',
					'width': 660,
					'height': 380
				});//end fancybox
			}
		}//end overlay.init
	},//end ui.overlay
	Search: function () {
		$('input[placeholder], textarea[placeholder]').placeholder();
		//recipes/search.aspx/{Product}/{MealType}/{Keyword}
		$('#search .button.go').bind('click submit', function (e) {
			e.preventDefault();
			//alert(encodeURI( $('#Keyword').val()));
			var str = "All_Products/All_Meals/" + encodeURI($('#kw').val());
			window.location.href = "/recipes/search.aspx/" + str;
		});
		$('#refine .button.go').bind('click submit', function (e) {
			e.preventDefault();
			var str = $('#SearchProduct').val();
			str += "/" + $('#SearchMeal').val(); 
			str += "/" + $('#Keyword').val();
			str += "?SortBy=" + $('#SortBy').val();
			window.location.href = "/recipes/search.aspx/" + str;
		});	
	},
	Tabs: function () {
		$('#util-tabs').tabs({
			cookie: {
				expires: 1,
				name: "util-tabID-Cookie"
			},
			select: function(e, ui){
				window.onhashchange = function () { 
   				if (window.location.hash == "" || window.location.hash == "#")
   				return false;
   			}
   		}
		});
		$('#recipe-tabs').tabs({
			cookie: {
				expires: 1,
				name: "reci-tabID-Cookie"
			}
		});
	},
	Tipsy: function () {
		$('.tip').tipsy({gravity: 's'});
	},//end Tipsy
	Believer : function () {
		$('.copy img:last').hide();
	}
};//end allbran.UI

AllBran.Tracking = {
	init: function () {
		// GA initialization and pageview tracking
		BGC.track.init("UA-5870493-5", "UA-5624474-1");
		BGC.track();
		// class-based GA tracking hooks
		// link tracking (finds and tracks links with class="track category|action|label" applied)
		$("a.track").click(function (e) {
			var ev = getEventString(this.className), target = null, callback = null, href = null;
			if (ev) {
				target = this.target;
				if (!this.className.match(/no-follow/) && (!target || target.match(/^_(self)|(top)$/i))) {
					href = $(e.target).closest("a")[0].href;
					callback = function () {
						if (target.match(/^_top$/i)) {
							top.location.href = href;
						} else {
							location.href = href;
						}
					};
					e.preventDefault();
				}
				BGC.track(ev, callback);
			}
		});

		// form view/submit "action" (virtual pageview) tracking
		$("form.track").each(function () {
			var ev = getEventString(this.className).replace(/\|/g, "/");
			if (ev) {
				BGC.track(ev + "/view");
				$(this).submit(function (e) {
					if (Page_IsValid) { // only track the submit action if the .NET validation routine passed
						BGC.track(ev + "/submit");
					}
				});
			}
		});

		function getEventString(s) {
			var ev = "";
			s = s.split(" ");
			$.each(s, function () {
				if (this.indexOf("|") > -1) {
					ev = this.toString();
					return;
				}
			});
			return ev;
		}
	}
};
AllBran.Testimonials = {
	init: function () {
		if ($('.carousel').length) {
			$('.carousel').jcarousel({
				size: 5,
				scroll: 1,
				wrap: 'circular',
				itemFallbackDimension : 2325
			});
			$('.testimonials ul').removeClass('hidden');
			/* tracking */
			$('.jcarousel-prev').bind('click', function () {
				BGC.track("shareyourstory|morearrow|moreleft");
			});
			$('.jcarousel-next').bind('click', function () {
				BGC.track("shareyourstory|morearrow|moreright");
			});
		}
	}
};

AllBran.Data = {
	//turn this into a constructor somehow and retun a copy of itself
	init: function (options) {
		this.settings = {
			key: '',
			dataSet: [],
			recipeIDs: [],
			maxL: 8,
			matchPos: 0,
			target_node: "#recent ul"
		};
		if (options) {
			$.extend(this.settings, options);
		}
		return this;
	},
	get_data: function (callback) {
		var self = this.settings;
		self.recipeIDs = $.jStorage.get(self.key);
		if (self.recipeIDs) {
			$.ajax({
				url: "/Recipe.aspx/GetJSON",
				type: "POST",
				data: {
					RecipeIDs: self.recipeIDs,
					width: 250
				},
				success: function (recipes) {
					var i;
					for (i = 0; i < recipes.length; i++) {
						//populate my array
						self.dataSet[i] =  recipes[i];
					}
					if (!_.isEmpty(self.recipeIDs)) {
						var j;
						for (j = 0; j < self.dataSet.length; j++) {
							var string = '<li><img alt="Save this recipe" class="saveRecipe sidebar" data-recipeid="' + self.dataSet[j].RecipeID + '" src="/images/shapes/save_btn.png" width="20" height="20" alt="X"/>';
							string += '<a href="\/' + self.dataSet[j].Url + '" >';
							string += self.dataSet[j].Name + '<\/a><\/li>';
							$(self.target_node).append(string);
						}
					}
					if (typeof callback === 'function') {
						callback();
					}
				},
				error: function (jqXHR, textStatus, errorThrown) {}
			});
		} else {
			$(self.target_node).append("<p>You haven't viewed anything yet. Check out some of our great recipes</p>");
		}
	},
	set_data: function (nameValue) {
		if (!nameValue) {
			return;
		}

		//this.settings.recipeIDs=[];
		if (this.settings.recipeIDs === null) {
			this.settings.recipeIDs = [nameValue];
		}

		//do we have a duplicate?
		//no
		if (!this.duplicates(nameValue)) {
			this.settings.recipeIDs.unshift(nameValue);
		} else {//yes
			this.reorder();
		}

		// addition create more than desired?
		if (this.settings.recipeIDs.length > this.settings.maxL) {
			this.pop_element();
		}
		//now set the data in LocalSotrage
		$.jStorage.set(this.settings.key, this.settings.recipeIDs);
	},
	duplicates: function (nameValue) {
		var i = 0;
		for (i; i < this.settings.recipeIDs.length; i++) {
			if (_.isEqual(nameValue, this.settings.recipeIDs[i])) {
				this.settings.matchPos = i;
				return true;
			}
		}
		return false;
	},
	reorder: function () {
		var repl = this.settings.recipeIDs.splice(this.settings.matchPos, 1);
		this.settings.recipeIDs.unshift(repl[0]);
	},
	pop_element: function () {
		while (this.settings.recipeIDs.length > this.settings.maxL) {
			this.settings.recipeIDs.pop();
		}
	}
};

AllBran.Data.premade = {
	quickNeasy : [15601, 342, 6404, 5944, 1707, 488, 9192],

	ethincInspired : [15642, 5524, 15622, 1473, 15981, 5720, 2524],

	vegetarian : [11101, 11081, 5764, 6748, 6746, 6747, 6745],

	kidFriendly : [20562, 15621, 11121, 56, 6382, 19902, 17101]
};
AllBran.Menu = {
	dow: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
	selectedMenu: AllBran.Data.premade[$('#preMade').val()],
	currentMenu: [],
	equalize: function (jqset) {
		var mHeight = 0;
		var $this = jqset;
		$this.css('height', '');
		$this.each(function () {
			var $that = $(this);
			mHeight = Math.max($that.height(), mHeight);
		});
		$this.each(function () {
			var $that = $(this);
			var height = $that.height();
			var pad = mHeight - height;
			if (height) {
				$that.css('height', pad + height);
			}
		});
	},
	setDays: function () {
		var i = 0;
		for (i; i < 7; i++) {
			$('#recipeCards > div').eq(i).find('h3').text(AllBran.Menu.dow[i]);
		}
	},
	populateMenu: function (selectedMenu) {
		$.ajax({
			url: "/Recipe.aspx/GetJSON",
			type: "POST",
			data: {
				RecipeIDs: AllBran.Menu.selectedMenu,
				width: 100
			},
			success: function (recipes) {
				var i = 0;
				for (i; i < recipes.length; i++) {
					AllBran.Menu.currentMenu[i] =  recipes[i];
				}
				i = 0;
				var sel = $('#recipeCards > div');
				var len = $(sel).length;
				var counter = 0;
				for (i; i < len; i++) {
					var $this = $(sel).eq(i);
					$this.find('div').eq(1).attr('recipeid', AllBran.Menu.currentMenu[i].RecipeID);
					$this.find('img').attr('src', AllBran.Menu.currentMenu[i].ImageUrl);
					$this.find('p').text(AllBran.Menu.currentMenu[i].Name);
				}
				AllBran.Menu.equalize($('#recipeCards > div >div'));
				AllBran.Menu.setDays();
				AllBran.Menu.currentMenu = [];
				$('#recipeCards div > div > div').each(function () {
					var $this = $(this);
					AllBran.Menu.currentMenu.push($this.attr('recipeid'));
				});
				$('#RecipeIDs').attr('value', AllBran.Menu.currentMenu.toString());
			},
			error: function (jqXHR, textStatus, errorThrown) {
			}
		});
	},
	addDrag: function () {
		$('.tab-content li').draggable({
			appendTo: 'body',
			containment: 'window',
			delay: 50,
			helper: 'clone',
			revert: false,
			revertDuration: 250,
			scroll: false,
			zIndex: 35000,
			drag: function (e, ui) {},
			start: function (e, ui) {
				if (!$('.ie7, .ie8').length ){
					$(this).css('opacity', '.5');
				}
			},
			//e= dragstart
			//ui.helper
			//ui.offset
			//ui.originalPosition
			//ui.position
			stop: function (e, ui) {
				if (!$('.ie7, .ie8').length ){
					$(this).css('opacity', '1');
				}
			}
		});
	}
};

$(document).ready(function () {
	$('#Story_FirstName').attr('title', 'Your first name');
	$('#email').attr('title', 'Your e-mail address');
	$('#email2').attr('title', 'Confirm e-mail address');


	//title attr swap
	$('#Story_FirstName, #email, #email2, .storyArea textarea').bind('focus', function () {
		$('this').attr('value') === $('this').attr('title') ? $('this').val($('this').attr('title')) : $('this').val($('this').attr('value'));
		if ($(this).val() === $(this).attr('title')) {
			$(this).val("");
		}
	});

	$('#Story_FirstName, #email, #email2, .storyArea textarea').bind('blur', function () {
	//swap out
		var cont = $(this).val();
		if (cont === "") {
			$(this).val($(this).attr('title'));
		}
	});

	$('#story, #story_Body, .storyArea textarea').charCounter(160, {
		container: "div.storyArea p",
		format: "%1 characters",
		formatOver: "<span class=\"red\">-%1 </span>characters",
		formatZero: "0 characters",
		trim: false,
		pulse: false,
		delay: 50
	});

	/*tracking*/
	
	$('p.signup a img').click(function () {
		BGC.track("/7-day-promise/sign-up");
	});

});
