$(document).ready(function() {

	/*-----  Main Menu -------------------------------------------*/
	ddsmoothmenu.init({
		mainmenuid		: 'menu', 
		orientation		: 'h', 
		contentsource	: 'markup'
	})

	/*----- Rounded corners -------------------------------------------*/
	DD_roundies.addRule('#menu ul li ul li a:hover, #menu ul li ul li.active a', '5px' , true);
	
	
	/*----- Home carousel -------------------------------------------*/
	$(".scrollable").scrollable({
		circular: true,
		history: true,
		easing:'swing',
		mousewheel: true
	}).autoscroll({ autoplay: true, interval: 7000 });
	
	$(".scrollable-news").scrollable({
		circular: true,
		history: true,
		easing:'swing',
		mousewheel: true	
	}).autoscroll({ autoplay: true, interval: 5000 });	
	
	$("#latest-news .prev").click( function(event) {
	
		// get handle to scrollable API
		var api = $(".scrollable-news").data("scrollable");
		api.prev();
		return false;
	});
	
	$("#latest-news .next").click( function(event) {
	
		// get handle to scrollable API
		var api = $(".scrollable-news").data("scrollable");
		api.next();
		return false;		
	}); 
	
 	$(".scrollable-hire").scrollable({
		circular: true,
		history: true,
		mousewheel: true,
		easing:'swing', 
		onSeek: updateSliderPages
	}); 
		
	// Enable accordion effect on sidebar
	$("#accordion .sidebar-for-hire").eq(0).show(); // Avoids distracting animation on page load. Instead of using initialIndex.
	$("#accordion").tabs("#accordion .sidebar-for-hire", {tabs: 'h2', effect: 'slide', initialIndex: null});
	
	updateSliderPages();

	/*
	//------------- CSS Manipulation
	$('.siteChunk:odd,.contentChunk:odd').addClass('odd');
	$('div.awardsSidebarItem:last').css({
		'border-bottom' : '1px dotted #898989',
		'margin-bottom' : '15px'
	});
	
	//------------- Rounded corners
	DD_roundies.addRule('.siteChunk, .contentChunk', '10px 0 0 10px' , true);
	DD_roundies.addRule('#latestNews .scrollable', '10px 0 0 10px' , true);
	DD_roundies.addRule('#mainNav ul li ul', '0 0 10px 10px' , true);
	
	(!$('#rightSidebar').length) ? $('#content').width(735) : '';
	( !$('a.ditto_page').length ) ? $('span.ditto_currentpage').css('display','none') : '';

	//------------- Project dropdown
	$("select[name='categoryDropdown']").change(function () {	
        link = $(this).val();
		if (link != '') window.location = '/_v2/'+link;
    });

	//$('img[src$=.png]').parent().addClass('fix');
	
	
	//Inline gallery
	( $('a.popup').length > 1) ? $('a.popup').attr('rel','gallery') : ''
	$('a.popup').fancybox({
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic',
		'titlePosition'	: 'over'
	});
	
	//------------- Latest News Scroller
	$("#latestNews .scrollable").scrollable({circular: true, mousewheel: true, next: '', prev: ''}).autoscroll({ autoplay: true, interval: 5000 }).navigator();
	
	
	//------------- Gallery Slider
	($('#subNav').length) ? $('#hide_slideshow').width(680) : '';
	(!$('#slideshow_wrapper').length) ? $('#rightSidebar').css('margin-top','30px') : '';
	$("#slideshow.home").scrollable({easing: 'custom', circular: true, mousewheel: true, size: 2 }).autoscroll({ autoplay: true, interval: 8000 });
	$("#slideshow.slideshow").scrollable({easing: 'custom', circular: true, mousewheel: true, size: 2 });
	$('#hide_slideshow span').toggle(function() {
		$('#slideshow_wrapper').animate({
			opacity: 'toggle',
			height: 'toggle'
		}, 700, function() {
			$('#hide_slideshow').css('background','url(assets/templates/default_tpl/images/gallery_show.gif) no-repeat left center');
			$('#hide_slideshow span').text('show gallery');
		});
	}, function() {
		$('#slideshow_wrapper').animate({
			opacity: 'toggle',
			height: 'toggle'
		}, 700, function() {
			$('#hide_slideshow').css('background','url(assets/templates/default_tpl/images/gallery_hide.gif) no-repeat left center');
			$('#hide_slideshow span').text('hide gallery');
		});
	});
	
	//------------ Callback form
	$('#requestCallback').fancybox({
		ajax : {
		    type	: "POST"
		},
		'hideOnOverlayClick' : false,
		'hideOnContentClick' : false,
		'transitionIn'	 	 : 'elastic',
		'transitionOut'	 	 : 'elastic',
		'autoScale'		 	 : true,
		'centerOnScroll' 	 : true,
		'showCloseButton' 	 : true	
	});

	$("#callbackForm").live('submit',function() {
		$.fancybox.showActivity();
		$.ajax({
			type		: "POST",
			cache		: false,
			url			: "index.php?id=26",
			data		: $(this).serializeArray(),
			success		: function(data) {
							$.fancybox(data);
			}
		});
		return false;
	});
	
	
	//------------- Back to top scroller
	$('#contentDivider img').click(function(){
		$('html, body').animate({scrollTop:0}, 'slow'); 
		return false;
	});
	
	//-------------- Main Menu
	ddsmoothmenu.init({
		mainmenuid		: 'mainNav', 
		orientation		: 'h', 
		contentsource	: 'markup'
	})

	//-------------- SubNav     
	$('#subNav ul li.active:has(ul)').find('a').css('border-bottom','none')
	
	//var target = $('#subNav li.active a');

	$('#subNav li a').not('#subNav li.active li a').hover(function() {
		$(this).animate({ paddingLeft: '25px' }, 350);
	}, function() {
		if ( $(this).parent('li').hasClass('active') ) {
			$(this).animate({ paddingLeft: '20px' }, 450); 
		} else {
			$(this).animate({ paddingLeft: '0' }, 450);     
		}			
	});

	//--- Project & news dropdown
	var type = getQueryVariable('category');	
	if (type != null)  { 
		$('#subNav').find('a:Contains("' + ucwords(type.replace('-',' ')) + '")').parents('li').addClass('active');
	}	
	
	//----------------------------- Subscribe form 
	$("#subForm").validate({
		 rules: { 
	      "cm-name": { 
			  required: true,
			  checkForDefaultVale: true 
	      },
		  "cm-jljlq-jljlq": {
			  required: true,
			  email: true
		  }
	    }, 
		messages: { 
 	      "cm-name": "Please enter a your full name",
		  "cm-jljlq-jljlq": "Please enter your email address"
 	    },
		submitHandler: function(form) { 
			sumbitForm(form.id); 
		}
	});

	//---------------------------- The team accordion
	$("#accordion").tabs("#accordion div.pane", {tabs: '#teamTrigger', effect: 'slide', initialIndex: null});
	
	//---- Tooltips
	$(".project img.thumb").each(function() {
		target = $(this).parent().next().attr('class');
		//console.log(target);
		if (target == 'tooltip') {
			$(this).tooltip({
				effect: 'slide',
				position: "top center", 
				offset: [60, 0],
				predelay: 100
			 }); 
		} 			
	});
	*/
});

function updateSliderPages()
{		
	if ($('#slider-controls span').text(page+'/'+pages)) // Slider is on several pages. Only front has area for page/pages read out.
	{
		// get handle to scrollable API
		var api = $(".scrollable-hire").data("scrollable");
		
		if (api) // why is api not set on initial call to updatePage???
		{
			var pages = api.getSize();
			var page = api.getIndex() + 1;
			$('#slider-controls span').text(page+'/'+pages);
		}
		/* else
		{
			var pages = $('.scrollable-hire .items div').size() - 2; // circular so take off 2 artificially added elements.
			var left = $('.scrollable-hire .items').position().left;
			var width = $('.scrollable-hire').width();
			var page = -(left/width); 
			$('#slider-controls span').text(page+'/'+pages);
			//alert (left + '|' + width);
		} */
	}
}

$(window).resize(function() {
});

$(window).bind("load", function() {							
});

/*------- Validation additonal methods--------------------------------------------------*/
$.validator.addMethod( "checkForDefaultVale", function(value, element) { 
	data = (element.value == "Your Name") ? false : true; 
	return data;
});
/*------- Newsletter form action --------------------------------------------------------*/
function sumbitForm(formId) {
	data = $('#'+formId).serialize();
	formAction = $('#'+formId).attr("action");
	url = 'assets/snippets/campaignMonitor/proxy.php';
	finalData = data + "&action=" + formAction;
	$.ajax({
		type: "POST",    
		url: url,
		data: finalData,
		success: function(msg){
			$('#newsletterForm').html("<span class='info'>Thank you for subscribing to the Dara Creative newsletter.<br />You'll receive the first edition by email soon.</span>");
			
			// Fire off Google Analytics fake pageview
			/*
			var pageTracker = _gat._getTracker("UA-7041570-21");
			pageTracker._trackPageview("/newsletter_signup");
			*/

		}
	});
	return false;
}

$.easing.custom = function (x, t, b, c, d) {
	var s = 0.70158; 
	if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
	return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
}
$.easing.bouncy = function (x, t, b, c, d) {
    var s = 1.70158;
    if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
    return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
}
$.tools.tooltip.addEffect("bouncy",

	// opening animation
	function(done) {
		this.getTip().animate({top: '+=15'}, 500, 'bouncy', done).show();
	},

	// closing animation
	function(done) {
		this.getTip().animate({top: '-=15'}, 500, 'bouncy', function()  {
			$(this).hide();
			done.call();
		});
	}
);
function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split('&');
	for (var i = 0 ;i < vars.length; i++) {
		var pair = vars[i].split('=');
		if (pair[0] == variable) {
			return pair[1];
		}
	}
}
jQuery.expr[':'].Contains = function(a,i,m){
    return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
function ucwords(str) {
    // http://kevin.vanzonneveld.net
    return (str + '').replace(/^(.)|\s(.)/g, function ($1) {
        return $1.toUpperCase();
    });
}
