/**
 * Namespaced object. Encapsulating private methods, exposing these 
 * as public via an object proxy. 
 *
 * @author 		Zone
 * @email		info@zonecontent.com
 * @url 		http://www.zonecontent.com/
 * @copyright 	Copyright (c) 2011, zonecontent.com. All rights reserved.
 * @version		2.0.1
 */

var relentless = window.relentless = function($) {
	
  /* Homepage - Carousel */
  var carouselTimer;

  function initCarousel() {
    createCarouselPositionList();
    carouselTimer = setInterval('window.relentless.scrollCarousel()', 10000);
  }
	
  function createCarouselPositionList() {
    var positionList = '<div class="position-wrapper"><ul class="position">';
    $('div.carousel ul.info').children('li').each(function() {
      var index = $(this).parent().children('li').index($(this)) + 1;
      positionList += '<li><span class="button"><span>' + index + '</span></span></li>'
    });
    positionList += '</ul></div>'
    $('div.carousel ul.info').after(positionList);
    $('div.carousel ul.position li:first-child').addClass('active');
    $('div.carousel ul.position li').bind('click', changeCarouselPosition);
  }
	
  function displayBackground(index) {
    var selector = $('#page ul.backgrounds').children('li').eq(index);
    if ($(selector).children('img').length == 0) {
      var url = $(selector).children('span.src').text();
      var alt = $(selector).children('span.alt').text();
      $(selector).children('span').remove();
      $(selector).html('<img src="' + url + '" alt="' + alt +'" />');
      $('div.carousel ul.position li').unbind('click', changeCarouselPosition);
      $(selector).children('img').load(function() {
        $('#page ul.backgrounds').children('li').fadeOut(0).removeClass('active');
        $(selector).fadeIn(1000).addClass('active');
        displayCarouselDetails(index);
      });
    } else {
      $('#page ul.backgrounds').children('li').fadeOut(0).removeClass('active');
      $(selector).fadeIn(1000).addClass('active');
      displayCarouselDetails(index);
    }
  }
	
  function displayCarouselDetails(index) {
    $('div.carousel ul.info').children('li').removeClass('active');
    $('div.carousel ul.info').children('li').eq(index).addClass('active');
    $('div.carousel ul.position li').bind('click', changeCarouselPosition);
    carouselTimer = setInterval('window.relentless.scrollCarousel()', 10000);
  }
	
  function changeCarouselPosition() {
    if (!$(this).hasClass('active')) {
      clearInterval(carouselTimer);
      var index = $(this).parent().children('li').index($(this));
      $(this).siblings().removeClass('active');
      $(this).addClass('active');
      redraw($(this).parent().find('span'));
      displayBackground(index);
    }
  }
	
  function scrollCarousel() {
    if ($('div.carousel ul.position li.active').next().length === 0) {
      $('div.carousel ul.position li:first').click();
    } else {
      $('div.carousel ul.position li.active').next().click()
    }
  }
	
	
  /* Homepage - Filter */
  function initFilter() {
    $('#content div.filter').addClass('filter-java');
		
    reduceKeywordListLength(12);
		
    htmlSnippets = getHTMLSnippets();
    $('#content div.filter div.content-type').append($(htmlSnippets).find('p.order-by'));
		
    $('#content div.filter div.keyword ul li a').click(function() {
      filterThis($(this));
      return false;
    });
		
    $('#content div.filter div.keyword select').change(function() {
      filterThis($(this));
      return false;
    });
		
    $('#content div.filter div.content-type ul li a').click(function() {
      filterThis($(this));
      return false;
    });
		
    $('#content div.filter div.content-type p.order-by a').click(function() {
      filterThis($(this));
      return false;
    });
		
    $('#content div.filter div.pagination ul li:not(.active) > a:not(.disabled)').click(function() {
      filterThis($(this), $(this).attr('rel'));
      return false;
    });
  }
	
  function reduceKeywordListLength(count) {
    if ($('#content div.filter div.keyword ul li:not(.all)').length > count) {
      var select = $('<select>').append($('<option>').text('More...'));
      $('#content div.filter div.keyword ul li:gt(' + count + ')').each(function(){
        var item = $(this);				
        var link = item.find('a');
        item.remove();
        $('<option>').attr('rel', link.attr('rel')).text(link.text()).appendTo(select);
      });
      select.appendTo($('<li>').appendTo($('#content div.filter div.keyword ul')));
    }
  }
	
  function filterThis(option, page) {
    if (option.parents('div.pagination').length == 0) {
      if (option.parent().hasClass('order-by')) {
        option.siblings().removeClass('active');
        option.addClass('active');
      } else {
        option.parent().removeClass('active')
        .siblings().removeClass('active')
        .children('select').attr('selectedIndex', 0);
        if (option.is('select') && !option.children('option:selected').attr('rel')) {
          $('#content div.filter div.keyword ul li.all').addClass('active');
        } else {
          option.parent().addClass('active');
        }
      }
    }
		
    var keyword = $('#content div.filter div.keyword ul li.active a').attr('rel');
    if (keyword == undefined && !($('#content div.filter div.keyword ul li.active').hasClass('all'))) {
      keyword = $('#content div.filter div.keyword select option:selected').attr('rel');
    }
    var contentType = $('#content div.filter div.content-type ul li.active a').attr('rel');
    var orderBy = $('#content div.filter div.content-type p.order-by a.active').attr('rel');
    updateFilter(keyword, contentType, orderBy, page);
  }
	
  function updateFilter(keyword, contentType, orderBy, page) {
    htmlSnippets = getHTMLSnippets();
    var listItem = $(htmlSnippets).find('li.filter-item');
    var processingOverlay = $(htmlSnippets).find('div.processing');
    $('#content div.filter div.results').before(processingOverlay);
    $.ajax({
      url: '/articles/json',
      data: {
        url: location.pathname, 
        keyword: keyword, 
        contentType: contentType, 
        orderBy: orderBy, 
        page: page
      },
      dataType: 'json',
      success: function(data) {
        $('#content div.filter div.processing').remove();
        $('#content div.filter-java div.results ul.posts li').remove();
        $(data.articles).each(function(i, item) {
          var item = data.articles[i];
          var newListItem = listItem.clone();
          $('a', newListItem).attr('href', item.url);
          if (item.image) {
            $('a img', newListItem).attr('src', item.image.src).attr('alt', item.image.alt);
          }		 
          $('a span.info', newListItem).html(item.title + '<span>' + item.description + '</span>');
					
          $('#content div.filter-java div.results ul.posts').append(newListItem);
        });
        var page = data.page;
        var pagesize = data.pagesize;
        var total = data.total;
        var url = data.url;
        updatePagination(page, pagesize, total, url);
      },
      error: ajaxFailure
    });
  }
	
  function updatePagination(page, pagesize, total, url) {
    var pages = (((total % pagesize) > 0)) ? Math.ceil(total / pagesize) : Math.floor(total / pagesize);
		
    var pagesList = $('#content div.pagination ul li ul.pages');
    $(pagesList).children('li').remove();
    for (var i = 1; i <= pages; i++) {
      var add = false;
			
      if (i == 1 || i == pages) {
        add = true;
      } else {
        if (i >= (page - 2) && i <= (page + 2)) {
          add = true;
        }
      }
			
      if (add) {
        var label = (i < 10) ? '0' + i : i;
        var pagesListItem = '<li><a href="' + url + '?p=' + i + '" rel="' + i + '">' + label + '</a></li>'
        $(pagesList).append(pagesListItem);
      }
			
      if (i == page) {
        $(pagesList).children('li:last').addClass('active');
      }
    }
		
    $(pagesList).children('li').each(function() {
      var previousRel = $(this).prev().children('a').attr('rel');
      var thisRel = $(this).children('a').attr('rel');
      if (previousRel != undefined) {
        if (previousRel != (thisRel - 1)) {
          $(this).before('<li>...</li>');
        }
      }
    });
		
    $('#content div.filter div.pagination ul li a').click(function() {
      return false;
    });
		
    if (page == 1) {
      $('#content div.filter div.pagination ul li a.first, #content div.filter div.pagination ul li a.previous').addClass('disabled');
      $('#content div.filter div.pagination ul li a.first, #content div.filter div.pagination ul li a.previous').removeAttr('href');
      $('#content div.filter div.pagination ul li a.first, #content div.filter div.pagination ul li a.previous').removeAttr('rel');
    } else {
      $('#content div.filter div.pagination ul li a.first, #content div.filter div.pagination ul li a.previous').removeClass('disabled');
      $('#content div.filter div.pagination ul li a.first').attr('href', url + '?p=' + 1).attr('rel', 1);
      $('#content div.filter div.pagination ul li a.previous').attr('href', url + '?p=' + (page - 1)).attr('rel', (page - 1));
    }
		
    if (page == pages) {
      $('#content div.filter div.pagination ul li a.last, #content div.filter div.pagination ul li a.next').addClass('disabled');
      $('#content div.filter div.pagination ul li a.last, #content div.filter div.pagination ul li a.next').removeAttr('href');
      $('#content div.filter div.pagination ul li a.last, #content div.filter div.pagination ul li a.next').removeAttr('rel');
    } else {
      $('#content div.filter div.pagination ul li a.last, #content div.filter div.pagination ul li a.next').removeClass('disabled');
      $('#content div.filter div.pagination ul li a.last').attr('href', url + '?p=' + pages).attr('rel', pages);
      $('#content div.filter div.pagination ul li a.next').attr('href', url + '?p=' + (page + 1)).attr('rel', (page + 1));
    }
		
    $('#content div.filter div.pagination ul li:not(.active) > a:not(.disabled)').click(function() {
      filterThis($(this), $(this).attr('rel'));
      return false;
    });
  }
	
	
  /* Gallery - Main */
  function initGalleryMain(id) {
    var gallery = $('#' + id);
    htmlSnippets = getHTMLSnippets();
    var code = $(htmlSnippets).find('div.gallery-container');
    var list = gallery.children('ul');
		
    gallery.children('ul').remove();
    gallery.children('div.head').after(code);
    gallery.find('span.button-left').after(list);
		
    galleryUpdate(gallery, gallery.find('ul').children('li:first-child'));
		
    gallery.find('ul').children('li').click(function() {
      galleryUpdate($(this).parents('div.gallery-main'), $(this));
      return false;
    });
		
    gallery.find('span.button').bind('click', galleryScroll);
		
    if (gallery.find('ul').children('li').length < 6) {
      gallery.find('span.button').remove();
    }
  }
	
  function galleryUpdate(gallery, li) {
    if (!$(li).hasClass('active')) {
      $(li).siblings('li').removeClass('active');
      $(li).addClass('active');
      var src = $(li).children('a').attr('href');
      var alt = $(li).children('a').children('img').attr('alt');
      var mainImage = $(gallery).children('div.gallery-container').children('img');
      $(mainImage).attr('src', src);
      $(mainImage).attr('alt', alt);
    }
  }
	
  function galleryScroll() {
    $(this).parent().children('span.button').unbind('click', galleryScroll);
    var gallery = $(this).parents('div.gallery-main, div.gallery-remote');
    var list = $(gallery).find('ul');
		
    if ($(this).hasClass('button-left')) {
      var width = $('li:last img', list).width();
      $('li:last', list).prependTo(list);
      $(list).animate({
        left: '-=' + (width + 10)
      }, 0, function() {
        });
      $(list).animate({
        left: '+=' + (width + 10)
      }, 500, function() {
        $(this).parent().children('span.button').bind('click', galleryScroll);
      });
    } else {
      var width = $('li:first img', list).width();
      $(list).animate({
        left: '-=' + (width + 10)
      }, 500, function() {
        $('li:first', list).appendTo(list);
        $(list).animate({
          left: '+=' + (width + 10)
        }, 0, function() {
          $(this).parent().children('span.button').bind('click', galleryScroll);
        });
      });
    }
  }
	
	
	/* Gallery - Remote */
	function initGalleryRemote(id, params) {
		var gallery = $('#' + id);
		htmlSnippets = getHTMLSnippets();
		var code = $(htmlSnippets).find('div.window-remote');
		gallery.children('div.head').after(code);
		populateRemoteImages(gallery, params);
	}
	
	function populateRemoteImages(gallery, params) {
		var list = $(gallery).find('ul');
		$.ajax({
			url: '/services/gallery/flickr/json',
			data: params,
			dataType: 'json',
			success: function(data) {
				$(data.data).each(function(i, image) {
					var li = '<li><a href="' + image.ImageUrl + '"><img src="' + image.ThumbUrl + '" alt="' + image.Caption + '" /></a></li>';
					$(list).append(li);
				});
				$(gallery).show();
				$(gallery).find('span.button').bind('click', galleryScroll);
			},
			error: ajaxFailure
		});
	}


  return {
		
    'initCarousel': function() {
      initCarousel();
    },
    'initFilter': function() {
      initFilter();
    },
    		
    'initGalleryMain': initGalleryMain,
    'initGalleryRemote': initGalleryRemote,
    'scrollCarousel': scrollCarousel

  };

} (jQuery);
