/*  ------------------------------------------------------------------
    Browser IE6 ------------------------------------------------------ */
	var isIE6 = false;
	var isOP  = false;
	if($.browser.msie && $.browser.version < 7){ var isIE6 = true; }
	if($.browser.opera){ var isOP = true; }

$(function(){		   
/*  ------------------------------------------------------------------
    JavaScript Disabled Warning -------------------------------------- */
	$("#container").css("margin-top","0");
	
/*  ------------------------------------------------------------------
    AJAX ------------------------------------------------------------- */
	$("#ajax_loading")
	.ajaxStart(function(){ $(this).show(); $("body").css("cursor", "wait");    })
	.ajaxStop(function() { $(this).hide(); $("body").css("cursor", "default"); });

/*  ------------------------------------------------------------------
    Remove default value on Focus ------------------------------------ */
	$("input[@type*='text'][title]:not('.required')")
	.bind("focus",function(){ if(this.value==this.title){ this.value=""; } })
	.bind("blur",function(){ if(this.value==""){ this.value=this.title; } });

/*  ------------------------------------------------------------------
    ScrollTo Anchor -------------------------------------------------- */
    var target = location.hash && $(location.hash)[0]; 
    if(target) { $.scrollTo(target, {speed:1000}); }

/*  ------------------------------------------------------------------
    Footer - Main Sites ---------------------------------------------- */
	$("a", ".mainother").hover(
		function(){ $(this).siblings("p").show(); },
		function(){ $(this).siblings("p").hide(); }
	);

/*  ------------------------------------------------------------------
    Tags Corners ----------------------------------------------------- */
	$("a", "ul.list_tags li").corners();
		
/*  ------------------------------------------------------------------
    Send to a Friend ------------------------------------------------- */
	$("#b_stf").bind("click", function(){
		if($("#stf").css("display")=="none"){
			openSTF(this.href, $(this).attr("rel"));
		}else{
			closeSTF('#stf');
		}
		return false;
	});

/*  ------------------------------------------------------------------
    External Link ---------------------------------------------------- */
    var allowedDomains = [location.hostname];
	$("a[href^=http]:not(.internal)")
	.filter(function(el){
		for ( var i=0; i < allowedDomains.length; i++ ) {
			if ( this.href.indexOf(allowedDomains[i])>-1 ) return false;
		}
		return true;
	})
	.bind("click", function(){ return !window.open(this.href); });

/*  ------------------------------------------------------------------
    Sharing Utilities Popup ------------------------------------------ */
	var popFeatures = "scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no,width=700,height=400";
	$("a:not(a[id='b_stf'])", "#list_sharing, #list_sharing_encyclopedia").bind("click", function(){
		window.open(this.href, 'pop_'+$(this).text(), popFeatures);
		return false;
	});

/*  ------------------------------------------------------------------
    Remove default value on Focus ------------------------------------ */
	/*First H2 in list_tabs_content*/
	$("h2:not('.hide_a'):first, h3.h2:first", ".list_tabs_content > div").addClass("first");
	
/*  ------------------------------------------------------------------
    Font Switcher ---------------------------------------------------- */
	$("#fontswitcher").switchSize();

/*  ------------------------------------------------------------------
    Search onSubmit -------------------------------------------------- */
	$("#frm_search").bind("submit", function(){
		if($("#searchtext").val()==$("#searchtext").attr("title")){
			return false;
		}
	});
	
/*  ------------------------------------------------------------------
    Search Top options ----------------------------------------------- */
	$('input[name="searchfilter"]', '#frm_search').change(function() {
		$('#frm_search').attr('action', this.value);
	});
	
/*  ------------------------------------------------------------------
    Utilities -------------------------------------------------------- */
	$("#utilities").show();
	var utilities_marginright = $("#utilities").css("margin-right");
	var expanded = false;
	var closeTimeUtilities = false;
	var closeUtilities = false;

	$("#utilities_icon").click(function(){
		if(expanded){
			expanded = false;
			if(isIE6){
                $("#utilities").css("width", "38px");
                $("#utilities_options").hide();				
			}else{
				$("#utilities").animate({marginRight:utilities_marginright}, 'normal', 'swing');	
			}
		}else{
			expanded = true;
			if(isIE6){
                $("#utilities").css("width", "283px");
                $("#utilities_options").show();
			}else{
				$("#utilities").animate({marginRight:'0px'}, 'normal', 'swing');
			}
		}
	});
	if(!isIE6){
		$("#utilities").mouseenter(function(){
			if(expanded == false){
				expandUtilities = window.setTimeout(function (){
					expanded = true;					
					$("#utilities").animate({marginRight:'0px'}, 'normal', 'swing');
				},1000);/*Time in ms before expanding after the mouseenter*/
			}else{
				expanded = true;
				if(closeTimeUtilities){window.clearTimeout(closeTimeUtilities);}
				if(closeUtilities){window.clearTimeout(closeUtilities);}
			}
		});
		$("#utilities").mouseleave(function(){
			window.clearTimeout(expandUtilities);
			if(expanded){
				closeTimeUtilities = window.setTimeout(function (){
					expanded = false;
					closeTimeUtilities = false;
				},1000);/*Time in ms before being able to expand again after the mouseleave*/			
				closeUtilities = window.setTimeout(function (){					
					$("#utilities").animate({marginRight:utilities_marginright}, 'normal', 'swing');
				},1000);/*Time in ms before closing after the mouseleave*/
			};		
		});
	}
	
/*  ------------------------------------------------------------------
    Dock Milk Products ----------------------------------------------- */
	$('#m2_wrap').removeClass("noscript");
	$('#m2_wrap').Fisheye({
		maxWidth: 15,
		items: 'a',
		itemsText: 'span',
		container: '#m2',
		itemWidth: 55,
		proximity: 40,
		alignment : 'left',
		valign: 'bottom',
		halign : 'center'
	});
	
	/* Hover Fix 
	var getPointerBackup;
	var disableGetPointer = function() { return {x:-1000, y:-1000}; }
	
	$("#header, #content").mouseenter(function(){
		getPointerBackup = jQuery.iUtil.getPointer;
		jQuery.iUtil.getPointer = disableGetPointer;
	}).mouseleave(function(){
		jQuery.iUtil.getPointer = getPointerBackup;
	});*/
});


/*  -----------------------------------------------------------------------
	Resize Photos --------------------------------------------------------- */
	$.fn.resizePhoto = function(options) {
		return this.each(function() {
			oriRatio     = options.oriWidth / options.oriHeight;
			diff	     = options.oriWidth - options.minWidth;
			resizeHeight = options.resizeHeight;
			
			if($.browser.msie && $.browser.version < 7){ $objInside = $("img", this); }
			else{ $objInside = $(this); }

			if(bodyInnerWidth>=1000){
				if(bodyInnerWidth<1219){
					xtra  = 1219 - bodyInnerWidth;
					prcnt = 1 - (xtra / 218);
					addition = prcnt * diff;
					
					$objInside.width(options.minWidth + addition);
					if(resizeHeight){ $(this).height((options.minWidth + addition) / oriRatio);	}
				}else{
					$objInside.width(options.oriWidth);
					if(resizeHeight){ $(this).height(options.oriHeight); }
				}
			}else{
				$objInside.width(options.minWidth);
				if(resizeHeight){ $(this).height(options.minHeight); }
			}
		});  
	};


/*  -----------------------------------------------------------------------
	Smart Columns --------------------------------------------------------- */
	$.fn.smartColumns = function(options) {
		return this.each(function() {
			$list = $(this);
			$list.css({'width':"100%"});

			var colWrap = $list.width();
			var colNum = Math.floor(colWrap / 240);
			var colFixed = Math.floor(colWrap / colNum);
			var rowFixed = Math.floor(colFixed / 1.36) -1;

			$list.css({'width':colWrap});
			$("li", $list).css({'width':colFixed, 'height':rowFixed });

			if($list.hasClass("list_smartcolumns_onerow")){ $($list).css({ 'height': rowFixed}); }
		});  
	};


/*  ------------------------------------------------------------------
Vertical Align --------------------------------------------------- */
$.fn.verticalAlign = function() {
	return this.each(function(i){
		var ah = $(this).height();
		var ph = $(this).parent().height();
		var mh = (ph - ah) / 2;
		$(this).css('margin-top', mh);
	});
};



/*  -----------------------------------------------------------------------
	Sub Menu -------------------------------------------------------------- */
	function submenuPos(){
		//Get Window, Container Width and Sides
		var windowWidth = $(window).width();  
		var centerWidth = 960;
		var sides 		= (windowWidth - 960)/2;

		$(".withsub", "#subnav").each(function(){
			var ssmLeft = $(this).offset().left;
											   
			$(".ssm1", this).each(function(){
				var ssmWidth    = $(this).width();
				var ssmRightpos = ssmLeft + ssmWidth;
				
				//Apply only if we have multiple columns
				if(!$(this).hasClass('col1')){
					//If outside 960
					if(ssmRightpos > (centerWidth+sides)){
						$(this).css("left", "-" + (ssmRightpos-centerWidth-sides+20) + "px");
					}
				}
			});
		});
		
		/*Submenu - Fix IE6 Hover*/
		if($.browser.msie && $.browser.version < 7){
			$(".withsub", "#subnav").hover(
				function (){ $(this).addClass('withsub_hover'); },
				function (){ $(this).removeClass('withsub_hover'); }
			);
		}
	};


/*  -----------------------------------------------------------------------
	Scroll Comments ------------------------------------------------------- */
	function scrollComments() {
		$.browserOffset = 122;
		if($.browser.msie && $.browser.version == 6) {
			$.browserBelowOffset = 22; /* bigger moves down */
		} else {
			$.browserBelowOffset = 2; /* bigger moves down */	
		}

		if (!$.initialOffset) $.initialOffset = $('#comments').offset().top-10;
		$.endOffset = $('#scroll_stop').offset().top-$('#scroll_comments').height()-$.browserOffset;
		
		if ($('#comments').height() > $('#scroll_comments').height()+100) {
			$('#scroll_comments').css({position: 'absolute'});
			if ($(document).scrollTop() <= $.initialOffset+20) {
				// Above Scroll
				$('#scroll_comments').css({top: 20});
			} else {
				if ( $(document).scrollTop() <= $.endOffset) {
					// Scroll - Update current css:top value
					$('#scroll_comments').css({top: $(document).scrollTop() - $.initialOffset});
				} else {
					// Snap to bottom
					$('#scroll_comments').css({top: $(".layout4_col1").height()-$('#scroll_comments').height()+$.browserBelowOffset});
				}
			}
		}else{
			$('#scroll_comments').css({position: ''});
		}
	}


/*  -----------------------------------------------------------------------
	Rounded Corners ------------------------------------------------------- */
	$.fn.corners = function(options) {
		return this.each(function() {
			$(this).append('<span class="c_tl"></span><span class="c_tr"></span><span class="c_bl"></span><span class="c_br"></span>');
		});
	};
	
	
/*  ------------------------------------------------------------------
    Plugin/Cookie ---------------------------------------------------- */
    $.cookie = function(name, value, options) {
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    };


/*  ------------------------------------------------------------------
    switchSize ------------------------------------------------------- */
    function switchTextSize(size, settings) {
        if(size !== ''){
            $('body').removeClass().addClass(size);
            if (settings.saveCookie === true) {
                $.cookie('textsize', size, { expires: 365, path: '/'  });
            }
        }
    }
    $.fn.switchSize = function(settings) {
        // defaults settings
        settings = $.extend({
            saveCookie: true
        },settings);

        return this.each(function(){
            var container = this;
            var curtextsize = $.cookie('textsize');
            if (curtextsize) { $('body').removeClass().addClass(curtextsize); }

            $(this)
                .find("a")
                .bind('click', function(){
                    switchTextSize( $(this).attr("rel"), settings);
                    return false;
                });
        });
    };


/*  ------------------------------------------------------------------
    Send to a Friend ------------------------------------------------- */
	function openSTF(target, node){
		var $stf = $('#stf');

		if(!$stf.hasClass('loaded')) {
			$stf.load("/tisendtofriend/template/sendtofriend/"+node, function() {
				if($("#content.section22").is("div")){
					/*AYNIC*/
					$stf.addClass('loaded').insertBefore('#content');
				}else{
					if($("#subnav").is("div")){
						$stf.addClass('loaded').insertAfter('#subnav');
					}else{
						$stf.addClass('loaded').prependTo('#content');
					}
				}
				$.scrollTo(target, 500, { onAfter: function(){
					$stf.slideDown();
				}});
			});
		} else {
			$.scrollTo(target, 500, { onAfter: function(){
				$stf.slideDown();
			}});
		}
	};
	function closeSTF(which){
		$(which).slideUp();
		return false;
	};

	function validateSTF(errorMap, ErrorList) {
		var messages = '';
		var countErrors = 0;
		for (var i = 0; this.errorList[i]; i++) {
			var error = this.errorList[i];
			this.settings.highlight && this.settings.highlight.call(this, error.element, this.settings.errorClass, this.settings.validClass);
			if((error.element.id == 'frm_stf_your_email' && error.message != '')||(error.element.id == 'frm_stf_friends_email' && error.message != '')) {
				message = error.message;
				countErrors++;
			}
		}
		if (this.errorList.length) {
			if(this.errorList.length == countErrors && message){
				this.containers.find(".stf_required").html(message).show();
				this.containers.find(".stf_generic").hide();
			}else{
				this.containers.find(".stf_required").hide();
				this.containers.find(".stf_generic").show();
			}
		} 
		if (this.settings.unhighlight) {
			for (var i = 0, elements = this.validElements(); elements[i]; i++) {
				this.settings.unhighlight.call(this, elements[i], this.settings.errorClass, this.settings.validClass);
			}
		}
	}


/*  ------------------------------------------------------------------
    Register / Forgot Password --------------------------------------- */
	function toggleForgotPassword(obj){
		if(!$("#frm_div_forgotpassword").is("div")){
			$.ajax({
				type: "POST",
				url: "/layout/set/ajax/" + $(obj).attr("href"),
				success: function(msg){
					if(!$("#frm_div_forgotpassword").is("div")){
						$('<div id="frm_div_forgotpassword"></div>').insertAfter("#frm_div_login");
						$("#frm_div_forgotpassword").html(msg).toggle();
						$("#frm_div_login").toggle();
					}
				}
			});
		}else{
			$("#frm_div_forgotpassword").toggle();
			$("#frm_div_login").toggle();
		}
	}
	
	function submitForgotPassword(obj){
		userEmail = $("#UserEmail").val();
		$.ajax({
			type: "POST",
			data: "GenerateButton=&UserEmail=" + userEmail,
			url: "/layout/set/ajax/" + $(obj).attr("action"),
			success: function(msg){
				$("#frm_div_forgotpassword").html(msg);
			}
		});
	}
	
	
/*  -----------------------------------------------------------------------
	Recipe Rating --------------------------------------------------------- */
	function recipeRankTop(obj){
		$obj    = $(obj);
		obj_rel = $obj.attr("rel");
		obj_rel = obj_rel.split("/");
		recipe_id      = obj_rel[0];
		recipe_version = obj_rel[1];
		top_rated_url  = $obj.siblings(".b_recipetopratedlink").attr("href");
		top_rated_url  = top_rated_url.replace(/\//g, "::");

		$.ajax({
			type: "POST",
			url: "/layout/set/ajax/favorite/collect/ContentObjectAttributeID/"+recipe_id+"/version/"+recipe_version+"/top_rated_url/"+top_rated_url,
			success: function(msg){
				$obj.parents(".boxdotted_content:first").html(msg);
			}
		});
		return false;
	}


/*  -----------------------------------------------------------------------
	Add Recipes and Menus to favorites ------------------------------------ */
	function addFavorites(obj){
		$obj = $(obj);
		href = $obj.attr("href");
		$.ajax({
			type: "POST",
			url: href + "/(via)/ajax",
			success: function(msg){ $obj.parent().html(msg); }
		});
		return false;
	}
	
	
/*  -----------------------------------------------------------------------
	Add recipes to Menu --------------------------------------------------- */
	function addRecipeToMenu(obj){
		$obj = $(obj);
		href = $obj.attr("href");
		menu_name = $obj.text();
		$.ajax({
			type: "POST",
			url: href + "/(via)/ajax/(menu_name)/" + encodeURI(menu_name),
			success: function(msg){
				$obj.parents('li:first').html(msg).animate({'backgroundColor' : '#ff0000'});
			}
		});
		return false;
	}
	
	
/*  ------------------------------------------------------------------
    Popin - Simple Modal --------------------------------------------- */
	/*Default Parameters*/
	$.extend($.modal.defaults, {
		opacity: 50,
		overlayClose: true,
		focus: false,
		onOpen: function (dialog) {
			dialog.overlay.fadeIn('fast', function () {
				dialog.data.hide();
				dialog.container.fadeIn('fast');
				dialog.data.fadeIn('fast');
			});
		},
		onClose: function (dialog) {
			dialog.data.fadeOut('fast');
			dialog.container.fadeOut('fast', function () {
				dialog.overlay.fadeOut('fast', function(){$.modal.close(); });
			});
		}
	});

	function createPopin(size, style, arrow, portion){
		size  = size  ? size  : "medium"; /* options: tiny, small, medium, large, xlarge, full */
		style = style ? style : "lightpink"; /* options: lightpink, lightgrey, pink85 */
		arrow = arrow ? arrow : false; /* options: true or false */
		
		popin  = '';
		if(portion=="start"){
			if(isIE6){
				popin += '<div class="pi_ie6 pi_'+style+' pi_'+size+'">';
			}else{
				popin += '<div class="pi pi_'+style+' pi_'+size+'">';
				popin += '	<div class="pi_wrap">';
				popin += '		<div class="pi_t"></div>';
				popin += '		<div class="pi_content">';
			}
		}else{
			if(isIE6){
				popin += '</div>';
			}else{
				popin += '		</div>';
				popin += '	</div>';
				popin += '	<div class="pi_b"><div></div></div>';
				if(arrow){ popin += '  <div class="pi_arrowd"> </div>'; }
				popin += '</div>';
			}
		}
		return popin;
	}


/*  ------------------------------------------------------------------
    Menu Star Rating ------------------------------------------------- */
	var fadeout_txt;
	function rate_menu(e){
		$.ajax({
			type: "POST",
			url: $(this).attr("href") + "/(via)/ajax",
			success: function(msg){
				var msg_split = msg.split("-");				
				clearTimeout(fadeout_txt);
				// freeze the stars to the user's rating
				$('#ezsr_user_rating_' + msg_split[0] + ' a').removeClass('rated');
				$('#ezsr_user_rating_' + msg_split[0] + ' a.ezsr-stars-' + msg_split[2]).addClass('rated');
					
				//generate the community rate
				$('#ezsr_rating_' + msg_split[0] + ' a').css('width', msg_split[1] + '%' );
				$('.rating_thanks').show(1, function(){
						fadeout_txt = setTimeout(function() {
							$('.rating_thanks').fadeOut("slow");
						}, 2000);
				});
			}			
		});
		return false;
	}


/*  ------------------------------------------------------------------
    Dropdown --------------------------------------------------------- */	
	$.fn.dropdown = function(options) {
		return this.each(function() {
			var $box = $(this);
			
			/* Open/Close the dropdown */
			$box.find(".b_dd").bind("click", function(e){
				$box.children(".boxdotted_dd:first").toggle();
				if($box.children(".boxdotted_dd:first").children(".boxdotted_dd_content:first").children(".ajax_loading_small").is("span")){
					$box.children(".boxdotted_dd:first").children(".boxdotted_dd_content:first").load($(this).attr("href"));
				}
				e.stopPropagation();
				return false;
			});
			
			/* Close the dropdown when clicking outside */
			$(document).bind("click", function(){
				$box.find(".boxdotted_dd").hide();
			});
			
			/* Stop propagation of click in dropdown */
			$box.find(".boxdotted_dd").bind("click", function(e){
				e.stopPropagation();
			});
		});  
	};
	function closeDropdown(obj){
		$(obj).parents(".boxdotted_dd:first").hide();
	}


/*  ------------------------------------------------------------------
    Menu Sliders ----------------------------------------------------- */
	function formatText(index, panel) {
		return index + "";
	}