//if(window.console && console.log) {
//  cl = console.log;
//}
$(document).ready(function(){
  var current_url = location.protocol + '//' + location.host + '/';
  if(location.pathname.split('/')[1].match('amnicus') != null)
    current_url += location.pathname.split('/')[1] + '/';

  $('div#main').find('a').each(function(i, el) {
    if($(el).attr('href').match('http://www.') != null) {
      $(el).attr('rel', 'external'); 
    }
  });

  $(window).resize(function() {
    var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    var elHeight = $('div#content_holder').height();
    var topSpace = (height - elHeight)/2;
    topSpace = topSpace < 0 ? 0 : topSpace
    if(topSpace >= 0) { $('div#page').css('top',topSpace + 'px'); }
  });
  $(window).resize();
  
  $('div#searchbox div').hide();
  $('a').each(function(dom, el) {
    if($(el).attr('rel') == 'external') {
      $(el).attr('title', $(el).attr('href'));
      $(el).click(function() {
        $.post('register_click', 'bla');
        window.open($(el).attr('href'));
        return false;
      });
    }
  });
  $('a#show_search').each(function(dom, el) {
    $(el).click(function() {
      if($('div#searchbox div').css('display') == 'block') {
        var value = $('div#searchbox input[type=text]').val(); 
        if(value != '' && value != 'Type zoekterm, druk enter') {
          $('div#searchbox').parent().submit();
        } else {
          $('div#searchbox div').fadeOut('fast');
        }
      } else {
        $('div#searchbox input[type=text]').val('');
        $('div#searchbox div').fadeIn('fast');
        $('div#searchbox input[type=text]').example('Type zoekterm, druk enter');
      }
    });
  });

  if($('div.projects').length > 0 || $('div.newsitems').length > 0) {
    var type = 'newsitem';
    if($('div.projects').length > 0)
      type = 'project';
    var max = 5;
    var count = 1;
    var page = 1;
    var activePage = $('div#page_' + page);
    var items = $('div.' + type);
    var ids = [];
    var pages = [activePage];
    $.each($(items), function(i, p) {
      if($(p).hasClass('spotlight'))
        count += 1;
      if(count <= max)
        ids.push($(p).attr('id'));
      if(count >= max) {
        page += 1;
        activePage.parent().append('<div id="page_' + page + '" class="page left_none"></div>');
        activePage = $('div#page_' + page);
        pages.push(activePage);
        activePage.append('<div class="column_left"></div>')
                  .append('<div class="column_middle"></div>')
                  .append('<div class="column_right"><div class="' + type + 's' + '"></div></div>');
        count = 0;
        $.each($(items), function(i2, p2) {
          if($.inArray($(p2).attr('id'), ids) == -1)
            $(p2).appendTo($(activePage).find('div.' + type + 's'));
        });
      }
      count += 1;
    });
    $.each(pages, function(ip, pp) {
      var el = $(pp).find('div.' + type + 's');
      if($.trim($(el).text()) == '') {
        $(el).parent().parent().remove();
      }
    });
  }


  if($('div.fp_picture_shower').length > 0 || $('div.cm_picture_shower').length > 0) {
    var type = $('div.fp_picture_shower').length > 0 ? 'frontpage' : 'column';
    if(type == 'column') {
      var el = $('div.cm_picture_shower');
      if($(el).parent().width() >= 670) {
        type = 'column_wide';
      }
    }
    // wait function
    $.fn.wait = function(time, type) {
      time = time || 20000;
      type = type || "fx";
      return this.queue(type, function() {
        var self = this;
        setTimeout(function() {
          $(self).dequeue();
        }, time);
      });
    };
    // run function for periodic update
    function run() {
      var img = new Image();
      $(img).css('display', 'none')
            .attr('src', current_url + 'pictures/' + type + '?_dc=' + Math.floor(Math.random()*11*10000));
      $('#loader').append(img);

      $(img).wait()
            .load(function() {
              var current_hidden = $('img:hidden', $('#loader'));
              var current_visible = $('img:visible', $('#loader'));
              $(current_visible).wait()
                                .fadeOut('slow', function() {
                                  $(current_visible).remove();
                                  $(current_hidden).fadeIn('slow', run);
                                });
            });
    }
    // set initial image
    var img = new Image();
    $(img).css('display', 'none')
          .attr('src', current_url + 'pictures/' + type + '?_dc=' + Math.floor(Math.random()*11*10000));
    $('#loader').append(img);
    $(img).fadeIn('slow', run);
  }

  // Page handler (set init)
  var el = $('div#pageswitcher_holder');
  if($('div#columns').children().length > 1) {
    var useCookie = false;
    if($('div.newsitems').length > 0 || $('div.projects').length > 0) {
      useCookie= true;
      nameCookie = location.pathname;
    }
    el.show();
    el.append('<ul>');
    $.each($('div#columns div.page'), function(i, p) {
      el.children('ul').append('<li id="swith_' + $(p).attr('id') + '">' + (i + 1) + '</li>');
      el.children('ul').find('li:last').click(function(e) {
        var x = this;
        $.each($('div#columns div.page.active'), function(i, c) {
          var cp = $(c);
          var np = $(p);
          if(!((np.children('div.column_left').length > 0) && (np.children('div.column_left:first').text() == '[ancestor]'))) {
            if(np.children('div.column_left').css('display') == 'none') {
              cp.children('div.column_left').fadeOut('fast', function() {
                np.children('div.column_left').fadeIn('fast');
              });
            }
          }

          if(!((np.children('div.column_middle').length > 0) && (np.children('div.column_middle:first').text() == '[ancestor]'))) {
            if(np.children('div.column_middle').css('display') == 'none') {
              cp.children('div.column_middle').fadeOut('fast', function() {
                np.children('div.column_middle').fadeIn('fast');
              });
            }
          }

          if(!((np.children('div.column_right').length > 0) && (np.children('div.column_right:first').text() == '[ancestor]'))) {
            if(np.children('div.column_right').css('display') == 'none') {
              cp.children('div.column_right').fadeOut('fast', function() {
                np.children('div.column_right').fadeIn('fast');
              });
            }
          }
          el.find('ul li.active').removeClass('active');
          $(p).addClass('active');
          $(c).removeClass('active');
          $(x).addClass('active');

          if(useCookie) {
            var currentPage = $(p).attr('id').split('_')[1];
            $.cookie(nameCookie, null, { path: location.pathname });
            var date = new Date();
            date.setTime(date.getTime() + (5 * 60 * 1000));
            $.cookie(nameCookie, currentPage, { path: location.pathname, expires: date });
          }
        });
      });
      el.children('ul').find('li:last').hover(
        function(eIn) {
          $(this).addClass('hover');
        }, function(eOut) {
          $(this).removeClass('hover');
        }
      );
      if($(p).attr('id') != 'page_1') {
        $(p).children('div').hide();
      } else {
        el.children('ul').find('li:last').addClass('active');
        $(p).addClass('active');
      }
    });
    if(useCookie && $.cookie(nameCookie)) {
      var page = $.cookie(nameCookie);
      var id = 'page_' + page;
      if($('div#columns div.page#' + id).length > 0) {
        $('div#pageswitcher_holder').find('li').removeClass('active');
        $.each($('div#columns div.page'), function(i, page) {
          if($(page).attr('id') == id) {
            $(page).addClass('active').children().show();
            $('div#pageswitcher_holder li#swith_' + id).addClass('active');
          } else {
            $(page).removeClass('active').children('div').hide();
          }
        });
      }

    }
  }

  // auto form validator
  if($('form.validate').length > 0) {
    $.each($('form.validate'), function(i, f) {
      var sb = $(f).find('input[type=submit]');
      $(sb).click(function(e) {
        var fields = [];
        fields = $.merge(fields, $.makeArray($(f).find('input:visible')));
        fields = $.merge(fields, $.makeArray($(f).find('textarea:visible')));
        fields = $.merge(fields, $.makeArray($(f).find('checkbox:visible')));
        fields = $.merge(fields, $.makeArray($(f).find('select:visible')));
        var errorCount = 0;
        var errorFields = [];
        var errorMessages = [];
        $.each(fields, function(i, field) {
          $(field).removeClass('error');
          var label = $(this).siblings('label').text().split(' *')[0];
          if($(this).hasClass('required')) {
            if($(this).val() == '') {
              errorFields.push($(this).attr('id'));
              errorMessages.push('Het veld \'' + label + '\' is verplicht'); 
            }
          }
          if($(this).hasClass('valid_email')) {
            var regExp = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/;
            if(!regExp.test($(this).val())) {
              errorFields.push($(this).attr('id'));
              errorMessages.push('Het veld \'' + label + '\' moet een geldig e-mailadres bevatten');
            }
          }
        });
        if(errorFields.length > 0) {
          $.each($.unique(errorFields), function(index, ef) {
            $(f).find('#' + ef).addClass('error');
          });
          $(f).find('div.error').remove();
          var message = '<div class="error">Een of meerdere velden zijn onjuist ingevuld:</div>' + "\n";
          message += '<div class="error"><ul class="error">' + "\n";
          $.each(errorMessages, function(ind, em) {
            message += '<li>' + em + '</li>' + "\n";
          });
          message += '</ul></div>' + "\n";
          $(f).prepend(message);
          return false;
        } else {
          return true;
        }
      });
    });
  }
});
