// JavaScript Document
var theWeather = null;
$(document).ready(function() {
	// enter the count down date using the format year/month/day
	countdown(1, 1,'#countdownDigits');
	$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20location%3D10036&format=json&diagnostics=true&callback=?", function(data){
		//console.log(data);
		theWeather = data;
		var theWeatherCode = theWeather.query.results.channel.item.condition.code;
		$("#temp").text(theWeather.query.results.channel.item.condition.temp);
		if (theWeatherCode == '1' || theWeatherCode == '2' || theWeatherCode == '3' || theWeatherCode == '4' || theWeatherCode == '8' || theWeatherCode == '9' || theWeatherCode == '10' || theWeatherCode == '11' || theWeatherCode == '12' || theWeatherCode == '18' || theWeatherCode == '35' || theWeatherCode == '37' || theWeatherCode == '38' || theWeatherCode == '39' || theWeatherCode == '40' || theWeatherCode == '45' || theWeatherCode == '47'){
			//Rain Icon (Green)
			$("#condition").addClass('rain');
		} else if (theWeatherCode == '5' || theWeatherCode == '6' || theWeatherCode == '7' || theWeatherCode == '13' || theWeatherCode == '14' || theWeatherCode == '15' || theWeatherCode == '16' || theWeatherCode == '41' || theWeatherCode == '42' || theWeatherCode == '43' || theWeatherCode == '46'){
			//Snow Icon (Red)
			$("#condition").addClass('snow');
		} else if (theWeatherCode == '26' || theWeatherCode == '27' || theWeatherCode == '28'){
			//Cloud Icon (Blue)
			$("#condition").addClass('cloudy');
		} else if (theWeatherCode == '29' || theWeatherCode == '30' || theWeatherCode == '44'){
			//Partly Cloudy Icon (Purple)
			$("#condition").addClass('partlyCloudy');
		} else if (theWeatherCode == '32' || theWeatherCode == '33' || theWeatherCode == '34'){
			//Sun Icon (Yella)
			$("#condition").addClass('sun');
		} else {
			//all others
			$("#condition").addClass('unusual');
		}
		$("#condition").text(theWeather.query.results.channel.item.condition.text);
		$("#degree").css('display','inline');
	});
	startTime();
	$("#searchField").focus(function() {
		if ($(this).val() == 'Search') {
			$(this).val('');
		}
		return false;
	});
	$("#searchField").blur(function() {
		if ($(this).val() == '') {
			$(this).val('Search');
		}
		return false;
	});	
	$("#search form").validsearch();
	$('#myItineraryWrapper:has(ul)').transDrop();
	$('#translate:has(ul)').transDrop();
	for (i=0;i<$('#translate ul li a').length;i++) {
		if(i==0){
			var linkFix = $('#translate ul li a:first').attr('href');
			linkFix = linkFix.replace('http://www.timessquarenyc.org',location.href);
			$('#translate ul li a:first').attr('href',linkFix);
		} else {
			var linkFix = $('#translate ul li a:eq('+i+')').attr('href');
			linkFix = linkFix.replace('http://www.timessquarenyc.org',location.href);
			$('#translate ul li a:eq('+i+')').attr('href',linkFix);
		}
	}
	$('ul.primaryNav li').navDrops();
	$("ul.primaryNav li").hover(
		function(){$(this).addClass("hover");},
		function(){$(this).removeClass("hover");
	});
	//Masthead Dynamic Class Application Trick
	var mastheadTester = $('.masthead').html();
	//alert(mastheadTester);
	if (mastheadTester == null){
		mastheadTester = 'noValue';
	}
	if (mastheadTester.indexOf('img') != -1 || mastheadTester.indexOf('IMG') != -1 ){
		//alert('There is a masthead image present.');
		$('.masthead img').addClass('rightBreak');
		$('.masthead').after('<div class="rightBreakCorner"></div>');
	} else {
		//alert('No masthead image present.');
		$('.mastFig').remove();
	}
	$('.breadcrumbs p a:first').css('padding-left','0px');
	$("#searchForm").submit(function() {
		keywordSearchFixes();
		return true;
	});
	$("#searchButton").click(function() {
		keywordSearchFixes();
		return true;
	});
});
function keywordSearchFixes(){
	delete_cookie("prevSearch");
	var deadCookieTest = get_cookie("prevSearch");
	var submittedKeywords = $("#searchField").val();
	var ampLoop = submittedKeywords.indexOf('&');
	while (ampLoop != -1){
		submittedKeywords = submittedKeywords.replace('&','%26');
		ampLoop = submittedKeywords.indexOf('&');
	}	
}
//change the text below to reflect your own,
var current="Today is New Years. Happpy New Years!";
var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

function countdown(mon,dat,id){
	var digitsId;	
	if(id == undefined){
		digitsId = 'countdownDigits';
	}else{
		digitsId = id;
	}
	showCountdown(mon,dat,digitsId);
}

function showCountdown(mon,dat,id){
	var timeZoneOffset;
	var daylighSavingsTime = true;//hardcoded and manually changed twice a year
	if (daylighSavingsTime == true){
		timeZoneOffset = '-5';//winter
	} else if (daylighSavingsTime == false){
		timeZoneOffset = '-4';//summer
	}
	var nowIsh=new Date();
	var universalTimeCode = nowIsh.getTime() + (nowIsh.getTimezoneOffset() * 60000);
	// create new Date object for different city using supplied offset
	var newDate = new Date(universalTimeCode + (3600000*timeZoneOffset));
	var todayYear=newDate.getYear();
	if (todayYear < 1000){
		todayYear+=1900;
	}
	var nextYear=todayYear+1;//This should always be the next year, no matter what
	//START passed params
	var theMonth=mon;
	var theDay=dat;
	var digitsId=id;
	//END passed params
	var todaym=newDate.getMonth();
	var todayd=newDate.getDate();
	var todayh=newDate.getHours();
	var todaymin=newDate.getMinutes();
	var todaysec=newDate.getSeconds();
	var todaystring=montharray[todaym]+" "+todayd+", "+todayYear+" "+todayh+":"+todaymin+":"+todaysec;
	futurestring=montharray[mon-1]+" "+dat+", "+nextYear;
	//console.log(todaystring+" : "+futurestring);
	dd=Date.parse(futurestring)-Date.parse(todaystring);
	dday=Math.floor(dd/(60*60*1000*24)*1);
	dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1);
	dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1);
	dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1);
	/* START TESTING
	var hardDate = new Date("December 31, 2011 23:59:00")
	var utcTest = hardDate.getTime() + (hardDate.getTimezoneOffset() * 60000);
	var adjustedTest = new Date(utcTest + (3600000*timeZoneOffset));
	adjustedTest.setDate(adjustedTest.getDate()+1);
	
	var hardDate2 = new Date("January 01, 2012 00:00:01")
	var utcTest2 = hardDate2.getTime() + (hardDate2.getTimezoneOffset() * 60000);
	var adjustedTest2 = new Date(utcTest2 + (3600000*timeZoneOffset));
	adjustedTest2.setDate(adjustedTest2.getDate()-1);
	//console.log("-New Year's Eve Incremented 1 Day: "+adjustedTest+"; -New Year's Day Decremented 1 Day:"+adjustedTest2);
	if (dmin == 3 && nextYear == 2012){
		//console.log("Test Conditions Met");
	}
	END TESTING */
	$(digitsId).text(dday+ " : "+dhour+" : "+dmin+" : "+dsec);
	if ($(digitsId).parent().parent().hasClass('countdown'+nextYear) == false){
		$(digitsId).parent().parent().addClass('countdown'+nextYear);
		//console.log('class added');
	}
	setTimeout(function(){
		countdown(theMonth,theDay,digitsId);
	},1000);
}


//Weather Clock
function startTime() {
	var today=new Date();
	var dst = true;//this will be true in the winter
	if (dst == true){
		var tzOffset = '-5';
	} else if (dst == false){
		var tzOffset = '-4';
	}
	//var h=today.getHours();
	//var m=today.getMinutes();
	//var s=today.getSeconds();
	// convert to msec, add local time zone offset, and get UTC time in msec
	utc = today.getTime() + (today.getTimezoneOffset() * 60000);
	// create new Date object for different city using supplied offset
	nd = new Date(utc + (3600000*tzOffset));
	//we are selecting the hours, minutes, and seconds from the new adjusted date object now, not the original local one
	var h=nd.getHours();
	var m=nd.getMinutes();
	var s=nd.getSeconds();
	if (h>12){
	   h=h-12;
	   var meridian = 'P.M.';
	}else if (h==12){
	   var meridian = 'P.M.';
	}else{
	   var meridian = 'A.M.';
	}
	// add a zero in front of numbers<10
	m=checkTime(m);
	s=checkTime(s);
	//document.getElementById('txt').innerHTML=h+":"+m+":"+s;
	t=setTimeout('startTime()',500);
	$("#time").text(h+":"+m+" "+meridian);
}
function checkTime(i) {
	if (i<10) {
	  i="0" + i;
	}
	return i;
}
//Clear input box plugin.
$.fn.search=function(){return this.focus(function(){if(this.value==this.defaultValue){this.value=""}}).blur(function(){if(!this.value.length){this.value=this.defaultValue}})};
//validate FAU Search on submit
$.fn.validsearch=function(){return this.submit(function(){
if(this.elements['keywords'].value==''||this.elements['keywords'].value==this.elements['keywords'].defaultValue){$(".tryagain").html("Please enter a keyword before submitting").fadeIn(300);setTimeout('$("p.tryagain").fadeOut()', 5000);return false}})};
//validate email on submit
$.fn.validemail=function(){return this.submit(function(){
if(this.elements['email'].value==''||this.elements['email'].value==this.elements['email'].defaultValue||this.elements['email'].value.indexOf('@')==-1||this.elements['email'].value.indexOf('.',this.elements['email'].value.indexOf('@'))==-1){$("p.tryagain2").html("Please enter a valid email address").fadeIn(300);setTimeout('$("p.tryagain2").fadeOut()', 5000);return false}})};

$.fn.transDrop=function(){
	return this
	.hoverIntent(
		function () {if ($(this).children('ul')) {$(this).children('ul').slideDown(300);}},
		function () {$(this).children('ul').slideUp(300);});
};
//dropdown for absurdly impractical ultra mega primary navigation dropdowns
$.fn.navDrops=function(){
	return this
	.hoverIntent(
		function () {if ($(this).children('ul')) {$(this).children('ul').slideDown(300);}},
		function () {$(this).children('ul').slideUp(300);});
};
// hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+ <http://cherne.net/brian/resources/jquery.hoverIntent.html | author Brian Cherne <brian@cherne.net>
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:6000,interval:150,timeout:500};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);

function dateValidator(){
	var startDate = $('#start_date').val();
	var endDate = $('#end_date').val();
	if (startDate == 'Start Date'){
		$('#start_date').val('');
		startDate = '';//Can't just go round passin' invalid values
	}
	if (endDate == 'End Date'){
		$('#end_date').val('');
		endDate = '';//Can't just go round passin' invalid values
	}
};

//BarkleyREI AJAX Click function 1.0
$.fn.rei_ajax_click=function(templateId, targetId, loadingId){
	return this.click(function(){
		$(loadingId).fadeIn(100);
		var datasource = "/TemplateMarkupCallbackHandler.ashx?templateId=" + templateId + "&amp;",
			datasource = datasource.replace("amp;", ""),
			href = $(this).attr("href").split("?");
			//set cookie, expires in 4:30min
			$.cookie('results_url', datasource + href[1], {expires:.003});
		$.ajax({
			type: "GET",
			url: datasource + href[1],
			dataType: "html",
			success: function(html){
				$(targetId).html(html);
				$(loadingId).hide();
			}
		});
		return false;
	});
};

// Add to planner button
$.fn.plan_btn_add=function(planner_name, status){
	$(this).click(function() {
		//messages						
		var success_msg = "This item has been added to your " + planner_name + ".";
		var fail_msg = "Submission of this item to your " + planner_name + " failed. Please try again.";
		var error_msg = "Error. Submission of this item to your " + planner_name + " may have timed out. Please try again or check your " + planner_name + " to make sure it has been added.";
		//send
		jQuery.ajax({
			url: this.href,
			timeout: 10000,
			error: function() {$(status).html(error_msg).fadeIn(300);status_timeout();},
			success: function(r) { 
				if (r == "success=true") {
					$(status).html(success_msg).fadeIn(300);
					//update tp dropdown
					$("#myItineraryWrapper").load("/gettransform.ashx?templateId=60");
					status_timeout();}
				else if (r == "success=false") {$(status).html(fail_msg).fadeIn(300);status_timeout();}
			}
		});
		return false;
	})
	function status_timeout() {setTimeout('$("' + status + '").fadeOut()', 3000);};
};

// Remove from planner button
$.fn.plan_btn_remove=function(planner_name, status){
	$(this).click(function() {
		//messages						
		var success_msg = "This item has been removed from your " + planner_name + ".";
		var fail_msg = "Removal of this item from your " + planner_name + " failed. Please try again.";
		var error_msg = "Error. Submission of this item to your " + planner_name + " may have timed out. Please try again or check your " + planner_name + " to make sure it has been added.";
		//send
		jQuery.ajax({
			url: this.href,
			timeout: 10000,
			error: function() {$(status).html(error_msg).fadeIn(300);status_timeout();},
			success: function(r) { 
				if (r == "success=true") {
					$(status).html(success_msg).fadeIn(300);
					//update tp dropdown
					$("#myItineraryWrapper").load("/gettransform.ashx?templateId=60");
					status_timeout();}
				else if (r == "success=false") {$(status).html(fail_msg).fadeIn(300);status_timeout();}
			}
		});
		return false;
	})
	function status_timeout() {
		setTimeout('$("' + status + '").fadeOut(750, function() {$("' + status + '").parent("li").remove();})', 3000);
	};
};

// Add to planner form 
$.fn.plan_submit=function(planner_name, status){
	$(this).submit(function() {
		var form = "#" + this.id;
		//messages
		var success_msg = "Checked item(s) have been added to your " + planner_name + ".";
		var fail_msg = "Submission failed. Please ensure that you have checked an item and try again.";
		var error_msg = "Error. Submission of these items to your " + planner_name + " timed out. Please try again or check your " + planner_name + " to make sure it has been added.";
		//gather checkbox values
		var inputs = [];		
		$(':input', this).each(function() {
			if($(this).attr("checked") && !($(this).attr("disabled")))  {
				inputs.push(this.name + '=' + escape(this.value));
			}
		});
	  	//send
		jQuery.ajax({
			data: inputs.join(unescape('%26')),
			url: this.action,
			timeout: 10000,
			error: function() {$(status).html(error_msg).fadeIn(300);status_timeout();},
			success: function(r) { 
				if (r == "success=true") {
					$(status).html(success_msg).fadeIn(300);
					$(form + ' :input').each(function() {
						if($(this).attr("checked"))  {
							$(this).attr({disabled: "disabled",value: ""});	
							//$(this).parent("li").hide();
						};
					});
					//update tp dropdown
					$("#myItineraryWrapper").load("/gettransform.ashx?templateId=60");
					status_timeout();
				}
				else if (r == "success=false") {$(status).html(fail_msg).fadeIn(300);status_timeout();}
			}
		});
		return false;
	});
	function status_timeout() {setTimeout('$("' + status + '").fadeOut()', 3000);};
};

// Add to event calendar button
$.fn.event_btn_add=function(planner_name, status){
	$(this).click(function() {
		//messages
		var success_msg = "This item has been added to your " + planner_name + ".";
		var fail_msg = "Submission of this item to your " + planner_name + " failed. Please try again.";
		var error_msg = "Error. Submission of this item to your " + planner_name + " may have timed out. Please try again or check your " + planner_name + " to make sure it has been added.";
		//send
		jQuery.ajax({
			url: this.href,
			timeout: 10000,
			error: function() {$(status).html(error_msg).fadeIn(300);status_timeout();},
			success: function(r) { 
				if (r == "success=true") {
					$(status).html(success_msg).fadeIn(300);
					

					status_timeout();}
				else if (r == "success=false") {$(status).html(fail_msg).fadeIn(300);status_timeout();}
			}
		});
		return false;
	})
	function status_timeout() {setTimeout('$("' + status + '").fadeOut()', 3000);};
};

// Cookie retrieval and deletion
function get_cookie(cookie_name) {
	var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
	if (results)
		return ( unescape ( results[2] ) );
	else
		return null;
};
function delete_cookie(cookie_name) {
	var cookie_date = new Date ( );  
	cookie_date.setTime ( cookie_date.getTime() - 1 );
	document.cookie = cookie_name += "=; path=/; expires=" + cookie_date.toGMTString();
};

//automatic jQuery cookies if you don't feel like parsing them yourself - credit: Klaus Hartl (stilbuero.de)...Klaus is representin' DEUTSCHLAND!!!
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){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();}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{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]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}return cookieValue;}};


