/**
 * Equivalent to PHP in_array : check if needle is present
 * in haystack array
 * @author	Simon Hostelet
 * @version	2009-09-19
 * @param needle, string
 * @param haystack, array
 * @param strict, bool
 * @return bool
 */
function in_array(needle, haystack, strict)
{
	if(strict)
	{
		for(key in haystack)
		{
			if(haystack[key] === needle)
				return true;
		}
	}
	else
	{
		for(key in haystack)
		{
			if(haystack[key] == needle)
				return true;
		}
	}

	return false;
}

/**
 * Using a pattern, find and return match1 on a text
 * Used in input names to retrieve an ID (see backend_combo_add_inputs.js for example)
 * Example :
 * 		You got a series of html tag, for instance :
 * 			<input type="text" id="foobar_1>
 * 			<input type="text" id="foobar_2>
 * 			...
 * 			<input type="text" id="foobar_20>
 *
 * To find out what is the number, you call findItemId :
 * var currentId = findItemId('foobar_([0-9]+)', jQuery(this).attr('id'));
 * The part between brackets will be returned. In our example : 1, 2, ... or 20
 * depending on which one you trigger.
 *
 * @param pattern, regexp schema
 * @param text, string to be tested
 * @return string
 */
function findItemId(pattern, text)
{
	var find = new RegExp(pattern, 'gi');
	var match = new Array();
	if(match = find.exec(text))
		return match[1];
	else
		return false;
}

/**
 * Count number of elements in an array that have length==0
 * @author	Simon Hostelet
 * @version	2009-09-19
 * @param elements, array
 * @return integer
 */
function countEmptyElements(elements)
{
	var elementCount = elements.length * 1;
	var i = 0;
	var nbElementsEmpty = 0;
	for(i=0; i<elementCount; i++)
	{
		if(elements[i].value.length == 0)
			nbElementsEmpty++;
	}
	return nbElementsEmpty;
}

function ucfirst (str) {
	// Makes a string's first character uppercase
	//
	// version: 909.322
	// discuss at: http://phpjs.org/functions/ucfirst
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   bugfixed by: Onno Marsman
	// +   improved by: Brett Zamir (http://brett-zamir.me)
	// *     example 1: ucfirst('kevin van zonneveld');
	// *     returns 1: 'Kevin van zonneveld'
	str += '';
	var f = str.charAt(0).toUpperCase();
	return f + str.substr(1);
}

/**
 * This function is called by a click on a link.
 * Change style display property to visible or invisble for
 * the given element param.
 * @author	Simon Hostelet
 * @version	2009-10-01
 * @param element
 * @return
 */
function show(event, element) {
	event.preventDefault();
	if(document.getElementById(element).style.display == 'none')
		document.getElementById(element).style.display = 'block';
	else
		document.getElementById(element).style.display = 'none';
}

function simpleEscape(element) {

	var new_element = '' ;
	new_element = element.replace(/"/g, '&quot;' );
	new_element = new_element.replace(/>/g,'&gt;');
	new_element = new_element.replace(/</g,'&lt;');

	return new_element ;
}

function str_pad (input, pad_length, pad_string, pad_type) {
  // http://kevin.vanzonneveld.net
  // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // + namespaced by: Michael White (http://getsprink.com)
  // +      input by: Marco van Oort
  // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
  // *     example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');
  // *     returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
  // *     example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
  // *     returns 2: '------Kevin van Zonneveld-----'

  var half = '', pad_to_go;

  var str_pad_repeater = function (s, len) {
      var collect = '', i;

      while (collect.length < len) {collect += s;}
      collect = collect.substr(0,len);

      return collect;
  };

  input += '';
  pad_string = pad_string !== undefined ? pad_string : ' ';
  
  if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') {pad_type = 'STR_PAD_RIGHT';}
  if ((pad_to_go = pad_length - input.length) > 0) {
      if (pad_type == 'STR_PAD_LEFT') {input = str_pad_repeater(pad_string, pad_to_go) + input;}
      else if (pad_type == 'STR_PAD_RIGHT') {input = input + str_pad_repeater(pad_string, pad_to_go);}
      else if (pad_type == 'STR_PAD_BOTH') {
          half = str_pad_repeater(pad_string, Math.ceil(pad_to_go/2));
          input = half + input + half;
          input = input.substr(0, pad_length);
      }
  }

  return input;
}





/*
 * Function count the number of character
 * in object identified by "object", and
 * prevent user from filling in more
 * than "max" characters.
 * Optionnal, an object identified by
 * "counter" can be provided in order
 * to display a feedback to user of
 * number of char remaining
 * 
 * @author	Simon
 */
function countChar(object, max, counter) {
	var charLength = jQuery(object).val().length;
	
	if(charLength > max) {
		// if length of string > max, we cut it to the max
		var substr = jQuery(object).val().substr(0, max);
		jQuery(object).val(substr);
		charLength = jQuery(object).val().length;
	}
	if(counter != null) {
		jQuery(counter).html(max - charLength);
	}
}

/*
 * This function returns true if
 * browser is MSIE6 or below
 * 
 * Useful to prevent an impossible to display script
 * to run with IE6 and shitty navigators like that
 * 
 * @author	Simon
 */
function isIe6()
{
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
		 var ieversion = new Number(RegExp.$1) // capture x.x portion and store as a number
		 if (ieversion <= 6) {
			 return true;
		 }
	}
	return false;
}
function isIe6orIe7()
{
        if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
                 var ieversion = new Number(RegExp.$1) // capture x.x portion and store as a number
                 if (ieversion <= 7) {
                         return true;
                 }
        }
        return false;
}

/*
 * This function returns true if
 * browser is MSIE7 or below
 * 
 * @author	Julian
 */
function isIe6or7()
{
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
		 var ieversion = new Number(RegExp.$1) // capture x.x portion and store as a number
		 if (ieversion <= 7) {
			 return true;
		 }
	}
	return false;
}


/*
 * Test if navigator platform is a tactile tablet, phone or such gear
 */
function isTablet()
{
  var platforms = new Array('iPad', 'iPhone', 'iPod');
  var user_platform = navigator.platform;
  if(in_array(user_platform, platforms))
  {
    return true;
  }
  return false;
}


/*
 * Change DOM element Object style bottom
 * depending on position of the window in the document.
 * 
 *  If user has scrolled down, we dont want the Object to
 *  cover up the #footer, so style.bottom value is set
 *  between 0px and #footer.height
 *  
 *  @author Simon
 */
function setBoxBottom(object) {
  var footer = jQuery('#footer');

  var doc_height = jQuery(document).height();
  var win_height = jQuery(window).scrollTop() + jQuery(window).height();
  
  var bottom = footer.height() - (doc_height - win_height);
  
  if(isTablet())
  {
    object.css('position', 'absolute');
    object.css('bottom', (doc_height - win_height) + 'px');
  }
  else
  {
    /*
     * Define Object bottom property 'bottom' to stick it to window's bottom
     * or to stick it at the top of the footer
     */
    if(bottom <= 0 && Math.round(object.offset().top + object.height()) <= Math.round(footer.offset().top))
    {
    object.css('bottom', '0px');
    }
    else if (bottom <= footer.offset().top)
    {
      bottom = win_height - footer.offset().top;
      object.css('bottom', '' + bottom + 'px');
    }
    else
    {
    object.css('bottom', '' + bottom  + 'px');
    }
  }
}


/*
 * Teste si le String commence / termine par l'argument passé en paramètre
 * source : http://stackoverflow.com/questions/646628/javascript-startswith
 */
String.prototype.startsWith = function (str) {
  return this.slice(0, str.length) == str;
}
String.prototype.endsWith = function (str) {
  return this.slice(-str.length) == str;
}

// Makes a string's first character uppercase
String.prototype.ucfirst = function()
{
  str = this + '';
	var f = str.charAt(0).toUpperCase();
	return f + str.substr(1);
}


/*
 * Faire apparaitre un flash notice ou error
 * Par exemple suite à une réponse ajax de formulaire
 */
function show_flash(type, msg, fade_after)
{
  var tag_id = 'flash_'+type+'_message';
  
  // Si jamais l'element existe deja
  jQuery('#' + tag_id).remove();
  
  jQuery('#container').prepend('<p id="'+tag_id+'">'+msg+'</p>');
  if(fade_after > 0)
  {
    var fadeOutFlash = function()
    {
      jQuery('#' + tag_id).fadeOut();
    }
    setTimeout(fadeOutFlash, 1000 * fade_after);
  }
}




/* Cookies, only for session */

function setCookie(c_name,c_value,exdays)
{
  //var exdate=new Date();
  //exdate.setDate(exdate.getDate() + exdays);
  //var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
  document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
  var i,x,y,ARRcookies=document.cookie.split(";");
  for (i=0;i<ARRcookies.length;i++)
  {
   x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
   y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
   x=x.replace(/^\s+|\s+$/g,"");
   if (x==c_name)
   {
     return unescape(y);
   }
  }
}


function sleep(ms)
{
  var date = new Date();
  date.setTime(date.getTime() + ms);
  while(new Date().getTime() < date.getTime());
}

