theModelCarousel = null;
PropertyImages = {
  gallery : [],
  index : 0,

  init : function(obj, state) {
    theModelCarousel = obj;
    PropertyImages.buildGallery();
    if (PropertyImages.gallery.length > 0) {
      PropertyImages.showPhoto(0);
    } else {
      PropertyImages.showNoPhoto();
    }
  },
  
  buildGallery : function() {
    PropertyImages.gallery = jQuery("#listing-photo-carousel > li > a > img");
  },

  setClickCbOnItem : function(obj, state) {
    jQuery("#listing-photo-carousel > li > a").click(function(ev) {
      ev.preventDefault();
      PropertyImages.showPhoto(parseInt(jQuery(this).attr('jcIndex')));
    });
  },

  showPhoto : function(index) {
    jQuery("#listing-photo-img").attr('src', this.gallery[index].src);
    jQuery("#listing-photo-caption").text(this.gallery[index].alt);
  },

  showNoPhoto : function() {
    jQuery("#listing-photo-caption").text("No photo available");
  }
}

jQuery(document).ready(function() {
  addJCarousel();
  jQuery("ul.gallery li").showGallery();
});
function addJCarousel(){
  theModelCarousel = jQuery('#listing-photo-carousel').jcarousel({
    scroll: 1,
    visible: 2,
    easing: "linear",
    initCallback: PropertyImages.init,
    itemLoadCallback: PropertyImages.setClickCbOnItem
  });
}
jQuery.fn.showGallery = function() {
  return this.each(function() {
    jQuery(this).click(function(){
      var _li = jQuery(this);
      if (_li.attr('class') != 'active'){
        var _id = _li.attr('rel'); // get gallery_id
        _li.find('.loading').removeClass('hidden'); //Show loading
        jQuery.ajax({
          type: "POST",
          url: "/galleries/jcarousel_show/" + _id,
          success: function(data){
            jQuery('.gallery_show').html(data);
            jQuery('ul.gallery li .loading').addClass('hidden'); // hidden loading
            _li.parent().find('li').removeClass("active"); // Remove current active li
            _li.addClass('active'); // set as active
            theModelCarousel = null;
            addJCarousel();
          }
         });
        }
      return false;
    });
  });
}
