var img_default = 'images/im_home.jpg';
jQuery.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];
  }
});
jQuery.fn.menuHorizontal = function(o) {

  var o = jQuery.extend( {
    speed: 'normal',
    mode: 'click',
    imgdefault: 'im_home.jpg',
    colorlink: '#919191',
    colorlinkactif: '#b6121d'
  },o);
  var index_menu_deroule = null;
  var menu_deroule = null;

	function clickOnTitle(){
		if(menu_deroule){
			if(index_menu_deroule != jQuery(this).parent('.titre_menu').attr('rel') ) {
				menu_deroule.slideUp(o.speed);
				menu_deroule.parent('.titre_menu').children('a').css('color', o.colorlink);
				index_menu_deroule = jQuery(this).parent('.titre_menu').attr('rel');
				menu_deroule = jQuery(this).parent('.titre_menu').children('.sous_menu');
				menu_deroule.slideDown(o.speed);
				jQuery(this).css('color', o.colorlinkactif);
				$("#langues").animate({ 'height': "44px"}, 1000 );
				table_langues_deroule = false;
				
			} else {
				menu_deroule.slideUp(o.speed);
				menu_deroule = null;
			}
		} else  {
			index_menu_deroule = jQuery(this).parent('.titre_menu').attr('rel');
			menu_deroule = jQuery(this).parent('.titre_menu').children('.sous_menu');
			menu_deroule.slideDown(o.speed);
			jQuery(this).css('color', o.colorlinkactif);
			$("#langues").animate({ height: "44px"}, 1000 );
			table_langues_deroule = false;
		}
		return false;
	}

	function mouseOnTitle(){
		if(menu_deroule){
			if(index_menu_deroule != jQuery(this).parent('.titre_menu').attr('rel') ) {
				menu_deroule.slideUp(o.speed);
				menu_deroule.parent('.titre_menu').children('a').css('color', o.colorlink);
				index_menu_deroule = jQuery(this).parent('.titre_menu').attr('rel');
				menu_deroule = jQuery(this).parent('.titre_menu').children('.sous_menu');
				menu_deroule.slideDown(o.speed);
				jQuery(this).css('color', o.colorlinkactif);
				$("#langues").animate({ height: "44px"}, 1000 );
				table_langues_deroule = false;
			}
		} else  {
			index_menu_deroule = jQuery(this).parent('.titre_menu').attr('rel');
			menu_deroule = jQuery(this).parent('.titre_menu').children('.sous_menu');
			menu_deroule.slideDown(o.speed);
			jQuery(this).css('color', o.colorlinkactif);
			$("#langues").animate({ height: "44px"}, 1000 );
			table_langues_deroule = false;
		}
		return false;
	}

	function mouseOutSubMenu(){
		if(menu_deroule){
			menu_deroule.stop(true,true);  
			menu_deroule.slideUp(o.speed);
			menu_deroule.parent('.titre_menu').children('a').css('color', o.colorlink);
			menu_deroule = null;
			if(  $('#affichee').attr('src') != o.imgdefault ){
				$('#affichee').hide();
				$('#affichee').attr('src', o.imgdefault);
				$('#affichee').show();
			}
		}
		return false;
	}


	return this.each(function() {
		jQuery(this).children('.titre_menu').children('.sous_menu').hide();
		if (o.mode == 'click'){
			jQuery(this).children('.titre_menu').each(
				function(index){
					jQuery(this).attr( 'rel', index );
					jQuery(this).children('a').click(clickOnTitle );
				}
			);
		}
		if (o.mode == 'roll_close_on_out'){
			jQuery(this).children('.titre_menu').each(
				function(index){
					jQuery(this).attr( 'rel', index );
					jQuery(this).children('a').mouseover(mouseOnTitle );
					jQuery(this).mouseleave(mouseOutSubMenu );
				}
			);
		}
		if (o.mode == 'roll_no_close_on_out'){
			jQuery(this).children('.titre_menu').each(
				function(index){
					jQuery(this).attr( 'rel', index );
					jQuery(this).children('a').mouseover(mouseOnTitle );
				}
			);
		}
	});
};

jQuery.fn.imgChange = function(o) {
	var o = jQuery.extend( {
		speed: 'normal',
		imgdefault: 'images/default.jpg'
	},o);


	function mouseOnLink(){
		imgsrc = jQuery(this).attr('rel');
		if(imgsrc != $('#affichee').attr('src')){
			$('#affichee').stop(true,true);
			$('#affichee').attr('src',imgsrc);
		}
		return false;
	}
	return this.each(function() {
		jQuery(this).mouseover(mouseOnLink ) ;
	});
};

$(document).ready(function() {
	var table_langue_height;
	var dim_image_left = [2000,1800];  //[w , h]
	var dim_image_left_min = [400,360];  //[w , h]
	var dim_image_h_logo = 88;  //h
	var max_width_menu = 576;
	var secureMargins = 12;

	function rebind(){
		var wmtemp = Math.min( max_width_menu , parseInt( $('#right').width() ) );
		var newWidthMenu = (wmtemp-secureMargins);
		var newWidthRow = ((Math.round(wmtemp/3))-secureMargins);
		$('#menu').css('width', newWidthMenu );
		$('#mainmenu a').css('width', newWidthRow );
		$('#mainmenu a span').css('width', newWidthRow );
		$('.sous_menu').css('width', newWidthRow );
		$('#mainmenu').menuHorizontal( { mode: 'roll_close_on_out', imgdefault: img_default } );
		$(".change_img").imgChange({ speed: 'fast', imgdefault: img_default });
	};

	function getXmlCode(){
		var xmlCode;
		try {
			var countryCode = $.getUrlVar("m")
			if (countryCode == undefined) countryCode = geoip_country_code();
			var lang = $.getUrlVar("l");
			if (lang == undefined) lang = navigator.userLanguage ? navigator.userLanguage : navigator.language;
			xmlCode = xmlCodes[countryCode + "_" + lang.substring(3,5).toUpperCase()];
			if(xmlCode == undefined) xmlCodes[countryCode + "_" + lang.substring(0,2).toUpperCase()];
			if(xmlCode == undefined) xmlCode = xmlCodes[countryCode];
		}catch (e){ }
			if(xmlCode == undefined) xmlCode = "INT_EN";
		return xmlCode;
	}
	function createMenu(menuData, actuLabel){
		var menu = $("<li class='titre_menu'><a href='#'><span>"+menuData.find("menu_title").text()+"</span></a><ul class='sous_menu'></ul></li>");
		var submenu = menu.find(".sous_menu");
		appendSubMenu(submenu, menuData.find("item"));
		var news = menuData.find("new");
		if (news.length > 0) submenu.append("<li><span class='actu'>"+actuLabel+"</span></li>");
		appendSubMenu(submenu, news);
		return menu;
	}
	function appendSubMenu(submenu, items){
		items.each(function() {
			submenu.append("<li class='change_img' rel='"+$(this).find("img").text()+"'><a href='"+$(this).find("link").text()+"'>"+$(this).find("title").text()+"</a></li>");
			if(navigator.userAgent.match(/iPad/i) == null && navigator.userAgent.match(/iPhone/i) == null){
				$('#image_left').append('<img src="' + $(this).find("img").text() + '" alt="-" class="img_preload" />' );
			}
		});
	}
	function loadMenu(xmlCode){
		$.ajax({
			type: "GET",
			url: "xml/marche_"+xmlCode+".xml",
			dataType: "xml",
			success: function(xml){
				var main = $("<ul id='mainmenu'></ul>")
				img_default = $(xml).find("img_defaut").text()
				var actuLabel = $(xml).find("trad_actu").text();
				$("#your_country").text($(xml).find("trad_votre_pays").text());
				$('#votre_pays').html ( $(".load_lang[rel="+xmlCode+"]").attr('country') );
				$('#image_left').html("");
				$('#image_left').append('<img src="' + img_default + '" alt="-" id="affichee" />');
				$(xml).find("menu").each(function() {
					main.append(createMenu($(this), actuLabel));
				});
				$("#menu").append(main);
				rebind();
				updateMenu();
			}
		});
	}
	function rebindLangues(){
		$('.load_lang').click(function() {
			$('#menu').html('');
			loadMenu($(this).attr('rel'));
			return false;
		});
		var table_langues_deroule = false ;
		var table_langues_deroule_timer = null ;
		var id_continent_deroule = 'O';
		$('#table_langues div').hide();
		table_langue_height = $("#langues").height();
		$('#langues').css('visibility', 'visible' );
		$("#langues").css('height','44px');
		$('#langues').mouseover(function() {
			if (!table_langues_deroule){
				$("#langues").animate({ height: table_langue_height+"px"}, 1000 );
				table_langues_deroule = true;
			} else {
				if(table_langues_deroule_timer != null){
					clearTimeout(table_langues_deroule_timer);
				}
			}
			return false;
		});
		$('#langues').mouseleave(function(){
			if(table_langues_deroule){
				table_langues_deroule_timer = setTimeout(function() {
				$('#langues').stop(true,true);
				if ( table_langues_deroule ){
					$("#langues").animate({ height: "44px"}, 1000 );
					table_langues_deroule = false;
				}
				return false; },1000);
			}
		});
		$('.show_continent').click(function() {
			if ( id_continent_deroule != jQuery(this).attr('id') ){
				$( '#detail_'+id_continent_deroule ).hide();
				$('#' +id_continent_deroule ).css('color', '#919191' )
				$('#toremove').remove();
				$( '#detail_'+ jQuery(this).attr('id')  ).slideDown('low');
				id_continent_deroule = jQuery(this).attr('id');
				$('#' +id_continent_deroule ).css('color', '#000000' );
				jQuery(this).append('<img src="ui_images/fleche_droite.png" alt="->" id="toremove" />');
			}
			return false;
		});
	};


	var trunkTitles = {
		saveWidthTab : [],
		saveCharPos : [],
		extrTxt : [],
		headLinksTab : [],
		strtoArray : [],
		set : function(o, maxElmtWd){
			
			this.headLinksTab = o;
			for(var i=0; i<this.headLinksTab.length; i++) {
				this.extrTxt[i] = this.getTextNode(this.headLinksTab[i].innerHTML);
				this.strtoArray[i] = this.extrTxt[i].split('');
				this.saveWidthTab[i] = 0;
				this.saveCharPos[i] = new Array();
				for(var j=0; j<this.strtoArray[i].length; j++) {
					if (this.strtoArray[i][j]==' ') this.saveCharPos[i].push(j);
					this.ephem(this.strtoArray[i][j], i);
					//document.body.removeChild(o);
				}
			}

			var cut = false;
			for(var i=0; i<this.saveWidthTab.length; i++) {
				if (this.saveWidthTab[i]>maxElmtWd) cut=true;
			}

			if (cut) {
				if((this.extrTxt[0].search('<br/>')>=0) || (this.extrTxt[0].search('<br>')>=0) || (this.extrTxt[0].search('<br />')>=0) || (this.extrTxt[0].search('<BR>')>=0) ){
					return;
				}
				for(var i=0; i<this.saveCharPos.length; i++) {
					var indoxOfPos = (this.getNearestNumber(this.saveCharPos[i], (Math.ceil(this.strtoArray[i].length/2)) ));
					var newData = this.dataWork(this.extrTxt[i], indoxOfPos, i);
					this.headLinksTab[i].innerHTML = newData;
				}
			} else {
				for(var i=0; i<this.strtoArray.length; i++) {
					var newtxt = this.extrTxt[i].replace('<br/>','');
					newtxt = newtxt.replace('<br>','');
					newtxt = newtxt.replace('<BR>','');
					newtxt = newtxt.replace('<br />','');
					this.headLinksTab[i].innerHTML = newtxt;
				}
			}
			$('.spanTemp').remove();
		},
		ephem : function(data, n) {
			var sp = document.createElement('span');
			document.getElementById('tempSpan').appendChild(sp);
			sp.className = 'spanTemp';
			sp.style.visibility = 'hidden';
			var txt = document.createTextNode(data);
			sp.appendChild(txt);
			var spOW = parseFloat(sp.offsetWidth);
			this.saveWidthTab[n] += ((spOW==0)? 4: spOW);
			return;
		},
		getNearestNumber : function(tab, n, i){
			if((l = tab.length) < 2)
				return l - 1;
			for(var l, p = Math.abs(tab[--l] - n); l--;) {
				if(p < (p = Math.abs(tab[l] - n))) break;
			}
			return l + 1;
		},
		dataWork : function(data, index, i){
			var txt = document.createTextNode(data);
			txt.insertData(this.saveCharPos[i][index],'<br/>');
			return txt.data;
		},
		getTextNode : function(data){
			var txt = document.createTextNode(data);
			var newData = txt.data.replace('<br/>','');
			newData = newData.replace('<br>','');
			newData = newData.replace('<BR>',' ');
			newData = newData.replace('<br />','');
			return newData;
		}
	}

	function updateMenu(){
		if(parseInt( $('#global').height() ) > parseInt( $(window).height() )){
			himage = Math.min( dim_image_left[1] , parseInt( $('#global').height() ) );
		}else{
			himage = Math.min( dim_image_left[1] , parseInt( $(window).height() ) );
		}
		himage = Math.max( dim_image_left_min[1] , himage );
		wimage = himage * ( dim_image_left[0] / dim_image_left[1] )
		$('#image_left img').css('width', wimage );
		$('#image_left img').css('height', himage );
		max_fen = Math.min( dim_image_left[1] , $(window).height());
		max_fen = Math.max( dim_image_left_min[1] , max_fen );

		wmtemp = Math.min( max_width_menu , parseInt( $('#right').width() ) );
		var newWidthMenu = (wmtemp-secureMargins);
		var newWidthRow = ((Math.round(wmtemp/3))-secureMargins);
		$('#menu').css('width', newWidthMenu );
		$('#mainmenu a').css('width', newWidthRow );
		$('#mainmenu a span').css('width', newWidthRow );
		$('.sous_menu').css('width', newWidthRow );
		trunkTitles.set( $('.titre_menu a span'), newWidthRow);
	}
	loadMenu(getXmlCode());
	$('#mainmenu').menuHorizontal( { mode: 'roll_close_on_out', imgdefault: img_default } );

	$(window).resize(function() { updateMenu(); });
	
	$(".change_img").imgChange({ speed: 'normal', imgdefault: img_default });
	rebindLangues();
});


