/**
 * @desc     checks if a string is in an array
 * @author   Septimiu CERNAT
 * @since    2009-10-22
 * @mod      2011-04-22 GP - jQuery.inArray
 * @param    string - needle -  the string you search
 * @param    array - haystack - the array to look in for
 * @return   bool
 */
function in_array(needle, haystack)
{
	return (jQuery.inArray(needle, haystack) != -1);
}

/**
 * Debugging
 */
var debug = new Object();
debug.info = function() { try { if(window.console) { console.info(arguments); } } catch(e) { } }
debug.log = function() { try { if(window.console) { console.log(arguments); } } catch(e) {} }

function hide(nCatid)
{
    document.getElementById('div_category_'+nCatid).style.display='none';
    document.getElementById('img_category_'+nCatid).setAttribute("src",base_url+"images/bullet_arrow_right.png");
    document.getElementById('span_category_'+nCatid).onclick = function() {show(nCatid); }
}
function show(nCatid)
{
    document.getElementById('div_category_'+nCatid).style.display='';
    document.getElementById('img_category_'+nCatid).setAttribute("src",base_url+"images/bullet_arrow_down.png");
    document.getElementById('span_category_'+nCatid).onclick = function() {hide(nCatid); }
}

/*
| -------------------------------------------------------------------
|  Article Comments
| -------------------------------------------------------------------
|
*/
var modify = false;

/**
* @desc     show comment textarea
*/
function show_comment(id)
{
	var index = '';
	if(id != null)
		index = '_' + id;

	document.location.hash = 'c';
	// show comment
	$('#form_send_comment' + index).css('display', 'block');
	// delete comment from textarea
	$('#textarea_send_comment' + index).val('');
	// focus on comment texarea
	$('#textarea_send_comment' + index).focus();
}
/**
* @desc     post a comment
*/
function add_comment(id)
{
	// add comment
	if(!modify)
	{
		$('#form_add_comment_' + id).submit();
	}
	// modify comment
	else
	{
		if($('#mail_' + id).is(':checked'))
			$('#mail_comment_' + id).val(1);

		$('#modified_comment_' + id).val($('#textarea_send_comment_' + id).val());
		$('#form_mod_comment_' + id).submit();
	}
}

/**
* @desc     cancel a comment
*/
function cancel_comment(id)
{
	var ext = '';
	if(id != null)
		ext = '_' + id;

	// delete comment from textarea
	$('#textare_send_comment' + ext).val('');
	// hide comment
	$('#form_send_comment'+ ext).css('display', 'none');
}

/**
* @desc     modify a comment
*/
function modify_comment(index)
{
	// set global modify variable to true
	modify = true;

	// display editable comment
	$('#form_send_comment_' + index).css('display', 'block');
}

/**
* @desc     delete a comment
*/
function delete_comment(id)
{
	if (confirm('Etes-vous sûr(e) de vouloir effacer ce commentaire?'))
	{
		$('#deleted_comment').val(id);
		$('#form_delete_comment').submit();
	}
}

/**
* @desc     display users emails list
*/
function display_email_list()
{
	$('#articles_email').css('display', 'block');
	$('#button_send').css('display', 'none');
}

/**
* @desc     select users with the selected company
*/
function select_company()
{
	$('.emails_list tr.row td.column input:checkbox').each(function()
	{
		// unckeck each checkbox
		$(this).attr('checked', false);

		// check only the selected once
		if($(this).attr('block') == $('#select_company').val())
			$(this).attr('checked', true);
	});
}

function email_display(id,email)
{
	$('.files_list tr td.between_rows').each(function(){
		$(this).hide();
	});
	$('#'+id).show();
	$('#'+id+' .email_to').val(email);
}

/**
* @desc     select or unckeck all the entries in users emails list
*/
function select_all()
{
	var checked = true;

	if($('#select_all').is(':checked') == false)
		checked = false;

	// check or uncheck all emails
	$('.emails_list tr.row td.column input:checkbox').each(function()
	{
		$(this).attr('checked', checked);
	});

	// reset companies select
	$('#select_company').val(0);
}

/**
* @desc     select or unckecke all the companies in users emails list
*/
function filter_users()
{
	// get filter value
	var search_value = $('#articles_email input.filter_input').val().toLowerCase();

	// display the found results
	$('.emails_list tr.row').each(function()
	{
		var found = false;
		var children = $(this).children();

		for(i = 0; i < children.length; i++)
		{
			if($(children[i]).attr('class').indexOf('header') == -1)
			{
				if($(children[i]).html().toLowerCase().indexOf(search_value) > -1)
					found = true;
			}
			else
			{
				found = true;
			}
		}

		if(found == false)
			$(this).css('display', 'none');
		else
			$(this).css('display', 'block');
	});
}

/**
* @desc     send an email from an article
*/
function send_mail()
{
	var check = false;
	var users = new Array();
	var i = 0;

	$('.emails_list tr.row td.column input:checkbox').each(function()
	{
		if($(this).is(':checked'))
		{
			check = true;
			users[i] = $(this).val();
			i++;
		}
	});

	if(check == false)
	{
		alert('Vous devez choisir au moins 1 destinataire.');
	}
	else
	{
		$('#users_list').val(users.join(','));
		$('#message').val($('#email_body').val());
		$('#form_send_mail').submit();
	}
}

/*
| -------------------------------------------------------------------
|  Agenda
| -------------------------------------------------------------------
|
*/
/**
* @desc     display add agenda form
*/
function display_add_agenda_form()
{
	delete_agenda_form_inputs();
	$('div.add_agenda').css('display', 'block');
}

/**
* @desc     reset agenda form inputs
*/
function delete_agenda_form_inputs()
{
    // delete all errors
    $('.error').html('');
    // uncheck the is platforma checkbox
    $('#is_platforma').removeAttr('checked');
    // delete all form inputs
    $('#agen_hour_start').val('');
    $('#agen_hour_end').val('');
    $('#input_1_calendar').val('');
    $('#input_2_calendar').val('');
    $('#agen_place').val('');

    if($('#agen_title').val() != 'undefined')
        $('#agen_title').val('');
    if($('#agen_title').val() != 'undefined')
        $('#agen_organizer').val('');

    $('#agen_description').val('');

    // empty files accordion
    $('#table_attached_files tr').each(function(){
        if($(this).attr('id').indexOf('tr_attached_file') > -1)
            $(this).remove();
    });
    $('#table_attached_files').append('<tr id="tr_attached_file_0" style="display: none"><td><a href="javascript:;"></a></td></tr>');

    // empty links accordion
    $('#table_attached_links tr').each(function(){
        if($(this).attr('id').indexOf('tr_attached_link') > -1)
            $(this).remove();
    });
    $('#table_attached_links').append('<tr id="tr_attached_link_0" style="display: none"><td><a href="javascript:;"></a></td></tr>');

    // hide add agenda form
    $('div.add_agenda').css('display', 'none');

    // delete all the error messages
    $('#form_agenda_info span.error').each(function()
    {
        $(this).html('');
    });
}

/**
* @desc     reset user_email form inputs
*/
function delete_user_email_form_inputs()
{
    // delete all errors
    $('.error').html('');
    // uncheck the copy of email checkbox
    $('#check').removeAttr('checked');
    // delete all form inputs
    $('#subject').val('');
    $('#cc').val('');
    $('#email_to').val('');
    $('#text_ms').val('');
  
    // hide add agenda form
    $('td.between_rows').hide();
    
}

/*
| -------------------------------------------------------------------
|  Articles
| -------------------------------------------------------------------
|
*/
/**
* @desc     display add article form
*/
function display_add_article_form()
{
	cancel_add_article_form();
	$('div.add_article').css('display', 'block');
}

/**
* @desc     reset article form inputs
*/
function cancel_add_article_form()
{
	// delete all errors
	$('.error').html('');

	// reset ckeditor textarea
	$('iframe').contents().find('body').empty();

	$('#arti_title').val('');
	$('#arti_category').val('0');
	$('#arti_attached_files').val('');
	$('#arti_attached_links').val('');
	$('#arti_attached_articles').val('');

	// empty files accordion
	$('table #attached_files tr').each(function(){
		if($(this).attr('id').indexOf('tr_attached_file') > -1)
			$(this).remove();
	});
	$('table #attached_files').append('<tr id="tr_attached_file_0" style="display: none"><td><a href="javascript:;"></a></td></tr>');

	// empty links accordion
	$('table #attached_links tr').each(function(){
		if($(this).attr('id').indexOf('tr_attached_link') > -1)
			$(this).remove();
	});
	$('table #attached_links').append('<tr id="tr_attached_link_0" style="display: none"><td><a href="javascript:;"></a></td></tr>');

	// empty article accordion
	$('table #attached_articles tr').each(function(){
		if($(this).attr('id').indexOf('tr_attached_article') > -1)
			$(this).remove();
	});
	$('table #attached_articles').append('<tr id="tr_attached_article_0" style="display: none"><td><a href="javascript:;"></a></td></tr>');

	// hide add article form
	$('div.add_article').css('display', 'none');

	// delete all the error messages
	$('#form_article span.error').each(function()
	{
		$(this).html('');
	});
}

var dialog_opts = {
	modal: true,
	bgiframe: true,
	autoOpen: false,
	minWidth: 300,
	width: 300,
	maxWidth: 700,
	minHeight: 200,
	height: 200,
	maxHeight: 500,
	closeOnEscape: true,
	buttons: {
		"Annuler": function() {
			$(this).dialog('close');
		}
	}
};

/**
 * Show upload form
 */
function display_upload_form(link, dialog_params)
{
	// overwrite default(global) dialog options
	if(dialog_params != undefined)
	{
		dialog_opts = objUnion(dialog_opts, dialog_params);
	}
	$('#popup').dialog(dialog_opts);
	$('#popup').dialog('option', 'title', 'Ajouter un fichier');
	$('#popup').dialog('open');

	loadAjax('#popup_content',
		link,
		{},
		function(){
			
		}
	);
	return false;
}

/**
 * Show upload form v2
 */
function display_upload_form2()
{
	$('#uploader_container').toggle();
	$('#load_result').html('');
	$('#file_name').val('');
	return false;
}

/**
 * Objects Union
 */
function objUnion(obj1, obj2)
{
	for ( key in obj2 )
	{
		obj1[key] = obj2[key];
	}
	return obj1;
}

/**
 * Load File Uploader form
 */
function loadFileUploader(e, link, params)
{
	if(e!=null)
	{
		e.preventDefault();
	}
	loadAjax('#file_uploader', link, params);
	return false;
}

/**
 * Reload File List
 */
function reloadFileList(e, link, params)
{        
	if(e!=null)
	{
		e.preventDefault();
	}
	var $files_list = $('#files_list');
	if($files_list.length>0)
	{
		var callback = function(){
			resetFileFilter();
		}
		loadAjax('#files_list', link, params, callback);
	}        
	return false;
}

/**
 * Load Ajax
 */
function loadAjax(target, link, params, callback)
{
	$.ajax({
		url: link,
		data: params!=undefined ? params : {},
		type: "post",
		dataType: 'html',
		beforeSend: function(){
			$(target).html('Chargement...');
		},
		error: function(object, message){
			$(target).html('Erreur de chargement...');
		},
		success: function(response){
			$(target).html(response);
			try { setTimeout(callback, 200); }
			catch(e) {}
		}
	});
}

/**
 * Reset File Filter
 */
function resetFileFilter(filterValue)
{
	if(filterValue==undefined) filterValue = 'Rechercher...'
	var $filter_files = $('#filter_files');
	if($filter_files.val()!=filterValue)
	{
		$filter_files.val('');
	}
}

/**
 * @desc filter on an html element (table, div)
 * @param oNode - the filter
 * @param id - the id of the element
 * @param head - the first element in the path
 * @param body - the rest of elements in the path
 */
var setFilterElementIntervalId = 0;

function filterElement(oNode, id, head, body)
{
	clearInterval(setFilterElementIntervalId);
	setFilterElementIntervalId = setInterval(function(){ filterElementAction(oNode, id, head, body); }, 500);
}

function filterElementAction(oNode,id,head,body)
{
	clearInterval(setFilterElementIntervalId);

	var nLength = 0;
	$('#'+id+' '+head+' '+body).each(function(){
		if($(this).html().toLowerCase().indexOf(oNode.value.toLowerCase()) != -1)
		{
			$(this).parents(head+':first').css('display','');
			nLength ++;
		}
		else
		{
			$(this).parents(head+':first').css('display','none');
		}
	});

	if (nLength == 0)
	{
		$('#err_mess_' + id).css('display','');
	}
	else
	{
		$('#err_mess_' + id).css('display','none');
	}
}

/**
* @desc     ask to delete an element
* @author   Septimiu CERNAT
* @since    2009-10-22
* @param    string - element - the delete html element to be loaded (usually img)
*/
function delete_element(url)
{
    // crete the delete question
    var answer = confirm('Etes-vous sûr(e) de vouloir effacer cet élément?');
    // if the answer is true
    if (answer)
    {
        window.location.href = url;
    }
}

function select_entities()
{
	selected_item = $('#select_mem_par').val();
	if (selected_item == 'all')
	{
		$('.member_class').show();
		$('.partner_class').show();
	}
	else if (selected_item == 'mem')
	{
		$('.partner_class input').removeAttr('checked');
	    $('.partner_class').hide();
	    $('.member_class').show();
	}
	else if (selected_item == 'par')
	{
		$('.member_class input').removeAttr('checked');
		$('.member_class').hide();
		$('.partner_class').show();
	}

	$('#check_all').removeAttr('checked');
 	$('#uncheck_all').removeAttr('checked');	
	take_selected('#entities_list div input');
	
}
/**search a string in a list**/
function javascript_search(what_to_search, where_to_search, what_to_close)
{
	where_to_search.each(function()
	{
		var sentence = replace_accents($(this).html().toLowerCase());
		if (sentence.indexOf(replace_accents(what_to_search.val().toLowerCase())) == -1)
		{
	 		eval('$(this)'+what_to_close+'.hide();');
		}
		else
		{
		 	eval('$(this)'+what_to_close+'.show();'); 
		}
	});
}
/** replace de accents in a string **/
function replace_accents(text)
{
	text = text.replace(/[àáâãäå]/ig,'a');
	text = text.replace(/[èéêë]/ig,'e');
	text = text.replace(/[ìíîï]/ig,'i');
	text = text.replace(/[òóôõö]/ig,'o');
	text = text.replace(/[ùúûü]/ig,'u');
	text = text.replace(/ç/ig,'c');
	text = text.replace(/æ/ig,'ae');
	return text;
}

/** delete from a input the text **/
 function focus_filtrer_entities()
 {
 	if ($('#search_input').val() == 'filtrer')
 	{
 		$('#search_input').val('');
 		$('#search_input').css('color','black');
 	}
 }
 
 /** put in a input a value **/
 function blur_filtrer_entities()
 {
     if ($('#search_input').val() == '')
     {
     	$('#search_input').val('filtrer');
     	$('#search_input').css('color','#C0C0C0'); 
     }
 }

/** select the children from a parent **/
function select_all(from_where)
{
	$(from_where).each(function()
	{
		if ($(this).parent().css('display') == 'block')
		{
			$(this).attr('checked','checked');
		}
	});
}
/** unselect all the children from a parent **/
function select_none(from_where)
{
	$(from_where).each(function()
	{
		$(this).removeAttr('checked');
	});
}

/** take all the checked fields **/
function take_selected(root)
{
	text= '';
	$(root).each(function()
	{
	    id = $(this).attr('id');
		if ($(this).attr('checked') == true)
		{
			text = text + ($('#'+id+'_name').html()) + ', ';
		} 
	});
	text_new = text.substr(0,text.length-2);
	$('#text_entities_list').html(text_new); 
}

/** select all the entities **/
function click_select_all()
{
	select_all('#entities_list div input'); 
	take_selected('#entities_list div input');
	$('#uncheck_all').removeAttr('checked');
	$('#check_all').attr('checked','checked');
	
	
}
/** unselect all the entities **/
function click_select_none()
{
	select_none('#entities_list div input');
	take_selected('#entities_list div input');
	$('#check_all').removeAttr('checked');
	$('#uncheck_all').attr('checked','checked');
}
/** select one of entities **/
function select_one()
{
 	$('#check_all').removeAttr('checked');
 	$('#uncheck_all').removeAttr('checked');
 	take_selected('#entities_list div input');
}

/** delete the information added on form after singup **/
function delete_after_singup()
{
	$('.after_singup').each(function()
	{
		$(this).val('');
	});
}
