// JavaScript Document
$(document).ready(function() {
	
	// diminution de la largeur du template suivant la rÃ©solution de l'ecran
	//var widthWin = $(document).width();
	var widthWin = $(window).width();
	if(widthWin <= 1024){
		$('body').addClass('R1024');
		////
		$('.bgBox').each(function(index) {
			var bg = $(this).attr('style');
		    var newBg = '';
		    if(bg.search('bandeau/home') != -1){newBg = bg.replace("bandeau/home","bandeau/home/mini");}
		    else{
		    	if(bg.search('bandeau') != -1){newBg = bg.replace("bandeau","bandeau/mini");}
		    }
		    //alert(bg + '\n' + newBg);
		    if(newBg != ''){
		    	$(this).attr('style', newBg);
		    }
		  });
		
		$('.imgBox').each(function(index) {
			var imgSrc = $(this).attr('src');
			var newSrc = '';
			
			if(imgSrc.search('focus') != -1){ newSrc = imgSrc.replace('focus','focus/mini');}
			if(imgSrc.search('tv_hebdo') != -1){ newSrc = imgSrc.replace('tv_hebdo','tv_hebdo/mini');}
			if(imgSrc.search('notre_equipe') != -1){ newSrc = imgSrc.replace('notre_equipe','notre_equipe/mini');}
			//alert(newSrc + '\n' + imgSrc);
			if(newSrc != ''){
				$(this).attr('src', newSrc);
			}
		  });
	}
	////////////////////////////////////////////////////////////////////////////
	////// 
	$('.readMore[rel!=dontinit]').click(function(){
		$('.voile').fadeIn();
		$('.popup').show();
		$('#loader').show();
	});
	////// ### Popup
	$('.playVideo').click(function(){
		$('.voile').fadeIn();
		$('.popup').show();
		$('#loader').show();
	});
						   
	$('div[class="popup"] .close').click(function(){
		$('.popup').hide(function(){
			$('.voile').fadeOut();
			$('.popupBG').fadeOut();
			$('.popup iframe').remove();
		})
	});
	$('.popupBox .close').click(function(){
		//$('.popup').hide(function(){
			$('.voile').fadeOut();
			$('.popupBG').fadeOut();
		//})
	});
	//////////////////////////////////////////////
	////// ### Flash Popup
	/*$('.flashBox').click(function(){
		$('.voile').fadeIn(function(){
			$('.popupFlash').slideDown(function(){
				$('.popupFlashContent').fadeIn();
			});
		});
	});*/
	
	$('.popupFlash .close').click(function(){
		$('.popupFlashContent').fadeOut(function(){
			$('.popupFlash').slideUp(function(){
				$('.voile').fadeOut();
			});
		});
	});
	
	$('.voile').click(function(){
		$('.popupFlashContent').fadeOut(function(){
			$('.popupFlash').slideUp(function(){
				$('.voile').fadeOut();
			});
		});
	});
	//////////////////////////////////////////
	///// ### Sub menu (Level 2 and level 3)
	$('.menuBox li').click(function(){
		$('.menuBoxLevel2').hide();
		$(this).children('.menuBoxLevel2').show();
	});
	
	$('.menuBoxLevel2 li').click(function(){
		$('.menuBoxLevel3').hide();
		$(this).children('.menuBoxLevel3').show();
	});
	//////
	///// ### Sub menu (Level 2 and level 3)
	$('.menuLevel1 > li').hover(
		function(){
			$('.menuArea .subContentBox').hide();
			$(this).find("div").show();
			$(this).find("> div > ul").show();
		},
		function(){
			$('.subContentBox').hide();
		}
	);
	$('li.axebsubmenu').hover(
			function(){
				$(this).find("ul").show();
			},
			function(){
				$(this).find("ul").hide();
			}
	);
	$('.upMenuOverlay > li').hover(
			function(){
				$('.upSubmenu').hide();
				$(this).find(".upSubmenu").show();
			},
			function(){
				$('.upSubmenu').hide();
			}
		);
	$('li.sub').hover(
			function(){
				$(this).find("ul").show();
			},
			function(){
				$(this).find("ul").hide();
			}
	);
	$('.menuBoxLevel2 > li').click(function(){
		$('.menuBoxLevel3').hide();
		$(this).children('.menuBoxLevel3').show();
	});
	//////////////////////////////////////
	$('#ThemeLinksSelect').change(function(){
		if($(this).val() == 'all'){
			$('.linksDT').show();
			$('.linksDD').show();
		}else{
			$('.linksDT').hide();
			$('.linksDD').hide();
			$('.linkDT'+$(this).val()).show();
			$('.linkDD'+$(this).val()).show();
		}
	});
	
	/////////////////////////////
	$('.iClientPuce').toggle(
		function(){
			$(this).css('background-position','left bottom');
			//$(this).next('div').children('.iClientBox').hide();
			$(this).parent().find('.iClientBox').hide();
		},
		function(){
			$(this).css('background-position','left top');
			//$(this).next('div').children('.iClientBox').show();
			$(this).parent().find('.iClientBox').show();
		});
///////////////////////////
		resizeIclients();
		ActivateIclientTooltip() ;
});

var maxH = 0;
function resizeIclients(){
	$('.iClientBoxBody').each(function(index) {
		iClientBox  = $(this).find('.iClientBox');

		hBoxIClient = iClientBox.height();
		if(maxH < hBoxIClient){
			maxH = hBoxIClient;
		}
		if(index % 2 == 0){
			HFBox = iClientBox.height();
			FObj = iClientBox;
		}else{
			HSBox = iClientBox.height();
			SObj = iClientBox;
			if(HSBox < HFBox){maxH = HFBox;}else{maxH = HSBox;}
			FObj.css('min-height',maxH+'px');
			SObj.css('min-height',maxH+'px');
			maxH = 0;
		}
	 });	
}

/**
 * Cette fonction permet de charger les lien passÃ© en parametre "url" 
 * dans un endroit bien dÃ©terminÃ© celui qui passe en parametre "dom"
 */
function loadPopup(url, dom, popup){$(".voile").fadeIn();$('#loader').css('display','block');$(dom).hide();$(dom).load(url,function(){$(dom).show();$(popup).centerScreen();$('#loader').hide();});$(popup).show();$(popup).centerScreen();}

function ajaxLoad(url, dom){
	$('#loaderIcon2').css('display','inline-block');
	//$(dom).hide();
	$(dom).load(url,function(){
		$(dom).fadeOut(100).delay(100).fadeIn(300);
		$('#loaderIcon2').hide();
	});
}
/**
 * loadExistantPopup
 * Permet l'affichage d'un div (dom) Existant, sous la forme d'un lightbox (popUp)
 */
function loadExistantPopup(dom, popup){$(dom).show();$(popup).show();$(".popupBox").centerScreen()}

/**
 * centerScreen
 * Permet l'auto-centrage d'un popup.
 * $("#div").centerScreen();
 */

$(document).ready(function() {
    jQuery.fn.centerScreen = function(loaded) {
    		var widthWin = $(window).width();
            var obj = this;
            var objChild = obj.children('div');
            if(!loaded) {
            		if(this.height() < $(window).height()){
            			obj.css('top', $(window).height()/2-this.height()/2+"px");
            			obj.css('left', $(window).width()/2-this.width()/2+"px");
            		}else{
            			var h = $(window).height() - 80;
            			//obj.css('max-height', h+"px");
            			objChild.css('max-height', h+"px");
            			objChild.css('overflow-y', "scroll");
            			obj.css('top', "40px");
            			obj.css('left', $(window).width()/2-this.width()/2+"px");
            		}
                    
                    $(window).resize(function(){ obj.centerScreen(!loaded); });
            } else {
                    obj.stop();
                    obj.animate({ top: $(window).height()/2-this.height()/2, left: $(window).width()/2-this.width()/2}, 200, 'linear');
            }
    }
});

/*
 * Fonction qui permet d'ouvrir et de fermer un div 
 * Cette fonction est utilisé dans le service Chiffres clés
 */

function tableau(idTr,afficher, ancre){
	if (afficher == 0){
		document.getElementById('trDetail' + idTr).style.display = 'none';
		document.getElementById('trLienAfficherDetail' + idTr).style.display = '';
		document.getElementById('trLienCacherDetail' + idTr).style.display = 'none';
		if (ancre == 1){window.location = '#' + idTr;}
	} else {
		document.getElementById('trDetail' + idTr).style.display = '';
		document.getElementById('trLienAfficherDetail' + idTr).style.display = 'none';
		document.getElementById('trLienCacherDetail' + idTr).style.display = '';
	}

}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function YY_checkform() { //v4.71
//copyright (c)1998,2002 Yaromat.com
  var a=YY_checkform.arguments,oo=true,v='',s='',err=false,r,o,at,o1,t,i,j,ma,rx,cd,cm,cy,dte,at;
  for (i=1; i<a.length;i=i+4){
	if (a[i+1].charAt(0)=='#'){r=true; a[i+1]=a[i+1].substring(1);}else{r=false}
	o=MM_findObj(a[i].replace(/\[\d+\]/ig,""));
	o1=MM_findObj(a[i+1].replace(/\[\d+\]/ig,""));
	v=o.value;t=a[i+2];
	if (o.type=='text'||o.type=='password'||o.type=='hidden'){
	  if (r&&v.length==0){err=true}
	  if (v.length>0)
	  if (t==1){ //fromto
		ma=a[i+1].split('_');if(isNaN(v)||v<ma[0]/1||v > ma[1]/1){err=true}
	  } else if (t==2){
		rx=new RegExp("^[\\w\.=-]+@[\\w\\.-]+\\.[a-zA-Z]{2,4}$");if(!rx.test(v))err=true;
	  } else if (t==3){ // date
		//ma=a[i+1].split("#");at=v.match(ma[0]);
		  ma=a[i+1].split("#");at=v.match('^\([0-9][0-9]\)\/\([0-9][0-9]\)\/\([0-9]{4}\)$');
		if(at){
		  cd=(at[ma[1]])?at[ma[1]]:1;cm=at[ma[2]]-1;cy=at[ma[3]];
		  dte=new Date(cy,cm,cd);
		  if(dte.getFullYear()!=cy||dte.getDate()!=cd||dte.getMonth()!=cm){err=true};
		}else{err=true}
	  } else if (t==4){ // time
		ma=a[i+1].split("#");at=v.match(ma[0]);if(!at){err=true}
	  } else if (t==5){ // check this 2
			if(o1.length)o1=o1[a[i+1].replace(/(.*\[)|(\].*)/ig,"")];
			if(!o1.checked){err=true}
	  } else if (t==6){ // the same
			if(v!=MM_findObj(a[i+1]).value){err=true}
	  }
	} else
	if (!o.type&&o.length>0&&o[0].type=='radio'){
		  at = a[i].match(/(.*)\[(\d+)\].*/i);
		  o2=(o.length>1)?o[at[2]]:o;
	  if (t==1&&o2&&o2.checked&&o1&&o1.value.length/1==0){err=true}
	  if (t==2){
		oo=false;
		for(j=0;j<o.length;j++){oo=oo||o[j].checked}
		if(!oo){s+='* '+a[i+3]+'\n'}
	  }
	} else if (o.type=='checkbox'){
	  if((t==1&&o.checked==false)||(t==2&&o.checked&&o1&&o1.value.length/1==0)){err=true}
	} else if (o.type=='select-one'||o.type=='select-multiple'){
	  if(t==1&&o.selectedIndex/1==0){err=true}
	}else if (o.type=='textarea'){
	  if(v.length<a[i+1]){err=true}
	}
	if (err){s+='* '+a[i+3]+'\n'; err=false}
  }
  if (s!=''){alert('Certaines informations sont incomplètes ou erronées:\t\t\t\t\t\n\n'+s)}else{
	  document.forms.form.submit();
  }
  document.MM_returnValue = (s=='');
}


/*
 * Fonction qui permet d'ouvrir un pop
 * Cette fonction est utilisé dans le service Chiffres clés
 */

function ur(url,nom,w,h,features)
{ 
t=(screen.height - h)/2;
l=(screen.width - w)/2;
center=("top="+t+",left="+l+",width="+w+",height="+h+","+features);
window.open(url,nom,center);
}

function displayPlan() { 
	obj = document.getElementById('plans');
	var currentlyDisplayed = document.getElementById('displayed_plan').value;
	document.getElementById('i' + currentlyDisplayed).style.display = 'none';
	document.getElementById('j' + currentlyDisplayed).style.display = 'none';
	currentlyDisplayed = obj.options[obj.selectedIndex].value;
	document.getElementById('i' + currentlyDisplayed).style.display = '';
	document.getElementById('j' + currentlyDisplayed).style.display = '';
	document.getElementById('displayed_plan').value = document.getElementById('plans').value;
}
$(document).ready(function(){
	$('.searchTextHeader[rel!="dontinit"], .searchText[rel!="dontinit"]').attr('value','Rechercher');
	$('.searchTextHeader, .searchText').click( function(){ if($(this).attr("value") == 'Rechercher'){$(this).attr("value","")} });
	$('.searchTextHeader, .searchText').blur( function(){ if($(this).attr("value") == ''){$(this).attr("value","Rechercher")} });
});
function preloadImages() {
	if (document.images) {
		pre_bt_plusdeservices_over = newImage('/medias/bt_plusdeservices_over.gif');
		pre_bt_ecriveznous_over = newImage('/medias/bt_ecriveznous_over.gif');
		preloadFlag = true;
	}
}

function tableau(idTr,afficher, ancre){
	if (afficher == 0){
		document.getElementById('trDetail' + idTr).style.display = 'none';
		document.getElementById('trLienAfficherDetail' + idTr).style.display = '';
		document.getElementById('trLienCacherDetail' + idTr).style.display = 'none';
		if (ancre == 1){window.location = '#' + idTr;}
	} else {
		document.getElementById('trDetail' + idTr).style.display = '';
		document.getElementById('trLienAfficherDetail' + idTr).style.display = 'none';
		document.getElementById('trLienCacherDetail' + idTr).style.display = '';
	}
}

function memTableau(){
	var tabIdsCc ;
	var ids ='';
	
	if (document.getElementById('idsCc').value != ''){
		tabIdsCc = document.getElementById('idsCc').value.split(';');
		for (i=0;i<tabIdsCc.length;i++){
			if (document.getElementById('trDetail' + tabIdsCc[i]).style.display == 'none'){
				ids += tabIdsCc[i] + '~' + 0 + ';';
			} else {
				ids += tabIdsCc[i] + '~' + 1 + ';';
			}
		}
		
		
		document.getElementById('idsCc').value = ids.substr(0,ids.length -1);
	}
}
function validForm(){
	var msg = '';
	YY_checkform('form','nom','#q','0','Le nom doit être renseigné.','prenom','#q','0','Le prénom doit être renseigné.','email','#S','2','L\'adresse e-mail doit être renseignée et valide');
	if (document.MM_returnValue){ document.forms.form1.submit();}
}
function majCoche(num,I_D){
	if (I_D=='I'){
		document.getElementById('D' + num).checked = false;
	} else {
		document.getElementById('I' + num).checked = false;
	}
}
function refreshByTheme(theme,id){
	if($(theme).attr("class")!="active"){
		$(id+" div[class=iClientBox]").fadeTo("fast",0.3);
		$.ajax({
		  url: $(theme).attr("href"),
		  success: function(data) {
			$(id).replaceWith(data);
			resizeIclients();
		  }
		})
	}
	return false ;
}
function iClientFullItem(t,id){
	$(id+" div[class=iClientBox]").hide();
	$($(t).attr("href")).show();
	$($(t).attr("href")).css("display","block");
	$("div[rel=iClientFullItemX]").show();
}
function iClientRestorItems(id){
	$("div[rel=iClientFullItemX]").hide() ;
	$("div[rel=iClientFullItem]").hide();
	$(id+" div[class=iClientBox]").show();
}
function FlashScreen(time){
	$('.voile').fadeIn();
	$("#flashscreen").fadeIn();
	$("#flashscreen").centerScreen();
	$("#flashscreen .close").click(function(){
		hideflashScreen();
	});
	if(time > 0){
		window.setTimeout("hideflashScreen();",(time*1000));
	}
}
function hideflashScreen(){
	$('.voile').fadeOut();
	$("#flashscreen").fadeOut();
}
function FlashScreen(time){
	$('.voile').fadeIn();
	$("#flashscreen").fadeIn();
	$("#flashscreen").centerScreen();
	$("#flashscreen .close").click(function(){
		hideflashScreen();
	});
	if(time > 0){
		window.setTimeout("hideflashScreen();",(time*1000));
	}
	$("#flashscreen").draggable({ handle: 'h2' });
}
function hideflashScreen(){
	$('.voile').fadeOut();
	$("#flashscreen").fadeOut();
}
function validateConnexion(){
	if($('#log').val() != "" && $('#pass').val() != ""){
		return true ;
	};
	if($('#log').val() == ""){
		alert("Veuillez saisir votre Nom d'utilisateur.");
		$('#log').focus();
	}else if($('#pass').val() == ""){
		alert("Veuillez saisir votre Mot de passe.");
		$('#pass').focus();
	}
	return false ;
}
function addFavorite(serviceId,obj){
	//loadExistantPopup("#serviceAddedSucess",".voile") ;
	$("#"+obj).attr("class","iClientPuceAdd iClientPuceLoading");
	$.ajax({
	  url: "/services/home.php?FAV",
	  type: 'POST',
	  data: "SERVICE="+serviceId ,
	  success: function(data){
		if(data == "1"){
			jAlert('Ce service a bien été ajouté à votre télécommande', 'Mon Univers');
			//loadExistantPopup("#serviceAddedSucess",".voile") ;
			if(obj != null){
				$("#"+obj).attr("class","iClientPuceAdd iClientPucedel");
				$("#"+obj).attr("href","javascript:removeFavorite(" + serviceId + ",'"+obj+"')");
				$("#"+obj).find(".tooltipAide").html("Retirer de votre Télécommande");
				refreshFavorite();
			}
		}else{
			jAlert('Impossible d\'ajouter le service.', 'Mon Univers');
		}
		  
	  }
	}) ;
}
function removeFavorite(serviceId,obj,fCback,elm,elm1){
	jConfirm('Voulez-vous vraiment retirer ce Service de votre télécommande ?', 'Mon Univers', function(r) {
		if(r){
			$("#"+obj).attr("class","iClientPuceAdd iClientPuceLoading");
			$.ajax({
			  url: "/services/home.php?REMFAV",
			  type: 'POST',
			  data: "SERVICE="+serviceId ,
			  success: function(data){
				//$(id).replaceWith(data);
				if(data == "1"){
					jAlert('Ce service a bien été supprimé de votre télécommande.', 'Mon Univers');
					//loadExistantPopup("#serviceRemovedSucess",".voile") ;
					if(obj != null){
						$("#"+obj).attr("class","iClientPuceAdd");
						$("#"+obj).attr("href","javascript:addFavorite(" + serviceId + ",'"+obj+"')");
						$("#"+obj).find(".tooltipAide").html("Ajouter à votre télécommande");
					}
					refreshFavorite();
					if(fCback != null && elm != null) fCback(elm);
					if(fCback != null && elm1 != null) fCback($(elm1).parent().parent().parent());
					if(fCback == null){
						if($("li[rel=Editable"+serviceId+"]").size() == 1){
							Eliminate("li[rel=Editable"+serviceId+"]") ;
							Eliminate($("#service"+serviceId).parent().parent().parent()) ;
						}
					}
				}else{
					jAlert('Impossible de retiré le service.', 'Mon Univers');
				}
				  
			  }
			}) ;
		}
	});
	
}
function refreshFavorite(){
	$("#FAVBOX").html("<div class=\"boxList\" style=\"text-align:center;padding:10px\"><img src=\"/medias/ajax-loader.gif\" /></div>");
	$.ajax({
	  url: "/services/home.php?REFFAV",
	  success: function(data){
		$("#FAVBOX").html(data);
		ActivateTooltip() ;
	  }
	}) ;
}
function Eliminate(elm){
	$(elm).fadeOut() ;
}
function ActivateTooltip(){
	$(".tooltipArea").hover(
			function(){
				$(this).children('.tooltipAide').css('display','block');
			},
			function(){
				$(this).children('.tooltipAide').css('display','none');
			}
		);
}
function ActivateIclientTooltip(){
	$(".addToIclientHolder").hover(
			function(){
				$(this).children('.addToIclient').fadeIn();
			},
			function(){
				$(this).children('.addToIclient').fadeOut();
			}
		);
}
////Scan cokie
function scanCookie(cookieName, currentItem, showInFirstVisit, flashTimer){ // params : 'flashscreen', 'currentItem', true
	if(showInFirstVisit){
		var cookie = $.cookie(cookieName);
		var items = cookie ? cookie.split(',') : new Array();
		exist = false;
		//alert('items' + items);
		for (val in items){
			if(items[val] == currentItem ){
				exist = true;
			}
		}
		if(!exist){
			//alert('not exist');
			items.push(currentItem);
			$.cookie(cookieName, items.join(','));
			// Afficher le POPUP
			FlashScreen(flashTimer);
		}
		//else{alert('exist');}
	}
}
