/**
 * SlideShow Element
 * 
 * @author Javier Melero <jmelero at linkedsc.com.ar>
 * @package cocyar.com
 */

/**
 * SlideShow behavior object
 * 
 * Constructor method
 * @ScrollableId "scrollable-items"
 */
function SlideShow(scrollableId) {
    // seteamos las propiedades
    this.scrollable = $("#" + scrollableId);
    this.items = $(">ul>li", this.scrollable);
    this.obraItems = $(".item>ul>li", this.scrollable);
    this.animationControl = false;
    this.rotateIntervalId = false;

    // inicializamos los elementos
    this.items.each(function(){
        this.cantidad_elementos = 3;
    });
}

/**
 * Definimos las propiedades
 */
SlideShow.prototype.scrollable;
SlideShow.prototype.items;
SlideShow.prototype.obraItems;
SlideShow.prototype.rotateIntervalId;
SlideShow.prototype.activeItemId;
SlideShow.prototype.animationControl;

/**
 * Definimos los métodos
 */
SlideShow.prototype.mouseEnterItem = function(li){
    var height = li.cantidad_elementos * 81;
    var jItem = $(li);
    // escondemos el titulo ...
    jItem.find('div.subtitle_container').slideUp('fast');
    // si tenemos el activo en este grupo, tenemos q corregir el bottom
    if (jItem.find('.active').length > 0) {
//        jItem.css('bottom', '0px');
        jItem.find('ul').stop(true).animate({
            'bottom': '0px'
        }, 'slow');
    }
    // animamos el height del li, asi se ven todos los elementos
    jItem.stop(true).animate({
        'height': height + 'px'
        }, 'slow');
};

SlideShow.prototype.mouseLeaveItem = function(li){
    var jItem = $(li);
    // si tenemos el activo aca, tenemos q volverlo como estaba..
    var item_activo = jItem.find('.active');
    if (item_activo.length > 0) {
        jItem.find('ul').stop(true).animate({'bottom': '-' + item_activo.get(0).desp + 'px'}, 'slow');
    }
    jItem.stop(true).animate({'height': '81px'}, 'slow', function(){
        // volvemos a mostrar el titulo
        jItem.find('.subtitle_container').slideDown('fast');
    });
};

SlideShow.prototype.setActiveItem = function(itemId, animate){
    var item = $("#" + itemId);
    var pos = item.position();
    var active_item = false;
    if (typeof item.desp == 'undefined') {
        item.get(0).desp = item.parent().height() - item.outerHeight() - pos.top;
    }
    // limpiamos si hay alguno activo...    
    if (this.activeItemId != 'undefined') {
        active_item = $("#" + this.activeItemId);
        active_item.removeClass('active');
        // si el item que activo, esta en distinto ul que el desactivo, tengo q acomodar ese ul
        if (active_item.parent().attr('id') != item.parent().attr('id')) {
            // seteamos uno como visible dentro de ese ul que...
            var ul_activo = active_item.parent();
            //ul_activo.animate({'bottom': '0px'}, 'slow');
        }
    }
    item.addClass('active');
    this.activeItemId = item.attr('id');
    if (typeof animate != 'undefined' && animate) {
        item.parent().animate({'bottom': '-' + item.get(0).desp + 'px'}, 'slow');
    }
    // si clickeamos el mismo que esta activo no hacemos nada...
    if (active_item.attr('id') == item.attr('id')) {
        return;
    }
    // nos encargamos del panel central
    $(".description_box>table").html($("#content_" + item.attr('rel')).html());
    $("#image_description span").html($("#link_obra_" + itemId).html());
    $(".image_bg").css('z-index', 1);
    $("#img_obra_" + itemId)
        .css({'z-index': 2, 'opacity': 1}).show();
    $("#img_obra_" + active_item.attr('id'))
        .css('z-index', 3)
        .fadeTo('normal',0);
};

SlideShow.prototype.mouseEnterSlide = function(){
    this.stopAutoRotate();
    return true;
};
SlideShow.prototype.mouseLeaveSlide = function(){
    setTimeout(function(){ slide.startAutoRotate(); }, 2000);
};
SlideShow.prototype.startAutoRotate = function(){
    if (this.rotateIntervalId) {
        this.stopAutoRotate();
    }
    this.rotateIntervalId = setInterval(function(){ slide.advance(); }, 8000);
};

SlideShow.prototype.stopAutoRotate = function(){
    if (this.rotateIntervalId != false) {
        clearInterval(this.rotateIntervalId);
        this.rotateIntervalId = false;
    }
};

SlideShow.prototype.advance = function(){
    if (this.animationControl) {
        return false;
    }
    this.animationControl = true;
    this.setActiveItem(this.next(), true);
    // para evitar que se solapen las llamadas, safe
    setTimeout(function(){ slide.animationControl = false }, 800);
    return false;
};

SlideShow.prototype.back = function(){
    if (this.animationControl) {
        return false;
    }
    this.animationControl = true;
    this.setActiveItem(this.prev(), true);
    // para evitar que se solapen las llamadas, safe
    setTimeout(function(){ slide.animationControl = false }, 800);
    return false;
};

SlideShow.prototype.next = function(){
    var active_item = $("#" + this.activeItemId);
    // si el siguiente está en el mismo ul
    if (active_item.next().size() == 1) {
        return active_item.next().attr('id');
    }
    // sino esta en el siguiente, buscamos el siguiente ul
    var contenedor = active_item.parents('li.item');
    // sino es el ultimo ul
    if (contenedor.next().size() == 1) {
        return contenedor.next().find('>ul li').first().attr('id');
    }
    // sino tenemos un li siguiente, tonces llegamos al final, retornamos el primero
    else {
        return this.obraItems.first().attr('id');
    }
};

SlideShow.prototype.prev = function(){
    var active_item = $("#" + this.activeItemId);
    // si el anterior está en el mismo ul
    if (active_item.prev().size() == 1) {
        return active_item.prev().attr('id');
    }
    // sino, buscamos el anterior ul
    var contenedor = active_item.parents('li.item');
    // sino es el ultimo ul
    if (contenedor.prev().size() == 1) {
        return contenedor.prev().find('ul li').first().attr('id');
    }
    // sino tenemos un li anterior, tonces llegamos al principio, retornamos el ultimo
    else {
        return $("#items-container li.item:last ul li").last().attr('id');
    }
};

SlideShow.prototype.startup = function(){
    // asignamos los eventos
    this.items.mouseenter(function(){ slide.mouseEnterItem(this); });
    this.items.mouseleave(function(){ slide.mouseLeaveItem(this); });
    this.obraItems.click(function(){ slide.setActiveItem(this.id); })
    $(".left", this.scrollable).click(function(){ return slide.back(); });
    $(".right", this.scrollable).click(function(){ return slide.advance(); });
    this.scrollable.mouseenter(function(){ slide.mouseEnterSlide(); });
    this.scrollable.mouseleave(function(){ slide.mouseLeaveSlide(); });
};

/**
 * SlideShow
 */
var slide;

$().ready(function(){
    slide = new SlideShow("scrollable-items");
    slide.startup();
    slide.startAutoRotate();
    setTimeout(function() { 
        slide.setActiveItem($("#items-container li.item ul li").first().attr('id'), true);
        $("#loading_box").fadeOut('fast'); 
    }, 1000);
});

