$.tag = function (type) {
	return $( document.createElement(type) );
}

var scrolling = false;

function contact_us_load_callback (data) {
	var $data = $(data);
	set_popup_content($('div.body:first', $data));
}

function set_popup_content(html) {
	var pc = $.tag('div')
		, bg = $.tag('div')
		, fg = $.tag('div')
		, close = $.tag('a')
		;
	pc.appendTo('body').addClass('popup');
	bg.appendTo(pc).addClass('popup-bg').data('popup', pc);
	fg.appendTo(pc).addClass('popup-fg page-contact_us');

    bg.click( function () {
        hide_popup($(this).data('popup'));
    });

	set_popup_content = function (html) {
	
		var close = $.tag('a');
		close.addClass('close-popup')
			 .html('&raquo; ' + translations['back'])
			 .attr('href', 'javascript:void(0)')
			 .click( function() {
				hide_popup( $(this).parent().parent() );
				return false;
			 });
		
		fg.html( html ).append( close );
		add_form_listener( fg );
		animate_popup( pc, bg, fg );
	}
	return set_popup_content(html);
}

function animate_popup (container, background, foreground) {
	if (scrolling) {
		setTimeout( function () {
			animate_popup(container, background, foreground);
		}, 100);
		return;
	}
	container.show();
	$('body').addClass('popup-visible');
}

function hide_popup (container, background, foreground) {
	container.hide();
	$('body').removeClass('popup-visible');
}

function add_form_listener(foreground) {
	$('form', $(foreground)).submit(function () {
		$.post(this.action, $(this).serialize(), contact_us_load_callback, 'html');
		return false;
	});
}

$(document).ready( function () {
	$('a[href*=contact_us], a[href*=contactez_nous]').click(function () {
		scrolling = true;
		$('html, body').animate(
			{scrollTop: 0},
			400,
			null,
			function () {
				scrolling = false;
			}
		);
		$.get(this.href, {}, contact_us_load_callback, 'html');
		return false;
	})
});
