﻿/// <reference path="jquery.intellisense.js"/>
/// <reference path="jquery.easing.1.3.js"/>
/// <reference path="jquery.dimensions.js"/>

/// <reference path="Kleenex.Core.js"/>

Kleenex.BlueCouch = function(clientId, cardCreationUrl)
{
    this.ClientID = clientId;
    this.Selector = "#" + clientId;
    this.CardCreationUrl = cardCreationUrl;
    this.Delay = 500;
    this.BlueCouch = undefined;
    this.ScrollTimeout = undefined;
    
    this.Initialize();
};
Kleenex.BlueCouch.prototype =
{
    Name : 'Kleenex.BlueCouch',
    __typeName : 'Kleenex.BlueCouch',
    __class : true,
    AttachEvents : function()
    {
        var __app = this;
        var context = $(this.Selector);
        
        $('a', context).click(function()
        {
            this.blur();
            Kleenex.ShowModal(__app.CardCreationUrl, true);
        });
        
    },
    MoveCouch : function()
    {
        var __app = this;        
        var context = $(this.Selector);

        var scrollTop = $(window).scrollTop();        
        var windowHeight = $(window).height();
        var nextTop = scrollTop - this.OriginalTop + (windowHeight / 2) - (context.height() / 2);
        if (nextTop < 0)
        {
            nextTop = 0;
        }
        if (nextTop > this.ContainerBottom)
        {
            nextTop = this.ContainerBottom;
        }
        
        var currentTop = parseInt(context.css('top'), 10);
        if (currentTop != nextTop)
        {
            context.animate({ 'top' : nextTop }, this.Delay, 'easeOutQuad');
        }
    },
    Enable : function()
    {
        var __app = this;
        var context = $(this.Selector);
        
        var parent = context.parent();
        
        var parentHeight = parent.height();        
        var contextHeight = context.height();
        var prev = context.prev();
        
        // instance variables
        this.OriginalTop = context.offset().top;
        this.ContainerTop = this.OriginalTop;
        this.ContainerBottom = parentHeight - contextHeight - prev.height();

        var considerMovingCouch = function() 
        {
            clearTimeout(__app.ScrollTimeout);
            __app.ScrollTimeout = setTimeout(function()
            {
                __app.MoveCouch();
            }, __app.Delay);
        };
        
        $(window).scroll(considerMovingCouch);
        $(window).resize(considerMovingCouch);
        
        this.MoveCouch();
    }
};

Kleenex.Extend(Kleenex.BlueCouch, Kleenex.UserControl);
