var produits_recette_submit = new Array();

function set_js_active() {
    $$('body').addClass("js_active");
}

window.addEvent( 'domready', function() {
     
     if($("main_nav")){
        select_list($$("#main_nav .niveau_1"));
    }
     if($$(".select_list").length>0){
        select_list($$(".select_list"));
    }
     if($$(".visionneuse").length>0){
        visionneuse();
    }
    
    //lien_blank();
    
    if($$(".carrousel").length>0){
        new SlideItMoo({
            overallContainer: 'carrousel',
            elementScrolled: 'carrousel_mask',
            thumbsContainer: 'carrousel_content',		
            itemsVisible:5,
            elemsSlide:1,
            duration:300,
            autoSlide:10000,
            itemsSelector: '.view',
            itemWidth: 178,
            showControls:1,
            startIndex:5			
        });
    }

    // Autocompletion
    if($('search_produit') != null) { init_autocomplete(); }
    if($('recette_produits') != null) { init_autocomplete_submit_recette(); }
    // Fin autocompletion

    // Espace perso
    if($('region_offer_alert') != null) {
	$('region_offer_alert').addEvent('change', function(event) {
    	    init_offer_departement_select_reload(this.getSelected()[0]);
    	});
    }
    if($('candidature_region') != null) {
	$('candidature_region').addEvent('change', function(event) {
    	    init_candidature_departement_select_reload(this.getSelected()[0]);
    	});
    }
    // Fin espace perso  

    // Proposition de local
	    // Vérification des checkbox
	    if($('local_caracteristiques_cdad') != null) {
		$('local_caracteristiques_cdad').addEvent('click', function() {
		    if($('local_caracteristiques_cdad').get('checked') == true) {
			$('local_caracteristiques_activitescdad').disabled = 0; }
		     else {
			$('local_caracteristiques_activitescdad').disabled = 1; }
		});
	    }
	    if($('local_caracteristiques_erp') != null) {
		$('local_caracteristiques_erp').addEvent('click', function() {
		    if($('local_caracteristiques_erp').get('checked') == true) {
			$('local_caracteristiques_categorie').disabled = 0; }
		     else {
			$('local_caracteristiques_categorie').disabled = 1; }
		});
	    }
	    // Vérification des selects
	    if($('local_type_transaction') != null) {
		organizeLocalPropositionFrom();
		$('local_type_transaction').addEvent('change', function(event) {
		    organizeLocalPropositionFrom();
		});
	    }
    // Fin proposition de local
});

function organizeLocalPropositionFrom()
{
	// Vérification des checkbox
	if($('local_caracteristiques_cdad').get('checked') == true) {
	        $('local_caracteristiques_activitescdad').disabled = 0; }
        else {
		$('local_caracteristiques_activitescdad').disabled = 1; }
	if($('local_caracteristiques_erp').get('checked') == true) {
	        $('local_caracteristiques_categorie').disabled = 0; }
        else {
		$('local_caracteristiques_categorie').disabled = 1; }
	// Vérification des selects
	var checkForALotOfInputs = new Array("location_pure", "location_droits", "location_cession", "bail");
	var checkForInputCession = new Array("vente_fond_commerce", "vente_murs_fond", "location_droits", "location_cession");
	var checkForInputMontant = new Array("vente_murs", "vente_vefa", "vente_terrain", "autre");
	var checkForInputDescriptif = new Array("vente_murs", "vente_vefa", "vente_terrain", "autre");
	if(checkForALotOfInputs.contains($('local_type_transaction').value)) {
	$('local_conditions_loyer').disabled = 0; $('local_conditions_charges').disabled = 0; $('local_bail_activite_actuelle').disabled = 0; $('local_bail_duree').disabled = 0; $('local_bail_activite_alimentaire').disabled = 0; $('local_bail_despecialisation').disabled = 0; }
	else {
		$('local_conditions_loyer').disabled = 1; $('local_conditions_charges').disabled = 1; $('local_bail_activite_actuelle').disabled = 1; $('local_bail_duree').disabled = 1; $('local_bail_activite_alimentaire').disabled = 1; $('local_bail_despecialisation').disabled = 1; }
	if(checkForInputCession.contains($('local_type_transaction').value)) {
		$('local_conditions_cession').disabled = 0; }
	else {
		$('local_conditions_cession').disabled = 1; }
	if(checkForInputMontant.contains($('local_type_transaction').value)) {
		$('local_conditions_montant').disabled = 0; }
	else {
		$('local_conditions_montant').disabled = 1; }
	if(checkForInputDescriptif.contains($('local_type_transaction').value)) {
		$('local_conditions_descriptif').disabled = 0; }
	else {
		$('local_conditions_descriptif').disabled = 1; }
}

/** 
Listes deroulantes
*/
function select_list(div){
	div.each(function(el, index) {
        el.set("tabindex","0");
        var open = function (){ el.addClass("open");}
        var close = function (){ el.removeClass("open");}
        el.addEvent("mouseover", open );
        el.addEvent("focus", open );
        el.addEvent("mouseout", close );
        var last_a = el.getElements('a').getLast();
        last_a.addEvent("blur",close ); 
	});
}

/** 
Visionneuse en page d'accueil
*/
function visionneuse(){
    
	var ancre = $$('.ancres li a');
    ancre.each(function(el, index) {
        var action_lien = 'visio_'+index;
        el.addClass(action_lien);
        el.set('href','javascript:void(0)');
        if (index==0){
            $(action_lien).addClass("open");
            el.addClass("open");
        }
        el.addEvent("mouseover", function() {
            $$(".ancres a").removeClass("open");
            el.addClass("open");
            $$(".content_visio li").removeClass("open");
            $(action_lien).addClass("open");
        });
    });
}


/** 
Liens dans une nouvelle fenêtre
*/
function lien_blank() {
	
	var liens = $$("a");
	liens.each(function(lien) {
		var href = lien.get("href");
		if(null != href && (href.contains('http://')||href.contains('https://'))) 
		{
			lien.addEvent("click", function() {window.open(href);return false;});
			var titre_lien = lien.get('title');
			var intitule_lien = "";

            for(var i = 0; i <lien.childNodes.length; i++) {
                if(lien.childNodes[i].nodeName == 'IMG' ){
                    intitule_lien += lien.childNodes[i].attributes['alt'].nodeValue.trim() + " ";
                }else{
                    intitule_lien += lien.childNodes[i].textContent.trim() + " ";
                }
            }
            if(titre_lien){
				lien.set("title", titre_lien+" (nouvelle fenêtre)");
			}else{
				lien.set("title", intitule_lien+"(nouvelle fenêtre)");
			}
		}
	});
	
}

function init_offer_departement_select_reload(option_value) {
    if(option_value.value != 0) {
	    var link = "/espace_perso/update_departement_offer?region_id=" + option_value.value;
	    var updateRequest = new Request({
		url: link,
		method: 'get',
		onLoadstart: function(event, xhr) {
			$('offer_departement_result_zone').set('html', '<b>Chargement...</b>');
		},
		onSuccess: function(responseText) {
		    $('offer_departement_result_zone').set('html', responseText);
		}
	    });
	    updateRequest.send();
    } else {
	$('offer_departement_result_zone').set('html', '<b>Veuillez choisir une région</b>');
    }
}

function init_candidature_departement_select_reload(option_value) {
    if(option_value.value != 0) {
	    var link = "/candidature/update_departement_candidature?region_id=" + option_value.value;
	    var updateRequest = new Request({
		url: link,
		method: 'get',
		onLoadstart: function(event, xhr) {
			$('candidature_departement_result_zone').set('html', '<b>Chargement...</b>');
		},
		onSuccess: function(responseText) {
		    $('candidature_departement_result_zone').set('html', responseText);
		}
	    });
	    updateRequest.send();
    } else {
	$('candidature_departement_result_zone').set('html', '<b>Veuillez choisir une région</b>');
    }
}


function init_autocomplete_submit_recette()
{
	var search_epi_word = $('recette_produits');
    	var cn = 'autocompleter-choices';
   	var a1 = new Autocompleter.Request.HTML(search_epi_word, '/autocomplete_search/search', {
        	'indicatorClass': 'autocompleter-loading',
        	'postData': {
            		'extended': '1',
			'submit_recette_ajax' : '1'
        	},
        	'injectChoice': function(choice) {
            		// choice is one <li> element
            		var text = choice.getFirst();
			var value = text.innerHTML;
			choice.inputValue = value;
			text.set('html', this.markQueryValue(value));
			this.addChoiceEvents(choice);
        	},
       		className: cn
    	});
}

function add_produit_submit_recette(produit)
{
	if(!produits_recette_submit.contains(produit))
	{
		$('test_li').innerHTML = "<b>Liste des produits:</b><br/><ul>";
		$('hidden_products').value = "";
		produits_recette_submit.push(produit);
		Array.each(produits_recette_submit, function(value, key) {
			$('test_li').innerHTML += "<li>" + value + " <small style='cursor: pointer;' onclick=\'remove_produit_submit_recette(\"" + value + "\");\'>[supprimer]</small></li>";
			if(key == 0)
				$('hidden_products').value += value;
			else
				$('hidden_products').value += "," + value;
		});
		$('test_li').innerHTML += "</ul>";
	}
}

function update_produits_on_edit_recette()
{
	$('test_li').innerHTML = "<b>Liste des produits:</b><br/><ul>";
	var i = 0;
	var products = $('hidden_products').value;
	var products = products.split(', ');
	$('hidden_products').value = "";
	for(var i = 0; i < products.length; i++) {
		produits_recette_submit.push(products[i]);
		$('test_li').innerHTML += "<li>" + products[i] + " <small style='cursor: pointer;' onclick=\'remove_produit_submit_recette(\"" + products[i] + "\");\'>[supprimer]</small></li>";
		if(i == 0)
			$('hidden_products').value += products[i];
		else
			$('hidden_products').value += "," + products[i];
	}
	$('test_li').innerHTML += "</ul>";
}

function confirm_delete_recette(recette_id, user_id)
{
	if(confirm("Êtes-vous sûr de vouloir supprimer cette recette ?"))
		window.location.href = "/espace_perso/delete_recette?id=" + recette_id + "&user=" + user_id;
}

function remove_produit_submit_recette(produit)
{
	$('test_li').innerHTML = "<b>Liste des produits:</b><br/><ul>";
	$('hidden_products').value = "";
	produits_recette_submit.erase(produit);
	Array.each(produits_recette_submit, function(value, key) {
		$('test_li').innerHTML += "<li>" + value + " <small style='cursor: pointer;' onclick=\'remove_produit_submit_recette(\"" + value + "\");\'>[supprimer]</small></li>";
		if(key == 0)
			$('hidden_products').value += value;
		else
			$('hidden_products').value += ", " + value;
	});
	$('test_li').innerHTML += "</ul>";
}

function init_autocomplete() {
    var search_epi_word = $('search_produit');
    var type_recette = $('RecetteType').value;
    var cn = 'autocompleter-choices';
    //if(is_epi_in_arbo_center)
        //cn = 'autocompleter-choices center';
    var a1 = new Autocompleter.Request.HTML(search_epi_word, '/autocomplete_search/search', {
        'indicatorClass': 'autocompleter-loading',
        'postData': {
            'extended': '1',
	    'type_recette': type_recette
        },
        'injectChoice': function(choice) {
            var text = choice.getFirst();
            var value = text.innerHTML;
            choice.inputValue = value;
            text.set('html', this.markQueryValue(value));
            this.addChoiceEvents(choice);
        },
        className: cn
    });
};



