try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

$(function() {
	// Google Analytics
	var pageTracker = _gat._getTracker("UA-291171-5");
	pageTracker._initData();
	pageTracker._trackPageview();
	
	// External Link
    var allowedDomains = [location.hostname, "besthealthmag", "http://besthealthmag", "rd.ca/bh"];
	$("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;
		})
		.attr('target', '_blank');
	
	// For file manager
	$("a[@href*=uploads/filemanager]").attr('target', '_blank')

	// Rollover on table row & Stripe table
	$("#col1 div.content_pad table:not(.layout) tr")
		.hover(function(){ $(this).addClass("hover"); },
			   function(){ $(this).removeClass("hover"); })
		.filter(':odd').addClass("odd");
	
	// Rollovers for Input
	$("input.rollover")
		.bind('mouseover', function(){this.src = this.src.replace(/(?:_o)?\.([a-z1-9]*)$/i,"_o.$1"); })
		.bind('mouseout',  function(){this.src = this.src.replace(/_o\./i,".");});

	// See Articles in Other Sections
	$('#frm_pillar select').bind('change', function() {
		location.href = this.value;
	});

	// Launch Rotator
	if ($('#rotator').size()) {
		$('#rotator').rotator();
	}
	
	// NO Generic (no-ajax) Form Validation (can submit form empty)
	$('#frm_comment').formHandling({
		invalidMsg: 'Looks like you\'ve missed a field, or the email address you entered is not valid. Please try again.',
		errorContainer: 'div.errors',
		errorWrapper: '<div class="error_msg"></div>',
		titleHandler: 'h2',
		extraData: '&ajax=1',
		callback : function ($form) {
			$('input.b_submit', $form).after($('input.b_submit', $form)); // IE6 bug fix
		}
	});

	// Add javascript utilities
	$('ul.utilities a').bind("click", function(event){
		var size, which = $(this).attr("class").replace('b_', '');
		switch (which) {
			case 'facebook': size = "width=620,height=436"; break;
			case 'delicious': size = "width=725,height=400"; break;
			case 'digg': size = "width=962,height=500"; break;
			default: size = "width=500,height=500";
		}
		var my_popup = window.open($(this).attr("href"), "share_"+which, "scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no,"+size);
		if (my_popup) {my_popup.focus();}
		return !my_popup;
	});
	
	var $util = $('#col1 > ul.utilities').find('li:only-child').remove().end();
	if(window.opera && window.print) { // opera
		$util.append('<li><a href="'+location.href+'" title="'+document.title+'" rel="sidebar" class="b_favorites"><span>Add Bookmark</span></a></li>');
	}
	else if(window.external && document.all) {// ie
		$util.append('<li><a title="Add to Favorites" href="javascript:window.external.AddFavorite(location.href, document.title);" rev="sidebar" class="b_favorites"><span>Add to Your Favorites</span></a></li>');
	}

	$util.append('<li><a title="Send to a Friend" href="#" onclick="return openStf(this)" class="b_stf"><span>Send to a Friend</span></a></li>')
		 .append('<li><a title="Print this Page" href="javascript:window.print();" class="b_print"><span>Print this Page</span></a></li>');

	/*SlideShow Chooser*/
	$.easing.backout = function(x, t, b, c, d){
		var s=1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	};
	if ($('ul.slideshow_chooser').size()) {
		$('ul.slideshow_chooser').scrollShow({
			itemSize: {height:'auto', width:122},
			view:'.view',
			content:'.images',
			easing:'backout',
			navigators:'a[class^="slide"]',
			scollBy: 3,
			start:0
		});
	}
	
	/* Comment form */
	$('#comment.closed').each(function () {
		var $self = $(this);
		var $link = $('<a href="#comment" class="b_comment">Post a comment about this item</a>');
		$link.click(function() {
			$(this).addClass('used');
			$self.show();
			$('input', $self).eq(0).focus();
			return false;
		});
		$self.hide().before($link);
	});
	
	$('#cryptogram').click(function () {
		var now = new Date();
		$(this).attr('src', $(this).attr('src').replace(/(\?\d+)?$/, '?'+now.getTime()));
	});
	
	/* Dynamic popup menu */
	$('#menu').addClass('dyn');
	$('#menu li').hover(
		function() {
			$(this).addClass('hover');
			$('div.dynmenu', this).show();
		},function () {
			$(this).removeClass('hover');
			$('div.dynmenu', this).hide();
		}
	);
	$('div.bl_atozindex').hover(
		function () { $('div', this).show(); },
		function () { $('div', this).hide(); });
});

function openStf(self) {
	var $popup = createPopup('stf');
	var form = '<form action="/stf" method="post" id="frm_stf">'
		 + '	<fieldset>'
		 + '    <p>Know someone who\'d enjoy this page? Simply complete the fields below and click send to share it with them.</p>'
		 + '		<ol>'
		 + '			<li>'
		 + '				<label for="stf_name">Your Name<span class="label_info"> *</span></label>'
		 + '				<input name="stf_name" id="stf_name" class="v-mandatory" value="" maxlength="36" />'
		 + '			</li>'
		 + '			<li>'
		 + '				<label for="stf_email">Your Email<span class="label_info"> *</span></label>'
		 + '				<input name="stf_email" id="stf_email" class="v-mandatory v-email" value="" maxlength="36" />'
		 + '			</li>'
		 + '			<li>'
		 + '				<label for="stf_fname">Friend\'s Name<span class="label_info"> *</span></label>'
		 + '				<input name="stf_fname" id="stf_fname" class="v-mandatory" value="" maxlength="36" />'
		 + '			</li>'
		 + '			<li>'
		 + '				<label for="stf_femail">Friend\'s Email<span class="label_info"> *</span></label>'
		 + '				<input name="stf_femail" id="stf_femail" class="v-mandatory v-email" value="" maxlength="36" />'
		 + '			</li>'
		 + '			<li>'
		 + '				<label for="stf_comments">Comments<span class="label_info"> (&nbsp;<span class="counter">max of </span><span class="max">2000</span>&nbsp;characters&nbsp;)</span></label>'
		 + '				<textarea name="stf_comments" id="stf_comments" cols="30" rows="5"></textarea>'
		 + '			</li>'
		 + '		</ol>'
		 + '	</fieldset>'
		 + '	<div class="actions">'
		 + '		<input type="image" value="Send" class="b_send rollover" src="/img/en/b_send.gif" />'
		 + '	</div>'
		 + '</form>';
	$('div.wrapper', $popup)
		.prepend('<h1>Send this page</h1>')
		.find('.content').append(form);
		
	$('form', $popup).formHandling({
		invalidMsg: 'Looks like you\'ve missed a field, or the email address you entered is not valid.<br />Please try again.',
		extraData: '&stf_path='+location.href,
		callback : function ($form) {
			$('a.b_close', $form.parents('.popup')).css('position', 'absolute'); // IE6 bug fix
		}
	});

	$("input.rollover", $popup)
		.bind('mouseover', function(){this.src = this.src.replace(/\.([a-z]*)$/i,"_o.$1"); })
		.bind('mouseout',  function(){this.src = this.src.replace(/_o\./i,".");});

	// Align with the button
	var pos = $(self).offset();
	$popup.css('top', pos.top + 24)
		  .css('left', pos.left - 228);
	
	$('body').append($popup);
	$("#stf_name").focus();
	
	return false;
}

function createPopup(id) {
	removePopup();
	var html = '<div class="popup form_wrapper" id="'+id+'">'
		 + '  <div class="top"></div>'
		 + '  <div class="wrapper"><div class="content"></div></div>'
		 + '  <a class="b_close" href="javascript:removePopup(\'stf\')">Close</a>'
		 + '</div>';
	return $(html);
}

function removePopup(id) {
	if(id) {$('#'+id).remove();}
	else {$('div.popup').remove();}
}
function closePopup(id) {
	if(id) {$('#'+id).hide();}
	else {$('div.popup').hide();}
}