

/* Anything to do once the page has loaded? */

$(function($) {
		//Cufon.refresh(".subevent .name");
		//applyCufon();
		// Set year in the subFooter
		var theDate=new Date()
		var year=theDate.getFullYear()
		$(".subFooter .year").text(year);
		
		
		// DETECT OS AND APPLY CORRECT LETTER SPACING 
		
		var os;
			
		function OSDetect(string){
			var detect = navigator.userAgent.toLowerCase();
			place = detect.indexOf(string) + 1;
			return place;
		}

		if (OSDetect('mac')) {
			os="Mac";
		}
		else{
			os="Other";
		}
		for(var i=0;i<fontReplacement.length;i++){
			// Set letter spacing
			var sel=fontReplacement[i].sel;
			var val=fontReplacement[i]["val"+os];
			$(sel).css('letter-spacing',val + "em");
			
			// Apply Cufon
			if(fontReplacement[i].engine=="cufon"){
				Cufon.replace(sel);
			}
		}
		
		
	
		

		/**
		* Mailing list forms
		*/
		turnOnMailingListForms($(".mailinglist")  );

		/**
		* Guides
		*/
		// Turn on guides
		var guidesEnabled=false;			// Set to true to make guides functioning
		var guidesVisible=false;
		
		function toggleGuides(){		
			if(guidesVisible && guidesEnabled){
				$(".guides").hide();
				guidesVisible=false;
			}
			else if(!guidesVisible && guidesEnabled){
				$(".guides").show();
				guidesVisible=true;
			}
		}
		// Key up listeners
		$(this).keyup(function(event){
			// Is "g" pressed?
			if(event.which==71){
				if(guidesEnabled){
					toggleGuides();
				}
				
			}
		});


});


/* ==============================================
		MAILING LIST AJAX 
*/
	
	
		/** Turn the ajax on for mailinglist forms.
	*		@param $mailinglist	The mailinglist form container(s) to be turned on.
	*/
	function turnOnMailingListForms($mailinglist) {
		$mailinglist.each(
			function() {
				var id = $(this).attr('id');

				turnOnInputGhostInstruction($("form .email", this));
		
				// set up the form action
				$("form", this).ajaxForm(
					{
						target: 
							"#" + id + " .response",
						success: 	
							function() {
								window.setTimeout(function() {$('#' + id + ' .response').empty();}, 5*1000);
								if ($('#' + id + ' .response .success') ) {
									// If they've signed up to the mailing list, remember that for a hundred years.
									Cookie.set("addedToMailingList", "true", 24*7*52*100  );
								}
							}
					
					}
				);
			}
			
		)

	}
	
/* 
	==============================================
	INPUT FIELD INSTRUCTIONS
*/

	function turnOnInputGhostInstruction($fields) {
		$fields.each(
			function() {
				$field = $(this);
				var defaultValue = $field.attr("defaultValue");
				if ($field.is("textarea"))
					defaultValue = $field.text();
					
				//console.log($field.parent().parent().parent().attr('id')+':'+defaultValue+':'+$field.val());
				
				if ($field.val()==defaultValue)
					$field.addClass("inputFaint");
					
				if ($field.val()=='') {
						$(this).val(defaultValue);
						$(this).addClass('inputFaint');
				}

				$field.focus(
							function() {
								if ($(this).val()==defaultValue ) {
									$(this).val('');
									$(this).removeClass('inputFaint');
								}
							}
				);
				$field.blur(
							function() {
								if ($(this).val()=='') {
									$(this).val(defaultValue);
									$(this).addClass('inputFaint');
								}
							}
				);
				
				
				
			}
		);
	}
		




/* 
	==============================================
*/





/** 
	Event menutrail needs to be activated for pages deeper than 3, 
	e.g. /events/kytn/programme/mahershalalhashbaz 
*/
function activateEventMenuTrail(menu) {
	pathname = window.location.pathname;
	if (pathname.length>0) {
		// Walk through the menu. Ignore the first item (it's the menu parent, confusingly)
		$("li:not(:first-child) a", menu).each(function(){
			itemUrl = $(this).attr("href")
			if (pathname.substring(0, itemUrl.length)==itemUrl   )
				$(this).addClass("active");
		});
	}
}

/** 
	Turn on carousels, if they have more than one picture. And set their controls to fade in and out on mouseover
*/
function turnOnCarousels($carousels, options) {
	$carousels.each(function() {
		if ($('>li', this).length > 1) {
	  		$(this).jcarousel(options);
		}
	 	initCarouselFadeControls($('.jcarousel-container'));
	})
}


/** 
	Tell the carousels to fade the prev/next buttons in and out on mouseover
*/
function initCarouselFadeControls($container) {
  	$container.hover(
  		function() {
		  	$('.jcarousel-prev, .jcarousel-next',this).css('visibility', 'visible').hide().fadeIn(500);
	
  		}
  		,
  		function() {
		  	$('.jcarousel-prev, .jcarousel-next',this).fadeOut(500);	  		
  		}
  	);
}

/**
	Add jquery.expander functionalty to any elements with the teaser break <!--break-->
	Used in Multievent page.
	@param $o		Any elements to be expanded
	@param options	jquery.expander options
*/
function initAjaxTeaserBreak($o, options) {
	if ($o && $o.length>0) {
		var breakPoint = $o.html().indexOf('<!--break-->');
		var slicePoint = $($o.html().substring(0, breakPoint)+"</p>").text().length;
		if (slicePoint>0 && slicePoint<500)
			options.slicePoint = slicePoint;
		$o.expander(options);
	}
}


function repairTemplate(nodeType) {

	switch(nodeType) {
		case "event_book_tickets":
			// If they've buggered up the template's <ul>, reapply the class to the first <ul> we can find.
			//if ($(".wizz ul.t-row").length==0)
			//	$(".wizz ul:first").addClass("t-row");
			break;
		case "about":
			// Make sure quote pairs are the same height.
			$(".t-quotePair li:first").each(function() {
				var $next = $(this).next();
				if ($(this).height()  < $next.height()  )
					$(this).height($next.height());
			});
			break;
		case "multievent":
			// If they've forgotten to apply the sponsors editor styling, add it for them.
			var $ul = $(".sponsors.wizz ul");
			var numSponsorCols = $("li", $ul).length;
			$ul.removeClass("t-sponsors1 t-sponsors2 t-sponsors3 t-sponsors4").addClass("t-sponsors"+numSponsorCols);
			break;
		case "home":
			// If an event has carousel images and external images, show only the first set of images.
			$(".recent .event").each(function() {
				if ($(".images", this).length>1)
					$(".images:not(:first)", this).hide();
			});
			break;
			
	}
}






$.fn.equalHeights = function($others) {
	var tallest = 0;
	$(this).each(function() {
		var thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	
	if ($others) {
		$others.each(function() {
			var thisHeight = $(this).height();
			if(thisHeight > tallest) {
				tallest = thisHeight;
			}
		});
	}
	$(this).height(tallest);
	if ($others) {
		$others.height(tallest);
	}
	return this;
}






/** Add the Add To Calendar menu to a div.
*		The div must have an element with "button" class
*		and an element with "popup" class.
*		@param cal
*						The selector for the wrapper div, e.g. ".addToCalWrapper"
*						Only one selector here please, no multiple selectors separated by commas.
*/
function turnOnAddToCalendar(cal) {
	$(cal).removeClass("accessible").show();
	$(cal+" .popup").hide();
	
	$(cal+" .button").click(function() {
			$(".popup", $(this).parent()).toggle();
	});
	
	
	$(document).click(function(event) {
			if (!$(event.target).is(cal+" .button")) {
				$opencalpops = $(cal+" .popup:visible");
				if ($opencalpops.length) {
					$opencalpops.hide();
        	if (!$(event.target).is(cal+" .popup a")) {
	        	event.preventDefault();
	        	return false;
	        }
				}
			}

	});
}








/**
 * @author 	Maxime Haineault (max@centdessin.com)
 * @version	0.3
 * @desc 	JavaScript cookie manipulation class
 * 
 */

Cookie = {	

	/** Get a cookie's value
	 *
	 *  @param integer	key		The token used to create the cookie
	 *  @return void
	 */
	get: function(key) {
		// Still not sure that "[a-zA-Z0-9.()=|%/]+($|;)" match *all* allowed characters in cookies
		tmp =  document.cookie.match((new RegExp(key +'=[a-zA-Z0-9.()=|%/]+($|;)','g')));
		if(!tmp || !tmp[0]) return null;
		else return unescape(tmp[0].substring(key.length+1,tmp[0].length).replace(';','')) || null;
		
	},	
	
	/** Set a cookie
	 *
	 *  @param integer	key		The token that will be used to retrieve the cookie
	 *  @param string	value	The string to be stored
	 *  @param integer	ttl		Time To Live (hours)
	 *  @param string	path	Path in which the cookie is effective, default is "/" (optional)
	 *  @param string	domain	Domain where the cookie is effective, default is window.location.hostname (optional)
	 *  @param boolean 	secure	Use SSL or not, default false (optional)
	 * 
	 *  @return setted cookie
	 */
	set: function(key, value, ttl, path, domain, secure) {
		cookie = [key+'='+    escape(value),
		 		  'path='+    ((!path   || path=='')  ? '/' : path),
		 		  'domain='+  ((!domain || domain=='')?  window.location.hostname : domain)];
		
		if (ttl)         cookie.push(Cookie.hoursToExpireDate(ttl));
		if (secure)      cookie.push('secure');
		return document.cookie = cookie.join('; ');
	},
	
	/** Unset a cookie
	 *
	 *  @param integer	key		The token that will be used to retrieve the cookie
	 *  @param string	path	Path used to create the cookie (optional)
	 *  @param string	domain	Domain used to create the cookie, default is null (optional)
	 *  @return void
	 */
	unset: function(key, path, domain) {
		path   = (!path   || typeof path   != 'string') ? '' : path;
        domain = (!domain || typeof domain != 'string') ? '' : domain;
		if (Cookie.get(key)) Cookie.set(key, '', 'Thu, 01-Jan-70 00:00:01 GMT', path, domain);
	},

	/** Return GTM date string of "now" + time to live
	 *
	 *  @param integer	ttl		Time To Live (hours)
	 *  @return string
	 */
	hoursToExpireDate: function(ttl) {
		if (parseInt(ttl) == 'NaN' ) return '';
		else {
			now = new Date();
			now.setTime(now.getTime() + (parseInt(ttl) * 60 * 60 * 1000));
			return now.toGMTString();			
		}
	},

	/** Return true if cookie functionnalities are available
	 *
	 *  @return boolean
	 */
	test: function() {
		Cookie.set('b49f729efde9b2578ea9f00563d06e57', 'true');
		if (Cookie.get('b49f729efde9b2578ea9f00563d06e57') == 'true') {
			Cookie.unset('b49f729efde9b2578ea9f00563d06e57');
			return true;
		}
		return false;
	},
	
	/** If Firebug JavaScript console is present, it will dump cookie string to console.
	 * 
	 *  @return void
	 */
	dump: function() {
		if (typeof console != 'undefined') {
			console.log(document.cookie.split(';'));
		}
	}
}
