$(window).load(function(){ 

	// ###############################################
	// Global vars
	// ie bug!! --> Mai usare variabili con lo stesso nome della classe o id css (in un oggetto jquery)
	// per esempio: logo = $('#logo') // dá errore in ie8!!! 

	var pf_menu = $('#pf_menu_box'),
		pf_menu_button = $('a#pfmenu_icon'),
	 	pf_items_container = $('#pf_menu_box #pf_menu_items'),
		pf_div_item = $('#pf_menu_box #pf_menu_items div.item'),
		pf_img =  $('#pf_menu_box #pf_menu_items img.item'),
		pf_img_colored =  $('#pf_menu_box #pf_menu_items img.colored'),
		pf_open = false,
		pf_item_length = pf_img.length, //numero di items nel portfolio
		
		// screen and roundabout
		pf_screen = $('#pf_screen_box'),
		screen_open = false,
		active_screen,
		item_number,
		ra_holder = $('#pf_screen_box #roundabout-holder'),
		left_cont = $('#left_container'),
		modal_background = $('#modal_bg'),
		
		basic_pf_img_width = 180,
		pf_img_ratio = 1.54867,
		basic_pf_item_height = Math.round(basic_pf_img_width * pf_img_ratio),
		sez_aurea = 1.6180339887,
		pf_item_height = basic_pf_item_height,
		scroller_height = pf_item_length * pf_item_height,
		
		screen_color = '#3B3A36',
		page_margins = 30,
		current_page,
	
		prev_next_buttons = $('#pf_prev, #pf_next'),
		prev_button = $('#pf_prev'),
		next_button = $('#pf_next'),
		pf_arrow_button = $('#pf_menu_box_button #pf_arrow'),
		
		tabs_content = $('#tabs .content'),
		footer_div = $('#footer'),
		header_menu = $('#header #menu'),
		header_next = $('#header li#next_icon'),
		pf_links = [],
		ref_number = $('#ref_n'),
		columns,
		scroller_page_height,
		scroller_total_pages,
		scroller_last_page,
		items_per_page,
		scroller_last_page_height,
		current_top_position,
		end_position,
		ajaxRequests = [];
		

		
	// ###############################################
	// Window size and resize handlers for proportions
	
	$(window).resize(function() {
		location.reload();
	});
	

	// ###############################################
	// Scroll functions
	function scroller_variables() 
	{
		columns = pf_menu.data('pf_columns');
		// altezza totale dello scroller in base al numero di colonne e all'altezza degli item
		scroller_height = Math.ceil(pf_item_length / columns) * pf_item_height;
		scroller_page_height = items_per_page * pf_item_height;
		scroller_total_pages = Math.ceil(scroller_height/scroller_page_height);
		scroller_last_page = scroller_total_pages - 1;
		scroller_last_page_height = scroller_height - (scroller_last_page * scroller_page_height);		
		// current position of the first item visible (the position is always negative: less than 0)
		current_top_position = parseInt(pf_items_container.css('top'));
		end_position = (scroller_height - (scroller_height*2)) + scroller_page_height;
	}

	function distance_to_nextpage() 
	{
		return Math.abs(current_top_position + ((current_page + 1) * scroller_page_height));
	}
	function distance_to_prevpage() 
	{
		return Math.abs(current_top_position + ((current_page - 1) * scroller_page_height));
	}

	function pf_scroll(position) 
	{
		scroller_variables();
		if (!(pf_items_container.is(":animated"))) 
		{
			if (position == 'start') 
			{
				pf_items_container.css({top: 0});
				current_page = 0;
				show_hide_arrows();
			} else if (position == 'end') 
			{
				pf_items_container.css({top: end_position});
				current_page = scroller_last_page;
				show_hide_arrows();
			} else if (position == 'next') 
			{
				if (current_page != scroller_last_page && current_page != scroller_last_page - 1)
				{
					pf_items_container.animate({top: '-=' +  distance_to_nextpage()  + 'px'},200, 'easeOutExpo', function() {show_hide_arrows();});
					current_page++;
				} 
				else if (current_page == scroller_last_page - 1) 
				{
					pf_items_container.animate({top: end_position + 'px'},200, 'easeOutExpo', function() {show_hide_arrows();});
					current_page = scroller_last_page;
				}
			} else if (position == 'prev') 
			{
				if (current_page != 0 && current_page != 1 && current_page != scroller_last_page)
				{
					pf_items_container.animate({top: '+=' +  distance_to_prevpage()  + 'px'},200, 'easeOutExpo', function() {show_hide_arrows();});
					current_page--;
				}
				else if (current_page == 1 || current_page == 0)
				{
					pf_items_container.animate({top: '0px'},200, 'easeOutExpo', function() {show_hide_arrows()});
					current_page = 0;
				}
				else if (current_page == scroller_last_page) 
				{
					pf_items_container.animate({top: '+=' + scroller_last_page_height + 'px'},200, 'easeOutExpo', function() {show_hide_arrows();});
					current_page--;	
				}
			}
		}
	}
	

	// ###############################################
	// Mouse wheel scroll
	pf_menu.mousewheel(function(event,delta) 
	{ 	
		event.stopPropagation();
        event.preventDefault();
		scroller_variables();
		var dir = delta > 0 ? 'Up' : 'Down', vel = Math.round((Math.abs(delta)) * 12);
		
		if (dir == 'Down' && current_top_position > end_position)
		{
			pf_items_container.animate({top: '-=' + vel +'px'}, 0);
			if (current_top_position < end_position)
			{
				pf_items_container.css({top: end_position + 'px'});
			}
		}
		
		if (dir == 'Up' && current_top_position < 0) 
		{
			pf_items_container.animate({top: '+=' + vel +'px'}, 0);
			if (current_top_position > 0)
			{
				pf_items_container.css({top: '0px'});
			} 
		}
		
		if (current_top_position < end_position)
			{
				pf_items_container.css({top: end_position + 'px'});
			}
		if (current_top_position > 0)
			{
				pf_items_container.css({top: '0px'});
			} 
		
		current_page = Math.abs(Math.floor(current_top_position / scroller_page_height)) - 1;
		if (current_page < 0)
			{
				current_page = 0;
			}
		else if (current_top_position == end_position)
			{
				current_page = scroller_last_page;
			}
		show_hide_arrows();
	});
	

	// ###############################################
	// Portfolio buttons & arrows
	function show_buttons() 
	{
		//pf_close_button.css({right: '-20px'}).show();
		//pf_close_button.animate({right: '5px'}, 200, 'easeOutExpo');
		show_hide_arrows();
		prev_next_buttons.css({right: '-20px'}).animate({right: '5px'}, 200, 'easeOutExpo');
	}
	
	function show_hide_arrows() 
	{
		current_top_position = parseInt(pf_items_container.css('top'));
		scroller_variables();
		//$('#output').show().text('page= ' + current_page + ' - top_position= ' + current_top_position);
		if (current_top_position == 0) 
		{
			prev_button.hide();
		}
		else
		{
			prev_button.show();	
		}
		if (current_page == scroller_last_page) 
		{
			next_button.hide();
		}
		 else 
		{
			next_button.show();
		}
	}
	
	function hide_buttons() 
	{
		//pf_close_button.fadeOut(200).css({right: '-20px'});
		prev_next_buttons.fadeOut(200).css({right: '-20px'});
	}

	// ###############################################
	// Portfolio Menu switch/open/close/anim
	function switch_portfolio() {
			if (!pf_open) {
				open_portfolio();
			} else {
				close_portfolio();
			}
	}
		
	function close_portfolio() {
		pf_open = false;
		modal_background.hide();
		pf_menu.animate({width: '0px'},400, 'easeOutExpo', function() {pf_menu.hide();});
		pf_menu_button.animate({right:  page_margins + 'px'},400, 'easeOutExpo').removeClass('closepf');
		footer_div.hide();
		hide_buttons();
		pf_arrow_button.show();
		pf_img.removeClass("on");
		left_cont.css({width: '100%'});
	}
	
	function open_portfolio() {
		if (screen_open) {modal_background.show();}
		pf_open = true;
		pf_menu.show().animate({width: pf_width + page_margins + 15 + 'px'},400, 'easeOutExpo');
		pf_menu_button.animate({right: pf_width + page_margins + 15 + 'px'},400, 'easeOutExpo').addClass('closepf');
		footer_div.fadeIn('fast');
		pf_items_container.css({width: pf_width + page_margins + 'px'});
		show_buttons();
		pf_arrow_button.hide();
		left_cont.css({width: window_width - pf_menu.width() + 'px'});
	}



	// ###############################################
	// General check_sizes function
	function check_sizes() 
	{
		window_height = $(window).height();
		document_height = $(document).height();
		window_width = $(window).width();
		pf_item_proportions();
		pf_scroll('start');
	}
	
	function pf_item_proportions() 
	{
		// primo calcolo della larghezza del menu item in base a sezione aurea di window
		pf_item_width = Math.round(window_width - (page_margins*3) - (window_width  / sez_aurea));
		set_items();
		set_items_columns();
		// dimensiona le immagini e il contenitore delle immagini del portfolio	
		pf_img.css({width: pf_item_width + 'px'});
		pf_img_colored.css({width: pf_item_width + 'px'});
		pf_div_item.css({width: pf_item_width + 'px', height: pf_img.height() + 'px'});
		
		//left_cont.css({width: window_width - (pf_item_width*pf_menu.data('pf_columns')+page_margins) + 'px'});
		footer_div.css({width: pf_item_width * pf_menu.data('pf_columns') + page_margins + 15 + 'px'});
		$('#pf_menu_items .tooltip').css({width: pf_item_width + 'px'});
	}	

	function set_items() 
	{
		pf_item_height = Math.round(pf_item_width / pf_img_ratio);
		items_per_page = Math.floor(window_height / pf_item_height);		
		// spazio che avanza nella pagina con gli item ad altezza predefinita
		space_available = window_height - (items_per_page * pf_item_height);
		// calcola il numero ottimale e l'altezza esatta degli item, in base all'altezza della pagina (window_height)
		if (space_available > (pf_item_height/2)) 
		{
			items_per_page = items_per_page+1;
			pf_item_height = Math.ceil(window_height / items_per_page);
		} 
		else 
		{
			pf_item_height = Math.ceil(window_height / items_per_page);
		}
		// larghezza item in base all'altezza stabilita e al valore pf_img_ratio
		pf_item_width = Math.ceil(pf_item_height * pf_img_ratio);
	}
	
	function set_items_columns() 
	{
		// se la larghezza di item é troppo grande valuta se non fare 2 o 3 colonne
		if ((pf_item_width/2) >= basic_pf_img_width) 
		{
			pf_width = pf_item_width;
			pf_item_width = pf_item_width/2;
			pf_menu.data('pf_columns', 2);
			set_items();
		}
		else if (pf_item_width /2 >= basic_pf_img_width) 
		{
			pf_width = pf_item_width;
			pf_item_width = pf_item_width/3;
			pf_menu.data('pf_columns', 3);
			set_items();
		}
		else 
		{
			pf_width = pf_item_width;
			pf_menu.data('pf_columns', 1);
		}
	}


	// ###############################################
	// PF Screen

	function close_screen() 
	{
		screen_open = false;
		header_next.hide();
		ref_number.animate({left: -100, opacity: 0}, 400, 'easeOutExpo', function() {$(this).hide()});
		header_menu.show().animate({opacity : 1}, 1000, 'easeOutExpo');
		ra_holder.hide().empty();
		pf_screen.hide();
		active_screen = null;
		item_number = null;
		open_portfolio();
		
	}

	function open_screen(item_number, animation) 
	{
		screen_open = true;
		if (pf_open) {close_portfolio();}
		if (animation) {
			header_menu.animate({opacity : 0}, 1000, 'easeOutExpo', function() {
				$(this).hide();
				header_next.fadeIn(400);
				ref_number.show().animate({left: 0, opacity: 1}, 400, 'easeOutExpo');
			});
			pf_screen.show();
		}
		ajax_load_php('pf_items.php', item_number);
		active_screen = item_number;
	}


	// ###############################################
	// Ajax per portfolio
	function ajax_load_php(filename, ref) 
	{	
		// abort all the ajax requests in the queue 
		// (in case the user clicks many times very quicly!!)
		for(var i = 0; i < ajaxRequests.length; i++) {
    		ajaxRequests[i].abort();
		}
		
		// set the ajax request and push it into the ajaRequest array (to have a queue)
		ajaxRequests.push(
			$.ajax({
				url: filename,
				data: 'r=' + ref,
				cache: true,
				async: true,
				type: 'GET',
				dataType: 'html',
				timeout: 10000,
				context: pf_screen,
				beforeSend:
					function () {},
				success:
					function(html)
					{
						ra_holder.empty().append(html).show();
						start_presentation();
						ra_holder.find('.item').show().find('img').hide().each(function(i) {
								$(this).load(function(){$(this).fadeIn(200)});
							});
						if ($.browser.msie) 
						{
							$('#monolith span').css('marginLeft', parseInt($('.roundabout-in-focus').css('left')) + 20 + 'px');
						}
						else
						{ 
							$('#monolith span').css('marginLeft', $('.roundabout-in-focus').css('left'));
						}
					}
			}) // end $.ajax
		); // end ajaxRequests.push	
	}


	// ###############################################
	// Portfolio presentation screen
	function start_presentation() {
		
		//ra_holder.find('.outer_img').append('<div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div>'); 	
		
		// manage ie delirium for shadow
		if ($.browser.msie) 
		{
			ra_holder.addClass('fancybox-ie');
			ra_holder.find('.item').addClass('ie_padding').css({background: 'none'}).find('.outer_img').css({position: 'relative', padding: 0});
		}
		
		// focus/blur handler
		// #there is an unbind bug in msie (even 9): fancybox will be then disabled in msie
		ra_holder.find('.item').hide().each(function(i)
		{
			// get the rel attribute containing image ratio and calculates the size of the item
			var img_ratio = $(this).find('img').attr('rel'),
			screen_item_width = Math.floor(ra_holder.width() / sez_aurea), 
			screen_item_height = Math.round(screen_item_width / img_ratio);
			if (screen_item_height > ($(window).height()*0.625)) 
			{
				screen_item_height = Math.floor($(window).height()*0.625);
				screen_item_width = Math.round(screen_item_height * img_ratio);
			}
			// apply sizes to the item
			$(this).css({width: screen_item_width + 'px', height: screen_item_height + 'px'});
			
			// binds fancybox zoom to the item on focus
			$(this)
			.bind('focus', {index:i}, function(e)
			{
				//var item_number = e.data.index;
				//$('#output').show().empty().text('focus: ' + item_number);
				// Only for NON-msie:  add/remove Fancybox and shadow on focus/blur
				if (!$.browser.msie) 
				{
						// Fancybox
						$(this).find('img').bind('click.fb',  function(event) 
						{
							$.fancybox(
							{
								'orig'			: 	$(event.target),
								'hideOnContentClick': true,
								'padding'		: 	0,
								'href'			: 	$(event.target).attr('src'),
								'showCloseButton':	true,
								'transitionIn'	:	'elastic',
								'transitionOut' :	'elastic',
								'speedIn'		:	100, 
								'speedOut'		:	100,
								'overlayOpacity': 	1,
								'type'			:	'image',
								'overlayColor'	: 	screen_color
							});
							//e.preventDefault();
						});
				} // end NON-msie browsers
			})
			.bind('blur', {index:i}, function(e) {
					//var item_number = e.data.index;
					//$('.output').empty().text('blur: ' + item_number);
					// only NON-msie: unbind click for Fancybox
					//$(this).find('.watermark_logo').hide();

					if (!$.browser.msie) 
					{
						$(this).find('img').unbind('.fb');
					}
			});
		});

		
		// Roundabout 
		ra_holder.roundabout(
		{
			childSelector: 'div.item',
			easing: 'easeOutExpo',
			duration: 400,
			maxOpacity: 1,
			minOpacity: 0.1,
			tilt: -0.05,
			btnNext: '#next',
			btnPrev: '#previous',
			//debug: true,
			shape: 'square',
			reflect: true
		})
		.bind('mousewheel', function(e, delta) 
		{
			e.preventDefault();
			delta = delta * 1.8;
			ra_holder.roundabout_adjustBearing(delta);
		});
		
	}

	
	// ###############################################
	// Hash Navigation
	$(window).bind('hashchange', function () {
		var hash = window.location.hash || "#!home";
		hash = hash.replace("#!","");
		
		tabs_content.contents().hide();
		
		if (hash == "home" || hash == "clients" || hash == "services" || hash == "contact")
		{
			modal_background.hide();
			header_menu.stop();
			header_next.hide();
			if (screen_open){close_screen();}
			if (!pf_open) {open_portfolio();}
			tabs_content.not('#' + hash).hide();
			tabs_content.filter('#' + hash).show().contents().fadeIn(400);
			$('a').removeClass('selected');
			$('#header a').each(function() {
				if ($(this).attr('href') == "#!" + hash)
				{
					$(this).addClass('selected');
				}
			});
			// BUG with ! ---> $('a[hash=#!' + hash + ']').addClass('selected');
		}
		else if (hash.indexOf("portfolio") == 0)
		{
			tabs_content.hide();
			item_number = hash.substr(9);
			//menu_item_ON(item_number);
			$('a').removeClass('selected').removeClass('on');
			$('#page a').each(function() {
				if ($(this).attr('href') == "#!portfolio")
				{
					$(this).addClass('selected').addClass('on');
				}
			});
			// BUG with ! ---> $('a[hash=#!portfolio]').addClass('selected').addClass('on');
			set_pf_next_link();
			footer_div.hide();
			if (screen_open) {
				open_screen(item_number, false);
			} else {
				open_screen(item_number, true);
			}
		}
	});
	
	
	
	// ###############################################
	// Create an array with all the links to the portfolio items
	pf_div_item.each(function() 
	{	
		pf_links.push($(this).find('a').attr('href'));
	});	

	// Change the link to the NEXT button
	function set_pf_next_link() 
	{
		// $('#output').show().text('Hash=' + window.location.hash + ' - Links=' + pf_links);
		for (i=0;i<pf_links.length;i++)
		{
			if (window.location.hash == pf_links[i])
			{
				var next_link;
				if (pf_links.length == i+1) {
					next_link = pf_links[0];
				} else {
					next_link = pf_links[i+1];
				}
				header_next.find('a').attr('href', next_link);
				$('#ref_n').show().html('<span class="yellow">&hearts;</span> ' + (i+1));
			}
			else if (window.location.hash == "#!portfolio")
			{
				header_next.find('a').attr('href', pf_links[1]);
				ref_number.html('<span class="yellow">&hearts;</span> ' + 1);
			}
		}
	}

	
	// ###############################################
	// START!
	$('#page').fadeIn('fast'); // Fade in the whole page
	modal_background.css({opacity: 0.75});
	check_sizes();
	prev_next_buttons.hide();
	$("#pf_menu_items .item img[title]").tooltip({
		effect: 'fade',
		delay: 0,
		events: {
		  def:     "mouseenter,mouseleave",
		  tooltip: "mouseenter,mouseleave"
		},
		opacity: 1,
		fadeInSpeed: 100,
		fadeOutSpeed: 100,
		predelay: 0,
		position: 'center left'
		});
	prev_button.bind('click', function() {pf_scroll('prev')});
	next_button.bind('click', function() {pf_scroll('next')});
	pf_menu_button.bind('click', function() {switch_portfolio(); return false;});
	modal_background.bind('click', function() {close_portfolio()});
	$('#warning_browser #warning_close').click(function() {$(this).parent().hide();});
	
	header_menu.lavaLamp({ fx: "easeOutExpo", speed: 400});
	ref_number.hide().css({left: -100, opacity : 0});
	$(window).trigger("hashchange");

	
	$('a.dfakjbwi').each(function(){
			e = this.rel.replace('/','@');
			this.href = 'mailto:' + e;
			$(this).text(e);
		});
	
}); // end window load





