//variable d'internationalisation
var lang = "fr";
//variable contenant les hash a charger
var hash_array = new Array();
//variables pour width des container
var left_wrap_width;
var left_wrap_position;
var right_wrap_width;
var right_wrap_position;
var wrapper_width;
var wrapper_position;
//var contenant width image
var left_img_w = 100;
var right_img_w = 50;
//var contenant le multiplicateur des images
var multiple = 6;
//slide id
var page_book;

//$(document).ready(launchFlash);
$(document).ready(initSite);

function launchFlash()
{
	var flashvars = {};
	flashvars.top = "auto";
	var params = {};
	params.bgcolor = "#2d1505";
	params.allowfullscreen = "true";
	var attributes = {};
	attributes.id = "drai_flash";
	swfobject.embedSWF("index.swf", "content", "100%", "100%", "9.0.45", false, flashvars, params, attributes);
	
	if($("#drai_flash").length == 0)
	{
		initSite();
	}
}

function initSite()
{
	//ecouteur ipad, iphone
	if(!$.browser.SafariMobile)
	{
		$(window).resize(setHeighSite);	
	}
	//récupération du cookie
	var introduction = $.cookie('launch_intro');
	//config container
	setHeighSite();
    //stockage hash
    $("#menu ul li a:not([rel=slide])").each
    (
        function()
        {
          var final_hash = getHashAndSetLang($(this).attr('href'));
          //on donne un attribut dynamique au a
          $(this).attr('rev',final_hash);
          hash_array.push(final_hash);
        }
    );
	
	/******************Set des listeners*************************/
	//slide
	$("a[rel=slide]").live('click',slideTo);
	$("#menu ul li a span").each(
		    function()
		    {
		      var parent_li_value = parseInt($(this).parent().parent().width());
		      var value_right = parseInt($(this).parent().parent().width())-$(this).width();
		     
		      if($(this).parent().parent().attr('id') == 'network-menu'){ value_right = value_right+10; }
		      $(this).parent().attr('original',value_right).css('width',$(this).width()+1+'px');
		      $(this).parent().css('marginRight',value_right+"px");
		    }
		);
	$("#menu ul li ul").css('display','none');
	/******************Stockage des taille initiales des containers && leur left*************/
	left_wrap_width = $('#left_wrap').width();
	right_wrap_width = $('#right_wrap').width();
	wrapper_width = $("#wrapper").width();
	left_wrap_position = parseInt($("#left_wrap").css('left'));
	right_wrap_position = parseInt($("#right_wrap").css('left'));
	wrapper_position = parseInt($("#wrapper").css('left'));
	/******************Ecouteur des hashs****************************************************/
    $(window).bind("hashchange",controllerLoading);
	/******************On regarde si l'intro a deja été lancée sinon on la lance*************/
	if(!introduction && (window.location.hash == null || window.location.hash == ""))
	{
		$('body').addClass('intro');
		$("#menu ul li a").live('click',function(){return false;});
		launchIntro();
	}
	else
	{
	/******************Gestion des hashs****************************************************/
	    $(window).trigger('hashchange');
	    $("#menu ul li a").live('click',activeCategory);
	}
}

//fonction charger de recalculer le site en fonction du redimensionnement de la fenetre
function setHeighSite()
{
	//config container
    $("#content").css('height',$(window).height());	
    $("#bg_container").css('display','block');
}
//fonction chargée de l'animation de départ
function launchIntro()
{
	//desactiveation logo
	$("#logo").removeClass('active');
	//on block le bouton du logo
	$("#drai a").live("click",function(){return false;});
	//on montre les boutons
	$("#intro_button").show('slow');
	$("#intro_button a").click(launchSite);
	//on cache les rub
	$("#menu>ul>li>a").css('opacity',0);
	//on cache les flags
	$("#flags").css('opacity',0);
	//on set le cookie d'intro
	//$.cookie('launch_intro', true, { path: '/', domain: window.location.host});
}

function launchSite()
{
	var default_hash = "home";
	//on donne la langue par default
	var lang = $(this).attr('lang');
	$('#body').data('lang',lang);
	$.post('/ajax/setAndGetMenuLocalization',{lang:lang},
			function(response)
			{
				if(response.validate)
				{
					//regénération du menu
					regenerateMenu(response.html);
					//set logo
					$("#drai a").attr('href',response.home_logo);
				}
			}
	);
	//on lance l'animation
	$("#logo").animate({bottom:"18px"},800).addClass('active');
	$("#drai").animate({marginTop:0},1200);
	$("#menu").animate({height:"282px"},1200,
			function()
			{
	             $("#flags").fadeTo(400,1);
				$("#container").css({border:'1px solid #4c2f1a'});
				$("#menu>ul>li>a").each
				(
					function(i)
					{
						$('body').removeClass('intro');
						$(this).fadeTo(600*(i/2),1);
					}
				);
			}
	);
	//on cache les boutons
	$("#intro_button").fadeOut(1200);
	//on lance un bind
	$.bbq.pushState('#!/'+lang+"/"+default_hash+'/accueil.html');
	//active du logo
	$("#logo").addClass('active');
	//on active le logo
	$("#drai a").die();
	//on casse l'écouteur du menu
	$("#menu ul li a").die().live('click',activeCategory);
}

//fonction regenerateMenu chargée de reformater le menu en fonction de la langue
function regenerateMenu(menu_json,hash)
{
	if(hash != null && hash != "")
	{
		var default_active = hash;
	}
	else
	{
		var default_active = "home";
	}
	//on récupère le menu formaté
	$("#menu").empty().append(menu_json);
	//on redéfinis les widths de chacuns
	$("#menu ul li a span").each(
		    function()
		    {
		      var parent_li_value = parseInt($(this).parent().parent().width());
		      var value_right = parseInt($(this).parent().parent().width())-$(this).width();
		      if($(this).parent().parent().attr('id') == 'network-menu') value_right -= 5;
		      $(this).parent().attr('original',value_right).css('width',$(this).width()+1+'px');
		      $(this).parent().css('marginRight',value_right+"px");
		    }
		);
	//stockage hash
    $("#menu ul li a:not([rel=slide])").each
    (
        function()
        {
          var final_hash = getHashAndSetLang($(this).attr('href'));
          //on donne un attribut dynamique au a
          $(this).attr('rev',final_hash);
          hash_array.push(final_hash);
        }
    );
    $("#menu ul li ul").css('display','none');
    //on active la bonne category
    activeManCategory(default_active);
    //rev
    $("a[rel=slide]").live('click',slideTo);
}

//fonction chargée de charger en ajax ce que l'user souhaite
function controllerLoading()
{
	var hash = location.hash;
	//si le hash est a null : on load la home
	if(hash == null || hash == "")
	{
	    hash = $('#drai a').attr('href');
	}
	var final_hash = getHashAndSetLang(hash);
	page_book = getIdSlide(hash);
	
	//si la langue change, on reload le menu
	if($("#body").data('lang') != lang)
	{
		$.post('/ajax/setAndGetMenuLocalization',{lang:lang},
				function(response)
				{
					if(response.validate)
					{
						//regénération du menu
						regenerateMenu(response.html,final_hash);
					}
				}
		);
		$("#body").data('lang',lang);
		
	}
	activeByControlCategory(final_hash);
	loadContent(final_hash);
}


//fonction chargée de charger le contenu ajax
function loadContent(hash)
{
		//on casse les animates
		$("#body>div").stop(true,true).css('width',0);
		activeManCategory(hash);
		//vidage du content et on le cache
	    $("#body").empty();
	    //loading ajax
		$.post('/ajax/loadPage',{hash:hash,lang:lang},
			function(data)
			{
				//on ajoute l'html au content
				$(data.html).appendTo("#body");
				//on cache les enfants
				$("#body>div").css({width:0,left:0});
				$("#left_wrap>img,#right_wrap>img").css('display','none');
				$("#wrapper").css('opacity',0.4).children().css('display','none');
				$('#body>div').css('width',0);
				$("#body").css('display','block');
				//on set les listeners si besoin
				if($("#book").length > 0)
				{
					initSlide();
				}
				//on lance l'animation
				animateContent(data.wrapper);
			}
		);
}

//fonction chargée d'animer le content. Réinit content et anim
function animateContent(url_bg_wrap)
{
	//on change les width des images
	$("#left_wrap>img").css('width',left_img_w*multiple+"px").css('marginLeft',-left_img_w*multiple+"px");
	$("#right_wrap>img").css('width',right_img_w*multiple+"px").css('marginLeft',+left_img_w*multiple+"px");
	//on lance l'anim des div
	$("#right_wrap").animate({width:right_wrap_width,backgroundColor:"#DFD3C0",left:right_wrap_position+"px"},1000,'linear');
	setTimeout(
	function()
	{
		$("#wrapper").animate({width:wrapper_width/1.5+"px",opacity:1,left:wrapper_position+20+"px"},1000,'linear',
				function()
				{
					$("#wrapper").animate({width:wrapper_width,left:wrapper_position+"px"},800);
				}
		);
		
	},600);
	setTimeout(function(){$("#left_wrap").animate({width:left_wrap_width,opacity:1,left:left_wrap_position+"px"},1000,'easeOutQuart',
			function()
			{
				//opactiy container
				$("#wrapper").css({opacity:0.1,backgroundImage:'url('+url_bg_wrap+')'},400);
				//on lance l'affichage des images
				$("#left_wrap>img,#right_wrap>img").fadeIn(400);
				$("#left_wrap>img").animate({width:left_img_w,marginLeft:0},600);
				$("#right_wrap>img").animate({width:right_img_w,marginLeft:0},600);
				$("#wrapper").animate({opacity:1},600,
						function()
						{
							//on affiche le content
							$("#wrapper").children().fadeIn();
						}
				);

			}
	)},1200);
}

//fonction activant manuellement la bonne category
function activeManCategory(hash)
{
	if($('.active_cat').length == 0 && $(".sub_cat_active").length == 0)
	{
		$('a[rev='+hash+"]").addClass('active_cat').animate({marginRight:"6px"},400);
		if($('a[rev='+hash+"]").parent().children('ul').length != 0)
	    {
		  var my_a_child = $('a[rev='+hash+"]");
	      showSubCategory(my_a_child);
	    }		
	}
}

//fonction pour les boutons prec & next navigateur
function activeByControlCategory(hash_final)
{
	var hash_id = hash_final;
	//init menu
    var original_pos = $('.active_cat').attr('original');
    $('.active_cat').parent().children('ul').slideUp();
    $(".separator_ul").remove();
    $('.active_cat').removeClass().animate({marginRight:original_pos+"px"},400);
    $('a[rev='+hash_id+"]").addClass('active_cat').animate({marginRight:"6px"},400);	
	//affichage cat
	$('a[rev='+hash_id+"]").addClass('active_cat').animate({marginRight:"6px"},400);
	if($('a[rev='+hash_id+"]").parent().children('ul').length != 0)
    {
	  var my_a_child = $('a[rev='+hash_id+"]");
      showSubCategory(my_a_child);
    }	
}

//fonction chargée d'activer la categorie a partir d'un lien interne
function activeIntCategory(hash_final)
{
//	var href_site = $(this).attr('href');
//	var hash_id = getHashAndSetLang(href_site);
//	//init menu
//    var original_pos = $('.active_cat').attr('original');
//    $('.active_cat').parent().children('ul').slideUp();
//    $(".separator_ul").remove();
//    $('.active_cat').removeClass().animate({marginRight:original_pos+"px"},400);
//    $(this).addClass('active_cat').animate({marginRight:"6px"},400);	
//	//affichage cat
//	$('a[rev='+hash_id+"]").addClass('active_cat').animate({marginRight:"6px"},400);
//	if($('a[rev='+hash_id+"]").parent().children('ul').length != 0)
//    {
//	  var my_a_child = $('a[rev='+hash_id+"]");
//      showSubCategory(my_a_child);
//    }
}
//fonction activant la catégory slide
function activeCategorySlide(hash)
{
	if(!$('#menu a[href=#'+hash+"]").hasClass('sub_cat_active'))
	{
		var original_pos = $('.sub_cat_active').attr('original');
		$('.sub_cat_active').removeClass().animate({marginRight:original_pos+"px"},400);
		$("#menu a[href=#"+hash+"]").addClass('sub_cat_active').animate({marginRight:"6px"},400);
	}	
}

//fonction chargée de gérer les rubriques de niveau 1
function activeCategory()
{
  if(!$(this).hasClass('active_cat') && !$(this).hasClass('sub_cat_active'))
  {
    //on regarde si le lien a un parent ou non et on désactive eventuellemnt une sous rubrique
    if($(this).parent().parent().prev('a').hasClass('active_cat'))
    {
      var original_pos = $('.sub_cat_active').attr('original');
      $('.sub_cat_active').removeClass().animate({marginRight:original_pos+"px"},400);
      $(this).addClass('sub_cat_active').animate({marginRight:"6px"},400); 
    }
    else
    {
//      var original_pos = $('.active_cat').attr('original');
//      $('.active_cat').parent().children('ul').slideUp();
//      $(".separator_ul").remove();
//      $('.active_cat').removeClass().animate({marginRight:original_pos+"px"},400);
//      $(this).addClass('active_cat').animate({marginRight:"6px"},400);
//      if($(this).parent().children('ul').length != 0)
//      {
//        showSubCategory(this);
//      }
    }
    
    //si on est sur un control des slide on retourne false
    if($(this).attr('rel') != "" && $(this).attr('rel') != null)
    {
      return false;
    } 
  }
  else
  {
      return false;
  }
}

//fonction chargée de montrer les sous rubriques
function showSubCategory(a_child)
{
		$(a_child).next().children('li:first-child').children('a').before('<div class="separator_ul" id="top_sep"></div>');
  		$(a_child).next().children('li:last-child').append('<div class="separator_ul" id="bot_sep"></div>');
  		$('.separator_ul').css('opacity',0);
  		$(a_child).next().slideDown(800,
		  function()
		  {
	  		$(".separator_ul").fadeTo(400,1);
		  }
  		);
  		var pos_o = $(".sub_cat_active").attr('original');
  		$(".sub_cat_active").removeClass().animate({marginRight:pos_o+"px"},400);
}



//fonction chargée de retourner le bon hash et set la langue
function getHashAndSetLang(hash)
{
    var href = hash.replace("http://"+window.location.host,'');
    var reg = new RegExp('#?\/?([A-Za-z]+\-?[A-Za-z]*)+\/?([A-Za-z]+\-?[A-Za-z]*)+\/?');
    var tab = reg.exec(href);
    //on retire les slashs
    lang = tab[1];
    var final_hash = tab[2].replace('/','');
    final_hash = final_hash.replace('/','');
    return final_hash;
}

//fonction chargée de récupérée l'id du slide
function getSlideHash(hash)
{
	if(hash != null && hash != "")
	{
		var reg = new RegExp('#+([A-Za-z]+\-?[A-Za-z]*)+');
		var tab = reg.exec(hash);
		return tab[1];
	}
}

//Fonction chargée de voir si un id est dans l'url
function getIdSlide(hash)
{
	if(hash != null && hash != "")
	{
		var reg = new RegExp('\/{1}!{1}([A-Za-z]+\-?[A-Za-z]*)+');
		var tab = reg.exec(hash);
		if(tab != null)
		{
			return tab[1];
		}
		else
		{
			return null;
		}
	}	
}

function mailTo(event)
{
	event.stopImmediatePropagation();
}
/*******************************Gestion SLIDE*************************************/

// Gestion du swipe sur iPad

// Enregistrement de l'élément
function onSwipe(elmt, f_callback)
{
	
}


//function initSlide
function initSlide()
{
	//liens internes
	$(".one_page a[rev=ajax_slide]").click(activeIntCategory);
	$(".one_page .link_mail_to").click(mailTo);
	//for IE..
	$('.learn_more').attr('href',"#"+$('.learn_more').attr('rev'));
	$(".learn_more").live('click',slideTo);
	$(".controls_slide").click(slideBook).css('opacity',0);
	//multiplicateur
	$('.one_page').each(
		function(i)
		{
			$(this).attr('multiple',i);
		}
	);
	//listener du mouseouver (page suivante, precente...)
	$(".controls_slide a").addClass('active_mobile');
	if($.browser.SafariMobile)
	{
	  $(".controls_slide a").addClass('active_mobile');
	}
	
	//listener lien intérieurs
	
	//container
	var width_book = $('.one_page').width();
	var nb_page = $('.one_page').length;
	$("#book").css('width',width_book*nb_page+"px");
	//initialisation de la page à insérer
	if(page_book != null)
	{
		firstPageToInitSlide(page_book);
		$(".controls_slide").fadeIn('slow');
	}
	else
	{
		//premier slide active
		$(".one_page:first-child").addClass('active_slide');
		//ecouteurs
		$("#right_control").fadeTo(400,1);
	}
	
}

function showcontrols(controls)
{
  if(controls == "left")
  {
    $("#left_control").children('a').addClass('active');
  }
  else
  {
    $("#right_control").children('a').addClass('active');
  }
}

function disableControls()
{
  $(".controls_slide a").removeClass('active');
}

function slideBook(movment)
{
	if($(this).attr('id') == "right_control" || movment == "right")
	{
		//on vérifie qu'il y a bien un next
		if($('.active_slide').next().hasClass('one_page'))
		{
			var multiple = $('.active_slide').next().attr('multiple');
			var width_book = $('.one_page').width();
			//on définis le nouvel active
			$('.active_slide').removeClass('active_slide').next().addClass('active_slide');

			$("#book").animate({marginLeft:-multiple*width_book},500,
				function()
				{

				}
			);
		}
	}
	else
	{
		//on vérifie qu'il y a bien un next sinon on retourne au départ
		if($('.active_slide').prev().hasClass('one_page'))
		{
			var multiple = $('.active_slide').prev().attr('multiple');
			var width_book = $('.one_page').width();
			//on définis le nouvel active
			$('.active_slide').removeClass('active_slide').prev().addClass('active_slide');

			$("#book").animate({marginLeft:-multiple*width_book},500,
				function()
				{
					
				}
			);		
		}
		else
		{
			$('.active_slide').removeClass('active_slide');
			$('.one_page:first-child').addClass('active_slide');
			$("#book").animate({marginLeft:0},500);
		}			
	}
	//on verifie qu'il y a un prev.
	if($('.active_slide').prev().hasClass('one_page'))
	{
		$('#left_control').removeClass('disable').fadeTo(400,1);
	}
	else
	{
		$("#left_control").addClass('disable').fadeTo(400,0);
	}
	
	//on verifie qu'il y a un prev.
	if($('.active_slide').next().hasClass('one_page'))
	{
		$('#right_control').removeClass('disable').fadeTo(400,1);
	}
	else
	{
		$("#right_control").addClass('disable').fadeTo(400,0);
	}
	
	//on regarde si la rub est active dans le menu
	var href_to_act = $('.active_slide').attr('id');
	activeCategorySlide(href_to_act);
	return false;
}

//fonction chargée de gérer le slide des cachiers présents
function slideTo()
{
	var id_to_slide = getSlideHash($(this).attr('href'));
    //récupération multiple && width
    var multiple = $("#"+id_to_slide).attr('multiple');
    var width_book = 590;
    //suppression ancien active
    $('.active_slide').removeClass('active_slide');
    //mise en place nouvel active
    $("#"+id_to_slide).addClass('active_slide');
    //animate
    $("#book").animate({marginLeft:-multiple*width_book},500);

	return false;
}

//fonction init Slide To
function firstPageToInitSlide(id_to_slide)
{
	var id_to_slide = id_to_slide;
    //récupération multiple && width
    var multiple = $("#"+id_to_slide).attr('multiple');
    var width_book = $("#"+id_to_slide).width();
    //suppression ancien active
    $('.active_slide').removeClass('active_slide');
    //mise en place nouvel active
    $("#"+id_to_slide).addClass('active_slide');
    //animate
    $("#book").animate({marginLeft:-multiple*width_book},500);
    
    //url interne du slide
    activeCategorySlide(id_to_slide);
}
//fonction imitant la fonction in_array php
function in_array(value,tab)
{
  for(one_value in tab)
  {
    if(tab[one_value] == value)
    {
      return true;
    }
  }
  
  return false;
}

/*********************************Plugin JQUERY SAFARI************************/
jQuery.extend(jQuery.browser,
	{SafariMobile : navigator.userAgent.toLowerCase().match(/iP(hone|ad)/i) }
	);
