/*
	FSI Sir Speedy global.js
	Paul Farning - ISITE Design
	12.17.08
*/

//jQuery dom ready
$(document).ready(function() {

	// dropdowns
	$("#nav div.drop").hover(
		function() {
			var elWidth = $(this).find("a:first").width()+32;
			$(this).find("ul").addClass("over").width(elWidth==32? "94.5%" : $(this).find("a:first").width()+32);
			$(this).find("a:first").css("background","#1f3324");
		},
		function() {
			$(this).find("ul").removeClass("over"); 
			$(this).find("a:first").css("background","transparent");
		}
	);
	
	// homepage controller tabs
	Controllers.init();

	// apply automatic input clearing to the search input
	$(".searchform input#searchterm").inputClear();
		
	// add class to buttons for IE <6
	if(document.all) {
	    $("button").hover(
			function() { $(this).addClass("over"); },
			function() { $(this).removeClass("over"); }
	    );
	}// if document.all

	// build carouselflow
	Carouselflow.init();

	// secondary nav span hovers
	$("#nav-section a").hover(function(){$(this).toggleClass("hover")},function(){$(this).toggleClass("hover")});
	
	// print link
	$("#actions-print a").click(function(){ window.print(); return false; });
});// goodnight, jQuery

var Controllers = {
	
	height: 0,
	adjust: $.browser.msie && $.browser.version < 7.0 ? 0 : 0, // some version of ie need extra padding
	init: function() {
		if($(".tab-inner").length==0) { return; }
		$(".tab-inner").each(function(){
			//alert(Controllers.height+", "+ $(this).height());
			Controllers.height = Controllers.height > $(this).height() ? Controllers.height : $(this).height();
		}).height(Controllers.height+Controllers.adjust<222 ? "222px" : Controllers.height+Controllers.adjust+"px");
		
		$(".tab").hide().filter("#tab-1a,#tab-1b").show();
		$(".controller li:first-child").addClass("current");
		$(".controller li").bind("mouseover",Controllers.controllerTabs);

		$(".ordernow + a").wrapInner("<span></span>");
		var cssObj = {'width' : $(".ordernow + a").width() + 'px'};
		$(".ordernow + a").children("span").css(cssObj);
		Controllers.adjustButtons($("#tab-1a,#tab-1b"));
	},
	
	// show/hide content for homepage tabs
	controllerTabs: function() {
		var $this = $(this);
		var $widget = $(this).parents(".widget");
		var $tabContent = $("#tab"+$(this).attr("id").substr(4));
		
		$widget.find(".tab").hide();
		$tabContent.show();
		$widget.find("li").removeClass("current");
		$this.addClass("current");		
		Controllers.adjustButtons($tabContent);
	},
	
	adjustButtons: function(jqTab) {
		jqTab.find(".ordernow").each(function(){
			var liHeight = $(this).parent().height();
			var spanHeight = $(this).next("a").children("span").height();
			
			var cssObj = {'height' : liHeight + 'px',
				'background-position' : '0px ' + ((liHeight/2)-(spanHeight/2)+5) + 'px'};
			$(this).next("a").css(cssObj);
			
			cssObj = {'margin-top' : '-' + (spanHeight/2) + 'px',
			'width' : $(this).next("a").width() + 'px'};
			$(this).next("a").children("span").css(cssObj);
		});		
	}
	
};

var Carouselflow = {
	
	total: 0,
	imgs: 0,
	current: 0,
	items: [],
	itemcount: 0,
	itemmiddle: 0,
	maxheight: 300,
	positions: [],
	zoomed: false,
	avail_positions : [
		{ left: "0px", top: "127px", width: "56px", height: "75.04px", opacity: "0" },
		{ left: "0px", top: "127px", width: "56px", height: "75.04px", opacity: "0.35" },
		{ left: "8px", top: "113px", width: "71px", height: "95.14px", opacity: "0.45" },
		{ left: "23px", top: "91px", width: "96px", height: "128.64px", opacity: "0.75" },
		{ left: "62px", top: "50px", width: "142px", height: "190.28px", opacity: "0.9" },
		{ left: "213px", top: "0px", width: "200px", height: "268px", opacity: "1" },
		{ left: "422px", top: "50px", width: "142px", height: "190.28px", opacity: "0.9" },
		{ left: "507px", top: "91px", width: "96px", height: "128.64px", opacity: "0.75" },
		{ left: "547px", top: "113px", width: "71px", height: "95.14px", opacity: "0.45" },
		{ left: "572px", top: "127px", width: "56px", height: "75.04px", opacity: "0.35" },
		{ left: "572px", top: "127px", width: "56px", height: "75.04px", opacity: "0" }//,
//		{ left: "572px", top: "127px", width: "56px", height: "75.04px", opacity: "0" }
	],

	flow: function() {	
		$.each(Carouselflow.items,function(i) {	
			var index = i+1<=Carouselflow.itemmiddle ? i+1 : Carouselflow.positions.length - i;
			var $el = $(this[0]).clone(true);
			$el.appendTo("#images").attr("rel",i).css(Carouselflow.positions[i]).css("z-index",index).bind("mousedown",Carouselflow.animate);
			return;
		});
		$("#images,#images img").show().css("visibility","visible");
		$("#carouselflow-list li:eq("+Carouselflow.itemmiddle+")").show().css("visibility","visible");			
	},
	
	animate: function() {
		
		if(Carouselflow.zoomed) return;
		var move = parseInt($(this).attr("rel"))-Carouselflow.itemmiddle;		
		var pos;
		
		if(move==0) {
			Carouselflow.zoomImage($(this));
			return;
		}
		
		if(move != 0) {
			$("#images img").each(function(i){
				var current	= parseInt($(this).attr("rel"));
				var newpos 	= current - move;
				newpos 		= newpos < 0  ? Carouselflow.positions.length - Math.abs(newpos) : newpos;
				newpos 		= newpos > Carouselflow.itemcount -1 ? newpos - Carouselflow.positions.length : newpos;
				//pos 		= Carouselflow.avail_positions[newpos];
				pos			= Carouselflow.adjustPosition(Carouselflow.positions[newpos],Carouselflow.items[$(this).attr("class")][0].get(0));
				var index 	= newpos+1<=Carouselflow.itemmiddle ? newpos+1 : Carouselflow.positions.length - newpos;
				$(this).animate(pos,400,"swing").css({zIndex: index,height:"auto"}).attr("rel",newpos);
			});
						
			Carouselflow.showDescription();		
			return false;		
		}
	},
	
	showDescription: function() {
		var toshow = $("#images img[rel='"+Carouselflow.itemmiddle+"']").attr("class");
		$("#carouselflow-list li").hide().filter("."+toshow).show();				
	},
	
	zoomImage: function($this) {
		Carouselflow.zoomed = true;
		var newimg = new Image();
		newimg.src = $this.attr("src");
		var newwidth = newimg.width>675 ? 675 : newimg.width;
		var newleft = ((parseInt($("#images").width()) - newwidth)/2) -19;
		
		$("body").addClass("zoomimage");
		if(newimg.height+150>(parseInt($("#content").height()))){
			$("#content").animate({height:newimg.height+150+"px"},1,"swing");		
		}
		
		$this.clone().appendTo("#carouselflow #images").css({zIndex:100000}).addClass("zoomed")
			.animate({left:newleft,top:"-10px",width:newwidth+"px",height:newimg.height+"px"},400,"swing")
			.click(function(){
				$(this).fadeOut(400, function(){
					$(this).remove();
					$("body").removeClass("zoomimage");
					Carouselflow.zoomed = false;
				});
				$("#carouselflow-list,#portfolio-nav").show();
			});
		
		$("#carouselflow-list,#portfolio-nav").hide();
	},
	
	adjustPosition: function(position, oImg) {
		/*alert("positions 0 before:\n" +
			  "left:" + Carouselflow.positions[0].left + "\n" +
			  "top:" + Carouselflow.positions[0].top + "\n" +
			  "width:" + Carouselflow.positions[0].width + "\n" +
			  "height:" + Carouselflow.positions[0].height + "\n" +
			  "opacity:" + Carouselflow.positions[0].opacity + "\n");*/
		//Create a copy so as not to effect the original position
		if (typeof(eval(position)) != "undefined") {
			var tempPos = {left: position.left, top: position.top, width: position.width, height: position.height, opacity: position.opacity};
			var origHeight = oImg.height;
			var origWidth = oImg.width;
			var newWidth = new Number(tempPos.width.replace("px",""));
			var newHeight = new Number(tempPos.height.replace("px",""));
			
			if (origWidth >= origHeight) {
				//Landscape
				if (origWidth != 0) {
					var ratio = origHeight/origWidth;
					newHeight = new Number(newWidth * ratio);
				}
			} else {
				//Portrait
				if (origHeight != 0) {
					var ratio = origWidth/origHeight;
					newWidth = new Number(newHeight * ratio);
				}
			}
			
			var topNum = new Number(tempPos.top.replace("px",""));
			var leftNum = new Number(tempPos.left.replace("px",""));
			var heightNum = new Number(tempPos.height.replace("px",""));
			var widthNum = new Number(tempPos.width.replace("px",""));
			
			/*alert("oImg.class:" + $(oImg).attr("class") + "\n" +
				  "origHeight:" + origHeight + "\n" +
				  "origWidth:" + origWidth + "\n" +
				  "newHeight:" + newHeight + "\n" +
				  "newWidth:" + newWidth + "\n" +
				  "heightNum:" + heightNum + "\n");*/
						
			tempPos.top = eval(topNum + (heightNum - newHeight)/2).toFixed(0) + "px";
			tempPos.left = eval(leftNum + (widthNum - newWidth)/2).toFixed(0) + "px";
			tempPos.height = newHeight.toFixed(0) + "px";
			tempPos.width = newWidth.toFixed(0) + "px";
		}
		
		/*alert("position after:\n" +
			  "left:" + tempPos.left + "\n" +
			  "top:" + tempPos.top + "\n" +
			  "width:" + tempPos.width + "\n" +
			  "height:" + tempPos.height + "\n" +
			  "opacity:" + tempPos.opacity + "\n");*/
		return tempPos;
	},
	
	init: function() {
	
		Carouselflow.total = $("#carouselflow-list img").length;
	
		if($("#carouselflow-list").length==0) { return; }
		
		$("#carouselflow-list").before('<div id="carouselflow"><div id="loading"><strong>Loading images</strong></div><div id="images"></div></div>').find("li").hide();
		$("#carouselflow-list").after('<div id="portfolio-nav"><a id="click-prev" href="#prev">Previous Portfolio Item</a><a id="click-next" href="#next">Next Portfolio Item</a></div>');
		
		$("#click-next").click(function(){			
			$("#images img[rel='"+(Carouselflow.itemmiddle+1)+"']").mousedown();
			return false;										
		});
		$("#click-prev").click(function(){			
			$("#images img[rel='"+(Carouselflow.itemmiddle-1)+"']").mousedown();
			return false;										
		});
		
		$("#carouselflow-list li").each(function(i){
			$(this).addClass(""+i).find("img").bind("mousedown",Carouselflow.animate).addClass(""+i); // number each for later reference
			Carouselflow.items.push([$(this).find("img"),$(this)]);
		});
		
		Carouselflow.itemcount 	= Carouselflow.items.length;
		Carouselflow.itemmiddle = Math.floor(Carouselflow.itemcount/2)%2==0 ? Math.floor(Carouselflow.itemcount/2)-1 : Math.floor(Carouselflow.itemcount/2);
		Carouselflow.itemmiddle = Carouselflow.itemcount==9 || Carouselflow.itemcount==5 ? Carouselflow.itemmiddle+1 : Carouselflow.itemmiddle;
		Carouselflow.itemmiddle = Carouselflow.itemcount==6 || Carouselflow.itemcount==10? Carouselflow.itemmiddle-1 : Carouselflow.itemmiddle;
		
		// load up Carouselflow.positions
		var posmid 	= Math.floor(Carouselflow.avail_positions.length/2);
		var range 	= Carouselflow.itemmiddle;
		
		if(Carouselflow.itemcount==1) {
			Carouselflow.positions.push(Carouselflow.avail_positions[posmid]);
			$("#portfolio-nav").remove();
			Carouselflow.itemmiddle = 0;
		} else {
			for(i=(posmid-range); i<(posmid-range+Carouselflow.itemcount); i++) {
				Carouselflow.positions.push(Carouselflow.avail_positions[i]);	
			}
			if(Carouselflow.positions.length%2==0 && Carouselflow.positions.length!=2) {
				Carouselflow.positions.pop();
				var copy = Carouselflow.positions[Carouselflow.positions.length-1];
				var newobj = { left: Carouselflow.avail_positions[5].left, top: copy.top, width: copy.width, height: copy.height, opacity: "0"};
				Carouselflow.positions.push(newobj);
			}
		}		
		
		$("#carouselflow-list img").each(function(){
			
			//preloader
			var img = new Image();
			var src = $(this).attr("src");
			$(img).load(function () {
			
				Carouselflow.imgs++;
				
				// all images loaded, initialize imageflow
				if(Carouselflow.imgs == Carouselflow.total) {
					$("#loading").hide();
					Carouselflow.flow();
					
					//Rotate carousel to the first image added
					$("#images img[rel='0']").mousedown();
				}
				
			}).attr('src',src);
			
			Carouselflow.maxheight = img.height > Carouselflow.maxheight ? img.height : Carouselflow.maxheight;			
		});
	}
}

// clear search field on click
jQuery.fn.inputClear = function() {
	return this.focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
	});
};

function detectMacFirefox2() {
	var ua = navigator.userAgent.toLowerCase();
	if ($.browser.mozilla && $.browser.version<"1.9" && ua.indexOf('mac') != -1) { return true; }
	return false;
}

// Cookies get/set/delete
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+"="+escape( value ) +
		( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
