/*==========  GLOBAL VARS ==============*/

 var min_image_height;
 var interval_id;
 var resizeTO;
 var background_image = null;
 var gallery_link = null;
 var gallery_id = null;
 var is_gallery = false;
 var bg_image = null;
 var path_background_image = 'media/img/fondi/';
 var img_gap = 100;
 // Only for index
 var bg_fixed = false;
 
/*
 // console.log($(window).height());
 // console.log($(window).outerHeight(true));
 // console.log($(window).innerHeight());
*/
 
 /*==========  START document ready ==============*/
 
 $(document).ready(function()
 {
	var deviceAgent = navigator.userAgent.toLowerCase();
	var agentID = deviceAgent.match(/(ipad)/);
	if (agentID)
	{
		// IPAD
		if($('#balls').length)
		{
		  // home page
		  $('#balls').empty();
		  $('.index_bg').css("background-image", "url('media/img/fondi/fondi_home-ipad.jpg')");
		}
		  
		$('.remove_ipad').remove();
		$('#preload').css('marginLeft', '-90px');
		$('.menu_footer').css('left', '140px').css('width', '620px').css('padding', '0px');
	}
	else
	{
		if($('.index_bg').length)
		{
			// home page
			var flashvars = {};
			var params = {wmode:"transparent"};
			var attributes = {};
		swfobject.embedSWF("media/swf/balls.swf", "balls", "580", "480", "8.0.0", "expressInstall.swf", flashvars, params, attributes);	
		}
	}
	 
 	$('.news').css('opacity',0);
				
	min_image_height = $('.header').height()+$('.content').height()+ $('.footer').height() +50;

	/*==========  Resize ==============*/
	
	$(window).resize(function()
	{
		//// console.log("w: "+min_window_height);
		//// console.log("c: "+min_image_height);
		if( (background_image != null) || (is_gallery) )
		{
			if(resizeTO) clearTimeout(resizeTO);
			resizeTO = setTimeout(function()
			{
				$(this).trigger('resizeEnd');
			}, 500);
		}
	});
	
	$(window).bind('resizeEnd', function()
	{
		var min_window_height = $(window).height();
    	//do something, window hasn't changed size in 500ms
		if( min_window_height > min_image_height )
		{
			if( background_image != null)
			{
				resizeBackGroundImage();
			}
			else if(is_gallery)
			{
				resizeSlideShow();
			}
		}
	});
	
	/*==========  Gallery ==============*/

    if(is_gallery)
	{
		createGallery(gallery_id);
		if(gallery_link != null)
		{
			var len = gallery_link.length;
			var balls = "";
			for (var i = 0; i<len; i++)
			{
				balls += '<div class="small_ball small_ball_'+(i+1)+'"><a href="javascript:void(0);" rel="'+gallery_link[i].id+'">Gallery <br /><br />'+gallery_link[i].name+'</a></div>';
			}
			$('.content').append(balls);
			$('.small_ball').css('opacity',0);
			$(".small_ball a").click(function (event)
			{
				event.preventDefault();
				var gal_id = $(this).attr("rel");
				createGallery(gal_id);
			});
		}
	}
	else
	{
		/*if($('.news').length)
		{
			// FadeIn balls
			$('.news').animate({opacity: 1}, 1000);	
		}*/
		
		//$('.container').removeClass('container_bg');
		
		if(bg_image == null)
		{
			if(!bg_fixed)
			{
				// Not index.php
				$('.container').removeClass('container_bg');
			}
			else
			{
				// index.php
				$('.news').animate({opacity: 1}, 1000);		
			}
		}
		else
		{
			$('.container').css("background-image", "none");  
		}
	}

	/*==========  Menu ==============*/
	
	var link_id = location.hash;
	if(link_id != '')
	{
		var main_id = link_id.charAt(1);
		var sub_id = link_id.charAt(3);
		$('.menu_header .menu a[rel="'+main_id+'"]').addClass('current');
		if(sub_id != '')
		{
			showSubMenu(main_id, sub_id);
		}
		else
		{
			showSubMenu(main_id);
		}
	}
	
	$(".menu_header .menu a").click(function (event)
	{
		var main_id = $(this).attr('rel');
		
		if((main_id != '4') && (main_id != '5'))
		{
			event.preventDefault();
		
			$(".menu_header .menu a").removeClass('current');
			$(this).addClass('current');
		
			showSubMenu(main_id);
		}
	});
	
	// Sezione archivio_news
	if($('.news_link').length)
	{
		$(".news_link").click(function (event)
		{
			event.preventDefault();
			
			var id = $(this).attr('rel');
			modalNew(id);
		});
	}
	
	// Sezione press
	if($('.press_link').length)
	{
		$(".press_link").click(function (event)
		{
			event.preventDefault();
			
			var id = $(this).attr('rel');
			var url = 'preview.php?d='+id;
			openCenteredWindow(url)
		});
	}
		
	/*==========  Background Image ==============*/
	
	if(background_image != null)
	{
		loadBackGroundImage(background_image);
	}
	
	/*========== Form mail ==============*/
	
	if($('#form_mail').length)
	{		
		$('#form_mail').submit(function(event)
		{
			event.preventDefault();
			validateForm(this);
		});
	}
	
	// Wedding news
	if($('#paging_wedding').length)
	{
		$('#paging_wedding a').live('click', function (event)
		{
			event.preventDefault();
			
			var pageNum = $(this).attr('rel');
			var data = { page:pageNum };
			
			$.post('server/newsPaginationWedding.php', data, function(data)
			{	
				$('.news_wedding').empty().html(data.html_news);
				$('#paging_wedding').empty().html(data.html_pagination);
				
			}, 'json');
		});
	}
	
	// Wedding news
	if($('#paging_aziende').length)
	{
		$('#paging_aziende a').live('click', function (event)
		{
			event.preventDefault();
			
			var pageNum = $(this).attr('rel');
			var data = { page:pageNum };
			
			$.post('server/newsPaginationAziende.php', data, function(data)
			{	
				$('.news_aziende').empty().html(data.html_news);
				$('#paging_aziende').empty().html(data.html_pagination);
				
			}, 'json');
		});
	}
	
	// Press area
	if($('#pagination_press').length)
	{
		$('#pagination_press a').live('click', function (event)
		{
			event.preventDefault();
			
			var pageNum = $(this).attr('rel');
			var data = { page:pageNum };
			
			$.post('server/newsPaginationPress.php', data, function(data)
			{	
				$('.press_list').empty().html(data.html_news);
				$('#pagination_press').empty().html(data.html_pagination);
				
			}, 'json');
		});
	}
	
	// Locations
	if($('#locations').length)
	{
		// Append shadow image to each LI
		$(".nav-shadow li").append('<img class="shadow" src="media/img/icons-shadow.png" width="81" height="27" alt="" />');
	
		// Animate buttons, shrink and fade shadow
		$(".nav-shadow li").hover(function() {
			var e = this;
			$(e).find("a").stop().animate({ marginTop: "-14px"}, 250, function() {
				$(e).find("a").animate({ marginTop: "-10px" }, 250);
			});
			//$(e).find("span").stop().animate({opacity: 1, marginBottom: "5"}, 250);
			$(e).find("span").stop().animate({marginBottom: "10"}, 250);
			$(e).find("img.shadow").stop().animate({ width: "80%", height: "20px", marginLeft: "8px", opacity: 0.25 }, 250);
		},function(){
			var e = this;
			$(e).find("a").stop().animate({ marginTop: "4px" }, 250, function() {
				$(e).find("a").animate({ marginTop: "0px" }, 250);
			});
			//$(e).find("span").stop().animate({opacity: 1, marginBottom: "0"}, 250);
			$(e).find("span").stop().animate({marginBottom: "5"}, 250);
			$(e).find("img.shadow").stop().animate({ width: "100%", height: "27px", marginLeft: "0", opacity: 1 }, 250);
		});
	}
	
 });

 /*==========  end document ready ==============*/


function modalNew(id)
{
	$.facebox({ ajax: 'scheda_new.php?id='+id });
}

function showSubMenu(link_id, sub_id)
{
	//alert(link_id+' => '+sub_id);
	var sub_menu = $('.sub_menu');
	sub_menu.empty();
	sub_menu.css('opacity',0);
	switch(parseInt(link_id))
	{
		case 1:
			// Wedding
			if(sub_id == undefined)
			{
				window.location='wedding.php#1#1';
			}
			var content = '<a href="wedding.php#1#1" rel="1">L\'evento</a> \
			<a href="richiedi_informazioni.php#1#2" rel="2">Richedi Informazioni</a>';
		break;
			
		case 2:
			// Aziende
			if(sub_id == undefined)
			{
				window.location='eventi_aziendali.php#2#1';
			}
			var content = '<a href="eventi_aziendali.php#2#1" rel="1">Eventi Aziendali</a> \
			<a href="big_events.php#2#2" rel="2">Big Events</a> \
			<a href="team_building.php#2#3" rel="3">Team Building</a> \
			<a href="richiedi_informazioni_aziende.php#2#4" rel="4">Richedi Informazioni</a>';
		break;
		
		case 3:
			// Il gruppo visconti
			if(sub_id == undefined)
			{
				window.location='filosofia_visconti.php#3#1';
			}
			var content = '<a href="filosofia_visconti.php#3#1" rel="1">Filosofia Visconti</a> \
			<a href="archivio_news.php#3#2" rel="2">Archivio News</a> \
			<a href="rassegna_stampa.php#3#3" rel="3">Rassegna Stampa</a> \
			<a href="javascript:void(0);" onclick="openWindow(\'http://www.afterpixel.com/apletter/apletter.php\');">Iscriviti alla Newsletter</a> \
			<a href="contatti.php#3#4" rel="4">Contatti</a>';
		break;
		
		case 4:
			// Locations
			if(sub_id == "1")
			{
				//Inside Location page
				if($('#link_site').length)
				{
					var _link = $('#link_site').html();
					var content = _link+'<a href="locations.php#4" rel="4">Torna alle locations</a>';
				}
			}
		break;
		
		case 5:
			// Green Food
		break;		
	}
	sub_menu.html(content);
	if(sub_id != undefined)
	{
		$('.sub_menu a[rel="'+sub_id+'"]').addClass('current');
	}
	sub_menu.animate({opacity: 1}, 1000);
}

function loadBackGroundImage(file)
{
	$('#background_image').empty().css('opacity',0);
	$('#progress').show();
	$('#preload').show();
	
	if(bg_image == null)
	{
		$('.container').addClass('container_bg');
	}
	else
	{
		$('.container').css("background-image", "url('"+path_background_image+bg_image+"')");
		$('.container').css("background-position", "center,130px");
		$('.container').css("background-repeat", "no-repeat"); 
	}
	
	/*if($(".small_ball_1").length)
	{
		$('.small_ball_1').css('opacity',0);
	}
	if($('.news').length)
	{
		$('.news').css('opacity',0);
	}*/
	if($('#press_content').length)
	{
		$('#press_content').css('opacity',0);
	}
	if($('#news_content').length)
	{
		$('#news_content').css('opacity',0);
	}
	
	var data = { w: $(window).width(), h: $(window).height(), img_name: file, t:'static' };

	$.post('server/getBackGroundImage.php', data, function(data)
	{
		$('#background_image').html(data);
		$('#background_image img').load( function()
		{
			$('#progress').hide();
			$('#preload').hide();
			
			if(bg_image == null)
			{
				$('.container').removeClass('container_bg');
			}
			else
			{
				$('.container').css("background-image", "none");  
			}
					
			$('#background_image').animate({opacity: 1}, 1000, function(){
				if($('#news_content').length)
				{
					$('#news_content').animate({opacity: 1}, 1000);
				}
				if($('.news').length)
				{
					$('.news').animate({opacity: 1}, 1000,function()
					{
						if($(".small_ball_1").length)
						{
							// eccezione contatti.php
							$(".small_ball_1").animate({opacity: 1}, 1000);
						}
					});
				}
				if($('#press_content').length)
				{
					$('#press_content').animate({opacity: 1}, 1000);
				}
				if($('.contact_form').length)
				{
					$('.contact_form').animate({opacity: 1}, 1000);	
				}
				if($('#locations').length)
				{
					$('#locations').animate({opacity: 1}, 1000);
				}
			});
		});
	});
}

function createGallery(gallery_id)
{
	if(interval_id != undefined)
	{
		clearInterval(interval_id);
	}
	$('#slideshow').empty().css('opacity',0);
	$('#progress').show();
	$('#preload').show();
	
	//$('.container').addClass('container_bg');
	if(bg_image == null)
	{
		$('.container').addClass('container_bg');
	}
	else
	{
		$('.container').css("background-image", "url('"+path_background_image+bg_image+"')");  
	}
			
	var gal_data = { w: $(window).width(), h: $(window).height(), gal_id: gallery_id, t:'big', constrain:1  };
	
	$.post('server/getImages.php', gal_data, function(data)
	{
		//// console.log(data);
		
		$('#slideshow').html(data);
		$('#slideshow img.active').load( function()
		{
			//$('.news').css('opacity',0);
			//$('.small_ball').css('opacity',0);
			// console.log($(this).height());
			// console.log($(this).width());
			// console.log($(window).height());
			
			//var movetopY = Math.round(($(this).height() - $(window).height()) / 2);
			//// console.log(movetopY);
			
			// $("#slideshow").offset({ top: movetopY });
			// $("#slideshow").css({ 'top': -movetopY });
			
			$('#progress').hide();
			$('#preload').hide();
			
			if(bg_image == null)
			{
				$('.container').removeClass('container_bg');
			}
			else
			{
				$('.container').css("background-image", "none");  
			}
			//$('.container').removeClass('container_bg');
			
			// fadeIn di #slideshow
			$('#slideshow').animate({opacity: 1}, 1000, function(){
				// FadeIn balls
				$('.news').fadeTo(1000, 1.0, function()
				//$('.news').animate({opacity: 1}, 1000, function()
				{
					if(gallery_link != null)
					{
						var len = gallery_link.length;
						if(len > 0)
						{
							for (var i = 1; i<=len; i++)
							{
								//$(".small_ball_"+i).animate({opacity: 1}, 1000*i);
								$(".small_ball_"+i).fadeTo(1000*i, 1.0);
								if(i == len)
								{
									// partenza slideshow
									interval_id = setInterval( "slideSwitch()", 5000 );
								}
							}
						}
						else
						{
							// partenza slideshow
							interval_id = setInterval( "slideSwitch()", 5000 );	
						}
					}
					else
					{
						// partenza slideshow
						interval_id = setInterval( "slideSwitch()", 5000 );	
					}
				});
			});
		})
	});
}

function resizeSlideShow()
{
	var t = $('#slideshow img');
	//Resize each image seperately
	$(t).each(function()
	{
		//Define image ratio, toFixed => the number of digits after the decimal point. Default is 0 
		var ratio = ($(this).height()/$(this).width()).toFixed(2);
		var thisSlide = $(this);
		
		//Gather browser size
		var browserwidth = $(window).width()+img_gap;
		var browserheight = $(window).height();
		
		if ((browserheight/browserwidth) > ratio)
		{
			ratio <= 1 ? resizeWidth(thisSlide, browserwidth, ratio) : resizeHeight(thisSlide, browserheight, ratio);
			//If landscapes are set to fit
		} else {
			ratio > 1 ? resizeHeight(thisSlide, browserheight, ratio) : resizeWidth(thisSlide, browserwidth, ratio);
			//If portraits are set to fit
		}	
	});
}

function resizeBackGroundImage()
{
	// console.log('resizeBackGroundImage()');
	
	var img = $('#background_image img');
	var ratio = ($(img).height()/$(img).width()).toFixed(2);
	var thisSlide = $(img);
	
	//Gather browser size
	var browserwidth = $(window).width()+img_gap;
	var browserheight = $(window).height();
	
	if ((browserheight/browserwidth) > ratio)
	{
		ratio <= 1 ? resizeWidth(thisSlide, browserwidth, ratio) : resizeHeight(thisSlide, browserheight, ratio);
		//If landscapes are set to fit
	} else {
		ratio > 1 ? resizeHeight(thisSlide, browserheight, ratio) : resizeWidth(thisSlide, browserwidth, ratio);
		//If portraits are set to fit
	}
}

function resizeWidth(thisSlide, browserwidth, ratio)
{
	thisSlide.width(browserwidth);
	thisSlide.height(browserwidth * ratio);
};

function resizeHeight(thisSlide, browserheight, ratio)
{
	thisSlide.height(browserheight);
	thisSlide.width(browserheight / ratio);
};
	
/*==========  GALLERY JQUERY ==============*/
	
function slideSwitch()
{
	//alert('slideSwitch');
	
	var $active = $('#slideshow img.active');

	if ( $active.length == 0 ) $active = $('#slideshow img:last');

	// use this to pull the images in the order they appear in the markup
	var $next =  $active.next().length ? $active.next() : $('#slideshow img:first');
	
	// uncomment the 3 lines below to pull the images in random order
	/*var $sibs  = $active.siblings();
	var rndNum = Math.floor(Math.random() * $sibs.length );
	var $next  = $( $sibs[ rndNum ] );*/

	$active.addClass('last-active');

	$next.css({opacity: 0})
		.addClass('active')
		.animate({opacity: 1}, 1000, function() {
			$active.removeClass('active last-active');
		});
}

/*==========  Window ==============*/

function openWindow(url)
{
	var w = 400;
	var h = 300;
	window.open(url, "", "width="+w+",height="+h+",left=0,top=0,resizable=no,menubar=yes,toolbar=yes, scrollbars=no,locations=no,status=no");	
}

function openCenteredWindow(url) 
{
	var width  = screen.width-100;
	var height = screen.height-100;
	var left   = (screen.width  - width)/2;
	var top    = (screen.height - height)/2;
	var params = 'width='+width+', height='+height;
	params += ', top='+top+', left='+left;
	params += ', directories=no';
	params += ', location=no';
	params += ', menubar=no';
	params += ', resizable=no';
	params += ', scrollbars=yes';
	params += ', status=no';
	params += ', toolbar=no';
	newwin=window.open(url,'preview', params);
	if (window.focus) {newwin.focus()}
	return false;
}

/*==========  MAIL ==============*/

function validateForm(form)
{
	if($('#cognome').length)
	{
		if($('#cognome').val() == '')
		{
			alert('Inserite il cognome.');
			return false;
		}
	}
	if($('#tel').length)
	{
		if($('#tel').val() == '')
		{
			alert('Inserite il telefono.');
			return false;
		}
	}
	if($('#email').length)
	{
		if($('#email').val() == '')
		{
			alert('Inserite la mail.');
			return false;
		}
		else
		{
			if( !isEmail($('#email').val()) )
			{
				alert('Inserire una mail valida.');
				return false;
			}
		}
	}
		
	sendMailInfo(form);
}

function isEmail(string) 
{
	if (string.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/) != -1)
	{
		return true;	
	}
	else
	{
		return false;
	}
}

function sendMailInfo(form)
{
	if($('#mail_type').val() == "a")
	{
		var url="server/mail_a.php";
	}
	else
	{
		var url="server/mail_w.php";
	}
	
	var data=$(form).serialize();
	
	$.post(url, data, function(data)
	{
		var msg="<div class='contact_form_title'><br><br>"+data+"</div>";
		var el=$('#mail_response').html(msg);
	});
}
