var writingSearch = false;
var timerActive = false;
var menuTimeout = 20000;
var languageDropDownIsOpen = false;
var myScroll = null;

var isMagazineHidden = false;
var isMenuHidden = false;
var enableMenuHiding = true;

var isMouseInMenu = false;

var slideshowPreloadingWindow = 6;
var slideshowIterations = 0;

function adjustBackgroundImageSize($img) {
	if ($("#bg").width() / $("#bg").height() < $img.width() / $img.height()) {
		
		$img.css({
			width: "auto",
			height: "100%"
		});	
		var w = ($("#bg").width() - $img.width()) / 2;	
		$img.css({
			"left": w + 'px',
			"top": '0px'
		});
	} else {
		
		$img.css({
			width: "100%",
			height: "auto"
		});
		var h = ($("#bg").height() - $img.height()) / 2;		
		$img.css({
			"top": h + 'px',
			"left": '0px'
		});
	}		
}

function adjustAllBackgroundImageSizes() {
	$("#bg img").each(function() {
		adjustBackgroundImageSize($(this));
	});
}

$(window).resize(function () {
	adjustAllBackgroundImageSizes();
});

(function ($) {
	$.fn.replaceText = function (b, a, c) {
		return this.each(function () {
			var f = this.firstChild,
				g, e, d = [];
			if (f) {
				do {
					if (f.nodeType === 3) {
						g = f.nodeValue;
						e = g.replace(b, a);
						if (e !== g) {
							if (!c && /</.test(e)) {
								$(f).before(e);
								d.push(f)
							} else {
								f.nodeValue = e
							}
						}
					}
				} while (f = f.nextSibling)
			}
			d.length && $(d).remove()
		})
	}
})(jQuery);

function hideAllMenues(duration) {
	if (typeof(duration) == 'undefined') {
		duration = 400;
	}

	$("#menu_slider").slideUp(duration);
	$("#showMenu").css("display", "block");
	$("#logo_bkg").slideUp(duration);

	if (a2plusPageManager.currentPage == "home") {
		hideMagInHome();
	}

	if (a2plusPageManager.isProject()) {
		$("#mag_bottom").hide();
		$("#project-controls").show();
	}
}

function showAllMenues() {
	showMenu();

	if (a2plusPageManager.currentPage == "home") {
		showMagInHome();
	}
}

function showMenu() {
	$("#menu_slider").slideDown();
	$("#logo_bkg").slideDown();
	$("#showMenu").css("display", "none");

	if (a2plusPageManager.currentPage == "home") {
		$("#mag_rightbox").css("opacity", "0.0");	
		$("#mag_menu").animate({
			bottom: '-192px',
		}, 500);		
	} else if (a2plusPageManager.isProject()) {
		$("#mag_bottom").show();
		$("#project-controls").hide();
	}

	startMenuTimer();
}

function hideMag() {
	$("#mag_menu").animate({
		bottom: '0px',
	}, 500, function() {
		isMagazineHidden = true;
	});

	$("#mag_rightbox").slideUp();	
}

function hideMagInHome() {
	$("#mag_menu").animate({
		bottom: '-230px',
	}, 500, function() {
		isMagazineHidden = true;
	});
}

function showMagInHome() {
	$("#mag_rightbox").css("opacity", "1.0");
	$("#mag_menu").animate({
		bottom: '0px',
	}, 500, function() {
		isMagazineHidden = false;
	});
}
	

function startMenuTimer() {

	if (!timerActive && enableMenuHiding) {
		//hide menu after 5 sec if text slider active
		timerActive = true;
		window.setTimeout(function () {
			timerActive = false;
			if (enableMenuHiding && !isMenuHidden && !writingSearch && !isMouseInMenu) {
				hideAllMenues();
			}
		}, menuTimeout);
	}
}

function searchFunction() {
	alert("performSearch");
	return false;
}

function setupBackgrounds () {

	if (a2plusPageManager.currentPage == "home") {

		fadeBackgroundIn();

	} else if (!a2plusPageManager.isProject()) {

		fadeBackgroundOut();

	}
}

function setupBackgroundTempFiller () {
	if (slideshowData.length > 0) {
		var newImageHTML = '<img id="bg-temp-filler" src="' + slideshowData[0].src + '" style="position: absolute; display: none;" />';
		$("#bg").before(newImageHTML);
		$("#bg-temp-filler").load(function() {
			var $bgTempImage = $(this);
			setTimeout(function () {
				adjustBackgroundImageSize($bgTempImage);
				$bgTempImage.fadeIn("fast");
			}, 200);
		})
	}
}

function setupMenues() {

	if (a2plusPageManager.currentPage == "home") {

		enableMenuHiding = true;
		startMenuTimer();	

	} else if (a2plusPageManager.isProject()) {

		if (!isNavigatingProjects) {
			enableMenuHiding = true;
			menuTimeout = 2000;
			startMenuTimer();
			$("#project-controls").hide();
		} else {
			// Close immediately the menues, without animation
			enableMenuHiding = true;
			menuTimeout = 2000;
			hideAllMenues(0);
			$("#project-controls").show();
		}

	} else { // Nor home, nor projects
		enableMenuHiding = false;
		showMenu();
	}	
}

function setupFullScreen() {

	if (document.mozFullScreen === true || document.webkitIsFullScreen === true || document.isFullScreen === true) {
		$("#fullscreenbutton").text("exit full screen");
	}

	// Fullscreen buttons
	$("#fullscreenbutton").click(function() {
		var supportsFullScreen = false;
		if (this.webkitRequestFullScreen) {

			if (!document.webkitIsFullScreen) {
				document.documentElement.webkitRequestFullScreen();
			} else {
				document.webkitCancelFullScreen();
			}            	

        } else if (this.mozRequestFullScreen) {

			if (!document.mozFullScreen) {
				document.documentElement.mozRequestFullScreen();
			} else {
				document.mozCancelFullScreen();
			}                   	

        } else if (this.requestFullScreen) {

			if (!document.isFullScreen) {
				document.documentElement.requestFullScreen();
			} else {
				document.cancelFullScreen();
			}

        } else {
            alert ('Your browser cannot enter fullscreen mode.');
        }

        setTimeout(function() {
			if (document.mozFullScreen === true || document.webkitIsFullScreen === true || document.isFullScreen === true) {
				$("#fullscreenbutton").text("exit full screen");
			} else {
				$("#fullscreenbutton").text("open full screen");
			}      	
        }, 1000);

	});	
}

function setupHomeSwipes() { 
	$("body").swipe({
		click:click,
		swipe:swipe,
		threshold:50
	});
	
	//Swipe handlers.
	//The only arg passed is the original touch event object			
	function swipe(event, direction) {
		if (a2plusPageManager.currentPage == "home") {
			if (direction == "left") {
				$('#bg').goToNextImage(crossFadeCallback);
				$("#payoff-container").hide("slow");
			}
			
			if (direction == "right") {
				$('#bg').goToPreviousImage(crossFadeCallback);
				$("#payoff-container").hide("slow");					
			}			
		}
	}	
}

var inited = false;

// This function is always executed after the "ready" event
function prepareMain() {

	setupBackgrounds();
	setupMenues();

	// Hide the map background
	if (a2plusPageManager.currentPage != "contact") {
		$("#background-map").animate({
			"opacity": "0.0"
			}, 300, function() {
				$("#background-map").remove();
			});	
	}

	if (!inited) {

		// Background temp filler only works in home
		if (a2plusPageManager.currentPage == "home") {
			setupBackgroundTempFiller();
		}		

		setupFullScreen();

		// if (!a2plusPageManager.isProject()) {
		// 	setupHomeSwipes();
		// }

		if (!a2plusPageManager.isProject() && isTablet) {
			preloadPageBackgrounds();
		}

		// Save image in fullscreen
		$("#savefullscreenbutton").click(function () {
			location.href = TEMPLATE_URL + "/downloadImage.php?src=" + slideshowData[crossSlideHomeImagesIndex].src;
		});

		// Save screensaver
		$("#savescreensaverbutton").click(function () {
			location.href = TEMPLATE_URL + "/files/A++ScreenSaver.zip";
		});

		//click on the logo: back to home (text slider)
		$("#logo_img").click(function () {
		
			if (a2plusPageManager.currentPage == "home") {
				if (isMagazineHidden) {
					showAllMenues();
				} else {
					hideAllMenues();
				}
			}

			//clear style of previous selected menu item
			$(".menu_link").removeClass("selected");
			if (!isMenuHidden) {
				startMenuTimer();
			}
			$.address.value("home");
		});

		//menu click and hover functions
		$(".menu_link").click(function () {

			//clear style of previous selected
			$(".menu_link").removeClass("selected");
	
			//set style to selected
			$(this).addClass("selected");
		});
		
		$("#s").focus(function () {
			writingSearch = true;
			var defVal = $(this).attr("placeholder");
	
			if ($(this).val() == defVal) {
				$(this).val("");
				$(this).css("color", "#000");
			}
		});	
		
		$("#s").focusout(function () {
			writingSearch = false;
			var defVal = $(this).attr("placeholder");
	
			if ($(this).val() == "") {
				$(this).val(defVal);
				$(this).css("color", "#818181");
			}
	
			//restart the hide menu timer
			startMenuTimer();
		});
	
		$("#showMenu").click(function () {
			showMenu();
		});		

		$("#menu").mouseover(function () {
			isMouseInMenu = true;
		});

		$("#menu").mouseleave(function () {
			isMouseInMenu = false;
			startMenuTimer();
		});		
		
		// Language dropdown Management
		$("#leftbar_language_list").click(function () {
			languageDropDownIsOpen = true;
			$("#leftbar_language_list a").show();
		});
	
		$("#leftbar_language_list").mouseleave(function () {
			languageDropDownIsOpen = false;
			$("#leftbar_language_list a").hide();
		});		
		
		playCrossSlideHomeImages();
		playCrossSlideHomeMessages();	
	}
	
	if (a2plusPageManager.isProject()) {
		$("#mag_rightbox").hide();
	}
	
	if (a2plusPageManager.currentPage == "home") {
		$("#fullscreencontrols").show();
	} else {
		$("#fullscreencontrols").hide();
	}
	
	
	inited = true;
}




// ------------------------------
// CROSS SLIDE HOME IMAGES
// ------------------------------

var crossSlideHomeImagesIndex = 0;
var canGoToNextPrev = true;

function playCrossSlideHomeImages() {
	if (!a2plusPageManager.isProject()) {

		// Create prev/next image container
		function createPrevNextImageContainerIfNeeded () {
			if ($("#bg-prev-next-images").length == 0) {
				$("#bg").append('<div id="bg-prev-next-images"></div>');
			} else {
				// If the container is not on top, force it
				if ($("#bg").children().last().attr("id") != "bg-prev-next-images") {
					$("#bg").append($("#bg-prev-next-images"));			
				}
			}		
		}

		function removePrevNextImageContainerIfNeeded () {
			if ($("#bg-prev-next-images").length > 0) {
				$("#bg-prev-next-images").fadeOut(500, function () {
					$("#bg-prev-next-images").remove();
				});
			}			
		}		
		
				
		$("#slideshow-description").click(function () {
			if (slideshowData[crossSlideHomeImagesIndex].permalink != "") {
				location.href = slideshowData[crossSlideHomeImagesIndex].permalink;
			}
		});

		function preloadMoreImagesIfNeeded(currentIndex) {

			var numberOfImagesInCurrentSet = $("#bg").get(0).crossSlideArgs[1].length;

			// Preload first image of the new group
			if (currentIndex == slideshowPreloadingWindow - 2 && slideshowPreloadingWindow < slideshowData.length) {
				if (slideshowIterations * slideshowPreloadingWindow < slideshowData.length) {
					var img1 = new Image(); 
					img1.src = slideshowData[slideshowIterations * slideshowPreloadingWindow];
				}	   				
			}

			if (currentIndex == numberOfImagesInCurrentSet - 1 && slideshowPreloadingWindow < slideshowData.length) {
				slideshowIterations++;

				$("#bg").crossSlidePause();

				// Add placeholder image (to avoid gray screen)
				$("#bg img:first").clone().insertBefore("#bg");

				// Make placeholder image opaque
				$("#background-slider img:first").css({"display": "block", "opacity": "1.0"});

				$("#bg").fadeOut(500, function () {
									
					// Remove and clear background
					$("#bg").remove();

					// Add new background
					$("#background-slider").append('<div id="bg"></div>');
					if (slideshowIterations * slideshowPreloadingWindow >= slideshowData.length) {
						slideshowIterations = 0;
					}

					setTimeout(function () {
						createCrossSlide(slideshowIterations * slideshowPreloadingWindow);
						}, 2000);

					// Remove placeholder image
					setTimeout(function() {
						$("#background-slider img:first").remove();
						}, 5000);						

				});
			}			
		}

		function createCrossSlide(sliceStart) {
			// Bad fix! Prevent the new set from containing only one element
			if (slideshowData.length > 0 && sliceStart == slideshowData.length - 1) {
				sliceStart--;
			}

			$('#bg').crossSlide({
				sleep: 8,
				fade: 0.5
			}, slideshowData.slice(sliceStart, sliceStart + slideshowPreloadingWindow), 
			function (currentIndex, imgAdditionalData) { // loop callback
				crossSlideHomeImagesIndex = getSlideshowDataIndexById(imgAdditionalData.post_id);
				updateDescription();
				preloadMoreImagesIfNeeded(currentIndex);				
			},
			function (imgAdditionalData) { // creationCallback

				adjustAllBackgroundImageSizes();

				crossSlideHomeImagesIndex = getSlideshowDataIndexById(imgAdditionalData.post_id);
				updateDescription();

				// Remove temporary background filler
				setTimeout(function () {
					$("#bg-temp-filler").remove();
				}, 1000);

				if (a2plusPageManager.currentPage == "search") {
					$('#bg').crossSlidePause();
				}
			});			
		}

		createCrossSlide(0);

		$(".crossfade-control.previous").click(function () {
			goToPrevImage();
		});

		$(".crossfade-control.next").click(function () {
			goToNextImage();
		});

		$(".crossfade-control.playpause").click(function () {
			$("#payoff-container").hide("slow");
			if ($("#bg").isPaused()) {
				removePrevNextImageContainerIfNeeded();
				$('#bg').crossSlideResume();
				$(".crossfade-control.playpause").attr("src", TEMPLATE_URL + '/images/cmd_pause.png');
				canGoToNextPrev = true;	
			} else {
				$('#bg').crossSlidePause();
				$(".crossfade-control.playpause").attr("src", TEMPLATE_URL + '/images/cmd_play.png');
			}
		});

		function goToNextImage() {
			if (!canGoToNextPrev) 
				return;

			canGoToNextPrev = false;

			// Set the slideshow to pause state
			$('#bg').crossSlidePause();
			$(".crossfade-control.playpause").attr("src", TEMPLATE_URL + '/images/cmd_play.png');
	
			$("#payoff-container").hide("slow");	

			crossSlideHomeImagesIndex++;
			if (crossSlideHomeImagesIndex == slideshowData.length) {
				crossSlideHomeImagesIndex = 0;
			}

			var imageId = "next-prev-" + crossSlideHomeImagesIndex;

			var newImg = new Image();
			newImg.onload = function (e) {
				createPrevNextImageContainerIfNeeded();	

				$("#bg-prev-next-images").append('<img style="display: none" id="' + imageId + '" src="' + newImg.src + '">');
				adjustBackgroundImageSize($('#' + imageId));

				updateDescription();

				// Fade in next image and remove the old one, just keep one image at a time
				$('#' + imageId).fadeIn(500, function () {
					if ($("#bg-prev-next-images img").length > 1) {
						$("#bg-prev-next-images img:first").remove();
					}
					canGoToNextPrev = true;										
				});
			}
			newImg.onerror = function (e) {
				goToNextImage();
			}

			newImg.additionalData =slideshowData[crossSlideHomeImagesIndex].data;
			newImg.src = slideshowData[crossSlideHomeImagesIndex].src;

		}

		function goToPrevImage() {

			if (!canGoToNextPrev) 
				return;

			canGoToNextPrev = false;

			// Set the slideshow to pause state
			$('#bg').crossSlidePause();
			$(".crossfade-control.playpause").attr("src", TEMPLATE_URL + '/images/cmd_play.png');
	
			$("#payoff-container").hide("slow");	

			crossSlideHomeImagesIndex--;
			if (crossSlideHomeImagesIndex == -1) {
				crossSlideHomeImagesIndex = slideshowData.length - 1;
			}

			var imageId = "next-prev-" + crossSlideHomeImagesIndex;

			var newImg = new Image();
			newImg.onload = function (e) {
				createPrevNextImageContainerIfNeeded();	

				$("#bg-prev-next-images").append('<img style="display: none" id="' + imageId + '" src="' + newImg.src + '">');
				adjustBackgroundImageSize($('#' + imageId));

				updateDescription();

				// Fade in next image and remove the old one, just keep one image at a time
				$('#' + imageId).fadeIn(500, function () {
					if ($("#bg-prev-next-images img").length > 1) {
						$("#bg-prev-next-images img:first").remove();
					}	
					canGoToNextPrev = true;					
				});
			}
			newImg.onerror = function (e) {
				goToPrevImage();
			}

			newImg.additionalData =slideshowData[crossSlideHomeImagesIndex].data;
			newImg.src = slideshowData[crossSlideHomeImagesIndex].src;			
		}		
	}
}

function crossFadeCallback(currentIndex, imgAdditionalData) {
	$(".crossfade-control.playpause").attr("src", TEMPLATE_URL + '/images/cmd_play.png');
	crossSlideHomeImagesIndex = getSlideshowDataIndexById(imgAdditionalData.post_id);
	updateDescription(imgAdditionalData.post_id);
}

function updateDescription() {
	if (typeof(slideshowData[crossSlideHomeImagesIndex]) != 'undefined') {
		$("#slideshow-description").fadeOut(250, function () {
			$("#slideshow-description .project-title").html(slideshowData[crossSlideHomeImagesIndex].title);
			$("#slideshow-description .project-info").html(slideshowData[crossSlideHomeImagesIndex].info);	
			$("#slideshow-description").fadeIn(250);
		});			
	}
}	

function getSlideshowDataIndexById(post_id) {
	for (var i = 0; i < slideshowData.length; i++) {
		if (slideshowData[i].data.post_id == post_id) {
			return i;
		}
	}
	return null;
}

// ------------------------------
// CROSS SLIDE HOME MESSAGES
// ------------------------------

function playCrossSlideHomeMessages() {
	if (a2plusPageManager.currentPage == "home" && $("#payoff-container")) {
		$('#payoff-container').crossSlideOver({
			sleep: 6.5,
			fade: 1,
			doubleFade: true
		}, [
			{ src: TEMPLATE_URL + '/images/home_msgs/1.png' , permalink: "http://www.a2plus.it/#/cross-architecture"},
			{ src: TEMPLATE_URL + '/images/home_msgs/2.png' , permalink: "http://www.a2plus.it/#/creativity-collector"},
			{ src: TEMPLATE_URL + '/images/home_msgs/3.png' , permalink: "http://www.a2plus.it/#/sustainability"},
			{ src: TEMPLATE_URL + '/images/home_msgs/4.png' , permalink: "http://www.a2plus.it/#/architecture"},
			{ src: TEMPLATE_URL + '/images/home_msgs/5.png' , permalink: "http://www.a2plus.it/#/interior-design"},
			{ src: TEMPLATE_URL + '/images/home_msgs/6.png' , permalink: "http://www.a2plus.it/#/communication"},
			{ src: TEMPLATE_URL + '/images/home_msgs/7.png' , permalink: "http://www.a2plus.it/#/design"}
		], 
		function(){
			$(".homelinkimg").click(function () {
				$(window.location).attr('href', $(this).attr("permalink"));
			});
		}
		);			
	}
}

function padSubsequentLines($element) {
	var element = $element.get(0);
	var words = element.innerHTML.split(' ');
	element.innerHTML = '';

	for (var i = 0; i < words.length; i++) {
		element.innerHTML += '<span>' + words[i] + '</span> ';
	}

	var spans = element.childNodes;
	var currentOffset = spans[0].offsetTop;
	var html = '<div class="line"><span>';

	for (var i = 0; i < spans.length; i++) {

		if (spans[i].nodeType === 3) continue;

		if (spans[i].offsetTop > currentOffset) {
			html += '</span></div><div class="line"><span>';
			currentOffset = spans[i].offsetTop;
		}

		html += spans[i].innerHTML + ' ';
	}

	html += '</span></div>';
	element.innerHTML = html;
	$element.width($element.width() + 100);
}

JSON.stringify = JSON.stringify ||
function (obj) {
	var t = typeof (obj);
	if (t != "object" || obj === null) {
		// simple data type
		if (t == "string") obj = '"' + obj + '"';
		return String(obj);
	} else {
		// recurse array or object
		var n, v, json = [],
			arr = (obj && obj.constructor == Array);
		for (n in obj) {
			v = obj[n];
			t = typeof (v);
			if (t == "string") v = '"' + v + '"';
			else if (t == "object" && v !== null) v = JSON.stringify(v);
			json.push((arr ? "" : '"' + n + '":') + String(v));
		}
		return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
	}
};

function a2plusNameFix(tagselector) {
	$(tagselector + ' *').replaceText(/A\+\+/g, 'A<span class="smallplusplus">++</span>');
}

$.extend({
	getUrlVars: function () {
		var vars = [],
			hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		for (var i = 0; i < hashes.length; i++) {
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		return vars;
	},
	getUrlVar: function (name) {
		return $.getUrlVars()[name];
	}
});

function preloadPageBackgrounds() {
   	   var img1 = new Image(); 
	   img1.src = TEMPLATE_URL + '/images/about/about_architecture.png';
	   var img2 = new Image(); 
	   img2.src = TEMPLATE_URL + '/images/about/about_communication.png';
	   var img3 = new Image(); 
	   img3.src = TEMPLATE_URL + '/images/about/about_creativity_collector.png';
	   var img4 = new Image(); 
	   img4.src = TEMPLATE_URL + '/images/about/about_cross_architecture.png';
	   var img5 = new Image(); 
	   img5.src = TEMPLATE_URL + '/images/about/about_design.png';
	   var img6 = new Image(); 
	   img6.src = TEMPLATE_URL + '/images/about/about_interior_design.png';
	   var img7 = new Image(); 
	   img7.src = TEMPLATE_URL + '/images/about/about_pagina_1.png';
	   var img8 = new Image(); 
	   img8.src = TEMPLATE_URL + '/images/about/about_sustainability.png';
	   var img9 = new Image(); 
	   img9.src = TEMPLATE_URL + '/images/network/network_milano.png';
	   var img10 = new Image(); 
	   img10.src = TEMPLATE_URL + '/images/network/network_pagina_1.png';
	   var img11 = new Image(); 
	   img11.src = TEMPLATE_URL + '/images/network/network_tehran.png';
	   var img12 = new Image(); 
	   img12.src = TEMPLATE_URL + '/images/about/about_how_to.png';
	   var img13 = new Image(); 
	   img13.src = TEMPLATE_URL + '/images/network/network_shanghai.png';
	   var img14 = new Image(); 
	   img14.src = TEMPLATE_URL + '/images/network/network_art.png';
	   var img15 = new Image(); 
	   img15.src = TEMPLATE_URL + '/images/network/network_partners.png';
	   var img16 = new Image(); 
	   img16.src = TEMPLATE_URL + '/images/network/network_communication.png';
	   
		   
}

function fadeBackgroundOut () {
	$("#bg").animate({opacity: 0.25}, 500);	
}

function fadeBackgroundIn () {
	$("#bg").animate({opacity: 1.0}, 500);	
}

