//var menu = 'search'; // Current menu name, default : 'search'.

/**
* JQuery Initialization :
* - Set HTML & CSS,
* - Load the correct menu.
**/
//$(document).ready(function()
//{
//	// Set HTML CSS :
//	menu = getMenuName();
//	setAffectedElements(menu);
//
//	// Display alert button if connected :
//	$.post('./alertajax.php', { type:'connect' }, function (res){
//		if( res == 'true' ){ alertButton(true); }
//	})
//
//	// show menu contents :
//	if( menu != 'search' )
//		showMenu(menu);
//});


/**
* Set CSS properties and set history url :
* @param menu : name of the current menu.
**/
//function setAffectedElements(menu)
//{
//	if( !$.browser.msie ) // IE bug with this king of retirect
//		window.location.replace( getAnchorLink(window.location.href, menu) ); // replace url ...
//
//	if( !menu || menu == 'search' )
//	{
//		$('#searchTitle').attr('className', '');
//		$('#alertTitle').attr('className', 'disabled cursor');
//	}
//	else
//	{
//		$('#searchTitle').attr('className', 'disabled cursor');
//		$('#alertTitle').attr('className', '');
//	}
//}


/**
* Add or change the anchor of the url :
* @param link : link to transform.
* @param anchor : anchor name to add/change.
* @return : (String) modified url with this anchor.
**/
//function getAnchorLink(link, anchor)
//{
//	if( link.match('#') )
//		return link.split('#')[0]+'#'+anchor; // change the anchor if already exists.
//
//	return link+'#'+anchor; // or simply add the anchor at the end of url.
//}


/**
* Return current menu name from the url :
* @return : (bool:false) if no anchor found or (String) the anchor.
**/
//function getMenuName()
//{
//	if( window.location.href.match('#') )
//		return window.location.href.split('#')[window.location.href.split('#').length-1];
//
//	return false;
//}


/**
* Display the menu with this content :
* @param content : content to show in the menu.
* @functions : setJavascriptContent().
**/
//function setMenuContent(content)
//{
//	var nZone = document.getElementById('notificationZone');
//
//	if( content != '' ){ nZone.innerHTML = '<br />'+content+'<br /><hr id="delimit" />'; } // Display menu content.
//	else { nZone.innerHTML = ''; } // Clear the notificationZone.
//
//	setJavascriptContent();
//
//	if( getMenuName() == 'alertadd' ){
//		$('#notificationZone #addAlertTitle').attr( 'value', $('#q').attr('value') );
//	}
//}


/**
* Initialize Javascript on the #notificationZone id (menu bloc):
* @fonctions : loadMenu(), showMenu(), alertButton().
**/
function setJavascriptContent()
{
	// Change contents of the menu when the balise <a class="alert-menu-redirect" href="location"></a> is found :
	if( $("#notificationZone").html().match(new RegExp('<a class="?alert-menu-redirect"? href="([^"]*)"></a>', 'gi')) )
	{
		var location = $("#notificationZone").html().replace(new RegExp('^[^ø]*<a class="?alert-menu-redirect"? href="([^"]*)"></a>[^ø]*$', 'gi'), '$1');
		if( location == 'alert' ){alertButton(true);} // Add the alert button before connexion redirection.
		loadMenu( location );return false;
	}
	
	// Force input[type=submit] to execute an ajax submitting of the form :
	$("#notificationZone").find('input[type=submit]').click(function()
	{
		if( menu == "alertadd" ){
			// send alertadd from + search form :
			loadMenu(menu, getForm(this)+"&url="+encodeURIComponent(getForm(document.getElementById('submit'))));
		}
		else if( menu != "alert" ){
			// send container form :
			loadMenu(menu, getForm(this));
		}
		
		return false;
	});
	
	// Set Ajax for <select> : update user's alerts infos.
	$("#notificationZone").find('select').change(function()
	{
		$.post('./alertajax.php', {update: $(this).attr('name'), value: $(this).attr('value')});
	});
	
	// Show title modification bar (alert/alert.php).
	$("#notificationZone .modatitle").click(function()
	{
		var id = $(this).attr('href');
		showTitleModBar(true, $(".title_"+id).text().substr(0, $(".title_"+id).text().length/$(".title_"+id).length), id);
		return false;
	});
	
	// Hidde options if the alert is being modified (alert/alert.php).
	$("#notificationZone .hiddeOption").css('display', 'none');
	
	// Update search alert modification (alert/alert.php).
	$("#notificationZone #modsearchalert").click(function()
	{
		var aid = $(this).attr('name');
		$.post('./alertajax.php', {searchUpdate: getForm(document.getElementById('submit')), id: aid}, function(url)
		{
			$("#notificationZone a.title_"+aid).attr('href', 'index.php?'+url);
			$("#notificationZone #modsearchannul").click(); // hidde bar.
		});
		
		return false;
	});
	
	// Hidde alert modification bar (alert/alert.php).
	$("#notificationZone #modsearchannul").click(function()
	{
		$("#notificationZone #modifBarEmplacement").animate({opacity: 0, height: 0}, 300).html('');
		$("#notificationZone .hiddeOption").css('display', 'inline');
		$.post('./alertajax.php', {clearModBar: 'true'});
		return false;
	});
	
	// Set Ajax for alertwizard.php <select> : update user's alerts infos.
	$("#notificationZone #listplateforme").each(function()
	{
		$(this).unbind('change').change( function(){setItemList(this.value);});
	});
	
	// Set Ajax for <a class="dellink"></a> : delete user alert.
	$("#notificationZone").find('.dellink').click(function()
	{
		$.post('./alertajax.php', {dell: $(this).attr('href')});if( noAlertMsg() ){return false;}
		$(this).parent().parent().parent().animate({opacity: 0}, 500, function(){$(this).remove();});
		return false;
	});
	
	// Set "confirm" style : not to be visible by default.
	if( $("#notificationZone").find('#confirm').length ){$("#notificationZone #confirm").css('opacity', '0');}
	
	// Set Ajax for <a class="addofficial"></a> : add an official alert.
	$("#notificationZone").find('.addofficial').click(function()
	{
		$.post('./alertajax.php', {addofficial: $(this).attr('href')});if( noAlertMsg() ){return false;}
		$("#confirm").css('height', 'auto').animate({opacity: 100}, 3500, function(){$("#confirm").animate({opacity: 0}, 1000, function(){$(this).css('height', '0px');});});
		$(this).parent().parent().animate({opacity: 0}, 800, function(){$(this).remove();});
		return false;
	});
	
	// Set Ajax for <a class="delofficial"></a> : delete an official alert.
	$("#notificationZone").find('.delofficial').click(function()
	{
		$.post('./alertajax.php', {delofficial: $(this).attr('href')});if( noAlertMsg() ){return false;}
		$(this).parent().parent().animate({opacity: 0}, 500, function(){$(this).remove();});
		return false;
	});
}


var tmplist = '';

/**
* Recursive function, return a hierarchical list of elements contained in a xml formated String.
* @param xml : xml used to retrieve the hierarchical list.
* @param space : string to be inserted before each line.
**/
function getXmlTree(type, xml, space, selected)
{
	var attrib_selected = '';
	if( type == 'Calenda' )
	{
		if( $(xml).get(0).tagName == "row" )
		{
			$(xml).children().each( function()
			{
				getXmlTree( type, $(this), space+'&nbsp;&nbsp;|&nbsp;&nbsp;', selected );
			});
		}
		else if( $(xml).get(0).tagName == "col" )
		{
			if(selected == $(xml).attr('name')) attrib_selected ='checked';
			tmplist += space.substring(25, space.length) + '<label><input type="radio" name="categories" value="'+$(xml).attr('name')+'" ' + attrib_selected + '> '+$(xml).attr('name')+'</label><br/>';
		
			$(xml).children().each( function()
			{
				getXmlTree( type, $(this), space, selected );
			});
		}
	}
	else if( type == 'Revues.org' || type == 'Hypothèses' )
	{
		if( $(xml).get(0).tagName.match("collections?") && ( type == 'Revues.org' && $(xml).attr('name') != "Les Carnets d'Hypothèses" || type == 'Hypothèses' && $(xml).attr('name') == "Les Carnets d'Hypothèses" || !$(xml).attr('name') ) )
		{
			if( $(xml).get(0).tagName == 'collection' ){
				if(selected == $(xml).attr('name')) attrib_selected ='checked';
				tmplist += space.substring(25, space.length) + '<label><input type="radio" name="categories" value="'+$(xml).attr('name')+'" ' + attrib_selected + '> '+$(xml).attr('name')+'</label><br/>';
			}

			$(xml).children().each( function()
			{
				getXmlTree( type, $(this), space+'&nbsp;&nbsp;|&nbsp;&nbsp;', selected );
			});
		}
		else if( $(xml).get(0).tagName == "item" )
		{
		        if(selected == $(xml).attr('name')) attrib_selected ='checked';
			tmplist += space.substring(25, space.length) + '<label'+( ($(xml).attr('name').length > 50) ? ' title="'+$(xml).attr('name')+'"' : '' )+'><input type="radio" name="categories" value="'+$(xml).attr('name')+'" ' + attrib_selected + '> '
				+( ($(xml).attr('name').length > 50) ? $(xml).attr('name').substr(0, $(xml).attr('name').lastIndexOf(' ', 50))+" ..." : $(xml).attr('name'))+'</label><br/>';
		
			$(xml).children().each( function()
			{
				getXmlTree( type, $(this), space, selected );
			});
		}
	}
}


/**
* Dispaly or hidde the Title modification bar (alert/alert.php)
* @param show : true/false, show/hidde the bar,
* @param title : default title to show in the input,
* @param id : id of the alert to be update.
**/
//function showTitleModBar(show, title, id)
//{
//	if( show == true && title != 'undefinied' && id )
//	{
//		if( $('#notificationZone').find('#formTitleMod').length == 0 )
//		{
//			$('#notificationZone #titleBarEmplacement').css('opacity', 0).css('height', 0);
//
//			$('#notificationZone #titleBarEmplacement').append('<form id="formTitleMod" style="margin-bottom:25px;">'
//								+'<input type="text" id="titleText" class="box" value="" style="text-align:center;" name="title" />'
//								+' <input type="submit" id="titleModif" class="submit rounded" value="" />'
//								+' <input type="submit" id="titleAnnul" class="submit rounded" value="" />'
//								+'</form>');
//
//			$("#titleBarEmplacement #titleText").attr('value', title);
//			$("#titleBarEmplacement #titleModif").attr('value', $('#transModif').html());
//			$("#titleBarEmplacement #titleAnnul").attr('value', $('#transAnnul').html());
//
//			$("#notificationZone #titleModif").click( function()
//			{
//				$.post('./alertajax.php', { update: 'title', value: id+'-'+$("#titleBarEmplacement #titleText").attr('value') },
//					function(){	$(".title_"+id).each(function(){ $(this).text($("#notificationZone #titleText").attr('value')); }) });
//				showTitleModBar(false);
//				return false;
//			});
//
//			$("#notificationZone #titleAnnul").click( function()
//			{
//				showTitleModBar(false);
//				return false;
//			});
//
//			$("#notificationZone #titleBarEmplacement").animate({opacity: 1, height: 45}, 300);
//			$("#titleBarEmplacement #titleText").focus();
//		}
//		else if( $('#notificationZone').find('#titleText').length >= 1 )
//		{
//			$("#titleBarEmplacement #titleText").attr('value', title);
//			$("#titleBarEmplacement #titleText").focus();
//
//			$("#notificationZone #titleModif").unbind('click').click( function()
//			{
//				$.post('./alertajax.php', { update: 'title', value: id+'-'+$("#titleBarEmplacement #titleText").attr('value') },
//					function(){	$(".title_"+id).each(function(){ $(this).text($("#notificationZone #titleText").attr('value')); }) });
//				showTitleModBar(false);
//				return false;
//			});
//		}
//	}
//	else if( show == false )
//	{
//		$("#notificationZone #titleBarEmplacement").animate({opacity: 0, height: 0}, 300, function(){ $(this).html(''); });
//	}
//}


/**
* If the deleted alert was the last one : show the "no alert" msg :
* @return : true if number of class="tralert" == 1, false otherwise.
* @fonctions : showMenu().
**/
//function noAlertMsg()
//{
//	if( $(".tralert").size() == 1 )
//	{
//		showMenu(menu);
//		return true;
//	}
//
//	return false;
//}


/**
* Display or remove the alert button :
* @param active : true = display, false = hidde.
**/
//function alertButton(active)
//{
//	if( active == true )
//	{
//		if( !document.getElementById('alertButton') ) // create button if not exists.
//		{
//			$("#submit").append('<input type="submit" id="alertButton" class="rounded submit" value="nouvelle alerte" />');
//			$("#alertButton").click(function(){ loadMenu('alertadd'); return false; });
//		}
//		else // rebind click action (needed for connexion by cookie).
//		{
//			$("#alertButton").unbind('click').click(function(){ loadMenu('alertadd'); return false; });
//		}
//	}
//	else if( active == false && document.getElementById('alertButton') ) // delete button.
//	{
//		$("#alertButton").remove();
//	}
//}


/**
* Return a formated string of all name/input of the form :
* @param obj : an HTML object contained by the <form>.
* @return : a formated string like "var1=value1&var2=value2&var3=value3".
**/
//function getForm(obj)
//{
//	var form = '';
//
//	$(obj).parents('form').find("input[type=submit]").each(function() // submit input
//	{
//		if( $(this).attr('name') == $(obj).attr('name') )
//		{
//			form += ((form=='')?'':'&')+$(this).attr('name')+'='+$(this).attr('value');
//		}
//	});
//
//	$(obj).parents('form').find("select[multiple]").each(function() // select multiple.
//	{
//		for( var i in $(this).val() ) // for each seleted values.
//		{
//			form += ((form=='')?'':'&')+$(this).attr('name')+'[]='+encodeURIComponent($(this).val()[i]); // create an array of values
//		}
//
//		$(this).removeAttr('name'); // remove name attribute, not to be use as a simple select (see below).
//	});
//
//	$(obj).parents('form').find("input[type=text], input[type=password], select").each(function() // text/password input & simple select.
//	{
//		form += ((form=='')?'':'&')+$(this).attr('name')+'='+encodeURIComponent($(this).attr('value'));
//	});
//
//	$(obj).parents('form').find(":checked").each(function() // checkbox & radio input.
//	{
//		form += ((form=='')?'':'&')+$(this).attr('name')+'='+(($(this).attr('value'))?$(this).attr('value'):'on');
//	});
//
//	return form;
//}


/**
* Load menu and set CSS/Javascript + hidde alert button if deconnexion :
* @fonctions : setAffectedElements(), alertButton(), showMenu(), setMenuContent().
**/
//function loadMenu(menu, data)
//{
//	setAffectedElements(menu);
//
//	if( menu == 'deconnexion' )
//		alertButton(false);
//
//	if( menu == 'search' )
//	{
//		$.post('./alert/search.php'); // set php session.
//		setMenuContent(''); // clear all.
//	}
//	else
//	{
//		showMenu(menu, (data)?data:'');
//	}
//
//	if( menu == 'alert' ) // send a mail if a new alert has been added.
//		$.get('./alertmail.php', {directUpdate: 'true'} /*, function(r){ alert(r); }*/ );
//}


/**
* Get and display the content of the selected menu :
* @param pmenu : menu name of the menu to display.
* @param data : informations send by POST to the menu (var1=val1&var2=val2 ...).
**/
//function showMenu(pmenu, data)
//{
//	if( !data ){ var data = ''; }
//
//	if( pmenu == 'alertadd' || pmenu == 'alertwizard' ){ rmenu = './'+pmenu+'.php'; } // "alertadd.php" is in "search/" folder
//	else { rmenu = './alert/'+pmenu+'.php'; } // other files are in "search/alert/" folder
//
//	$.post(rmenu, {datas: data}, function(content)
//	{
//		setMenuContent(content); // Display menu.
//		menu = pmenu; // Save last used menu.
//	});
//}



function setItemListAjax(platforme, categorie){
    var cat = '';
    if(platforme == 'Calenda')
	{
	cat = '&cat='+categorie; //calenda
	}
    else if(platforme == 'Hypotheses.org')
	cat = '&s='+categorie; // revues.org et hypotheses
    else if(platforme == 'Revues.org'){
        if(categorie in {'Bulletin':'', 'Cahier':'', 'Monographies':'', 'Revue':''})
            cat = '&pt='+categorie; // revues.org for type of pubblication
        else
            cat = '&s='+categorie; // revues.org
    }

    $('#itemlist').html('<center style="margin-top: 80px;"><img src="images/loading_anim.gif"></center>');

    $.ajax({
	    type: "GET",
	    url: "categorie.php",
	    data: 'pf='+platforme+'&q=*'+cat,
	    success: function(msg){
		    $('#itemlist').html(msg);
	    }
	
//	    async: false
    });
}


function addItem(item, last, value){

    value = value.replace(/^\s+|\s+$/g,"");
    if(value == "") return false;
    $("#addItem"+item).before('<tr id="tr'+item+last+'"><td class="itemAdd">'+
                            '<input type="hidden" name="'+item+'['+$('#last'+item).val()+']" value="'+value+'">'+
                            '<label>'+value+'</label>'+
                            '<span class="message_top_right">'+
                            '<input onclick="removeItem(\'tr'+item+last+'\');" type="button" name="del_share" class="rounded submit" value="X">'+
                            '</span>'+
                        '</td></tr>');
    $('#last'+item).val(parseInt(last) + 1);
}


function removeItem(item){
    $('#'+item).remove();
}

function addDomainItem(last_domain, value){

    value = value.replace(/^\s+|\s+$/g,"");

    if(value == "") return false;
    $("#addDomainItem").before('<tr id="item_'+last_domain+'"><td style="padding: 4px;border-bottom:  1px solid #9FD041;">'+
                            '<input type="hidden" name="maildom['+$('#last_domain').val()+']" value="'+value+'">'+
                            '<label>'+value+'</label>'+
                            '<span class="message_top_right">'+
                            '<input onclick="removeDomainItem(\'domain_'+last_domain+'\');" type="button" name="del_domain" class="rounded submit" value="X">'+
                            '</span>'+
                        '</td></tr>');
    $('#last_domain').val(parseInt(last_domain) + 1);
}

function removeDomainItem(item){
    $('#'+item).remove();
}


function addIpItem(last_ip, value){

    value = value.replace(/^\s+|\s+$/g,"");

    if(value == "") return false;
    $("#addIpItem").before('<tr id="ip_'+last_ip+'"><td style="padding: 4px;border-bottom:  1px solid #9FD041;">'+
                            '<input type="hidden" name="ip['+$('#last_ip').val()+']" value="'+value+'">'+
                            '<label>'+value+'</label>'+
                            '<span class="message_top_right">'+
                            '<input onclick="removeIpItem(\'ip_'+last_ip+'\');" type="button" name="del_ip" class="rounded submit" value="X">'+
                            '</span>'+
                        '</td></tr>');
    $('#last_ip').val(parseInt(last_ip) + 1);
}

function removeIpItem(item){
    $('#'+item).remove();
}
