var triggers;
var $form;
var $advancedForm;
var ajaxLoaderTag = '<img class="ajax-loader" src="/images/loading_ajax.gif" alt="" />';
var computeResults = false; // Calculer le nombre de résultat à l'ouverture et à// la fermeture de la popup de recherche avancée ?
$(document).ready(function()
{
    $form = $('#gmap-form');
    $advancedForm = $('#avanced-form');

    $('#nav li').hover(function()
    {
        // show its submenu
        $('ul', this).slideDown(100);
    }, function()
    {
        // hide its submenu
        $('ul', this).slideUp(100);
    });

    if($('.thin').get(0))
    {
        $('.thin').columnize(
                             {
                                 width : 276
                             });
    }

    if($('div#controller').get(0))
    {
        $("div#controller").jFlow(
        {
            slides : "#slides",
            width : "586px",
            height : "315px"
        });
    }
    
    $('a.add-to-tour').live('click', function(e)
    {
        e.preventDefault(); // prevent default link action
        var href = this.href;
        $(this).overlay(
        {
            mask :
            {
                color : '#fff',
                loadSpeed : 100,
                opacity : 0
            },
            effect : 'default',
            onBeforeLoad : function()
            {
                var wrap = this.getOverlay().find(".contentWrap");
                wrap.load(href);
            },
            load : true
        });
    });

    // ajout d'une classe sur les checkbox "Type evenement"
    var dd = $('dl.event_type_list dd');
    if (dd.get(0))
    {
        dd.first().addClass('type_A');
        dd.eq(1).addClass('type_C');
        dd.eq(2).addClass('type_M');
        dd = null;
    }

    // Recherche avancée
    if($("#open-avanced-form").get(0))
    {
        triggers = $("#open-avanced-form").overlay(
           {
               // some mask tweaks suitable for modal dialogs
               mask :
               {
                   color : '#ebecff',
                   loadSpeed : 200,
                   opacity : 0.9
               },
               closeOnClick : true,
               onClose : function()
               {
                   copyValues(1);
                   $currentForm = $form;
                   if(computeResults)
                   {
                       countResults = true;
                       sendForm();
                   }
               },
               onBeforeLoad : function()
               {
                   copyValues(0);
                   $currentForm = $advancedForm;
                   if(computeResults)
                   {
                       countResults = true;
                       sendForm();
                   }
               }
           });
    }
    
    $('#simple-search').click(closeAdvancedSearchPopup);

    
    if(typeof orderedDeps != 'undefined')
    {
        $('select[id$="region_id"]').each(function(){
            $selectRegion = $(this);
            var depId = $selectRegion.attr('id').replace('region_id', 'departement_id');
            refreshSelect($selectRegion.val(), depId, departments, orderedDeps);
            $selectRegion.change(function()
            {
                refreshSelect($(this).val(), depId, departments, orderedDeps);
            });
        });
    }
    
    if(typeof orderedJobs != 'undefined')
    {
        $('select[id$="job_fields_list"]').each(function(){
            $selectJob = $(this);
            var jobId = $selectJob.attr('id').replace('job_fields_list', 'jobs_list');
            refreshSelect($selectJob.val(), jobId, jobs, orderedJobs);
            $selectJob.change(function()
            {
                refreshSelect($(this).val(), jobId, jobs, orderedJobs);
            });
        });
    }
    
    initControlProfessionnalUserInscription();
    infobulle();
    selectProfessionalUser();
    registrationSaved();
    initCaroussels();
    add_registration_photo();
    add_photo_from_gallery();
    edit_photo_from_gallery();
    //photo_wrapper();
    
    initSortCircuitRegistrations();
    
    if($("a.iframe_fancy").length){
        $("a.iframe_fancy").fancybox({
            'height': 400,
            'type': 'iframe'
        });
    }
    
    if($("a#inline").length){
        $("a#inline").fancybox({
            'hideOnContentClick': false,
            'width': 600,
            'autoDimensions': false
        });
    }
});

function refreshSelect(selectedValue, inputTo, values, orderedValues)
{
    value = $('#' + inputTo).val();
    firstOption = $('#' + inputTo)[0].options[0].innerHTML;

    $('#' + inputTo).empty();
    $('#' + inputTo)[0].options.length = 0;
    $('#' + inputTo).append('<option value="">' + firstOption + '</option>');

    // On insere toutes les valeurs ordonnées
    if (selectedValue == '')
    {
        for ( var key in orderedValues)
        {
            $('#' + inputTo).append('<option value="' + orderedValues[key][0] + '">' + orderedValues[key][1] + '</option>');
        }
    }

    for ( var key in values[selectedValue])
    {
        var obj = values[selectedValue][key];
        $('#' + inputTo).append('<option value="' + obj.id + '">' + obj.name + '</option>');
    }


    $('#' + inputTo).val(value);
}

function getOrdered(obj)
{
    var sortable = [];
    for ( var key1 in obj)
    {
        for ( var key in obj[key1])
        {
            sortable.push(
            [
                obj[key1][key].id, obj[key1][key].name
            ]);
        }
    }
    return sortable.sort(compare);
}

function compare(a, b)
{
    if (a[1] > b[1])
        return 1;
    return -1;
}

function closeAdvancedSearchPopup()
{
    copyValues(1);
    triggers.eq(0).overlay().close();
}

// Copie les valeurs du formulaire simple vers le formulaire avancé ou l'inverse
function copyValues(toSimple)
{
    if (toSimple)
    {
        from = $advancedForm;
        to = $form;
    } else
    {
        from = $form;
        to = $advancedForm;
    }

    $.each(from.find('select, input'), function(id, fromField)
    {
        if (toSimple)
            toField = $('#' + fromField.id.replace('adv_', ''));
        else
            toField = $('#adv_' + fromField.id);

        if (toField)
        {
            if (fromField.type == 'checkbox')
            {
                toField.attr('checked', fromField.checked);
            } else
            {
                toField.val(fromField.value);
            }
        }
    });
}

function trim(str)
{
    var str = str.replace(/^\s\s*/, ''), ws = /\s/, i = str.length;
    while (ws.test(str.charAt(--i)));
    return str.slice(0, i + 1);
}

function isFloat(str)
{
    str = trim(str);
    return /^[-+]?\d+(\.\d+)?$/.test(str);
}

function initControlProfessionnalUserInscription()
{
	$("#professional_user_inscription_form").validate({
		rules: {
			"professional_user[email]" : {
				required: true,
				email: true
			},
			"professional_user[firstname]" : "required",
			"professional_user[lastname]" : "required",
			"professional_user[address]" : "required",
			"professional_user[zipcode]" : "required",
			"professional_user[city]" : "required",
			"professional_user[phone]" : {
					required:true,
					number:true,
					rangelength:[10,10]
			},
			"conditionsofuse"		 : "required"
		},
		messages : {
			"professional_user[email]" : {
				required: "Veuillez remplir ce champ",
				email: "Veuillez indiquer un email valide du type nom@domaine.com."
			},
			"professional_user[firstname]" : "Veuillez remplir ce champ",
			"professional_user[lastname]" : "Veuillez remplir ce champ",
			"professional_user[address]" : "Veuillez remplir ce champ",
			"professional_user[zipcode]" : "Veuillez remplir ce champ",
			"professional_user[city]" : "Veuillez remplir ce champ",
			"professional_user[phone]" : {
				required: "Veuillez remplir ce champ",
				number: "Erreur format téléphone : 0100000000",
				rangelength: "Erreur format téléphone : 0600000000"
			},
			"conditionsofuse" : "Vous devez accepter les conditions générales"
		},
		success: function(label) {
			label.parent().append('<span class="valid-thick"></span>');
		},
		errorElement: "span",
		errorPlacement: function(error, element) {
			error.appendTo(element.parent());
			element.parent().find('.valid-thick').each(function(){
				$(this).remove();
			});
		}
	});
	
	
}

function infobulle(){
	$('.info').mouseenter(function(){
		$(this).next().fadeIn(250);
	}).mouseleave(function(){
		$(this).next().fadeOut(250);
	});
}

function selectProfessionalUser()
{
	$('#mastered_professional_user').change(function(){
		$(this).parent().submit();
	});
}

function registrationSaved()
{
	$('#btn_suivant').click(function(){
		if($('#saved-step'))
		{
			$('#saved-step').fadeIn(800).fadeOut(800);
		}
	});
        
        if($("#photos-registration-form").length){
            $('#btn_suivant').click(function(e){
                e.preventDefault();
                var redir_attr = $(this).attr('href');
                if($("#photos-registration-form").length){
                    var form = $("#photos-registration-form").serialize();
                    var params = 'do=addphotosregistration';
                    params += '&form='+form;
                    if($('#current-registration-id'))
                    {
                    params += '&registration_id='+$('#current-registration-id').val();
                    }
                    $.ajax({
                            type: "POST",
                            url: "/ajax",
                            data: params,
                            dataType: "json",
                            success: function(response){
                                if(response.result == 0)
                                {
                                    
                                    if($('#saved-step'))
                                    {
                                        $('#saved-step').fadeIn(800).fadeOut(800);
                                    };
                                    $("form:last").submit();
                                }
                                else if(response.result == 2)
                                {
                                    alert("Problème");
                                }
                            }
                    });
                }
            })
        }
        
        $('#registration-tabs li a').click(function(e){
                e.preventDefault();
                var redir_attr = $(this).attr('href');
                if($("#photos-registration-form").length){
                    var form = $("#photos-registration-form").serialize();
                    var params = 'do=addphotosregistration';
                    params += '&form='+form;
                    if($('#current-registration-id'))
                    {
                    params += '&registration_id='+$('#current-registration-id').val();
                    }
                    $.ajax({
                            type: "POST",
                            url: "/ajax",
                            data: params,
                            dataType: "json",
                            success: function(response){
                                if(response.result == 0)
                                {
                                    $("form:last").append('<input type="hidden" name="registration[redir_from_menu]" value="'+redir_attr+'"/>').submit();
                                }
                                else if(response.result == 2)
                                {
                                    alert("Problème");
                                }
                            }
                    });
                }else{
                    $("form:last").append('<input type="hidden" name="registration[redir_from_menu]" value="'+$(this).attr('href')+'"/>').submit();
                }
                
		if($('#saved-step'))
		{
                    $('#saved-step').fadeIn(800).fadeOut(800);
		}
                return;
	});
}

function add_registration_photo()
{
	$('#add-registration-photo').click(function(){
		$(this).parents('form').submit();
	});
}

function hoverCarousel2(){
    var buttonRemove = $(".remove_photo",this);
    $(this).mouseenter(function(){
        $(".remove_photo",this).show();
    }).mouseleave(function(){
        $(".remove_photo",this).hide();
    });
    buttonRemove.bind("click",removePhoto);
}

$("#carousel2 li").live("hover",hoverCarousel2);

function removePhoto(){
    var id = $("img",$(this).parent()).attr('id');
    $(this).parent().remove();
    $("#carousel1 #"+id).parent().show();
}

function add_photo_from_gallery()
{
    $( "#carousel1 li img" ).draggable({ 
        revert: true,
        helper: function(event){
            return $(this).clone().addClass("move_photo")
        }, opacity: 0.7
    });
    
    $("#carousel2").droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-state-hover",
        accept: "#carousel1 li img",
        drop: function( event, ui){
            //myCarousel.reset();
            var nb_imgs = $("#carousel2 li img").length;
            $('#carousel2').jcarousel('add', nb_imgs+1, ui.draggable.clone().after('<input type="hidden" name="registration_photo_registration[]" value="'+ui.draggable.attr('rel')+'" />').after("<div class='remove_photo'>X</div>"));
            ui.draggable.parent().hide();
        }
    }).sortable({containment: 'parent'});

}

function photo_wrapper()
{
  $('.photo-wrapper').click(function(){
  	
  	$('.wrapper-container').each(function(){
  		$(this).css('display','none');
  		$(this).parent().find('.photo-wrapper').attr('src','/images/scroll_up.gif');
  	});
  	
  	var container = $(this).parent().parent().find('.wrapper-container');
  	if(container.is(':visible'))
  	{
  		container.fadeOut();
  		$(this).attr('src','/images/scroll_up.gif');
  	}
  	else
  	{
  		container.fadeIn();
  		$(this).attr('src','/images/scroll_down.gif');
  		initCaroussels();
  	}
  	return false;
  });
}

function initCaroussels()
{
    myCarousel = null; // This will be the carousel object

    function onInitCarousel(carousel, state) {
        if (state == 'init') {
            myCarousel = carousel;
        }
    }
    
    $('#carousel1').jcarousel({
            visible: 4,
            scroll: 4
    });
    $('#carousel2').jcarousel({
            visible: 4,
            scroll: 4,
            initCallback: onInitCarousel
    });
   
}

function edit_photo_from_gallery()
{
	$('.edit-photo-gallery').click(function(){
		var original_img = $(this);
		var attr_id = $(this).attr('id');
		var reg = new RegExp("[-]+", "g");
		var parts = attr_id.split(reg);
		var id = parts[1];
		
		var params = 'do=editphoto';
		params += '&registration_photo_id='+id;

		$.ajax({
			type: "POST",
			url: "/ajax",
			data: params,
			dataType: "json",
			success: function(response){
				if(response.photo_src)
				{
					$('#photo-informations').html('');
										
					// Image
					var img = $('<img>');
					img.attr('src',response.photo_src);
					img.attr('class','large-photo-info');
					$('#photo-informations').append(img);					
					
					// Modification des infos de la photo
					$('#photo-informations').append('<div class="photo-info-title">Modifier la photo :</div>');
					$('#photo-informations').append('<div class="photo-info-label">Type de photo:</div>');
					
					var portrait = '';
					var produit = '';
					var atelier = '';
					switch(response.photo_format_type)
					{
						case('0'):portrait = ' checked="checked"';break;
						case('1'):produit = ' checked="checked"';break;
						case('2'):atelier = ' checked="checked"';break;
					}
					
					$('#photo-informations').append(('Portrait <input'+portrait+' type="radio" value="0" name="format_type" class="photo-format-type" />'));
					$('#photo-informations').append(('Produit <input'+produit+' type="radio" value="1" name="format_type" class="photo-format-type" />'));
					$('#photo-informations').append(('Atelier <input'+atelier+' type="radio" value="2" name="format_type" class="photo-format-type" />'));
					$('#photo-informations').append('<div class="photo-info-label">Crédit photo:</div><input type="text" id="photo-info-credit" value="'+response.photo_credit+'">');
					var update_button = $('<input type="button" id="photo-info-update-button" value="Enregistrer" />');
					update_button.click(function(){
						// mettre à jour la photo
						var credit = $('#photo-info-credit').val();
						var format_type = '';
						$('.photo-format-type').each(function(){
							if($(this).is(':checked'))
							{
								format_type = $(this).val();
							}
						});
						
						var params = 'do=updatephoto';
						params += '&registration_photo_id='+id;
						params += '&format_type='+format_type;
						params += '&credit='+credit;
						$.ajax({
							type: "POST",
							url: "/ajax",
							data: params,
							dataType: "json",
							success: function(response){
								if(response.result == 1)
								{
									alert('Votre photo est mise à jour');
								}
								else
								{
									alert('Une erreur est survenue lors de la suppression de la photo');
								}								
							}
						});						
					});
					$('#photo-informations').append(update_button);
					
					// Evénements rattachés
					var ul = false;
					
					if(response.registrations)
					{
						ul = $('<ul>');
						ul.attr('id','photo-info-registrations');
						for(var i=0; i<response.registrations.length; i++)
						{
							var registration = response.registrations[i];
							
							var li = $('<li>');
							li.html('<a href="#" target="_blank">'+registration.name+'</a> ('+registration.type+') ('+registration.status+')');
							
							ul.append(li);
						}
					}
					
					

					if(ul != false)
					{
						$('#photo-informations').append('<div class="photo-info-title">Cette photo illustre les événements suivants :</div>');
						$('#photo-informations').append(ul);
					}
					
					var button = $('<input>');
					button.attr('type','button');
					button.attr('value','Supprimer');
					button.attr('id','photo-info-delete-button');
					button.click(function(){
						if(confirm("Attention, cette photo sera supprimée de tous les événements !\nEtes-vous sûr de vouloir continuer ?"))
						{
							// supprimer la photo
							var params = 'do=deletephoto';
							params += '&registration_photo_id='+id;
							$.ajax({
								type: "POST",
								url: "/ajax",
								data: params,
								dataType: "json",
								success: function(response){
									if(response.result == 1)
									{
										$('#photo-'+id).parent().remove();
										$('#photo-informations').html('');
									}
									else
									{
										alert('Une erreur est survenue lors de la suppression de la photo');
									}
								}
							});							
						}
					});
					$('#photo-informations').append(button);
				}
			}
		});
	});
}

function initSortCircuitRegistrations()
{
	$('.sort-registration-top').click(function(){
		var id = $(this).parents('td').find('.sort-registration-id').first().val();
		var params = 'do=sortregistrationtop';
		params += '&registration_id='+id;
		$.ajax({
			type: "POST",
			url: "/ajax",
			data: params,
			dataType: "json",
			success: function(response){
				if(response.result == 1) window.location.href = window.location.href;
			}
		});		
	});
	
	$('.sort-registration-bottom').click(function(){
		var id = $(this).parents('td').find('.sort-registration-id').first().val();
		var params = 'do=sortregistrationbottom';
		params += '&registration_id='+id;
		$.ajax({
			type: "POST",
			url: "/ajax",
			data: params,
			dataType: "json",
			success: function(response){
				if(response.result == 1) window.location.href = window.location.href;
			}
		});		
	});
}

