/*custom fadeTo including IE8 opacity/cleartype fix - see http://blog.bmn.name/2008/03/jquery-fadeinfadeout-ie-cleartype-glitch/comment-page-2/#comment-368*/
jQuery.fn.fadeTo = function(speed,to,callback) {
    return this.animate({opacity: to}, speed, function() {
        if (to == 1 && jQuery.browser.msie)
            this.style.removeAttribute('filter');

        if (jQuery.isFunction(callback))
            callback();
    });
};

$(document).ready(function() {
	//reassign .jsactive class to html element (originally set in page using javascript before jquery had loaded)
	$("html").addClass("jsactive");//this must be set BEFORE a slider initiates
	
	//set Cufon to show hover state on blog article snippets - targeted via matching to div class='blog'. This must be before main Cufon call - don't move it!
	Cufon.replace('.blog h2', {hover: true});
	//IE8 suffers performance hit when using Cufon on 'hidden' elements with opacity, so use feature detection to find IE browsers and serve slightly different Cufon call omitting those elements
	if (jQuery.support.opacity==false)
	{			
		Cufon.replace('#contentwrapper h1, .slider-controls h2, #contentwrapper h2, #contentwrapper h3, .banner-controls p, #banner-controls-testimonial blockquote, caption');	
	}
	else
	{//modern browsers
		Cufon.replace('h1, h2, h3, .banner-controls p, #banner-controls-testimonial blockquote, caption');
	}	
	
	//animate in the default slider text elements	
	$("#slider-controls-left h2, #slider-controls-right h2").css({
        "visibility": "visible"}).fadeIn(700, function(){$(this).siblings().css({
        "visibility": "visible" }).fadeIn(500)});
		
	//animate in all h1, h2 elements with visibility hidden via css .jsactive rules. This enables smoother transitions and reduces chance of FOUC
	$("h1, h2").css({"visibility": "visible"}).fadeIn();
	
	/*animate back to top and comment reply scroll links*/
	$("p#backtotop a").click(function(){
		$.scrollTo($(this).attr("href"), 800);
		return false;
	});
	$(".respond").click(function(){
		$.scrollTo($(this).attr("href"), 800);
		return false;
	});
	
	//superfish menu - see http://users.tpg.com.au/j_birch/plugins/superfish/
	$('#primarynav').supersubs({ 
            minWidth:    12,   // minimum width of sub-menus in em units 
            maxWidth:    27,   // maximum width of sub-menus in em units 
            extraWidth:  1     // extra width can ensure lines don't sometimes turn over 
                               // due to slight rounding differences and font-family 
        }).superfish({							   
								delay:       200,                            // one second delay on mouseout 
								animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation 
								speed:       50,	
								dropShadows:   false });
	
	$("#header label, #hp-bottom-col1 label, #content-contactfieldset label, #comment-contactfieldset label").overlabel();	//trigger overlabel for search and contact form		
	$("#feedslink").click(function(){$('#feeds ul').slideToggle('fast');});//slide toggle header feeds list	
	$("#feeds ul a").click(function(){$("#feeds ul").slideUp('fast');});
	
	$('textarea').elastic();//used in contact form for expandable text area				
	doButtonShadows();//hover effect on buttons
	showOverlays();//slide captions in image slider on homepage	
	layoutOptions();//demo layout options 
	$("#customise, a.chooseoptions").colorbox({inline:true, height:"420px", width:"670px", href:"#panel .content"});
	$("a#redfooter-preview").toggle(function()//switch footer colours, triggered on content-red.htm
	{
		$("#bottom-contentwrapper, #footerwrapper").removeClass().addClass("red");
		$(this).html("<a href='#' title=''>Switch to the default grey footer</a>");
		$.scrollTo($("#bottom-contentwrapper"), 800);
		}, function(){
		$("#bottom-contentwrapper, #footerwrapper").removeClass();		
		$(this).html("<a href='#' title=''>Preview the red footer version</a>");
		$.scrollTo($("#bottom-contentwrapper"), 800);
	});	
});//ends on load script

function onAfter(curr, next, opts) {//callback function for back/next dynamic nav used by cycle plugin
	var index = opts.currSlide;
	if (typeof strContainer == "undefined")
	{//set this to the default panel
		strContainer="#slider-controls-left";
	}
	$(strContainer+" .button-left")[index == 0 ? 'hide' : 'show']();
	$(strContainer+" .button-right")[index == opts.slideCount - 1 ? 'hide' : 'show']();
	if (strContainer == "#slider-controls-full"){
		showOverlays('hide');//close any open text overlays when user triggers prev/next buttons when using full width image slider					
	}	
}		
	
function setUpCycleSlider(strContainer, strCycleElementPrev, strCycleElementNext)
{//image slider - Cycle
	if (typeof strContainer == 'undefined')
	{//matches condition on page load when function is called from page	
	//sets up the default cycle slider - text to left, sliding images to right.  
		if (jQuery.support.opacity==false)	{	//IE 7 has issues with opacity applied to images, so if using IE, no fade transitions...
			  $('#slider-controls-left .panel').css({"visibility":"visible","left":"0"}).cycle({        
					next: "#slider-controls-left .button-right",
					prev: "#slider-controls-left .button-left",			
					fx: 'scrollHorz',						
					speed: 400,
					after: onAfter,
					timeout:0
				}).fadeIn();		
		}	
		else
		{//modern browsers are served this version
			$('#slider-controls-left .panel img:first').fadeIn(1000, function() {
				$('#slider-controls-left .panel').css({"visibility":"visible","left":"0"}).cycle({        
					next: "#slider-controls-left .button-right",
					prev: "#slider-controls-left .button-left",			
					fx: 'scrollHorz',						
					speed: 400,
					after: onAfter,
					timeout:0//this stops auto cycling. To enable auto cycling, set a value here (values are in milliseconds)
				}).fadeIn();		
			});
		}	
	}
else
	{//what's been called? Is it full width slider version?	
		if (strContainer == "#slider-controls-full")			
		{//full width slider	
			var strFxType = 'fade';//set fx type here, it is used for cycle prefs and to add class to target element for css
			$(strContainer+' .panel ul').cycle({   
				fx :strFxType,
				pause:1
			}).fadeIn().find('.overlay').css({"cursor":"pointer","opacity":"0.9"}).hover(function()
				{			
					$(this).animate({ opacity:"1" },200);
				},function(){
					$(this).animate({ opacity:"0.9" },200);
				});					
			//now add a class to this element based on fx type - if it's 'fade', hide nav buttons
			$(strContainer).addClass(strFxType);				
		}
	else	
		{
		//standard left/right slider
		$(strContainer+' .panel').css({"visibility":"visible","left":"0"}).cycle({        
			next: strCycleElementNext,
			prev: strCycleElementPrev,
			fx :"scrollHorz",
			speed: 400,
			timeout:0, //this stops auto cycling. To enable auto cycling, set a value here (values are in milliseconds)
			after: onAfter}).fadeIn();			
		}	
	}
}	

function setUpNivoSlider()
{//image slider - Nivo - http://www.readactor.com/articles/nivo-a-new-jquery-image-slider/
	$('#slider-controls-left .panel').css({"visibility":"visible","left":"0"}).nivoSlider({
		effect:'random',
		slices:7,
		animSpeed:500,
		pauseTime:3000,
		startSlide:0, //Set starting Slide (0 index)
		directionNav:true, //Next & Prev
		directionNavHide:false, //Only show on hover
		controlNav:false, //1,2,3...
		controlNavThumbs:false, //Use thumbnails for Control Nav
		controlNavThumbsSearch: '.jpg', //Replace this with...
		controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src
		keyboardNav:true, //Use left & right arrows
		pauseOnHover:true, //Stop animation while hovering
		manualAdvance:true, //Force manual transitions
		captionOpacity:0.8, //Universal caption opacity
		beforeChange: function(){},
		afterChange: function(){},
		slideshowEnd: function(){} //Triggers after all slides have been shown
	}).fadeIn();
}

function showOverlays(strType)
{//pop up the overlays on the full width image slider	
	$('#slider-controls-full li .overlay').toggle(function(){
		$(this).stop().animate({bottom:'0'},{queue:false,duration:160});
		}, function() {
			$(this).stop().animate({bottom:'-78px'},{queue:false,duration:160});
		});
	if (strType == 'hide')
	{//used when it is open but the user navigates to another slide	
		$('#slider-controls-full li .overlay').stop().animate({bottom:'-78px'},{queue:false,duration:60});
	}			
}

function doButtonShadows()
/*
Main Javascript for jQuery Realistic Hover Effect
Created by Adrian Pelletier
http://www.adrianpelletier.com
This version amended to work with the go button and the shadow nav effect only. For the complete version, see http://www.adrianpelletier.com/2009/05/31/create-a-realistic-hover-effect-with-jquery-ui/	
Shadow Nav
-------------------------------------------------------------------------- */	
{
	// Append shadow image to each go button		
	$(".gotobutton").append('<img class="shadow" src="images/slide-gotoproject-button-shadow.jpg" width="138" height="22" alt="" />');	
	// Animate buttons, shrink and fade shadow		
	$(".gotobutton").hover(function() {
		var e = this;
		$(e).find("a").stop().animate({ marginTop: "-10px" }, 250, function() {
			$(e).find("a").animate({ marginTop: "-6px" }, 250);
		});
		$(e).find("img.shadow").stop().animate({ width: "100px", height: "22px", marginLeft: "18px", opacity:"0.65"}, 250);
	},function(){
		var e = this;
		$(e).find("a").stop().animate({ marginTop: "4px" }, 250, function() {
			$(e).find("a").animate({ marginTop: "0px" }, 250);
		});
		$(e).find("img.shadow").stop().animate({ width: "138px", height: "22px", marginLeft: "0", opacity:"1"}, 250);
	});	

}//end doButtonShadows();

function processSelection(strTypeOfElement,element)
{//handle user selections on the customise popup, handling both inputs and label clicks
	if (strTypeOfElement=='input'){//radio buttons
		changeDemoDisplay($(element).attr("id"),$(element).parents("div").attr("id"));
		$(this).attr("checked", "checked");
	}
	else
	{//labels
		changeDemoDisplay($(element).attr("for"),$(element).parents("div").attr("id"));
		$(this).prev().attr("checked", "checked");
	}
	$.fn.colorbox.close();//choice made, hide popup;
}
	
function layoutOptions()
{		
	$("#explorelist div input").click(function(){	
		processSelection('input',this);
		}
	);
	$("#explorelist div label").click(function(){
		processSelection('label',this);
		}
	);
	
	$("#explorelist div input").each(function(i, element) {  //on load, reset checked radio buttons	
		if ($(element).attr("id")!=="red" && $(element).attr("id")!=="left" && $(element).attr("id")!="testimonial" && $(element).attr("id")!="stretchcolumn")//do not remove the default checked state for these
		{
			//handle nivo options (depends if we're on a cycle or nivo page) - check by seeing if nivo is active
			if($(".nivoSlider").length==0 && $(element).attr("id")!="nivo")
			{
				$(element).removeAttr("checked");		
			}
			
		}
		else
		{//go back to defaults, it's a page reload
			$(element).attr("checked", "checked");
		}
	});		
}

function changeDemoDisplay(strID, strParent)
{//logic for homepage panels
	$("#"+strID).attr("checked", "checked"); //set it checked (if label clicked there will be a delay otherwise)
	//strID + " " + strParent will equal, for example, 'right slider-controls' - so we know the label clicked and its control group
	var strContainer = "#"+strParent+"-"+strID;//eg #slider-controls-right
	
	if(strID=="nivo")
	{//in this case redirect to the nivo page (it's buggy if we add dynamically) 
		//which colour scheme should we redirect to?		
		window.location ="index-"+ $("#"+strID).val() +".htm";//eg index-nivo-blue.htm
	}
	if(strID=="cycle-left")
	{//in this case redirect to the cycle page
		window.location ="index-"+ $("#"+strID).val() +".htm";//eg index-red.htm
	}
	
	if (strParent=="colour-controls")//process colour options
	{
				window.location ="index-"+strID+".htm";//eg index-blue.htm
	}
	
	//is it visible? 		
	if ($(strContainer).css("display")=="none")//stop if it's already visible
	{			
		$("div").filter("."+strParent).fadeOut("fast");	//hide any visible - find all divs belonging to that group and hide them
		$('.panel ul').cycle('destroy');//find any cycle instances and destroy them
		$(strContainer).fadeIn(300);//show the new panel
		var strCycleElementPrev = $(strContainer +" .button-left");//assigns correct slider nav links to the slider
		var strCycleElementNext = $(strContainer +" .button-right");	
		setUpCycleSlider(strContainer, strCycleElementPrev, strCycleElementNext);//call slider setup function			
	}
	else
	{//is it the banner to hide?
		if (strContainer=='#banner-controls-hidebanner')
		{
			$("."+strParent).hide();
		}	
	}	
	
}