var cache = [],
	img,
	page_content,
	supersize,
	absPath = '/';

//Miglioramento animazioni
function now(){
    return (new Date()).getTime();
}

$.fx.prototype.custom = function( from, to, unit ) {
    this.startTime = now();
    this.start = from;
    this.end = to;
    this.unit = unit || this.unit || "px";
    this.now = this.start;
    this.pos = this.state = 0;

    var self = this;
    function t( gotoEnd ) {
        return self.step(gotoEnd);
    }

    t.elem = this.elem;
	if($.browser.msie){
	    if ( t() && jQuery.timers.push(t) && !jQuery.fx.prototype.timerId ) {
	        //timerId = setInterval(jQuery.fx.tick, 13);
	        jQuery.fx.prototype.timerId = setInterval(jQuery.fx.tick, 70);
	    }
    } else {
	    if ( t() && jQuery.timers.push(t) && !jQuery.fx.prototype.timerId ) {
	        //timerId = setInterval(jQuery.fx.tick, 13);
	        jQuery.fx.prototype.timerId = setInterval(jQuery.fx.tick, 50);
	    }
    }
};

//Preload img
$.preloadImages = function() {
	var args_len = arguments.length;
	for (var i = args_len; i--;) {
		var cacheImage = document.createElement('img');
		cacheImage.src = arguments[i];
		cache.push(cacheImage);
	}
};
	
//Carico css monitor < 1020px
function css1020(){
	$('div#wrapper').height($(window).height());
	if($(window).width() <= 1020){
		if(!$('head link#css1020').length){
			$("head").append("<link>");
			var css = $("head").children(":last");
			css.attr({
				rel:  "stylesheet",
				type: "text/css",
				href: absPath + "css/style1020.css",
				id:   "css1020"
			});
		}
	} else if($('head link#css1020').length > 0) {
		$('head link#css1020').remove();
	}
}

function team(){

	$('.team_info').first().addClass('selected').show();

	$('.team a').click(function(e){
		
		try{
			e.preventDefault();
		}
		catch(e){
			return false;
		}
		
	});
	
	$('.team').click(function(event){
		
		if(!$(this).hasClass('selected')){

		var full_url = $(this).find('a').attr('href');
		full_url = full_url.split('#');
		full_url = full_url[full_url.length - 1];
		//console.info(full_url);
		
		
		var mail = $('#'+full_url).find('div.mail').text();
		
		$('div.team_single_mail a').html(mail).attr('href', 'mailto:'+mail);
		$('.team_info.selected').hide(300);
		$('.team_info').removeClass('selected');
		$('#'+full_url).slideDown(300).addClass('selected');
		
		$(this).addClass('selected').siblings('.team').removeClass('selected');
		}
	});
	
	if(($.browser.msie) && ($.browser.version <= 7)){
		$('#team-list').css('overflow', 'auto');
	} else {
		$.getScript(absPath + 'js/jpane.js',function(){
			$('#team-list').jScrollPane(
				{
					showArrows: true,
					verticalArrowPositions: 'split',
					horizontalArrowPositions: 'split'
				}
			).hide().show();
			$('.jspVerticalBar').appendTo($('#scroll')).css('right', '15px');
			$('.jspPane ').css('width', '335px');
		});
	}
	
}

function checkPage(href){

	/* Ombra sui titoli */
	if($.browser.msie){
//		$('h1').wrap('<div style="background:red" class="wrap_title" />');
		$('h1').each(function(){
			var txt = $(this).text();
			$(this).wrap('<div class="wrap_title" />');
			var container = $(this).closest('.wrap_title');
			$('<h1 class="t_shad">' + txt + '</h1>').appendTo(container);
		});
		
		$('h2').not('.offerta h2').each(function(){
			var txt = $(this).text();
			$(this).wrap('<div class="wrap_title" />');
			var container = $(this).closest('.wrap_title');
			$('<h2 class="t_shad">' + txt + '</h2>').appendTo(container);
		});
	}
	
	switch(href){
		
		case 'team.php':
			$('.team').unbind('click');
			//$.getScript('js/slider.js', function(){
			team();
			//});
		break;
	
		case 'dovesiamo.php':  //Ita
		case 'address.php':  //Eng
			$.getScript(absPath + 'js/map.js', function(){
				map(46.0040825, 8.950869);
			});
		break;
		
		case 'link.php': //Ita
		case 'links.php':  //Eng
			$('.link').click(function(){
				var h = $(this).find('a');
				var openLink = window.open(h.attr('href'), '_blank');
				
				try{
					openLink.focus();
				}
				catch(e){
				
				}
				
			});
			$('.link a').click(function(e){
				try{
					e.preventDefault();
				}
				catch(e){
					return false;
				}
			});
			
			if(($.browser.msie) && ($.browser.version <= 7)){
				$('#link-list').css('overflow', 'auto');
			} else {
				$.getScript(absPath + 'js/jpane.js',function(){
					$('#link-list').jScrollPane(
						{
							showArrows: true,
							verticalArrowPositions: 'split',
							horizontalArrowPositions: 'split'
						}
					).hide().show();
					$('.jspVerticalBar').appendTo($('#scroll'));
					$('.jspPane ').css('width', '630px');
				});
			}
		break;
		default:
	}
}

//Cambio il contenuto della pagina
function updatePage(href, title, bg, content){

	img = new Image();			//new img obj
	page_content = 'div#wrapper_content';
	supersize = 'div#supersize'; 
		
	img.src = bg;	//set src either absolute or rel to css dir
	img.id = 'back';
	
	if(!$.browser.msie){
		$('head').find('title#pageTitle')
				.html(title);
	}
	
	$(page_content).animate({opacity: "hide"}, 400,
		function(){
			$(this).html(content);
		}
	);
	setTimeout(function(){
		$(supersize).animate({opacity: "hide"}, 400);
	},400);
	
	var onload = function(){
		setTimeout(function(){
			$(supersize).html('<img src="' + bg + '" />')
						.resizenow()
						.animate({opacity: "show"}, 400);
		},800);
		
		setTimeout(function(){
			$(page_content).animate({opacity: "show"}, 400, function(){
				checkPage(href);
			});
			
		},1200);
		
		setTimeout(function(t){
			//$('img', 'div.content-loading').remove();
			$('div#nav').find('div.selected')
						
						.removeClass('selected');
			$('div.content-loading').animate({paddingRight: 0, paddingLeft: 0})
									.removeClass('content-loading')
									.addClass('selected');
		},1800);
	};

	var testImg = function(){
		if(img.complete !== null && img.complete === true){ 
			onload();
			return;
		}
		setTimeout(testImg, 1000);
	};

	// IE 7 workarond
	if($.browser.msie){
	    setTimeout(testImg, 1000);
	}else{
	    $(img).bind('load',onload);
	}
	
}


//Carico il contenuto della pagina
function goTo(){
	
	var pageTitle, back, pageContent,
		obj = $(this),
		href = obj.find('a').attr('href'),
		h;
		//call = href.split('.');
		
	if(!obj.hasClass('selected') && !$('div.content-loading').length){
		obj.animate({paddingRight: 16},200);
		
		//var loading = '<img style="position: absolute; right:5px; top: 50%; margin-top:-9px;" src="img/page-loader.gif" alt="progress" width="16" height="16" />';
		setTimeout(function(){
			obj.addClass('content-loading');
			//$('.content-loading').css('background-position', (w-26)+'px center');
			//loading.appendTo($('.content-loading'));
		}, 210);
		h = href;
		if(window.location.href.indexOf('en/') != -1){
			h = 'en/' + href;
		}
		
		if(window.location.href.indexOf('de/') != -1){
			h = 'de/' + href;
		}
		
		if(window.location.href.indexOf('ru/') != -1){
			h = 'ru/' + href;
		}
		
		$.getJSON(absPath + 'js/ajax.php?action=page&page=' + h + '&callback=?', function(j){
			$.each(j, function(i, page){
				pageTitle = page.title;
				back = page.bg;
				pageContent = page.content;
			});

			updatePage(href, pageTitle, back, pageContent);
		});		
	}
	return false;
}


//Animazioni e Handlers
function MenuAnim(){
	$('div.menu-element a').click(function(e){
		try{
			e.preventDefault();
		}
		catch(e){
			return false;
		}
	});
	
	var logo_elem = 'div#logoGlobus',
		logoWidth = $(logo_elem).width() + 20;
		
	$(logo_elem).css('margin-left', '-' + logoWidth + 'px')
				.animate({ marginLeft: '0' }, 400)
				.animate({ marginLeft: '5px' }, 100)
				.animate({ marginLeft: '0' }, 200, function(e){
	
						setTimeout(function(){
							var toolbar = $('#toolbar');
							toolbar.css('margin-right', '10px')
							.animate({
								opacity:	  '1',
								marginRight: '60px'
							}, 400);
							
							toolbar.animate({
								marginRight: '65px'
							}, 100);
							
							toolbar.animate({
								marginRight: '60px'
							}, 200, function(i){
							
								$(this).find('li').each(function(j){
									var obj = $(this);
									if(!obj.hasClass('selected')){
										obj.hover(
											function()
											{
												obj.stop(true,true)
												.animate({ opacity: 0.3 }, 150);
												/*
.siblings()
												.stop(true,true)
												.animate({ opacity: 1 }, 150);
*/
											},
											function()
											{
												obj.stop(true,true)
												.animate({ opacity: 1 }, 150);
												/*
.siblings('.selected')
												.stop(true,true)
												.animate({ opacity: 0.3 }, 150);
*/
											}
										);
									}
								});
							});

							setTimeout(function(){
							$('#wrapper_content').animate({opacity:'show'},400, function(){
								var l = window.location.href;
								l = l.split('/');
								checkPage(l[l.length - 1]);
							});
							},1000);
							},800);
						});
	
	setTimeout(function(){

		var navigation_id = 'div#nav',
			list_elements = navigation_id + " div.menu-element",
			timer = 0,
			multiplier = 0.7,
			time = 150,
			WidthPad = 0;

		$(list_elements).each(function(i){
			var obj = $(this);
			WidthPad = obj.width() + 18;
	        // margin left = - ([width of element] + [total vertical padding of element])
	        
	        // updates timer
	        timer = (timer*multiplier + time);
			obj.css("margin-left",'-' + WidthPad + 'px')
				.animate({ marginLeft: "0" }, timer)
				.animate({ marginLeft: "5px" }, timer)
				.animate({ marginLeft: "0" }, timer);
	    });
		
		setTimeout(function(){
			$(list_elements).each(function(i){
				var obj = $(this);
				obj.hover(
					function()
					{
						if(!obj.hasClass('content-loading')){
							obj.stop(true,true)
							.animate({ paddingLeft: 5 }, 150);
						}
					},
					function()
					{
						if(!obj.hasClass('content-loading')){
							obj.stop(true,true)
							.animate({ paddingLeft: 0 }, 150);
						}
					}
				)
				.click(goTo);
			});
			$('div.menu-element a').unbind('click');
		},1800);

	},700);
}

(function($){

	//Resize image on ready or resize
	$.fn.supersized = function() {
		$.inAnimation = false;
		$.paused = false;
		//var options = $.extend($.fn.supersized.defaults, $.fn.supersized.options);
		
		$(window).bind("load", function(){
			$('#loading').hide();
			$('#supersize').animate({opacity: "show"}, 600, MenuAnim);
			if($('#slideshow .activeslide').length === 0){ $('#supersize img:first').addClass('activeslide'); }
		});
				
		$(document).bind('ready', function() {
			$('#supersize').resizenow();
		});
		
		$(window).bind("resize", function(){
			$('#supersize').resizenow();
		});
		
		$('#supersize').hide();
	};
	
	//Adjust image size
	$.fn.resizenow = function() {
		var options = $.extend($.fn.supersized.defaults, $.fn.supersized.options);
		return this.each(function() {

			//Define image ratio
			var ratio = options.startheight/options.startwidth,
				browserwidth = $(window).width(),
				browserheight = $(window).height();
				
			//Gather browser and current image size
			//var imagewidth = $(this).width();
			//var imageheight = $(this).height();
			//var offset;

			//Resize image to proper ratio
			if ((browserheight/browserwidth) > ratio){
			    $(this).height(browserheight);
			    $(this).width(browserheight / ratio);
			    $(this).children().height(browserheight);
			    $(this).children().width(browserheight / ratio);
			} else {
			    $(this).width(browserwidth);
			    $(this).height(browserwidth * ratio);
			    $(this).children().width(browserwidth);
			    $(this).children().height(browserwidth * ratio);
			}
			
				$(this).children().css('left', (browserwidth - $(this).width())/2);
				$(this).children().css('top', (browserheight - $(this).height())/2);
			
			return false;
		});
	};
	
	$.fn.supersized.defaults = { 
			startwidth: 1800,  
			startheight: 1200,
			vertical_center: 1
	};
	
})(jQuery);

$(function(){
    $('div#supersize').supersized();
	css1020();
	$.preloadImages(absPath + "img/page-loader.gif");
});

$(window).resize(function(){
	$('div#supersize').resizenow();
	css1020();
});
