//  factory declaration
var action = "../plug/action/action.php";
var adminAction = "http://www.peche-saintgeniezdolt.fr/admin/plug/action/action.php";

/* ----- Tab menu management ----- */
// Load the selected tab in the menu
function loadTabIn(tab){
	var ul = document.getElementById(tab).parentNode;
	var ullist = ul.childNodes;
	for (var i=0; i<ullist.length; i++){
		if (ullist[i].id == tab){
			ullist[i].className="active";
		}else{
			ullist[i].className="";
		}
	}
}

function load2ndTabIn(tab){
	var ul = document.getElementById(tab).parentNode;
	var ullist = ul.childNodes;
	for (var i=0; i<ullist.length; i++){
		var a = ullist[i].getElementsByTagName("a");
		//var span = current.getElementsByTagName("span");
		
		if (ullist[i].id == tab){	
			a[0].className="active";
			//span[0].className="active";
			
		}else{
			a[0].className="";
			//span[0].className="";
		}
	}
}

function date(){
	today = new Date()
	document.write(today.getFullYear());
} 

/* ----- Cookie management ----- */
function getCookie(Name){ 
	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
	return document.cookie.match(re)[0].split("=")[1] //return its value
	return ""
}

function setCookie(name, value){
	//alert('cookie to set: '+name+', value: '+value);
	var d = new Date();
	d.setDate(d.getDate() + 365);
	document.cookie = name+'='+value+';expires='+ d.toGMTString()+';path="/"'; //cookie value is domain wide (path=/)
}

function setCookieWithoutPath(name, value){
	var d = new Date();
	d.setDate(d.getDate() + 365);
	document.cookie = name+'='+value+';expires='+ d.toGMTString(); //cookie value is domain wide (path=/)
}


/* ----- Display Selected Item DIV ----- */
function loadPanel(){
	var section = getSectionName();	
	var panel = getCookie(section);
	if (panel == null || panel == ''){
		panel = 0;
	}
	 displayPanel(panel);	
}

function loadPanelAndGenerateInfo(panel){
	generateInfo(panel);
	highlightLi(document.getElementById('li_'+panel));	
	showPanel(panel);
}

function displayPanel(panel){
	var ullist = getLeftMenu();
	highlightLi(ullist[panel]);
	showPanel(panel);
}function changePanel(panel){
	var section = getSectionName();	
	var ullist = getLeftMenu();
	// unselect all div and li
	for (i=0; i<=ullist.length-1; i++){
		hidePanel(i);
		unHighlightLi(ullist[i]);
	}
	// select given div and li
	highlightLi(ullist[panel]);
	showPanel(panel);
	setCookie(section, panel);
}

function generateInfo(panel){
	var itemTitle = document.getElementById("itemTitle_"+panel).innerHTML;
	var itemSubTitle = document.getElementById("itemSubTitle_"+panel).innerHTML;
	document.getElementById("postTitle").innerHTML = itemTitle;
	document.getElementById("postSubTitle").innerHTML = itemSubTitle;
	document.getElementById("post_"+panel).style.display='block';
}

function addSelectors(page){
	$("a.prestations").click(function(e){
		var panel = (this.id == undefined  || this.id == '') ? 0 : ((this.id).substr((this.id).lastIndexOf('-'), (this.id).length));		
		displayInfo(panel); 
		this.blur();
		return false;
	});
}

function getSectionName(){
	return document.getElementById("wrapper").getAttribute("section");
}

function highlightLi(li){
	li.className = 'selected';
}

function unHighlightLi(li){
	li.className = "";
}

function loadInfo(panel){
	document.getElementById("post_"+panel).style.display ='block';
}

function showPanel(panel){
	document.getElementById("post_"+panel).style.display ='block';
}

function hidePanel(panel){
	document.getElementById("post_"+panel).style.display ='none';
}

function getLeftMenu(){
	var ullist = document.getElementById("ulLinks").getElementsByTagName("li");
	return ullist;
}

function printIframe(iframe){
	iframe.focus();
	iframe.print();
}

/* ----- HIDE/SHOW ----- */
// display / hide the given element
function toggleEl(element){	
	var style = 'block';
	var el = document.getElementById(element);
	
	if (el.style.display=='block'){
		style ='none';
	}
	el.style.display = style;
}


/* ----- NEWS MAIL ----- */
// display / hide the form to send Mail to friend
function showMailToFriend(){
	var divName = 'friendForm';
	toggleEl(divName);
	var div = document.getElementById(divName);	
	if (div.style.display == 'block'){	
		new Effect.ScrollTo('friendForm',{duration:1});
	}
	return false;
}

// Load the corresponding page's banner
function loadBanner(id){
/* How to use 
onClick="loadBanner(this.parentNode.parentNode.id); return false;"
*/
	alert('id: '+id);
	var idBanner = "slide";
	var bannerPath = "./swf/slide_XXX.swf";
	var slideUrl = bannerPath.replace("XXX", id);
	alert('url :'+ slideUrl);
	document.getElementById(idBanner).src = slideUrl;
}



// Redirects to the given page
function redirect(url){
	location.href = url;
}


/*  ###########################################################################################
	#																						  #		
	#										AJAX											  #
	#																						  #
	########################################################################################### */

function getXhr(){
	var xhr = null; 
	if (window.XMLHttpRequest) // Firefox et autres
	   xhr = new XMLHttpRequest(); 
	else if(window.ActiveXObject){ // Internet Explorer 
	   try {
				xhr = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
	} else { // XMLHttpRequest non supporté par le navigateur 
	   alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); 
	   xhr = false; 
	} 
	
	return xhr;
}

// Node cleaner
function go(c){
	if(!c.data.replace(/\s/g,''))
		c.parentNode.removeChild(c);
}

function clean(d){
	var bal=d.getElementsByTagName('*');
	for(i=0;i<bal.length;i++){
		a=bal[i].previousSibling;
		if(a && a.nodeType==3)
			go(a);
		b=bal[i].nextSibling;
		if(b && b.nodeType==3)
			go(b);
	}
	return d;
} 

function showLoadingStatus(){	
	var status = document.getElementById('loadingStatus');
	status.innerHTML = '<img src="http://www.peche-saintgeniezdolt.fr/images/icons/loading.gif" height="28px" width="28px"/><br/>chargement';
	document.getElementById('loadingStatus').style.display = 'block';
}

function hideLoadingStatus(){
	document.getElementById('loadingStatus').style.display = 'none';
}

function showMessage(id, message){
	div = document.getElementById(id);
	new Effect.Appear(div);
	div.innerHTML = message;	
	hideMessage(id, 10000);
}

function hideMessage(id, duration){
	window.setTimeout("new Effect.Fade('"+id+"')", duration);
}


/*  ###########################################################################################
	#																						  #		
	#										NEWSLETTER										  #
	#																						  #
	########################################################################################### */

function subscribe(){
	var xhr = getXhr();
	var action = "http://lapechestgeniez.free.fr/new/admin/plug/newsletter/newsletter.php";
	xhr.onreadystatechange = function(){
		if (xhr.readyState == 4 && xhr.status == 200){
			result = xhr.responseText;			
			showMessage('newsletterC', result);
		}
	}
		
		// retieve data
		newsEmail = document.getElementById('newsEmail').value;	
		radio = document.getElementsByName('action');
		for (var i=0; i<radio.length;i++) {
			if (radio[i].checked) {
				newsAction = radio[i].value;
			}
		}		
	
		xhr.open("POST",action,true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send('action='+newsAction+'&email='+newsEmail);
}
	
/*  ###########################################################################################
	#																						  #		
	#										NEWS											  #
	#																						  #
	########################################################################################### */	
function goTo(page){	
	var xhr = getXhr();
	xhr.onreadystatechange = function(){
		if (xhr.readyState < 4){
			showLoadingStatus();
		}
		if (xhr.readyState == 4 && xhr.status == 200){		
			result = xhr.responseText;	
			document.getElementById('listNews').innerHTML = result;
			hideLoadingStatus();
		}
	}
		xhr.open("POST",action,true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send('method=getAllNewsAjax&page='+page);
}	

function allNews(){	
	var xhr = getXhr();
	xhr.onreadystatechange = function(){	
		if (xhr.readyState < 4){
			showLoadingStatus();
		}
		if (xhr.readyState == 4 && xhr.status == 200){
			result = xhr.responseText;	
			document.getElementById('newsContent').innerHTML = result;
			hideLoadingStatus();
		}
	}
		xhr.open("POST",action,true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send('method=getAllNewsAjax');
}	

function goToA(page){	
	var xhr = getXhr();
	xhr.onreadystatechange = function(){
		if (xhr.readyState < 4){
			showLoadingStatus();
		}	
		if (xhr.readyState == 4 && xhr.status == 200){
			result = xhr.responseText;	
			document.getElementById('rowListNews').innerHTML = result;
			hideLoadingStatus();			
		}
	}
		xhr.open("POST",adminAction,true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send('method=getAllNewsAjax&page='+page);
}

/*  ###########################################################################################
	#																						  #		
	#										RSS 												  #
	#																						  #
	########################################################################################### */
function createRSSFeed(){
	alert('enter');
	var xhr = getXhr();
	xhr.onreadystatechange = function(){
		if (xhr.readyState == 4 && xhr.status == 200){
			result = xhr.responseText;	
			//document.getElementById('rowListNews').innerHTML = result;
			alert(result);
		}
	}
		xhr.open("POST",action ,true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send('method=createRSSFeed');
		alert('req sent');

}

/*  ###########################################################################################
	#																						  #		
	#										ADMIN NEWS										  #
	#																						  #
	########################################################################################### */

function deconnect(){
	alert('enter');
	var xhr = getXhr();
	xhr.onreadystatechange = function(){
		if (xhr.readyState == 4 && xhr.status == 200){
			result = xhr.responseText;
alert('ok: '+result);			
			//document.getElementById('rowListNews').innerHTML = result;
		}
	}
		xhr.open("POST",adminAction ,true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send('method=deconnect');
}
	
function setNewsDeleted(id){
	var xhr = getXhr();
	xhr.onreadystatechange = function(){
		if (xhr.readyState == 4 && xhr.status == 200){
			result = xhr.responseText;			
			document.getElementById('rowListNews').innerHTML = result;
		}
	}
		xhr.open("POST",adminAction ,true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send('method=setNewsDeleted&id='+id);
}

function setNewsErased(id){
	var xhr = getXhr();
	xhr.onreadystatechange = function(){
		if (xhr.readyState == 4 && xhr.status == 200){
			alert("setNewsErased: "+id);
			result = xhr.responseText;			
			document.getElementById('rowListNews').innerHTML = result;
		}
	}
		xhr.open("POST",adminAction ,true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send('method=setNewsErased&id='+id);
}

function setNewsHidden(id){
	var xhr = getXhr();
	var isHiddenNews = document.getElementById('tr_'+id).getAttribute("isHiddenNews");
	
	xhr.onreadystatechange = function(){
		if (xhr.readyState == 4 && xhr.status == 200){
			result = xhr.responseText;
			document.getElementById('tr_'+id).className = result;
			document.getElementById('tr_'+id).setAttribute("isHiddenNews", (parseInt(isHiddenNews)+1)%2);
		}
	}
	
	xhr.open("POST",adminAction ,true);
	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhr.send('method=setNewsHidden&id='+id+'&state='+isHiddenNews);
}

function hideSelection(){
	var xhr = getXhr();
	number = 0;
	xhr.onreadystatechange = function(){
		if (xhr.readyState == 4 && xhr.status == 200){
			result = xhr.responseText;
			document.getElementById('rowListNews').innerHTML = result;			
			if (number == 1){
				msg = number + ' article a été caché';				
			}else{
				msg = number + ' articles ont été cachés';	
			}			
			addMessage(0, msg);	
		}
	}
	
	selected = false;
	field = document.getElementsByName('list');
	// test the checkbox selection
	if (field.length!=0){
		for (i = 0; i < field.length; i++) {
			if (field[i].checked){
				selected = true;
				break;
			}
		}
	}
	
	if (selected){
		// Get the list
		ids = '';
		var idTab = new Array();
		for (i = 0; i < field.length; i++) {
			if (field[i].checked){
				idTab.push(field[i].id);
				number++;
			}
		}
		
		ids = idTab.join('-');
		xhr.open("POST",adminAction ,true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send('method=hideSelection&ids='+ids);
	}else{
		addMessage(1, 'Veuillez selectionner au moins un article');		
	}
}

function deleteSelection(){
	var xhr = getXhr();
	number = 0;
	xhr.onreadystatechange = function(){
		if (xhr.readyState == 4 && xhr.status == 200){
			result = xhr.responseText;
			document.getElementById('rowListNews').innerHTML = result;
			if (number == 1){
				msg = number + ' article a été supprimé';				
			}else{
				msg = number + ' articles ont été supprimés';	
			}			
			addMessage(0, msg);		
		}
	}
	
	selected = false;
	field = document.getElementsByName('list');
	// test the checkbox selection
	if (field.length!=0){
		for (i = 0; i < field.length; i++) {
			if (field[i].checked){
				selected = true;
				break;
			}
		}
	}
	
	if (selected){
		// Get the list
		ids = '';
		var idTab = new Array();
		for (i = 0; i < field.length; i++) {
			if (field[i].checked){
				idTab.push(field[i].id);
				number++;
			}
		}
		
		ids = idTab.join('-');
		xhr.open("POST",adminAction ,true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send('method=deleteSelection&ids='+ids);
	}else{
		addMessage(1, 'Veuillez selectionner au moins un article');		
	}
}


var checkflag = "false";
function check(field) {
	if (checkflag == "false") {
		for (i = 0; i < field.length; i++) {
			field[i].checked = true;
			id = 'tr_'+field[i].id;
			style = document.getElementById(id).getAttribute('name');
			setRowSelected(field[i], id, style);
		}
		checkflag = "true";
		return "Tout décocher"; 
	} else {
		for (i = 0; i < field.length; i++) {
			field[i].checked = false;
			iden = 'tr_'+field[i].id;
			style = document.getElementById(iden).getAttribute('name');
			setRowSelected(field[i], iden, style);
		}
		checkflag = "false";
		return "Tout cocher"; 
	}
}


function setRowSelected(field, id, style){

	if(field.checked){
		className = "selected";
	} else{
		className = style;
	}
	document.getElementById(id).className = className;
}


function addMessage(type, message){
	var errorPanel = document.getElementById('errorPanel');	
	switch(type){
		case 0:
		classe = 'success';
		break;
		
		case 1:
		classe = 'error';
		break;
				
		case 2:
		classe = 'info';
		break;		
	}

	errorPanel.className = classe;
	new Effect.Appear(errorPanel);
	errorPanel.innerHTML = message;	
	hideMessage(errorPanel.id, 10000);	
}

function displayWeather(){

	var weather_area = document.getElementById('weather_area');
	weather_area.style.display = 'block';
	
	var children = weather_area.childNodes;
	var container = weather_area.getElementsByTagName("div")[0];
	var table = container.childNodes[0];
	var row   = table.getElementsByTagName("tr")[2];
	table.deleteRow(0);
	table.style.color="#838B91";
	container.style.background = 'none';
	var image = table.getElementsByTagName("img")[0];
	var img_src = image.src;
	var img_pos = img_src.lastIndexOf('/');
	var img_name = img_src.substring(img_pos, img_src.length);
	img_name = img_name.replace("gif", "png");
	img_src = "http://www.fredlynx.info/widgets/Images/Icones_3/"+img_name;	
	image.src = img_src;
	image.height = "70"; 
	image.width = "70";
	
}