/* 
	dd|a Common Scripts
	copyright 2009
	author: Jacob Dunn
	
	Scripts that are used site-wide.
	
	Includes:
		
		* Ajax Functionality
		* Sifr Replacement
		* Flash Embeds
		* Navigation Animation
		* Anchor Animation
		* Print Functionality
		* Facebox initiation
		* Form Compilation and Sending
	
	Notes:
	
		Honestly, there's a lot in here - probably need to abstract some of this out into new jquery plugins

*/

var redirect;

$(document).ready(function() {
	
	//Check to make sure we're on the home page
	if(redirect == null || redirect != false)
		if(checkIsHome()) return;
	
	//Functions to be called after load
	init();
	
	//Content specific functions called after ajax loads, as well
	content_init();
	
	//Set up ajax
	setupAjax();
});

var hidden = false;

function init(){
	
	//Set up toggle button
	var offset = $('#center').width() + $('#center').offset().left;
	
	$('#toggle span').css( {backgroundPosition: "100% 100%"} );
	
	$('#toggle').toggle(
		function(){
			$(this).find('span').stop().animate(
				{backgroundPosition:"(100% 0%)"}, 
				{duration:400});
			$('#center').animate(
				{left:-offset+'px'},
				{duration:400,
			     easing:'easeInOutQuad'});
			tempSidebar('<a id="close" href="#close" class="button" style="width:38px; height:40px;"><span style="background-image:url(/images/buttons/close.gif);"></span></a>');
			$('#close').click(function(){
				$('#toggle').click();
				return false;
			});
			hidden = true;
			background.setHidden(false);
		},
		function(){
			$(this).find('span').stop().animate(
				{backgroundPosition:"(100% 100%)"}, 
				{duration:400});
			$('#center').animate(
				{left:'0px'}, 
				{duration:400,
			     easing:'easeInOutQuad'});
			removeTemp();
			hidden = false;
			background.setHidden(true);
		});
	$('#toggle')
		.show()
		.bind('click',function(){
			return false;
		})
		.bind('focus',function(){
			this.blur();
		});
	
	loadGallery("/background_photos.aspx",true);
	
	//Navigation
	fullWidth = $('#nav .bar').width();
	
	$('#nav')
	.bind('mouseenter',function(){
		$(this).find('.bar').stop()
		.animate({width:fullWidth},200);
	})
	.bind('mouseleave',function(){
		$(this).find('.bar').stop()
		.animate({width:0},200);
	});
	
	$('#nav a')
	.bind('mouseenter',function(){
		removeImage(this);
	})
	.bind('mouseleave',function(){
		returnImage(this);
	});
	
	$('#nav .bar').css({width:0, display:'block', overflow:'hidden'});
	$('#nav a img').css({display:'none'});
}

var fullWidth;

function removeImage(element)
{
	$(element).find('img')
		.attr('rel',$(element).attr('href'))
		.appendTo('#nav .bar')
		.css({display:'block'})
		.wrap('<span />');
	
	var width = $('#nav .bar img:last').width();
	var height = $('#nav .bar img:last').height();
	var offsetX = fullWidth * .5 - width * .5;
	
	$('#nav .bar span:last')
		.css({
			left:offsetX+"px",
			marginTop:-height * .5 + 'px',
			width:width,
			height:height,
			display:'none'})
		.slideDown(200);
}

function returnImage(element)
{
	var span = $('#nav .bar img[rel='+$(element).attr('href')+']').parent();
	var offset = span.parent().height() * .5 - span.find('img').height() *.5;
	span.stop()
		.css({
			marginTop: '0',
			bottom: offset+'px',
			top:'auto'})
		.slideUp(200,function(){
			$('#nav .bar img[rel='+$(element).attr('href')+']')
				.css({display:'none'})
				.appendTo($(element));
				
			$(this).remove();
		});
}

function tempSidebar(newElement)
{
	var temp = $('#right .temp');
	if(temp.length == 0){
		$('#right .content').prepend('<div class="temp"></div>');
		temp = $('#right .temp');
	}
	temp.append(newElement);
}

function removeTemp()
{
	$('#right .temp').remove();
}

var background;

function scroll_init(){
	//Set up scoll panels
	$('.scroll-pane').jScrollPane({
		reinitialiseOnImageLoad:true,
		animateTo:true
	});
}

function loadGallery(hash,baseGallery){
	$.get(hash, function(data){
		var images = new Array();
		
		var imageLoad = function(){
			if(baseGallery){
	
				//Background Flash
				$(data).parents(':first').find("#center .content img").each(function(){
					images.push($(this).attr('src'));
				});
				
				var params = {menu:"false",	wmode:"transparent",flashvars:"default="+images.join(",")};
				var attributes = {
					id: "background",
					name: "background"
				};
				swfobject.embedSWF("/scripts/Background.swf", "background", "100%", "100%", "9.0.0", "/scripts/expressInstall.swf",null,params,attributes);
				background = document.getElementById('background');
			}else{
				$(data).parents(':first').find("#center .content img").each(function(){
					images.push({image:$(this).attr('src'),title:$(this).attr('alt')});
				});
				$('#toggle').click();
				background.setGallery(images);
			}
		}
		
		try{
			imageLoad();
		}catch(e){
			$('#background').load(function(){
				imageLoad();
			});
		}
	});
}

function content_init(){
	
	scroll_init();
	
	//sifr
	$.sifr({path:'/fonts'});
	//$('.content h2, .content h3, .content h4, .content h5').sifr({font:'Arial Narrow'});
	
	//Set up facebox popups
	$('.facebox, a[rel*=facebox]').facebox({opacity:.5});
	
	//Set up launch buttons
	$('.launch').click(function(){
		var hash = $(this).attr('href');
		if(hash != null){
			loadGallery(hash,false);
		}
		return false;
	});
	
	//Parse history links
	var host = new RegExp('^.*' + window.location.hostname);
	var begin = new RegExp('^/');
	
    $("a[rel='history']").each(function(){
		$(this).attr('rel','history_active');
		$(this).attr('href',$(this).attr('href').replace(host,'').replace(begin,'#/'));
		$(this).click(function(){
			$.history.load(this.href.replace(/^.*#/, ''));
			$(this).blur();
			return false;
		});
	});
}

// --------------------------- Begin Ajax -- ||

//Check to make sure we're on the home page
function checkIsHome(){
	var regex = new RegExp('^.*' + window.location.hostname + '/');
	var baseRef = 'http://' + window.location.hostname + '/'
	var basePage = window.location.href.replace(/#.*$/,'');
	var currentPage = window.location.href.replace(regex,'#/');
	if(basePage != baseRef){
		window.location = baseRef+currentPage;
		return true;
	}
	return false;
}

function setupAjax(){
    $.history.init(callback);
	$('body').append('<div id="loading" style="display:none;"><span></span></div>');
	$('body').prepend('<div id="ajax_status" />');
	
	//Set up ajax event handling
	$('body').ajaxError(function(event, request, settings){
		$('#ajax_status').append('<div><span class="back"></span><p class="error">Error requesting page <b>' + stripAjax(settings.url) + '</b></p></div>');
		format();
	});
	$('body').ajaxSuccess(function(event, request, settings){
		/*$('#ajax_status').append('<div><span class="back"></span><p>Loaded <b>' + stripAjax(settings.url) + '</b></p></div>');
		format();*/
	});
	$('body').ajaxStart(function(){
		//Show loading screen
		$('#loading').stop().css({
			opacity:.5
		}).fadeIn('fast');
	});
	$('body').ajaxStop(function(){
		$('#loading').stop().fadeOut('fast');
	});
}

function stripAjax(url){
	var baseRegex = new RegExp('^http://' + window.location.hostname);
	var returnUrl = url.replace(/^\/ajax\//,'').replace(baseRegex,'');
	return (returnUrl == "") ? "home" : returnUrl;
}

function format(){
	var last = $('#ajax_status div:last');
	
	last.find('.back').css({
		opacity:'.8',
		height:last.height(),
		width:last.width()
	});
	
	last.css('display','none')
	.fadeIn('normal')
	.animate({opacity:"1"}, 4000)
	.slideUp('normal',function(){$(this).remove();});
}

//Loads page content based on hash variable
var homePage = true;
function callback(hash)
{
	if(hash == '') hash = '/';
	if(hash == '/' && homePage == true) return;
	
	if(hash == '/'){
		//home page is loading
		homePage = true;
		$("#logo").attr("class","graphical");
		
	}else if(homePage != false){
		//transitioning out of home page
		homePage = false;
		$("#logo").attr("class","button");
		
	}
	
	fullLoad(hash);
	sortNav(hash);
	
	if(hidden) $('#toggle').click();
}

function fullLoad(hash)
{
	$('#center .content').empty();
	$('#right .content').empty();
	
	$.get(hash, function(data){
		var regex = /[^\>]*?(?=\<\/title\>)/;
		var results = regex.exec(data);
		changeTitle(results[0]);
		
		$('#center .content').empty().append($(data).parents(':first').find("#center .content").children()).show();
		$('#right .content').empty().append($(data).parents(':first').find("#right .content").children()).show();
		
		content_init();
	});
}

//Displays the correct Navigation
function sortNav(hash)
{
	//Deactivate last menu items
	$('.at').each(function(){
		$(this).removeClass('at');
		
		if($(this).hasClass('button_at')){
			$(this).removeClass('button_at');
			$(this).addClass('button');
		}
	});
	
	if(hash == "/") return;
	
	//Activate the correct menu items
	$('a[href=#'+hash+']').each(function(){
		$(this).addClass('at');
		
		if($(this).hasClass('button')){
			$(this).removeClass('button');
			$(this).addClass('button_at');
		}
		
		$(this).parents('li').each(function(){
			$(this).addClass('at');
			$(this).children('.button').each(function(){
				$(this).removeClass('button');
				$(this).addClass('button_at').addClass('at');
			});
		});
	});
	
	//If the secondary nav has no children, display all secondary nav
	if($('#nav li.at li.at>ul').length == 0){
		$('#nav>li.at>ul>li').css({display:'block'});
	}else{
		$('#nav>li.at>ul>li').attr('style','');
	}
}

function changeTitle(title)
{
	document.title = title;
}

//-- End Ajax

//--------------------------- Begin Form Functions --||

function compileForm(form){	
	//Only include each field if filled
	var message = "";
	
	$(form).find(":input").each(function(){
		if($(this).val() == "") return;
		
		//Eliminate null options
		var type = $(this).attr("type");
		if(type == "submit" || type == "reset" || type == "button") return;
		if(type == "radio" && !$(this).is(":checked")) return;
		if(type == "checkbox" && !$(this).is(":checked")) return;
		if($(this).is("select") && $(this).find("option:selected").hasClass("legend")) return;
		
		//Find the label
		var name = $(this).attr("name");
		var id = (type == "radio") ? $(form).find(":input[name='"+name+"']:first").attr("id") : $(this).attr("id");
		var label = $(form).find("label[for='"+id+"']:first");
		
		message += label.text() +" : " + $(this).val() +"\n";
	});
	
	return message;
}

function sendForm(form,sender,recipient,subject,message){
	//Check that all elements are present
	if($(form).find(".sending").length == 0)
		$(form).append('<div class="sending"></div>');
	if($(form).find(".confirmation").length == 0)
		$(form).append('<div class="confirmation"><p>Thank you.  Your information has been successfully submitted.</p><p>Please feel free to continue browsing our site.</p></div>');
	
	
	//Display Sending Animation
	$(form).find(".sending").css({width:$(form).width(), height:$(form).height()}).fadeIn();
	
	//Set up error handling
	$(form).ajaxError(function(event, request, settings){
		$(this).append("<strong>Error occured while requesting page " + settings.url + "</strong>");
	});
	
	//Send ajax request
	$.post("/forms/email_form.aspx", {
		sender:sender, 
		recipient:recipient, 
		subject:subject, 
		message:message
	}, function(data, textStatus){
		//Show confirmation on success
		$(form).find(".sending").hide();
		$(form).find("fieldset").hide();
		$(form).find(".confirmation").show();
	});
}

//-- End Form Functions


//Print Functionality
function printArticle() {
	if (window.print) {
		window.print();
	}else if (agt.indexOf("mac") != -1) {
		alert("Press 'Cmd+p' on your keyboard to print article.");
	}else {
		alert("Press 'Ctrl+p' on your keyboard to print article.")
	}
}