/* create an array of days which need to be disabled */ 
/*var disabledDays = ["23/05/2010","24/05/2010"]; 

function nationalDays(date) { 
  var m = date.getMonth(), d = date.getDate(), y = date.getFullYear(); 
  for (i = 0; i < disabledDays.length; i++) { 
    if($.inArray(d + '/' + m + '/' + y,disabledDays) != -1 || new Date() > date) { 
      return [false];
    }
  }
  return [true]; 
} 

function parsedays(date) { 
  var noWeekend = jQuery.datepicker.noWeekends(date); 
  return noWeekend[0] ? nationalDays(date) : noWeekend; 
}*/

var g_log_stack = new Array();
var timer = 0;
var g_newuser = 1;

function nslog (text) {
	clearTimeout(timer);
	timer = setInterval(nslog_write_to_server, 5*60000);
    if (typeof console !== 'undefined') {
        console.log('NSLOG:'+text);
    }
    else {
        //alert(text);    
    }
    
    nslog_add_to_stack(" "+text);
    if(g_log_stack.length > 9) {
    	nslog_write_to_server();
    }
}

function nslog_add_to_stack(text){
	g_log_stack.push(text);
}
function nslog_write_to_server(){
	if(g_log_stack.length > 0) {
		var text = g_log_stack.join('\n');
		$.post("writelog.php", {input: text, newuser: g_newuser}, function(data){
			//console.log("writelog.php:"+data);
			g_log_stack = new Array();
			g_newuser = 0;
	 	});
	}
}

jQuery(function($){
	$.datepicker.regional['fr'] = {
		closeText: 'Fermer',
		prevText: '&#x3c;Préc',
		nextText: 'Suiv&#x3e;',
		currentText: 'Courant',
		monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
		'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
		monthNamesShort: ['Janvier','Février','Mars','Avril','Mai','Juin',
		'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
		dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
		dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
		dayNamesMin: ['D','L','M','M','J','V','S'],
		weekHeader: 'Sm',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: '',
		changeYear: true,
		changeMonth : true,
		duration: 'fast',
		constrainInput: false,
		showCurrentAtPos: 0,
		numberOfMonths: [1, 1]};
	$.datepicker.setDefaults($.datepicker.regional['fr']);
});


function checkKey(element)
{
    if (window.event.keyCode == 13)
    {
        try{
        	element.onchange();
        }
	      catch(err)
		  {
		  //No onchange method on this element
		  }
        return false;
    }
}
    
function loadf()
{
	//alert("LOAD OK");	
}

function LoadDesc(id,TabDesc)
{
	//alert(id + ":" + TabDesc[id]);
	var programme = document.getElementById('programme');
	programme.innerHTML = TabDesc[id];
		
}

function DeleteOptionsFromAge(dateanniv)
{
	var selectdate = document.getElementById('date');
	var nboption = selectdate.childNodes.length;
	//alert(nboption);
	
	Today = new Date;
	var Jour = Today.getDate();
	var Mois = (Today.getMonth())+1;
	var Annee = Today.getFullYear();

	var dateannivslipt = dateanniv.split('/');
	var Age = Annee - dateannivslipt[2];
	
	var len = selectdate.childNodes.length;

	if(len == 0) len = 1;
	var i = 0;
	for (i = len-1; i >= 0; i--)
	{
		if((Age <= 12) && (Age>= 6))
		{//Enfant
			//Si le contenu de l'event contient ! => Ados, on l'efface du select
			if(selectdate.childNodes[i].innerHTML.indexOf('!') != -1)
			{
				//selectdate.removeChild(selectdate.childNodes[i]);
				//TabDesc.splice(i,1);
				//TabDispo.splice(i,1);
			}
		}
		else if(Age >= 12)
		{//Ados
			//Si le contenu de l'event NE contient PAS ! => Ados, on l'efface du select
			if(selectdate.childNodes[i].innerHTML.indexOf('!') == -1)
			{
				//selectdate.removeChild(selectdate.childNodes[i]);
				//TabDesc.splice(i,1);
				//TabDispo.splice(i,1);
			}
		}
		else
		{
			alert('D\'apres la date de naissance de l\'enfant, il ne peux pas encore participer à un atelier Cook&Croc\'.');
			var el_img = document.getElementById('enfant_datedenaissance_img');
			$('#enfant_datedenaissance_img').hide();
			el_img.src = '../rw_common/themes/seasonal/images/tomatoe_little.png';
			$('#enfant_datedenaissance_img').fadeIn(300);
			checkrequierdfields();
			break;
		}
	}
}

function getElementsByClass( searchClass, domNode, tagName) {
	if (domNode == null) domNode = document;
	if (tagName == null) tagName = '*';
	var el = new Array();
	var tags = domNode.getElementsByTagName(tagName);
	var tcl = " "+searchClass+" ";
	for(i=0,j=0; i<tags.length; i++) {
		var test = " " + tags[i].className + " ";
		if (test.indexOf(tcl) != -1)
			el[j++] = tags[i];
	}
	return el;
}

function DisplayEveryFieldsRequierd()
{
   alert("Veuillez d'abord remplir tous les champs obligatoires.");
}
   
function checkrequierdfields()
{
	var ok = 0;
	var nbok = 0;
	var champs = getElementsByClass('check_img');
	
	for(var i=0, n=champs.length; i<n; i++)
	{
	   if(champs[i].getAttribute("src" ) == '../rw_common/themes/seasonal/images/kiwi_little.png')
	   {
	   		nbok++;
	   }
	}

	$('#submit').hide();
	var submitel = document.getElementById('submitel');
	var textenvoyer = document.getElementById('textenvoyer');
	
	if((nbok >=8) || bAdmin)
	{
		submitel.src = '../rw_common/themes/seasonal/images/kiwi.png';
		submitel.disabled = '';
		submitel.alt = "Cliquez ici pour envoyer le formulaire à Cook&Croc'";
		submitel.title = "Cliquez ici pour envoyer le formulaire à Cook&Croc'";
		textenvoyer.innerHTML = 'Envoyer';
		textenvoyer.style.color = '#FFF';
		ok = 1;
	}
	else
	{
		submitel.src = '../rw_common/themes/seasonal/images/kiwi_disabled.png';
		submitel.disabled = 'true';
		submitel.alt = "Completer correctement le formulaire pour pouvoir l'envoyer à Cook&Croc'";
		submitel.title = "Completer correctement le formulaire pour pouvoir l'envoyer à Cook&Croc'";
		textenvoyer.innerHTML = 'Envoyer';
		textenvoyer.style.color = '#333';
		ok = 0;
	}
	$('#submit').fadeIn(300);
	
	return ok;
}

function submitform()
{
	var ok = checkrequierdfields();
	
	if(ok == 1)
	{
		document.myform.submit();
	}
}


function resetrequierdfields()
{
	var nbok = 0;
	var champs = getElementsByClass('check_img');
	
	for(var i=0, n=champs.length; i<n; i++)
	{
		champs[i].src = '../rw_common/themes/seasonal/images/tomatoe_little.png';
	}

	$('#submit').hide();
	var submitel = document.getElementById('submit');
	var textenvoyer = document.getElementById('textenvoyer');
	
	submitel.src = '../rw_common/themes/seasonal/images/kiwi_disabled.png';
	submitel.disabled = 'true';
	submitel.alt = "Completer correctement le formulaire pour pouvoir l'envoyer a Cook&Croc'";
	submitel.title = "Completer correctement le formulaire pour pouvoir l'envoyer a Cook&Croc'";
	textenvoyer.innerHTML = 'Envoyer';
	textenvoyer.style.color = '#333';
	$('#submit').fadeIn(300);
	
	var el_img = document.getElementById('gift_img');
	el_img.src = '../rw_common/themes/seasonal/images/kiwi_little.png';
}


function clearDefault(el) {
  if (el.defaultValue==el.value) el.value = "";
}

function check_selectdate(el,id,TabDispo)
{
	//alert(id + ":" + TabDesc[id]);
	var dispo = TabDispo[id];

	var el_img = document.getElementById(el.name + '_img');
	$('#' + el.name + '_img').hide();

	if(dispo == 0)
	{
		el_img.src = '../rw_common/themes/seasonal/images/tomatoe_little.png';
		alert("Attention : cet atelier est déjà complet. Veuillez s'il vous plaît choisir une autre date.");
	}
	else
	{
		el_img.src = '../rw_common/themes/seasonal/images/kiwi_little.png';
	}
	$('#' + el.name + '_img').fadeIn(300);
	checkrequierdfields();
}

function check_date(el)
{
	var el_img = document.getElementById(el.name + '_img');
	
	var valuestring = validateFRDate(el.value)
	if(valuestring != 0)
	{
		//$('#' + el.name + '_img').hide();
		el_img.src = '../rw_common/themes/seasonal/images/kiwi_little.png';
		el.value = valuestring;
		if(el.name == 'enfant_datedenaissance') DeleteOptionsFromAge(el.value);
	}
	else
	{
		$('#' + el.name + '_img').hide();
		el_img.src = '../rw_common/themes/seasonal/images/tomatoe_little.png';
	}
	$('#' + el.name + '_img').fadeIn(300);
	checkrequierdfields();
}

function check_string(el)
{
	var div_img = document.getElementById(el.name + '_img');
	
	if(validateString(el.value))
	{
		div_img.src = '../rw_common/themes/seasonal/images/kiwi_little.png';
		el.value = removeCommas(el.value);
		el.value = el.value.toUpperCase();
		
		if(el.name == 'parent_nom')
		{
			var div_enfant_nom = document.getElementById('enfant_nom');
			div_enfant_nom.value = el.value;
			check_string(div_enfant_nom);
		}
	}
	else
	{
		div_img.src = '../rw_common/themes/seasonal/images/tomatoe_little.png';
	}
	$('#' + el.name + '_img').hide().fadeIn(300);
	checkrequierdfields();
}

function check_gift(el,id)
{
	var el_img = document.getElementById(el.name + '_img');
	
	if(el.value != '')
	{
		if(validateGift(el.value) || (el.value == ''))
		{
			//alert("Vous allez être redirigé vers le formulaire correspondant au numéro cadeau que vous venez de saisir.");
			if(el.value.substr(0,1) != id) window.location.href = "http://www.cookncroc.com/inscription/index.php?id=" + el.value.substr(0,1) + "&type=2&gift=" + el.value;
			el_img.src = '../rw_common/themes/seasonal/images/kiwi_little.png';
		}
		else
		{
			el_img.src = '../rw_common/themes/seasonal/images/tomatoe_little.png';
		}
		$('#' + el.name + '_img').hide().fadeIn(300);
		checkrequierdfields();
	}
	else
	{
		el_img.src = '../rw_common/themes/seasonal/images/kiwi_little.png';
	}
}


function check_phone(el)
{
	var el_img = document.getElementById(el.name + '_img');
	
	if(validateFRPhone(el.value))
	{
		el_img.src = '../rw_common/themes/seasonal/images/kiwi_little.png';
	}
	else
	{
		el_img.src = '../rw_common/themes/seasonal/images/tomatoe_little.png';
	}
	$('#' + el.name + '_img').hide().fadeIn(300);
	checkrequierdfields();
}

function check_email(el)
{
	var el_img = document.getElementById(el.name + '_img');

	if (validateEmail(el.value))
	{
		el_img.src = '../rw_common/themes/seasonal/images/kiwi_little.png';
	}
	else
	{
		el_img.src = '../rw_common/themes/seasonal/images/tomatoe_little.png';
	}
	$('#' + el.name + '_img').hide().fadeIn(300);
	checkrequierdfields();
}

function validateString( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains valid
  US phone pattern.
  Ex. abCDE123@abcdEF45.ABCabc

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
  var objRegExp  = /^.{1,}$/;
  return objRegExp.test(strValue);
}


function validateEmail( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains valid
  US phone pattern.
  Ex. abCDE123@abcdEF45.ABCabc

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
  var objRegExp  = /^.+\@.+\..{2,4}$/;
  return objRegExp.test(strValue);
}


function validateFRPhone( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains valid
  US phone pattern.
  Ex. 00.00.00.00.00

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
  var objRegExp  = /^\d{2}(\-|\/|\.|\ |)\d{2}(\-|\/|\.|\ |)\d{2}(\-|\/|\.|\ |)\d{2}(\-|\/|\.|\ |)\d{2}(\-|\/|\.|\ |)$/;
  return objRegExp.test(strValue);
}

function validateGift( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains valid
  US phone pattern.
  Ex. ABCD00 ou abcd00

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
  var objRegExp  = /^[0-9]{1}[a-zA-Z]{4}[0-9]{2}$/;
  return objRegExp.test(strValue);
}

function removeCommas( strValue ) {
/************************************************
DESCRIPTION: Removes commas from source string.

PARAMETERS:
  strValue - Source string from which commas will
    be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /,/g; //search for commas globally

  //replace all matches with empty strings
  return strValue.replace(objRegExp,'');
}

function validateValue( strValue, strMatchPattern ) {
/************************************************
DESCRIPTION: Validates that a string a matches
  a valid regular expression value.

PARAMETERS:
   strValue - String to be tested for validity
   strMatchPattern - String containing a valid
      regular expression match pattern.

RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp = new RegExp( strMatchPattern);

 //check if string matches pattern
 return objRegExp.test(strValue);
}

function removeCharacters( strValue, strMatchPattern ) {
/************************************************
DESCRIPTION: Removes characters from a source string
  based upon matches of the supplied pattern.

PARAMETERS:
  strValue - source string containing number.

RETURNS: String modified with characters
  matching search pattern removed

USAGE:  strNoSpaces = removeCharacters( ' sfdf  dfd',
                                '\s*')
*************************************************/
 var objRegExp =  new RegExp( strMatchPattern, 'gi' );

 //replace passed pattern matches with blanks
  return strValue.replace(objRegExp,'');
}

function validateFRDate( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid dates with 2 digit month, 2 digit day,
    4 digit year. Date separator can be ., -, or /.
    Uses combination of regular expressions and
    string parsing to validate date.
    Ex. dd/mm/yyyy

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
  var objRegExp = /^\d{1,2}(\/|\-|\.| )(\d{1,2}|[a-zA-Zéû]{3,})(\/|\-|\.| )\d{4}$/;
 
  //check to see if in correct format
  if(!objRegExp.test(strValue))
  {
  	//alert("FAILED");
    return 0; //doesn't match pattern, bad date
  }
  else{

    var pos = strValue.indexOf("/",0);
    if(pos == -1) pos = strValue.indexOf(".",0);
    if(pos == -1) pos = strValue.indexOf("-",0);
    if(pos == -1) pos = strValue.indexOf(" ",0);
    //alert("pos=" + pos);
    if(pos != 0)
    {
    	
    	var strSeparator = strValue.substring(pos,pos+1);
    	//alert("separator=" + strSeparator);
    }
    
    var arrayDate = strValue.split(strSeparator); 
    //create a lookup for months not equal to Feb.
    var arrayLookup = { '01' : 31,'03' : 31, 
                        '04' : 30,'05' : 31,
                        '06' : 30,'07' : 31,
                        '08' : 31,'09' : 30,
                        '10' : 31,'11' : 30,'12' : 31}
    var intDay = parseInt(arrayDate[0],10);

	var objRegExp2 = /^[a-zA-Zéû]{3,}$/;
	if(objRegExp2.test(arrayDate[1]))
	{
		var month_text = arrayDate[1];
		var month_number = 0;
		//alert(month_text.toLowerCase());
		if(month_text.toLowerCase() == 'janvier') month_number = '01';
		if(month_text.toLowerCase() == 'février') month_number = '02';
		if(month_text.toLowerCase() == 'fevrier') month_number = '02';
		if(month_text.toLowerCase() == 'mars') month_number = '03';
		if(month_text.toLowerCase() == 'avril') month_number = '04';
		if(month_text.toLowerCase() == 'mai') month_number = '05';
		if(month_text.toLowerCase() == 'juin') month_number = '06';
		if(month_text.toLowerCase() == 'juillet') month_number = '07';
		if(month_text.toLowerCase() == 'août') month_number = '08';
		if(month_text.toLowerCase() == 'aout') month_number = '08';
		if(month_text.toLowerCase() == 'septembre') month_number = '09';
		if(month_text.toLowerCase() == 'octobre') month_number = '10';
		if(month_text.toLowerCase() == 'novembre') month_number = '11';
		if(month_text.toLowerCase() == 'décembre') month_number = '12';
		if(month_text.toLowerCase() == 'decembre') month_number = '12';
		
		if(month_number == 0) return 0;
		
		arrayDate[1] = month_number;
	}

    //check if month value and day value agree
    if(arrayLookup[arrayDate[1]] != null) {
      if(intDay <= arrayLookup[arrayDate[1]] && intDay != 0)
        return arrayDate[0] + "/" + arrayDate[1] + "/" + arrayDate[2]; //found in lookup table, good date
    }

    var intMonth = parseInt(arrayDate[1],10);
    if (intMonth == 2) { 
       var intYear = parseInt(arrayDate[2]);
       if (intDay > 0 && intDay < 29) {
           return arrayDate[0] + "/" + arrayDate[1] + "/" + arrayDate[2];
       }
       else if (intDay == 29) {
         if ((intYear % 4 == 0) && (intYear % 100 != 0) || 
             (intYear % 400 == 0)) {
              // year div by 4 and ((not div by 100) or div by 400) ->ok
             return arrayDate[0] + "/" + arrayDate[1] + "/" + arrayDate[2];
         }   
       }
    }
  }  
  return 0; //any other values, bad date
}

function validateNotEmpty( strValue ) {
/************************************************
DESCRIPTION: Validates that a string is not all
  blank (whitespace) characters.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
   var strTemp = strValue;
   strTemp = trimAll(strTemp);
   if(strTemp.length > 0){
     return true;
   }
   return false;
}

// limit to part of the page ... pass an ID to limitTo:
//supersleight.limitTo('navcontainer');
