/* 

Author: Mr. Henry
Date: 2010-05-17

Fueled by jQuery

*/


/*
 * DOM Ready
 */
$(function(){
    
    // Initial shizzial
    $('body').addClass('js');
    try { $("select, input[type=checkbox], input[type=radio]").uniform(); } catch(e) { log(e); };
    
    // Tabs & navigation
    try { ws_tabify(); } catch(e) { log(e); }
    try { ws_navigation(); } catch(e) { log(e); }
    
    
    // Banner
    try { ws_banner(); } catch(e) { log(e); }
    
    
    // Products
    try { ws_grid(); } catch(e) { log(e); }
    try { ws_product_expose(); } catch(e) { log(e); }
    try { ws_product_order_info_request(); } catch(e) { log(e); }
    try { ws_product_share_request(); } catch(e) { log(e); }
    
    
    // Contact
    try { ws_contact_form(); } catch(e) { log(e); }
    
    
    // Gallery
    try { ws_gallery(); } catch(e) { log(e); }
    
    
    // Participate
    try { ws_participation_form(); } catch(e) { log(e); }
    
    
    // Order by
    try { order_by(); } catch(e) { log(e); }
    
    
    // Transport
    try { ws_transport_conditions(); } catch(e) { log(e); }
    
    
    // Hocus focus
    try { ws_search_focus(); } catch(e) { log(e); }
    try { ws_newsletter_focus(); } catch(e) { 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()
{
    
    // Backgroud image
    try { hyper_size(); } catch(e) { log(e); }
    
    // Slideshows
    try { ws_slideshows(); } catch(e) { log(e); }
    
    // Products
    try { ws_product_color_change(); } catch(e) { log(e); }
    
}


/*
 * Slideshows
 * Driven by http://jquery.malsup.com/cycle/
 */
function ws_slideshows()
{
    
    $('.slideshow').cycle('fade');
    
}


/*
 * Tabs
 * http://jqueryui.com/demos/tabs/
 */
function ws_tabify()
{
    
    $('.tabs').tabs();
    
}


/*
 * Navigation
 */
function ws_navigation()
{
    var navigation = $('#header .navigation');
    navigation.find('li').hoverClass();
} 


/*
 * Banner
 */
function ws_banner()
{
    
    var banner = $('#banner');
    if (banner.length > 0) {
        banner.hide();
        setTimeout(function(){
            banner.slideDown(1200, 'easeOutBounce');
        }, 750);
        banner.hoverClass();
        banner.click(function(){
            window.location.href = banner.find('a').attr('href');
        });
    }
}


/*
 * Grid behaviours
 */
function ws_grid()
{
  var grid = $('.grid');
  if (grid.length > 0) {
    //$('img', grid).fadeTo(0, 0.5);
    $('li', grid).hover(
      function(){
        var img = $('img', $(this));
        img.stop();
        img.fadeTo('fast', 0.5);
      }, function(){
        var img = $('img', $(this));
        img.stop();
        img.fadeTo('fast', 1);
      }
    );
  }
} 

 
/*
 * Product image exposé
 */
function ws_product_expose()
{
    if ($('.product-detail .product-image img').length > 0) {
        var image_wrap  = $('.product-detail .product-image');
        var button      = image_wrap.find('a');
        var button_text = button.html();
        var content     = $('#content .block');
        button.click(function(){
            if ($('.overlay').length > 0) {
                $('.block').removeClass('invisible');
                $(this).removeClass('close').html(button_text);
                $('.overlay').remove();
            } else {
                $('.block').addClass('invisible');
                $(this).addClass('close').html('Afbeelding sluiten');
                var big_image_url   = $(this).attr('href');
                var image_tag       = $('<img>').attr('src', big_image_url);
                var overlay_el      = $('<div class="overlay">');
                image_tag.appendTo(overlay_el);
                overlay_el.prependTo(image_wrap);
            }
            return false;
        });
    }
}


/*
 * Product color change
 */
function ws_product_color_change()
{
    var colors  = $('.product-detail .colors img');
    if (colors.length > 0) {
        try { 
          $('.product-detail .colors ul').masonry({
            itemSelector: 'li' ,
            columnWidth: 95
          });
        } catch (e) { log(e); }
        colors.hover(
            function(){
                $(this).stop();
                $(this).animate({ 'opacity': 0.6 });
            }, function(){
                $(this).stop();
                $(this).animate({ 'opacity': 1 });
        });
        colors.click(function(){
            var product_nr  = $(this).attr('rel');
            var image_url   = $(this).attr('src').replace('mini', 'medium');
            var big_image_url   = image_url.replace('medium','big');
            $('.product-image img').attr('src', image_url);
            $('.product-image a').attr('href', big_image_url);
            $('#product-info .nr span').html(product_nr);
            $('#order_info_product_nr, #share_product_nr').val(product_nr);
        });
    }
}


/*
 * Product order info request
 */
function ws_product_order_info_request(){
    var block   = $('#order-info');
    var form    = block.find('form');
    if (block.length > 0) {
        block.find('button[type=submit]').click(function(){
            addLoader(block);
            $.ajax({
                url: form.attr('action'),
                data: form.serialize(),
                type: 'post',
                success: function(data){
                    log(data);
                    removeLoader(block);
                    responseHandler(data, {
                        'container': block,
                        'hide_form_on_success': true,
                        'hide_form_animation': 'fade'
                    });
                }
            });
            return false;
        });
    }
}



/*
 * Product share request
 */
function ws_product_share_request(){
    var block   = $('#share');
    var form    = block.find('form');
    if (block.length > 0) {
        block.find('button[type=submit]').click(function(){
            addLoader(block);
            $.ajax({
                url: form.attr('action'),
                data: form.serialize(),
                type: 'post',
                success: function(data){
                    log(data);
                    removeLoader(block);
                    responseHandler(data, {
                        'container': block,
                        'hide_form_on_success': true,
                        'hide_form_animation': 'fade'
                    });
                }
            });
            return false;
        });
    }
}


/*
 * Contact form
 */
function ws_contact_form()
{
    if ($('body.contact').length > 0) {
        
        var form_block  = $('.block.form');
        form_block.hide();
        
        $("a[href*='mailto']").click(function(){
            var title       = $('h1');
            var btn_close   = $('<a>').addClass('close').html('Formulier sluiten');
            var target      = $('.block').first();
            
            target.css({ 'overflow': 'visible' });
            title.css({ 'z-index': '4', 'position': 'relative' });
            
            if (target.height() > form_block.height()) {
                form_block.css({ 'height': target.height() });
            }
            
            btn_close.appendTo(form_block);
            form_block.appendTo(target);
            form_block.addClass('overlay');
            
            form_block.show();
            
            btn_close.click(function(){
                form_block.hide();
            });
            
            return false; 
        });
        
        if (location.href.indexOf("#form") != -1) {
            $("a[href*='mailto']").click();
        }
        
        // Validation
        var f_last_name     = new LiveValidation("contact_request_last_name", {onlyOnSubmit: true });
        var f_first_name    = new LiveValidation("contact_request_first_name", {onlyOnSubmit: true });
        var f_email         = new LiveValidation("contact_request_email", {onlyOnSubmit: true });
        var f_question      = new LiveValidation("contact_request_question", {onlyOnSubmit: true});
        
        f_last_name.add(Validate.Presence);
        f_first_name.add(Validate.Presence);
        f_email.add(Validate.Presence);
        f_question.add(Validate.Presence);
    }
} 


/*
 * Image gallery
 */
function ws_gallery()
{
  
  var gallery_el = $('#gallery');
  if (gallery_el.length > 0) {
    
    // VARS
    var t_dir = 'thumb';  // Name of thumb image folder
    var l_dir = 'large';  // Name of large image folder
    var f_time = 300;     // Fade time
    var s_time = 500;     // Slide time
    var ul_w = $('#thumbnails ul:eq(0)').outerWidth(true);
    var ul_l = $('#thumbnails ul').length - 1; // -1 since we want to start the counting from zero
    var curr_ul = 0;
    var curr_img = 0;
    var image_urls = [];
    
    $('#thumbnails a').each(function(){
      image_urls.push($(this).attr('href'));
    });
   
    // CSS
    $('#thumbnails').width(ul_w*(ul_l+1)); // +1 since we started counting from zero
    $('#gallery').append('<a href="#" class="previous"></a><a href="#" class="next"></a>');
    $('#gallery .next, #gallery .previous').not('#thumb_wp .next').css({ 'opacity': 0 });
   
   
    // INTERACTIVIY
    function slide_uls()
    {
      $('#thumbnails ul').animate({
        'left' : -( ul_w*curr_ul )+'px'
      }, { queue: false, duration: s_time });
    }
    
    $('#gallery .next, #gallery .previous').not('#thumb_wp .next').hover(
        function(){
            $(this).stop().animate({ 'opacity': 1 });
        }, function(){
            $(this).stop().animate({ 'opacity': 0 });
        }
    );
    
    $('#gallery .next, #gallery .previous').not('#thumb_wp .next').click(function(){
      change_image($(this).attr('href'));
      return false;
    });
    
    $('#thumbnails li').hover(
        function(){
          $(this).stop();
          $(this).animate({ 'opacity': 0.6 });
        }, function(){
          $(this).stop();
          $(this).animate({ 'opacity': 1 });
        }
    );
   
    $('#thumbnails li').click(function(){
      change_image($(this).find('a').attr('href'));
      return false;
    });
   
    $('#thumb_wp .prev, #thumb_wp .next').click(function(){
      if( $(this).hasClass('prev') && curr_ul > 0 )
      {
        curr_ul--;
        slide_uls();
      }
      else if ( $(this).hasClass('next') && curr_ul < ul_l )
      {
        curr_ul++;
        slide_uls();    
      }
      return false;
    });
    
    function get_next_image(url){
      var next_image = null;
      $.each(image_urls, function(idx, value){
        if (value == url){
          if (image_urls[idx + 1] != undefined) {
            next_image = image_urls[idx + 1];
          }
        }
      });
      return next_image;
    }
    
    function get_previous_image(url){
      var previous_image = null;
      $.each(image_urls, function(idx, value){
        if (value == url){
          if (image_urls[idx - 1] != undefined) {
            previous_image = image_urls[idx - 1];
          }
        }
      });
      return previous_image;
    }
    
    function change_image(url){
      var img = new Image();
      $(img).attr('src', url.replace(t_dir, l_dir)).load(function(){
        $(this).hide();
        $('#background-image img').attr('src', url.replace(t_dir, l_dir));
      });
      
      var next_image = get_next_image(url);
      if (next_image != null){
        $('#gallery .next').not('#thumb_wp .next').show().attr('href', next_image);
      } else {
        $('#gallery .next').not('#thumb_wp .next').hide();
      };
      
      var previous_image = get_previous_image(url);
      if (previous_image != null){
        $('#gallery .previous').show().attr('href', previous_image);
      } else {
        $('#gallery .previous').hide();
      };
    }
    
    // Initial click
    $('#thumbnails li').first().click();
  }
}


/*
 * Participation form
 */
function ws_participation_form()
{
    if ($('body.participate').length > 0) {
        var form   = $('.new_participation_request');
        var form_1 = $('#part1');
        var form_2 = $('#part2');
        
        // Initialize
        form_2.hide();
        form_1.find('.other input[type=text]').hide();
        
        form_1.find('.other .checker').click(function(){
            if ($(this).find('.checked').length > 0) {
                form_1.find('.other input[type=text]').show();
            } else {
                form_1.find('.other input[type=text]').hide();
            }
        });
        
        // Validation part 1
        form_1.find('.button').click(function(){
            var message = { 'status': 'success' };
            form_1.find('.message').remove();
            if (form_1.find('input:checkbox:checked').length <= 0) {
                message = { 'status': 'error', 'message': 'Gelieve minstens één productgroep aan te vinken' };
                var message_block   = $('<p>').addClass('message ' + message.status).html(message.message);
                message_block.insertAfter(form_1.find('h2'));
                return false;
            };
            if (form_1.find('input:radio:checked').length <= 0) {
                message = { 'status': 'error', 'message': 'Gelieve het netto aantal vierkante meters aan te vinken' };
                var message_block   = $('<p>').addClass('message ' + message.status).html(message.message);
                message_block.insertAfter(form_1.find('h2'));
                return false;
            };
            if (message.status == 'success') {
                form_1.hide();
                form_2.show();
            }
        });
        
        form_2.find('.arrow-back').click(function(){
            form_2.hide();
            form_1.show();
        });
        
        // Validation part 2
        var f_company       = new LiveValidation("participation_request_company", {onlyOnSubmit: true });
        var f_address       = new LiveValidation("participation_request_address", {onlyOnSubmit: true });
        var f_postal_code   = new LiveValidation("participation_request_postal_code", {onlyOnSubmit: true });
        var f_place         = new LiveValidation("participation_request_place", {onlyOnSubmit: true });
        var f_country       = new LiveValidation("participation_request_country", {onlyOnSubmit: true });
        var f_phone         = new LiveValidation("participation_request_phone", {onlyOnSubmit: true });
        var f_coc_nr        = new LiveValidation("participation_request_coc_nr", {onlyOnSubmit: true });
        var f_vat_nr        = new LiveValidation("participation_request_vat_nr", {onlyOnSubmit: true });
        var f_last_name     = new LiveValidation("participation_request_last_name", {onlyOnSubmit: true });
        var f_first_name    = new LiveValidation("participation_request_first_name", {onlyOnSubmit: true });
        var f_email         = new LiveValidation("participation_request_email", {onlyOnSubmit: true });
        
        f_company.add(Validate.Presence);
        f_address.add(Validate.Presence);
        f_postal_code.add(Validate.Presence);
        f_place.add(Validate.Presence);
        f_country.add(Validate.Presence);
        f_phone.add(Validate.Presence);
        f_coc_nr.add(Validate.Presence);
        f_vat_nr.add(Validate.Presence);
        f_last_name.add(Validate.Presence);
        f_first_name.add(Validate.Presence);
        f_email.add(Validate.Presence);
        
    }
}


/*
 * Transport conditions 
 */
function ws_transport_conditions()
{
    if ($('body.transport').length > 0) {
        
        var block  = $('#transport_conditions');
        block.hide();
        
        $("a[href*='#transport_conditions']").click(function(){
            var title       = $('h1');
            var btn_close   = $('<a>').addClass('close').html('Voorwaarden sluiten');
            var target      = $('.block').first();
            
            target.css({ 'overflow': 'visible' });
            title.css({ 'z-index': '4', 'position': 'relative' });

            if (target.height() > block.height()) {
                block.css({ 'height': target.height() });
            }
            
            btn_close.appendTo(block);
            block.appendTo(target);
            block.addClass('overlay').addClass('wide');

            block.show();

            btn_close.click(function(){
                block.hide();
            });

            return false; 
        });
    }
} 


/*
 * Add & remove ajax loader
 */
function addLoader(target){
    if (target == undefined){
        return false;
    } else {
        $('<div class="loader"></div>').prependTo(target);
        return true;
    }
}

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



/*
 * Response handler
 */
function responseHandler(data, options)
{
    var defaults = {
        'container'             : $('body'),
        'hide_form_on_success'  : false,
        'hide_form_animation'   : null,
        'animation_speed'       : 300
    };
    var settings = $.extend(defaults, options);
    
    if (data != undefined) {
        settings.container.find('.message').remove(); // Delete previous messages
        
        var form            = settings.container.find('form');
        var message_block   = $('<p>').addClass('message ' + data.status).html(data.message);
        message_block.insertBefore(form).hide();
        
        if (data.status == 'success') {
            if (settings.hide_form_on_success) {
                if (settings.hide_form_animation == null) {
                    form.hide();
                    message_block.show();
                } else {
                    form.fadeOut(settings.animation_speed, function(){
                       message_block.fadeIn(settings.animation_speed); 
                    });
                }
            } 
        } else {
            message_block.show();
        }
        

    }
}


/*
 * Order by
 */
function order_by()
{
  
  $('form.order_by button').css({'display':'none'});
  
  $('select#order_by').change(function(){ 
    $('form.order_by').submit();
  });
  
}


/*
 * Search focus
 */
function ws_search_focus()
{
  
  var search_container = $('#search');
  
  $('#search-term').focus(function(){
    search_container.addClass('hover');
  }).blur(function(){
    search_container.removeClass('hover');
  });
  
}


/*
 * Newsletter focus
 */
function ws_newsletter_focus()
{
  var input_id = '#newsletter_email';
  $('a[href=' + input_id + ']').click(function(){
    $(input_id).focus();
    return false;
  });
}


/*
 * Log function which checks if the console & log functions are available
 */
function log()
{
    if (window.console && window.log) {
        window.console.log(Array.prototype.join.call(arguments,' '));
    }
};



/*
 * Hover class adds and removes a given classname to an element
 * Usage: $(selector).hoverClass('class-name');
 * Options:
 *   css_class = CSS class to be added, (default: 'hover')
 */
$.fn.hoverClass = function(options){
    var defaults = {
        'css_class': 'hover'
    };
    var settings = $.extend(defaults, options);
    
    $(this).hover(function(){
        $(this).addClass(settings.css_class);
    }, function(){
        $(this).removeClass(settings.css_class);
    });
};



jQuery.fn.fadeOut = function(speed, callback) {
 return this.animate({opacity: 'hide'}, speed, function() {
 if (jQuery.browser.msie) {
   this.style.removeAttribute('filter');
 }
  
 if (jQuery.isFunction(callback))
  callback();
 });
};

jQuery.fn.fadeTo = function(speed,to,callback) {
 return this.animate({opacity: to}, speed, function() {
   if (to == 1 && jQuery.browser.msie)
    this.style.removeAttribute('filter');
   if (jQuery.isFunction(callback))
    callback();
 });
};

