/* Standard Macromedia functions for rollovers */

function preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function swap_back() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function swap() { //v3.0
  var i,j=0,x,a=swap.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
/* ====================================================================================== */
/* jQuery document-is-ready function. Place all calls here */
jQuery(document).ready(function() {

//	$("a[rel^='prettyPhoto']").prettyPhoto();
	$("a[rel^='prettyPopin']").prettyPopin({
		width:600
	});
	
	//preloadImages('images/mb_brands_f2.png','images/mb_campaigns_f2.png');
	
	// ============================================================
	// Activate our Superfish dropdown main menu, a la jQuery ;)
	jQuery('ul.sf-menu').superfish();

	// STUPID IE!!!!!!!!!!!!!!!
	// Blasted browser keeps collapsing the shorter article div even though the
	// submenu div is taller. This line copies height from submenu to article
	// to stop this action!!!
	if($("#article").height() < $("#left").height())
		$("#article").height($("#left").height());
	
	// ============================================================
	$("#print_button").click(function(e) {
		e.preventDefault();
		window.print();
	});
	// ============================================================
	// convert our taEmail class of links from a standard email link
	// to a non-clickable version. But on click, convert it back!
	$(".taEmail").each(function() {
		var newhref = this.href.replace(/%20at%20/,"@");
		//alert(newhref);
		$(this).attr("href",newhref);
	});
	$(".taEmail").click(function() {
		var newhref = this.href.replace(/%20at%20/,"@");
		//alert(newhref);
		$(this).attr("href",newhref).click();
	});

	// ============================================================
	$("#signup").submit(function(e){
     				
		// stop normal link click
		e.preventDefault();

		// send request
		if(this.signup_email.value != "Email address" && this.signup_email.value != "" && this.signup_name.value != "First name" && this.signup_name.value != "") {
			$("#signup_status").empty().addClass("ajax-loading");
			
			$.post("newsletterSignup.php", {signup_email:$("#signup_email").val(),signup_name:$("#signup_name").val()}, function(result) {
				// format and output result. fadeTo(3000,1) simulates delay(), which isn't in jQuery
				$("#signup_status").html(result).show("fast").fadeTo(3000,1).hide("fast");
				$("#signup_status").removeClass("ajax-loading");
			});
		}
	});
	// ============================================================
	// First quote is random
	var hcount = 12;
	var header_number = Math.floor(Math.random()*hcount);

	if($(".dynamic_header")) {
		// show first quote
	//	$(".dynamic_header img").fadeOut("fast",function(){$(this).attr("src",getHeader()).fadeIn("fast");});
		// Pick a quote from our array
		function getHeader() {
			header_number++
			//$('h1').html("header_" + ((header_number % hcount) + 1 ) + ".jpg");
			return "/Filestore/HeaderImages/header_" + ((header_number % hcount) + 1 ) + ".jpg";
		}
		// Loop and get another quote at a regular interval
		$.timer(14000,function(timer) {
			$(".dynamic_header img").fadeOut("fast",function() {
				$(this).attr("src",getHeader()).fadeIn("fast");
			})
		});
	}
	// ============================================================
	if($("#homepage_image")) {
		$("#homepage_image").cycle({speed:1000,timeout:5000});
	}

	

	// ============================================================
	// Font Resize methods. Provide 3 links with classes 
	// .resetFont, .increaseFont, decreaseFont. Size is saved in a 
	// Cookie (requires jqery.cookie.js as well as jquery.js)
	// Set size of body {} font
	// ------------------------------------------------------------
	var originalFontSize = '13px';//$('body').css('font-size');
	var originalFontSizeNum = parseFloat(originalFontSize);
	var cookie_name = 'textsize';
/*	
	if($.cookie(cookie_name))
		$('body').css('font-size', $.cookie(cookie_name));
	else
		$('body').css('font-size', originalFontSize);
*/
	// ------------------------------------------------------------
	// Reset Cookie
	$(".resetFont").click(function() {
		$('body').css('font-size', originalFontSize);
		$.cookie(cookie_name, null);
	});
	
	// ------------------------------------------------------------
	// Increase Font Size
	$(".increaseFont").click(function(){
		var currentFontSize = $('body').css('font-size');
		var currentFontSizeNum = parseFloat(currentFontSize);
		if(currentFontSizeNum < 20) {
			var newFontSize = currentFontSizeNum*1.2;
			$('body').css('font-size', newFontSize);
			$.cookie(cookie_name, newFontSize);
		}
		return false;
	});
	// ------------------------------------------------------------
	// Decrease Font Size
	$('.decreaseFont').click(function(){
		var currentFontSize = $('body').css('font-size');
		var currentFontSizeNum = parseFloat(currentFontSize, 10);
		if(currentFontSizeNum > 8) {
			var newFontSize = currentFontSizeNum*0.8;
			$('body').css('font-size', newFontSize);
			$.cookie(cookie_name, newFontSize);
		}
		return false;
	});

});


function twuSetTheme() {
	var originalFontSize = "13px";
	var originalFontSizeNum = parseFloat(originalFontSize);
	var cookie_name = 'textsize';
	
	if($.cookie(cookie_name))
		$('body').css('font-size', $.cookie(cookie_name) + "px");
	else
		$('body').css('font-size', originalFontSize);
}

// *************************************************************************
 jQuery.timer = function (interval, callback)
 {
 /**
  *
  * timer() provides a cleaner way to handle intervals  
  *
  *	@usage
  * $.timer(interval, callback);
  *
  *
  * @example
  * $.timer(1000, function (timer) {
  * 	alert("hello");
  * 	timer.stop();
  * });
  * @desc Show an alert box after 1 second and stop
  * 
  * @example
  * var second = false;
  *	$.timer(1000, function (timer) {
  *		if (!second) {
  *			alert('First time!');
  *			second = true;
  *			timer.reset(3000);
  *		}
  *		else {
  *			alert('Second time');
  *			timer.stop();
  *		}
  *	});
  * @desc Show an alert box after 1 second and show another after 3 seconds
  *
  * 
  */
	var interval = interval || 100;

	if (!callback)
		return false;
	
	_timer = function (interval, callback) {
		this.stop = function () {
			clearInterval(self.id);
		};
		
		this.internalCallback = function () {
			callback(self);
		};
		
		this.reset = function (val) {
			if (self.id)
				clearInterval(self.id);
			
			var val = val || 100;
			this.id = setInterval(this.internalCallback, val);
		};
		
		this.interval = interval;
		this.id = setInterval(this.internalCallback, this.interval);
		
		var self = this;
	};
	
	return new _timer(interval, callback);
 };
// *************************************************************************
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.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;
    }
};