/* 
	Title: Hungry Browser Limited - Global JavaScript document
	Description: Contains any custom JavaScript functions
	Version: 1.1
	Author: Ben Ellis
	Author URI: http://www.hungrybrowser.co.uk
	Created: 20/01/2010
	Updated: 11/01/2012
*/

/* ------------------------------------------------------------
	Declare global functions
---------------------------------------------------------------- */

/* 
	Function to scroll the page
	@param: triggerId = id of the link to attach the event to
	@param: targetId = id of the object to scroll to
*/
function backToTop(triggerId,targetId){
	$(document).ready(function(){
		// Attach the onclick event
		$(triggerId).click(function(){
			// Scroll the page
			$('html, body').animate({
				scrollTop: $(targetId).offset().top
			}, 250);	
			// Ensure that the anchors don't make the page jump 
			return false;
		 });
	})
}

/* 
	Function to create a drop down list from a bulleted list
	@param: id = the element to target
	@param: defaultText = the default text for the drop down 
*/
function dropDownNav(id,defaultText){
	$(document).ready(function(){
		// Create the dropdown base
		$("<select />").appendTo(id);
		// Create default option "Go to..."
		$("<option />", {
		 "selected": "selected",
		 "value"   : "",
		 "text"    : defaultText
		}).appendTo(id+" select");
		// Populate dropdown with menu items
		$(id+" a").each(function() {
			var el = $(this);
			$("<option />", {
			   "value"   : el.attr("href"),
			   "text"    : el.text()
			}).appendTo(id+" select");
		});
		// To make dropdown actually work
		$(id+" select").change(function() {
			window.location = $(this).find("option:selected").val();
		});
	});
}

/* 
	Function to fade between a set of images
	@param: id = the element to fade
*/
function slideShow(slideId){
	$(document).ready(function(){
		// Run the carousel
		$(slideId).flexslider({
			animation: "fade",
			slideshow: true,
			slideToStart: 0,
			pauseOnHover: true,
			slideshowSpeed: 7000,
			animationDuration: 1000,
			directionNav: false,
			controlNav: true
		});
	});
}

// Fade toggle function
jQuery.fn.fadeToggle = function(speed, easing, callback) { 
   return this.animate({opacity: 'toggle'}, speed, easing, callback); 
}; 

// Function to show/hide the contact drawer
function contactUs(){
	$(document).ready(function(){
		// Contact us form - character count
		$("textarea#comments").attr("maxlength",500);
		$('textarea#comments').maxlength({
		'feedback' : '.charsLeft'
		});	
	});
}

// Function to hide email addresses from spammers
function spamFree(id){
	$(document).ready(function(){
		var target = "."+id;
		var at = / at /;
		var dot = / dot /g;
		var addr = $(target).text().replace(at,"@").replace(dot,".");
		$(target).after('<a href="mailto:'+addr+'" title="Send an email to '+ addr +'">'+ addr +'</a>')
		.hover(function(){window.status="Send an email";}, function(){window.status="";});
		$(target).remove();
	});
}

// Function to change the number of columns on a page 
function budgetSlider(triggerId,targetId){
	$(document).ready(function(){
    	// Get the current value
    	var currentValue = $(triggerId).attr('value');
    	// Update the label
    	$(targetId).text(currentValue);
	});
}

// Funciton to create homepage slider
function slider(){
	// Only show for non-mobile devices
	if ($(window).width() > 480){
		// Run the slider function
		$(document).ready(function() {
			// Create the navigation
			var slideNav = [
				'<ul id="slide_nav">', 
				'<li><a class="prev" href="#slider" title="Previous portfolio case study">Previous portfolio case study</a></li>', 
				'<li><a class="next" href="#slider" title="Next portfolio case study">Next portfolio case study</a></li>',
				'</ul>'
			].join("");
			
			// Find the slide wrapper
			$('#slide_wrapper')
				// Append the nav
				.append(slideNav)
				// Run the carousel
				.carousel({
					slider: '#slider',
					slide: '.slide',
					nextSlide: '.next',
					prevSlide: '.prev',
					speed: 300 // ms.
			});
		});
	}
}

// Function to remove the column slider for handheld devices 
function columnSlider(targetId){
	// Only show for non-mobile devices
	if ($(window).width() < 480){
		$(document).ready(function(){
			// Remove the html
			$(targetId).remove();
		});
	}
}

/*
	Function to add custom event tracking to an object using Google Analytics
	@param: id = id of the object to target
	@param: category for the event
	@param: action for the event
	@param: title of the event
*/
function trackEvent(id,category, action, title){
	$(document).ready(function(){
		// Attach the event
		$(id).click(function(){
			_gaq.push(['_trackEvent', category, action, title]);
		});
	});
}

// Function to change the number of columns on a page 
function changeColumns(triggerId,targetId){
	// Only show for non-mobile devices
	if ($(window).width() > 480){
		$(document).ready(function(){
			// Get the max value from the slider
			var maxValue = $(triggerId).attr('max');
			// Get the min value from the slider
			var minValue = $(triggerId).attr('min');
	    	// Get the current value
	    	var currentValue = $(triggerId).attr('value');
	    	// Create the % width
	    	var currentWidth = (100/currentValue)-2+"%";
	    	// Update the css (if the value is reasonable)
	    	if(currentValue !=0 && currentValue <= maxValue){
	    		// Update the width of the columns
	    		$(targetId).width(currentWidth);
	    		// More than 2 columns
	    		if(currentValue>2){
	    			// Reduce the font size in ems
	    			$(targetId).css('font-size','0.9230769231em'); /* 12px/13px = 0.9230769231em */
	    		}
	    		else {
	    			// Reset to default font size in ems
	    			$(targetId).css('font-size','1em');
	    		}
	    		// More than 1 column
	    		if(currentValue>1){
	    			// Set the type to plural
	    			var cols = "columns";
	    		}
	    		else {
	    			// Set the type to singular
	    			var cols = "column";
	    		}
	    		// Update the label
	    		$('#columns').text(currentValue+" "+cols);
	    	}
	    	// Error message
	    	else alert('Uh oh, looks like you are trying to enter more than '+maxValue+' columns, now that\'s just not cricket!');
		});
	}
}

// Function to cycle through the tweets
function twitter(){
	$(document).ready(function(){
		// Remove the @hungrybrowser text
		$('#twitter ul li a').each(function(){
			// Replace the @hungrybrower text
			$(this).html($(this).html().replace('hungrybrowser:',''));
			// Add the external link attribute
			$(this).attr('rel','external');
		});
	});
}

// ATTACH EVENTS FOR SIDEBAR ITEMS
function blogSideBar(){
	$(document).ready(function(){
		// Attach attributes for Flickr
		$('#flickr a').each(function() {
			$(this).attr('rel','prettyPhoto[flickr]');
			var imgSrc = $(this).children().attr('src');
			$(this).attr('href',imgSrc.replace('_m.jpg','.jpg'));
		});
		// Attach attributes for Vimeo
		$('#vimeo a').each(function() {
			$(this).attr('rel','prettyPhoto[vimeo]');
		});
		// Attach attributes for YouTube links
		$('#youtube a').each(function() {
			$(this).attr('rel','prettyPhoto[youtube]');
			var youtubeUrl = $(this).attr('href');
			$(this).attr('href',youtubeUrl.replace('&feature=youtube_gdata',''));
		});
		// Run the Prettyphoto script
		$("a[rel^='prettyPhoto']").prettyPhoto({theme:'dark_rounded'});
	});
}

// Function to toggle between the two project views
function projectNav(){
	$(document).ready(function(){
	
		// Hide the A-to-Z
		$('#portfolio_archive').addClass('hidden');
		
		// Add click event to link 1
		$('#project_link_1 a').click(function(){
			// Remove the hidden class
			$('#portfolio_thumbnails').removeClass('hidden');
			// Add the hidden class
			$('#portfolio_archive').addClass('hidden');
			// Add the active class to the link
			$(this).addClass('active');
			// Remove it from the other link 
			$('#project_link_2 a').removeClass('active');
			// Ensure that the anchors don't make the page jump 
			return false;
		});	
	
		// Add click event to link 2
		$('#project_link_2 a').click(function(){
			// Remove the hidden class
			$('#portfolio_archive').removeClass('hidden');
			// Add the hidden class
			$('#portfolio_thumbnails').addClass('hidden');
			// Add the active class to the link
			$(this).addClass('active');
			// Remove it from the other link 
			$('#project_link_1 a').removeClass('active');
			// Ensure that the anchors don't make the page jump 
			return false;
		});	
	
	});
}

/* ------------------------------------------------------------
	Declare global functions
---------------------------------------------------------------- */

$(document).ready(function(){
	// Dropdown list for main navigation
	dropDownNav('#main_nav','- Select a page -')
	// Back to top
	backToTop('.top a','#page');
	// Pretty Photo
	$("a[rel^='prettyPhoto']").prettyPhoto();
	// Pretty Photo for blog 
	blogSideBar();
	// Firefox 3.0 hack to add n-th child support
	$(".threesome article:nth-child(3n+1)").addClass('no_margin');
	$(".threesome div:nth-child(3n+1)").addClass('no_margin');
	// Responsive videos
	$("#page").fitVids();
})
