var DS = {
  version: 1.0,
  author: "craigtmackenzie"
};

Array.prototype.unique = function () {
	var r = new Array();
	o:for(var i = 0, n = this.length; i < n; i++)
	{
		for(var x = 0, y = r.length; x < y; x++)
		{
			if(r[x]==this[i])
			{
				continue o;
			}
		}
		r[r.length] = this[i];
	}
	return r;
}

DS.Interface = {};
DS.Interface.WorkFilter = {
  View: {
    fadeInItem: function() {
        $('.work-grid').hide().removeClass('hide-visibility').fadeIn(1500);
    },
    bindItemHover: function() {
      $('.work-item').hover(
        function() {
            if ( $(this).find('.content').length ) {
                $(this).stop();
                $(this).animate({backgroundColor: 'black'}, 200);
            }
        },
        function() {
            $(this).stop();
            $(this).animate({backgroundColor: '#EFEFEF'}, 150, function() {
                //$(this).css('backgroundColor', 'transparent');
            });
        }
      );
    },
    createNavigationLinks: function() {
      var tags = [];
      $('.work-grid .work-item .content').each(function() {
        var item_tags = $(this).attr("rel").split(",");
        for (var i = item_tags.length - 1; i >= 0; i--){
          tags.push(item_tags[i]);
        }
      });

      // Alphabeta sort tags
      tags = tags.unique();
      tags.sort();

      for ( i = 0; i < tags.length; i++ ) {
          if ( tags[i] )
            $('<li><a rel="'+tags[i]+'" href="#">'+tags[i]+'</a></li>').appendTo($('#work-filter'));
      }
    },
    bindNavigationLinks: function() {
      $("#work-filter li a").each(function(i,link){
        $(link).bind("click.filter", function(e){
          e.preventDefault();
          $("#work-filter li a").removeClass('active-filter');
          $(this).addClass('active-filter');
          DS.Interface.WorkFilter.Control.filterGrid(link);
        })
      })
    },
    
    bindAllLink: function() {
      $("#work-filter li a[rel=all]").unbind(".filter").bind("click", function(e){
        e.preventDefault();
        $("#work-filter li a").removeClass('active-filter');
        $(this).addClass('active-filter');
        DS.Interface.WorkFilter.Control.resetGrid();
      })
      
    },
    
    reorderItemsBasedOn: function(items) {
      wraps = $(".work-item");
      $(wraps).each(function(i,wrap){
        if ($(wrap).children().length == 0){
          $(wrap).append(items[i])
        }
      })
    },
    
    hideEverythingBut: function(items) {
      ordered = DS.Interface.WorkFilter.Control.sortItems($(".work-item .content").not(items))
      ordered.each(function(i,item){
        $(item).fadeTo(600, 0, function(){
          $(item).appendTo(".dead-sea")
        });
      });      
    },
    
    revealTaggedItems: function(items) {
      $(items).each(function(i,item){
        $(item).fadeTo(600, 1);
      })
    },
    
    createDeadSea: function() {
      $(".work-grid").append("<div class='dead-sea'></div>");
    },
    
    reorderAndRevealItems: function(items) {
      setTimeout(function(){
        DS.Interface.WorkFilter.View.reorderItemsBasedOn(items);
      }, 800);
      
      
      setTimeout(function(){
        DS.Interface.WorkFilter.View.revealTaggedItems(items);
      }, 850);
    }
  },
  
  Control: {
    filterGrid: function(link) {
      items = DS.Interface.WorkFilter.Control.findItemsWithTag($(link).attr("rel"));
      DS.Interface.WorkFilter.View.hideEverythingBut(items);
      DS.Interface.WorkFilter.View.reorderAndRevealItems(items);
    },
    
    resetGrid: function() {
      items = this.sortItems($(".work-grid .content"));
      
      items.each(function(i,item){
        $(item).fadeTo(600, 0, function(){
          $(item).appendTo(".dead-sea")
        });
      });
      
      setTimeout(function(){
        DS.Interface.WorkFilter.View.reorderItemsBasedOn(items);
      }, 800);
      
      
      setTimeout(function(){
        DS.Interface.WorkFilter.View.revealTaggedItems(items);
      }, 850);
      
    },
    
    findItemsWithTag: function(tag) {
      items = [];
      $(".work-grid .content").each(function(i,item){
        if (DS.Interface.WorkFilter.Control.checkItemForTag(item, tag)) items.push(item);
      })
      return items;
    },
    
    checkItemForTag: function(item, tag) {
      tags = $(item).attr("rel").split(",");
      for (var i = tags.length - 1; i >= 0; i--){
        if (tags[i] == tag) return true;
      };
      return false
    },
    
    setItemsOriginalPosition: function() {
      $(".work-grid .content").each(function(i,item){
        $(item).data("position", i);
      })
    },
    
    sortItems: function(items) {
      return items.sort(this.sortFunction);
    },
    
    sortFunction: function(a,b) {
      a = parseInt($(a).data("position"));
      b = parseInt($(b).data("position"));
      if (a==b) return 0;
      return ((a < b) ? -1 : 1);
    }
  },
  
  init: function (){
    this.Control.setItemsOriginalPosition();
    this.View.createNavigationLinks();
    this.View.bindNavigationLinks();
    this.View.bindAllLink();
    this.View.createDeadSea();
    this.View.bindItemHover();
    this.View.fadeInItem();
  }
}

DS.Interface.RelatedToolTip = {
  View: {    
    findAndBindRelatedLinks: function() {
      $(".related a").each(function(i,link){
          $(link).data('title', $(link).attr('title')).removeAttr('title');
        $(link).hover(function(e){
          e.preventDefault();
          DS.Interface.RelatedToolTip.View.createToolTip($(link).data("title"),e);
        },
        function(e){
          DS.Interface.RelatedToolTip.View.destroyToolTip();
        })
      })
    },
    
    createToolTip: function(label,e) {
      $("body").append("<p class='tool-tip'>"+label+"</p>")
      $().mousemove(function(e){
         $(".tool-tip").css("top", e.pageY+15).css("left", e.pageX+15);
      });
    },
    
    destroyToolTip: function() {
      $(".tool-tip").remove();
    }
  },
  
  init: function() {
    this.View.findAndBindRelatedLinks();
  }
}

DS.Interface.Slider = {
  View: {
    findAndBindSlider: function() {
      $('.slider .items-wrapper').each(function() {
        var rand_id = Math.round(Math.random() * 10000000);

        $('<a id="p'+rand_id+'" class="prev-feature show-hover" href="#"></a>').css('opacity', 0).appendTo($(this));
        $('<a id="n'+rand_id+'" class="next-feature show-hover" href="#"></a>').css('opacity', 0).appendTo($(this));

        $('.items', this).cycle({
            fx:      'scrollHorz',
            timeout:  0,
            pause: 1,
            prev:    '#p'+rand_id,
            next:    '#n'+rand_id
        });

        $(this).hover(
            function() {
                if ( $(this).find('.item').length > 1 ) {
                    $('.show-hover', this).stop(false, false);
                    $('.show-hover', this).animate({opacity: 1}, 300);
                }
            },
            function() {
                $('.show-hover', this).stop(false, false);
                $('.show-hover', this).animate({opacity: 0}, 600);
            }
        );
      });
    },
    fixBloggingBox: function() {
        $('.latest .blog-post').each(function() {
            // get bg image
            var bg_img = $('.post-img img', this).attr('src');

            $(this).css('background-image', 'url('+bg_img+')');
            $('.post-img', this).css('display', 'none');
            $('.post').css({position: 'relative', 'float': 'right'})
        })
    }
  },
  init: function() {
    DS.Interface.Slider.View.fixBloggingBox();
    DS.Interface.Slider.View.findAndBindSlider();
  }
}

DS.Interface.Slideshow = {
  View: {
    findAndBindSlideshow: function() {
        $('.slideshow').each(function() {
            var parts = $(this).attr('id').split('-');
            var slideID = parts[parts.length-1];
            var slide_count = $(this).find('img').length;

            var $slide_nav = $('#slideshow_nav-'+slideID);

            // prev button
            $slide_nav.append('<a id="slide_prev-'+slideID+'" class="slide_prev" onfocus="this.blur()" href="#prev">Previous</a>');
            // slash
            $slide_nav.append('<span class="slash"> / </span>');
            // next button
            $slide_nav.append('<a id="slide_next-'+slideID+'" class="slide_next" onfocus="this.blur()" href="#next">Next</a>');
            // text image
            $slide_nav.append('<span> image</span>');
            // slide current / slide total
            $slide_nav.append(' (<span class="slide_current">1</span> <span class="slash"> of </span> <span class="slide_total">'+slide_count+'</span>)');

            $(this).cycle({
                fx:      'fade',
                timeout:  0,
                prev:    '#slide_prev-'+slideID,
                next:    '#slide_next-'+slideID,
                nav:     '#slideshow_nav-'+slideID,
                prevNextClick:  function(isNext, zeroBasedSlideIndex, slideElement) {
                    $('.slide_current', $slide_nav).html(zeroBasedSlideIndex + 1);
                }
            });
        });
    }
  },
  init: function() {
    this.View.findAndBindSlideshow();
  }
}

DS.App = {
  init: function() {
   DS.Interface.WorkFilter.init();
   DS.Interface.RelatedToolTip.init();
   DS.Interface.Slider.init();
   DS.Interface.Slideshow.init();
  }
};

$(document).ready(function(){
  $("body").addClass("js")
  DS.App.init();
});
