var garbageCollector = function() {};
var boxCallBack = function(box) {};

var BACKGROUND_STORE = ['/images/backDrop/1.jpg','/images/backDrop/2.jpg','/images/backDrop/3.jpg','/images/backDrop/4.jpg'];

var nextBackground = 0;
var BACKGROUND_TIMER = 5000; //change background every n ms
var defaultHeight = 703;
var menuPosition = defaultHeight;
var menuPositionOpened = menuPosition-112;
var apexPosition = menuPosition-27;
var overlayContact, overlaySkateComposerError;
var boxStore = {};

function swipe(method, newBox, callBack)
{	var newInitialX=0,newInitialY=0,oldFinalX=0,oldFinalY=0;
	switch (method)
	{	case "left":
			newInitialX = 1000;
			oldFinalX = -1000;
			break;
		case "right":
			newInitialX = -1000;
			oldFinalX = 1000;
			break;
		case "bottom":
			newInitialY = 1000;
			oldFinalY = -1000;
			break;
		case "top":
			newInitialY = -1000;
			oldFinalY = 1000;
			break;
	}

	if ($(newBox).hasClass("activeBox") == true)	//the target box is already active, just do nothing.
		return;

	var oldBox = $(".activeBox").removeClass("activeBox").css({"overflowY":"hidden"});
	newBox.addClass("activeBox").css({left: newInitialX, top: newInitialY, opacity:0, overflowY:"hidden"});
	newBox.find(".customShadow").hide();

	//declaring the step #2
	var step2 = function() {
			oldBox.animate( {"left":oldFinalX, "top": oldFinalY, opacity:0.0}, 300, "easeInCirc", function() {
			newBox.css({overflowY:"auto"})
			adjustWindowSize();
			boxCallBack(newBox);
			boxCallBack = function(box) {};
		});
		newBox.animate({"left":0, "top": 0, opacity:1.0}, 300, "easeInCirc", function() { newBox.find(".customShadow").fadeIn("fast"); });	
	}


	var oldShadow = oldBox.find(".customShadow")
	if (oldShadow.length > 0)
		oldShadow.fadeOut("fast", step2);
	else
		step2();

}


/* Fonction pour changer de page
* usage: getBoxContentAndSwitch("url")
*/

function getBoxContentAndSwitch(metaName) {
	garbageCollector();		//last box implemented a garbage collector we call here
	garbageCollector = function() {};	//and we reset here

	//It's time to tell google analytics
	var pReq = window.location.href.replace("/#/","/").replace("#","");
	if (pReq.indexOf(".php") >= 0)
		var pReq = 	pReq.substring(0, pReq.indexOf(".php")+4);
	_gat._getTracker("UA-10203105-1")._trackPageview(pReq);	

	if (!boxStore[metaName])	//this box has never been opened before.
	{	var newBox = $("<div class='mainGridBox'></div>");
		$("#loadingBoxProgress").fadeIn("slow");
		boxStore[metaName] = newBox;
		$.ajax({url : metaName,
				cache:true,
				dataType:"html",
				success: function(returnedData) {
					newBox.html(returnedData)
					newBox.data("level",parseInt(newBox.find("input[name='level']").val()));
					newBox.data("subLevel",parseInt(newBox.find("input[name='subLevel']").val() || 0));
					newBox.find(".loadScript").each(function() { $.getScript($(this).val())});
					newBox.find(".enableToolTip").tooltip({position: "top center", opacity:0.9, offset:[2,-6]});
					newBox.find(".regularToolTip").each(function() { 
						$(this).tooltip({delay: parseInt($(this).attr("delay")) || 0, offset:[parseInt($(this).attr("offsettop")) || 0,parseInt($(this).attr("offsetleft")) || 0]}); 
					}); 

					//Make sure everything is loaded in that box before showing it to the user.
					var imgStore = listBoxImg(newBox);
					if (imgStore.length == 0)
					{
						newBox.appendTo($("#boxContainer"));
						switchToBox(newBox);
					}
					else
						$.xLazyLoader({
						    img: imgStore,
						    complete: function(){
								newBox.appendTo($("#boxContainer"));
								switchToBox(newBox);
						    }
						});
				}
				}
		);
	}
	else
		switchToBox(boxStore[metaName]);
}

function listBoxImg(box)
{
	var imgStore = [];
	box.find("img").each(function() { imgStore.push($(this).attr("src")) });
	box.find("div").each(function() {
		var bgImg = $(this).css("background-image");
		if (bgImg.indexOf(".") == -1)
			return;
		bgImg = bgImg.replace("url(http://apexracingskates.com","").replace("url(http://www.apexracingskates.com","").replace(')','');
		if (bgImg.indexOf("(") >= 0) //we have failed trimming it
			return;
		imgStore.push(bgImg);
	})
	return imgStore;
}

function switchToBox(box)
{	$("#loadingBoxProgress").fadeOut("slow");
	var activeBox = $(".activeBox");
	document.title = box.find("input[name='title']").val() + " - Apex Racing Skates";
	if (activeBox.length == 0)	//so basically we can't replace an existing box since this is the first one
	{	adjustWindowSize();
		box.hide().addClass("activeBox").fadeIn("slow", 
		function() {
			boxCallBack(box);
			boxCallBack = function(box) {};

		});
	}
	else
		if (box.data("level") == activeBox.data("level") && box.data("subLevel") > activeBox.data("subLevel"))
		 	swipe("top", box);
		else if (box.data("level") == activeBox.data("level") && box.data("subLevel") < activeBox.data("subLevel"))
		 	swipe("bottom", box);
		else if (box.data("level") > activeBox.data("level"))
			swipe("left", box);
		else
			swipe("right", box);
		
}

function metaCallBack(options) {

}

//changeBackground expexts a path to an image to put in background.
function changeBackground(targetBackground)
{
	var newBG = $("<img src='" + targetBackground + "'>").addClass("background").insertBefore(".currentBackground").load(function() {
		$(".currentBackground").fadeOut("slow", function() { $(this).remove(); })
		newBG.addClass("currentBackground");
	});

}

//Set background to the next value and set the next value
function nextBackgroundInterval()
{	changeBackground(BACKGROUND_STORE[nextBackground]);
	nextBackground = ++nextBackground % (BACKGROUND_STORE.length-1);
	window.setTimeout(function() { nextBackgroundInterval() }, BACKGROUND_TIMER);
}

function preload() 
{	var preloadStore = [];
	preloadStore = preloadStore.concat(BACKGROUND_STORE);
	var loadDiv = $("<div id=loadDiv></div>").hide();
	$.each(preloadStore, function(i,elem) { loadDiv.append("<img src='" + elem + "'>");	});
	//Now time to preload that image
	$("body").append(loadDiv);
}

function menuRentre(delay)
{	return;
	var delay = delay || 500;
	var menuBar = $("#menuBar");
	window.setTimeout(function() {
		if (menuBar.data("active") == "true") return;
		menuBar.stop().animate({top:menuPosition}, 500, "easeOutBounce", function() {	menuBar.data("active","false");});	
	}, delay);
	menuBar.data("active","false");

}

function adjustWindowSize() 
{
		var newHeight = $(window).height()
		dif = newHeight - defaultHeight;
		if (dif >0 ) // on espace la fenetre.
		{
			menuPosition = defaultHeight-26;
			menuPositionOpened = menuPosition-112;
			apexPosition = menuPosition-55;
			$("#spacerTop").css({height:dif/2});
			$(".autoHeight").add(".mainGridBox").css({height:defaultHeight})
			$("#menuBar").css({top:menuPosition})
			$("#apexLogo").css({top:apexPosition})
		}
		else
		{	$("#spacerTop").css({height:0});
			$(".autoHeight").add(".mainGridBox").css({height:newHeight})
			menuPosition = newHeight-26;
			menuPositionOpened = menuPosition-112;
			$("#menuBar").css({top:menuPosition})
			apexPosition = menuPosition-55;
			$("#apexLogo").css({top:apexPosition})

		}


		if ($(".autoPaint").length > 0)
				$(".autoPaint").css({height:$(".mainGridBox")[0].scrollHeight || 0});

}
$(function() {

//	preload(); //precharger les images de background pour une sweet transition.
//	nextBackgroundInterval();

	$("#apexLogo img").hover(function() {
		$(this).stop().animate({width:193, height:147});
	}, function() {
		$(this).stop().animate({width:100, height:76});
	}
	);
	$.historyInit(getBoxContentAndSwitch);
	if (self.document.location.hash.length==0)
		$.historyLoad("splash.htm");

	/* Code pour centrer verticalement le site et le redimensionnˇ si window.height < 703
	*/
	var dif;

	$(window).bind('resize', function() {
		adjustWindowSize();
	}).trigger("resize");


	$("a").live("click",function(event) {
		event.preventDefault();

		if ($(this).hasClass("overwrite"))
			window.location=$(this).attr("href");

		var linkClicked = $(this).attr("href");
		linkClicked = linkClicked.replace("http://www.apexracingskates.com","").replace("http://apexracingskates.com","");
		if (linkClicked)
			if (linkClicked.indexOf("http://") >= 0)
				window.open(linkClicked);
			else
				$.historyLoad(linkClicked);
	});

	/*Gestion des ˇvˇnements "click" sur les boutons du menu
	*/
	$("#menuBar").find("a").click(function() {
			var tab = $(this).find("div");
			var oldItem = $(".activeMenuItem").removeClass("activeMenuItem");
			tab.addClass("activeMenuItem");
			menuRentre(15);
	});
	
				

	//Code pour faire monter et descendre la barre de menu quand la souris passe dessus
	$("#menuBar").hover(function() { //donc ici on fait sortir la barre
		return;
		$(this).stop();
		$(this).animate({top:menuPositionOpened}, 300, "easeInCirc");	
		$(this).data("active","true");
	}, function() { menuRentre();	});

	$(".reactiveButton").live("mouseenter",function() {
		$(this).addClass("ui-state-hover");
	}).live("mouseleave", function() { $(this).removeClass("ui-state-hover"); });

    overlayContact = $("#contactForm").overlay({effect:'apple', api:true}); 
	overlaySkateComposerError = $("#errorSkateComposer").overlay({effect:'apple', api:true}); 


	$(".submitForm").click(function() {
		var butClicked = $(this);
		butClicked.after("<img src=/images/progress.gif class=frmProgress height=16 width=16>");
		$.post("/mail.php", $(this).parents("form").serialize(), function() {
			$(".frmProgress").remove();
			butClicked.parents("form").slideUp("slow", function() {
				butClicked.parents("form").parent().find(".thankYou").slideDown("slow");
			})
		})
	});

});	//fin the onBodyLoad


function openContactOverlay(ref)
{	var cName = $(ref).attr("data-CountryName");
	$("#countryName").text(cName);
	$("#frmDealer").val(cName);
	
	overlayContact.load();
}


