/**
 * common.js
 * contains common variables and methods used throughout the site
 *
 */


var common = function(){

	this.docRoot = '/';
	this.isInitialLoad = true;
	this.pageName = undefined;
	this.section = undefined;

	this.querystring = (function() {

	    var queryStringDictionary = {};
	    var querystring = decodeURI(location.search);
	    if (!querystring) {
	        return {};
	    }

	    querystring = querystring.substring(1);
	    var pairs = querystring.split("&");

	    for (var i = 0; i < pairs.length; i++) {
	        var keyValuePair = pairs[i].split("=");
	        queryStringDictionary[keyValuePair[0]] = keyValuePair[1];
	    }

	    queryStringDictionary.toString = function() {
	        if (queryStringDictionary.length == 0) {
	            return "";
	        }

	        var toString = "?";

	        for (var key in queryStringDictionary) {
	            toString += key + "=" + queryStringDictionary[key];
	        }
	        return toString;
	    };

	    return queryStringDictionary;
	})();
}

/**
 * after the page loads, do these things
 * then enjoy a sipper of the Reposado
 */
common.prototype.init = function(){
	this.pageName = $("body").attr("name");
	this.section = $("body").attr("section");

	this.initTopNav();
	this.initHomeLink();
	this.initMailListForm();
	this.drawHeadline();
	this.initLeftBorder();

	if (this.section == "contact"){
		this.initContactForm();
	}

	if (this.section == "tequilas"){
		this.initAwardImages();
	}

	this.initTwitterFeed();
}

common.prototype.strToCamelCase = function(str){
	return str.substr(0, 1).toUpperCase() + str.substr(1);
}

common.prototype.initHomeLink = function(){

	switch (this.pageName){
		case 'howToEnjoy':
		case 'reviews':
		case 'news':
		case 'whereToBuy':
		case 'contact':
		case 'privacy':
		case 'terms':

			var leftPos = $('.topBanner').position().left;
			$('body').append('<div onclick="location.href=\'/\'; return false;" style="z-index:99;background:white;opacity:.01;filter: alpha(opacity = 1); width:300px;height:160px; position:absolute;top:30px;left:'+leftPos+'px;cursor:pointer;"');
			break;
	}
}

/**
 * set the left border gradient height now that we know how tall THIS page is
 * these functions are always so unfortunate
 */
common.prototype.initLeftBorder = function(){

	var $fullPageDiv = $(".fullPageWidth");

	if ($fullPageDiv.length){
		var h = $fullPageDiv.height();
		$fullPageDiv.height(Math.max(h, 500));
	}
	if (this.pageName == 'howToEnjoy'){
		var $leftRail = $(".leftRail:first");
		$leftRail.height(Math.max($leftRail.height(), 800));
	}

	if (this.pageName == 'news'){

		var $rightRail = $(".rightRail:first");
		var $leftRail = $(".leftRail:first");
		$rightRail.height(Math.max(
			$leftRail.height(),
			($(".rightRail .colHeader:first").height() + $(".rightRail div.line:first").height() + $(".rightRail img:last").height())

		));
	}

	var $leftBorder = $(".borderGradientLeft:first");
	var totalHeight = $(".outerContainer").height() - $(".footer").height() - $(".topBanner").height() - 25;

	$leftBorder.height(totalHeight);
}

common.prototype.initTopNav = function(){
	var self = this;
	var $images = $('#topNav img');

	// light up the current page (if we're on such a page)
	$images.each(function(){
		var linkTo = $(this).attr("linkTo");
		if (self.strToCamelCase(self.pageName) == linkTo || self.strToCamelCase(self.section) == linkTo){
			$(this).addClass('nav'+linkTo+'On')
		}
	});


	// setup the rollovers
	function mouseover(){
		var linkTo = $(this).attr("linkTo");
		$(this).addClass('nav'+linkTo+'On');
	}

	function mouseout(){
		var linkTo = $(this).attr("linkTo");
		if (self.strToCamelCase(self.pageName) != linkTo && self.strToCamelCase(self.section) != linkTo){
			$(this).removeClass('nav'+linkTo+'On');
		}
	}

	$images.bind({
		'mouseover': mouseover,
		'mouseout': mouseout
	});
}


/**
 * our footer is doing it in the Facebook with the Twitter
 */
function updateTwitter(){
	$.getJSON("http://twitter.com/status/user_timeline/69486986.json?count=1&callback=?", function(data) {
		if (data.length){
			$('.latestHeadline').html(data[0].text);
		} else {
			$('.latestHeadline').html('&nbsp;');
		}
	});
}

common.prototype.initTwitterFeed = function(){
	updateTwitter();
	setTimeout("updateTwitter", 2 * 60 * 1000); // update twitter every 2 minutes
}


/**
 * our footer is doing it in the Facebook with the Twitter
 */
common.prototype.initMailListForm = function(){
	var $formContainer = $(".footer .col3");
	var $submitButton = $formContainer.find(".buttonSubmit");


	$formContainer.find("input").bind({
		'focus': function(){
			var defaultVal = $(this).attr("defaultVal");
			if ($(this).val() == defaultVal){
				$(this).val("");
			}
		},
		'blur': function(){
			var defaultVal = $(this).attr("defaultVal");
			if ($(this).val() == ""){
				$(this).val(defaultVal);
			}
		}
	});

	$submitButton.bind({
		'click': function(){
			var $email = $formContainer.find("input.email");
			var $postalCode = $formContainer.find("input.postalCode");

			if ($email.val() == $email.attr("defaultVal")){
				$email.focus();
				return;
			}
			if ($postalCode.val() == $postalCode.attr("defaultVal")){
				$postalCode.focus();
				return;
			}
			$formContainer.hide();
			$.ajax({
				type: 'POST',
				url: "/resources/jsapi.php",
				data: {
					action: "mailListForm",
					email: $email.val(),
					postalCode: $postalCode.val(),
					mailList: true
				},
				success: function() {
					$formContainer.hide().html("<div class=\"contactFormSuccess\">We thank you for your interest</div>").fadeIn();
				}
			});
		}
	});
}


/**
 * contact page form
 */
common.prototype.initContactForm = function(){
	$formContainer = $(".contactFormContainer:first");
	$buttonSubmitForm = $formContainer.find(".buttonSubmitForm");

	$buttonSubmitForm.bind({
		"click": function(){

			var formData = {
				action: "contactForm",
				contactType: $formContainer.find("input[name=contactType]:checked").val(),
				nameFirst: $formContainer.find("input[name=nameFirst]").val() || null,
				nameLast: $formContainer.find("input[name=nameLast]").val() || null,
				email: $formContainer.find("input[name=email]").val() || null,
				mailList: $formContainer.find("input[name=mailList]").is(':checked'),
				company: $formContainer.find("input[name=company]").val() || null,
				comments: $formContainer.find("textarea[name=comments]").val() || null
			};

			$.ajax({
				type: 'POST',
				url: "/resources/jsapi.php",
				data: formData,
				success: function() {
					$formContainer.find("input, textarea").each(function(){ $(this).attr("disabled", true); });
					$buttonSubmitForm.hide().replaceWith("<div class=\"contactFormSuccess italic\">Thank you for your interest</div>").fadeIn();
				}
			});
		}
	});
}


/**
 * initialize rotating award images on each tequila page
 */
common.prototype.initAwardImages = function(){
	this.awardImageIndex = 0;

	function rotate(){

		var awardImages = [];
		var $awardImage = $(".awardImage:first");

		switch (common.pageName){
			case 'blanco':
				awardImages = [
					"medalBlanco2008cancun.jpg",
					"medalBlanco2010SanFran.jpg"
				];
				break;

			case 'reposado':
				awardImages = [
					"medalReposado2010SanFran.jpg",
					"medalReposado2008Cancun.jpg"
				];
				break;

			case 'extraAnejo':
				awardImages = [
					"medalExtraAnejo2010SanFran.jpg",
					"medalExtraAnejo2008Cancun.jpg",
					"medalExtraAnejoTopAgave2008.jpg"
				];
				break;
		}

		$awardImage
			.fadeOut('slow', function(){
				$(this).attr("src", '/resources/img/'+awardImages[common.awardImageIndex]);
			})
			.fadeIn('slow');


		common.awardImageIndex = (common.awardImageIndex == (awardImages.length-1))
			? 0
			: common.awardImageIndex + 1;
	}

	window.setInterval(rotate, 4000);
}


/**
 * the big ribbony looking thing right aligned, middle of the page
 */
common.prototype.drawHeadline = function(){
//console.time("drawHeadline")
	var page = this.strToCamelCase(this.pageName);
	var position = $(".rightRail").position();

	switch (page){

		case 'Tequilas':
			position.top += 181;
			position.left -= 367;
			break;

		case 'Blanco':
			position.top += 263;
			position.left -= 382;
			break;

		case 'Reposado':
			position.top += 244;
			position.left -= 183;
			break;

		case 'ExtraAnejo':
			position.top += 244;
			position.left -= 252;
			break;

		case 'Distillery':
			position.top += 212;
			position.left -= 358;
			break;

		case 'Home':
			position.top += 150;
			position.left -= 313;
			break;

		default:
			return; // not currently on a page that has this functionality
	}


	this.$headlineDiv = this.$headlineDiv || $('.headline:first');
	if (! this.$headlineDiv.length){
		this.$headlineDiv = $('<div class="sprite headline headline'+page+'"></div>');
		this.$headlineDiv.css({'top': position.top, 'left': position.left});
		$("body").append(this.$headlineDiv);
		this.$headlineDiv.fadeIn(2000);

	} else {
		this.$headlineDiv.css({'top': position.top, 'left': position.left});
	}

//console.timeEnd("drawHeadline")
}

var common = new common();



var news = function(){
	this.monthNames = ['January','February','March','April','May','June','July','August','September','October','November','December'];
	this.dayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
}

news.prototype.getCalendarData = function(){

	//'http://www.google.com/calendar/feeds/jubileate@gmail.com/public/basic?alt=json&callback=?'
	$("#eventsCalendar").fullCalendar({
		events: $.fullCalendar.gcalFeed("http://www.google.com/calendar/feeds/jubileate@gmail.com/public/basic"),
		loading: function(bool) {
			if (! bool) news.showEvents();
		}
	});
}

news.prototype.showEvents = function(){
	var self = this;
	var eventsDrawn = {};

	$("div.fc-day-number").each(function(){ $(this).removeClass("highlighted"); });

	var $eventSummary = $('<div></div>');
	$('span.fc-dayHasEvent').each(function(){

		var eventTitle = $(this).attr("eventTitle");
		var eventDesc = $(this).attr("eventDesc");
		var eventStart = new Date($(this).attr("eventStart"));
		var eventEnd = new Date($(this).attr("eventEnd"));

		if (! eventsDrawn[eventStart] && ! (eventsDrawn[eventStart] == eventTitle) ){
			var eventDateFormatted = self.dayNames[eventStart.getDay()] + ', ' + self.monthNames[eventStart.getMonth()] + ' ' + eventStart.getDate();
			$eventSummary.append('<h4>'+eventDateFormatted+'</h4><h3>'+eventTitle+'</h3><p>'+eventDesc+'</p>');
		}


		// make the date bold on the calendar
		$("div.fc-day-number").each(function(){
			var thisDay = $(this).text();

			//if (thisDay == eventStart.getDate()){

				if ($(this).parents("td:first").hasClass("fc-other-month") && parseInt(thisDay) > 15 ){
					var thisDate = new Date(self.lastMonth);

				} else if ($(this).parents("td:first").hasClass("fc-other-month") && parseInt(thisDay) < 15 ){
					var thisDate = new Date(self.nextMonth);

				} else {
					var thisDate = new Date(self.currentDisplayedMonth);
				}



				thisDate.setDate(thisDay);
				thisDate.setHours(0);

				eventStart.setHours(0);
				eventEnd.setHours(23)

				//console.log(thisDate)
				//console.log(eventStart)
				//console.log(eventEnd)
				//console.log('next')

				if (thisDate >= eventStart && thisDate <= eventEnd){
					$(this).addClass("highlighted");
				}
			//}
		});

		eventsDrawn[eventStart] = eventTitle;

	});

	$('#eventSummary').html($eventSummary);
	common.initLeftBorder();

}

news.prototype.toggleMonthDisplay = function(direction){
	$('#eventsCalendar').fullCalendar(direction);

	if (direction == "prev"){
		this.currentDisplayedMonth.setMonth(this.currentDisplayedMonth.getMonth()-1);
		this.lastMonth.setMonth(this.lastMonth.getMonth()-1);
		this.nextMonth.setMonth(this.nextMonth.getMonth()-1);

	} else {
		this.currentDisplayedMonth.setMonth(this.currentDisplayedMonth.getMonth()+1);
		this.lastMonth.setMonth(this.lastMonth.getMonth()+1);
		this.nextMonth.setMonth(this.nextMonth.getMonth()+1);
	}

	this.drawMonthNav();
}

news.prototype.drawMonthNav = function(){
	$("#eventsCalendarHead").html(
		'<span class="monthToggle" onclick="news.toggleMonthDisplay(\'prev\');">' + this.monthNames[this.lastMonth.getMonth()] +' '+ this.lastMonth.getFullYear() + '</span> ' +
		'<span class="bold">' + this.monthNames[this.currentDisplayedMonth.getMonth()] +' '+ this.currentDisplayedMonth.getFullYear() + '</span> ' +
		'<span class="monthToggle" onclick="news.toggleMonthDisplay(\'next\');">' + this.monthNames[this.nextMonth.getMonth()] + ' ' + this.nextMonth.getFullYear() + '</span>'
	);
}

/**
 * TODO
 * duplicate events on weeklongs
 * some events not coming through?
 * window height
 */

news.prototype.init = function(){
	this.now = new Date();
	this.currentDisplayedMonth = new Date();
	this.lastMonth = new Date();
	this.nextMonth = new Date();
	this.lastMonth.setMonth(this.now.getMonth()-1);
	this.nextMonth.setMonth(this.now.getMonth()+1);

	this.getCalendarData();
	this.drawMonthNav();
}

var news = new news();


/**
 * page init routines run on all pages
 * window.load should work better than document.ready because it waits for all
 * images to load, without which, the banner positioning doesnt always work right
 *
 * @see http://4loc.wordpress.com/2009/04/28/documentready-vs-windowload/
 */
//$(document).ready(function(){
$(window).load(function(){
	common.init();
	$(window).bind("resize", $.proxy(common.drawHeadline, common));

	if (common.pageName == "news"){

		news.init();
	}
});
