/*
*	FUNCTIONS
*/


//	PREPS PAGE CONTENT
//	$animaBg = true/false if the bg is animated | $navObject = clicked nav object | $url = url of content
function prepPageContent($animaBg,$navObject,$url){
	$navObject = ($navObject)? $navObject : false;
	$url = ($url)? $url : convertHash();
	
	if($navObject){
		if($url != convertHash()){
			$("#rootContentWrapper").animate({right: 372}, 450, function() {
				loadPageContent($animaBg,$navObject,$url);
			});
		}
		else{
			loadPageContent(false,$navObject,$url);
		}
		
	}else{
		loadPageContent($animaBg,$navObject,$url);
	}		
}




//	LOADS PAGE CONTENT
//	$animaBg = true/false if the bg is animated | $navObject = clicked nav object | $url = url of content
function loadPageContent($animaBg,$navObject,$url){
	//If content has not already been loaded
	if(!$("#rootContentWrapper *").hasClass(createUrlClass($url))){		
		$("#tempContent").load($url,{ json: "yes"}, function() {
			
			
			//Redirects to hash version of url
			if($navObject && $url)window.location = convertUrltoHash($url);	
			
			//Loaded content
			var loadedContent = "<li class=\""+createUrlClass($url)+"\">"+$(this).html()+"</li>";
			
			//Hides all content
			$("#rootContentWrapper li").hide();
			
			// Empty Temp div
			$(this).empty();//Emptys temp div
			if(!$navObject)$("#rootContentWrapper").empty();//if refresh then drop all content
			
			//Adds Loaded content to UL list
			$("#rootContentWrapper").append(loadedContent);
		
								
			//Once loaded re-apply the usual plugins
			functionBundle($animaBg,$navObject,$url);
			
			//Load background
			loadBackground($url, $animaBg);
			
		});	
	}
	else{
			//Redirects to hash version of url
			if($navObject && $url)window.location = convertUrltoHash($url);	
			
			//Hides all content
			$("#rootContentWrapper li").hide();

			$("#rootContentWrapper ."+createUrlClass($url)).show();
					
			//Once loaded re-apply the usual plugins
			functionBundle($animaBg,$navObject,$url);
			
			//Load background
			loadBackground($url, $animaBg);	
	}
	
}



		
//	LOADS BACKGROUND IMAGE
//	$url = image name |	$animate = true/false if you want the gb to animate out and in
function loadBackground($url, $animate){
	
	$.post("/background-image-json", { url: $url},
		function(data){
		var imageFolder = "/images/main-images/";
		var imagePath =  imageFolder + data['image'];
		var bgImage = new Image();
		
		if($animate){
			$("#rootContentWrapper").animate({right: 0}, 200, function() {															
				$('img.mainImg').fadeOut(500, function() {

					//Image Loader
  					$(bgImage).load(function () {
						$('img.mainImg').attr('src', imagePath).fadeIn(500);
					}).error(function () {}).attr('src', imagePath);
					
				});	
			});	
		}else{
			//Image Loader
			$(bgImage).load(function () {
				$('img.mainImg').attr('src', imagePath).show();
			}).error(function () {}).attr('src', imagePath);
		}
	}, "json");
}

//CONTACT US FORM
var options = { success:	showResponse, data: { json: 'true'}};
function showResponse(responseText, statusText, xhr, $form)  {  
	if(statusText == "success"){
		alert(responseText);
	}
	else{
		alert("an error occured, please try again!");	
	}
}

function formSubmit(){
	$('#contact-form').ajaxForm(options);
}
	




	
	
	
	
	
	

//	ALL THE FUNCTIONS THAT ARE RE-RUN ON EACH PAGE LOAD
function functionBundle($animaBg,$navObject,$url){			  
	$(document).pngFix();
	Cufon.replace('.avantGarde', { fontFamily: 'avant-garde-gothic'});
	colorboxPlugin();
	highlightNav($navObject);
	pageSpecific();
	
	/*
	if(navigator.appName != "Microsoft Internet Explorer")
		$('.styleScroller').jScrollPane({verticalGutter: 10});
		*/
	formSubmit();
}



//	PAGE SPECIFIC CODE
function pageSpecific(){
	
	/*
	*	STYLE GALLERY
	*/
	
	//	SELECT A GALLERY
	//$('#selectGallery ul li').first().find("a").addClass("current");
	$('.styleScroller ul').first().show();
	$('#selectGallery ul li a').click(function(){
		$('#selectGallery ul li a').removeClass("current");				   
		$(this).addClass("current");
		$iIndex = $("#selectGallery ul li a").index(this);
		$('.styleScroller ul').hide();
		$('.styleScroller ul').eq($iIndex).show();
											   
	});
	
		//STYLE GALLERY IMAGE ROLLOVERS
	$('.styleGallery').live("mouseover",function(){
		$sFolder = explode("/",$(this).attr("href"));
		$sFolder = $sFolder[3];
		var hoverpath = "/images/style-gallery/"+$sFolder+"/thumbs/style-"+ $(this).attr("id")+"-hover.jpg";

		$(this).find("img").attr("src", hoverpath);			
	}).live("mouseout", function(){
		var normalPath = "/images/style-gallery/"+$sFolder+"/thumbs/style-"+ $(this).attr("id")+".jpg";		
		$(this).find("img").attr("src", normalPath);
	});
	
	
}



		
//	HIGHLIGHTS NAVIGATION ITEMS WHEN CLICKED OR LOADED
function highlightNav($object){
	var CurrentButton = $('#rootNavigation li a[href|="'+convertHash()+'"]');		
	$('#rootNavigation li a').removeClass('current');
	Cufon.replace('#rootNavigation li a', {color: '#3b2a0d'});
	Cufon.replace(CurrentButton, {color: '#12acba'});
	$object = ($object)? $object : CurrentButton;
	$($object).addClass('current');
}
		
		
		
		
//	SCALES BACKGROUND IMAGE
function scaleImage(){

	$('img.mainImg').maxImage({
	isBackground: false,
	maxFollows: 'height',
	verticalAlign: 'center',
	horizontalAlign: 'right'
})
}








// COLORBOX PLUGIN (http://colorpowered.com/colorbox/) */
function colorboxPlugin(){
	$(".video").colorbox({iframe:true, innerWidth:425, innerHeight:344});
	
	$(".colorbox, .styleGallery[rel='gallery']").colorbox({
		title: true,
		onComplete:function(){ 
		Cufon.replace('.avantGarde', { fontFamily: 'avant-garde-gothic'});
}})};
	
	
	
	
//JS POPUP, THIS MAKES EXTERNAL LINKS POPUP IN A SCALED WINDOW(replacement for target="_blank")
function popupJs(){
	$( ".popup" ).live( "click", function( event ) {
		event.preventDefault();
		var sTarget = $( this ).attr( "href" );
		var iWidth = 800;
		var iHeight = 600;
		var iScrollbars = 2;
		var iLeft = (screen.width)?(screen.width-iWidth)/2:100;
		var iTop = (screen.height)?(screen.height-iHeight)/2:100;
		var sSettings='width='+iWidth+',height='+iHeight+',top='+iTop+',left='+iLeft+',scrollbars='+iScrollbars+',location=yes,directories=no,status=yes,menubar=yes,toolbar=yes,resizable=yes';
		win=window.open( sTarget, "", sSettings );
})};




//CONVERTS HASH TO A URL EG: /#welcome-home to /welcome-home
function convertHash($hash){
	if(!$hash) $hash = location.hash;
	var refreshHash = new String($hash);
	var refreshHash = refreshHash.replace(refreshHash.charAt(0), "/");
	return refreshHash.replace(refreshHash.charAt(0), "");
}

//CONVERTS HASH TO A URL EG: /#welcome-home to /welcome-home
function convertUrltoHash($url){	
	if(!$url) $url = location.pathname;
	var refreshHash = new String($url);
	return refreshHash.replace(refreshHash.charAt(0), "#/");
}

//CREATES CLASS NAME FROM URL
function createUrlClass($url){	
	$url = (!$url)? location.pathname : $url;
	$url = ($url == "/")? "/index" : $url;
	var refreshHash = new String($url);
	return refreshHash.replace(refreshHash.charAt(0), "");
}




function explode (delimiter, string, limit) {
    // Splits a string on string separator and return array of components. If limit is positive only limit number of components is returned. If limit is negative all components except the last abs(limit) are returned.  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/explode    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']
    var emptyArray = {        0: ''
    };
 
    // third argument is not required
    if (arguments.length < 2 || typeof arguments[0] == 'undefined' || typeof arguments[1] == 'undefined') {        return null;
    }
 
    if (delimiter === '' || delimiter === false || delimiter === null) {
        return false;    }
 
    if (typeof delimiter == 'function' || typeof delimiter == 'object' || typeof string == 'function' || typeof string == 'object') {
        return emptyArray;
    } 
    if (delimiter === true) {
        delimiter = '1';
    }
     if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }}
	
	
