﻿var sliding;
$(document).ready(function(){

	$('html').addClass('js');

	Cufon.replace('h1');

	Cufon.replace('#programs h2', { hover: true });
	Cufon.replace('#testimonials h2', { hover: true });
	Cufon.replace('#coaches h2', { hover: true });
	Cufon.replace('#info h2', { hover: true });
	Cufon.replace('.carousel h2', { hover: true });
	Cufon.replace('#contact-form h2', { hover: true });
	Cufon.replace('#program-overview h2', { hover: true });
	Cufon.replace('#side h2');
	Cufon.replace('#side .carousel p');
	Cufon.replace('.quote p:not(.source)');
	Cufon.replace('div#nav ul li a', { hover: true });

	sliding = setInterval("slideSwitch()", 5000);

	$('#campaign').InitCampaign();

	$('fieldset').TextfieldPlaceholders();
	$('.carousel').InitSlides();
	$('.carousel ul.slide-nav li').ChangeActiveSlide();
	$('#programs ul li.even').IEClearer();
	$('#content .listing ul').SetListWidth();
	$('#menu').AddMenuClasses();
	$('.videopreview').VideoPlayer();
	$('ul.clickable li').Clickable();
	$('#show-folders').Extendable();
	$('#folder-list input').UpdateSelectedList();
	$('#inspiration').InitInspirationRoom();

	
	$('.expandable').hoverIntent({
		'timeout':500,
		'over':	function (event)
				{
					$('#menu-dropdown').stop().show().css({ opacity: 1 });
				},
		'out':function(event) {}
	});
	$('body').bind('click',function(e)
	{
		//console.log(e,e.target);
		if($('#menu-dropdown').is(':visible') === true) 
		{
			if($(e.target).is('#menu-dropdown') === false && $(e.target).parents('#menu-dropdown').length === 0)
			{
				$('#menu-dropdown').fadeOut(400);
			}
		}
	});
	
	$('<div id="menu-dropdown-close"></div>')
		.html(((getLanguage() === 'en') ? 'close' : 'stäng'))
		.bind('click',function(e) { $('#menu-dropdown').fadeOut(400); })
		.appendTo('#menu-dropdown');
	
	
	
	/*
	if(getLanguage() === 'en') { return 'close' } else { return 'stäng'; }
	*/
	/*$('.expandable').mouseenter(function (event) {
		$('#menu-dropdown').stop().show().css({ opacity: 1 });
	});
	$('.expandable').mouseleave(function (event) {
		if ($(event.relatedTarget).attr("id") != "menu-dropdown") {
			$('#menu-dropdown').fadeOut(400);
		}
	});
	$('#menu-dropdown').mouseleave(function (event) {
		if (!$(event.relatedTarget).is(".expandable")) {
			$('#menu-dropdown').fadeOut(400);
		}
	});
	*/


	$('#offline').click(function () {
		$('.offline-info').toggle();
	});

	Cufon.now();

});


var getLanguage=function(){if($('meta[http-equiv="Content-Language"]').attr('content')===undefined){return(location.href.toString().indexOf('/en/')==-1)? 'sv':'en';}else{return($('meta[http-equiv="Content-Language"]').attr('content')==='sv')? 'sv':'en';}};

/* AddIEClearer
    Adds clearing list elements in IE 6 and 7 for startpage
*/
(function ($) {
	$.fn.IEClearer = function(){
		return this.each(function () {
			if ($.browser.msie && parseInt(jQuery.browser.version.substr(0, 1)) < 8)
				$(this).after('<li class="clearer"></li>');
		});
	};
})(jQuery);

/* SetListWidth
	Fixes list width for listings with only text (no image or calendar date)
*/
(function ($) {
	$.fn.SetListWidth = function () {
		return this.each(function () {
				if($(this).siblings().length == 0)
					$(this).css('width','100%');
		});
	};
})(jQuery);

(function ($) {
	$.fn.AddMenuClasses = function () {
		return this.each(function () {
			$(this).find('li').each(function (index, value) {
				if($(this).hasClass('selected'))
					$(this).children('a').addClass('selected');
				if($(this).hasClass('active'))
					$(this).children('a').addClass('active');
			});
		});
	};
})(jQuery);

/* Videoplayer
*/
(function ($) {
	$.fn.VideoPlayer = function () {
		autoplay = 0;
		return this.each(function () {
			$(this).bind('click', function () {
				id = $(this).attr("id");
				width = $('#videoplayer object').width();
				height = $('#videoplayer object').height();
				$(window).scrollTop($("#videoplayer").position().top+100);
				newVideoString =    
								'<object width=' + width + '" height="' + height + '">' +
								'<param name="allowFullScreen" value="true"></param>' +
								'<param name="allowscriptaccess" value="always"></param>' +
								'<param name="movie" value="http://www.youtube.com/v/' + id + '"></param>' +
								'<embed src="http://www.youtube.com/v/' + id + '&autoplay=' + autoplay + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width=' + width + '" height="' + height + '"></embed>' +
								'</object>';
				$('#videoplayer object').replaceWith(newVideoString);
			});
		});
	};
})(jQuery);

/* MakeClickable
    Finds first href link in object and makes the whole object a link.
*/
(function ($) {
	$.fn.Clickable = function(){
		$(this).bind('mouseover', function () {
			$(this).addClass('hover');
			if($(this).parents('.dark').length == 0){
				$temp = $(this).find('a').css('color','#9a6d7f');
				$temp.css('text-decoration','underline');
			}
		});
		$(this).bind('mouseout', function () {
			$(this).removeClass('hover');
			if($(this).parents('.dark').length==0){
				$temp = $(this).find('a').css('color','#000');
				$temp.css('text-decoration','none');
			}
		});
		$(this).bind('click', function () {
			var link = $(this).find('a').first().attr("href");
			if (link != undefined)
				window.location.href = link;
		});
	};
})(jQuery);


/* MakeExtendable 
    Extended toggle functionality, also changes toggle button a bit. 
*/
(function ($) {
	$.fn.Extendable = function () {
		$(this).bind('click', function () {
			$('#folder-list').toggle();
			if ($('#show-folders').hasClass('extended')) {
				$('#show-folders').removeClass('extended');
				$('#show-folders').attr("value", "Välj fler programbroschyrer");
			} else {
				$('#show-folders').addClass('extended');
				$('#show-folders').attr("value", "Fäll ihop");
			}
		});
	};
})(jQuery);

/* UpdateSelectedList
	Updates list of selected items when items are selected or deselected 
*/
(function ($) {
	$.fn.UpdateSelectedList = function () {
		$(this).bind('click', function () {
			var selectedText = $(this).parent().find('label').text();
			if ($(this).attr('checked')) {
				$('#chosen-folders').append('<li>' + selectedText + '</li>');
			}
			else {
				$.each($('#chosen-folders li'), function (key, value) {
					if (selectedText == value.innerHTML) {
						$('#chosen-folders li:eq(' + key + ')').remove();
					}
				});
			}
		});
	};
})(jQuery);

/* ChangeActiveSlide 
    Changes active slide in carousel
*/
(function ($) {
	$.fn.ChangeActiveSlide = function () {
		$(this).bind('click', function () {
			//Current carousel
			$carousel = $(this).closest('.carousel').first();

			//Clicked slide
			clickednr = $(this).parent('.slide-nav').find('li').index($(this));

			//Finding previous active element 
			$active = $carousel.find('li.active').first();
			if ($active.length == 0) $active = $(this).find('li:last').first();
			$active.addClass('last-active');

			//Finding new active element and fade between the two
			$next = $carousel.find('li:nth-child(' + (clickednr + 1) + ')').first();
			$next.css({ opacity: 0.0 })
				.addClass('active')
				.animate({ opacity: 1.0 }, 1000, function () {
					$active.removeClass('active last-active');
				});

			//Update navigation
			$carousel.find('.slide-nav li').removeClass('navActive');
			$carousel.find('.slide-nav li:nth-child(' + (clickednr + 1) + ')').first().addClass('navActive');

			//Pause the automatic slider for a few seconds
			clearInterval(sliding);
			sliding = setInterval("slideSwitch()", 5000);
		});
	};
})(jQuery);

/* InitSlides
	Builds navigation for slides in carousel
*/
(function ($) {
	$.fn.InitSlides = function () {
		return this.each(function () {
			//Set proper height if small carousel, it needs fixed height.
			if ($(this).hasClass('centered')) {
				maxheight = 0;
				$(this).find('li p').each(function (index, value) {
					if (maxheight < $(this).outerHeight(true)) {
						maxheight = $(this).outerHeight(true);
					}
				});

				/*Adding top margin*/
				$(this).find('li p').each(function (index, value) {
					if (maxheight > $(this).outerHeight(true)) {
						$(this).css('padding-top',(maxheight-$(this).outerHeight(true))/2);
					}
				});

				$(this).css('height', (maxheight) + 'px');
				$(this).find('li').css('height', (maxheight) + 'px');
			}

			//Set first item to active
			$(this).find('li').first().addClass('active');

			//Add navigation dots
			var $e = $(document.createElement('ul'));
			$e.addClass("slide-nav");
			$(this).find('li').each(function (index, value) {
				if (index == 0)
					$e.append('<li class="navActive"></li>');
				else
					$e.append('<li></li>');
			});
			$(this).append($e);

			//Center navigation if small carousel
			if ($(this).hasClass('centered')) {
				left = $(this).width() / 2 - $e.width() / 2;
				$e.css('left', left);
			}
		});
	};
})(jQuery);

/* slideSwitch
	Switches slide from slide navigation 
*/
function slideSwitch() {
	$('.carousel').each(function (index, value) {

		//Finding previous active element 
		var $active = $(this).find('li.active').first();
		if ($active.length == 0) $active = $(this).find('li:last').first();
		$active.addClass('last-active');

		//Finding new active element and fade between the two
		var $next = $active.next().length ? $active.next()
		: $(this).find('li:first').first();

		$next.css({ opacity: 0.0 })
		.addClass('active')
		.animate({ opacity: 1.0 }, 1000, function () {
			$active.removeClass('active last-active');
		});

		//Update navigation
		$(this).find('.slide-nav li').removeClass('navActive');
		next = $(this).find('ul li').index($next);
		$(this).find('.slide-nav li:nth-child(' + (next + 1) + ')').first().addClass('navActive');
	});
}

function DisplayAllBroschures() {
	$('#folder-list').toggle();
	if ($('#show-folders').hasClass('extended')) {
		$('#show-folders').removeClass('extended');
		$('#show-folders').attr("value", "Välj fler");
	}
	else {
		$('#show-folders').addClass('extended');
		$('#show-folders').attr("value", "Fäll ihop");
	}
}

var initModalScreen = function () {
	var pageHeight = $('#page').height();
	var modalScreen = $('<div id="modal-screen"></div>').bind('click', function () {
		$(this).remove();
		$('#modal-container').remove();
	}).css('height', pageHeight + 'px').appendTo('body');

};

/* INIT CAMAPIGN
----------------------------------------------------*/
(function ($) {
	$.fn.InitCampaign = function () {
		if($(this).length !== 0){		
			initModalScreen();
			var campaign = $(this),
				winHeight = $(window).height(),
				winWidth = $(window).width(),
				elmHeight = 466,
				elmWidth = 960,
				posY = (winHeight / 2) - (elmHeight / 2),
				posX = (winWidth / 2) - (elmWidth / 2),
				modalContainer = $('<div id="modal-container"></div>').css({
					top: posY +'px',
					left: posX +'px'
				}),
				closeButton = $('<div class="close"><a href="javascript:;">Stäng</a></div>').bind('click', function(){
					campaign.remove();
					$('#modal-screen').remove();
				});
			modalContainer.append(campaign.append(closeButton)).appendTo('body');

		}
	};
})(jQuery);

/* INIT INSPIRATION ROOM
----------------------------------------------------*/
(function($){
	$.fn.InitInspirationRoom = function(){
//        if(document.location.search.indexOf('?path=')==0)
//        {
//            document.location.href=document.location.pathname+'#/' + document.location.search.substring(6) + '/';
//        }
		if(this.length === 0){
			return false;
		}
		
		var inspiration = $(this),
			pagingItterator = 0,
			hash = location.hash,
			boxes = $('#boxes'),
			SystemText = [];

		SystemText.Loading = (getLanguage() === 'sv') ? 'Laddar, ett ögonblick..' : 'Loading, one moment please..';
		SystemText.Close = (getLanguage() === 'sv') ? 'Stäng' : 'Close';
		SystemText.NoResult = (getLanguage() === 'sv') ? '<li id="systemmessage"><p>För närvarande finns det inget att visa med den nuvarande filtreringen.</p></li>' : '<li id="systemmessage"><p>There is currently nothing to display with the current filtering.</p></li>';
		SystemText.Error = (getLanguage() === 'sv') ? '<li id="errormessage"><p><strong>Hoppsan, ett fel har inträffat.</strong><br />Prova att laadda om sidan och se om problemet försvinner.</p></li>' : '<li id="errormessage"><p><strong>Ops, an Error Occurred.</strong><br />Try to fresh your browser to see if it will go away.</p></li>';

		//# ENABLE AJAX WAYPOINT PAGINATION
		$('#info').waypoint(function(event, direction) {
			++pagingItterator;
			$('#info').waypoint('remove');
			clearTimeout(ajaxTimer);
			var ajaxTimer = 0;
			var execPagination = function(){
				$.ajax({
					type: "GET",
					cache:false,
					url: "/Templates/InspirationServices/Pagination.aspx?lang="+ getLanguage() +"&epiPageID="+ $('#pageID').val() +"&page="+ pagingItterator +"&url="+ hash.replace('#',''), 
					success: function(data){
						if(data.length < 5){
							return;
						}
						var content = $(data),
							length = content.length;
						if(length > 0){
							$('#inspiration').append($('<div id="ajax-loading-message">'+ SystemText.Loading +'</div>').bind('click',function(){
								execPagination();
							}));
							var firstInQue = content.eq(0);
							ajaxTimer = window.setTimeout(function(){
								boxes.append(content)
									.css('height','')
									.fadeQueue({
										startAt: firstInQue,
										duration: 500,
										pause: 60
									},function(){
										boxes.find('div.text').textfill();
									}
								);
								$('#ajax-loading-message').remove();
								$('#info').waypoint({offset:'90%'});
								prepareBoxes();
							},1500);
						}
					},
					error: function(){
						boxes.before($(SystemText.Error));
					}
				});
			};
			execPagination();
		}, {
		   offset: '90%'
		});

		//# SORT BOXES
		var sortBoxes = function(sortUrl){
			$.ajax({
				type: "GET",
				cache:false,
				url: "/Templates/InspirationServices/Filter.aspx?lang="+ getLanguage() +"&epiPageID="+ $('#pageID').val() +"&url="+ sortUrl, 
				success: function(data){
					if(data.length > 10){
						boxes.html(data);
						boxes.find("li.box").hide()
							.end()
							.fadeQueue({
								duration: 500,
								pause: 60
							},function(){
								boxes.find('div.text').textfill();
							}
						);
						$('#box-article').remove();
						prepareBoxes();
					} else {
						boxes.html($(SystemText.NoResult));
					}
				},
				error: function(){
					boxes.html($(SystemText.Error));
				}
			});
		};

		//# INIT SORTING
		$('#inspiration div.sort a').bind('click',function(){
			$(this).parents('ul').find('a').removeClass('active');
			$(this).addClass('active');
			pagingItterator = 0;
			closeOverlay.hide();
			var sortUrl = '',
				active = $('#inspiration div.sort a.active'),
				sortCategory = $(active).eq(0).attr('href').toString(),
				sortType = $(active).eq(1).attr('href').toString();
			if(sortCategory.between('/category/','/')){
				sortUrl += '/category/'+ sortCategory.between('/category/','/') +'/';
			} else {
				sortUrl += '';
			}
			if(sortType.between('/type/','/')){
				sortUrl += '/type/'+ sortType.between('/type/','/') +'/';
			} else {
				sortUrl += '';
			}
			sortUrl = sortUrl.replace('//','/');
			if(sortUrl.length === 0){
				sortUrl = 'all';
				window.location.hash = '/';
			}else{
				window.location.hash = sortUrl;
			}
			sortBoxes(sortUrl);
			return false;
		});

		var prepareBoxes = function(){
			//# SET BOX TYPE ICON
			var boxType = boxes.find('li.box').each(function(i){
				var type = $(this).find('span.link a').attr('rel');
				if(type.length !== 0){
					$(this).append('<img src="/ui/images/i-'+ type +'.png" alt="" class="boxtype" />');
				}
			});
			//# INIT ARTICLES
			boxes.find('li.box').css('cursor','pointer').bind('click',function(){
				$('#info').waypoint('remove');
				boxes.css('height','');
				var url = $(this).find('span.link a').attr('href');
				if(location.href.indexOf(url) != -1){
					$(window).hashchange();
				}
				window.location.hash = url;
			});
		};
		
		//# DISPLAY BOXES
		if(hash.length === 0){
			boxes.fadeQueue({
				duration: 500,
				pause: 60
			},function(){
				boxes.find('div.text').textfill();
			});
		}

        //# CREATE AND ADD CLOSE BUTTON AND OVERLAY FUNCTIONS
		var closeOverlay = $('<div class="close"><span>'+ SystemText.Close +'</span></div>').bind('click', function(){
			window.location.hash = '/';
			$('#box-article').animate({
				height: 10,
				opacity: 0
			}, 200, function(){
				closeOverlay.fadeOut(200);
				$('#box-article').remove();
			});
		});
		inspiration.append(closeOverlay);

		//# GET ARTICLE AND INSERT
		var getBoxArticle = function(box){

			//# ADD INSERT POINTS FOR ARTICLES
			boxes.find('li.box:not(#box-article):nth-child(3n)').addClass('in');
			boxes.find('li.box:last').addClass('in');

			var articlePath = $(box).find('.link a').attr('href'),
				articlePlaceholder = $('<li id="box-article"><div class="wrap loading">&nbsp;</div></li>');
			if($('#box-article').length === 1){
				//# ARTICLE ALLREADY OPEN
				$('#box-article').animate({
					height: 10,
					opacity: 0
				}, 150, function(){
					$('#box-article').remove();
					closeOverlay.fadeOut(100, function(){
						var offset = box.position();
						if(offset !== null){
							closeOverlay.css({
								'top': offset.top,
								'left': offset.left
							});
							closeOverlay.fadeIn(200);							
							var insertPoint = (box.hasClass('in')) ? box : box.nextAll('li.in:first');
							insertPoint.after(articlePlaceholder);
							$('html,body').animate({ scrollTop: (offset.top+200) }, 500);
							$('#box-article div.wrap').animate({
								height: 500
							}, 200, function(){
								$.get('/Templates/InspirationServices/Box.aspx?lang='+ getLanguage() +'&epiPageID='+ $('#pageID').val() +'&url='+ articlePath, function(data) {
									$('#box-article').html('<div class="wrap">'+ data +'</div>');
								});
							});
						}
					});
				});
			} else {
				//# NO ARTICLE OPEN
				box.css('display','block');
				var offset = box.position();
				if(offset !== null){
					boxes.css('height','');
					closeOverlay.css({'top': offset.top,'left': offset.left});
					closeOverlay.fadeIn(200);
					var insertPoint = (box.hasClass('in')) ? box : box.nextAll('li.in:first');
					insertPoint.after(articlePlaceholder);
					$('html,body').animate({ scrollTop: (offset.top+200) }, 500);
					$('#box-article div.wrap').animate({
						height: 500
					}, 200, function(){
						$.get('/Templates/InspirationServices/Box.aspx?lang='+ getLanguage() +'&epiPageID='+ $('#pageID').val() +'&url='+ articlePath, function(data) {
							$('#box-article').html('<div class="wrap">'+ data +'</div>');
						});
					});
				}
			}
			boxes.find('div.text').textfill();
		};
		//# CHECK FOR HASH
		$(window).hashchange(function(){
			hash = location.hash;
			if(hash.length > 0){
				var targetedArticle = boxes.find('a[href="'+ hash.substring(1) +'"]');
				if(targetedArticle.length > 0){
					//# HASH IS FOR A TARGETED ARTICLE
					getBoxArticle(targetedArticle.parents('li.box:first'));
				}
			}
		});
		if(hash.length > 0){
			//# HASH IS FOR SORTING
			var category = hash.between('/category/','/'),
				type = hash.between('/type/','/');
			if(category || type){
				$('#inspiration .sort a').removeClass('active');
				if(category){
					$('#inspiration .sort a[href*="'+ category +'"]').addClass('active');
				} else {
					$('#inspiration .sort div:eq(0) a:first').addClass('active');
				}
				if(type){
					$('#inspiration .sort a[href*="'+ type +'"]').addClass('active');
				} else {
					$('#inspiration .sort div:eq(1) a:first').addClass('active');
				}
				sortBoxes(hash.replace('#',''));
			}
		}
		$(window).hashchange();
		prepareBoxes();
	};
})(jQuery);

/** Textfield Placeholders v1.2 - jQuery Plugin
* Copyright (c) Palle Zingmark <www.palleman.nu>
* Author: Palle Zingmark, www.palleman.nu
*         Philip Hofstetter, www.gnegg.ch
* Released with the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
(function($){$.fn.TextfieldPlaceholders=function(){return this.each(function(){var $parent=$(this);$parent.find('input:text[value=""],input:password[value=""]').each(function(i){var $input=$(this),$placeholder=$($input).attr('placeholder'),$basecolors=['#000000','rgb(0, 0, 0)'],$color=$($input).css('color'),$hascolor=jQuery.inArray($color,$basecolors);if(typeof $placeholder==='undefined'||$placeholder===''){$placeholder=$parent.find('label[for="'+$($input).attr('id')+'"]').text();}if(typeof $placeholder==='string'||$placeholder!==''){var $original_input='',$proxy='';if($input.attr('type')=='password'){$proxy=$('<input type="text" />');$original_input=$input;$proxy.attr('class',$input.attr('class'));$proxy.attr('style',$input.attr('style'));$proxy.insertAfter($input);$input.hide();$input=$proxy;}$input.attr('value',$placeholder);$input.attr('title',$placeholder);if($hascolor||$hascolor!=-1){$input.css('color','#aeaeae');}$input.bind('focus',function(){if($input.attr('value')==$placeholder){if($original_input){$input.hide();$original_input.show();$input=$original_input;$input.focus();}$input.attr('value','');$input.css('color',$color);}});($original_input||$input).bind('blur',function(){if($input.attr('value')===$placeholder||$input.attr('value')===''){if($original_input){$original_input.hide();$proxy.show();$input=$proxy;}$input.attr('value',$placeholder);if($hascolor||$hascolor!=-1){$input.css('color','#aeaeae');}}});}});});};})(jQuery);

if(typeof String.prototype.trim !== 'function') {
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g, ''); 
	};
}

//# CHANGE FONTSIZE TO FILL ENTIRE BOX
(function ($) {
	$.fn.textfill = function () {
		$(this).each(function () {
			var elm = $(this),
				p = elm.find('p:first'),
				textHeight = p.height(),
				fontSize = 10,
				maxFontSize = 72,
				maxHeight = parseInt(elm.css('height'), 10) - 30,
				failSafe = 100,
				boxText = p.text().trim();
			if(boxText.length !== 0 && p.length !== 0){
				while (textHeight < 170 && failSafe > 0) {
					fontSize = fontSize + 1;
					p.css('font-size', fontSize + 'px');
					textHeight = p.height();
					failSafe--;
				}
			}
		});
	};
})(jQuery);

/** jQuery fadeQueue - v0.5 - 25/2/2011
* Copyright (c) 2011 Palle Zingmark <www.palleman.nu>
* Dual licensed under the MIT and GPL licenses.
*/
(function($){$.fn.fadeQueue=function(args){var p=$(this),z={},y=null,d=200,k=0,c=null,t=0,q=0,s=p.children(':first');clearTimeout(t);if(typeof args!=='undefined'){for(var i=0,n=arguments.length;i<n;i++){var a=arguments[i];switch(typeof a){case'number':d=a;break;case'object':z=a;break;case'function':c=a;break;}}y=(typeof z.startAt!=='undefined')?z.startAt:null;d=(typeof z.duration!=='undefined')?z.duration:d;k=(typeof z.pause!=='undefined')?z.pause:k;}if(k===0){k=(d/2);}if(y){y.next().nextAll().hide();s=y;}else{$(this).children().hide();}p.children().stop(true,true);var f=function(elm){if(elm.length!==0){t=window.setTimeout(function(){elm.fadeIn(d);q=window.setTimeout(function(){f(elm.next());},k);},k/2);}else{if(typeof c=='function'){return new c();}}};f(s);};})(jQuery);

/** jQuery hashchange event - v1.3 - 7/21/2010
* http://benalman.com/projects/jquery-hashchange-plugin/
* 
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);

/** jQuery Waypoints - v1.0
* Copyright (c) 2011 Caleb Troughton
* Dual licensed under the MIT license and GPL license.
* https://github.com/imakewebthings/jquery-waypoints/blob/master/MIT-license.txt
* https://github.com/imakewebthings/jquery-waypoints/blob/master/GPL-license.txt
*/
(function($,l,n,j,d){var f=$(j),k=[],m=-99999,i=false,o=false,g="waypoint.reached";var c={init:function(q,p){this.each(function(){var u=$(this),r=h(u),t=r<0?$.fn[l].defaults:k[r].options,s=$.extend({},t,p);if(r<0){k.push({element:u,offset:u.offset().top,options:s})}else{k[r].options=s}q&&u.bind(g,q)});$[n]("refresh");return this},remove:function(){return this.each(function(){var p=h($(this));if(p>=0){k.splice(p,1)}})},destroy:function(){return this.unbind(g).waypoint("remove")}};function h(q){var p=k.length-1;while(p>=0&&k[p].element[0]!==q[0]){p-=1}return p}function b(q,p){q.element.trigger(g,p);if(q.options.triggerOnce){q.element.waypoint("destroy")}}function e(){var q=f.scrollTop(),p=q>m,r=$.grep(k,function(t,s){return p?(t.offset>m&&t.offset<=q):(t.offset<=m&&t.offset>q)});if(!r.length){return}if($[n].settings.continuous){$.each(p?r:r.reverse(),function(t,s){b(s,[p?"down":"up"])})}else{b(r[p?r.length-1:0],[p?"down":"up"])}m=q}$.fn[l]=function(p){if(c[p]){return c[p].apply(this,Array.prototype.slice.call(arguments,1))}else{if(typeof p==="function"||!p){return c.init.apply(this,arguments)}else{if(typeof p==="object"){return c.init.apply(this,[null,p])}else{$.error("Method "+p+" does not exist on jQuery"+l)}}}};$.fn[l].defaults={offset:0,triggerOnce:false};var a={refresh:function(){$.each(k,function(r,t){var p=0,s=t.offset;if(typeof t.options.offset==="function"){p=t.options.offset.apply(t.element)}else{if(typeof t.options.offset==="string"){var q=parseFloat(t.options.offset);p=t.options.offset.indexOf("%")?f.height()*(q/100):q}else{p=t.options.offset}}t.offset=t.element.offset().top-p;if(m>s&&m<=t.offset){b(t,["up"])}else{if(m<s&&m>=t.offset){b(t,["down"])}}});k.sort(function(q,p){return q.offset-p.offset})},aggregate:function(){var p=$();$.each(k,function(q,r){p=p.add(r.element)});return p}};$[n]=function(p){if(a[p]){return a[p].apply(this)}else{return a.aggregate()}};$[n].settings={continuous:true,resizeThrottle:200,scrollThrottle:100};f.load(function(){f.scroll(function(){if(!i){i=true;j.setTimeout(function(){e();i=false},$[n].settings.scrollThrottle)}});f.resize(function(){if(!o){o=true;j.setTimeout(function(){$.waypoints("refresh");o=false},$[n].settings.resizeThrottle)}});$[n]("refresh");e()})})(jQuery,"waypoint","waypoints",this);

/** JavaScript between - 21/4/2011
* Made by Palle Zingmark <www.palleman.nu>
*/
String.prototype.between = function(prefix, suffix){
	var re = new RegExp("\\"+ prefix +"(.*?)\\"+ suffix,"i");
	if(re.test(this)){
		return re.exec(this)[1];
	}else{
		return false;
	}
};


/**
* hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
* <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(at)cherne(dot)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 ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t)}if(e.type=="mouseenter"){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.bind('mouseenter',handleHover).bind('mouseleave',handleHover)}})(jQuery);
