// Track if this is your first page view
if ( ! $.cookie('first_visit')) {
	// Just in case delete the cookie first
	$.cookie('first_visit', null)
	// Set the first_visit cookie to true
	$.cookie('first_visit', 'true', { path: '/' });
}

function changePortfolioWidth(resized)
{
	// Default is false
	resized = resized || false;
	
	if (resized || $.cookie('first_visit') == 'true')
	{
		// Screen width and widths of the elements
		var window_width = $(window).width();
		var sidebars_width = 550;
		var item_width = 210;
		var item_padding = 10;
	
		// Calculate the number of items that fit in this 
		// window and change the width of the portfolio div
		var free_width = (window_width - sidebars_width);
		var num_items = Math.floor(free_width/item_width);
		var new_width = (num_items * item_width) + (item_padding * num_items);
		$('#portfolio').width(new_width);
		
		// Set a cookie so the server knows how many items to return
		$.cookie('num_items', null);
		$.cookie('num_items', 2 * num_items, { path: '/' });
		// Put the width in a cookie to to speed up
		$.cookie('portfolio_width', null);
		$.cookie('portfolio_width', new_width, { path: '/' });
		
		// Incase this is our first visit, now change the 
		// value of the cookie to false so we don't keep refreshing
		if ($.cookie('first_visit') != 'false') {
			$.cookie('first_visit', null);
			$.cookie('first_visit', 'false', { path: '/' });	
		}
		
		var pitems = $('#portfolio .item').size();
		var citems = Number($.cookie('num_items'));
		
		if (($.cookie('first_visit') == 'true' && citems != pitems) || resized) {
			window.location = window.location;
		}
	}
	else
	{
		// Just change the width according to the portfolio_width cookie
		$('#portfolio').width(Number($.cookie('portfolio_width')));
	}
}

function redirectHash()
{
	var total_url = String(window.location);
	var uri = total_url.substr(total_url.indexOf('.php/') + 5);
	
	if ( ! window.location.hash) 
	{
		nonhash_url = total_url;
		ci_uri = uri;
	}
	else 
	{
		var nonhash_url = total_url.substring(total_url.lastIndexOf('#'), -1);
		var hash_value = String(window.location.hash).substr(1);
		
		uri = uri.substring(uri.lastIndexOf('#'), -1);
		var last_part_uri = Number(uri.substring(uri.lastIndexOf('/')+1));
		if (last_part_uri) {
			uri = uri.substring(uri.lastIndexOf('/'), -1);
		};
		// console.log(last_part_uri);
		
		var ci_uri = uri + '/' + hash_value;
		window.location = 'index.php/' + ci_uri;
	}
}

$(document).ready(function () {	
	// In case there is a hash in the url on load
	// redirect to the normal page
	redirectHash();
	
	// When the browser is refreshed change the portfolio width
	if (! $.browser.msie) {
		$(window).resize(function(){
			changePortfolioWidth(true);
		});
	}
	
	// Change the portfolio width for the first visit
	changePortfolioWidth();
	
	// Catch ajax links, but not for IE
	// because IE sucks!
	if( ! $.browser.msie){
		var pattern = /item/i;
	
		if ( ! pattern.test(String(window.location))) 
		{
			$('a.ajax').live('click', function(){
				// Get the url of the link
				var href = $(this).attr('href');
				// Create the URI that needs to be requested through the ajax controller
				var ruri = href.substr(href.indexOf('.php/') + 5);
				// Grab the offset from the link
				var offset = Number(href.substring(href.lastIndexOf('/') + 1));
				// Hash it
				window.location.hash = offset;

				// Hide the porfolio, load the new data and fade in
				$('#portfolio').hide();
				if ($.cookie('tags')) var ajax_req_url = 'index.php/ajax/overview/cat/' + offset;
				else var ajax_req_url = 'index.php/ajax/' + ruri;
				$('#portfolio').load(ajax_req_url, '', function(){
					$('#portfolio').fadeIn('slow');
				});

				// Current url
				var url = String(window.location);
				var current_offset = Number(url.substring(url.lastIndexOf('#') + 1));

				// Fix next/prev links
				var old_href = $('nav#main a.ajax:first').attr('href');
				var non_dynamic_part_href = old_href.substring(old_href.lastIndexOf('/') + 1, -1);

				var prev_href = non_dynamic_part_href + (current_offset - Number($.cookie('num_items')));
				var next_href = non_dynamic_part_href + (current_offset + Number($.cookie('num_items')));

				$('nav#main a.ajax').filter(':first').attr('href', prev_href);
				$('nav#main a.ajax').filter(':last').attr('href', next_href);

				// Disable links
				return false;
			});
		}
		
		// Multiple tags
		var tags = Array();
		// First fill the tags array with the data from the cookie
		if ($.cookie('tags')) if (unserialize($.cookie('tags'))) tags = unserialize($.cookie('tags'));
		
		function tagem(tag)
		{
			if(tag == false)
			{
				tags = Array;
				$.cookie('tags', null);
			}
			else
			{
				var tag_index = tags.indexOf(tag);
				if (tag_index != -1) 
				{
					tags.splice(tag_index, 1);
				}
				else 
				{
					tags.push(tag);
					if(window.location.hash) window.location.hash = '';
				}

				// Serialize it so we can cookie it up
				var stags = serialize(tags);
				$.cookie('tags', null);
				$.cookie('tags', stags, { path: '/' });
			}
			
			return true;
		}
		
		$('#tags a').live('click', function(){
			// Grab the text
			var link = $(this)
			var tag = link.text();
			
			// Put that in the array if it is not in there yet
			if(tagem(tag)) {
				link.toggleClass('selected');
			
				var load_url = 'index.php/ajax/overview/cat';
				// Are there no tags left? Go to index
				if(tags.length == 0) load_url = 'index.php/ajax/overview/index';
			
				// Hide the porfolio, load the new data and fade in
				$('#portfolio').hide();
				$('#portfolio').load(load_url, function(){
					$('#portfolio').fadeIn('slow');
				});
			}
			// Disable links
			return false;
		});
		
		// Catch the client form
		$('#client-form select').change(function(){
			tagem(false);
			// if(tagem('client-' + $('#client-form select option:selected').text())) {
				$(this).closest("form").submit();
			// }
			// return false;
		});
	}

})