/* Author:
Mike Malusa (mikemalusa.com) @ Bullfrog Communications (ebullfrog.com)
*/

var oldIE;
var galLen;
var galCur;

$(document).ready(function() {

	$('header').append('<div id="loader" class="loader ir">Loading</div>');

	// Keep the correct aspect ratio of the background image.
	$(window).load(function() {
		var theWindow = $(window),
			$bg = $('#bgHolder #curBG'),
			aspectRatio = $bg.width() / $bg.height();

		function resizeBg() {
				if ((theWindow.width() / theWindow.height()) < aspectRatio) {
					$('#bgHolder').removeClass().addClass('taller');
				} else {
					$('#bgHolder').removeClass().addClass('wider');
				}
		}
		theWindow.resize(function() {
			resizeBg();
		}).trigger('resize');
	});

	// Main Nav
	$('#mainNav a[href$="php"]').each(function(idx) {
		$(this).bind('click', function(e) {
			var gallery = false;
			if ( $(this).hasClass('gallery') )
				gallery = true;
			loadContent($(this).attr('href'),$(this).text(),gallery);

			$(this).blur();
			e.preventDefault();
		});
	});
	// Hide drop down menu after a selection from the drop down is made
	$('#mainNav ul ul a').each(function(idx) {
		$(this).bind('click', function(e) {
			var ddLink = $(this);
			ddLink.closest('ul').addClass('hideDD');
			setTimeout(function(){
				ddLink.closest('ul').removeAttr('class');
			},1000);
		});
	});
	// Hide the drop down after the parent link is clicked
	$('#mainNav ul a[class*="dd"]').bind('click', function(e) {
		$(this).next().addClass('hideDD');
		$(this).mouseout(function() {
			$(this).next().removeAttr('class');
			$(this).unbind('mouseout');
		});
	});

	addClose();

	// Stuff to fix <=IE8
	var ieVer = msieversion();
	if (ieVer < 9) {
		oldIE = ieVer;
		/*$('body').append('<div class="bottomStripe"></div>');*/
		if (ieVer <= 7)
			$('#mainNav ul ul').prepend('<li class="ddSpacer"></li>');
	}

});

// Get IE Version
function msieversion() {
	var ua = window.navigator.userAgent;
	var msie = ua.indexOf ( "MSIE " );
	if ( msie > 0 ) {
		return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )))
	}
}


// Loads a new background image with the same name as the page it is loading
// ex. about.html will load photos/bgs/about.jpg
function loadBG(bgImg) {
	$('#loader').css({'top':-32, 'display':'block'}).stop().animate({'top':27}, 400);
	var img = new Image();
	$(img).load(function() {
		$(this).hide();
		$('#loader').stop().animate({'top':-32}, 300, function(){ $(this).css('display','none') });
		$('#bgHolder').append(this);
		$(this).fadeIn(800,function() {
			$('#bgHolder #curBG').remove();
			//$('#bgHolder').attr('id','curBG');
			$(this).attr('id','curBG');
			//$('#loader').stop().animate({'top':-32}, 300, function(){ $(this).css('display','none') });
		});
	})
	.error(function() {
		console.log('Photo not found');
		$('#loader').stop().animate({'top':-32}, 300, function(){ $(this).css('display','none') });
	})
	.attr('src', bgImg);
}

function loadContent(url,title,gallery) {
	$('#main').unbind('mouseenter mouseleave');
	//theLink = $(this).attr('href');
	//loadBG(url.split('.')[0]);
	if (!gallery) {
		loadBG('photos/bgs/' + url.split('.')[0].split('/')[url.split('.')[0].split('/').length-1]+'.jpg');
		$('#main').stop(false,true).animate({
			'opacity': 0,
			'left': '-=150'
		}, 200 ,function() {
			$('#main').empty().load(url +' #content',function() {
				addClose();
				$('#main').css('left',-150).animate({
					opacity:1,
					left:0
				},500, function(){ if(oldIE) $('#main').removeAttr('style'); });
			});
		});
	} else { // Gallery page
		$('#main').stop(false,true).animate({
			'opacity': 0,
			'left': '-=150'
		}, 200 ,function() {
			$('#main').empty().load(url +' #content',function() {
				startGallery();
				$('#main').css('left',-150).animate({
					'opacity':1,
					'left':0//'-480'//0
				},500, function(){ if(oldIE) $('#main').removeAttr('style'); });
			});
		});
	}

	updateHistory(url,title,false);
}

function addClose() {
	$('#main').append('<a href="#" id="close" title="Close">&#10005;</a>');

	$('#close').one('click', function(e) {
		$('#main').animate({
			'opacity': 0,
			'left': '-150'
		}, 500);
		if (oldIE) {
			$(this).fadeOut(500);
		}

		e.preventDefault();
	});
}

function startGallery() {
	//console.log('start gallery');
	galCur = 0;
	galLen = $('#galleryList li').length;

	$('#main').append('<div class="sideSpacer"></div><a href="#" id="prev" class="arrow" title="Prev">&#60;</a> <a href="#" id="next" class="arrow" title="Next">&#62;</a>');

	loadBG($('#galleryList li:first-child a').attr('href'));

	$('#galleryList a').each(function(idx) {
		$(this).bind('click', function(e) {
			loadBG($(this).attr('href'));

			galCur = $(this).parent().index();

			$(this).blur();
			e.preventDefault();
		});
	});

	$('#main').hover( function() {
		$('#main').stop().animate({ 'left': '0' }, 500);
		if ($('#close')) $('#close').fadeOut(200);
	}, function() {
		$('#main').stop().animate({ 'left': '-480' }, 300);
	});
	// Override hover functuin to keep #main hidden
	$('#next, #prev').hover( function(e) {
		e.stopPropagation();
		console.log('hover arrow');
		return false;
	}, function(e) {
		e.stopPropagation();
		console.log('end hover arrow');
		return false;
	});

	$('#next').bind('click', function(e) {
		if (galCur+1 < galLen) {
			galCur += 1;
			loadBG($('#galleryList li').eq(galCur).find('a').attr('href'));
		} else {
			galCur = 0;
			loadBG($('#galleryList li').eq(galCur).find('a').attr('href'));
		}

		$(this).blur();
		e.preventDefault();
	});
	$('#prev').bind('click', function(e) {
		if (galCur-1 >= 0) {
			galCur -= 1;
			loadBG($('#galleryList li').eq(galCur).find('a').attr('href'));
		} else {
			galCur = galLen-1;
			loadBG($('#galleryList li').eq(galCur).find('a').attr('href'));
		}

		$(this).blur();
		e.preventDefault();
	});

}

function updateHistory(url,title,skipHistory) {
	//console.log(url+', '+title);
	document.title = title + ' \u00AB Event Kings';
	var stateObj = {
		title: title,
		url: url
	};
	if (!skipHistory) {
		if (typeof window.history.pushState == 'function') {
			// push on to history
			window.history.pushState(stateObj,title,url);
		}
	}
}

window.onpopstate = function(event) {
	// if is one of ours
	if (event.state) {
		// load the content
		loadContent(window.location.pathname, event.state.title);
	}
	else { // we need to make it one of ours
		// generate stateObj, this is used on the pop event
		var stateObj = {
			title: document.title,
			url: window.location.pathname
		};
		window.history.replaceState(stateObj,document.title,window.location.pathname);
	}
}

$(document).on('submit', '#contactForm', function(e){
	e.preventDefault();
	var form = this;
	var action = $(form).attr('action');
	$('#submit')
		.after('<img src="img/loader.gif" class="loader" />')
		.attr('disabled','disabled');

	$.post(action, {
			name: $('#name').val(),
			email: $('#email').val(),
			phone: $('#phone').val(),
			date: $('#date').val(),
			comments: $('#comments').val()
		},
		function(data){
			$('#contactForm #submit').removeAttr("disabled");
			$('#response').remove();
			$('#contactForm').before('<div id="response" class="response">'+data+'</div>');
			$('#response').hide().slideDown();
			$('#contactForm img.loader').fadeOut(500,function(){$(this).remove()});
			if(data=='Your message has been sent.') $('#contactForm').slideUp();
		}
	);
});
