/* 

Author: Mr. Henry
Date: 2010-03-30

Fueled by jQuery

*/

/*
 * Globalize vars
 */
var language;


/*
 * DOM ready
 */
jQuery(document).ready(function(){
    
    // Initial shizzial
    $('body').addClass('js');
    $('.slideshow').hide();
    language = $('html').attr('lang');
    
    // Navigation
    try { navigation(); } catch(e) { /*console.log(e);*/ }
    
    // Forms
    try { newsletterSubscribe(); } catch(e) { /*console.log(e);*/ }
    try { languageSwitch(); } catch(e) { /*console.log(e);*/ }
    try { contactForm(); } catch(e) { console.log(e); }
    
    // Accordion
    try { accordionify(); } catch(e) { /*console.log(e);*/ }
    
    // News
    try { getOlderNews(); } catch(e) { /*console.log(e);*/ }
    
});


/*
 * Window load
 * (Use this function to do stuff with images like slideshows, otherwise you can
 * get troubles with dimensions if the attributes width/height aren't set on the image tag)
 */
window.onload = windowLoaded;
function windowLoaded(){
    
    // Slideshow
    try { slideshow(); } catch(e) { /*console.log(e);*/ }
    
    // Grid
    try { grid(); } catch(e) { /*console.log(e);*/ }
    
}


/*
 * Navigation
 */
function navigation(){
    
    var sub_menus           = $('#navigation > li > ul');
    var sub_menu_parents    = sub_menus.closest('li');
    var sub_sub_menu_parents= sub_menus.find('li ul').closest('li');
    
    sub_sub_menu_parents.addClass("children");
    
    // Give sub menus the width of their parent
    sub_menus.each(function(){
        var parent  = $(this).prev();
        var width   = parent.width();
        var padding = parseInt(parent.css('paddingLeft').replace('px',''));
        if ($.browser.msie) {
            width = width + padding;
        } else {
            width = width + padding
        }
        $(this).css({ 'width': (width), 'left': (padding/2) });
        
        // Position subsubmenu
        $(this).find('ul').css({ 'left': (width) });
        
    });
    
    // Events
    sub_menu_parents.add(sub_menu_parents.find('li')).hover(
        function(){
            $(this).addClass('hover');
        },
        function(){
            $(this).removeClass('hover');
        }
    );
}


/*
 * Slideshow
 * (Motorized by http://jquery.malsup.com/cycle)
 */
function slideshow(){
    
    // Initialize
    var slideshow   = $('.slideshow .viewport');
    if (slideshow.length > 0) {
        slideshow
            .before('<div class="navigation clearfix">')
            .cycle({
                timeout:    0,
                speed:      300, 
                //next:       slideshow,
                pager:      '.navigation',
                before:     adjustSlideshowDimensions,
                cleartype:  1
        });
        $('.slideshow').show();
    }
    
    // Adjust slideshow dimensions
    function adjustSlideshowDimensions(currSlideElement, nextSlideElement, options, forwardFlag){
        offset  = 20; // Yeah yeah I know, not the best way but it works :)
        radix   = 10;
        padding = offset + parseInt((slideshow.parent().css('paddingTop')).replace('px',''), radix) + parseInt((slideshow.parent().css('paddingBottom')).replace('px',''), radix);
        img_height  = $(nextSlideElement).find('img').attr('height');
        slideshow.parent().animate({ 'height': (padding + img_height) }, 200);
    }
    
    // Mini slideshow (with jQuery Cycle plugin)
    var mini_slideshow = $('.mini-slideshow');
    if (mini_slideshow.length > 0){
        try { mini_slideshow.cycle(); } catch(e) { }
    }
    
} 


/*
 * Grid
 * (Nibble-nabbled together with http://desandro.com/resources/jquery-masonry)
 */ 
function grid(){
    
    // Initialize
    var grid = $('.grid');
    if (grid.length > 0) {
        grid.masonry({
            itemSelector: '.box'
        });
    }
}


/*
 * Everything that has to do with a form
 * (Infield labels: http://fuelyourcoding.com/scripts/infield/)
 */
function newsletterSubscribe(){
    
    // Newsletter subscribe form
    var newsletter_box  = $('#secondary .newsletter');
    var newsletter_form = newsletter_box.find('form');
    if (newsletter_form.length > 0) {
        
        // Styling
        newsletter_form.find('label').inFieldLabels();
        var button = newsletter_form.find('button');
        var input_fields        = newsletter_form.find('input[type=text]');
        var input_outer_height  = input_fields.first().outerHeight(true);
        var input_margin_bottom = parseInt(input_fields.first().css('marginBottom').replace('px',''));
        var button_inner_height = (2 * input_outer_height) - input_margin_bottom;
        button.css({ 'height': button_inner_height });
        
        // Event
        newsletter_form.find('button[type=submit]').click(function(){
            addLoader(newsletter_box);
            newsletter_form.animate({ 'opacity' : '0.5' });
            $.ajax({
                url: '/nl/newsletter',
                data: newsletter_form.serialize(),
                type: 'post',
                success: function(data){
                    handleFormResponse(data, newsletter_box);
                }
            });
            return false;
        });
    }
}


function contactForm(){
  var contact_form = $('#primary .contact-form form');
  $('label', contact_form).inFieldLabels();
  contact_form.validate();
}

function languageSwitch()
{
    // Language switch
    var language_switch = $('#top-navigation .language');
    if (language_switch.length > 0) {
        
        // Transform list to select box
        language_switch.hide();
        var select_el   = $('<select class="language">');
        select_el.insertAfter(language_switch);
        language_switch.find('a').each(function(){
            var option_el   = $('<option>');
            var value       = $(this).attr('href').replace('/','');
            var title       = $(this).html();
            option_el.appendTo(select_el).attr('value', value).html(title);
        });
        language_switch.remove();
        language_switch = $('#top-navigation .language');
        language_switch.uniform();
        
        // Switch functionality
        language_switch.change(function(){
            window.location = '/' + $(this).find('option:selected').attr('value');
        });
    }
}


/*
 * Accordion
 * (Magic by http://jqueryui.com)
 */
function accordionify(){
    var accordion_el    = $('.accordion');
    if (accordion_el.length > 0) {
        accordion_el.accordion({ 'autoHeight': false });
    }
}


/*
 * Display loader
 */
function addLoader(container){
    if (container == undefined){
        return false;
    } else {
        $('<p class="loader"></p>').insertBefore(container.find('form'));
        return true;
    }
}

function removeLoader(container){
    if (container == undefined){
        return false;
    } else {
        container.find('.loader').remove();
        return true;
    }
}


/*
 * Handle form response 
 */
function handleFormResponse(data, container){
    /* 
        data.status:    'ok' or 'error' 
        data.message:   string or array
    */
    var class_error     = '.error';
    var class_success   = '.success';
    var class_notice    = '.notice';
    var form            = container.find('form');
    var wrapper;
    
    removeLoader(container);
    
    if (container.find(class_error + ', ' + class_success + ', ' + class_notice).length > 0) {
        container.find(class_error + ', ' + class_success + ', ' + class_notice).remove();
    }
    
    if (data.status == 'error') {
        wrapper = $('<p class="' + data.status + '"></p>');
    } else {
        wrapper = $('<p class="' + data.status + '"></p>');
    }
    wrapper.insertBefore(form).hide();
    
    if (typeof(data.message) == 'object') {
        //$.each(data.message, function(key, value){
        //    wrapper.append('<li>' + value + '</li>');
        //});
        wrapper.html(data.message[0]);
    } else {
        wrapper.html(data.message);
    }
    wrapper.show();
    
    if (data.status == 'error'){
        form.animate({ 'opacity' : '1' });
    } else if (data.status == 'success') {
        form.hide();
    }
}


/*
 * Get older news
 */
function getOlderNews(){
    var news_posts_box = $('.news-posts');
    if (news_posts_box.length > 0){
        
        // Events
        news_posts_box.find('.archive').click(function(){
            var button          = $(this);
            var visible_posts   = news_posts_box.find('li').length;
            var news_post_list  = news_posts_box.find('ul');
            var current_post_id = $('#primary .post').attr('id').replace('news-post-','');
            $.ajax({
                type: 'POST',
                url: $(this).attr('href'),
                data: 'offset=' + visible_posts,
                success: function(data){
                    switch(data.status){
                        case 'success':
                            var li;
                            $.each(data.posts, function(idx, value){
                                li          = $('<li>').attr('id', value.id);
                                a           = $('<a>').attr('href', '/' + language + '/news-post/' + value.id).html(value.title);
                                strong      = $('<strong>').addClass('date').html(value.published);
                                list_item   = li.wrapInner(a);
                                list_item.prepend(' ').prepend(strong);
                                if (value.id == current_post_id){
                                    list_item.addClass('active');
                                }
                                list_item.appendTo(news_post_list).hide().fadeIn('200');
                            });
                            if (data.posts.length <= 5){
                                button.hide();
                            }
                            break;
                        case 'no more posts':
                            button.hide();
                            break;
                    }
                }
            });
            return false;
        });
        
    }
}


