/**
 * Fonctions javascripts propres au site publique de tv5.ca
 */

/* calendrier grille horaire	*/
function selectDate(year, month, day)
{
	new Ajax.Updater('calendar', '/index.php/ctrlprogramme/showCalendar/'+year+'/'+month+'/'+day, {});
	new Ajax.Updater('ls_semaine', '/index.php/ctrlprogramme/showListeSemaine/'+year+'/'+month+'/'+day, {});

	new Ajax.Updater('ls_jour',
					'/index.php/ctrlprogramme/afficherGrilleHoraire/'+year+'/'+month+'/'+day,
					{
						onComplete: function()
						{
							filtreThemeGrilleHoraire($('i_grille_display').value,$('i_grille_display').options[$('i_grille_display').selectedIndex].innerHTML);
						}
					});
	
	var selectedDate = new Date(year, (month-1), day);
	var weekDay = selectedDate.getDay();

	switch(weekDay)
	{
		case 0 : 
			xt_med('F', '3', 'fin_de_semaine::dimanche');
			break;
		case 1 : 
			xt_med('F', '3', 'semaine::lundi');
			break;
		case 2 : 
			xt_med('F', '3', 'semaine::mardi');
			break;
		case 3 : 
			xt_med('F', '3', 'semaine::mercredi');
			break;
		case 4 : 
			xt_med('F', '3', 'semaine::jeudi');
			break;
		case 5 : 
			xt_med('F', '3', 'semaine::vendredi');
			break;
		case 6 : 
			xt_med('F', '3', 'fin_de_semaine::samedi');
			break;
	}
}

function selectMonth(year, month)
{
	new Ajax.Updater('calendar', '/index.php/ctrlprogramme/showCalendar/'+year+'/'+month+'/1', {});
}

function semainePrecedente(year, month, day)
{
	day-=7;
	if (day==0) day=1;
	selectDate(year, month, day);
}
function semaineSuivante(year, month, day)
{
	day+=7;
	selectDate(year, month, day);
}

/* FIN grille horaire	*/

function login()
{
	if(validateForm($('form_login'))) {
            new Ajax.Updater('box_login_user', '/index.php/ctrlprofil/login/',{
                parameters: {
                    i_login_mail:$F('i_login_mail'),
                    i_login_pass:$F('i_login_pass')
                },
                onComplete: function(transport){
                	if (stristr(transport.responseText, '<div class="error"><p class="error">')) {
                		return;
                	} else {
                    	history.go(0);
                    }
                }
            });
	}
}
function logout()
{
	new Ajax.Updater('box_login_user', '/index.php/ctrlprofil/logout/', {
                onComplete: function(){
                if(location.href.indexOf('/profil/')!=-1){
                        location.href='/index.html';
                }
                history.go(0);
            }
	});
}


function stristr (haystack, needle, bool) 
{
    var pos = 0;

    haystack += '';
    pos = haystack.toLowerCase().indexOf( (needle+'').toLowerCase() );
    if (pos == -1){
        return false;
    } else{
       return true;
    }
}



/***************************************************************************************
 * Login box refresh (the php loaded one is messed up in concours, refresh fixes that)
 ***************************************************************************************/
function rafraichirBoiteLogin()
{

}
/************
 * END PATCH 
 ************/

function rafraichirBoiteProfil()
{
	new Ajax.Updater('box_login_user', '/index.php/ctrlprofil/rafraichirBoiteProfil/', {
		onComplete: function(){
			box_user.bt.generate();
            var d=new Date();
            var day=d.getDate();
            var month=d.getMonth() + 1;
            var year=d.getFullYear();
            selectDate(year,month,day);
            listAlert();
            updateAlert();
		}
	});
}

/**
 * Fonction emprunter à jsLib.js (alex michaud)
 * @param {Element object} obj
 */
function removeChilds(obj){
	while(obj.hasChildNodes())
		obj.removeChild(obj.lastChild);
}

tabMessageErreur	= new Array();
tabMessageErreur["@email@"]				= "Vous devez entrer un courriel dans un format valide.";
tabMessageErreur["@emailConfirm@"]		= "Les adresses courriels ne correspondent pas.";
tabMessageErreur["@password@"]			= "Vous devez entrer votre mot de passe.";
tabMessageErreur["@passwordConfirm@"]	= "Les mots de passes ne correspondent pas.";
tabMessageErreur["@gender@"]			= "Politesse : Vous devez faire un choix.";
tabMessageErreur["@firstName@"]			= "Vous devez entrer votre prénom.";
tabMessageErreur["@lastName@"]			= "Vous devez entrer votre nom.";
tabMessageErreur["@address@"]			= "Vous devez entrer votre adresse.";
tabMessageErreur["@city@"]				= "Vous devez entrer votre ville.";
tabMessageErreur["@province@"]			= "Vous devez choisir votre province.";
tabMessageErreur["@country@"]			= "Vous devez choisir votre pays.";
tabMessageErreur["@postalCode@"]		= "Vous devez entrer un code postal dans un format valide.";
tabMessageErreur["@age@"]				= "Vous devez choisir votre tranche d'âge.";
tabMessageErreur["@timeZone@"]			= "Vous devez choisir votre fuseau horaire.";
tabMessageErreur["@jobCV@"]				= "Vous devez joindre votre CV.";
tabMessageErreur["@endDate@"]			= "La date de fin de publication doit être supérieur à la date de début.";
tabMessageErreur["@beginDate@"]			= "Erreur date de publication.";

/**
 * Ajoute les erreurs dans l'élément divId
 * @param {Element Id} divId
 */
function showErrors(divId)
{
	removeChilds($(divId)); // enlève les erreurs s'il y en a
	if(errorsObj.length>0){
		var divError = document.createElement('DIV');
		divError.className = "error";
		for(i=0;i<errorsObj.length;i++){
			if(errorsObj[i].getAttribute('js:message')){
				var pError = document.createElement('P');
				if( result = errorsObj[i].getAttribute('js:message').match("^@[^@]*@$") ){
					pError.innerHTML = tabMessageErreur[result[0]];
					errorsObj[i].title = tabMessageErreur[result[0]];
				}
				else{
					pError.innerHTML = errorsObj[i].getAttribute('js:message');
					errorsObj[i].title = errorsObj[i].getAttribute('js:message');
				}
				pError.className = errorsObj[i].getAttribute('js:errorclass');
				divError.appendChild(pError);
			}
			js.addClass(labelNodes[getLabelIndex(errorsObj[i].id)].firstChild, errorsObj[i].getAttribute('js:errorclass'));
		}
		$(divId).appendChild(divError);
		$(divId).scrollTo();
	}
}
function recupMotDePasse()
{
	new Ajax.Updater('box_login_user', '/index.php/ctrlprofil/recupMotDePasse/', {parameters: { i_login_mail:$F('i_login_mail') }});
}

function trouverSerieParTheme(theme)
{
	new Ajax.Updater('i_fast_search_emission', '/index.php/ctrlemissions/trouverSerieParTheme/'+theme, {});
}

function validerAccesRapide()
{
	try{
		if($('fast_search_error'))
			removeChilds($('fast_search_error')); // enlève les erreurs s'il y en a
	}
	catch(err) {}

	// on s'assure que les options choisis ne sont pas les 2è (2è option == '-----------')
	if($('i_fast_search_cat').selectedIndex==1 || $('i_fast_search_emission').selectedIndex==1)
		return false;

	// cas d'exeption pour IE
	if( ($('i_fast_search_cat').selectedIndex==0 || $('i_fast_search_cat').selectedIndex==1) && ($('i_fast_search_emission').selectedIndex==1))
		return false;

	// on verifie si nous sommes dans la page 'emissions'
	if(document.location.href.indexOf('emissions')!=-1){
		// si oui on s'assure que l'internaute a choisit un thème
		if($('i_fast_search_cat').selectedIndex==0){
			var divError = document.createElement('DIV');
			divError.className = "error";
			var pError = document.createElement('P');
			pError.className = "error";
			pError.innerHTML = "Vous devez choisir un thème.";
			divError.appendChild(pError);
			$('fast_search_error').appendChild(divError);
			return false;
		}
	}
	return true;
}

function trouverWebvideoParTheme(theme)
{
	new Ajax.Updater('i_fast_search_webvideo', '/ctrlwebvideo/trouverWebvideoParTheme/'+theme, {});
}

function validerAccesRapideWebvideo()
{
	removeChilds($('fast_search_error')); // enlève les erreurs s'il y en a

	// on s'assure que les options choisis ne sont pas les 2è (2è option == '-----------')
	if($('i_fast_search_cat').selectedIndex==1 || $('i_fast_search_webvideo').selectedIndex==1)
		return false;

	// cas d'exeption pour IE
	if( ($('i_fast_search_cat').selectedIndex==0 || $('i_fast_search_cat').selectedIndex==1) && ($('i_fast_search_webvideo').selectedIndex==0))
		return false;

	// on verifie si nous sommes dans la page 'webvideo'
	if(document.location.href.indexOf('webvideo')!=-1){
		// si oui on s'assure que l'internaute a choisit un thème
		if($('i_fast_search_cat').selectedIndex==0){
			var divError = document.createElement('DIV');
			divError.className = "error";
			var pError = document.createElement('P');
			pError.className = "error";
			pError.innerHTML = "Vous devez choisir un thème.";
			divError.appendChild(pError);
			$('fast_search_error').appendChild(divError);
			return false;
		}
	}
	return true;
}


/*
* function pour la recherche :permet de ne pas envoyer de recherche vide
*
* @author Alexis
* @param null
* @return void
*/
function envoieRecherche()
{
	var boolOk = false;
	var chaineRecherche = document.getElementById("i_search").value;

	if (chaineRecherche != '')
	{
		chaineRecherche = chaineRecherche.replace(/^\s+|\s+$/g,"");
		if (chaineRecherche.length > 0)
		{
			boolOk = true;
		}
	}

	if (boolOk == true)
	{
		document.getElementById("form_search").submit();
	}

}

/**
 * filtrer la programmation par thème dans la page Grille horaire
 * @param {Object} cssTheme
 * @param {Object} nomTheme
 */
function filtreThemeGrilleHoraire(cssTheme, nomTheme)
{
	var listeElem = $$('li.tm_act','li.tm_cin','li.tm_spr','li.tm_quz','li.tm_zin','li.tm_jeu','li.tm_doc','li.tm_div');
	for(i=0;i<listeElem.length;i++){
		listeElem[i].style.display = 'block';
	}
	$('filtre_info').innerHTML = '';

	for(i=0;i<listeElem.length;i++){
		if(listeElem[i].className.indexOf(cssTheme)==-1)
			listeElem[i].style.display = 'none';
	}
	if(cssTheme != '')
		$('filtre_info').innerHTML = 'Vous regardez actuellement la programmation de la catégorie '+nomTheme+'.';
}

function highLightChangement(elemId)
{
	$(elemId).descendants()[0].style.display = 'inline-block';
	$(elemId).descendants()[0].innerHTML 	 = '<em>Vous êtes maintenant abonné(e)</em>';
	//new Effect.Highlight($(elemId).descendants()[0], { startcolor: '#ffff5c', endcolor: '#ffffff' });
	//$(elemId).descendants()[0].style.backgroundColor = '#ffff5c';
}
function modifierStatutInfolettreHebdo(intStatut)
{
	new Ajax.Request('/index.php/ctrlprofil/modifierStatutInfolettreHebdo/'+intStatut, {
		onSuccess: function(){
			rafraichirBoiteProfil();
			highLightChangement('info1');
		}
	});
}

function modifierStatutInfolettreSport(intStatut)
{
	new Ajax.Request('/index.php/ctrlprofil/modifierStatutInfolettreSport/'+intStatut, {
		onSuccess: function(){
			rafraichirBoiteProfil();
			highLightChangement('info2');
		}
	});
}

function modifierStatutConcours(intStatut)
{
	new Ajax.Request('/index.php/ctrlprofil/modifierStatutConcours/'+intStatut, {
		onSuccess: function(){
			rafraichirBoiteProfil();
			highLightChangement('info3');
		}
	});
}

function modifierStatutChangement(intStatut)
{
	new Ajax.Request('/index.php/ctrlprofil/modifierStatutChangement/'+intStatut, {
		onSuccess: function(){
			rafraichirBoiteProfil();
			highLightChangement('info4');
		}
	});
}

function modifierStatutPromotions(intStatut)
{
	new Ajax.Request('/index.php/ctrlprofil/modifierStatutPromotions/'+intStatut, {
		onSuccess: function(){
			rafraichirBoiteProfil();
			highLightChangement('info5');
		}
	});
}

function modifierStatutPartenaire(intStatut)
{
	new Ajax.Request('/index.php/ctrlprofil/modifierStatutPartenaire/'+intStatut, {
		onSuccess: function(){
			rafraichirBoiteProfil();
			highLightChangement('info6');
		}
	});
}

function rafraichirTourDroite()
{
	try{
		if($('container_antenne'))
		{
			js.update('container_antenne', '/index.php/ctrlemissions/infoAntenne/',{evalScripts:'true'});
	        try{
	          listAlert();
	        }catch(e){}
		}
	}
	catch(e){}
}
new PeriodicalExecuter(rafraichirTourDroite, 120);

function changerFuseauHoraire(fuseauHoraire){
	new Ajax.Request('/index.php/profil/changerFuseauHoraire/',{
			parameters:{ fuseauHoraire: fuseauHoraire },
            onComplete: function(){
				window.location.reload();
			}
		});

}

function villeMeteoDefaut(elem,codeVilleDefaut)
{
	new Ajax.Updater('meteo','/index.php/meteo/setVilleMeteo/',{
		parameters:{codeVille:codeVilleDefaut},
		onComplete: function(transport) {
			ville.dfault(elem);
		}
	});
	
	return false;
}

function trouverJourneeParComp(idComp)
{
	new Ajax.Updater('i_fast_search_day2', '/index.php/ctrlsport/getDayListe/'+idComp, {});
}

function trouverEssaiParComp(idComp)
{
	new Ajax.Updater('i_fast_search_day2', '/index.php/ctrlsport/getEssaiListe/'+idComp, {});
}

function trouverEtapeParComp(idComp)
{
	new Ajax.Updater('i_fast_search_day2', '/index.php/ctrlsport/getEtapeListe/'+idComp, {});
}

function trouverCatParCircuit(strCircuit)
{
	new Ajax.Updater('i_fast_search_cat', '/index.php/ctrlsport/getCategorieSki/'+strCircuit, {});
}

function trouverCatParCircuit2(strCircuit)
{
	trouverCatParCircuit(strCircuit)
	new Ajax.Updater('i_fast_search_etape', '/index.php/ctrlsport/getEtapeSki/', {});
}


function trouverEtapeParCat(idComp)
{
	new Ajax.Updater('i_fast_search_etape', '/index.php/ctrlsport/getEtapeSki/'+idComp, {});
}


function trouverClassementParCircuit(strCircuit)
{
	new Ajax.Updater('i_fast_search_cat', '/index.php/ctrlsport/getCategorieGalSki/'+strCircuit, {});
}


function setSportDefaut(intSport)
{
	new Ajax.Request('/index.php/ctrlsport/setSportDefaut/'+intSport, {
		onSuccess: function()
		{
			$('id_sport_defaut').innerHTML = "<p class=\"infos\">(Votre sport par défaut)</p>";
		}
	});
}

function showRecaptcha(element, themeName) {
	Recaptcha.create("6LfPDQYAAAAAAHZAlemc4mw8bX95ivii02NVauqj", element, {
		theme: themeName,
		tabindex: 0,
		lang: 'fr',
		callback: Recaptcha.focus_response_field
	});
}
