
trb = {};
trb.ui = {};

trb.api = {};
trb.api.reactions = {};
trb.api.elements = {};

heap.api.setup({
  object: trb.api.reactions,
  api_class:'reactions',
  url: heap.urlmap.trb_api_json,
  methods: ['create']
});

heap.api.setup({
  object: trb.api.elements,
  api_class:'trbapi',
  url: heap.urlmap.trb_api_json,
  methods: ['renderComment', 'getAtomsList']
});

/**
* post comment
**/
trb.postComment = function()
{
	params = new Object;
  params['meta_user_name'] = $('#i_meta_user_name').val();
  params['meta_user_email'] = $('#i_meta_user_email').val();
  params['atom_id'] = $('#i_atom_id').val();
  params['title'] = $('#i_meta_user_email').val()+' : '+$('#i_atom_title').val();
  params['body'] = $('#i_body').val();
  params['user_id'] = $('#i_user_id').val();
  params['type'] = 'comment';
  
  $('#form_comment .error_panel p').hide();
  $('#form_comment .error_panel').hide();

  trb.api.reactions.create(trb.api.reactions.createCallback, params);  
  
  return false;
};

/**
* post comment callback
**/
trb.api.reactions.createCallback = function(response)
{
  // comment added successfully
	if(response.type == heap.SUCCESS)
	{
    var params = {
        _time_created: response.data._time_created,
        body: response.data.body,
        meta_user_name: response.data._meta.user_name,
        meta_user_email: response.data._meta.user_email
      };
    
    // render then append new comment elem
    trb.api.elements.renderComment(function(renderObject){ 
      
      $('#comments_container').prepend(renderObject.data.html);
      $('#comments_container .comment').removeClass('first');
      $('#comments_container .comment').eq(0).addClass('first new');
      $('#comments_container .comment').eq(0).animate({ backgroundColor: "#FCFBF7" }, 2500);
      
      var curr_atom = response.data._atom[0];
      
      // update all other comments counters
      $('.count_update_'+curr_atom._slug).each(function (i){
        var new_value = (parseInt($(this).text())+1);
        $(this).html(new_value);
        Cufon.refresh();
      });

      $('#form_comment').hide();
      trb.ui.setLinesHeight('#blog_post_container', '#blog_post_container .line', -2);
      window.location.href = '#view-comments';
    }, params);

    $('#form_comment .success').show();
	}
  // comment did not pass validation
	else
	{
    $('#form_comment .error_panel').show();
    $('#form_comment .success').hide();
    
	  for (var i in response.data) {
      $('#e_'+response.data[i]).fadeIn();
	  }
	}
	trb.ui.setLinesHeight('#blog_post_container', '#blog_post_container .line', -2);
	return false;
};


/**
* ui init / events binding
**/
trb.init = function()
{
  // cufon
  Cufon.replace('#header ul li a', { fontFamily: 'Museo Sans 500', hover: true});
  Cufon.replace('.fontr', { fontFamily: 'Museo 300' });
  //Cufon.replace('.fontrh', { fontFamily: 'Vegur' });
  Cufon.replace('.fontrh', { fontFamily: 'lanenarrow' });
  $('#sub_header form').css({zoom: 1});
  
  // show comment form
  $('#btn_leave_comment').bind('click', function(){
    $(this).hide();
    $('#form_comment').fadeIn();
    trb.ui.setLinesHeight('#blog_post_container', '#blog_post_container .line', -2);
    return false;
  });
  
  // add comment feature
  $('#form_comment').bind('submit', function(){
    trb.postComment();
    return false;
  });
  
  // project listing fade
  trb.ui.fadeOpacity('.opacitable');
  trb.ui.setBackgroundPosition('#blog .side #inner_container', '#blog_body #global_wrap #content');
  
  // project listing pagination
  $('ul.pagination li a').live('click', trb.ui.pagination);
  $('#sub_header .filters a.pager_link').live('click', trb.ui.pagination);
  $('#sub_header .filters a.filter_link').bind('click', trb.ui.openFiltersPanel);
  $('#sub_header .tags_list .col .inner ul li a').bind('click', trb.ui.filterResults);
    
  // homepage twitter listing
  trb.ui.setLinesHeight('#ilast_entries', '#ilast_entries .line', 100);

  trb.ui.feedTabInit();

  $("#ilast_entries .inner .filters li").each(function()
  {
    $(this).bind('click', trb.ui.feedTabClick);
  });

  //$('.last_entries .filters a').bind('click', trb.ui.filterNewsEntries);
  //$('.last_entries .filters a.hidden').css({opacity: 0.6});
	
	$('#project .side .medias ul li .row').hover(
	  function () {
			$(this).dequeue().stop().animate({paddingLeft: "5px"}, 200, function(){});
	  }, 
	  function () {
			$(this).animate({paddingLeft: "0px"}, 100, function(){});
	  }
	);
  
  // project page : media selector 
  $('.project_doc').bind('click', function(){
    var target = $(this).attr('rel');
    $('.project_img_container').hide();
    $(target).fadeIn();
   
    $('.medias ul li').removeClass('selected');
    $(this).closest('.medias ul li').addClass('selected');    
    return false;
  });
  
  // search form
	$('#form_search input').bind('focus', function(){
    if($(this).val() == heap.labels['default']['header_search'] )
      $(this).val('');
  }).bind('blur', function(){
    if($(this).val().length < 1)
      $(this).val(heap.labels['default']['header_search']);
  });
	
};


/**
* ui update
**/

trb.ui.setLinesHeight = function(reference, target, adjust, animate)
{
  var container_height = $(reference).outerHeight() + adjust;

  if(animate > 0)
  $(target).animate({ 'height':container_height}, animate);
  else
  $(target).css('height', container_height);

  return false;
};

/**
* ui update
**/
trb.ui.setBackgroundPosition = function(reference, target)
{
  var container_height = $(reference).height();
  $(target).css('background-position', 'center '+container_height+'px');
  return false;
};

/**
* ui update
**/
trb.ui.fadeOpacity = function(selector)
{
  $(selector).each(function(){
    $(this).css('opacity', parseInt($(this).attr('id').substr(2)) / 100);
  });
};

/**
* ui update
**/
trb.ui.openFiltersPanel = function()
{
  trb.ui.openFiltersPanelHandler($(this));
  return false;
};

trb.ui.openFiltersPanelHandler = function(obj)
{
  var target = obj.attr('rel');
  var params_hide = { height: "0px", opacity: 0 };
  var params_show = { height: "100%", opacity: 1 };
  
  if(!obj.hasClass('hidden'))
  {
    obj.addClass('hidden');
    $(target).animate(params_hide, 300, function() {
      $(this).hide();
    });
  }
  else
  {
    obj.removeClass('hidden');
    //alert($('#tags_list_container .col .inner').eq(0).height());
    $(target).animate(params_show, 300, function() {
      $(this).css({display: 'block'});
    });
  }  
  return false;

};


/**
* ui update
**/

trb.ui.feedTabInit = function()
{
  trb.ui.feedHideTabs();
  trb.ui.feedTabControl($(".filters li:first"), true);

  $("#ilast_entries .inner .filters li").each(function()
  {
    $(this).bind('click', trb.ui.feedTabClick);
  });

  setTimeout("trb.ui.feedTabSetHeight();", 400);
}

trb.ui.feedTabClick = function(e)
{
  trb.ui.feedHideTabs();
  trb.ui.feedTabControl($(this), true);
  return false;
};

trb.ui.feedTabSetHeight = function()
{
  trb.ui.setLinesHeight('#ilast_entries', '#ilast_entries .line', 10);
}

trb.ui.feedHideTabs = function()
{
  $(".feed").each(function() 
  {
     $(this).slideUp(150);
  });

  $(".filters li").each(function()
  {
    trb.ui.feedTabControl($(this), false);
  });
}
 
trb.ui.feedTabControl = function(tab, on)
{
  var selector = tab.find('a').attr('id');

  var params_hide = { 
        height: "0px",
        paddingBottom: "0",
        paddingTop: "0",
        opacity: 0
      };
  var params_show = { 
        height: "100%",
        paddingBottom: "10px",
        paddingTop: "14px",
        opacity: 1
      };
    
  if(!tab.hasClass('hidden') && !on)
  {
    tab.addClass('hidden');
    tab.css({opacity: 0.6});
  }
  else if(on == true)
  {
    tab.removeClass('hidden');
    tab.css({opacity: 1});

    var div_selector = tab.find('a').attr('href');
    $(div_selector).slideDown(150);
  }

  setTimeout("trb.ui.feedTabSetHeight();", 160);

  return false;
};

/**
* filter projects listing
**/
trb.ui.filterResults = function()
{
  trb.ui.filterResultsHandler($(this));
  return false;
}

trb.ui.filterResultsHandler = function(obj)
{
  obj.toggleClass('selected');
  
	$('#sub_header .filters a.pager_link').removeClass('selected');
	$('#sub_header .filters a.pager_link').eq(0).trigger('click');
  return false;
}
/**
* pagination projects listing
**/
trb.ui.pagination = function()
{  
  var cb_getAtomsList = function(response)
  {
    //console.log('focus_elem='+focus_elem+' focus_pager='+focus_pager);
    $(focus_elem+'_loader').hide();
    $(focus_pager+'_pagination_container').html(response.data.pager_html);
    $(focus_elem+'_listing').html(response.data.html);
    $(focus_elem+'_listing').fadeIn();
    
    trb.ui.fadeOpacity('.opacitable');
  };
 
  if(!$(this).hasClass('selected'))
  {
    var focus_elem = $(this).attr('href'); 
    focus_elem = focus_elem.substr(focus_elem.indexOf('#'));
    
    var focus_params = focus_elem.substring(1);
    var focus_pager = '.'+focus_elem.substring(1);
    var focus_params_sp = eval(focus_params+'_sp');
    var focus_params_so = eval(focus_params+'_so');

    $(focus_elem+'_loader').show();
    $(focus_elem+'_listing').fadeOut();
    if($(this).closest("#sub_header").length)
      $('#sub_header .filters a').removeClass('selected');      
    $(this).addClass('selected');
    
		// search options
    var page_param = ($(this).attr('rel')) ? $(this).attr('rel') : 1;
    var sort_param = $('#sub_header .filters a.selected').attr('title') ? $('#sub_header .filters a.selected').attr('title') : 'publish_start';    
    focus_params_so.sort = sort_param;

    if(sort_param == 'title')
      focus_params_so.sortOrder = 'ASC';
    else
      focus_params_so.sortOrder = 'DESC';
    
		// search parmas
		focus_params_sp.tags = [];
		$('#tags_list_container a.selected').each(function(i, val) {
			//console.log(i+' - '+val.toSource()+' // '+$(this).attr('id')+ ' // '+$(this).attr('id').replace(/-/, "."));
			focus_params_sp.tags.push($(this).attr('id').replace(/-/, "."));
		});
		
		
    var focus_params_se = { template: 'ui/projects_listing.html', paged: true, focus: focus_elem, object_type: 'pagination' };
    focus_params_so.page = page_param;
    
    params = { searchParams: focus_params_sp, searchOptions: focus_params_so, searchExtras: focus_params_se};   
    trb.api.elements.getAtomsList(cb_getAtomsList, params);
  }
  return false;
};

/**
* slideshow object
**/

trb.ui.slideshow = function(options)
{
  this.options = (options) ? options : {}; 
  this.initSlideshow();
  return false;
};

trb.ui.slideshow.prototype.initSlideshow  = function()
{ 
  this.container = $(this.options.container);
  this.overlay = $(this.options.overlay);
  this.overlay.css({
      'background-color'	: this.options.overlayColor,
      'opacity'			: this.options.overlayOpacity
    });
  this.params_show = { height : '576px' };
  this.params_hide = { height : '238px' };
  this.state = '';
  
  this.params_carousel = {
    vertical: false, 
    buttonPrevSelector: this.container.find('a.prev'),
    buttonNextSelector: this.container.find('a.next') 
  };
  
  $('.slider ul li a', this.container).bind('click', function(){
    if($(this).is('.selected'))
      return false;
    
    $('.slider ul li a', this.container).removeClass('selected');
    $(this).addClass('selected');
    var index = $('.slider ul li a', this.container).index(this);

    $('#js-page').text($('.slider ul li a', this.container).index(this) + 1);
    
    var target_slide = $(this).attr('href');
    var target_legend = $(this).attr('rel');
    $('.js-slides', this.container).hide();
    $('.js-legends', this.container).hide();
    $(target_slide).fadeIn();
    $(target_legend).fadeIn();
    return false;
  });
  
  $('.mininav a.prev', this.container).bind('click', function(){
    var target_index = 0;
    var elems = $('.slider ul li a', this.container);
    elems.each(function(index){
      if($(this).is('.selected') && (index > 0))
      {
        target_index = index - 1;
        elems.eq(target_index).trigger('click');
        return false;
      }
    });
    //var target = pretarget
    
    //console.log('target_index prev = '+target_index);
    
    return false;
  });
  
  $('.mininav a.next', this.container).bind('click', function(){
    var target_index = 0;
    var elems = $('.slider ul li a', this.container);
    elems.each(function(index){
      if($(this).is('.selected') && (index < (elems.length-1)))
      {
        target_index = index + 1;
        elems.eq(target_index).trigger('click');
        return false;
      }
    });
    //var target = pretarget
    
    //console.log('target_index next = '+target_index);
    
    return false;
  });
  
  return false;
};

trb.ui.slideshow.prototype.isOpen  = function()
{ 
  return (this.state == 'full');
};

trb.ui.slideshow.prototype.closeSlideshow  = function()
{
  var that = this;
  if(that.container.is(':animated')) return false;
  
  that.container.find('.maxinav').hide();
  that.container.find('.legend').css({ left: '-200px' }).hide();
  
  that.container.animate(that.params_hide, 500, function() {
    $(this).removeClass('full');
    that.state = '';
    that.overlay.fadeOut();
    $(this).find('.legend').show().animate({ left: '0px' }, 300, function() {
      that.container.find('.mininav').fadeIn('fast');
    });
    $(this).find('.line').animate({ left: '-592px' }, 300, function() {
    });
  });
  return false;
};

trb.ui.slideshow.prototype.openSlideshow  = function()
{
  var that = this;
  if(that.container.is(':animated')) return false;
  
  that.container.find('.mininav').hide();
  that.container.find('.legend').css({ left: '1000px' }).hide(); //.find('.text').css({ 'float': 'right'});
  that.overlay.show();
      
  that.container.animate(that.params_show, 1000, function() {
    $(this).addClass('full'); 
    that.state = 'full';
    $(this).find('.legend').show().animate({ left: '652px' }, 500, function() {      
      that.container.find('.maxinav').fadeIn('fast');
    });
    $(this).find('.line').animate({ left: '0px' }, 500, function() {
    });
  });
  
  return false;
};

/**
 *
 * --- carousel Object
 *
 */

trb.ui.carousel = function (target, options)
{
  this.params_carousel = {
    scroll: 3, 
    animation: 'slow', 
    vertical: false,
    buttonNextHTML: null,
    buttonPrevHTML: null,
    buttonNextSelector: null,
    buttonPrevSelector: null,
    initCallback: this.initCallback,
    buttonNextCallback: this.buttonNextCallback,
    buttonPrevCallback: this.buttonPrevCallback
  };
  
  jQuery.extend(this.params_carousel, options);    
    
  if(typeof target != 'object')
    target = $(target);
  if( $(target).length == 0)
    return false;
    
  if((this.params_carousel.buttonNextSelector != null) && (typeof this.params_carousel.buttonNextSelector != 'object'))
    this.params_carousel.buttonNextSelector = $(this.params_carousel.buttonNextSelector);
  
  if((this.params_carousel.buttonPrevSelector != null) && (typeof this.params_carousel.buttonPrevSelector != 'object'))
    this.params_carousel.buttonPrevSelector = $(this.params_carousel.buttonPrevSelector);
  
  $(target).jcarousel(this.params_carousel);
  this.carousel = $(target).data('jcarousel');
  return false;
};

trb.ui.carousel.prototype.initCallback = function(carousel)
{
  var that = this; 
  
  if( (that.buttonNextSelector != null) && ($(that.buttonNextSelector).length > 0) )
  {
    $(that.buttonNextSelector).bind('click', function() {
        carousel.next();
        return false;
    });
  }
  if( (that.buttonPrevSelector != null) && ($(that.buttonPrevSelector).length > 0) )
  {
    $(that.buttonPrevSelector).bind('click', function() {
        carousel.prev();
        return false;
    });
  }
};

trb.ui.carousel.prototype.buttonNextCallback = function (carousel) {
  var that = this;
  if (!$.browser.msie) {
    $(that.buttonNextSelector).filter('.jcarousel-next-disabled').css('opacity', 0.5);
    $(that.buttonNextSelector).filter(':not(.jcarousel-next-disabled)').css('opacity', 1);
  }
  else {
    $(that.buttonNextSelector).filter('.jcarousel-next-disabled').css('visibility', 'hidden');
    $(that.buttonNextSelector).filter(':not(.jcarousel-next-disabled)').css('visibility', 'visible');
  }
  return false;
};

trb.ui.carousel.prototype.buttonPrevCallback = function (carousel) {
  var that = this;
  if (!$.browser.msie) {
    var is_disabled = $(that.buttonPrevSelector).filter('.jcarousel-prev-disabled').length;
    $(that.buttonPrevSelector).filter('.jcarousel-prev-disabled').css('opacity', 0.5);
    $(that.buttonPrevSelector).filter(':not(.jcarousel-prev-disabled)').css('opacity', 1);
  }
  else {
    $(that.buttonPrevSelector).filter('.jcarousel-prev-disabled').css('visibility', 'hidden');
    $(that.buttonPrevSelector).filter(':not(.jcarousel-prev-disabled)').css('visibility', 'visible');
  }
  return false;
};





