/*********************************************
	Fruit2day 

	Authors: Joel Nagy & Tara Milone | dotglu
	Last Modified: July 21st, 2009 15:59:47 PM EST

	Dependency: jQuery

**********************************************/

// GLOBAL CONSTANTS --------------------------/
var MOZ = $.browser.mozilla;
var MSIE = $.browser.msie;
var OPERA = $.browser.opera;
var BROWSER_VERSION = $.browser.version;
var MAC = false;
var WIN = false;

var _CurrentMouseover = null;
var _Speed = 250;
var _CurrentNavTimer = null;
var _CurrentNavTimeset = '';

var _TAF = new Array();

//TOGGLE NUTRITIONAL INFORMATION ON PRODUCT PAGES
function showNutrition(id, scrollTo) {
	var $v = jQuery('#nutrition'+ id);
	var $l = jQuery('#nutritionlink'+ id);
	var $scroll = scrollTo? jQuery(scrollTo): $l;
	
	$v.slideToggle('normal', function() {
		var h = $l[0].innerHTML;
		if (h.indexOf('For') >= 0) {
			$l[0].innerHTML = 'To hide Nutrition Information and ingredients, click here';
			$('html, body').animate({ scrollTop: $scroll.offset().top }, 600);//SCROLL EFFECT
		} else {
			$l[0].innerHTML = 'For Nutrition Information and ingredients, click here';
		}
	});
	$l[0].blur();
}
//PRODUCTS LANDING PAGE ANIMATION
$(document).ready(function(){	
	// on mouseover of .productsbottle find all other .productsbottle that are not with same id
	$(".productsbottle")
	.mouseover(function() {
		var $t = $(this);
		var id = $t.attr('id');

_CurrentMouseover = id;
		// Set self to opaque
		$("#"+ id)
		.animate({opacity: "1"}, _Speed);
		// Set siblings to transparent
		$(".productsbottle").not("#"+ id)
		.animate({opacity: "0.5"}, _Speed);
		
		// Set .productsname to hover state
		$("#"+ id +"Nav")
		.css('background-position', '0 0');
	})
	.mouseout(function() {
		var $t = $(this);
		var id = $t.attr('id');

		$("#"+ id +"Nav")
		.css('background-position', '0 0');

		_CurrentMouseover = null;
		// if we are not over another sibling, then reset all to opaque
		setTimeout('if (_CurrentMouseover == null) $(".productsbottle").not("#'+ id +'").animate({opacity: "1"}, '+ _Speed +');', 400);
	});
	

/** // Make the CTA Arrows work on mouseover in IE 6
if ($.browser.msie && $.browser.version < 7) { // only IE < 7
	$('.forHoverArrow A.png').parent('.pngwrap').
	mouseover(function () {
		var $t = $(this);
		$t.css("clip", "rect(-10px 0px 10px 0px)");
$t.css("border-bottom", "1px solid red");
	});
}
**/

	// Prep outoging links for tracking
	$('a').each(function() {
		var lnk = '';
		try {
			var $t = $(this);
			var href = $t.attr('href');
			if (href != null && href != '' && href.indexOf('://') > 0 && href.indexOf('.fruit2day.') < 0) {
				lnk = '/outgoing/'+ href;
		        $t.attr('lnk', 'outgoing');
			} else 	if (href != null && href != '' && href.indexOf('mailto:') >= 0 && href.indexOf('.fruit2day.') < 0) {
				lnk = '/mailto/'+ href.slice('mailto:'.length);
				$t.attr('lnk', 'mailto');
			}
		} catch (e) { }
		if (lnk != '')
			$t.click(function() { try { pageTracker._trackPageview(lnk); } catch (e) { } });
	});
	
	// Prep Drop Down Menus
	$('UL>LI>A').each(function() {
		var $t = $(this);
		// if there are siblings
		$S = $t.siblings();
		if ($S != null && $S.length > 0 && $S[0].tagName == 'UL') {
			// here we add the mouseover and mouseout to the parent of the submenu (sibling A of the UL)
			$t.mouseover(function () {
				var $s = $t.siblings();
				if ($s != null && $s.length > 0 && $s[0].tagName == 'UL') {
					if (_CurrentNavTimer != null && _CurrentNavTimeset != '') {
						eval(_CurrentNavTimeset);
						clearTimeout(_CurrentNavTimer);
						_CurrentNavTimer = null;
						_CurrentNavTimeset = '';
					}
					$s.css('display', 'block');
				}
			});
			$t.mouseout(function () {
				var $s = $t.siblings();
				if ($s != null && $s.length > 0 && $s[0].tagName == 'UL') {
					_CurrentNavTimeset = "$('#"+ $s[0].id +"').css('display', 'none');";
					_CurrentNavTimer = setTimeout(_CurrentNavTimeset, 500);
				}
			});

			// mouseover and mouseout to submenu links (UL UL LI A)
			$S.children('LI A').mouseover(function () {
				clearTimeout(_CurrentNavTimer);
				_CurrentNavTimer = null;
				_CurrentNavTimeset = '';
			});
			$S.children('LI A').mouseout(function () {
				var $t = $(this);
				var $p = $t.parent('UL');
				_CurrentNavTimeset = "$('#"+ $p[0].id +"').css('display', 'none');";
				_CurrentNavTimer = setTimeout(_CurrentNavTimeset, 500);
			});
		}
	});
});	

// FORMS
var ZIP_REGEXP = new RegExp(/^[0-9]{5}$/); // US ZIP
var ZIP4_REGEXP = new RegExp(/^[0-9]{5}[ -_.x+|]?[0-9]{4}$/); // US ZIP+4
var CAPOSTAL_REGEXP = new RegExp(/^[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvwxyz]{1}[0-9]{1}[ -_.x+|]?[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvwxyz]{1}[ -_.x+|]?[0-9]{1}[ -_.x+|]?[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvwxyz]{1}[0-9]{1}$/);
var EMAIL_REGEXP = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,20})+$/);
var URL_REGEXP = new RegExp(/^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$/);
var STRING_REGEXP = new RegExp(/\w+/);
var DOC_REGEXP = new RegExp(/\w+\.(doc|pdf|txt)$/i);
var IMG_REGEXP = new RegExp(/\w+\.(jpg|png|gif|jpeg)$/i);
var DIGIT_REGEXP = new RegExp(/\d+/);
var PHONE_REGEXP = new RegExp(/^[0-9]{7,25}$/);
var errorBox = '#Error'

function validateZip(F) {
	F = isString(F)? document.getElementById(F): F;
	var val = F.postal.value;
	var zip = val.match(ZIP_REGEXP);
	var postal = val.match(CAPOSTAL_REGEXP);

	if ((zip != null && zip == val) || (postal != null && postal == val)) {
		$(errorBox).css('visibility', 'hidden');
		return true;
	} else {
		$(errorBox).css('visibility', 'visible');
		return false;	
	}
}


function validateCoupon(F) {
	try {
		F = isString(F)? document.getElementById(F): F;

		if (F.receiveOffers && F.receiveOffers.checked)
			F.submit();
		else if (F.redirect) {
			window.open(F.redirect.value);
			if (F.trackingCode != null && F.trackingCode.value != '')
				clickTracker(F.trackingCode.value);
		} else
			window.location = '/';
		return true;
	} catch (e) { return true; }
}

function couponLaunch(F) {
	try {
		F = isString(F)? document.getElementById(F): F;
		if (F.coupon != null && F.coupon.value != '') {
			window.open(F.coupon.value, 'f2d_coupon');
			if (F.trackingCode != null && F.trackingCode.value != '')
				clickTracker(F.trackingCode.value);
		}
	} catch (e) { return true; }
	return true;
}

function validate(F, func) {
	try {
		F = isString(F)? document.getElementById(F): F;
		var pass = true, errors = new Array();

		switch (F.id) {
			case 'CRM':
				validateField(F.webform_first_name.value.match(STRING_REGEXP), F.webform_first_name.id, errors);
				validateField(F.webform_last_name.value.match(STRING_REGEXP), F.webform_last_name.id, errors);
				validateField(F.webform_email.value.match(EMAIL_REGEXP), F.webform_email.id, errors);
				validateField(F.webform_zip.value.match(ZIP_REGEXP) || F.webform_zip.value.match(CAPOSTAL_REGEXP), F.webform_zip.id, errors);
				validateField(F.webform_birthday_month.selectedIndex > 0, 'month', errors);
				validateField(F.webform_birthday_day.selectedIndex > 0, 'month', errors);
				validateField(F.webform_birthday_year.selectedIndex > 0, 'month', errors);
				validateField(F.webform_f2d_offers.checked, F.webform_f2d_offers.id, errors);

				// Must meet minimum age
				var MinAge = 14;
				var today = new Date();
				var month = parseInt(today.getMonth()) + 1;
				var date = parseInt(today.getDate());
				var fullyear = parseInt(today.getFullYear());
				var daysInMonth = [31,isLeapYear(fullyear)? 29: 28,31,30,31,30,31,31,30,31,30,31];
				var selYear = toInt(F.webform_birthday_year.options[F.webform_birthday_year.selectedIndex].value);
				var selMonth = toInt(F.webform_birthday_month.options[F.webform_birthday_month.selectedIndex].value);
				var selDay = toInt(F.webform_birthday_day.options[F.webform_birthday_day.selectedIndex].value);

				if (selYear.toString() == 'NaN' || selMonth.toString() == 'NaN' || selDay.toString() == 'NaN' ||
						selYear > fullyear-MinAge || /* too young based on year alone */
						(selYear >= fullyear-MinAge && selMonth > month) ||	/* too young cause they turn 13 this year, but not in this month */
						(selYear >= fullyear-MinAge && selMonth >= month && selDay > date) ||
						(selDay > daysInMonth[selMonth-1])
					) {
					// mark as error, too young
					validateField(false, F.webform_birthday_day.id, errors);
					validateField(false, F.webform_birthday_month.id, errors);
					validateField(false, F.webform_birthday_year.id, errors);
				} else {
					// no error, age validated
					validateField(true, F.webform_birthday_day.id, errors);
					validateField(true, F.webform_birthday_month.id, errors);
					validateField(true, F.webform_birthday_year.id, errors);
				}
			break;
			case 'TAFsend':
				validateField(F.webform_sender_name.value.match(STRING_REGEXP), F.webform_sender_name.id, errors);
				validateField(F.webform_sender_email.value.match(EMAIL_REGEXP), F.webform_sender_email.id, errors);
				validateField(F.webform_friend_name.value.match(STRING_REGEXP), F.webform_friend_name.id, errors);
				validateField(F.webform_friend_email.value.match(EMAIL_REGEXP), F.webform_friend_email.id, errors);
				
				if (errors.length <= 0)
					storeFields(_TAF, F, true);
			break;
		}
		// if any errors report them, otherwise send
		if (errors.length > 0)
			return indicateErrors(errors);
		else {
			if ($(errorBox)[0])
				$(errorBox).css('visibility', 'hidden');
			if (func != null)
				func(F);
			return true;
		}
	} catch (e) { return true; }
}

String.prototype.trim = function (x) {
	if (!x) x = '\s';
    return eval('this.replace(/^'+ x +'*/, "").replace(/'+ x +'*$/, "");')
}
String.prototype.ltrim = function (x) {
	if (!x) x = '\s';
    return eval('this.replace(/^'+ x +'*/, "");')
}
String.prototype.rtrim = function (x) {
	if (!x) x = '\s';
    return eval('this.replace(/'+ x +'*$/, "");')
}

function toInt(s) {
	return parseInt(s.toString().ltrim('0'));
}

function isLeapYear(year) {
	return year % 4 == 0? year % 100 == 0? year % 400 == 0? true: false: true: false;
}

function getRadioValue(radio) {
	try { 
		for (var i = 0, l = radio.length; i < l; i++)
			if (radio[i].checked) return radio[i].value;
		return '';
	} catch (e) { }
}

function isString(o) {
   	return typeof(o) == 'string';
}

function isArray(o) {
	if (o.constructor && o.constructor.toString().indexOf("Array") >= 0)
		return true;
	else
		return false;
}

function validateField(fieldmatch, field, errors) {
	// push error field IDs into array or reset the fields class
	try {
		if (fieldmatch == false || fieldmatch == null || fieldmatch == '')
			errors.push(field);
		else {
			if (!isArray(field))
				field = [field];
			for (var i = 0, l = field.length; i < l; i++) {
				f = field[i];
				$(f).removeClass('error');
				$('label[for='+ f +']').removeClass('error');
			}
		}
	} catch (e) { }
}

function indicateErrors(errors) {
	// add class 'error' to the field's label
	for (var i = 0, l = errors.length; i < l; i++) {
		var errID = errors[i];
		var forID = errors[i];
		if (errors[i].indexOf(':') > 0) { // in the event that the for is inaccurately set by the CMS wizards!!
			var ee = errors[i].split(':');
			errID = ee[0];
			forID = ee[1];
		}
		var e = $(errID);
		var f = $(forID);
		if (e != null) {
			e.addClass('error');
			$('label[for='+ forID +']').addClass('error');
			//$(document).getElements('label[for='+ forID +']').getChildren().addClass('error');
		} else if (f != null) {
			$('label[id='+ forID +']').addClass('error');
			//$(document).getElements('label[id='+ forID +']').getChildren().addClass('error');
		}
	}
	$(errors[0]).focus();
	$(errorBox).css('visibility', 'visible');
	return false;
}

function storeField(val, id, store) {
	var field = new Array();
	field.push(id);
	field.push(val);
	store.push(field);
}

function getStore() {
	var x = null, c = getCookie('taf');
	if (c && c != '') {
		eval('x = '+ c);
		if (x && isArray(x))
			for (var i = 0, l = x.length; i < l; i++) {
				var a = x[i];
				if (a.length == 2) {
					document.getElementById(a[0]).value = a[1];
				}
			}
	}
}

function storeFields(store, F, ignore) {
	ignore = ignore == null? false: ignore;
	switch (F.id) {
		case 'TAFsend':
			setCookie('taf', ''); // clear out cookie
			
			storeField(F.webform_sender_name.value, F.webform_sender_name.id, store);
			storeField(F.webform_sender_email.value, F.webform_sender_email.id, store);
			if (!ignore) {
				storeField(F.webform_friend_name.value, F.webform_friend_name.id, store);
				storeField(F.webform_friend_email.value, F.webform_friend_email.id, store);
			}
			var s = '';
			for (var i = 0, l = _TAF.length; i < l; i++)
				if (_TAF[i].length == 2)
					s += '["'+ _TAF[i][0] +'","'+ _TAF[i][1] +'"],';
			if (s != '') { 
				s = s.slice(0,s.length-1);
				s = '['+ s +']';
			}
			setCookie('taf', s, 31);
		break;
	}
}

function goback(F, url) {
	try {
		F = isString(F)? document.getElementById(F): F;
		
		storeFields(_TAF, F);

		if (url != '')
			window.location.href = url;
		else
			window.location.href = '/';
	} catch (e) { }
}

// TRACKING
function clickTracker(click) {
	try {
		var r = Math.floor(Math.random() * 10000000);
		var tag_url = "http://ad.doubleclick.net/activity;src=2212293;type=fruit503;cat=unqcl"+ click +";ord=1;num="+ r + "?";
		jQuery('body').append('<img src="'+ tag_url +'" width="1" height="1" style="visibility:hidden;opacity:0; position:absolute;z-index:999;top:0;left:0;" />');
	} catch (e) { }
}

// COOKIES
function setCookie(name, value, days) {
	var expires = "";
	if (days) {
		var D = new Date();
		D.setTime(D.getTime()+(days*24*60*60*1000));
		expires = "; expires="+ D.toGMTString();
	} else expires = "";
	document.cookie = name +"="+ value + expires +"; path=/";
}

function getCookie(name) {
	var x = new RegExp("\\b" + name + "=([^;]*)");
	var value = x.exec(document.cookie);
	return (value) ? unescape(value[1]) : "";
}

// LOAD SWF
function loadSWF(url, width, height, background, div, flashvars, func, version) {
// flashvars is an array of name|value pairs of parameters
	$(function(){ // window.ready()
///		try {
			div = div == null? 'swfbox': div;
			version = version == null? '8.0.21': version;
			// SWFObject 1.5.1
			var so = new SWFObject(url, div+'flash', width, height, version, background);
			if (background == null || background == 'transparent')
				so.addParam("wmode", "transparent");
			so.addParam("allowScriptAccess", "always");
			so.useExpressInstall('/assets/templates/f2d/swf/expressInstall.swf');
			if (flashvars != null)
				for (var i = 0, l = flashvars.length; i < l; i++) {
					if (flashvars[i].length == 2) {
						so.addVariable(flashvars[i][0], flashvars[i][1]);
					}
				}
			so.write(div);
			
			if (func)
				func();
///			} catch (e) { }
	}); //: window.ready() from loadSWF()
}

// WINDOW READY
$(function(){
	if ($('#LocatorResults').length > 0) {
		$(window).bind('resize', function() {
			var Map = $('#Map');
			if (Map.length > 0 && MSIE) {
				// unset
				Map.css('height', '3px');
				Map.css('width', '6px');
				Map.css('position', 'relative');
				Map.css('display', 'none');
				Map.css('visibility', 'hidden');
				Map.css('zoom', '50%');
				// reset
				Map.css('height', '317px');
				Map.css('width', '700px');
				Map.css('position', 'relative');
				Map.css('display', 'block');
				Map.css('visibility', 'visible');
				Map.css('zoom', '100%');
			}	
		}); //: window.resize()
	}
}); //: main window.ready()