// Settings
var clickdelay = 5000; // How long to remove the button from the page, after clicking
var closed_width = '45px';
var open_width = '577px';
var slide_speed = 400;
var fade_speed = 1000;

// Accordion
load_slide = function(clicked_slide) {
    var clicked = clicked_slide.parent();
    var old = $("#accordion .selected");
    if (!clicked.hasClass('selected')) {
        old.children('.content').fadeOut(fade_speed);
        clicked.children('.content').fadeIn(fade_speed);
        old.animate({width:closed_width}, slide_speed);
        clicked.animate({width:open_width}, slide_speed, function() {
            old.removeClass('selected');
            clicked.addClass('selected');
        });
    }
};

$(document).ready(function(){
    $(['/media/img/ajax-loader.gif']).preload();

    $('#pagecontent').hide();
    $.address.init(function(event) {
        // Initializes plugin support for links
        $('a:not(#fancybox-close,[id^=contact_],[href^=http],[href*=mailto:],[class^=news],.lang_link,.fancybox_link,#fancybox-left,#fancybox-right)').address();
    }).change(function(event) {
        //$('#pagecontent').load(event.value);
        var value = $.address.state().replace(/^\/$/, '') + event.value;
        var handler = function(data) {
            // Get the page title
            var page_title = /the-page-title">([^<]*)<\/div>/.exec(data)[1];
            $.address.title(page_title.replace("&quot;", '"'));
            // Get the page slug
            var page_slug = /the-page-slug">([^<]*)<\/div>/.exec(data)[1];
            load_slide($("#"+page_slug));
            if (isIE) {
                $('#pagecontent').replaceWith(data);
            } else {
                $('#pagecontent').fadeOut('fast', function(){
                    $(this).replaceWith(data).hide().fadeIn(400);
                });
            }
        };

        // Loads the page content and inserts it into the content area
        $.ajax({
            url: value,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                handler(XMLHttpRequest.responseText);
            },
            success: function(data, textStatus, XMLHttpRequest) {

                handler(data);

                // handle language selection
                var next_value = value
                var re = /next=.+/
                var no_lang = /\/language\/\w+\?next=/
                $("#langs li a").each(function(){
                    var next = next_value.replace(no_lang, "");
                    var href = $(this).attr("href").replace(re, "next=" + next);
                    $(this).attr("href", href);
                });

                // handle language mark in html body
                var lang = /\/language\/(\w{2})/;
                language = value.match(lang)
                if (language) {
                    $("body").removeClass('en es fr').addClass(language[1]);
                };

            }
        });
    });

    $(".single-photo .singlephoto.fancybox_link").live('click', function() {
        var el = $(this);
        $.fancybox({
            'transitionIn':'elastic',
            'transitionOut':'elastic',
            'overlayOpacity':0.7,
            'overlayColor':'#000',
            'href':el.attr('href'),
            'title':el.attr('title')
        });
        return false;
    });
    // Ugly! Need to find a better way to do this :(
    $(".photo-gallery .singlephoto.fancybox_link.first_click").live('click', function() {
        var el = $(this);
        $(".photo-gallery .singlephoto.fancybox_link.first_click").attr('rel',el.attr('rel')).removeClass('first_click');
        $(".photo-gallery .singlephoto.fancybox_link").attr('rel',el.attr('rel')).fancybox({
            'transitionIn':'elastic',
            'transitionOut':'elastic',
            'overlayOpacity':0.7,
            'overlayColor':'#000',
            'onClosed':function() {
                $(".photo-gallery .singlephoto.fancybox_link").attr('rel',el.attr('rel')).addClass('first_click');
            }
        });
        el.trigger('click');
        return false;
    });
    $(".singlevideo.fancybox_link").live('click', function() {
        var el = $(this);
        $.fancybox({
            'padding': 0,
            'autoScale': false,
            'transitionIn': 'none',
            'transitionOut': 'none',
            'title': el.attr('title'),
            'overlayOpacity': 0.7,
            'overlayColor':'#000',
            'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/') + "?rel=0&hd=1&autoplay=1&fs=1",
            'width': 680,
            'height': 495,
            'type': 'swf',
            'swf': {
                'wmode': 'transparent',
                'allowfullscreen': 'true'
            }
        });
        return false;
    });

    $("a[id^=contact_]").live('click', function() {
        $.get($(this).attr('href'), function(data) {
            $.fancybox(data, {
                'transitionIn':'elastic',
                'transitionOut':'elastic',
                'overlayOpacity':0.7,
                'overlayColor':'#000',
                'scrolling':'no'
            });
        });
        return false;
    });
    
    $('.newslist_item_link').live('click', function() {
        $.get($(this).attr('href'), function(data) {
            // Get the page title
            var page_title = /the-page-title">([^<]*)<\/div>/.exec(data)[1];
            $.address.title(page_title.replace("&quot;", '"'));
            // Get the page slug
            var page_slug = /the-page-slug">([^<]*)<\/div>/.exec(data)[1];
            load_slide($("#"+page_slug));
            if (isIE) {
                $('#pagecontent').replaceWith(data);
            } else {
                $('#pagecontent').fadeOut('fast', function(){
                    $(this).replaceWith(data).hide().fadeIn(400);
                });
            }
        });
        return false;
    });

    $('input,textarea').live('focus', function() {
        $(this).parent().children('ul.errorlist').fadeOut('slow');
    });

    $("#general_contact_form").live('submit', function(e) {
        e.preventDefault();
        $.post('/email/', $(this).serialize(), function(data) {
            $('#data').replaceWith(data);
        });
    });
    $("#person_contact_form").live('submit', function(e) {
        e.preventDefault();
        var person_id = $("#person_id").val();
        $.post('/email/'+person_id+'/', $(this).serialize(), function(data) {
            $('#data').replaceWith(data);
        });
    });

    var loading = $('<img src="/media/img/ajax-loader.gif" alt="Please wait..." title="Please wait..." class="ajax-loader" />');
    $('input.disable-after-click').live('click', function() {
        var btn = $(this);
        loading.insertBefore(btn).hide();
        btn.fadeOut(400, function() {
            loading.fadeIn();
            setTimeout(function() {
                loading.fadeOut().remove();
                btn.fadeIn();
            }, clickdelay);
        });
    });

});

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

