/*global $, window */

var AEG = AEG || {};

var next_dates;
var prev_dates;
var rightNow = new Date();
var current_month = false;
var current_year = false;
var next_month = false;
var next_year = false;
var prev_month = false;
var prev_year = false;

function init_months(month, year)
{
	current_month = month;
	current_year = year;
	if (month == 12)
	{
		next_year = year+1;
		next_month = 1;
		prev_year = year;
		prev_month = month-1;
	}
	else if (month == 1)
	{
		prev_year = year-1;
		prev_month = 12;
		next_year = year;
		next_month = month+1;
	}
	else
	{
		next_month = month+1;
		next_year = year;
		prev_month = month-1;
		prev_year = year;
	}
}
init_months(rightNow.getMonth()+1, rightNow.getFullYear());


AEG.current_dates = null;

AEG.calendar = function () {
	
	if (!$('div.calendar').length) {
		return false;
	}
	
	AEG.calendarData = $.extend({
		url: '#'
	}, AEG.calendarData || {});
	
	AEG.calendarData.date = AEG.m.parseDate(AEG.calendarData.date);

	$.ajax({
		url: '/events/get_event_dates/' + (AEG.calendarData.date.getMonth()+1) + '/' + AEG.calendarData.date.getFullYear() + '/',
		type: 'GET',
		async: false,
		success: function(datum1) {
			AEG.current_dates = datum1.result;
			$.ajax({
				url: '/events/get_event_dates/' + next_month + '/' + next_year + '/',
				type: 'GET',
				async: true,
				success: function(datum2) {
					next_dates = datum2.result;
					
					$.ajax({
						url: '/events/get_event_dates/' + prev_month + '/' + prev_year + '/',
						type: 'GET',
						async: true,
						success: function(datum3) {
							prev_dates = datum3.result;
							
							$.extend(AEG.current_dates, next_dates, prev_dates);

							// console.log(AEG.current_dates);
							
						}
					});
					
				}
			});
			
		}
	});
	
	$('div.calendar').datepick({
		
		// Gets called when the calendar month is changed
		onChangeMonthYear: function (year, month) {
			// load in dates for selectable stuff
			// $.get('/events/get_event_dates/' + month + '/' + year + '/', null, function(datum) {
			// 	AEG.current_dates = datum.result;
			// });
			got_dates = false;
			$('.datepick-loading').show();
			
			init_months(month, year);
			
			// load previous and next months
			$.ajax({
				url: '/events/get_event_dates/' + next_month + '/' + next_year + '/',
				type: 'GET',
				async: true,
				success: function(datum) {
					next_dates = datum.result;
					
					$.ajax({
						url: '/events/get_event_dates/' + prev_month + '/' + prev_year + '/',
						type: 'GET',
						async: true,
						success: function(datum) {
							prev_dates = datum.result;
							
							AEG.current_dates = $.extend({}, next_dates, prev_dates);
							
							$('.datepick-loading').hide();
						}
					});
					
				}
			});
			
			
		},
		
		// Gets called when a date in the calendar is clicked
		onSelect: function (range) {
			window.location.href = AEG.calendarData.url + AEG.m.toDateStr(range[0]);
		},
				
		// check if date is selectable
		onDate: function (date) {
			var selectable = false;
			if (typeof AEG.current_dates[AEG.m.toDateStr(date)] != undefined && AEG.current_dates[AEG.m.toDateStr(date)]) {
				selectable = true;
			};
			return {content: date.getDate(), selectable: selectable};
		},
		
		onShow: function (picker, inst) {
			// $('.datepick-loading').toggle(false);
			$('.datepick-loading').height(picker.outerHeight());
			
		},
		
		useMouseWheel: false,
		changeMonth: false,
		defaultDate: AEG.calendarData.date,
		selectDefaultDate: true,
		minDate: new Date(),
		nextText: '&gt;',
		prevText: '&lt;',
		renderer: $.extend($.datepick.defaultRenderer, {
			picker: '<div class="datepick">' +
				'{months}' +
				'<div class="datepick-clear-fix"></div></div>',
			month: '<div class="datepick-month">' +
			'<div class="datepick-month-header">{link:prev}<span>{monthHeader}</span>{link:next}</div>' +
			'<table><tbody>{weeks}</tbody></table></div>'
		})
	});

	$('.datepick-loading').height($('.datepick').outerHeight());
	
};

// Initialize feature carousel
AEG.carousel = function () {
	var $ul = $('ul.features').first(), $li,
		btns = [], html, k, l,
		afterEnd;

	if (!$ul.length) {
		return false;
	}

	$li = $ul.find('li');
	l = $li.length;

	if (l < 4) {
		return true;
	}

	// don't need this as we can now specify number of items to return from AEG's featured_events feed
	// k = 3 - (l%3 || 0);
	// while (k--) {
	// 	$li.eq(k + (l > 6 ? 3 : 0)).clone().appendTo($ul);
	// }

	$li = $ul.find('li');
	l = $li.length;

	// Create the feature nav
	html = '<ul class="feature-nav">';
	$li.each(function (i) {
		btns.push('ul.feature-nav a.carousel-link:eq('+i+')');
		html += '<li><a class="carousel-link carousel-link-'+i+'" href="#">&nbsp;</a></li>';
		$(this).addClass('carousel-link carousel-link-'+i);
	});
	$ul.before(html + '</ul>');

	$ul.wrap('<div class="carousel" />');

	// Highlight the currently displayed features in the nav
	afterEnd = function(a) {
		if (a.attr('class').match(/carousel-link-([0-9]*)/) == null || a.attr('class').match(/carousel-link-([0-9]*)/)[1] == undefined)
		{
			return false;
		}
		var i = +a.attr('class').match(/carousel-link-([0-9]*)/)[1];

		$('ul.feature-nav')
			.find('a.carousel-link')
			.removeClass('current')
			.slice(i, i+3)
				.addClass('current')
				.end()
			.slice(0, i+3 > l ? (i + 3) - l : 0)
				.addClass('current');
	};
	
	afterEnd($li.slice(0, 3));
	
	$('ul.features li').show();
	
	$('div.carousel').jCarouselLite({
		afterEnd: afterEnd,
		// Enable these lines if you want it to autoscroll
		auto: 6000,
		speed: 1800,
		btnGo: btns,
		pauseOnHover: true,
		scroll: 3
	});
	
	
};

// Activate an overlay link
AEG.overlay = (function () {
	var $screen, success;

	success = function (html) {
		var height, $overlay;

		$overlay = $(innerShiv(html, false));
		$overlay = $overlay.find('.overlay').add($overlay.filter('.overlay'));
		$overlay.hide().appendTo('body').slideDown('fast');

		height = $('body').height();
		if (height > $screen.height()) {
			$screen.height(height)
		}

		$screen.fadeIn('fast');

		$('html, body').animate({ scrollTop:0 });
	}

	return function (value) {
		var $this = $(this), $parent;

		// Activated when the user wants to close the overlay
		if (value === false || $this.hasClass('overlay-close')) {
			// If the closer was clicked within an overlay, only close the parent
			$parent = $this.closest('.overlay');
			if ($parent.length) $parent.slideUp('fast');
			else $('.overlay').not('a').slideUp('fast');

			if ($screen) $screen.fadeOut('fast');
			return false;
		}

		if (!$screen) {
			$screen = $('<div class="overlay-screen"></div>')
				.hide()
				.click(function () {
					// Hide the overlay when the background screen is clicked
					AEG.overlay(false);
				})
				.appendTo('body');
		}

		// Test to see if the user passed HTML directly
		if (typeof value == 'string') {
			success(value);
			return false;
		}

		// Activated when the overlay is a link
		$.ajax({
			url: $this.attr('href'),
			success: success
		});

		return false;
	}
}());

// Geolocation
AEG.geo = {
	submit: function(){
		var zip = $(this).find('input[name=search]');
		var url = $(this).attr('action');
		var data = $(this).serialize();
		AEG.geo.resolve(url, data);
		AEG.overlay(false); // get rid of overlay
		return false;
	},
	all_locations: function () {
		AEG.cookies.unset('geo');
		AEG.cookies.set('all_locations', true);
		$('nav.geo-nav strong').html("All Locations");
		AEG.overlay(false);
		return false;
	},
	current_location: function () {
		AEG.geo.resolve('/geo/use_current');
		AEG.overlay(false);
		return false;
	},
	resolve: function(url, data) {
		var cookie_ttl = 24*365.25*10;	// ten years in hours

		$.ajax({
			url: url,
			type: "GET",
			data: data,
			success: function(data) {
			    //called when successful
				if ((data && data.length > 0) || (data['city'] !== null && data['city'] !== undefined)) {
					geo = data[0] || data;
					var prev_geo = AEG.cookies.get('geo');
					var new_geo = JSON.stringify(geo);
					AEG.cookies.set('geo', new_geo, cookie_ttl, '/', location.host);
					AEG.cookies.unset('all_locations');
					$('nav.geo-nav strong').html(geo.city + ", " + geo.region);

					// If location has changed, refresh the page to pull in updated content for new location
					if (new_geo!=prev_geo) {
						top.location = top.location.href;
					}
				}
				else if (AEG.cookies.get('geo') || AEG.cookies.get('all_locations')) {
					// no results, and we had a good location at one time... so not our first visit.
					alert('Sorry, we could not confirm that location.');
				}
				else
				{
					AEG.geo.all_locations();
				}
			},
			error: function() {
			    //called when there is an error
				alert('Sorry, there was an error setting your location.');
			}
		});
	},
	init: function ()
	{
		var geo = AEG.cookies.get('geo');
		geo = JSON.parse(geo);
		if (geo)
		{
			$('nav.geo-nav strong').html(geo.city + ", " + geo.region);
			$('.newsletter-location').html(geo.city);
		}
		else if (AEG.cookies.get('all_locations'))
		{
			$('nav.geo-nav strong').html('All Locations');
			$('.newsletter-location').html('your area');
		}
		else
		{
			// check for all locations cookie, I guess... so that we keep that instead of
			// trying to geocode their IP address
			if (!AEG.cookies.get('geo') && !AEG.cookies.get('all_locations'))
			{
				AEG.geo.current_location();
			}
		}
	}
};

AEG.tweets = {
	init: function ()
	{
		// set up scrollbar
		var pane = $('.scroll-pane');
		pane.jScrollPane();
		var paneapi = pane.data('jsp');
		
		var tweets = [];
		var counter = 0;
		$.get('/index/get_tweets', '', function (results) {
			tweets = results;
			// prepopulate
			for (var i=0; i < 25; i++) {
				paneapi.getContentPane().find('ul').append($(AEG.tweets.tweetparse(tweets[i])));
			};
			AEG.tweets.externalize_links();
			paneapi.reinitialise();
			
		});
		
		var block = 1;
		
		$('.twitter-more').live('click', function (ev) {
			ev.preventDefault();
			for (var i=(25*block); i < (25*block)+25; i++) {
				paneapi.getContentPane().find('ul').append($(AEG.tweets.tweetparse(tweets[i])));
			};
			block++;
			AEG.tweets.externalize_links();
			paneapi.reinitialise();
			if (block == 4) {
				$('a.twitter-more').remove();
			};
		});
		
		
		
	},
	tweetparse: function (tweet)
	{
		time = AEG.tweets.relative_time(tweet.created_at);
		
		var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
        var tweet_text = tweet.text.replace(regexp,"<a href=\"$1\">$1</a>")
        
		var html = '<li><a href="http://twitter.com/'+tweet.from_user+'"><img src="'+tweet.profile_image_url+'" alt="" width="50" height="50" /></a><div>'+tweet_text+' <span><a class="handle" href="http://twitter.com/'+tweet.from_user+'">'+tweet.from_user+'</a> <a class="permalink" href="http://twitter.com/'+tweet.from_user+'/status/'+tweet.id+'">'+time+'</a></span></div></li>';
		return html;
	},
	relative_time: function (time_value) {
      var parsed_date = AEG.tweets.parse_date(time_value);
      var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
      var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
      var r = '';
      if (delta < 60) {
	r = delta + ' seconds ago';
      } else if(delta < 120) {
	r = 'a minute ago';
      } else if(delta < (45*60)) {
	r = (parseInt(delta / 60, 10)).toString() + ' minutes ago';
      } else if(delta < (2*60*60)) {
	r = 'an hour ago';
      } else if(delta < (24*60*60)) {
	r = '' + (parseInt(delta / 3600, 10)).toString() + ' hours ago';
      } else if(delta < (48*60*60)) {
	r = 'a day ago';
      } else {
	r = (parseInt(delta / 86400, 10)).toString() + ' days ago';
      }
      return 'about ' + r;
    },
	parse_date: function(date_str) {
      // The non-search twitter APIs return inconsistently-formatted dates, which Date.parse
      // cannot handle in IE. We therefore perform the following transformation:
      // "Wed Apr 29 08:53:31 +0000 2009" => "Wed, Apr 29 2009 08:53:31 +0000"
      return Date.parse(date_str.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
    },
	externalize_links: function() {
		$('.scroll-pane a[href^="http://"]')
		  .attr({
		    target: "_blank", 
		    title: "Opens in a new window"
		  });
		$('.scroll-pane a[href^="https://"]')
		  .attr({
		    target: "_blank", 
		    title: "Opens in a new window"
		  });
		
	}
    
};

// Generally useful stuff
AEG.m = {

	// International date string to JavaScript date object. Provide a minumum date as the second argument.
	parseDate: function(str, minDate) {
		var this_date;
		
		if (typeof str != 'undefined') this_date = new Date(str.substr(0,4), parseInt(str.substr(5, 2), 10)-1, str.substr(8, 2), str.substr(11, 2), str.substr(14, 2), str.substr(17, 2));
		
		if (typeof minDate != 'undefined' && !(this_date > minDate)) this_date = new Date(minDate.getTime());
		return this_date;
	},

	// Throw it a date and it'll throw you a YYYY-MM-DD
	toDateStr: function(date) {
		var m = (date.getMonth()+1).toString(), d = (date.getDate()).toString();
		return date.getFullYear() + '-' + (m.length<2 ? '0'+m : m) + '-' + (d.length<2 ? '0'+d : d);
	},
	
	goToBySelector: function(selector){
		$('html,body').animate({scrollTop: ($(selector).offset().top - 20)},'fast');
	}
	

};

AEG.cookies = (function () {
	var c = {};
	
	/**
	 * Highly based on
	 * @author 	Maxime Haineault (max@centdessin.com)
	 * @version	0.4
	 * @desc 	JavaScript cookie manipulation class
	 * 
	 */

	/** Get a cookie's value
	 *
	 *  @param integer	key		The token used to create the cookie
	 *  @return void
	 */
	c.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.host (optional)
	 *  @param boolean 	secure	Use SSL or not, default false (optional)
	 * 
	 *  @return setted cookie
	 */
	c.set = function(key, value, ttl, path, domain, secure) {
		cookie = [key+'='+    escape(value),
		 		  'path='+    ((!path   || path=='')  ? '/' : path),
		 		  'domain='+  ((!domain || domain=='')?  window.location.host : domain)];

		if (ttl)         cookie.push('expires='+this.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
	 */
	c.unset = function(key, path, domain) {
		path   = (!path   || typeof path   != 'string') ? '' : path;
        domain = (!domain || typeof domain != 'string') ? '' : domain;
		if (this.get(key)) this.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
	 */
	c.hoursToExpireDate = function(ttl) {
		if (parseInt(ttl) == 'NaN' ) return '';
		else {
			now = new Date();
			now.setTime(now.getTime() + (parseInt(ttl) * 60 * 60 * 1000));
			return now.toUTCString();			
		}
	};

	/** Return true if cookie functionnalities are available
	 *
	 *  @return boolean
	 */
	c.test = function() {
		this.set('b49f729efde9b2578ea9f00563d06e57', 'true');
		if (this.get('b49f729efde9b2578ea9f00563d06e57') == 'true') {
			this.unset('b49f729efde9b2578ea9f00563d06e57');
			return true;
		}
		return false;
	};

	/** If Firebug JavaScript console is present, it will dump cookie string to console.
	 * 
	 *  @return void
	 */
	c.dump = function() {
		if (typeof console != 'undefined') {
			console.log(document.cookie.split(';'));
		}
	};

	return c;
})();


// On DOM ready
$(function () {
	
	// Shim for HTML5 placeholders
	$('body').placeholders();
	
	// Initialize the carousel for the front page etc.
	AEG.carousel();
	
	// Elements that require equal heights
	$('.equalize').parent().each(function () {
		$(this).find('.equalize').equalizeHeights();
	});
	$('.equalize-b').equalizeHeights();

	// Fix broken dimensions of Facebook container
	if ($('.equalize.facebook').length > 0 && $('.equalize.twitter').length > 0) {
		$('.equalize.facebook').height( $('.equalize.facebook').height() + $('.equalize.twitter').css('paddingTop').replace(/px/,'')*1 + $('.equalize.twitter').css('paddingBottom').replace(/px/,'')*1 );
		$('.equalize.facebook').width( $('.equalize.facebook').width() + $('.equalize.twitter').css('paddingLeft').replace(/px/,'')*1 + $('.equalize.twitter').css('paddingRight').replace(/px/,'')*1 );
	}
	
	// Custom select boxes
	new CustomFormElements();
	
	// Calendar widget
	AEG.calendar();

	// Color box for galleries
	$('ul.photo-list').find('a').colorbox();
	$('a.colorbox').colorbox();

	// Search form placeholder
	$('form.search input[name=term], .geo-overlay form input[name=search]')
		.focus(function(){
			if ($(this).val()==$(this).attr('placeholder')) $(this).val('');
		})
		.blur(function(){
			if ($(this).val()=='') $(this).val($(this).attr('placeholder'));
		});

	// Activate overlay links
	$('a.overlay, a.overlay-close').live('click', AEG.overlay);

	// Geo overlay form
	$('.geo-overlay form').live('submit', AEG.geo.submit);
	
	$('a.geo-overlay-all-locations').live('click', AEG.geo.all_locations);
	
	// $('a.geo-overlay-current-location').live('click', AEG.geo.current_location);
	// $('a.geo-overlay-current-location').live('click', AEG.overlay(false));
	
	AEG.geo.init();
	
	// find links that open to external sites and open them in a new window
	
	// nice easing for scrolling to archives on /news/index
	$('a.view-archives').click(function (ev) {
		ev.preventDefault();
		AEG.m.goToBySelector('#archives');
	});
	
	$('a[href^="http://"]')
	  .attr({
	    target: "_blank", 
	    title: "Opens in a new window"
	  });
	$('a[href^="https://"]')
	  .attr({
	    target: "_blank", 
	    title: "Opens in a new window"
	  });
	
	
	// run tweets if on home page
	if (window.location.pathname == "/")
	{
		AEG.tweets.init();
	}
	
	


});

