/**
 * Set Cookie
 * 
 * @param name
 * @param value
 * @param expires
 * @param path
 * @param domain
 * @param secure
 * @return
 */
function Set_Cookie( name, value, expires, path, domain, secure ){
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}


/**
* Get Cookie info
* 
* @param check_name
* @return cookie
*/
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

/**
* Delete specific Cookie 
* 
* @param name
* @param path
* @param domain
* @return
*/
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

/**
* Shod date - time live in french
* 
* @return
*/
function showDateTime(){
	var mydate=new Date();
	var hours=mydate.getHours();
	var minutes=mydate.getMinutes();
	var seconds=mydate.getSeconds();
	
	//clock
	var dn="AM";
	if (hours>12){
		dn="PM";
		hours=hours-12;
	}
	if (hours==0)
		hours=12;
	if (minutes<=9)
		minutes="0"+minutes;
	if (seconds<=9)
		seconds="0"+seconds;
	
	ora = hours+":"+minutes+":"+seconds+" "+dn;
	
	//date
	var year=mydate.getYear();
	var day=mydate.getDay();
	var month=mydate.getMonth();
	var daym=mydate.getDate();
	
	if (year < 1000)
		year+=1900;
	if (daym<10)
		daym="0"+daym;
	
	var dayarray=new Array("Dimanche","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi");
	var montharray=new Array("Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Aout","Septembre","Octobre","Novembre","Décembre");
	
	dat = dayarray[day]+", "+montharray[month]+" "+daym+", "+year;
	
	//set
	$('#ceas').html(ora);
	$('#data').html(dat);
	
	setTimeout("showDateTime()",1000);
}


/**
* Delete specific object with ajax, confirmation required
* 
* @param module
* @param action
* @param param
* @return
*/
function deleteObject(module, action, param) {
	if (!param)
		alert("Eroare");
	else {
		p = "&"+param;	
		if(confirm("Êtes-vous sûr de vouloir supprimer ?"))
		{
			$.ajax({ 
				url: "index.php?module="+module+"&action="+action+p, 
				success: function (responseText, statusText){
					if(!responseText.error)
					{												
						reloadGrid(module);
					}
					else
					{
						alert("Eroare"+responseText.msg);	
					}
				}
			});
		}
	}
}

/**
* Reload a specific module Grid 
* 
* @param module
* @return
*/
function reloadGrid(module)
{
	$("#list_"+module+"").trigger("reloadGrid");//Reload grid trigger
	
	return false
}


/**
* Change tabs with ajax 
* 
* @param module
* @param action
* @param param
* @return
*/
function changePage(module, action, param) {
	var selected = $tabs.tabs('option', 'selected'); // => 0
	selected = selected+1;
	
	if (param)
		p = "&"+param;
	else
		p = "";
	
	$("#ajax_preloader").show();
	$.ajax({ 
		url: "index.php?module="+module+"&action="+action+p, 
		success: function(msg){
			$('#ui-tabs-'+selected).empty();
        	$('#ui-tabs-'+selected).html(msg);
        	$("#ajax_preloader").hide();
    	}
	});
}



 /**
 * Load a simple page without POST vars
 * 
 * @param module
 * @param action
 * @param target
 * @return
 */
function loadPage(module, action, params, target) {
	target = (target == null) ? 'container' : target;
	$('#' + target).html("<img src='globals/resources/images/ajax-loader.gif' alt='Loading...' />");
	if(params != null)
		$('#' + target).load('index.php?module='+module+'&action='+action+'&'+params, function(){
		
		});
	else 
		$('#' + target).load('index.php?module='+module+'&action='+action, function(){
		
		});
	return true;
}
 
 /**
  * Method for making an ajax request and reload JqGrid
  * @param module
  * @param action
  * @param params
  * @return boolean
  */
  
 function asyncRequestReloadGrid(module, action, params){
 	if(params != null){
 		params = '&'+params;
 	}
 	else
 		params = '';
 	$.ajax( {
 		url : 'index.php?module='+module+'&action='+action+params,
 		dataType: "json",
 		success: function (responseText, statusText){
 			if(!responseText.error)	
 				reloadGrid(module);
 			else
 				alert("Error" + responseText.msg);
 		}
 	});
 }

/**
 * Method for making an ajax request and returning true on success
 * @param module
 * @param action
 * @param params
 * @return boolean
 */
 
function asyncRequest(module, action, params, execute){
	if(params != null){
		params = '&'+params;
	}
	else
		params = '';
	$.ajax( {
		url : 'index.php?module='+module+'&action='+action+params,
		dataType: "json",
		success: function (responseText, statusText){
			if(!responseText.error)	
			{
				if(execute != null)
					execute();
				return true;
			}
			else
				return false;
		}
	});
}

/**
 * Load a basic popup with a blue border on top
 * @param module
 * @param action
 * @param params
 * @param holder_id
 * @param width
 * @param height
 * @param title
 * @return
 */
function showPopup(module, action, params, holder_id, width, height, title) {
	var nr_files = 0;

	width = (width == null) ? 370 : width;
	height = (height == null) ? 320 : height;

	holder_id = (holder_id == null) ? 'popup-holder' : holder_id;

	$('#' + holder_id).remove();
	var a = $("<div></div>").attr('id', holder_id).css('text-align', 'left');

	if(params != null){
		params = '&'+params;
	}
	else
		params = '';

	$('body').append(a);
	$('#' + holder_id).load('index.php?module='+module+'&action='+action+params);

	$('#' + holder_id).dialog( {
		modal : true,
		zIndex : 100,
		position : [ 'center', 170 ],
		width : width,
		height : height,
		title : title,	
	});
	return true;
}

/**
 * Load a basic popup without the blue border on top
 * @param module
 * @param action
 * @param params
 * @param link
 * @param holder_id
 * @param width
 * @param height
 * @param title
 * @return
 */
function showPopupNoBorder(module, action, params, holder_id, width, height) {	
	width = (width == null) ? 370 : width;
	height = (height == null) ? 320 : height;

	holder_id = (holder_id == null) ? 'popup-holder' : holder_id;
	
	$('#' + holder_id).remove();
	var a = $("<div></div>").attr('id', holder_id).css('text-align', 'left');
	$('body').append(a);
	
	if(params != null){
		params = '&'+params;
	}
	else
		params = '';
	$('#' + holder_id).load('index.php?module='+module+'&action='+action+params);
	$('#' + holder_id).dialog( {
		modal : true,
		zIndex : 10,
		position : [ 'center', 'center' ],
		width : width,
		height : height
	});
	$('#' + holder_id).siblings('div.ui-dialog-titlebar').removeClass(
			'ui-widget-header');
	$('#' + holder_id).siblings('div.ui-dialog-titlebar').addClass(
			'ui-widget-dialog-header');
	return true;
}
 
/**
 * Show an ajax message in a popup
 * @param module
 * @param action
 * @param params
 * @param holder_id
 * @param width
 * @param height
 * @param title
 * @return
 */
function showPopupMessage(module, action, params, holder_id, width, height, title) {
	var nr_files = 0;

	width = (width == null) ? 370 : width;
	height = (height == null) ? 320 : height;

	holder_id = (holder_id == null) ? 'popup-holder' : holder_id;

	$('#' + holder_id).remove();
	var a = $("<div></div>").attr('id', holder_id).css('text-align', 'left');

	if(params != null){
		params = '&'+params;
	}
	else
		params = '';

	$('body').append(a);
	$('#' + holder_id).load('index.php?module='+module+'&action='+action+params);

	$('#' + holder_id).dialog( {
		modal : true,
		zIndex : 100,
		position : [ 'center', 170 ],
		width : width,
		height : height,
		title : title,	
		buttons: {
			Ok: function() {
				$(this).dialog('close');
			}
		},
	});
	return true;
} 
 
 /**
   * Show a pop up form
   * @param module
   * @param action
   * @param params
   * @param holder_id
   * @param width
   * @param height
   * @param title
   * @param form_name
   * @param button_val
   * @return
   */ 
function showPopupForm(module, action, params, holder_id, width, height, title, form_name, button_val) {
	var nr_files = 0;

	width = (width == null) ? 370 : width;
	height = (height == null) ? 320 : height;
	
	button_val = (button_val == null) ? 'Validate' : button_val;

	holder_id = (holder_id == null) ? 'popup-holder' : holder_id;

	$('#' + holder_id).remove();
	var a = $("<div></div>").attr('id', holder_id).css('text-align', 'left');

	if(params != null){
		params = '&'+params;
	}
	else
		params = '';

	$('body').append(a);
	$('#' + holder_id).load('index.php?module='+module+'&action='+action+params);

	$('#' + holder_id).dialog( {
		modal : true,
		zIndex : 100,
		position : [ 'center', 170 ],
		width : width,
		height : height,
		title : title,	
		buttons: {
			"Validate": function() {
				$("#"+form_name).submit();
			}
		},
	});
	
	$(document).ready(function() {
		$('.ui-dialog-buttonpane button:contains(Validate)').attr("id","dialog_box_send-button");
		$('#dialog_box_send-button').html(button_val);
	});
	return true;
} 
 
/**
* Convert a calendar to a datepicker
* @param holder_id
* @return
*/ 
function addCalendar(holder_id) {
	$('#' + holder_id).datepicker({
		dateFormat: 'dd/mm/yy',
		minDate: due,
	});
}  

/**
 * toggle a message
 * @param id
 * @return
 */
function toggleMessage(id) {
	if (document.getElementById("exp_message" + id).style.display == 'inline') {
		document.getElementById("exp_message" + id).style.display = "none";
		document.getElementById("message" + id).innerHTML = document
				.getElementById("from_min_message" + id).innerHTML
				+ document.getElementById("from_exp_message" + id).innerHTML;

	} else {
		document.getElementById("message" + id).innerHTML = document
				.getElementById("from_min_message" + id).innerHTML
				+ " ...";

		document.getElementById("exp_message" + id).style.display = "inline";
	}
}

/**
 * verify if a string is number
 * @param sText
 * @return true/false
 */
function isNumeric(sText) {
	var ValidChars = "0123456789.";
	var IsNumber = true;
	var Char;

	for (i = 0; i < sText.length && IsNumber == true; i++) {
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
	return IsNumber;

}


/**
 * Validate the formular with jquery and submit with ajaxSubmit the form
 * The return should be a json
 * Form must have a submit button ! ! !
 * @param id_form - id of the form to be validated
 * @return json
 */
function formValidate(id_form){
	$("#" + id_form).validate({
		submitHandler : function(form) {
			$(form).ajaxSubmit({
				dataType : "json",
				success : function(data) {
					if(data.result == "1")
						loadPage(data.module, data.action, data.params, data.container);
					else if (data.result == "file_extension")
						showNotification("Error!", "Uploaded pictures should be ONLY jpg or jpeg !");
					else if (data.result == "0")
						showNotification("Error!", "Contact the admin!!!");
				}
			});
		}
	});
}


/**
 * special content uploading method
 * @param uploading_method can be id_session if we enter from instructions
 * @return
 */
function ajaxFileUpload() {
	$("#loading").ajaxStart(function() {
		$(this).show();
	}).ajaxComplete(function() {
		$(this).hide();
	});
	
	id_document = document.getElementById('id_document').value;
	file_to_upload = document.getElementById('file_to_upload').value;

	if(file_to_upload !== "")
	{
		$.ajaxFileUpload( {
			url : 'index.php?module=SpecialContent&action=uploadContent&id_document=' + id_document + '&id_session=' + uploading_method,
			secureuri : false,
			fileElementId : 'file_to_upload',
			dataType : 'json',
			async : false,
			success : function(data, status) {
				if(data.error != "" && data.error != 'uploaded') {
					parseUploadError(data.error);
				} else {
					showPopup('index.php?module=SpecialContent&action=addDocumentInstructions&id_document=' + data.id_document + '&id_session=' + data.id_session, "addFiles", 635, 'auto', "Instruction pour l'intervenant (2/4)");
				}
			},
			error : function(data, status, e) {
				showNotification("Erreur", e);
			}
		});
	}
}

/**
 * swhitching the error from uploading formular and shwo a notification
 * @param error
 * @return
 */
function parseUploadError(error){
	if (error != '') {
		switch (error) {
			case "select_upload":
				showNotification(
						"Sélectionnez ou télécharger",
						"Vous devez sélectionner ou télécharger un fichier.");
				break;
			case "invalid_extension":
				showNotification(
						"Extension invalide",
						"L’extension de ce fichier n’est pas compatible avec Webex. Les formats disponibles sont : jpeg, pdf,ppt, doc. Merci de votre compréhension.");
				break;
			case "invalid_filesize":
				showNotification(
						"Taille du fichier non valide",
						"Le fichier que vous souhaitez télécharger dépasse la taille maximale autorisée (5 Mo) ");
				break;
			case "invalid_free_space":
				showNotification(
						"Hors de l'espace",
						"Votre espace de stockage est plein, vous devez d’abord libérer de l’espace afin de pouvoir télécharger ce fichier ");
				break;
			case "cannot_mkdir":
				showNotification(
						"Permisions",
						"Ne peut pas créer le répertoire");
				break;
			case "cannot_move":
				showNotification(
						"Permisions",
						"Ne pouvez pas télécharger le document dans le répertoire");
				break;
		}
		return false;
	}
}


/**
 * Function for creating a Json from an array of parameters for sending arrays trough POST
 * @param container_name
 * @param container_id
 * @return
 */
function generateParamJson(container_source_name, container_source_ids, container_target){
	var container_ids_array = container_source_ids.split(':');
	// first remove unwanted entries like 0
	var processed_array = new Array();
	for (var i = 0; i < container_ids_array.length ; i++){
		var input_target = $('#'+container_source_name+container_ids_array[i]);
		if (input_target.val() != '0'){
			processed_array.push(container_ids_array[i]);
		}
	}
		
	var json_string = '[';
	for (var i = 0; i < processed_array.length ; i++){
		var input_target = $('#'+container_source_name+processed_array[i]);
		if(i == (processed_array.length - 1))
			json_string += '{"name": "' + container_source_name+processed_array[i] + '", "value": "' + input_target.val()+'"}';
		else
			json_string += '{"name": "' + container_source_name+processed_array[i] + '", "value": "' + input_target.val()+'"},';
	}
	json_string += ']';
	$('#'+container_target).val(json_string);
}

/**
 * Method for populating and showing/hiding a container
 * First we populate, after if data is already there we just show/hide
 * @param module
 * @param action
 * @param param
 * @param container_id
 */
function toogleAjax(module, action, param, container_id){
	if($("#"+container_id).children().length == 0){
		$('body').append(
				'<div class="ui-widget-overlay" style="position: fixed; width: 100%; height: 100%; z-index: 11;" /><div style="position: fixed; left: 56%; top: 400px; z-index: 13;" id="preloader"><img src="globals/resources/images/ajax-loader.gif" border="0" /></div>'
			);
		$.get('index.php?module='+module+'&action='+action+param,
		function(html) {
			$("#"+container_id).append(html);
			$("#"+container_id).show();
			$('a.noFollow').click(function(event) {
				event.preventDefault();
			});
			$('.ui-widget-overlay').remove();
			$('#preloader').remove();
		});
	}
	else {
		if($('#'+container_id).is(':visible'))
			$('#'+container_id).hide(); 
		else if($('#'+container_id).is(':hidden'))
			$('#'+container_id).show(); 
	}
	return true;
}

/**
 * Close a specific div from his class
 * @param ul_class

 * @return
 */
function closeDiv(ul_class){
	$('ul .' + ul_class).hide();
}

function change_color(id){
	for (i = 1; i <= 7; i++) 
		for(j = 1; j <= 10; j++) {
		var buton = 'link' + i + j;
		if ("" + i + j == id) {
			$("#"+buton).attr('class','green');
		} else {
			$("#"+buton).attr('class','black');
		}
	}
}

/**
 * method used for project form for the child answers
 * enable or disabled the child of selected parent answers
 * @param parent_id
 * @param category_id
 */
function changeDisabledChild(parent_id, category_id){
	var element_name = document.getElementsByName('parent_array[' + category_id + ']');
	for(var i = 0; i < element_name.length; i++)
	{
		var obj = element_name[i];
		if(obj.value == parent_id) {
			for(var j = 0; j < 3; j++)
					document.getElementById('parent_' + obj.value + '_' + j).disabled = false;
		}
		else {
			for(var j = 0; j < 3; j++) {
				document.getElementById('parent_' + obj.value + '_' + j).checked = false;
				document.getElementById('parent_' + obj.value + '_' + j).disabled = true;
			}
		}
    }
}

function utf8_encode (argString) {
    // Encodes an ISO-8859-1 string to UTF-8  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/utf8_encode    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'    
 var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
    var utftext = "",
        start, end, stringl = 0;
 
    start = end = 0;    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;
         if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.slice(start, end);            }
            utftext += enc;
            start = end = n + 1;
        }
    } 
    if (end > start) {
        utftext += string.slice(start, stringl);
    }
     return utftext;
}

function base64_encode (data) {
    // Encodes string using MIME base64 algorithm  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/base64_encode    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // +   improved by: Thunder.m
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Pellentesque Malesuada    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
    // mozilla has this native    // - but breaks in 2.0.0.12!
    //if (typeof this.window['atob'] == 'function') {
    //    return atob(data);
    //}
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
        ac = 0,
        enc = "",
        tmp_arr = [];
     if (!data) {
        return data;
    }
 
    data = utf8_encode(data + ''); 
    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++); 
        bits = o1 << 16 | o2 << 8 | o3;
 
        h1 = bits >> 18 & 0x3f;
        h2 = bits >> 12 & 0x3f;        h3 = bits >> 6 & 0x3f;
        h4 = bits & 0x3f;
 
        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);    } while (i < data.length);
 
    enc = tmp_arr.join('');
 
    switch (data.length % 3) {    case 1:
        enc = enc.slice(0, -2) + '==';
        break;
    case 2:
        enc = enc.slice(0, -1) + '=';        break;
    }
 
    return enc;
}
