$(function(){
/*  ------------------------------------------------------------------
    JavaScript Disabled Warning -------------------------------------- */
	$("body").css("margin-top","0");

/*  ------------------------------------------------------------------
    Browser IE6 ------------------------------------------------------ */
	var isIE6 = false;
	if($.browser.msie && $.browser.version < 7){ var isIE6 = true; }

/*  ------------------------------------------------------------------
    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'):not('.notxt')")
	.bind("focus",function(){ if(this.value==this.title){ this.value=""; } })
	.bind("blur",function(){ if(this.value==""){ this.value=this.title; } });

/*  ------------------------------------------------------------------
    Send to a Friend ------------------------------------------------- */
	$("#b_stf").bind("click", function(){
		location.href = $(this).attr("href");
		if($("#stf").css("display")=="none"){
			openSTF(this.href, $(this).attr("rel"));
		}else{
			closeSTF('#stf');
		}
		return false;
	});
	
/*  ------------------------------------------------------------------
    Stripe Tables ---------------------------------------------------- */
	$("tr:even", "table.tb_default").addClass("even");
	
/*  ------------------------------------------------------------------
    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").bind("click", function(){
		location.href = "#utilities-share-" + $(this).attr("rel");
		window.open(this.href, 'pop_'+$(this).text(), popFeatures);
		return false;
	});
	
/*  ------------------------------------------------------------------
    Font Switcher ---------------------------------------------------- */
	$("#fontswitcher").switchSize();
	
/*  ------------------------------------------------------------------
    Search onSubmit -------------------------------------------------- */
	$("#frm_search").bind("submit", function(){
		if($("#searchtext").val()==$("#searchtext").attr("title")){
			return false;
		}
	});
	
/*  ------------------------------------------------------------------
    External Link ---------------------------------------------------- */
    var allowedDomains = [location.hostname];
	$("a[href^=http]:not(.internal):not([rel^='popup'])")
	.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);
	});
	
/*  ------------------------------------------------------------------
    Popup ------------------------------------------------------------ */
	$("a[rel^='popup']").bind("click", function(){
		rel = $(this).attr("rel");
		rel = rel.replace("popup", "").split("x");
		w   = rel[0];
		h   = rel[1];
		return !window.open(this.href, 'pop_'+$(this).text(), "location=1, status=1, scrollbars=1, menubar=1, toolbar=1, width="+w+", height="+h);
	});


/*  ------------------------------------------------------------------
    Fix IE6 Hover ---------------------------------------------------- */
	if($.browser.msie && $.browser.version < 7){
		/*Submenu*/
		$(".withsub", "#m1").hover(
			function (){ $(this).addClass('withsub_hover'); },
			function (){ $(this).removeClass('withsub_hover'); }
		);

		/*Filters Dropdowns*/
		$(".articles_filter_dd").hover(
			function (){ $(this).addClass('articles_filter_dd_hover'); },
			function (){ $(this).removeClass('articles_filter_dd_hover'); }
		);
	}

/*  ------------------------------------------------------------------
    Tispy tooltip ---------------------------------------------------- */
    $('[rel=tooltip]').tipsy({gravity:'s', opacity:1});

/*  ------------------------------------------------------------------
    Slider ----------------------------------------------------------- */
	$('.list_slidable').anythingSlider({ });

/*  ------------------------------------------------------------------
    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*/
			};		
		});
	}
});


/*  ------------------------------------------------------------------
    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
            }
            // CAUTION: Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            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(){
					location.href = $(this).attr("href");
                    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($(".layout1_col1").is("div")){ $stf.addClass('loaded').insertBefore('.layout1_col1:first'); }
				else{ $stf.addClass('loaded').insertBefore('#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);
			}
		}
	}


