(function($){

/* !--- Details --- */
/* --------------------------------------------------------------------------------------------------------------

Global Javascript
Author: Lee Powell

 ---------------------------------------------------------------------------------------------------------------- */


/* !--- Pre-Document Load ---                                                                                     */
/* -------------------------------------------------------------------------------------------------------------- */

var flashRequired = 8;

var flashVersion = swfobject.getFlashPlayerVersion().major;

var flashActive = flashVersion >= flashRequired;

var iPhone = (( typeof window.orientation !== 'undefined' ) && ( navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) ));

var ie6 = $.browser.msie && $.browser.version == 6;


// Add classes to html element for styling hooks
var htmlEl = $('html');

htmlEl.addClass('js-active');

if( flashActive ){
	htmlEl.addClass('flash-active');
}


/* !--- Document Load ---                                                                                         */
/* -------------------------------------------------------------------------------------------------------------- */
jQuery(function(){
	
	// Boot strap IE6 fixes for CSS styling
	if( ie6 && (typeof ie6BootStrap == 'function') ){
		ie6BootStrap();
	}
	
	// Emulate target="_blank" by using rel="external" attribute for anchors
	$('a[rel="external"]').bind( 'click', newWindow );
	
	// Page initialisation
	var pageId = $('body').attr('id');
	
	switch( pageId ){
		case 'home':
			homePageInit();
		break;
		
		case 'project':
			projectPageInit();
		break;
		
		default:
	}
	
	// Global content header
	if( pageId !== 'home' ){
		headerInit();
	}
	
	// Set up newsletter widget
	var nlw = $('#newsletter-widget');
	
	if( nlw.length ){
		newsletterInit( nlw );
	}
	
});

/* !--- Page Specific ---                                                                                         */
/* -------------------------------------------------------------------------------------------------------------- */

function homePageInit(){
	
	if( flashActive ){
		// add container for swfobject
		$('#header').append('<div id="projects-featured"></div>');
		
		// swfobject replacement
		var flashVars = {
			mtv: '/portfolios/design/mtv.php',
			barbie: '/portfolios/fashion/barbie-rainbow.php',
			chatter: '/portfolios/design/chatterbooks.php',
			harry: '/portfolios/kids/harry.php',
			notable: '/portfolios/design/novelists.php'
		};
		
		var flashParams = {
			wmode: 'transparent'	
		};
		
		swfobject.embedSWF('/swf/header-home.swf', 'projects-featured', '960', '415', '8.0.0', null, flashVars, flashParams);
	}
	
}

function projectPageInit(){

	var npTimer;
	var npEl = $('#nav-projects');
	var npItemEl = $('#nav-projects-items');
	var npProjects = $('.project', npItemEl);
	
	// if there are more than 6 projects, and user is NOT iPone set up the navigation
	if( npProjects.length > 6 && !iPhone ){
				
		npEl.addClass('enabled');
		
		// create extra elements needed
		npItemEl.wrapInner('<div id="nav-projects-wrapper"><div id="nav-projects-inner-wrapper"></div></div>');
		npItemEl.prepend('<span id="nav-projects-prev" class="nav imr disabled">Previous</span>');
		npItemEl.append('<span href="#" id="nav-projects-next" class="nav imr">Next</span>');
		
		// cache required elements
		var npWrap = $('#nav-projects-wrapper');
		var npInnerWrap = $('#nav-projects-inner-wrapper');
		
		var npPrev = $('#nav-projects-prev');
		var npNext = $('#nav-projects-next');
		
		// calculate the height of the viewport based on the position of the 7th project
		var npProject7 = $(npProjects[6]);
		npWrap.height( Math.round(npProject7.position().top) + 30 );
		
		// calculate how far up to scroll the nav
		var npTarget = $(npProjects[npProjects.length - 5]);
		var npTargetTop = Math.round( (npTarget.position().top) * -1 );
		
		npInnerWrap.css('top', '0');
		
		// prevent default actions of next and prev buttons for iPhone
		$.each( [npPrev, npNext], function(i, val){
			val.bind('click mousedown', function(e){
				e.preventDefault();
			});
			val.bind('mouseup', function(e){
				clearInterval(npTimer);
			});
		});
		
		var npPrevDisabled = true;
		var npNextDisabled = false;
				
		npPrev.bind('mousedown', function(){				
			npTimer = setInterval(function(){
				var top = parseFloat(npInnerWrap.css('top'));
				
				if( top < 0 ){
					if( npNextDisabled ){
						npNextDisabled = false;
						npNext.removeClass('disabled');
					}
				
					npInnerWrap.css('top', top + 10);
					
					// check to see if animation has gone past target
					top = parseFloat(npInnerWrap.css('top'));
					
					if( top >= 0 ){
						npInnerWrap.css('top', 0);
						
						npPrevDisabled = true;
						
						npPrev.addClass('disabled');
					}					
				}
			}, 40);
		});
		
		npNext.bind('mousedown', function(){	
			npTimer = setInterval(function(){
				var top = parseFloat(npInnerWrap.css('top'));
				
				if( top > npTargetTop ){
					if( npPrevDisabled ){
						npPrevDisabled = false;
						npPrev.removeClass('disabled');
					}
					
					npInnerWrap.css('top', top - 10);
					
					// check to see if animation has gone past target
					top = parseFloat(npInnerWrap.css('top'));
					
					if( top <= npTargetTop ){
						npInnerWrap.css('top', npTargetTop);
						
						npNextDisabled = true;
						
						npNext.addClass('disabled');
					}
				}
			}, 40);
		});
	}
	
}

function headerInit(){
	// add container for swfobject
	$('#header').append('<div id="header-ani"></div>');
	
	var flashParams = {
		wmode: 'transparent'	
	};
	
	swfobject.embedSWF('/swf/header.swf', 'header-ani', '960', '200', '8.0.0', null, null, flashParams);
	
}


/* !--- Misc Functions ---                                                                                        */
/* -------------------------------------------------------------------------------------------------------------- */
function newWindow(e){
	var url = $(this).attr('href');

	window.open( url );
	
	e.preventDefault();
}

function  printProps(obj, objName) {
	var output = "" ;
	for (var prop in obj) {
		output += objName + "." + prop + " = " + obj[prop] + "\n" ;
	}
	return output ;
}

function preloadImages(images){
	$.each(images, function(i, image){
		var img = $('<img>').attr('src', image);		
	});
}

function setInputDefault(el){
		
	var titleVal = el.attr('title');			
	
	el
	
	/* Remove the title attribute to stop IE using it as a tooltip */
	.attr('title', '')
	
	/* Use the title of the element we got earlier to set it's default value */
	.val(titleVal)
		
	/* If user is focusing on element with default text, remove it to allow them to enter data on focus */
	.focus(
		function(){
			if( $(this).val() == titleVal ){
				$(this).val('');
			}
		}
	)
	
	/* If user has losst focus on the element without entering content, replace with default text */
	.blur(
		function(){
			if( $(this).val() == '' ){
				$(this).val(titleVal);
			}
		}
	);
}

function newsletterInit(el){

	// cache form object
	var form = $('form', el);
	
	// cache email input object
	var email = $('input', form);
	
	setInputDefault(email);
	
	// loading stuff
	form.before('<span id="newsletter-loading">Sending...</span>');
	
	var loading = $('#newsletter-loading');
	
	loading.hide();
	
	// timer to show loading
	var timer;
	
	form.submit(function(e){
		
		// get value of input
		var val = email.val();
						
		// make ajax request
		$.ajax({
			url: form.attr('action'),
			
			type: 'POST',
			
			data: '&email='+escape(val)+'&ajax=true',
			
			dataType: 'json',
			
			beforeSend: function(){
				// wait a quarter of a second before showing loading message
				timer = setTimeout(function(){
					form.hide();
					loading.show();
				}, 500);
			},
			
			error: function(XMLHttpRequest, textStatus, errorThrown){
				form.replaceWith('<span class="error">An error has occurred. Please try again in a few moments.</span>');
			},
			
			success: function(data, textStatus){
				switch(data.result){
					case '1':
						form.replaceWith('<span class="success">'+data.text+'</span>');
					break;
					
					default:
						var target = $('.error', form);
						
						if( target.length ){
							target.text(data.text);
						}
						else {
							form.prepend('<span class="error">'+data.text+'</span>');
						}								
				}
			},
			
			complete: function(XMLHttpRequest, textStatus){
				clearTimeout(timer);
				
				if( loading.is(':visible') ){
					loading.hide();
				
					form.show();
				}
			}
		});
		
		e.preventDefault();
	});
}


/* ------------------------------------------------------------------------------------------------------------ */
})(jQuery);