/*document.observe('dom:loaded', function () {
  if($('body_p') != null)
  {
	  var arrayPageSize = getPageSize();
	  if(arrayPageSize[1] < 1300)
	  {
	    $('body_p').setStyle({
	      backgroundImage: 'url(/images/theme/background_gradient_little.png)'
	    });
	  }
	  else if(arrayPageSize[1] < 2200)
	  {
	    $('body_p').setStyle({
	      backgroundImage: 'url(/images/theme/background_gradient_medium.png)'
	    });
	  }
  }
});*/

/**
 * Change la couleur des petites etoiles pour la note d'un film.
 */
function setStarColor(index, filmId) {
	var side = '';
    for(i=0; i<10; i++) {
    	(i%2 == 0) ? side = 'left' : side = 'right';
    	if(i <= index) { $('film_n_you_note_'+filmId+'_'+(i+1)).className = 'star_note_purple_'+side; }
    	else { $('film_n_you_note_'+filmId+'_'+(i+1)).className = 'star_note_gray_'+side; }
    }
}

/**
 * Retablit la couleur des petites etoiles en fonction de la note du film.
 */
function resetStarColor(note, filmId) {
    var side = '';
    for(i=0; i<10; i++) {
    	(i%2 == 0) ? side = 'left' : side = 'right';
    	if(i >= note) { $('film_n_you_note_'+filmId+'_'+(i+1)).className = 'star_note_gray_'+side; }
    	else { $('film_n_you_note_'+filmId+'_'+(i+1)).className = 'star_note_purple_'+side; }
    }
}

/**
 * Forme l'url pour faire une recherche
 */
function executeSearchSimple() {
	var Recherche = $('keywords_simple').value;
    
	if(Recherche.replace(/\s+ /g, '') != '') {
	    Recherche = replaceAccents(Recherche);
		var Categorie = $('categorie_simple').value;
        var urlCategorie = 'all';
        
        switch (Categorie) {
            case 'All': urlCategorie = 'tout'; break;
            case 'Filmfr': urlCategorie = 'film';  break;
            case 'Filmus': urlCategorie = 'film-us'; break;
            case 'Personne': urlCategorie = 'artiste'; break;
            case 'Listefr': urlCategorie = 'liste-film'; break;
            case 'Listeus': urlCategorie = 'liste-film-us'; break;
            case 'Video': urlCategorie = 'video-extrait'; break;
            case 'Users': urlCategorie = 'membre'; break;
            default: urlCategorie = 'all'; break;
        } 
        
		var Chemin = '/' + urlCategorie + '/' + Recherche + '';
		$('headerSearchForm').action = $('headerSearchForm').action + Chemin.replace(/\s+/g, '+');
		var Response = true;
	}
	else {
		var Response = false;
	}
    
	return Response;
}

function executeSearchAdvanced() {
	var Recherche = $('keywords_advanced').value;
	if(Recherche != '') {
		var Exact = 'noexact'
		if($('exact_advanced_exact').checked) {
			Exact = 'exact';
		}
		var Categorie = $('categorie_advanced').value;
		var Chemin = '/'+Categorie+'/'+Recherche+'/'+Exact;
		$('formSearchAdvanced').action = $('formSearchAdvanced').action+Chemin.replace(/\s+/g, '+');
		var Response = true;
	}
	else {
		var Response = false;
	}
	return Response;
}

function removeDefaultSearchLibSimple(Lib) {
	var Recherche = $('keywords_simple').value;
	if(Recherche == Lib) {
		$('keywords_simple').value = '';
	}
}

function setDefaultSearchLibSimple(Lib) {
	var Recherche = $('keywords_simple').value.replace(/\s+/g, "");
	if(Recherche == '') {
		$('keywords_simple').value = Lib;
	}
}

function removeDefaultSearchLibMesFilms(Lib) {
	var Recherche = $('mesfilms_search_field_input').value;
	if(Recherche == Lib) {
		$('mesfilms_search_field_input').value = '';
	}
}

function setDefaultSearchLibMesFilms(Lib) {
	var Recherche = $('mesfilms_search_field_input').value.replace(/\s+/g, "");
	if(Recherche == '') {
		$('mesfilms_search_field_input').value = Lib;
	}
}

function calcHeight(iframeId, morePix, getParent) {
    if(getParent) { var iframe = window.parent.document.getElementById(iframeId); }
    else { var iframe = document.getElementById(iframeId); }

	iframe.style.height = (iframe.contentWindow.document.getElementById('content').scrollHeight + morePix) + 'px'; //changement de la hauteur
}

/**
 * Change l'onglet actif sur la page "mon actu"
 */
function swithTab(tabToShow) {
    var tabs = $$('.mon_actu_tab_active');
    var tabsContent = $$('.mon_actu_tab_content');

    tabs.each( function(aTab) { aTab.className = 'mon_actu_tab'; } );
    tabsContent.each( function(aTabContent) { aTabContent.hide(); } );

    $(tabToShow).className = 'mon_actu_tab_active';
    $(tabToShow+'_content').show();
}

/**
 * Fonction utilis� pour r�aliser l'appel ajax d'ajout d'un film � une liste en cours de cr�ation.
 * @param route - route pour sauvegarder l'ajout du film dans la liste
 * @param listeId -
 * @param filmId -
 * @param sortRoute - route pour le sortable
 */
function addNewFilmToListe(route, listeId, filmId, sortRoute) {
    var time = (new Date()).getTime();
    var div_id = 'liste_film_'+filmId+'_'+time;
    if(!$(div_id)) {
        $('liste_film').insert('<div id="'+div_id+'" style="float: left; width: 100%;"></div>');
        new Ajax.Updater(div_id,
                         route,
                         { asynchronous:true,
                           evalScripts:false,
                           onComplete:function(request, json){$('waitPlease').hide()},
                           onLoading:function(request, json){$('waitPlease').show()},
                           parameters:{ liste: listeId, film: filmId, time: time }
                         } );

        // on recr� un Sortable pour prendre en compte la div ajout�e
        Sortable.create('liste_film',
                        { onUpdate:function() {
                                       new Ajax.Request(sortRoute+'?listeId='+listeId,
                                                       {asynchronous:true,
                                                        evalScripts:false,
                                                        onComplete:function(request, json){var films = $$('div.liste_film_item_rank_top'); films.each(function(aFilm, index){ aFilm.replace('<div class="liste_film_item_rank_top">'+(index+1)+'</div>'); }); new Effect.Appear(element, {});},
                                                        parameters: Sortable.serialize('liste_film')
                                                       });
                                   },
                          tag:'div'
                        });

        $('nb_liste_films').innerHTML = parseInt($('nb_liste_films').innerHTML) + 1;
    }
    else {
        alert("Impossible d'ajouter ce film. Il est peut etre deja present dans la liste.");
    }

    return false;
}

/**
 * Fonction pour recup les tags � ajouter � un film.
 * Voir le partial tag/tagFilmForm.
 */
function getAddedAutoCompleteElmt(elmtId,inputName) {
	var last_saisie = $(inputName).value.replace(/^\s+/g,'').replace(/\s+$/g,'').replace(/^,/g,'');
    var children = $(elmtId).getElementsByTagName('div');
    var alltags = " { ";

    if(last_saisie.length>0){
    	alltags += elmtId+":"+last_saisie.replace(/^\s+/g,'').replace(/\s+$/g,'').replace(/^,/g,'');
    	if(children.length>0){
    		alltags += ";";
    	}
    }

    for(i=0; i<children.length; i++) {
        var span = children[i].getElementsByTagName('span');
        var tagName = span[0].innerHTML;

        alltags += children[i].id + ":" + tagName.replace(/^\s+/g,'').replace(/\s+$/g,'');
        if(i != children.length-1) { alltags += ";"; }
    }

    alltags += " }";

    return alltags;
}

/**
 * Place le contenu saisi dans tiny mce dans le textarea corespondant.
 */
function getTinyMCEContent(textareaClass) {
    var containers = $$('.mceIframeContainer');
    var iframes = containers[0].getElementsByTagName('iframe');
    var mceIframe = iframes[0];
    var mceContent = mceIframe.contentWindow.document.body.innerHTML;
    var textearea = $$(textareaClass);
    textearea[0].value = mceContent;
}

function majPoints(conteneur_point,conteneur_message){
	var reg=new RegExp('Impossible');
	var reg2=new RegExp('Connecte-toi');
	if(!reg.test($(conteneur_message).innerHTML)&&!reg2.test($(conteneur_message).innerHTML)){
		$(conteneur_point).innerHTML = parseInt($(conteneur_point).innerHTML)+1
	}
}

function displayMessageBox(conteneur_message){
	var reg=new RegExp('Point memoris');
	if(!reg.test($(conteneur_message).innerHTML)){
		showModalDiv();
		$(conteneur_message).show();
	}
}

function replaceAccents(string)
{
	string = string.replace(/À|Á|Â|Ã|Ä|Å|à|á|â|ã|ä|å/g, 'a');
	string = string.replace(/Ç|ČĆç|č|ć|ç/g, 'c');
	string = string.replace(/È|É|Ê|Ë|Ě|è|é|ê|ë|ě/g, 'e');
	string = string.replace(/Ì|Í|Î|Ï|ì|í|î|ï/g, 'i');
	string = string.replace(/Ñ|ñ/g, 'n');
	string = string.replace(/Ò|Ó|Ô|Õ|Ö|Ø|Ō|ò|ó|ô|õ|ö|ø|ō/g, 'o');
	string = string.replace(/ř|Ř/g, 'r');
	string = string.replace(/Š|š/g, 's');
	string = string.replace(/Ù|Ú|Û|Ü|Ů|ù|ú|û|ü|ů/g, 'u');
	string = string.replace(/Ý|Ÿ|Ŷ|Ȳ|ý|ÿ|ŷ/g, 'y');
	string = string.replace(/Ž|Ż|ž|ż/g, 'z');

    // replace all non letters or digits by -
    string = string.replace(/\W+/g, '-');
    string = string.replace(/^-/, '').replace(/-$/, '');

    // trim and lowercase
    string = string.toLowerCase();

    return string;
}

function defineModalDivHeight()
{
  var arrayPageSize = getPageSize();
  $('modalDiv').setStyle({
    width: (arrayPageSize[0] - 20) + 'px',
    height: arrayPageSize[1] + 'px'
  });

	if($('fixieselect') != null)
	{
	  $('fixieselect').setStyle({
	    width: arrayPageSize[0] + 'px',
	    height: arrayPageSize[1] + 'px'
	  });
	}
}

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){

  var xScroll, yScroll;

  if (window.innerHeight && window.scrollMaxY) {
    xScroll = document.body.scrollWidth;
    yScroll = window.innerHeight + window.scrollMaxY;
  } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
    xScroll = document.body.scrollWidth;
    yScroll = document.body.scrollHeight;
  } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    xScroll = document.body.offsetWidth;
    yScroll = document.body.offsetHeight;
  }

  var windowWidth, windowHeight;
  if (self.innerHeight) { // all except Explorer
    windowWidth = self.innerWidth;
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
  }

  // for small pages with total height less then height of the viewport
  if(yScroll < windowHeight){
    pageHeight = windowHeight;
  } else {
    pageHeight = yScroll;
  }

  // for small pages with total width less then width of the viewport
  if(xScroll < windowWidth){
    pageWidth = windowWidth;
  } else {
    pageWidth = xScroll;
  }


  arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
  return arrayPageSize;
}

function showModalDiv()
{
  defineModalDivHeight();
  $('modalDiv').show();
  $('modalDiv').scrollTo();
}

function showUserStatus(id)
{
  var dimensions = $(id).getDimensions();
  $(id).show();

  if($(id + '_iframe') != null)
  {
    $(id + '_iframe').setStyle({
      width: dimensions.width + 'px',
      height: dimensions.height + 'px'
    });
  }
}

function addPersonne(targetId, personneType, libDelete, inputField, selectedItem)
{
  if($(targetId) != null)
  {
    var target = $(targetId);
    var personneId = selectedItem.id;
    if($(personneType + "_" + personneId) == null)
    {
      var personneName = selectedItem.innerHTML;
      var personneDivId = personneType + '_' + personneId
      //$(targetId).insert("<div id=\"" + personneType + "_" + personneId + "\" class=\"add_film_personne\">" + personneName + "&nbsp<a class=\"add_film_remove\" href=\"#\" onclick=\"$('" + personneType + "_" + personneId + "').remove(); return false;\">" + libDelete + "</a><input type=\"hidden\" name=\"addfilm[" + personneType + "][" + personneId + "]\" id=\"addfilm_" + personneType + "_" + personneId + "\" value=\"" + personneId + "\" /></div>" ,'after');
      var newPersonneElement = Builder.node('div',{id: personneDivId, className: 'add_film_personne' }, [
                                             personneName,
                                             Builder.node('a', {className:'add_film_remove', href:'#', onclick:'$(\'' + personneType + '_' + personneId + '\').remove(); return false;'}, libDelete),
                                             Builder.node('input', {type:'hidden', name:'addfilm[' + personneType + '][' + personneId + ']', id:'addfilm_' + personneType + '_' + personneId, value:personneId})
                                            ]);

      target.insert(newPersonneElement, 'after');
    }
    inputField.value = "";
  }
  return false;
}

/**
 * lien JS
 */
var linker = {
    create: function(name, params, className,popup) {
        document.write('<a href="#" class="'+className+'" onclick="linker.go(new Array(\''+params.join("', '")+'\'),'+popup+')">'+name+'</a>');
    },
    
    go: function(path,popup) {
    	if(popup == 1){
    		window.open(path.join('/'));
    	}
    	else{
    		window.location.href = '/' + path.join('/');
    	}
        return false;
    }
}