/*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();
    });
};

jQuery(document).ready(function() {
	//reassign .jsactive class to html element (originally set in page using javascript before jquery had loaded)
	jQuery("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('#primarynav a', {fontFamily: 'Proxima Nova Rg', hover: true});
	Cufon.replace('.blog h2, .post h2, h6.sifr, h4', {fontFamily: 'Proxima Nova Lt', 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, div.phone', {fontFamily: 'Proxima Nova Lt'});
        Cufon.replace('#portfolio-wrapper h2', {fontFamily: 'Proxima Nova Lt', fontSize:'20px'});
	}
	else
	{//modern browsers
        
		Cufon.replace('h1, h2, h3, .banner-controls p, #banner-controls-testimonial blockquote, caption, div.phone', {fontFamily: 'Proxima Nova Lt'});
        Cufon.replace('#portfolio-wrapper h2', {fontFamily: 'Proxima Nova Lt', fontSize:'20px'}); 
        
	}
	//animate in the slider text elements
	//wdpSliderType - set from studio admin panel
	if (wdpSliderType!=="cycle-fullwidth")
		{
		jQuery(".slider-controls h2, .slider-controls h2").css({
			"visibility": "visible"}).fadeIn(700, function(){jQuery(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
	jQuery("h1, h2").css({"visibility": "visible"}).fadeIn();

	/*animate back to top scroll links*/
	jQuery("p#backtotop a, b a[href=#header]").click(function(){
		jQuery.scrollTo(jQuery(this).attr("href"), 800);
		return false;
	});



//	jQuery("#header label, fieldset label, #comment-contactfieldset label").overlabel();	//trigger overlabel for search and contact form
	jQuery("a#feedslink").click(function(){jQuery('#feeds ul').slideToggle('fast');});//slide toggle header feeds list
	jQuery("#feeds ul a").click(function(){jQuery("#feeds ul").slideUp('fast');});

	jQuery('textarea').elastic();//used in contact form for expandable text area
	doButtonShadows();//hover effect on buttons
	showOverlays();//slide captions in image slider on homepage

	jQuery("#customise, a.chooseoptions").colorbox({inline:true, height:"420px", width:"670px", href:"#panel .content"});
	jQuery("a#redfooter-preview").toggle(function()//switch footer colours, triggered on content-red.htm
	{
		jQuery("#bottom-contentwrapper, #footerwrapper").removeClass().addClass("red");
		jQuery(this).html("<a href='#' title=''>Switch to the default grey footer</a>");
		jQuery.scrollTo(jQuery("#bottom-contentwrapper"), 800);
		}, function(){
		jQuery("#bottom-contentwrapper, #footerwrapper").removeClass();
		jQuery(this).html("<a href='#' title=''>Preview the red footer version</a>");
		jQuery.scrollTo(jQuery("#bottom-contentwrapper"), 800);
	});

	//Contact form - do what we need to when form is submitted.
	jQuery('#bottom-content-contact #submit-bottomcontent').click(function(){
	//Setup any needed variables.

	var input_name = jQuery('#fullname').val(),
		input_email = jQuery('#contactemail').val(),
		to_email = jQuery('#toem').val(),
		input_subject = "Contact form submission",
		input_message = jQuery('#contactmessage').val(),
		response_text = jQuery('#response');
		//Hide any previous response text
		response_text.hide();

		//Change response text to 'loading...'
		response_text.html('Loading...').show();

		//Make AJAX request
		jQuery.post(wdpThemePath+'/contact-send.php', {fullname: input_name, contactemail: input_email, subject: input_subject, contactmessage: input_message, toemail: to_email}, function(data){
			response_text.html(data);
		});
		//Cancel default action
		return false;
	});

	//portfolio scripts
	//attach onImagesLoad to portfolio wrapper
	$('#portfolio-wrapper div').onImagesLoad({
		selectorCallback: processImages()
	});
	//attach event to images for transparency
	$('#portfolio-wrapper div[id^="portfolio"] div').hover(function(){
	if($(this).find('img').css('opacity')=='1')
	{//only show if parent div is active in the filtered list
		$(this).find('.overlaybutton').show();
	}
		},function(){
			$(this).find('.overlaybutton').hide();
		}

	)
	$('#portfolio-wrapper div[id^="portfolio"] div').find('a:not(.more-link)').prepend('<div class="overlaybutton"></div>');

	doPortfolioItemSort();//loads filterlisting function
	$("div[id^='portfolio-'] a.colorbox").not('.filtered').colorbox({
			width:"720px"
	});

	//add colorbox class to view more links and add popup link class
	//find out if the portfolio item should open in a pop up
	if ($("body.page-template-portfolio-php")){
		var stroriginalhref = $(".page-template-portfolio-php a.more-link").parents("div").find("a.colorbox").attr("href");
		if (typeof stroriginalhref != 'undefined') {
			if (stroriginalhref.indexOf("?popup")>0)
			{
				var strhref = $(".page-template-portfolio-php a.more-link").attr("href");
				strhref += "?popup=true";
				$(".page-template-portfolio-php a.more-link").attr("href",strhref).colorbox({width:"720px"});
			}
		}
	}
	else if ($("body.page-template-services-php")){
		var stroriginalhref = $(".page-template-services-php a.more-link").parents("div").find("a.colorbox").attr("href");
		if (typeof stroriginalhref != 'undefined') {
			if (stroriginalhref.indexOf("?popup")>0)
			{
				var strhref = $(".page-template-services-php a.more-link").attr("href");
				strhref += "?popup=true";
				$(".page-template-services-php a.more-link").attr("href",strhref).colorbox({width:"720px"});
			}
		}
	}
	else if ($("body.page-template-technology-php")){
		var stroriginalhref = $(".page-template-technology-php a.more-link").parents("div").find("a.colorbox").attr("href");
		if (typeof stroriginalhref != 'undefined') {
			if (stroriginalhref.indexOf("?popup")>0)
			{
				var strhref = $(".page-template-technology-php a.more-link").attr("href");
				strhref += "?popup=true";
				$(".page-template-technology-php a.more-link").attr("href",strhref).colorbox({width:"720px"});
			}
		}
	}
	//find any image galleries and hook them up to colorbox
	$("div[id^='portfolio-'] a").each(function(){
    for(var i = 1; i<=30;i++)
    {
		if ($(this).attr("rel")=="gallery"+i)
		{
			$(this).colorbox();
		}
    }
	});

});//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="#cycle-texttoleft";
	}
	jQuery(".button-left")[index == 0 ? 'hide' : 'show']();
	jQuery(".button-right")[index == opts.slideCount - 1 ? 'hide' : 'show']();
	if (strContainer == "#cycle-fullwidth"){
		showOverlays('hide');//close any open text overlays when user triggers prev/next buttons when using full width image slider
	}
}

function setUpImageSlider(strContainer)
{//we have Cycle - text to left, Cycle - text to right, Cycle - full width and Nivo

	jQuery('.panel img:first').fadeIn(1000, function() {
		if (strContainer=="nivo")
		{
			jQuery('.panel').css({"visibility":"visible","left":"0"}).nivoSlider({
				effect:wdpSliderFxTypeNivo,
				slices:wdpSliderSlicesNivo,
				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();
		}
		else if (strContainer=="cycle-fullwidth")
		{//any user options?

		if (wdpSliderNav=="false"){//nav is hidden, force auto scroll
				jQuery('.panel ul').cycle({
					fx :wdpSliderFxTypeCycle,
					pause:1,
					speed: 400,
				timeout:3000
				});
			}
			else
			{
				jQuery('.panel ul').cycle({
					fx :"fade",
					pause:1,
					next: ".button-right",
					prev: ".button-left"
				});
			}

			jQuery('.panel ul').fadeIn().find('.overlay').css({"cursor":"pointer","opacity":"0.9"}).hover(function()
				{
					jQuery(this).animate({ opacity:"1" },200);
				},function(){
					jQuery(this).animate({ opacity:"0.9" },200);
				});
		}
		else
		{//left or right Cycle

			jQuery('.panel').css({"visibility":"visible","left":"0"}).cycle({
				next: ".button-right",
				prev: ".button-left",
				fx :wdpSliderFxTypeCycle,
				speed: 400,
				timeout:0 //this stops auto cycling. To enable auto cycling, set a value here (values are in milliseconds)
				//after: onAfter
				}).fadeIn();

		}
		if (wdpSliderNav=="false"){
				jQuery(".slider").addClass("hide");
			}
	});
}
//end setUpImageSlider()

function showOverlays(strType)
{//pop up the overlays on the full width image slider
	jQuery('#cycle-fullwidth li .overlay').toggle(function(){
		jQuery(this).stop().animate({bottom:'0'},{queue:false,duration:160});
		}, function() {
			jQuery(this).stop().animate({bottom:'-78px'},{queue:false,duration:160});
		});
	if (strType == 'hide')
	{//used when it is open but the user navigates to another slide
		jQuery('#cycle-fullwidth 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
	jQuery(".gotobutton").append('<img class="shadow" src="'+wdpThemePath+'/images/slide-gotoproject-button-shadow.jpg" width="138" height="22" alt="" />');
	// Animate buttons, shrink and fade shadow
	jQuery(".gotobutton").hover(function() {
		var e = this;
		jQuery(e).find("a").stop().animate({ marginTop: "-10px" }, 250, function() {
			jQuery(e).find("a").animate({ marginTop: "-6px" }, 250);
		});
		jQuery(e).find("img.shadow").stop().animate({ width: "100px", height: "22px", marginLeft: "18px", opacity:"0.65"}, 250);
	},function(){
		var e = this;
		jQuery(e).find("a").stop().animate({ marginTop: "4px" }, 250, function() {
			jQuery(e).find("a").animate({ marginTop: "0px" }, 250);
		});
		jQuery(e).find("img.shadow").stop().animate({ width: "138px", height: "22px", marginLeft: "0", opacity:"1"}, 250);
	});

}//end doButtonShadows();

function processImages()
{//images have been loaded when this is called, so fade them in
	$('#portfolio-wrapper div img').hide().css({visibility:"visible"}).fadeIn(1000);
}
function doPortfolioItemSort()
{//amended version of http://net.tutsplus.com/tutorials/javascript-ajax/creating-a-filterable-portfolio-with-jquery
//fades out any not selected
	$('#filtertags a').click(function() {
		$('#filtertags .active').removeClass('active');
		$(this).parent().addClass('active');
		var filterlistVal = $(this).text().toLowerCase();
		filterlistVal = filterlistVal.replace(/ /gi,'-');//global search and replace
		if(filterlistVal == 'all') {//reset to defaults
			$('div[id^="portfolio"].filtered').fadeTo('fast',1);
			$('.filtered').removeClass('filtered');
			$('a, img, p, span').fadeTo('fast',1);//we have to fade child elements not the div as that will bork IE8
		} else {
			$('#portfolio-wrapper div[id^="portfolio"]').each(function() {
				if(!$(this).hasClass(filterlistVal)) {
					$("a, img, p, span", this).fadeTo('fast',0.3).addClass('filtered');
				} else {
					$("a, img, p, span", this).fadeTo('fast',1).removeClass('filtered');
				}
			});
		}

		return false;
	});
}

