var j = jQuery.noConflict();

//gets browser information
var agent=navigator.userAgent;

//string pattern for mobile device detection using html5
var devicesRegExp = /ipad|iphone|android|mobile/i;

//holds browser identity
var browsersniffer = agent.match(devicesRegExp);
browsersniffer = Boolean(browsersniffer);

var popupActive = false;
var warning = false;
 
var j = jQuery.noConflict();


var homePageInterval;
var currentSlide=1;
var visibleSlide = 1;
var previousSlide = 1;
var prevSlideEnd;


var caseNavBackPos = "-79px 0px";


//flip book variables
var flipbook_flashvars = {};
flipbook_flashvars.XMLFileName = null;
flipbook_flashvars.DataFolder = "/";
flipbook_flashvars.StartPage = "1";
flipbook_flashvars.StartAutoFlip = "false";

var flipbook_params = {};
flipbook_params.scale = "noscale";
flipbook_params.salign = "TL";
flipbook_params.wmode = "transparent";
flipbook_params.allowscriptaccess = "always";
flipbook_params.allowfullscreen = "true";
flipbook_params.menu = "true";
flipbook_params.bgcolor = "#FFFFFF";

var flipbook_attributes = {};



// home page intro menu control and property change
function homePageMenu(selected,stopAni,previous){

	j(".showCoverHolder").hide();
	j("#showNext").hide();
	j("#showPrev").hide();

	
	currentSlide = selected;
	
		
	var topPixel = 0;
	
	//stops homepage animation
	if(stopAni){
		clearInterval(homePageInterval);
	}
	
	if(j("#showcase" + selected).css("visibility")=='hidden'){
		j("#showcase" + selected).css("visibility","visible");
	}
	

	//resets background for all buttons			
	for(var i=1;i<=totalShowCaseItems;i++){
		j("#" + i).css("background-position","0px 0px");
	}
	
	j("#" + selected).css("background-position",caseNavBackPos);
	
	var prevZ = Number(j("#showcase" + visibleSlide).css("z-index"));
	var startPixel = 0 - Number(j("#showcaseBack").width());
	var endPixel = 0;
	

	j("#showcase" + selected).css({"z-index":prevZ+1,"left": startPixel + "px" });
	j("#showcasenav").css("z-index",prevZ+2);
	
	visibleSlide=selected;
	
	
	if(!browsersniffer){
		
		if(!previous){
			
			j("#showcase" + selected).css("left",prevSlideEnd + "px");
			
			j("#showcase" + selected).animate({
				left: 0
				},500,"linear");	
				
			
			j("#showcase" + previousSlide).animate({
				left: (-1 - j("#showcaseBack").width())
				},500,"linear",function(){
					
				j("#showcase" + previousSlide).css("left","0px");
				
			});
		}
		else{

			j("#showcase" + selected).animate({
				left: endPixel
				},500,"linear");	
				
			j("#showcase" + previousSlide).animate({
				left: prevSlideEnd
				},500,"linear",function(){
					
				j("#showcase" + previousSlide).css("left","0px");
				
			});
		}
	}
	else{
		j("#showcase" + selected).css({"left":"0px"});
	}

	return false;
}



function homeNextPrev(previous){
	
	previousSlide = currentSlide;
	
	if(previous){
		currentSlide--;
	}
	else{
		currentSlide++;
	}
	
	if(currentSlide<=0){
		currentSlide=totalShowCaseItems;
	}
	
	if(currentSlide>totalShowCaseItems){
		currentSlide=1;
	}
	
	if(previous){
		homePageMenu(currentSlide,true,true);
	}
	else{
		homePageMenu(currentSlide,true,false);
	}
	
	return false;
}


function cycleHomePageMenu(){
	
	previousSlide = currentSlide;
	currentSlide++;
	
	if(currentSlide>totalShowCaseItems){
		currentSlide=1;
	}
	
	homePageMenu(currentSlide,false);
}




function showHighlights(object){
	
	if(String(object).match(/mm_/)){
		j("#" + object).addClass("selectedMain");		
	}
	else if(String(object).match(/sub_/)){
		j("#" + object).addClass("selectedSub");		
	}
	else{
		j("#" + object).addClass("selectedButn");	
	}
	
}


var imageLoaded = 0;
var loadChecker;
var counter = 0;

function showHidePreloadedImage(visibility){
	for(i=0;i<imagesToPreload.length;i++){
		
		j(imagesToPreload[i]).css('visibility',visibility);
	}
}

function loadMessageText(textToShow){
	j("#homeLoader").text(textToShow);
}

function createLoadMessage(){
		j("#homeLoader").show();
		
		var tempHeight = (j("#showcaseBack").height()/2 - j("#homeLoader").height()/2)
		
		j("#homeLoader").css("top",	tempHeight + "px");
}

function startWebsite(){
	
	counter++;
	
	if(imageLoaded==0){
		createLoadMessage();
	}
	
	if(j(imagesToPreload[imageLoaded]).attr('complete')){
		imageLoaded++;
	}

	if(imageLoaded>=imagesToPreload.length){
		clearInterval(loadChecker);
		imageLoaded = 0;
		
		j("#homeLoader").hide();
		
		
		visibleSlide = totalShowCaseItems;
		
		drawShowcaseNav();
	
		homePageInterval = setInterval(cycleHomePageMenu,7000);

		
	}
	
}



function drawShowcaseNav(){
	
		//gets margin of css class for casebutn to add to width below.
		var tempMargin;
	
		//adds one button for each case study image
		for(var i=1;i<=totalShowCaseItems;i++){
			
			j('#showcasenav').append("<a href='' class='showcasebutn' id=" + i + "></a>");
			
			 tempMargin = Number(String(j(".showcasebutn").css("margin-left")).replace(/px/,""));
			
			j("#showcasenav").css("width",(j(".showcasebutn").width() + tempMargin) * totalShowCaseItems + "px");
		
			j("#" + i).bind("click",function(){ 
				
				previousSlide = currentSlide;
				

				if(Number(j(this).attr("id")) != currentSlide){
				homePageMenu(Number(j(this).attr("id")),true); 
				}
				
				return false; 
				});
			
			//sets z-indexes of shawcase area items.
			j('#showcase' + i).css("z-index",i);
		}
		
		j("#showcasenav").css("left",(j('#showcaseBack').width() - j("#showcasenav").width())-10 + "px");
		j("#showcasenav").css("top",(j('#showcaseBack').height() - j("#showcasenav").height()) + "px");
		
		prevSlideEnd = j("#showcaseBack").width()+1;
		previousSlide = totalShowCaseItems;
		
		
		//set first button to selected
		j("#1").css("background-position",caseNavBackPos);		
		//homePageMenu(1);

		
}


//holds current case study id
var currentCase =0;

//loads case study image
function loadCaseStudyImage(){
	
	j('#caseimagearea').addClass("workloader");

	//repositions all casebutn background to ornage default
	if(workImages.length>1){
	j('.casebutn').css("background-position","0px 0px");
	}
	
	//if currentCase greater than number of images
	//resets to zero
	if(currentCase>workImages.length-1){
		currentCase = 0;
	}
 
	 //adds case study label and image to hyperlink holder
	
	//looks to see if hide is in the graphic title
	//show case study graphic title if no "hide" attribute 
	var currentCaseTitle;
	var hideTitle = Boolean(workImages[currentCase][1].match(/hide/i));
	
	if(!hideTitle){
		currentCaseTitle = workImages[currentCase][1];
	}
	else{
		currentCaseTitle = "";
	}
	
	
	if(String(workImages[currentCase][2]).match(/video/)){
		
		var tempSize = String(workImages[currentCase][3]).match(/([0-9]{1,3}):([0-9]{1,3})/);
				
		j("#casestudyimage").html("<div id='caselabel'>" + currentCaseTitle +  "</div><div id='videoarea'></div><div id='flashBack'></div>");
		
	
		if(workImages.length>1){
			j("#" + currentCase).css("background-position",caseNavBackPos);
		//j("#casestudyimage").css("height", j(this).height() + "px");
		}
		
		var movieSizes = Array();
		
		tempSize[1] = Number(tempSize[1]);
		tempSize[2] = Number(tempSize[2]);

		switch(tempSize[1]){
			case 16:
				movieSizes[0] = 550;
				movieSizes[1] = 309;
			break;
			
			
			case 4:
				movieSizes[0] = 550;
				movieSizes[1] = 413;
			break;	
			
			default:
				movieSizes[0] = tempSize[1];
				movieSizes[1] = tempSize[2];
			break;
		}

		//find fallback image for video
		for(var i=0;i<fallbackImages.length;i++){
			if(String(workImages[currentCase][3]).match(fallbackImages[i][1])){
			var html5FallBack = fallbackImages[i][0];
			}
			
		}
		
		
		//add fallback image to video area tag
		if(html5FallBack){
			j("#videoarea").css("background-image","url(" + html5FallBack +  ")");
		}
	//	j("#videoarea").css("background-color","#ff7813");

		createVideoWindow(String(workImages[currentCase][0]),"videoarea",movieSizes[0],movieSizes[1],html5FallBack);
		
		j('#caseimagearea').removeClass("workloader");

		j("#casestudyimage").css("left","0px");		
		
		j("#videoarea").css({"top":Math.round(j('#caseimagearea').height()/2 - movieSizes[1]/2) + "px","left":Math.round(j('#caseimagearea').width()/2 - movieSizes[0]/2) + "px"});
		
		j("#casestudyimage").fadeIn(200);
		j("#caselabel").fadeIn(200);
		
	}
	
	else if(String(workImages[currentCase][2]).match(/flash/)){
		
		var flashSize = String(workImages[currentCase][3]).match(/([0-9]{1,4})x([0-9]{1,4})/);
		j("#casestudyimage").html("<div id='caselabel'>" + currentCaseTitle +  "</div><div id='flasharea'></div><div id='flashBack'></div>");
		
		j("#flasharea").css({"width":flashSize[1] + "px" ,"height":flashSize[2] + "px","left":Math.round(j('#caseimagearea').width()/2 - flashSize[1]/2) + "px", "top":Math.round(j("#caseimagearea").height()/2 - flashSize[2]/2) + "px"});
		
	
		
		//retreive fallback image for fsw
		for(var i=0;i<fallbackImages.length;i++){
			if(Boolean(String(workImages[currentCase][3]).match(fallbackImages[i][1]))){
					//j("#flasharea").html("<img src='" + fallbackImages[i][0]  +  "' width='"  +  flashSize[1] + "'  height='"  +  flashSize[2] + "' alt='Fallback' />");
					j("#flasharea").css("background-image","url(" + fallbackImages[i][0] + ")");
					
			}
		}
	
		//creates object to pass to flash embed functionality
		var flashvars = {};
		var params = {};
		params.bgcolor = "#000000";
		var attributes = {};

		swfobject.embedSWF(String(workImages[currentCase][0]), "flasharea", flashSize[1], flashSize[2], "10.0.0", false, flashvars, params, attributes);

		
		j("#casestudyimage").fadeIn(200);
		j("#caselabel").fadeIn(200);
		
		if(workImages.length>1){
			j("#" + currentCase).css("background-position",caseNavBackPos);
		//j("#casestudyimage").css("height", j(this).height() + "px");
		}
		
		j('#caseimagearea').removeClass("workloader");
		
	}
	
	
	else if(String(workImages[currentCase][3]).match(/flipbook/) && !browsersniffer){
		
		var flashSize = String(workImages[currentCase][3]).match(/([0-9]{1,4})x([0-9]{1,4})/);
		var flipbookxmlfile = String(workImages[currentCase][3]).match(/flipbook\=([a-z_\/\.]*)/);
		j("#casestudyimage").html("<div id='caselabel'>" + currentCaseTitle +  "</div><div id='flipbook'></div><div id='flashBack'></div>");
		
	
		flipbook_flashvars.XMLFileName = flipbookxmlfile[1];
		swfobject.embedSWF("/interface/swf/pageFlip.swf", "flipbook", flashSize[1], flashSize[2], "10.0.0", false, flipbook_flashvars, flipbook_params, flipbook_attributes);
		
		j("#flipbook").css({"width":flashSize[1] + "px" ,"height":flashSize[2] + "px","left":Math.round(j('#caseimagearea').width()/2 - flashSize[1]/2) + "px", "top":Math.round(j("#caseimagearea").height()/2 - flashSize[2]/2) + "px"});
	
		j("#casestudyimage").fadeIn(200);
		j("#caselabel").fadeIn(200);
		
		if(workImages.length>1){
			j("#" + currentCase).css("background-position",caseNavBackPos);
		//j("#casestudyimage").css("height", j(this).height() + "px");
		}
		
		j('#caseimagearea').removeClass("workloader");
		
	}
	
	else{
		j("#casestudyimage").html("<div id='caselabel'>" + currentCaseTitle +  "</div><img src='" + workImages[currentCase][0]  + "''/>");
	
		//when image is loaded fades in image and label
		//sets casebutn background to green highlight
		j('#casestudyimage img').load(function(){
			j("#casestudyimage").fadeIn(200);
			j("#casestudyimage img").css("display","block");
			j("#caselabel").fadeIn(200);
			j('#caseimagearea').removeClass("workloader");
			j("#casestudyimage").append("<div id='flashBack'></div>");
			
			var imageWidth = Number(j("#casestudyimage img").attr("width"));
			var imageHeight = Number(j("#casestudyimage img").attr("height"));
			
			if(imageWidth<550){
				imageWidth = 550 -imageWidth;	
				var curLeft = Number(String(j("#casestudyimage img").css("left")).replace(/px/,""));
				if(!Boolean(curLeft)){
					curLeft=1;
				}
				j("#casestudyimage img").css({"left":Math.floor(imageWidth/2) + "px"});
			}
			
			
			if(imageHeight<550){
				imageHeight = 550 -imageHeight;
				var curTop = Number(String(j("#casestudyimage img").css("top")).replace(/px/,""));
				if(!Boolean(curTop)){
					curTop=25;
				}
				j("#casestudyimage img").css({"top": curTop + Math.floor(imageHeight/2) + "px"});
			}
			
				
			if(workImages.length>1){
				j("#" + currentCase).css("background-position",caseNavBackPos);
			//j("#casestudyimage").css("height", j(this).height() + "px");
			}
		});
		
	}
	
	if(workImages.length>1 && !browsersniffer){
		j("#casestudyimage").append("<a href='' id='caseNext'></a><a href='' id='casePrev'></a>");
		
		j("#caseNext").bind('click',function(){
			nextAndPrev(true);
			return false;
		});
	
		j("#casePrev").bind('click',function(){
			nextAndPrev(false);
			return false;
		});
		
		
		j("#caseNext, #casePrev").bind('mouseover',function(){
				showNextPrev(true);
		});
			
		j("#casestudyimage").bind('mouseover',function(){
				showNextPrev(true);
		});
		
		j("#casestudyimage").bind('mouseout',function(){
				showNextPrev(false);
		});

	}
	
	return false;
	
}

//creates the casebutn navigation to upper right of image
function createLoadNav(){
	
	//if there are more than one case study image
	//creates navihations
	if(workImages.length>1){
		
		//add nav holder to case study area
		j('#caseimagearea').append("<div id='casestudynav'></div><div href='' id='casestudyimage'></div>");
		j('#caseimagearea').addClass("workloader");
	
		//gets margin of css class for casebutn to add to width below.
		var tempMargin;
		var navLength = 0;
		
		//adds one button for each case study image
		for(var i=0;i<workImages.length;i++){
			
				j('#casestudynav').append("<a href='' class='casebutn' id=" + i + "></a>");
				navLength++;
			
			tempMargin = Number(String(j(".casebutn").css("margin-left")).replace(/px/,""));
				
		}
		
		//calculates width and left placement of case navigation based on number of images
		j("#casestudynav").css("width",(j(".casebutn").width() + tempMargin) * navLength + "px");
		j("#casestudynav").css("left",j('#caseimagearea').width() - j("#casestudynav").width() + "px");
					
		//adds cycling action to case study button
				
		j('.casebutn').bind('click',function(){
			showNextCaseImage(j(this).attr("id"));	
			j(this).css("background-position",caseNavBackPos);
			return false;
		});
		
		//adds rollover to case study button
		j('.casebutn').bind('mouseover',function(){
			j(this).css("background-position",caseNavBackPos);
			return false;
		});
		
		//adds rollout to case study button
		//if case study image is not the currently selected
		j('.casebutn').bind('mouseout',function(){
			if(j(this).attr("id")!=currentCase){
			j(this).css("background-position","0px 0px");
			}
			return false;
		});
		
	}
	else{
		j('#caseimagearea').append("<div id='casestudyimage'></div>");
	}
	
	//finally loads  default case study
	loadCaseStudyImage();
	
}

//gets hash value from url location
function getHashFromAddress(){
	
	var hashValue;
	
	if(window.location.hash){
		hashValue=window.location.hash;
	}
	else{
		hashValue=location.hash;
	}
	
	return hashValue;
}

//gets hash value from url location
function hashToAddress(hashValue,removeHash){
	
	if(window.location.hash){
			window.location.hash = ((removeHash)?"":"#" + hashValue);
	}
	else{
		location.hash = ((removeHash)?"":"#" + hashValue);
	}
	
}


function showNextPrev(show){
	
	if(show){
		j("#caseNext").show();
		j("#casePrev").show();
	}
	else{
		j("#caseNext").hide();
		j("#casePrev").hide();
	}
}


 function nextAndPrev(foward){
	
	 if(foward){
		 currentCase++
	 }
	 else{
		 currentCase--;
	 }
	 
	if(currentCase>workImages.length-1){
		currentCase = 0;
	}
	
	if(currentCase<0){
		currentCase = workImages.length-1;
	}
	
	 
	 showNextCaseImage(currentCase);
 }



//actions for click function of case study image and button
function showNextCaseImage(imgID){
	
		//fades out image and label
		j("#caselabel").fadeOut(200);
		j('#casestudyimage').fadeOut(200,function(){
			
			j("#casestudyimage img").css("display","none");
			j('#caseimagearea').show();
			j('#caseimagearea').addClass("workloader");
			
			// on fadeout complete next image
			
			//gets id sent from case study button		
			if(imgID || imgID=='0'){
				currentCase=imgID;
			}
			//or selects next case study image
			else{
				currentCase++;
			}
			
			
			loadCaseStudyImage(currentCase);			
		});
		
		return false;
		
}



//news drop downs
function newsDropDown(){
	
		j("#filselec-month,#filselec-month a").bind('mouseover',function(){
				j("#filtdrop-month").css({"display":"block","left":j(this).position().left + "px","top":j(this).position().top + 15 + "px"});
				dropDownCloser();
				
		});
		
		j("#filselec-year, #filselec-year a").bind('mouseover',function(){
				j("#filtdrop-year").css({"display":"block","left":j(this).position().left + "px","top":j(this).position().top + 15 + "px"});
				dropDownCloser();
				
		});
		
		
		j("#newssubmit").bind('mouseover',function(){
				j(".filterdrop").css({"display":"none"});
				
		});
	
		
		j("#filtdrop-month, #filtdrop-year").bind('mouseleave',function(){
				j(".filterdrop").css({"display":"none"});
		});
	
		
		j("#filtdrop-month a, #filtdrop-year a").bind('click',function(event){
				j(".filterdrop").css({"display":"none"});
				
				hashToAddress("",true)
			
				var parentid = j(event.target).parent().attr("id");
								
				if(parentid.match(/month/)){
					j("#filselec-month").text(j(this).text());
					j("#filselec-month").attr("title",j(this).attr("id"));
					j("#filselec-month").addClass('filterSelect');
				}
				else{
					j("#filselec-year").text(j(this).text());
					j("#filselec-year").addClass('filterSelect');
				}
		});
	
}

function newsTriage(month,year,useHash){

	j("#sectionContent").html("<div class='workloader'></div>");
	
	var hashCheck = getHashFromAddress();
	
	var myData = new Object();
	myData.action ='showNews';
	myData.functionname = 'getNewsContent';
	
	if(hashCheck.match(/fb/) && !month){
		myData.fb = hashCheck;
	}
	else{
		if(month){myData.month = String(month).replace(/f-/,"");}
		if(year){myData.year = year;}
	}

	j.ajax({
 		type: 'POST',
		url: ajaxURL,
	  	data: myData,
  		success:  function(response){
      		j("#sectionContent").html(response);
   		}
	});
	
	return false;
}
	
	
	
//general drop downs
function makeDropDown(){
	
		j("#filselec,#filselec a").bind('mouseover',function(){
			j("#filtdrop").css({"display":"block","left":j(this).position().left + "px","top":j(this).position().top + 15 + "px"});
			dropDownCloser();
			
		});
		
	
		j("#filtdrop").bind('mouseleave',function(){
				j(".filterdrop").css({"display":"none"});
		});
	
		
		j("#filtdrop a").bind('click',function(event){
				j(".filterdrop").css({"display":"none"});
				
				j("#filselec").text(j(this).text());
				j("#filselec").addClass('filterSelect');
		});
	
}

	
	
	
function getStaffBio(staffName){

	j("#workContent").html("<div class='workloader'></div>");
	
	var hashCheck = getHashFromAddress();
	
	var myData = new Object();
	myData.action ='showPeople';
	myData.functionname = 'getStaffBio';
	
	if(staffName){
		myData.staffbio = staffName;
	}
	else if(hashCheck.match(/\w/)){
		myData.staffbio = String(hashCheck).replace(/#/,"");
	}
	
	if(!staffName && !Boolean(getHashFromAddress())){
		j("#sectionSubNav").hide();
	}
	else{
		j("#sectionSubNav").show();
	}

	j.ajax({
 		type: 'POST',
		url: ajaxURL,
	  	data: myData,
  		success:  function(response){
      		j("#workContent").html(response);
   		}
	});
	
	return false;

}


var contentSlide = 0;
//slides is built in php code in category.php

function cycleSlides(){	

	j("#slide"+ contentSlide).fadeOut(250,function(){
		contentSlide++;
		if(contentSlide>slides.length-1){
			contentSlide=0;
		}
		j("#slide"+ contentSlide).fadeIn(250);
	});
	
	
	
}


function createSlideShow(){
	for (var i=0;i<slides.length;i++){
		j("#slideshow").append("<img src='" + slides[i][0] + "' alt='" + slides[i][1] + "' id='slide" + i + "' style='z-index:" + (i+1) + "' />")
	}
	
	j("#slide"+ contentSlide).show();
	var slideshow = setInterval(cycleSlides,5000);
	
}


//drop down closer
function dropDownCloser(){
	var t=setTimeout(closer,10000);
		
	function closer(){
		var obj = j(".filterdrop");
		
		if(obj){
			j(".filterdrop").css({"display":"none"});
		}// end of if
		
		clearTimeout(t);

	}// end closer
}// end dropDownCloser




