/*
    Loads the background image specified in the property of a page
    into the given element
*/
function Background(jqObject, propertyName)
{
    this.JQObject = jqObject;
    this.DefaultBackground = jqObject.css('backgroundImage');
    this.Active = "default";
    this.PropertyName = propertyName;
    
    Navigator.OnDocumentLoad.Bind(this.DocumentChange, this);
}

/*
    Checks for a background file when a new page is opened
*/
Background.prototype.DocumentChange = function(menuitem, opened)
{
    if (opened == true){
        // retrieve background
        var backgroundFile = this.GetBackground(menuitem);
        
        if (backgroundFile == ""){
            // load default background
            if (this.Active != "default"){
                this.JQObject.css('backgroundImage', this.DefaultBackground);
                this.Active = "default";
            }
        } else {
            // load property background
            if (this.Active != backgroundFile){
                this.JQObject.css('backgroundImage', "url('" + backgroundFile + "')");
                this.Active = backgroundFile;
            }
        }
    }
}

/*
    Gets the background file specified in the property of the menuitem or one of its ascendants.
    
    returns "" if nothing was found
*/
Background.prototype.GetBackground = function(menuitem)
{
    if (menuitem.Properties != null) {
        for(var i in menuitem.Properties)
        {
            var property = menuitem.Properties[i];
            
            if (property.Name == this.PropertyName){
                return "custom/" + property.Value;
            }
        }
    }
    
    if (menuitem.Parent != null){
        return this.GetBackground(menuitem.Parent);
    }
    
    return "";
}