function TMsg(obj) {
	$.notifier.broadcast(obj);
}
function TError(msg) {
	TMsg({msg:msg, code:"error"});
}
function TSuccess(msg) {
	TMsg({msg:msg, code:"success"});
}
(function($){
    /**
     * jQuery delayed event execution.
     */
    $.fn.delay = function(options) {
        var timer;
        var delayImpl = function(eventObj) {
            if (timer != null) {
                clearTimeout(timer);
            }
            var newFn = function() {
                options.fn(eventObj);
            };
            timer = setTimeout(newFn, options.delay);
        }
       
        return this.each(function() {
            var obj = $(this);
            obj.bind(options.event, function(eventObj) {
                 delayImpl(eventObj);  
            });
        });
    };
})(jQuery);

$(document).ready(function() {

	$(document).ajaxStart(function() {
		$("#ajaxLoading").show();
	}).ajaxStop(function() {
		$("#ajaxLoading").hide();
	});
	
	Cufon.replace('.am-wr');
	Cufon.replace('h2');
	//Cufon.replace('h3');
	//Cufon.replace('h4');
	
	$(".newsletter").one('focus', function() {
		$(this).val('');
	});
	
	$("#newsletter-form").submit(function() {
		$.post($(this).attr('action'), $(this).serialize(), function(response) { TMsg(response); }, 'json');
		return false;
	})
	
	// pages corporates
	$(".corporates-link a").click(function(e) {
		e.preventDefault();
		$("#page_corporates").lithiumWindow({
			padding:10,
			width:600,
			height:($(window).height()-60)
		});
		$("#page_corporates").lithiumWindow_html('');
		$("#page_corporates").lithiumWindow_load($(this).attr('href'));
	});
	
	/****** ACTUS *******/
	$("#search-actus-button").click(function(e) {
		e.preventDefault();
		var params = {};
		$("#actus-search-form input").each(function() {
			params[$(this).attr('name')] = $(this).val();
		});
		params.page = 1;
		$.get($("#actus-search-form").attr('action'), params, function(data) {
			$("#actus-list-box").html(data);
		});
	});
	// Formulaire de recherche d'actus
	$("#open-actus-search-link").click(function(e) {
		e.preventDefault();
		$("#actus-search-form").slideToggle('fast');
	});
	$(".close-actus-search-box").click(function(e) {
		e.preventDefault();
		$("#actus-search-form").hide('fast');
	});
	$(".reset-actus-search").click(function(e) {
		e.preventDefault();
		$("#actus-from-field").val('');
		$("#actus-to-field").val('');
		$("#actus-search-q").val('');
		$("#search-actus-button").click();
	});
	$(".actu-img-link, .actu-title-link").live('click', function(e) {
		e.preventDefault();
		
		$("#detail-actu-box").lithiumWindow({
			width: 342
		});
		var parent = $(this).closest('li');
		$("#detail-actu-wesh-box").html(parent.html());
		$("#detail-actu-box .actu-content").show();
		$("#detail-actu-box .actu-profil-link").show();
		$("#detail-actu-box").lithiumWindow_resize();
	});
	$(".detail-actu-close-link").live('click', function(e) {
		e.preventDefault();
		$("#detail-actu-box").lithiumWindow_close();
	});
	
	/****** RDV *****/
	$("#search-rdvs-button").click(function(e) {
		e.preventDefault();
		var params = {};
		$("#actus-search-form input").each(function() {
			params[$(this).attr('name')] = $(this).val();
		});
		params.page = 1;
		$.get($("#rdvs-search-form").attr('action'), params, function(data) {
			$("#rdvs-list-box").html(data);
		});
	});
	// Formulaire de recherche d'actus
	$("#open-rdvs-search-link").click(function(e) {
		e.preventDefault();
		$("#rdvs-search-form").slideToggle('fast');
	});
	$(".close-rdvs-search-box").click(function(e) {
		e.preventDefault();
		$("#rdvs-search-form").hide('fast');
	});
	$(".reset-rdvs-search").click(function(e) {
		e.preventDefault();
		$("#rdvs-from-field").val('');
		$("#rdvs-to-field").val('');
		$("#rdvs-search-q").val('');
		$("#search-rdvs-button").click();
	});
	$(".rdv-title-link").live('click', function(e) {
		e.preventDefault();
		
		$("#detail-rdv-box").lithiumWindow({
			width: 342
		});
		var parent = $(this).closest('li');
		$("#detail-rdv-wesh-box").html(parent.html());
		$("#detail-rdv-box .rdv-content-extrait").hide();
		$("#detail-rdv-box .rdv-profil-link").show();
		$("#detail-rdv-box .rdv-content").show();
		Cufon.replace('.am-wr');
		$("#detail-rdv-box").lithiumWindow_resize();
	});
	$(".detail-rdv-close-link").live('click', function(e) {
		e.preventDefault();
		$("#detail-rdv-box").lithiumWindow_close();
	});

	//register box
	$(".register-link").click(function(e) {
		e.preventDefault();
		if ($(this).hasClass('distributeur')) {
			$("#register-box-distributeur").lithiumWindow({
				width: 640,
				height:440
			});
		} else {
			$("#register-box-annonceur").lithiumWindow({
				width: 640,
				height:440
			});
		}
	});
	
	$("#already-member-link").click(function(e) {
		e.preventDefault();
		$("#register-box-annonceur").lithiumWindow_close();
		$(".login-link").click();
	});
	
	$(".register-form form").submit(function(e) {

		var error= false;
		$(this).find("input, textarea").each(function() {
			if ($(this).val().length == 0) { $(this).css('border', 'solid 1px #FF0000'); error = true; }
			else { $(this).css('border', 'solid 1px #7F99A8'); }
		});
		
		var account = $(this).find('#account-field').val();
		var params = {};

		if (account == 'annonceur') {
			if ($(this).find("#password").val() != $(this).find("#password_confirm").val()) {
				$(this).find("#password_confirm").css('border', 'solid 1px #FF0000');
				error = true;
			}
			params.login = $(this).find("#login").val();
			params.password = $(this).find("#password").val();
		} else {
			params.message = $(this).find('#message-field').val();
		}

		if (error) {
			TMsg({msg:"Tous les champs n'ont pas été remplis", code:'error'});
			return false;
		}
		$.post($(this).attr('action'), $.extend({
			title: $(this).find('.title_field:checked').val(),
			firstname: $(this).find("#firstname").val(),
			lastname: $(this).find("#lastname").val(),
			company: $(this).find("#company").val(),
			email: $(this).find("#email").val(),
			title: $(this).find(".title_field:checked").val(),
			tel: $(this).find("#tel").val(),
			city: $(this).find('#city').val(),
			account: account,
			captcha_code: $(this).find('.captcha_code').val()
		}, params), function(response) {
			if (response.code == 'success') {
				if (account == 'annonceur') {
					$("#register-box-annonceur").lithiumWindow_close();
					window.location.reload();
				} else {
					$("#register-box-distributeur").lithiumWindow_close();
				}
			}
			TMsg(response);
		}, 'json');

		return false;
	});
	
	$("#connect-box form").submit(function() {
		var error = false;
		
		$(this).find("input").each(function() {
			if ($(this).val().length == 0) { $(this).css('border', 'solid 1px #FF0000'); error = true; }
			else { $(this).css('border', 'solid 1px #7F99A8'); }
		});

		if (error) {
			TMsg({title: 'Erreur', msg:"Tous les champs n'ont pas été remplis", renderClass:'error'});
			return false;
		}

		$.post($(this).attr('action'), {
			login: $(this).find("#connect-login-field").val(),
			password: $(this).find("#connect-password-field").val()
		}, function (data) {
			if (data.code == 'success') {
				window.location.reload();
			} else {
				TMsg(data);
			}
		}, 'json');
		return false;
	});

	$(".login-link").click(function(e) {
		e.preventDefault();
		$("#connect-box").lithiumWindow({
			width: 300,
			height: 180,
			top:(e.pageY + 20),
			left:(e.pageX - 280)
		});
	});
	
	$("#open-advanced-box").click(function(e) {
		e.preventDefault();
		$("#simple-search-tab").hide();
		$("#advanced-search-tab").show();
		$("#search-advanced-box").show();
		$("#is-advanced-search").val('1');
	});

	$(".close-advanced-search-box").click(function(e) {
	    e.preventDefault();
	    $("#advanced-search-tab").hide();
        $("#search-advanced-box").hide();
        $("#simple-search-tab").show();
        $("#is-advanced-search").val('0');
	});
	
	var sendSearch = function() {
		/*$("#produit-field option").each(function() {
			if ($("#q").val() == $(this).html()) {
				$("#produit-field").val( $(this).attr('value') );
				$("#is-advanced-search").val('1');
				$("#q").val('');
			}
		});*/
		$("#search-form").submit();
	}

	$("#search-advanced-button, #search-simple-button").click(function(e) {
		e.preventDefault();
		sendSearch();
	});
	
	$("#q").keypress(function(e) {
		if ( e.which == 13 ) {
			sendSearch();
		}
	});
	
	$("#q").click(function(e) {
		e.preventDefault();
		$("#open-advanced-box").click();
	});
	
	$("#q").autocomplete({
		//source:'/suggest',
		source: function( request, response ) {
			$.getJSON( "/suggest", {
				term: request.term,
				revendeur_id: $('#revendeur-id-field').val()
			}, response );
		},
		minLength: 1,
		delay: 100,
		select: function( event, ui ) {
			window.location.href = ui.item.url;
		}
	}).data( "autocomplete" )._renderItem = function( ul, item ) {
		return $( "<li></li>" )
		.data( "item.autocomplete", item )
		.append( '<a>' + item.richLabel + "</a>" )
		.appendTo( ul );
	};
	
	$("#famille-field").change(function() {
		$.post('/produitsbyfamille', {famille_id:$(this).val()}, function(data) {
			$("#produit-field").html(data);
		})
	});
	
	$(".reset-search").click(function(e) {
		e.preventDefault();
		$("#famille-field").val('-1');
		$("#produit-field").val('-1');
		$("#marque-field").val('-1');
		$("#etiquette_promo").attr('checked', '');
		$("#etiquette_top").attr('checked', '');
		$("#etiquette_new").attr('checked', '');
		$("#budget-min-field").val('');
		$("#budget-max-field").val('');
		$("#distributeur-field").attr('checked', 'checked');
		$("#annonceur-field").attr('checked', 'checked');
	});
	
	$("#display-options-link").click(function(e) {
        e.preventDefault();
        var position = $(this).position();
        $(this).toggleClass('clicked');
        $("#display-options-box").toggle();
        if ($("#display-options-box").is(':visible')) {
			$("#display-options-box").css('left', position.left+'px');
			$("#display-options-box").css('top', (position.top+29)+'px');
        }
    });

    $(".close-display-link").click(function(e) {
		e.preventDefault();
		$("#display-options-box").hide();
		$("#display-options-link").removeClass('clicked');
    });

    $(".display-options-button").click(function(e) {
        var params = {};
        params.perpage = $('.perPage-field:checked').val();
        params.preview = ($(".preview-field").is(':checked') ? 'yes' : 'no');
        
		$.post("/setDisplayOptions", params, function() {
			window.location.reload();
		});
    });
    
    $("#photo-link").click(function(e) {
		e.preventDefault();
		$("#photo-box").show();
		$("#video-box").hide();
		$("#photo-link").addClass('selected');
		$("#video-link").removeClass('selected');
	});
	$("#video-link").click(function(e) {
		e.preventDefault();
		$("#video-box").show();
		$("#photo-box").hide();
		$("#video-link").addClass('selected');
		$("#photo-link").removeClass('selected');
	});
	
	$("#front-diapo-g-link").click(function(e) {
		e.preventDefault();
		var max = $("#front-image-diapo").height();
		var top = parseInt($("#front-image-diapo").css('margin-top').replace('px', ''));
		if (top == 0) {
			top = -max + 340;
		} else {
			top += 340;
		}
		$("#front-image-diapo").css('margin-top', top+'px');
	});
	
	$("#front-diapo-d-link").click(function(e) {
		e.preventDefault();
		var max = $("#front-image-diapo").height();
		var top = parseInt($("#front-image-diapo").css('margin-top').replace('px', ''));
		if (top <= (340-max)) {
			top =  0;
		} else {
			top -= 340;
		}
		$("#front-image-diapo").css('margin-top', top+'px');
	});
    
    $("input.date").datepicker();
    if ($("#produit-field").val() != '-1') {
    	$("#produit-field").css('border', 'solid 2px red');
    }
});
