/*
 * Share Button fot STANDOUTUK.com
 * Author: Aaron Yates
 * Email: aaron@standoutuk.com
 */

function saturate(img) {
	var img2 = Pixastic.process(img, "desaturate");
	if( typeof(img2) != "undefined" ){//stop IE from erroring
		img2.onmouseover = function() {
			Pixastic.revert(this);
		}
	}
	return img2;
}

function changehsl(img) {
	var img2 = Pixastic.process(img, "hsl", {hue:0,saturation:-100,lightness:50});
	if( typeof(img2) != "undefined" ){//stop IE from erroring
		img2.onmouseover = function() {
			Pixastic.revert(this);
		}
	}
	return img2;
}






//placeholder fallback
(function(c){c.fn.extend({defaultValue:function(e){if("placeholder"in document.createElement("input"))return!1;return this.each(function(){if(c(this).data("defaultValued"))return!1;var a=c(this),h=a.attr("placeholder"),f={input:a};a.data("defaultValued",!0);var d=function(){var b;if(a.context.nodeName.toLowerCase()=="input")b=c("<input />").attr({type:"text"});else if(a.context.nodeName.toLowerCase()=="textarea")b=c("<textarea />");else throw"DefaultValue only works with input and textareas";b.attr({value:h,
	"class":a.attr("class")+" empty",size:a.attr("size"),style:a.attr("style"),tabindex:a.attr("tabindex"),rows:a.attr("rows"),cols:a.attr("cols"),name:"defaultvalue-clone-"+((1+(new Date()).getTime())*65536|0).toString(16).substring(1)});b.focus(function(){b.hide();a.show();setTimeout(function(){a.focus()},1)});return b}();f.clone=d;d.insertAfter(a);var g=function(){a.val().length<=0?(d.show(),a.hide()):(d.hide(),a.show().trigger("click"))};a.bind("blur",g);g();e&&e(f)})}})})(jQuery);


$(document).ready(function() {

	/*
	// REPLACED WITH STO_Slideshows plugin - Mat Marlow 18/03/2010
	$('ul.homePanel').innerfade({
				speed: 'normal',
				timeout: 4000,
				type: 'sequence',
				containerheight: '286px'
	});
	*/
	
	$("ul#social li p").each(function(i) {
		$(this).hide();
	});
	
	$("ul#social li").find("a.share_link").each(function(n) {
		
		$(this).click(function() {
			$("ul#social li p").each(function(j) {
				$(this).slideUp("fast");
			});
			
			if ( $(this).parent().next().next().hasClass('active') ) {
				$(this).parent().next().next().removeClass('active');
				$(this).removeClass('active');
				$(this).parent().next().next().slideUp("fast");
				
			} else {
				$("ul#social li p").each(function(a) {
					$(this).removeClass('active');
				});
				
				$("ul#social li span a.share_link").each(function(a) {
					$(this).removeClass('active');
				});
				
				$(this).parent().next().next().addClass('active');
				$(this).addClass('active');
				$(this).parent().next().next().slideDown("fast");
			}
			
			return false;
		});
	});
	
	/* Build the Our Work filters */
	$("a.ow_filter_client").mouseover(function() { 
		buildFilter($(this), 'client', filter_opts);
	});
	
	$("a.ow_filter_discipline").mouseover(function() { 
		buildFilter($(this), 'discipline', filter_opts);
	});
	
	$("a.ow_filter_sector").mouseover(function() { 
		buildFilter($(this), 'sector', filter_opts);
	});
	
	/* Fading out slideshow */
	$('ul#imgViewer').innerfade({
				speed: 'normal',
				timeout: 4000,
				type: 'sequence',
				containerheight: '250px'
	});
	
	

	/* Desaturate contact pics*/
	
	$("img.client_hover_desaturate").each(function() {
		if(this.complete) saturate(this);//if already loaded then change now
		else $(this).load(function(){saturate(this);});//otherwise wait until loaded
	});

	/* Desaturate client logos */

	$("img.client_logo").each(function() {
		if(this.complete) changehsl(this);
		else $(this).load(function(){changehsl(this);});
	});


/*************************************************************************************/
	
   $('ul#info-dropdowns ul').hide();
   $('ul#info-dropdowns > li > a').click(function(){
		 var submenu = $(this).parent().find('ul');
		 var parent = $(this).parents('ul');
		 var submenus = parent.find('ul');
		 parent.find('.plus').text('+').removeClass('minus');

		 if( submenu.is(':visible') ){
			 submenu.slideUp('fast');
			 parent.css({'height':''});
			 $(this).attr('title',$(this).attr('rel'));
		 }else{
			 submenus.not(submenu).slideUp('fast');
			 parent.animate({'height':'31em'},'fast',function(){$.scrollTo('#info-dropdowns',500,{axis:'y'});});
			 submenu.css('height','0px').animate({'height':'21em'},'fast');
			 $(this).find('.plus').text('_').addClass('minus');
			 $(this).attr('rel',$(this).attr('title')).attr('title','Close panel');
		 }
		 return false;
	});
   
   

	
	
	$("form#quick-contact-form input").each(function() {	
		$(this).focus(function() {
			$(this).attr('style', 'border-color: black;');
		});
		
		$(this).blur(function() {
			$(this).removeAttr('style');
		});
		
	});
	
	// HANDLE THE FORM SUBMISSION;
	
	$("form#quick-contact-form").submit(function() {
		var errors = 0;
		$('#name,#number,#email').each(function(){
			if( $(this).val()=='' ){
				$(this).attr('style', 'border-color: red;');
				errors++;
			}
		});
		
		if(!validEmail($('#email').val())){
			$('#email').attr('style', 'border-color: red;');
			errors++;
		}
		
		if(!errors){
			var parent = $('ul#info-dropdowns');
			
			values = $('form#quick-contact-form').serialize();
			$.post("/wp-content/themes/standout/_includes/php/email.php", values, function(data) {
					if( data.result == "ok" ){
						//alert("some kind of nice thank you pop up to go here");
						$('form#quick-contact-form ul').html('<li>Thank you for making an<br/>enquiry with Standout.</li><li>We will come back to you straight away and look forward to talking further.</li><li>If you have the time, you can find<br/>out more about us by clicking:</li><li>- <a href="/our-team/">Meet the team</a></li><li>- <a href="/our-clients/">View work by client</a></li><li>- <a href="/our-services/">View our products and services</a></li>');
					}
			},
			"json");
		}
		return false;
	});

	$("form#contact-form").submit(function() {
		var errors = 0;
		$('#contact-name,#contact-company,#contact-email,#contact-telephone').each(function(){
			if( $(this).val()=='' ){
				$(this).attr('style', 'background-color: red;color:#000;');
				errors++;
			}else{
				$(this).attr('style', '');
			}
		});
		
		if(!validEmail($('#contact-email').val())){
			$('#email').attr('style', 'background-color: red;color:#000;');
			errors++;
		}
		
		if(!errors){
			var parent = $('ul#info-dropdowns');
			
			values = $('form#contact-form').serialize();
			$.post("/wp-content/themes/standout/_includes/php/email2.php", values, function(data) {
					if( data.result == "ok" ){
						//alert("some kind of nice thank you pop up to go here");
						$('form#contact-form ul').html('<li><p>Thank you for making an enquiry with Standout.<br/><br/>We will come back to you straight away<br/>and look forward to talking further.<br/><br/>If you have the time, you can find out<br/>more about us by clicking:<br/>- <a href="/our-team/">Meet the team</a><br/>- <a href="/our-clients/">View work by client</a><br/>- <a href="/our-services/">View our products and services</a></p></li>');
					}
			},
			"json");
		}
		return false;
	});


	
	$('input[placeholder]').defaultValue();//if browser does not support placeholder then use script
	
	
	$('a.more-link, .body_our-services .product-logo').click(function(){
									var parent = $(this).closest('div:not(.product-logo)');
									var detail = $('.detail',parent)
									var morelink = $('a.more-link', parent);
									var morelinkspan = $('span',morelink);
									
									//convoluted way to do slide toggle, as slide doesn't work properly with margins etc.
									if(detail.is(':visible')){
										detail.animate({'height':'0px'},function(){$(this).hide()});
										parent.removeClass("active");
										morelinkspan.text('+');
										morelinkspan.removeClass('minus');
										morelink.attr('title',morelink.attr('rel'));
									}else{
										var height = detail.show().css({'height':''}).height();
										detail.css({'height':'0px'}).animate({'height':height+'px'});
										$.scrollTo(parent,500,{axis:'y'});
										parent.addClass("active");
										morelinkspan.addClass('minus');
										if($('body').hasClass('body_why-standout')){
											morelinkspan.text('_');
											if($(this).hasClass('testimonial-link')){
												$('a.more-link').not($(this)).closest('div').find('.detail:visible').closest('div').find('a.more-link').trigger('click');
											}
										}else{
											morelinkspan.text('-');
										}
										morelink.attr('rel',morelink.attr('title')).attr('title','Close panel');
									}
									$(this).blur();
									return false;
									});
	
	
	$('.body_our-services a.more-link, .body_our-services .product-logo').hover(function(){
																					var parent = $(this).closest('div:not(.product-logo)');
																					parent.addClass('hover');
																				},
																				function(){
																					var parent = $(this).closest('div:not(.product-logo)');
																					parent.removeClass('hover');
																				});
	
	$('.body_our-services .product-logo h2').parent().css({'cursor':'pointer'});
	
/*************************************************************************************/

   
   

});










function buildFilter(owobj, type, filter_opts) {
	getOpts(type);
	var tab_title = "";
	var shift_widths = "";
	shift_widths = " "+filter_opts;
	//alert("C:"+type+" / FO:"+filter_opts);
	
	if ((type == 'client') && (filter_opts == 'bcc')) {
		tab_title = "Change Client?";
	} else if ((type == 'discipline') && (filter_opts == 'bdf')) {
		tab_title = "Change Discipline?";
	} else if ((type == 'sector') && (filter_opts == 'bss')) {
		tab_title = "Change Sector?";
	} else {
		tab_title = "By "+ucfirst(type);	
	}
	
	var filter1 = '<div class="ow_filter'+shift_widths+'" style="display: none;">'
	var filter2 = '<div class="title '+type+'_title"><span>'+tab_title+'</span></div>';
	var filter3 = '<div class="menu">';
	var filter4 = '<div class="boxed_up">';
	var filter5 = '</div>';
	//var filter4 = '<select id="ow_options" name="ow_options"><option value="na">Please choose a '+ucfirst(type)+'</option>';
	//var filter6 = '</select>';
	var filter7 = '</div>';
	var filter8 = '</div>';
	
	var filter = filter1 + filter2 + filter3 + filter4 + filter5 + filter7 + filter8;
	
	owobj.parent().append(filter);
	$(".ow_filter").fadeIn("fast");
	
	$(".ow_filter .title span").click(function() {
		var currUrl = getCurrUrl();
		window.location = currUrl+"by-"+type+"/";
	});
	
	if ($(".ow_filter").length) {
		$('body').mouseover(function(event) {
			if ( ($(event.target).is('a, .ow_filter .title, .ow_filter .title span, .ow_filter .menu, .ow_filter .boxed_up')) ) {
			//if ( $(event.target).is('.ow_filter div') ) {
				// Nada;
			} else {
				$(".ow_filter").remove();
			}
		}); 
	}
}


/* UPPERCASE FIRST CHARACTER */
function ucfirst(string) {
	return string.charAt(0).toUpperCase() + string.slice(1);
}



/* GET OPTIONS FOR FILTER  */
function getOpts(type) {
	var currUrl = getCurrUrl();
	
	$.getJSON(currUrl+"wp-content/themes/standout/_includes/php/standout_filters.php?type="+type, function(data){
		var mystr = "";
		
		for(var j in data) {
			mystr += '<a href="#'+data[j].safe+'" rel="'+data[j].safe+'">'+data[j].opt+'</a><br />';
		}
		
		$('.ow_filter .menu .boxed_up').append(mystr);
		
		$('.ow_filter .menu a').each(function () {
			$(this).click(function() {
				
				var currUrl = getCurrUrl();
				var redirectString = '';
				
				switch (type) {
					case 'client':
						redirectString = currUrl+'by-client/?client='+$(this).attr('rel');
						break;
					case 'discipline':
						redirectString = currUrl+'by-discipline/?field='+$(this).attr('rel');
						break;
					case 'sector':
						redirectString = currUrl+'by-sector/?sector='+$(this).attr('rel');
						break;
				}
				window.location = redirectString;
				return false;
			});
		});
	});
}


/* RETURN THE CORRECT URL TO USE */
function getCurrUrl() {
	var currUrl = window.location.hostname;		
	currUrl = "http://"+currUrl+"/";	
	return currUrl;
}


/* SUBSCRIBE TO CAMPAIGN MONITOR */

var CMSubscribeResponses = new Array();
CMSubscribeResponses[0] = "Thanks! You have been added to our mailing list for news updates.";
CMSubscribeResponses[1] = "You have submitted an invalid email address, please try again.";	

function CMSubscribe(form)
{
	var email = $(form).children("#subscribe-email").val();
	if(email==''){
		displayUserMessage("Please enter an email address.");
	}else{
		var currUrl = getCurrUrl();
		var data = {
			email:	email
		}
		$.post(currUrl+"wp-content/themes/standout/_includes/php/campaign_monitor_subscribe.php?ajax=true", data, function(data){
			if(data.Result.Code=='0'){
				location.href = "/thank-you";
			}else{
				displayUserMessage(CMSubscribeResponses[data.Result.Code],'Sorry, there was a problem...');
			}
		}, "json");
	}
}

function displayUserMessage(_message,_title,useAlert)
{
	var useAlert = typeof useAlert == 'undefined' ? false : useAlert;
	
	if(useAlert)
	{			
		alert(_title+'\n\n'+_message);
		
	}else{
	
		var title = typeof _title == 'undefined' ? '' : '<h3 class="grey">'+_title+'</h3>';
		var message =  typeof _message == 'undefined' ? '' : '<p class="normal">'+_message+'</p>';
		
		//alert(message);
		
		var buttonMarkup = '';//'<button type="button" class="ok" onclick="$.fancybox.close();">Close</button></div>';
	
		$.fancybox({
			'content'		: '<div align="center" class="fancyBoxContent">' + title + message + buttonMarkup
			,'showCloseButton'	: true
			,'onComplete'		: function(){Cufon.refresh();}
			,'scrolling'		: false		
			,'transitionIn'		: 'none'
			,'transitionOut'	: 'none'
	
		});
	}
	
}
/**********************************************************************************************************************/







// CHECK A GIVEN STRING IS VALID FOR IT'S TYPE;
function checkStringValidity(obj, name, toCheck) {
	if (toCheck == "appr") {
		var minlen = '0';
		var maxlen = '50';
		var canBeNull = false;
		
		var value = obj.val().toString();
		//var span = obj.prev().find('span.attr');
		
		obj.removeClass('tick').removeClass('cross');
		
		switch (name) {
			case 'name':
				maxlen = 20;
				minlen = 2;
				break;
			
			case 'email':
				maxlen = 50;
				minlen = 8;
				break;
			
			case 'number':
				maxlen = 15;
				minlen = 10;
				canBeNull = true;
				break;
		}
		
		if ( (value.length < minlen) || (value.length > maxlen) || ((name == 'email') && (validEmail(value) == false)) || ( ((name == 'worktel') && (value.length > 0)) && (isNumeric(value) == false) ) || ( ((name == 'mobtel')  && (value.length > 0)) && (isNumeric(value) == false) )) {
			//obj.addClass('cross');
			obj.attr('style', 'border-color: red;');
		} else {
			attr('style', 'border-color: green;');
			//obj.addClass('tick');
		}
		
		if ( (canBeNull) && (value.length == 0) ) {
			obj.removeClass('cross');
		}
	}
}


// CHECK AN EMAIL ADDRESS IS VALID;
function validEmail(str) {
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
   return emailPattern.test(str); 				
}


// CHECK WE HAVE A VALID NUMBER;
function isNumeric(inputVal) {
	inputVal.split(' ').join('');
	if (isNaN(parseFloat(inputVal))) {
		return false;
	}
	return true
}
