var Gallery = {
  galleryContainer: '#galleryData',
  tagsContainer: '#tags',
  pagerContainer: '#galleryPager',
  pageSize: 6,
  pageNumber: 1,

  init: function(){
    Gallery.getPictures('All');
    Gallery.getTags();
    Gallery.page();
    Gallery.clickTag();
  },

  getPictures: function(type){
    if(type == 'All'){
      type = '';
    }
    $.ajax({
      type: "POST",
      url: "/services/gallery.asmx/Search",
      data: "{'tag': '" + type + "', 'pageSize':" + Gallery.pageSize + ", 'pageNumber':" + Gallery.pageNumber + ", sortDirection: 'Asc'}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(result) {
        Gallery.setupGallery({
          result: result,
          tag: type
        });
      },
      error: function(xhr, status, error) {
        var err = eval("(" + xhr.responseText + ")");
        alert(err.Message)
      }
    });
  },

  setupGallery: function(options){
    var result = options.result.Results;
    var totalPages = options.result.TotalPageCount;
        
    Gallery.checkPagingStatus(totalPages);
    (options.tag == '') ? tag = 'All' : tag = options.tag;
    $('li', Gallery.galleryContainer).remove();
    
    for(var i=0; i<result.length; i++){      
      var picture = new Picture(result[i]);
      var thumbnail = picture.buildThumbnail();
      $(Gallery.galleryContainer).append(thumbnail);
    }
    
    $('a', Gallery.galleryContainer).lightBox({
      fixedNavigation:true
    });

    var activeOpacity   = 1.0,
        inactiveOpacity = 0.6,
        fadeTime = 350;


    $('img', Gallery.galleryContainer).mouseover(function(){
        $(this).fadeTo(fadeTime, inactiveOpacity);
    })
    $('img', Gallery.galleryContainer).mouseout(function(){
        $(this).fadeTo(fadeTime, activeOpacity);
    })

    $('#name', Gallery.pagerContainer).html(tag);
  },

  getTags: function(){
    $.ajax({
      type: "POST",
      url: "/services/gallery.asmx/GetTags",
      data: "{}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(result) {
        Gallery.showTags(result);
      },
      error: function(xhr, status, error) {
        var err = eval("(" + xhr.responseText + ")");
        alert(err.Message)
      }
    });
  },

  showTags: function(result){
    var lis = '';
    for(var i=0; i<result.length; i++){
      var className = result[i].Tag.toLowerCase().replace(/ /g, '-');
      if(result[i].Tag == ''){
        lis = lis + '<li class="tag-all selected"><a href="#">All</a> (' + result[i].MaxCount +  ')</li>';
      }
      else{
        lis = lis + '<li class="tag-' + className + '"><a href="#">' + result[i].Tag + '</a> (' + result[i].MaxCount +  ')</li>';
      }
    }
    $(Gallery.tagsContainer).append(lis);
  },

  clickTag: function(){
    $(Gallery.tagsContainer).click(function(event){
      var target = $(event.target);
      if($(target).attr('nodeName').toLowerCase() == 'a'){
        $('li.selected', Gallery.tagsContainer).removeClass('selected');
        $(target).parents('li').addClass('selected');
        Gallery.pageNumber = 1;
        Gallery.getPictures($('li.selected a', Gallery.tagsContainer).text());
      }
      return false;
    })
  },

  checkPagingStatus: function(pages){
    if(pages <= 1){
      $('#galleryNext', Gallery.pagerContainer).addClass('disabled');
    }
    else{
      $('#galleryNext', Gallery.pagerContainer).removeClass('disabled');
      $('#galleryPrevious', Gallery.pagerContainer).removeClass('disabled');
    }
    if(pages == Gallery.pageNumber){
      $('#galleryNext', Gallery.pagerContainer).addClass('disabled');

    }
    if(Gallery.pageNumber == 1){
      $('#galleryPrevious', Gallery.pagerContainer).addClass('disabled');
    }
  },
    
  page: function(){
    $('#galleryNext', Gallery.pagerContainer).click(function(){
      if(!$(this).hasClass('disabled')){
        Gallery.pageNumber++;
        Gallery.getPictures($('li.selected a', Gallery.tagsContainer).text());
      }
      return false;
    });
    $('#galleryPrevious', Gallery.pagerContainer).click(function(){
      if(!$(this).hasClass('disabled')){
        Gallery.pageNumber--;
        Gallery.getPictures($('li.selected a', Gallery.tagsContainer).text());
      }
      return false;
    });
  }
}

function Picture(options){
  this.tags = ''; 
  this.tags = options.Tag;
  this.thumbnail = options.Path;
  this.path = options.Path;
}

Picture.prototype = {
  getTags: function(){
    return this.tags;
  },

  setTags: function(tags){
    this.tags = tags.join(',');
  },

  buildThumbnail: function(){
    var thumbnail = this.thumbnail;
    var li = $('<li rel="'+ this.tags +'"></li>');
	var div = $('<div></div>');
    var a = $('<a href="' + this.path +'"></a>');
    var image = new Image();
    $(image).load(function(){
      $(this).fadeIn('slow', function(){
        $(this).show();
      })
    }).attr({
      'src': thumbnail,
      'alt': ''
    });
    var html = $(li).append($(div).append($(a).append(image)));
    return html;
  //return '<li><a href="' + this.path + '"><img src="' + this.thumbnail + '" alt="" /></a></li>'
  }
}
