/*
 * Fix IE background image flicker (via http://www.mister-pixel.com/)
 */
try {
	document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

/*
 *  Namespace
 */
var VenturaFoods = {};

/*
 * Set "focus" to the first non-hidden input field
 */
VenturaFoods.SetFocusToFirstNonHiddenInputField = {
    init: function()
    {
        $(":input:not(:hidden):not(:disabled):not(select):not([multiple])").each(function(i){
            $(this).focus();
            return false;
        });
    }
};

/*
 *  Assignable control
 */
VenturaFoods.AssignableControl = function(container) {
    this.container = container;
    
    this.init();
};

VenturaFoods.AssignableControl.prototype = function() {
    // private variables
    var reservedActions = /['add', 'remove', 'up', 'down']/;
    
    // private methods
    var updateHiddenFieldValues = function()
    {
        var finalValues = [];
        
        this.selectedList.find('option').each(function(){
            finalValues.push($(this).val());
        });
        
        this.hiddenField.val(finalValues.join(','));
    };
    
    var add = function()
    {
        moveOptions.call(this, this.availableList, this.selectedList);
    };
    
    var remove = function()
    {
        moveOptions.call(this, this.selectedList, this.availableList);
    };
    
    var moveOptions = function(from, to)
    {
        from.find('option:selected').each(function(){
            $(this).attr('selected', false).appendTo(to);
        });
        
        updateHiddenFieldValues.call(this); // update hidden field with final "assigned" values
    };
    
    var up = function()
    {
        var options = this.selectedList.find('option');
        for (i = 0; i < options.length; i++)
        {
            if (options[i].selected)
            {
                // can't move first item up
                if (i == 0)
                {
                    return;
                }
                var tmp = new Object();
                tmp.text = options[i-1].text;
                tmp.value = options[i-1].value;
                options[i-1].text = options[i].text;
                options[i-1].value = options[i].value;
                options[i].text = tmp.text;
                options[i].value = tmp.value;
                
                options[i-1].selected = true;
                options[i].selected = false;
            }
        }
        
        updateHiddenFieldValues.call(this); // update hidden field with final "assigned" values
    };
    
    var down = function()
    {
        var options = this.selectedList.find('option');
        for (i = (options.length - 1); i >= 0; i--)
        {
            if (options[i].selected)
            {
                // can't move last item down
                if (i == (options.length - 1))
                {
                    return;
                }
                var tmp = new Object();
                tmp.text = options[i+1].text;
                tmp.value = options[i+1].value;
                options[i+1].text = options[i].text;
                options[i+1].value = options[i].value;
                options[i].text = tmp.text;
                options[i].value = tmp.value;
                
                options[i+1].selected = true;
                options[i].selected = false;
            }
        }
        
        updateHiddenFieldValues.call(this); // update hidden field with final "assigned" values
    };
    
    return {
        init: function()
        {
            // cache elements
            this.links = this.container.find('a');
            this.availableList = this.container.find('.available-list>select');
            this.selectedList = this.container.find('.selected-list>select');
            this.hiddenField = this.container.find('input:hidden');
            
            // set up methods
            this.attachEvents();
        },
        
        attachEvents: function()
        {
            var thisClass = this;
            
            this.availableList.dblclick(function(){
                add.call(thisClass); // add to "selected" list
                $(this).blur();
            });
            
            this.selectedList.dblclick(function(){
                remove.call(thisClass); // remove from "selected" list
                $(this).blur();
            });
            
            this.links.click(function(){
                var action = this.hash.substr(1); // get action from hash
                if (reservedActions.test(action)) // make sure "action" is valid
                {
                    eval(action).call(thisClass);
                }
                
                return false; // prevent default link click
            });
        }
    };
}();

/*
 *  Session timeout logic
 */
VenturaFoods.SessionTimeout = {
    defaultSessionTimeoutSeconds: 20 * 60,  //are (20 minutes * 60 seconds in a minute)
    sessionTimeoutSeconds: this.defaultSessionTimeoutSeconds,
    serverSessionTimeoutSetting: this.defaultSessionTimeoutSeconds,
    sessionTimeoutTime: null,
    countDownTimerID: "countdowntimer",
    
    init: function(actualSessionTimeoutSeconds)
    {
        // Initialize the session timeout with either the passed in value or the default
        if (actualSessionTimeoutSeconds >= 0)
        {
            this.sessionTimeoutSeconds = this.serverSessionTimeoutSetting = actualSessionTimeoutSeconds;
        }
        else
        {
            this.sessionTimeoutSeconds = this.serverSessionTimeoutSetting = this.defaultSessionTimeoutSeconds;
        }
        
        // save the time the session will expire
        this.sessionTimeoutTime = new Date();
        this.sessionTimeoutTime.setSeconds(this.sessionTimeoutTime.getSeconds() + this.sessionTimeoutSeconds);
        
        // set the timer that will update the timeout indicator at regular intervals
        this.beginTimer();
    },
    
    beginTimer: function()
    {
        var thisClass = this;
        
        // if on a page without the countown indicator, simply bail out
        if ($("#" + this.countDownTimerID).size() == 0)
        {
            return;
        }

        if (this.sessionTimeoutSeconds <= 0)
        {
            $("#" + this.countDownTimerID).parent().addClass("required");
            $("#" + this.countDownTimerID).parent().html("(Login Expired)");
        }
        else
        {
            // determine when the session will timeout
            var currentTime = new Date();
            var timeDifference = this.sessionTimeoutTime.getTime() - currentTime.getTime(); // in milliseconds
            this.sessionTimeoutSeconds = Math.floor(timeDifference / 1000); // converted back to seconds

            var curmin = Math.floor(this.sessionTimeoutSeconds / 60);
            var cursec = this.sessionTimeoutSeconds % 60;

            if (cursec < 10)
            {
                cursec = "0" + cursec;
            }

            var curtime = curmin + ":" + cursec;

            if (curmin == 5 && cursec == 0)
            {
                $("#" + this.countDownTimerID).addClass("required");
            }     

            $("#" + this.countDownTimerID).html(curtime);

            setTimeout(function(){thisClass.beginTimer();},1000); // return to this function in a second to recalculate the timeout
        }
    }
};

/*
 * methods to run on DOM ready
 */
$(document).ready(function() {
    VenturaFoods.SetFocusToFirstNonHiddenInputField.init();
    
    $('.assignable').each(function(){
        new VenturaFoods.AssignableControl($(this));
    });
    
	if (typeof SESSION_TIMEOUT_CONTROL != "undefined")
	{
	    VenturaFoods.SessionTimeout.init(SESSION_TIMEOUT_CONTROL);
	}
});

/*
 *	detach all handlers
 */
$(window).unload(function(){
    $("*").unbind();
});
