var PictureListModel = function()
{
    this.name       = null;
    this.mainTitle  = null;
    this.smallTitle = null;
    this.observers  = new Array();
    this.pictures   = new Array();
    this.icons      = new Array();
    this.products   = new Array();
    this.index      = 0;
};

PictureListModel.prototype =
{
    setName: function(name) { this.name = name },
    getName: function()     { return this.name },
    
    setMainTitle: function(url) { this.mainTitle = url  },
    getMainTitle: function()    { return this.mainTitle },
    
    setSmallTitle: function(url) { this.smallTitle = url },
    getSmallTitle: function()    { return this.smallTitle },

    addPicture: function(picture_url, icon_url) {
        this.pictures.push(picture_url);
        this.icons.push(icon_url);
    },
    
    addProduct: function(product_url, picture_url) {
        this.products.push({product_url:product_url, picture_url:picture_url});
    },
    
    getProducts: function()
    {
        return this.products;
    },
    
    setIndex: function(index) {
        if (this.pictures.length > 0) {
            index = index%this.pictures.length
            this.index = index;
            this.fireIndexChanged();
        }
    },
    
    nextIndex: function() {
        this.setIndex(this.index + 1);
        this.fireIndexChanged();
    },
    
    addObserver: function(o) {
        
        for (var i=0 ; i<this.observers.length ; i++)
            if (this.observers[i] == o)
                return;
        
        this.observers.push(o);
    },
    
    fireIndexChanged: function() {
        for (var i=0 ; i<this.observers.length ; i++) {
            this.observers[i].indexChanged(this.index);
        }
    }
};










var TimerModel = function(pictureListModel)
{
    this.observers = new Array();
    this.timer     = null;
    this.model     = pictureListModel;
    this.percent   = 0;
    this.delay     = 5000;
    this.steps     = 100;
};

TimerModel.prototype =
{
    start: function() {
        var o  = this;
        this.timer = setInterval(function () { o.update() }, this.delay/this.steps);
    },
    
    stop: function() {
        if (this.timer != null) {
            clearInterval(this.timer);
            this.timer = null;
        }
    },
    
    setPictureListModel: function(model) {
        this.model   = model;
        this.percent = 0;
    },
    
    update: function() {
        if (this.percent >= 100) {
            this.model.nextIndex();
            this.percent = 0;
        }
        else {
            this.percent += (100/this.steps);
            this.fireTimeChanged();
        }
    },
    
    dropObservers: function() {
        this.observers = new Array();
    },
    
    addObserver: function(o) {
        this.observers.push(o);
    },
    
    fireTimeChanged: function() {
        for (var i=0 ; i<this.observers.length ; i++) {
            this.observers[i].timeChanged(this.percent);
        }
    }
};







var Delegate = {
  create : function( obj, methodName ) {
    var args = new Array();
    if ( arguments.length > 2 ) {
      for( var i=2; i<arguments.length; i++ )
        args.push( arguments[ i ] );
    }
    return function() {
      var a = new Array();
        for( var i=0; i<arguments.length; i++ )
            a.push( arguments[ i ] );
      for( var i=0; i<args.length; i++ )
        a.push( args[ i ] );
        obj[ methodName ].apply( obj, a );
    }
  },
  
  bind: function( fn, props ) {
    return function() {
        for( var i in props )
            fn[ i ] = props[ i ];
      fn.apply( fn );
    }
    /*
    var fn = arguments[ 0 ];
    var args = [];
    for( var i=1; i<arguments.length; i++ )
      args.push( arguments[ i ] );
    return function() {
      fn.apply( fn, args );
    }
  */
  }

/*
  setTimeout( Delegate.bind(
    function() {
alert( this.o );
    }, { o: 'Hello world' }
  ), 500 );
*/  
  
}
var BackgroundView = function(container, model)
{
    this.index     = -1;
    this.model     = model;
    this.container = $(container);
    this.elements  = new Array();
    
    var o = this;
    
    this.model.addObserver(this);
    
    for (var i=0 ; i<this.model.pictures.length ; i++)
    {
        var e = $(document.createElement("img"));
        e.addClass("backgound");
        e.attr("src", this.model.pictures[i]);
        this.elements.push(e);
        this.container.append(e);
    }
    
    this.container.find(".back").click(Delegate.create(this,'open'));//function(){o.open();});
    this.container.find(".label").click(Delegate.create(this,'open'));//function(){o.open();});
};

BackgroundView.prototype =
{
    indexChanged: function(index) {
        if (this.index != index) {
            this.swap(this.index, index);
            this.index = index;
        }
    },
    
    swap: function(from, to) {
        from = (from!=-1) ? this.elements[from] : null;
        to   = this.elements[to];
    
        if (from != null)
            from.css('z-index', 2);
        
        to.css('z-index', 3).fadeIn(500, function() {
            if (from != null) {
                from.css('z-index', 1).hide();
            }
        });
    },
    
    setBackgroundManager: function(manager) {
        this.backgroundManager = manager;
    },
        
    open: function () {
        this.backgroundManager.open(this);
    }
};










var BackgroundManager = function()
{
    this.enabled = true;
    this.delay   = 800;
    this.current = arguments[0];
    
    for (var i=0 ; i<arguments.length ; i++) {
        arguments[i].setBackgroundManager(this);
    }
};

BackgroundManager.prototype =
{
    setTimer:       function(timer)    { this.timer       = timer; },
    setIcons:       function(icons)    { this.icons       = icons; },
    setProducts:    function(products) { this.products    = products; },
    setOpenButton:  function(button)   { this.openButton  = $(button); },
    setCloseButton: function(button)   { this.closeButton = $(button); },
    
    open: function(back) {
        if (!this.enabled) { return false };
        
        this.enabled = false;
        var o        = this;
        var cc       = this.current.container;
        var nc       = back.container;
        var left     = parseInt(nc.css("left"));
        var zindex   = nc.css("z-index");
        
        this.products.hide(function() {
            o.openButton.fadeOut(200);
            $("#title").fadeOut(200, function() {
                $("#title").find("img").attr("src", back.model.getMainTitle());
            });
            $("#icons").fadeOut(200, function(){
                o._moveBackgrounds(back);
            });
        });
    },
    
    _moveBackgrounds: function(background, callback) {
        var o            = this;
        var oldContainer = this.current.container;
        var newContainer = background.container;
        var products     = this.products;
        
        var left         = parseInt(newContainer.css("left"));
        var zindex       = newContainer.css("z-index");
        
        this.timer.stop();
        
        newContainer.animate({left:"0px"}, this.delay, "swing");
        newContainer.find(".label").fadeOut(this.delay);
        newContainer.find(".back").fadeOut(this.delay, function()
        {
            newContainer.css("z-index", 1);
            
            oldContainer.css("left", (left+58)+"px")
            oldContainer.css("z-index", zindex);
            oldContainer.find(".back").show().css("filter","alpha(opacity=70)");
            oldContainer.addClass("closed");
            oldContainer.find(".label").show();
            oldContainer.animate({left:left}, 250, function()
            {
                o.icons.setModel(background.model);
                o.timer.setPictureListModel(background.model);
                o.timer.start();
                
                o.closeButton.find(".ambiance").text(background.model.name);
                o.openButton.find(".ambiance").text(background.model.name);
                o.openButton.fadeIn(200);
                $("#icons").fadeIn(200);
                $("#title").fadeIn(200);
                
                products.setProductsFromModel(background.model);
            });
            
            o.enabled = true;
            o.current = background;
        });
    }
};







var IconsView = function(container, model, timerModel)
{
    this.index      = -1;
    this.container  = container;
    
    this.timerModel = timerModel;
    this.timerModel.addObserver(this);
    
    this.setModel(model);
};

IconsView.prototype = 
{
    reset: function() {
        this.container.find("tr").empty();
    },
    
    setModel: function(model) {
        this.model = model;
        this.model.addObserver(this);
        this.model.setIndex(0);
  
        this.reset();
              
        for (var i=0 ; i<this.model.pictures.length ; i++) {
            this.initIcon(i);
        }
    },

    initIcon: function (i) {
        var model      = this.model;
        var timerModel = this.timerModel;

        var icon = $('<td><div class="opacity"></div><img src="" /></td>');
        icon.find("img").attr("src", this.model.pictures[i]);
        icon.bind("click", function() {
            model.setIndex(i);
            timerModel.percent = 0;
        });
        this.container.find(".tn").append(icon);
        
        var time = $('<td><div class="back"></div><div class="timeline"></div></td>');
        this.container.find(".time").append(time);
    },
    
    indexChanged: function (index) {   
        if (this.index != index) {
            this.swap(this.index, index);
            this.setTimer(index, 0);
            this.index = index;
        }
    },
    
    timeChanged: function (percent) {
        if (this.index != - 1) {
            this.setTimer(this.index, percent);
        }
    },
    
    setTimer: function (index, percent) {
        for (var i=0 ; i<index ; i++)
            this.container.find(".timeline:eq("+i+")").css("width", "39px");
    
        var size = ((39 * percent) / 100).toFixed(0);
        this.container.find(".timeline:eq("+index+")").css("width", size+"px");
    
        for (var i=index+1 ; i<this.model.pictures.length ; i++)
            this.container.find(".timeline:eq("+i+")").css("width", "0px");
    },
    
    swap: function (from, to) {
        if (this.index != to) {
            this.container.find(".opacity:eq("+to+")").fadeTo(500, 0);
            this.index = to;
        }
        
        if (from != -1) {
            this.container.find(".opacity:eq("+from +")").fadeTo(500, 0.5);
        }
    }
};










var ProductsView = function(container)
{
    this.container = container;
    this.count     = 0;
    this.index     = 0;
    var o          = this;   
    
    $("#upbutton").click(function(){o._moveUp();});
    $("#downbutton").click(function(){o._moveDown();});
    this._setUpDownMouseMotionEffect($("#upbutton"));
    this._setUpDownMouseMotionEffect($("#downbutton"));
    
    $('#openbutton').click(function(){o.show();});
    $('#closebutton').click(function(){o.hide();});
};

ProductsView.prototype = 
{
    setLinkImagePath: function(path)
    {
        this.linkImagePath = path;
    },
    
    setProductsFromModel: function(model)
    {
        this.container.find(".content").empty();
        var l = model.getProducts();
        for (var i=0 ; i<l.length ; i++) {
            this.addProduct(l[i]);
        }
        
        if ($('document').pngFix)
            this.container.find(".content").pngFix();
    },
    
    addProduct: function (product)
    {
        this.count++;
        this.container.find(".content").append('<a href="'+product.product_url+'"><img src="'+product.picture_url+'" width="100" height="100"  style="margin:21px 30px;" border="0" /></a>');
        this.container.find(".content").append('<a href="'+product.product_url+'"><img src="'+this.linkImagePath+'" width="160" height="15" border="0" /></a>');
    },
    
    show: function () {
        var o = this;
        
        $('#openbutton').slideUp(100);
        $('#title').animate({bottom:"80px"}, 100);
        $('#closebutton').slideDown(100);
        
        this.container.animate({height:"488px"}, 250, null, function(){
            o._showButton($("#upbutton"));
            o._showButton($("#downbutton"));
        });
    },
    
    hide: function (callback) {
        var o = this;
        
        $('#closebutton').slideUp(100, function() { 
            $('#title').animate({bottom:"45px"}, 100);
        });
        
        this._hideButton($("#upbutton"));
        this._hideButton($("#downbutton"), function(){
            o.container.animate({height:"0px"}, 250, null, function(){
                $('#openbutton').slideDown(100, function() {
                    o.index = 0;
                    o.container.find(".content").css("top", "0px");         
                    if (callback) { callback(); }
                });
            });
        });
    },
    
    _setUpDownMouseMotionEffect: function(element)
    {
        $(element).find(".arrow").mouseover(function(){
            $(element).find(".back").fadeTo(200, 0.8);
        }).mouseout(function(){
            $(element).find(".back").fadeTo(200, 0.3);
        });
    },
    
    _showButton: function(element)
    {
        element.css("width", "0px");
        element.show();
        element.animate({width:"35px"}, 50);
    },
    
    _hideButton: function(element, callback)
    {
        element.animate({width:"0px"}, 50, null, function () {
            element.hide()
            if (callback != null)
                callback();
        });
    },
    
    _moveUp: function()
    {
        if (this.index > 0) {
            this.index--;
            this.container.find(".content").animate({top: (-this.index*157)+"px"}, 100);
        }
    },
    
    _moveDown: function()
    {
        if (this.index < this.count-3) {
            this.index++;
            this.container.find(".content").animate({top: (-this.index*157)+"px"}, 100);
        }
    }
}