$(document).ready(function(){
	
	var urlParams = {};
	(function () {
		var e,
		a = /\+/g,  // Regex for replacing addition symbol with a space
		r = /([^&;=]+)=?([^&;]*)/g,
		d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
		q = window.location.search.substring(1);
		while (e = r.exec(q))
			urlParams[d(e[1])] = d(e[2]);
	})();
	
	// hack to allow <a href="#" rel="external"> open a link in a new window
	$('a[rel=external]').attr('target','_blank');
	
	$('#content').brandoAccordion({dropFirstOnOpen: false, retractOptions: true, onTriggered: handleAccTrigger});
	
	if($('#author_' + urlParams['a']).length > 0) {
		$('#author_' + urlParams['a']).click();
	}
	
	if($('#service_' + urlParams['page_id']).length > 0) {
		$('#service_' + urlParams['page_id']).click();
	}
	
	function handleAccTrigger(ele, opts) {
		if($('.people').length > 0) {
			
			var page_id = parseInt(ele.attr('id').slice(ele.attr('id').indexOf('_') + 1, ele.attr('id').length));
			
			$('#related_author').slideUp();
			
			$('.peoplesidebar .peopleimg').each(function() {
				$(this).stop();
				if($(this).attr("id") != "peopleimg_" + page_id) {
					$(this).fadeOut('fast');
				}
			});
			
			$('.peoplesidebar #peopleimg_' + page_id).fadeIn('slow', function() {
				$(this).css('opacity', 100);
			});
			
			$.ajax({
				type: 'POST',
				url: ajaxurl, 
				data: {action: "get_author_articles", a: page_id},
				success: function(data) {
					$('#related_author').html(data);
					$('#related_author').slideDown();
				}, 
				dataType: "html"
			});
			
		}
		else if ($('.services').length > 0 )
		{
			var page_id = parseInt(ele.attr('id').slice(ele.attr('id').indexOf('_') + 1, ele.attr('id').length));
			
			$('#related_links').slideUp();
			
			$('.servicessidebar .serviceimg').each(function() {
				$(this).stop();
				if($(this).attr("id") != "serviceimg_" + page_id) {
					$(this).fadeOut('fast');
				}
			});
			
			$('.servicessidebar #serviceimg_' + page_id).fadeIn('slow', function() {
				$(this).css('opacity', 100);
			});
			
			$.ajax({
				type: 'POST',
				url: ajaxurl, 
				data: {action: "get_service_related_content", aid: page_id},
				success: function(data) {
					$('#related_links').html(data);
					$('#related_links').slideDown();
				}, 
				dataType: "html"
			});
			
		}
		
		
	}
	
	if($('.services').length > 0) {
		
		var ids = new Array();
		
		$('.services .acc_trigger').each(function() {
		
			var page_id = parseInt($(this).attr('id').slice($(this).attr('id').indexOf('_') + 1, $(this).attr('id').length));
			
			ids.push(page_id);
			
		});
		
		$.ajax(
		{
			type: 'POST',
			url: ajaxurl,
			data: {action:"get_services_pics", p: ids.join(",")},
			success: function(data)
			{
				$(data).prependTo('.servicessidebar .widget_sp_image');
				$('.servicessidebar .serviceimg').css('display', 'none');
				if($(".services .acc_trigger.active").length > 0){
					var page_id = parseInt($(".services .acc_trigger.active").attr('id').slice($(".services .acc_trigger.active").attr('id').indexOf('_') + 1, $(".services .acc_trigger.active").attr('id').length));
					$('.servicessidebar #serviceimg_' + page_id).fadeIn('slow');
				}
			},
			dataType: "html"
		});
		
	}

	if($('.people').length > 0) {
		
		var ids = new Array();
		
		$('.people .acc_trigger').each(function() {
		
			var page_id = parseInt($(this).attr('id').slice($(this).attr('id').indexOf('_') + 1, $(this).attr('id').length));
			
			ids.push(page_id);
			
		});
		
		$.ajax(
		{
			type: 'POST',
			url: ajaxurl,
			data: {action:"get_author_pics", a: ids.join(",")},
			success: function(data)
			{
				$(data).prependTo('.peoplesidebar .widget_sp_image');
				$('.peoplesidebar .peopleimg').css('display', 'none');
				if($(".people .acc_trigger.active").length > 0){
					var page_id = parseInt($(".people .acc_trigger.active").attr('id').slice($(".people .acc_trigger.active").attr('id').indexOf('_') + 1, $(".people .acc_trigger.active").attr('id').length));
					$('.peoplesidebar #peopleimg_' + page_id).fadeIn('slow');
				}
			},
			dataType: "html"
		});
		
	}
	
	if($('.acc_trigger').length > 0) {
		$('.acc_trigger').css('cursor', 'pointer');
	}

	$('.youtubeplayframe').each(function() {
		//$(this).children('.youtubeiframe').css('display', 'none');
		//$('<div class="coverholder"></div><div class="playholder"></div><img src="http://img.youtube.com/vi/-zVCYdrw-1o/0.jpg" />').prependTo($(this));
		$(this).children('.playholder,.coverholder').click(function() {
			var dtext = $(this).parent().next().text();
			alert(dtext);
			$(dtext).appendTo($(this).parent()); //$(this).parent().children('.youtubeiframe').css('display', 'block');
			$(this).parent().children('.playholder,.coverholder,img').css('display', 'none');
		});
		$(this).children('.playholder,.coverholder').css('cursor', 'pointer');
	});
	
	// Add hook for the cycle plugin to start swapping the homepage images.
	$('#office_imgs').cycle({ 
	    fx:			'fade', 
	    delay:		0,
	    speed:		2000  // speed of the transition (any valid fx speed value) 
	 /*   speedIn:    1500,  // speed of the 'in' transition 
	    speedOut:   500  // speed of the 'out' transition */
	 });
	
	
	
	/* Slydeshowfunctions */
	$("#slideshow_holder").css("overflow", "hidden");
	$("ul#slides").cycle({
		fx: 'fade',
	    delay:		0,
	    speed:		1000,		
		pause: 0,
		prev: '#prev',
		next: '#next',
		timeout: 0, 
   	 	pager:  '#nav', 
   		pagerAnchorBuilder: function(idx, slide) 
   		{ 
        	return '<li><a href="#"><img src="' + slide.firstChild.firstChild.src + '" width="165" height="93" /></a></li>'; 
    	}		
	});
	$("#slideshow_holder").hover(
		function() {
			$("ul#pager").fadeIn();
		},
		function() {
			$("ul#pager").fadeOut();
		}
	);

	function formatTitle(title, currentArray, currentIndex, currentOpts) {
	    return '<div id="fancybox-title-over-custom"><span><a href="#" onclick="$.fancybox.close(); return false;">CLOSE {X}</a></span>' + (title && title.length ? '<b>' + title + '</b>' : '' ) + '</div>';
	}
	/* Gallery functions */
	$('a.gallery-element').fancybox(
	{
		'modal'					:   false,
		'hideOnOverlayClick'	: 	true, 
		'showCloseButton'		: 	false,
		'showNavArrows'			: 	false,
		'titleFormat'			:   formatTitle,
		'titlePosition'			:	'over',		
		'onComplete'			:	function() {
			$("#fancybox-wrap").hover(function() {
				$("#fancybox-title").show();
			}, function() {
				$("#fancybox-title").hide();
			});
		}
	});
	

	/* THUMB FUNCTIONALITY ON THE HOMEPAGE */
	function setupWorkThumbMouseOver() {
		
		$('.thumb_holder').mouseover(function()
		{
			var $img = $(this).find('img'),
			src = $img.attr('src'),
			normal = /\.png$/;
			if(src.match(normal))
			{
				$img.attr('src', src.replace(normal, '-over.png'));
			}
		});
		
		$('.thumb_holder').mouseout(function()
		{
			var $img = $(this).find('img'),
			src = $img.attr('src'),
			overCheck = /\-over\.png$/;
	
			if(src.match(overCheck))
			{
				$img.attr('src', src.replace(overCheck, '.png'));
			}
			
		});
		
	}
	
	setupWorkThumbMouseOver();
	
	// RESET TO GET RID OF PESKY FireFox back bug ( consider developing plugin)
	$('.thumb_holder').click(function()
	{
		$(this).mouseout();
	});
		
	$('a.maillink').defuscate();
	
	
	/* WORK-ICON ROLLOVERS */
	$('.work-icon').mouseover(function()
	{
		var $displayText = $(this).find('span:first').html(),
		$activeCheck = $(this).hasClass('active'),
		$tipHolder = $(this).parent().parent().find('.types_tip');
		$tipHolder.html($displayText);
		if($activeCheck)$tipHolder.addClass('types_tip_active');
		$tipHolder.show();
	}).mouseout(function(){
		var $activeCheck = $(this).hasClass('active'),
		$tipHolder = $(this).parent().parent().find('.types_tip');
		$tipHolder.html("");		
	   	if($activeCheck)$tipHolder.removeClass('types_tip_active');
		$tipHolder.hide();
	});
	

	/* Comment form js validation */
	var defaultValidateOptions = {
		showErrors: function(errorMap, errorList){
			this.defaultShowErrors();
		}, 
		highlight: function(element, errorClass) {
			$("label[for=" + element.id + "]").parent().addClass("error");
			$("input[id=" + element.id + "]").addClass("invalid");
			$("input[id=" + element.id + "]").removeClass("valid");
		}, 
		unhighlight: function(element, errorClass) {
			$("label[for=" + element.id + "]").parent().removeClass("error");
			$("input[id=" + element.id + "]").removeClass("invalid");
			$("input[id=" + element.id + "]").addClass("valid");
		}, 
		errorPlacement: function(error, element) {
			error.insertAfter(element.next());
			error.wrap("<div style='margin: 0px; position: static; overflow: hidden;' />");
			error.wrap("<div class='error errorInput' />")
			error.hide().slideDown('fast');
		}, 
		onfocusout: function(element) {
			$(element).valid();
			return false;
		}, 
		onkeyup: false, 
		errorElement: "p"
	};
	
	$.extend($.validator.messages, {
		required: "This is a required field",
		email: "The email address you have entered appears to be invalid"
	});
	
	function setupRespondForm() {
		
		if($("#respond").length > 0) {
			
			var respond_options = {
				rules: {
					author: "required", 
					email: {
						required: true, 
						email: true
					}, 
					comment: "required"
				}
			};
			
			respond_options = $.extend(respond_options, defaultValidateOptions);
			
			var respondvalidator = $("#commentform").validate(respond_options);
			
		}
		
	}
	
	setupRespondForm();
	
	function setupWorkSearchForm() { 
		
		$("#client_name").change(function(){
			submitVals();
		});
		
		$("#work_type").change(function(){
			submitVals();
		});
		
		function submitVals() {
			
			$('#work-index').slideUp();
			if($('.loading').length > 0) $('.loading').each(function(){ $(this).remove(); })
			
			$('<div class="loading"><span>Loading</span></div>').insertAfter('#work-index');
			
			$.ajax({
				type: 'POST',
				url: ajaxurl, 
				data: {action: "do_work_search", work_type: $("#work_type").val(), client_name: $("#client_name").val()},
				success: function(data) {
					$('#work-index').html(data);
					$('#work-index').slideDown();
					$('.loading').fadeOut().slideUp('fast', function() {
						$(this).remove();
					});
					setupWorkThumbMouseOver();
				}, 
				dataType: "html"
			});
			
		}
		
	}
	
	function getParameterByName( name ) {
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		if( results == null )
			return "";
		else
			return decodeURIComponent(results[1].replace(/\+/g, " "));
	}
	
	setupWorkSearchForm();
	
});



