$.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;
	})

    $('#gallery').gallery();
});

$.fn.gallery = function () {

    var banner = $('div.banner img:first'),
        gallery = this,
        fading = false,
        changeTime = 4 * 1000, // 4 seconds
        changeTimeout = null,
        resetTimeout = null,
        overlay = null,
        createOverlay = null,
        thumbClicked = null,
        changeBanner = null,
        onKeyDown = null,
        
        BTN_LEFT = 37,
        BTN_RIGHT = 39
        ;

    // function starts a countdown to the next change in image
    resetTimeout = function () {
        if (changeTimeout)
            clearTimeout(changeTimeout);

        // less than two children does not warrant a timeout
        if (gallery.children().length < 2)
            return; 

        var next = gallery.children('li.selected').next();
        if (next.length == 0)
            next = gallery.children('li:first');

        changeTimeout = setTimeout(function () {
            next.children('a').click(); 
        }, changeTime);
    }

    // function called when a keyboard button was clicked
    onKeyDown = function (e) {
        var next = null;

        if (e.keyCode != BTN_LEFT && e.keyCode != BTN_RIGHT)
            return;
        if (gallery.children().length < 2)
            return;

        e.preventDefault();
        
        if (e.keyCode == BTN_RIGHT) {
            next = gallery.children('li.selected').next();
            if (next.length == 0) 
                next = gallery.children('li:first');
        } else if (e.keyCode == BTN_LEFT) {
            next = gallery.children('li.selected').prev();
            if (next.length == 0)
                next = gallery.children('li:last');
        }
        if (next != null) {
            next.children('a').click();
        }
    }

    // creates an overlay for transition from image to image
    createOverlay = function () {
        var overlayCSS = {
                'width': banner.width() + 'px',
                'height': banner.height() + 'px',
                'opacity': 0,
            },
            overlayParent = $('<div />').addClass('overlay').css(overlayCSS);

        overlay = $('<img />');
        overlayParent.append(overlay).insertBefore(gallery);
    }

    // called when a thumb is clicked
    thumbClicked = function (e) {
        e.preventDefault();
        var t = e.target,
            src = null;
        if (t.tagName == 'IMG')
            t = t.parentNode;
        if (t.tagName != 'A')
            return;

        if (changeBanner(t.href)) {
            $(t.parentNode).addClass('selected').siblings('.selected').removeClass('selected');
            resetTimeout();
        }
    }

    // change banner to the new value
    changeBanner = function (to) {
        if (fading || to == banner.attr('src'))
            return false;
        if (!overlay)
            createOverlay();
        fading = true;

        var img = new Image();
        img.onload = function () {
            banner.animate({'opacity': 0}, 'slow');
            overlay.attr('src', to).parent()
                .animate({'opacity': 1}, 'slow', function () {
                // changes the banner's source to that of the overlay
                banner.attr('src', to).css('opacity', 1);
                setTimeout(function () {
                    overlay.parent().css('opacity', 0);
                    fading = false; 
                }, 1);
            });
        }
        img.src = to;

        return true;
    }

    this.click(thumbClicked);
    resetTimeout();
    $(document).keydown(onKeyDown);

    // animates the children in a cute way
    var _children = gallery.children('li').css({'opacity': 0}),
        _index = _children.length - 1,
        _animateChild = function () {
            if (_index < 0)
                return;
            $(_children[_index--]).animate({'opacity': 1}, 'fast');
            setTimeout(_animateChild, 100);
        };
    _animateChild();

    return this;
}

