
// narville items
var narville = (function($){

  var $items, $twitter, $active = -1;
  
  // places the items in their wrapper
  function place_items(){
  
    var 
      total = (function(items){var c=0; for(i in items){if(items[i].images.length > 0)c++}return c})($items),
      count = 0;

    //empty the container
    $('#content_center').empty();
    
    //show loading bar
    start_loading();
    
    //itterate item metadata
    $.each($items, function(i){

      var thumbnail_width;
      var thumbnail_height;

      switch(this.block_id){
        case '1':
          thumbnail_width = 213;
          thumbnail_height = 186;
          break;
        case '2':
          thumbnail_width = 213;
          thumbnail_height = 396;
          break;
        case '3':
          thumbnail_width = 235;
          thumbnail_height = 187;
          break;
        case '4':
          thumbnail_width = 448;
          thumbnail_height = 187;
          break;
        case '5':
          thumbnail_width = 448;
          thumbnail_height = 397;
          break;
        case '6':
          thumbnail_width = 470;
          thumbnail_height = 282;
          break;
        case '7':
          thumbnail_width = 448;
          thumbnail_height = 187;
          // thumbnail_width = 680;
          // thumbnail_height = 285;
          break;
        case '8':
          thumbnail_width = 448;
          thumbnail_height = 187;
        default:
          thumbnail_width = 470;
          thumbnail_height = 281;
          break;
      }
      
      //append item
      $('#content_center').append($(
        '<div class="col block-'+this.block_id+' col-image shadow type-'+this.type_id+'">'+
        '  <div href="#' + this.category.toString() + '" class="project-item clearfix" rel="' + i + '">'+
      (this.thumbnail !== false ?
        '    <div class="project-image"><img src="http://www.narville.nl/img.php?file=/home/narville/domains/narville.nl/public_html/site/components/narville/uploads/'+this.thumbnail+'&resize='+thumbnail_width+'/'+thumbnail_height+'" /></div>' : '')+
        '    <div class="inner">'+
        '      <h3>' + this.title + '</h3>'+
        '      <h4>' + this.subtitle + '</h4>'+
      (this.block_id == 7 || this.block_id == 8 ?
        '      <div>'+this.text+'</div>' : '')+
        '      <div class="tag-container">'+
        '        ' + $.map(this.tags, function(v, i){return (i > 999 ? '' : '<a href="#tag-'+ v.toLowerCase() +'" class="tag disabled">'+ v +'</a>')}).join('') +
        '        <div class="reset"></div>'+
        '      </div>'+
        '    </div>'+
        '  </div>'+
        '</div>'
      )
      .disableSelection()
      .click(show_fullscreen)
      .find('.project-image img')
      .one('load', function(){
        count++;
        if(count == Math.round(total/6)){
          stop_loading();
          init_plugins();
        }
      }).end());
    
    });

    setTimeout(function(){
      i = 1;
      $('#content_center').find('.project-image img').each(function(){
        var src = $(this).attr('src')+'&test=1';
        var _this = $(this);
        setTimeout(function(){
          $(_this).attr('src', src);
        }, 200*i);
        i++;
      });
    }, 5000);
    
    //append clearfix
    $('#content_center').append('<div class="clear">');
    
  }
  
  // add .filter to the appropriate items
  function filter_items(){

    $('#content_center .col').each(function(){
      
      var data = ($(this).hasClass('col-twitter') ? null : $items[$('.project-item', this).attr('rel').toInt()]), filters = (
        
        //title is matched
        ($('#filter_text').val().length < 1 || $(this).find("h3, h4, .tag").text().toLowerCase().indexOf($('#filter_text').val().toLowerCase()) > -1) &&
        
        //category selected
        ($('.category-list a.selected').size() == 0 || (!$(this).hasClass('col-twitter') &&
        (
          //portfolio
          data.category == $('.category-list a.selected').attr('rel').toInt()
          || (data.category >= 1 && data.category <= 4 && $('.category-list a.selected').attr('rel').toInt() == 6)
        )
        )) &&
        
        //tags matching
        ($('#filter_tag a.selected').size() == 0 || (!$(this).hasClass('col-twitter') && (function(){
          var match=true;
          $('#filter_tag a.selected').each(function(){
            match = ($.inArray($(this).text(), data.tags) > -1);
            return match;
          });
          return match;
        })()))
        
      );
      
      if(!filters){
        $(this).addClass('filtered');
      }else{
        $(this).removeClass('filtered');
      }

    });
    
  }
  
  // add random twitter messages in between the current items
  function place_twitter(occurence){
    
    $.ajax({
      url: "/plugins/twitter/cache.ser"
    }).done(function(data){
      console.log(data);
    });
    
    var items = $('#content_center .col');
    var max = Math.round( items.size() / occurence );
    var tweets = $twitter, tweet = '', tweet_date = '';
    var i = 0;
    
    while(i < tweets.length && i < max)
    {
      
      if(i == 0){
        tweet = '<h3>Goede timing! De nieuwe Narville-site staat online. Heeft u het hele weekend om deze rustig te bekijken. Benieuwd naar de feedback.</h3>';
        tweet_date = '6 januari 2012';
      }else if(i == 1){
        tweet = '<h3>Voor dat feedbacken staat er overigens ook een button op de site. Check www.narville.nl</h3>';
        tweet_date = '6 januari 2012';
      }else if(i == 2){
        tweet = '<h3>Narville zoekt ervaren, creatief DTPer met hart en gevoel voor nieuwe media. Check <a href="http://www.narville.nl" target="_blank">http://www.narville.nl</a> Please RT</h3>';
        tweet_date = '9 januari 2012';
      }else if(i == 3){
        tweet = '<h3>#Narville heeft ook een heel sportief team. Anita vol in de schijnwerpers tijdens #Spinningmarathon <a href="http://pic.twitter.com/kkhFezqq" target="_blank">pic.twitter.com/kkhFezqq</a></h3>';
        tweet_date = '14 januari 2012';
      }else if(i == 4){
        tweet = '<h3>Ruim 54.000 euro voor #spinningmarathon! Trots op #Westland</h3>';
        tweet_date = '14 januari 2012';
      }else if(i == 5){
        tweet = '<h3>Burg vd Tak pleit voor meer toegevoegde waarde/promotie bij vermarkten van producten tijdens receptie 10 jaar #Fresq</h3>';
        tweet_date = '21 januari 2012';
      }else if(i == 6){
        tweet = '<h3>Trots op het eindresultaat! Red Star volop in beweging: <a href="http://www.groentennieuws.nl/nieuwsbericht_detail.asp?id=79413#.TyE1tz9W1i8.twitter" target="_blank">http://www.groentennieuws.nl/nieuwsbericht_detail.asp?id=79413#.TyE1tz9W1i8.twitter</a> via @AddThis</h3>';
        tweet_date = '26 januari 2012';
      }else if(i == 7){
        tweet = '<h3>Daar zit je dan... #stroomstoring Naaldwijk</h3>';
        tweet_date = '27 januari 2012';
      }else if(i == 8){
        tweet = '<h3>AGF Nederland, en @FresqRedStar en @versdirect.nl in het bijzonder, veel succes in Berlijn! #Fruit Logistica</h3>';
        tweet_date = '8 februari 2012';
      }else if(i == 9){
        tweet = '<h3>Mobiele website van #FresqRedStar gelanceerd, gericht op handel en consument! #smaaktomaten #voorlopers</h3>';
        tweet_date = '9 februari 2012';
      }else if(i == 10){
        tweet = '<h3>Made to fit...the future. #KemelingKunststoffen in het nieuw op #TBR2012 Gorinchem, by #Narville</h3>';
        tweet_date = '14 februari 2012';
      }else if(i == 11){
        tweet = '<h3>Eerste gesprekken achter de rug voor de functie van creatief #dtper bij #Narville #veelbelovend</h3>';
        tweet_date = '21 februari 2012';
      }

      items.eq(Math.floor((11-i) * items.size() / 10)).after(
        '<div class="col col-215 col-twitter shadow">'+
        '  <div class="project-item">'+
        '    <div class="inner">'+tweet+
        '      <h4><a href="https://twitter.com/narville" target="_blank">@ Narville</a> - '+tweet_date+'</h4>'+
        '    </div>'+
        '  </div>'+
        '</div>'
      ).disableSelection();

      i++;

    }
    
  }
  
  // show loading bar
  function start_loading(){
    $('#fullscreen-window .loading').fadeIn(200);
  }
  
  //hide loading bar
  function stop_loading(){
    $('#fullscreen-window .loading').fadeOut(200);
  }
  
  // bind events
  function bind_events(){
    
    var filter = function(){
      filter_items();
      $('#content_center').isotope({filter: ':not(.filtered)'});
      $.scrollTo(0, 200, {});
    }
     
    //search field
    $("#filter_text").bind("keyup change", filter);
    
    //enter key blurs all text fields
    $("input[type='text']").keypress(function(e){
      if(e.which == 13){
        e.preventDefault();
        $(this).blur(); 
      }
    });
    
    //filter category
    $(".category-list a").bind('click dblclick', function(){
      
      $('.category-list a.selected').not(this).removeClass('selected');
      $(this).toggleClass('selected');
      $("#filter_text").val('');
      $('.tag').removeClass('selected');
      
      filter();
      
      var tags = [];
      $('#content_center .col:not(.filtered):not(.col-twitter)').each(function(){
        $.merge(tags, $items[$('.project-item', this).attr('rel').toInt()].tags);
      });
      
      $('#filter_tag .tag').hide().filter(function(){
        return $.inArray($(this).text(), tags) > -1;
      }).show();
      
    });
    
    //tag hovers activate other tag hover states
    $('.tag')
      .live('mouseover', function(e){
        $('.tag[href="'+$(this).attr('href')+'"]').addClass('active');
      })
      .live('mouseleave', function(e){
        $('.tag[href="'+$(this).attr('href')+'"]').removeClass('active');
      })
      .live('click', function(e){
        $('.tag[href="'+$(this).attr('href')+'"]').toggleClass('selected');
        filter();
      });
   
    //close fullscreen view
    $('#logo, #close-btn').click(hide_fullscreen);
    
    //full screen text div is draggable
    $("#fullscreen-window .text").draggable({
      containment: '#fullscreen-window',
      start:function(e, ui){
        $("#fullscreen-window .text").css('bottom', 'auto');
      }, 
      stop:function(e, ui){
        $(this);
      }
    }).disableSelection();
    
    //doubleclicking in fullscreen mode hides content, logo and controls
    $('#fullscreen-window #hit-area').dblclick(function(e){
      
      switch($('#fullscreen-window').data('toggle')){
        case undefined:
        case 0:
          $('#fullscreen-window').find('.text, #controls:not(.single)').add('#logo').fadeOut(300);
          $('#fullscreen-window').data('toggle', 1);
          break;
        case 1:
          $('#fullscreen-window').find('.text, #controls:not(.single)').add('#logo').fadeIn(300);
          $('#fullscreen-window').data('toggle', 0);
          break;
      }
      
    });
   
    //clear filters
    $('#logo a').click(function(){
      if(!($('body').hasClass('fullscreen'))){
        $('#filter_text').val('');
        $('.category-list a, #filter_tag a, .tag-container .tag').removeClass('selected');
        $('#filter_tag .tag').show();
        filter();
      };
    });

  }
  
  //initiate plugins
  function init_plugins(){
    
    //initiate isotope
    $('#content_center').isotope({
      itemSelector : '.col:not(.type-2)',
      filter: ':not(.filtered)',
      layoutMode : 'masonry',
      masonry: {
        columnWidth: 235
      },
      animationOptions: {
        duration: 200,
        easing: 'linear',
        queue: false
      }
    });

    //initiate mbBgndGallery
    $('#fullscreen-window').delay(500).fadeOut(500, function(){
      
      $('#fullscreen-window').append(
        '<div id="controls">'+
        '  <div class="prev"><a href="#">prev</a></div>'+
        '  <div class="next"><a href="#">next</a></div>'+
        '  <div class="counter"></div>'+
        '</div>'
      );
      
      $.mbBgndGallery.buildGallery({
        containment: '#fullscreen-window',
        autostart: false,
        effTimer:500,
        controls:"#controls",
        onChange: function(i){
          if($active < 0) return;
          $('#content_center .col-image .project-item[rel="'+$active+'"] img')
          // .attr('src', function(){
            // return $items[$active].images[i].replace(/resize=[0-9\/]+/, 'resize='+$(this).width());
          // })
          .one('load', function(){
            $('#content_center').isotope('reLayout');
          });
        }
      });
      
    });
    
  }
  
  // event that shows fullscreen
  function show_fullscreen(e){

    if( $(e.target).hasClass('tag') || $(e.target).hasClass('block-7') || $(e.target).closest('.col').hasClass('block-7') || $(e.target).hasClass('block-8') || $(e.target).closest('.col').hasClass('block-8') ){
      return;
    }
    
    $active = (
      $(this).is('li') ?
        $(this).attr('rel').toInt()
      :
        $('.project-item', $(this).closest('.col')[0]).attr('rel').toInt()
    );
    
    var 
      o = $items[$active];

    e.preventDefault();
    start_loading();

    var startAt = 
      $.map(o.images, function(val, key){
        return val.regex(/file=([^&]*)/)[1];
      }).indexOf($('.project-item img', $(this).closest('.col')[0]).attr('src').regex(/file=([^&]*)/)[1]);
    
    $.mbBgndGallery.changeGallery($('#fullscreen-window')[0], o.images, 0, function(){
      stop_loading();
    });
    
    $('body').addClass('fullscreen');
    $('#controls').removeClass('single').hide();
    if(o.images.length < 2){
      $('#controls').addClass('single');
    }
    $('#fullscreen-content .text').html(
      '<h3>'+o.title+'</h3>'+
      '<h4>'+o.subtitle+'</h4>'+
      '<div class="description">'+o.text+'</div>'+
      '<div class="tags">'+$.map(o.tags, function(v, i){return (i > 999 ? '' : '<span class="tag disabled">'+ v +'</span>')}).join('')+'</div>'
    );
    
    $('#fullscreen-window').fadeIn(500, function(){
      $('#fullscreen-content, #controls:not(.single), .text', $('#fullscreen-window')[0]).fadeIn(200);
    }).data('toggle', 0);
    
  }
  
  // event that hides fullscreen
  function hide_fullscreen(e){
    
    if(e!=undefined) e.preventDefault();
    
    $('#logo').filter(':hidden').fadeIn(500);
    
    $('#fullscreen-window').fadeOut(500, function(){
    
      $('#fullscreen-content').hide();
      $('#fullscreen-window .text').removeAttr('style');
      $('body').removeClass('fullscreen');
      
    });
    
  }
  
  // initiate
  return function(items, twitter){
    
    $items = items;
    $twitter = twitter;
    
    $(function(){
      
      bind_events();
      place_items();
      place_twitter(3);
      filter_items();
      
      $('#hit-area').disableSelection();
      
    });
    
  }

})($);
