/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

/*--------------------------------------------------------------------------*/ 
// jQuery SWFObject v1.1.1 MIT/GPL @jon_neal
// http://jquery.thewikies.com/swfobject
(function(f,h,i){function k(a,c){var b=(a[0]||0)-(c[0]||0);return b>0||!b&&a.length>0&&k(a.slice(1),c.slice(1))}function l(a){if(typeof a!=g)return a;var c=[],b="";for(var d in a){b=typeof a[d]==g?l(a[d]):[d,m?encodeURI(a[d]):a[d]].join("=");c.push(b)}return c.join("&")}function n(a){var c=[];for(var b in a)a[b]&&c.push([b,'="',a[b],'"'].join(""));return c.join(" ")}function o(a){var c=[];for(var b in a)c.push(['<param name="',b,'" value="',l(a[b]),'" />'].join(""));return c.join("")}var g="object",m=true;try{var j=i.description||function(){return(new i("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version")}()}catch(p){j="Unavailable"}var e=j.match(/\d+/g)||[0];f[h]={available:e[0]>0,activeX:i&&!i.name,version:{original:j,array:e,string:e.join("."),major:parseInt(e[0],10)||0,minor:parseInt(e[1],10)||0,release:parseInt(e[2],10)||0},hasVersion:function(a){a=/string|number/.test(typeof a)?a.toString().split("."):/object/.test(typeof a)?[a.major,a.minor]:a||[0,0];return k(e,a)},encodeParams:true,expressInstall:"expressInstall.swf",expressInstallIsActive:false,create:function(a){if(!a.swf||this.expressInstallIsActive||!this.available&&!a.hasVersionFail)return false;if(!this.hasVersion(a.hasVersion||1)){this.expressInstallIsActive=true;if(typeof a.hasVersionFail=="function")if(!a.hasVersionFail.apply(a))return false;a={swf:a.expressInstall||this.expressInstall,height:137,width:214,flashvars:{MMredirectURL:location.href,MMplayerType:this.activeX?"ActiveX":"PlugIn",MMdoctitle:document.title.slice(0,47)+" - Flash Player Installation"}}}attrs={data:a.swf,type:"application/x-shockwave-flash",id:a.id||"flash_"+Math.floor(Math.random()*999999999),width:a.width||320,height:a.height||180,style:a.style||""};m=typeof a.useEncode!=="undefined"?a.useEncode:this.encodeParams;a.movie=a.swf;a.wmode=a.wmode||"opaque";delete a.fallback;delete a.hasVersion;delete a.hasVersionFail;delete a.height;delete a.id;delete a.swf;delete a.useEncode;delete a.width;var c=document.createElement("div");c.innerHTML=["<object ",n(attrs),">",o(a),"</object>"].join("");return c.firstChild}};f.fn[h]=function(a){var c=this.find(g).andSelf().filter(g);/string|object/.test(typeof a)&&this.each(function(){var b=f(this),d;a=typeof a==g?a:{swf:a};a.fallback=this;if(d=f[h].create(a)){b.children().remove();b.html(d)}});typeof a=="function"&&c.each(function(){var b=this;b.jsInteractionTimeoutMs=b.jsInteractionTimeoutMs||0;if(b.jsInteractionTimeoutMs<660)b.clientWidth||b.clientHeight?a.call(b):setTimeout(function(){f(b)[h](a)},b.jsInteractionTimeoutMs+66)});return c}})(jQuery,"flash",navigator.plugins["Shockwave Flash"]||window.ActiveXObject);

/*--------------------------------------------------------------------------*/

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}

/*--------------------------------------------------------------------------*/

var Tabs = function (container) {
	this.container = $(container);
	this.togglers = this.container.find('.togglers li');
	this.tabs = this.container.find('.tab');
	this.setup();
};
Tabs.prototype = {
	setup: function () {
		var self = this;
		this.show(0);
		this.togglers.each(function (i) {
			$(this).bind('click', function (ev) {
				ev.preventDefault();
				self.show(i);
			});
		});
	},
	show: function (idx) {
		this.togglers.removeClass('active');
		$(this.togglers[idx]).addClass('active');
		this.tabs.hide();
		$(this.tabs[idx]).show();
	}
};


/*--------------------------------------------------------------------------*/

var Navigation = function (container) {
	this.togglers = container.find('li');
	this.setup();
};
Navigation.prototype = {
	setup: function () {
		var self = this;
    	this.togglers.hoverIntent({
    		sensitivity: 1,
            interval: 10,
            over: function () {
            	self.open($(this));
            },
            out: function () {
				self.close($(this));
            }
		});
	},
	open: function (el) {
		el.addClass('active');
		var anchors = el.find('a');
    	anchors.hoverIntent({
    		sensitivity: 1,
            interval: 10,
            over: function () {
            	$(this).addClass('active');
            },
            out: function () {
				$(this).addClass('active');
            }
		});
		
		var dropdown = el.find('.dropdown:first');
		dropdown.show();
	},
	close: function (el) {
		el.removeClass('active');
		var anchors = el.find('a');
		
		el.find('a').removeClass('active');
		anchors.removeClass('active');
		var dropdown = el.find('.dropdown:first');
		dropdown.hide();
	}
};

/*--------------------------------------------------------------------------*/

var SlideShow = function (container, slides, delay, initial) {
    this.container = container;
    this.slides = slides;
    this.delay = delay;
    this.current = initial;
    this.togglers = this.container.find('.tout');
    this.togglers2 = this.container.find('.togglers li');
    this.setup();
};
SlideShow.prototype = {
    setup: function () {
        var self = this;
        this.showOnly($(this.slides[this.current]));
		$(this.togglers2[this.current]).addClass('active');
        
        this.togglers.bind('mouseenter', function () {
            self.pause();
            self.goTo($(this).index()+1);
        });
		
        this.togglers2.bind('click', function () {
            self.pause();
            self.goTo($(this).index());
        });
				
		this.start();
    },
    showOnly: function (el) {
        this.slides.hide();
        el.show();
    },
    goTo: function (idx) {
        var self = this;
		
        if (idx === this.current) {	
            return;
        }
		
        $(this.togglers).removeClass('active');
        $(this.togglers2).removeClass('active');
        $(this.slides[this.current]).fadeOut('slow');
        this.current = idx;
		
        $(this.togglers2[this.current]).addClass('active');
        $(this.togglers[this.current-1]).addClass('active');
		
        $(this.slides[this.current]).fadeIn('slow');
		
        this.start();
    },
    start: function () {
        if (this.timer) {
            return;
        }
        var self = this;
        this.timer = setTimeout(function(){
            self.next();
        }, this.delay * 1500);
    },
    pause: function () {
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = false;
        }
        else {
            return;
        }
    },
    next: function() {
        this.timer = false;
        if (this.current === this.slides.length - 1) {
            this.goTo(0);
        }
        else {
            this.goTo(this.current + 1);
        }
        this.start();
    }
};

/*--------------------------------------------------------------------------*/

var MenuToggler = function (trigger, content) {
    this.trigger = trigger;
    this.content = content;
	
    this.setup();
};
MenuToggler.prototype = {
	setup: function () {
		var self = this;
		this.trigger.toggle(
			function (ev) {
				ev.preventDefault();
				$(self.trigger).addClass('active');
				$(self.content).slideDown(300);
			},
			function (ev) {
				ev.preventDefault();
				$(self.trigger).removeClass('active');
				$(self.content).slideUp(300);
			}
		);
	}
};

/*--------------------------------------------------------------------------*/

var YouTubePopUp = function(trigger, pop, width, height){
    this.trigger = $(trigger);
    this.pop = $(pop);
	this.container = this.pop.find('.content');
    this.width = width;
    this.height = height;
    this.matches = this.trigger.attr('href').match(/v=([A-Za-z0-9\-=_]{11})/);
    this.setup();
};
YouTubePopUp.prototype = {
    setup: function() {
        var self = this;
        this.trigger.bind('click', function (ev) {
            ev.preventDefault();
            self.open();
        });
    },
	open: function () {
		var self = this;
		if ($('#modal_overlay')) {
			this.init_modal($('#modal_overlay'));
		}
		
		this.pop.center();
		this.pop.fadeIn(100, function () {
			self.embed_video();
		});
		
		var close_btn = this.pop.find('.close');
		close_btn.bind('click', function () {
			self.close();
		});
	},
	close: function () {
		var self = this;
		this.pop.fadeOut(100, function () {
			self.container.find('.player').html('');
		});
		if ($('#modal_overlay')) {
			$('#modal_overlay').hide();
		}
	},
	init_modal: function (el) {
		el.css("height", $('body:first').height());
		$(el).show();
	},
    embed_video: function (){
        var url = "http://www.youtube.com/v/" + this.matches[1] + "&hl=en&autoplay=1";
		var player = this.container.find('.player');
        player.flash({
            swf: url,
            width: this.width,
            height: this.height
        });
    }
};

/*--------------------------------------------------------------------------*/

var SimpleToggler = function (trigger, content) {
	this.trigger = $(trigger);
	this.content = $(content);
	this.setup();
};
SimpleToggler.prototype = {
	setup: function () {
		var self = this;
		var origHeight = this.content.height();
		var origTxt = this.trigger.text();
		this.trigger.toggle(
			function (ev) {
				ev.preventDefault();
				var target = self.content.find('div:first').height();
				self.content.animate(
					{ height: target },
					{ duration: 400 }
				);
				self.trigger.text('Read less');
			},
			function (ev) {
				ev.preventDefault();
				self.content.animate(
					{ height: origHeight },
					{ duration: 400 }
				);
				self.trigger.text(origTxt);
			}
		);
	}
};

/*--------------------------------------------------------------------------*/

var Prompt = function (field) {
	this.field = $(field);
	this.setup();
};
Prompt.prototype = {
	setup: function () {
		var self = this;
		var input = this.field.find('input');
		input.bind('click, focus', function () {
			self.field.addClass('active');
		});
		input.bind('blur', function () {
			self.field.removeClass('active');
		});
	}
};

/*--------------------------------------------------------------------------*/

var PopUp = function (trigger, pop) {
	this.trigger = $(trigger);
	this.pop = $(pop);
	this.fadeDur = $.browser.msie ? 0 : 200;
	this.setup();
};
PopUp.prototype = {
	setup: function () {
		var self = this;
		this.trigger.bind('click', function (ev) {
			ev.preventDefault();
			self.open();
		});
	},
	open: function () {
		var self = this;
		this.pop.center();
		this.pop.fadeIn(this.fadeDur);
		var close = this.pop.find('.close');
		close.bind('click', function () {
			self.close();
		});	
	},
	close: function () {
		this.pop.fadeOut(this.fadeDur);
	}
};

/*--------------------------------------------------------------------------*/

function externalLinks() {
 	if (!document.getElementsByTagName) return;
 	var externals = $("a[rel='external']");
	
	externals.each(function () {
		if ($(this).attr('href')) {
			$(this).bind('click', function (ev) {
				ev.preventDefault();
				window.open($(this).attr('href'));
			});
		}
	});
}

/*--------------------------------------------------------------------------*/

$(document).ready(function () {
	if ($.browser.msie && $.browser.version=="6.0") {
		try {
			document.execCommand('BackgroundImageCache', false, true);
		} catch (e) {}
	}
	
	new Prompt($('#global_search .input'));
	
	new Navigation($('#nav'));
	
	if ($('#hero').length) {
		new SlideShow($('#hero'), $('#hero .slide'), 5, 0);
	}
	
	if ($('.tabs').length) {
		new Tabs($('.tabs'));
	}
	
	
	if ($('.module_brochure').length) {
		new SlideShow($('.module_brochure'), $('.module_brochure .slide'), 5, 0);
	}

	if ($('#sidebar').length) {
		var triggers = $('#sidebar .trigger');
		var menus = $('#sidebar .menu');
		triggers.each(function (i) {
			new MenuToggler($(this), $(menus[i]));
		});
	}
	
	if ($('#tout_montella').length) {
		new YouTubePopUp($('#tout_montella'), $('.overlay'), 522, 318);
	}
	
	if ($('.member').length) {
		$('.member').each(function () {
			new SimpleToggler($(this).find('.toggle'), $(this).find('.content'));
		});
	}

	if ($('.news_listing .utility .dl').length) {
		$('.news_listing .utility .dl, .trigger_reg').each(function () {
			new PopUp($(this), $('#overlay_reg'));
		});
		new PopUp($('#overlay_reg .submit a'), $('#overlay_thanks'));
	}
	
	if ($('#overlay_itam').length) {
		new PopUp($('img.tout'), $('#overlay_itam'));
	}
	
	externalLinks();
});
