$(document).ready(function() {
	// Demo Reel
	$('#demo_reel').overlay();
	
	// Introductions
	$(".introThumb").click(function(){
		window.open( "/"+$(this).attr('rel'), "_self", false );
	});
	
});

/*-------------- Home ------------------------------*/
function Home() {
	/* Nivo-slider */
	$('#slider').nivoSlider({ controlNav: false, effect:'boxRain', pauseTime:8000});
	$('#prev, #next').bind('click',navClick).hover(function(){$(this).fadeTo('fast',1); }).mouseleave(function(){ $(this).fadeTo('slow',0.75)});
		
	// Callback response for nivo-slider navigation click.
	function navClick(e) {
		var button = $(this).attr('id');
		$('.nivo-'+button+'Nav').trigger('click');
	}
}

/*-------------- Introductions ----------------------*/

function Introductions(employee_id) {	
	load_tabs({page:'introductions',employee:employee_id});
	$('img').tooltip({position:'bottom',offset:[0,-95], effect:'slide'}).dynamic();
}

/*-------------- What we do -------------------------*/

function What_we_do() {
	load_tabs({page:'what_we_do'});
}

/*-------------- Careers -----------------------------*/

function Careers() { 
	load_tabs({page:'careers'});
}


/*-------------- Request a Quote -----------------------------*/

function Request_a_quote() {
	
}


/*-------------- Our Portfolio -----------------------*/

function Our_portfolio() {
		// Dynamic social buttons.
		(function(d, s, id) {
  		
		// facebook
		var js, fjs = d.getElementsByTagName(s)[0];
  		if (d.getElementById(id)) {return;}
  		js = d.createElement(s); js.id = id;
  		js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=162254233852693";
  		fjs.parentNode.insertBefore(js, fjs);
		
		// google+
		var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    	po.src = 'https://apis.google.com/js/plusone.js';
    	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
		
		//dig
		var s = document.createElement('SCRIPT'), s1 = document.getElementsByTagName('SCRIPT')[0];
		s.type = 'text/javascript';
		s.async = true;
		s.src = 'http://widgets.digg.com/buttons.js';
		s1.parentNode.insertBefore(s, s1);
		
		}(document, 'script', 'facebook-jssdk'));
		
		
		//twitter 
		!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
	
	
	
	// commonly referred to variables that are used throughout this function/class

	var vars = {
		number_of_projects : 0,	// current # of projects in projects array (changes when filter applied.)
		current_index : 0,
		animation_speed:500,
		fade_speed: 300,	
		filterId:'view-all'  // current filter id/key for project filtering.
	};

	// basic initialization
	load_projects();
	init_filter();
	init_listeners()
	
	// Deep Link: change event path/alias name (based on url), then update menu selection.
	$.address.change( function(event) {
		var path = event.pathNames[0];
						
		// default to learning newtork if specific project not requested.
		if(path) {
			for(var i=0;i<$('#project_images').data('projects').length;i++) {
				if($('#project_images').data('projects')[i].project_link == path) {
					set_project(i); 
					vars.current_index = i;
				}
			}
			
			// facebook google+ etc based on hash url.
			update_social_buttons(path);
			
		} else { change_project(); } //sets to project 0 in project model.
	});
	
	
   /*
	*	For tag filtering on projects.
	*/
	function init_filter() {
		$('#project-tags a, #view-all').click(function() {
			// get id of click element.
			filterId = $(this).attr('id');
						
			// only update if a new type of filter.
			if(vars.filterId != filterId) {
				vars.filterId = filterId;
				
				restoreProjectsArray();	
			
				// reset from previous filter.
				if(filterId =='view-all') {
					$('#project-tags a').css('color','#cc0000');
					$('#project-group').text("Our Portfolio");	
				} else {
					// filter array
					filterProjectsArray(filterId);
					// change tag colors and group title 
					$(this).css('color','#cc0000').siblings().css('color','#959596');
					// set group. (ex. Education)
					$('#project-group').text($(this).text());				
				}	
			
				resetIndex();
			}
		});
							
		// reset index to 0 and update number of projects.
		function resetIndex() {
			vars.current_index = 0;
			change_project();
		}
		
		// restores main array to unfiltered state.
		function restoreProjectsArray() {
			restore = $('#project_images').data('restore').slice(0);
			$('#project_images').data('projects',restore);
		}
		
		// filter out projects without a specific tag.
		function filterProjectsArray(filterId) {			
			for(var i=$('#project_images').data('projects').length-1;i>=0;i--) 						
				if($.inArray(filterId,$('#project_images').data('projects')[i].tags)==-1) 
					$('#project_images').data('projects').splice(i,1);
		}
	}
	
	/*
 	* Toggles the height of project_images in order to conceal, or view project images.
 	*/	
	$('#view-more').toggle(
		function(){
			// animate height change.			
			$('#project_images').animate({"max-height":$('#project_wrapper').height()},vars.animation_speed);
			// change button text.
			$('.show').hide().siblings().show();
			$(this).data('isShowing',true);
		},
		
		function() {
			// animate height change.				
			$('#project_images').animate({"max-height":$('#project_wrapper').children().filter(":first").height()},vars.animation_speed);
			// restore button text
			$('.hide').hide().siblings().show();
			$(this).data('isShowing',false);
		}
	);	
	
	
	// for cycling through projects
	function init_listeners() {
		/*
		*	Sets the previous project for viewing.
		*/
		$('#project_left').click(function() {
			vars.current_index-=1; change_project();
		});
	
		/*
		*	Sets the next project for viewing.
		*/
		$('#project_right').click(function() { 
			vars.current_index+=1; change_project();
		});
	}
	
	
	/*
	* For iterating through project object. Moves to next index.
	* Note: Current index actually gets incremented in the project change callbacks
	* which are initialized in init_listeners().
	*/
	function change_project() {
		// toggle project images into hiding again if they are showing.
		if($('#view-more').data('isShowing')) $('#view-more').trigger('click');
		
		vars.current_index = mod(vars.current_index,$('#project_images').data('projects').length);
		current_project =$('#project_images').data('projects')[vars.current_index].project_link;
		
		//update url for deeplinking (need to force update if url does not change from filter)
		if($.address.path().substring(1)==current_project) {
			$.address.value(current_project);
			$.address.update();
		} else {
			$.address.value(current_project);	
		}
	}	
	
	
	/*
 	* Switches to a project at a specified index in the project object. Goes by numerical index as opposed to project name/keyword.
	* @param index The index of the project to be displayed.
 	*/
	function set_project(index) {	
		$('#project_wrapper').empty();
		for(var i=0;i< $('#project_images').data('projects')[index].images.length;i++)
			$('#project_wrapper').append( "<image src = '"+Config.image_url+"portfolio/"+$('#project_images').data('projects')[index].images[i]+"' alt 'Sample'/>");
		
		$('#project_images').css({'max-height':$('#project_wrapper').children().filter(":first").height(),'overflow':"hidden"});		
		
		// update view with new project information.
		$('#write-up').hide().html($('#project_images').data('projects')[index].writeUp).fadeIn(vars.fade_speed);
		$('#page_left h1').hide().html($('#project_images').data('projects')[index].projectName).fadeIn(vars.fade_speed);
		$('#view-more span').text($('#project_images').data('projects')[index].images.length-1);
		$('#projectTotal').text($('#project_images').data('projects').length);		
		$('#projectOf').text(index+1);
		$('#project-url').hide().html('<a href="http://'+$('#project_images').data('projects')[index].url+'" target="_blank">'+$('#project_images').data('projects')[index].url+'</a>').fadeIn(vars.fade_speed);
		
		// change page title to that of project
		$.address.title("Aquanode Interactive | "+$('#project_images').data('projects')[index].projectName);
	}
	
	
	/*
	* Dynamically updates social buttons to particular state of portfolio.
	*/
	function update_social_buttons(project_link) {
		// static url used to keep counts etc.
		static_url = Config.url+'index.php/home/portfolio/'+project_link;
				
		// facebook
		$('#like div:eq(0)').html('<fb:like send="false" href="'+static_url+'" layout="box_count" width="30" show_faces="false"></fb:like>');
		FB.XFBML.parse();
				
		// twitter
		$('#twitter').html('<a class="twitter-share-button" href="http://twitter.com/share"  data-count="vertical" data-url="'+static_url+'" data-counturl="'+static_url+'">Tweet</a>');
		twttr.widgets.load()

		// google plus
		//$('#google').html('<g:plusone size="tall" href"'+$(location).attr('href')+'"></g:plusone>');
      	gapi.plusone.render('___plusone_0',{"size":"tall","href":static_url});
	}
	
	
	/*
 	* Fetches all the projects as a project object from the server.
 	*/
	function load_projects() {
		$.get('/home/get_projects', function(data) {	
			projects = $.parseJSON(data);
																
			// set projects object in project_images element
			$('#project_images').data('projects',projects.slice(0));	
			
			// fore restoring projects array after filter.		
			$('#project_images').data('restore',projects.slice(0));
			
			$('#project_images').data('filter','view-all');
						
			//update url for deep linking
			$.address.update();
		});
	}
}

/*----------------- Our Process ----------------------*/

function Our_process() {
	//$('#col1 .process_row div').hover(function(){$(this).fadeTo('fast',1); }).mouseleave(function(){ $(this).fadeTo('slow',0.75)});
}
/*-------------- General Functions -------------------*/

/*
 * Adds and removes default text on focus, and on blur.
 * @param textbox The textbox to apply the function to.
 * @param default_string The string you wish to have appear and disappear.
 */
function textbox_focus(textbox,default_string) {
	if(textbox.value == default_string) textbox.value = '';
	$(textbox).focusout(function() { if (textbox.value == '') textbox.value = default_string; });
}


function load_tabs(vars) {
	// post for page data. Assign data content to respective elements.
	$.post('/home/get_page',vars, function(data) {
		var tabs = $.parseJSON(data);
		
		if(vars.page == 'introductions')
			for(var i=0;i<tabs.length;i++)
				$('#deep_link ul li:eq('+(i)+')').data('content','<h1>'+tabs[i].question+'</h1><p>'+tabs[i].answer+'</p>').children('a').html(tabs[i].tab_text);
		else
			for(var i=0;i<tabs.length;i++)
				$('#deep_link ul li:eq('+(i)+')').data('content',tabs[i].content);
		
		//update page state when done fetching.
		$.address.update();
	});

	// Deep Link: change event path/alias name (based on url), then update menu selection.
	$.address.change( function(event) {
		var path = event.pathNames[0];
		if(event.pathNames.length == 0) path = 1;
								
		// change tab state
		$('#deep_link ul li:eq('+(path-1)+')').addClass('selected').siblings().removeClass('selected');
		
		var content = $('#deep_link ul li:eq('+(path-1)+')').data('content');
		$('.replaceable').hide().html(content);
		$('.replaceable').fadeIn();
	});
}

/*
 * Replaces the content of a specifed parent with a waiting gif at half width and half height.
 * @param parent A jquery selector for the parent.
 */
function transition(parent) {
	// subtract width and height of image from vaues before dividing.
	var height = (($(parent).height()-48)/2); 
	var width = (($(parent).width()-48)/2);
	
	$(parent).html("<image src = '"+Config.image_url+"/wait.gif' alt 'Processing' id = 'wait' style = 'margin-top:"+height+"px; margin-left:"+width+"px'><image>");
}

/*
*  Makes up for js's crappy mod behaviour.
*/
function mod(X, Y) { 
	var t // alternative method
  	t = X%Y ; return t<0 ? t + Y : t 
}
