// If DemoBrowser instance doesn't exist, create it
if (!window.DemoBrowser) window.DemoBrowser = {};

// Create DemoBrowser.Page function
DemoBrowser.Page = function() {};

// Console debugging object ---------------------------------------------------
if (typeof(console) == "undefined") {
    var console = {
        nLine: 0,
        log: function()
        {
            this.eOutputDiv = document.getElementById("consoleLogOutput");
            this.log = function(sMessage) {
                if (this.eOutputDiv != null) {
                    this.eOutputDiv.innerHTML = this.nLine++ + ": " + sMessage + "<br/>\n" + this.eOutputDiv.innerHTML;
                }
            }
        }
    };
}


// Just for Flash devs
trace = function(sMessage)
{
    console.log(sMessage);
}


// Function to create references to elements in XAML from an array of strings
Silverlight.makeReferences = function(oScope,aNames)
{
    var nNamesLength = aNames.length;
 
    
    // Loop through array of strings
    for (var i=0; i<nNamesLength; i++) {
        // Add references to designated scope object
        oScope[aNames[i]] = oScope.rootElement.findName(aNames[i]);
    }
}


// Create main object
DemoBrowser.Page.prototype = {}




// XAML loaded handler ********************************************************
DemoBrowser.Page.prototype.handleLoad = function(control, userContext, rootElement)
{
    // Make object root scope accessible to inner objects
    var that = this;
    
    // Make arguments availible to parent scope
    this.control = control;
    this.userContext = userContext;
    this.rootElement = rootElement;
    
    //Reference Animation Class
   
    
    // Reference elements
    Silverlight.makeReferences(this, [
        "listHolder",
        "listContents",
        "statesHolder",
        "productsHolder",
        "videoPlayerPosition",
        "listHolder",
        "listFlash",
        "listItemTitle",
        "listItemDescription",
        "listItemDemoTopic",
        "listItemCategory",
        "furtherDetails",
        "ListBground",
        "states",
        "products",
        "introTopHighlight",
        "introStates",
        "silverlight_logo",
        "silverlight_logoWhite",
        "listItemDate",
        "listItemBottomLine"
        
    ]);
    
     //ANIMATE PROPERTIES
     this._tFade = new Tweener(this.control, this.rootElement);
    
    // Make initParams avaliable
    this.initParams = eval("("+control.initParams+")");
    this.sAppPath = this.initParams.sAppPath;
    
    // Array of resources for MultiDownloader
    this.aResources = [
        {   // Resources ('demoList.json')
            title: "resources",
            location: this.sAppPath + "/resources.jpg"
        },
        {   // XAML for listItem component
            title: "listItemXAML",
            location: this.sAppPath + "/listItem.xaml"
        },
        {   // XAML for button component
            title: "buttonXAML",
            location: this.sAppPath + "/button.xaml"
        },
        {   // XAML for VideoPlayer component
            title: "videoPlayer",
            location: this.sAppPath + "/VideoPlayer.xaml"
        }
    ];
    
    // Initialise helper objects --------------------------
    
    // MultiDownloader init
    this.multiDownloader = MultiDownloader(
        this,                   // Silverlight root object
        control,                // Silverlight control object
        this.aResources,        // Resources description array
        this.MLAllComplete,     // All comprete event handler
        this.MLOnChange         // Progress change event handler
    );
    
    // Create shorthand alias for multiDownloader instance
    this.oMD = this.multiDownloader;
    
    // AnimationBuilder init
    this.animationBuilder = AnimationBuilder(rootElement);
    
    // Set default filters to all
    this.stateFilter = {check: function() {return true}};
    this.productFilter = {check: function() {return true}};
    
    // Create empty result list items array
    this.aResultListItems = [];
    
    
}






// Business -------------------------------------------------------------------

DemoBrowser.Page.prototype.initialProperties = function()
{
   this.listHolder.Opacity = 0;
   this.ListBground.Opacity = 0; 
   this.videoPlayer._control.Opacity = 0;
   
    
    this.intro();
}

DemoBrowser.Page.prototype.intro = function()
{

this.highlight = this._tFade.fade(this.silverlight_logo,
                         0,
                         1,
                         "0:0:0",
                         "0:0:1",
                          "callComplete"
                         );

 this.highlight = this._tFade.fade(this.silverlight_logoWhite,
                         1,
                         0,
                         "0:0:1",
                         "0:0:1.5",
                          "callComplete"
                         );

 
    
    //List Highlight
    this.highlight = this._tFade.fade(this.introTopHighlight,
                         1,
                         0,
                         "0:0:1",
                         "0:0:1.3",
                          "callComplete"
                         );
  
    this.highlight = this._tFade.fade(this.products,
                         0,
                         1,
                         "0:0:1",
                         "0:0:1.3"
                         );
    //STATES      
    this.highlight = this._tFade.fade(this.introStates,
                         1,
                         0,
                         "0:0:1.3",
                         "0:0:1.5",
                          "callComplete"
                         );
                         
    this.highlight = this._tFade.fade(this.states,
                         0,
                         1,
                         "0:0:1.3",
                         "0:0:1.5"
                         );
    
    //Listbground n Holder
                          
    this.highlight = this._tFade.fade(this.listFlash,
                         1,
                         0,
                         "0:0:1.6",
                         "0:0:1.8"
                          
                         );
                           
    this.highlight = this._tFade.fade(this.ListBground,
                         0,
                         1,
                         "0:0:1.6",
                         "0:0:1.8"
                         );
                         
  this.highlight = this._tFade.fade(this.listHolder,
                         0,
                         1,
                         "0:0:1.6",
                         "0:0:1.8"
                         );
  //VIDEO PLAYER  
   this.highlight = this._tFade.fade(this.videoPlayer._control,
                         0,
                         1,
                         "0:0:1.5",
                         "0:0:2"
                         );
  
  this.highlight = this._tFade.fade(this.videoPlayer.playerHighlight,
                         1,
                         0,
                         "0:0:1.9",
                         "0:0:2",
                         "callComplete"
                         );
 
  
  }


// Display Products list
DemoBrowser.Page.prototype.displayProducts = function()
{
    // Create instance of ButtonList for Products menu
    this.oProductButtonList = new ButtonList(this, "products", this.sButtonXAML, this.productsHolder, "horisontal");
    
    // Loop through products list ('data.js')
    for (var i=0; i< this.aProducts.length; i++) {
    
        // Add button to list
        this.oProductButtonList.add(this.aProducts[i]);
    
    }    
}

// Display states list
DemoBrowser.Page.prototype.displayStates = function()
{

    // Create instance of ButtonList for States menu
    this.oStatesButtonList = new ButtonList(this, "states", this.sButtonXAML, this.statesHolder, "vertical");
    
    // Loop through products list ('data.js')
    for (var i=0; i< this.aStates.length; i++) {
        
        // Add button to list
        this.oStatesButtonList.add(this.aStates[i]);
    }    
}


// Remove old results from display
DemoBrowser.Page.prototype.clearResults = function()
{
    // Reference results array length
    var resultsLength = this.aResultListItems.length;
    
    // Loop backwards through list
    for (var i=resultsLength; i>0; i--) {
        // Pop and remove button from list
        var resultItem = this.aResultListItems.pop();
        resultItem._remove();
    }
},


// Populate results display list
DemoBrowser.Page.prototype.displayResults = function()
{
    //View Panel
    var fadeInSpeed = 0.2;
    var nCounterKey1 = 0;
    var nCounterKey2 = fadeInSpeed;
    
   //Flash effect Properties
    var flashSpeed = 0.3;
    var nFlashCount1 = 0;
    var nFlashCount2 = flashSpeed;
    
    // Clear previous results
    this.clearResults();
    
    var listFlashSpeed = 0.5
    var nListKey1 = 0;
    var nListKey2 = listFlashSpeed;
    
    //List Highlight
    this.highlight = this._tFade.fade(this.listFlash,
                         1,
                         0,
                         "0:0:"+ nListKey1.toPrecision(2),
                         "0:0:"+ nListKey2.toPrecision(2)
                        
                         );
    
    
    
    // Set default top value to 0
    var nNextTop = 0;    
    
    // Create empty array for result list items
    this.aResultListItems = [];
    
    // Loop through results array
    for (var i=0; i< this.aResults.length; i++) {

        // If a previous item exists, get it's absolute bottom value
        if (typeof(this.aResultListItems[i-1]) != "undefined") {
            nNextTop = this.aResultListItems[i-1].absoluteBottom;
        }
        
        var listItem =   new ListItem(
                this,
                "listItem" + i,         // Unique item Id
                this.listContents,      // Destination canvas element
                this.sListItemXAML,     // List item XAML
                this.aResults[i],       // Data object
                [0, nNextTop])          // Element co-ordinates ['Canvas.Left','Canvas.Top']
        
        // Push a new list item to the result list array
        this.aResultListItems.push(listItem);
        
        listItem._listItem.Opacity = 0;
       
       
        nCounterKey1 += fadeInSpeed;
        nCounterKey2 += fadeInSpeed;
    
        //ANIMATION;
        this._tFade.fadeNSlide(listItem._listItem,
                    listItem._listItem.Opacity,
                    1,
                    "0:0:"+ nCounterKey1.toPrecision(2),
                    "0:0:"+nCounterKey2.toPrecision(2)
                    );
     
     
        nFlashCount1 += flashSpeed;
        nFlashCount2 += flashSpeed;
     
        this.highlight = this._tFade.fade(listItem._flashEffect,
                         .5,
                         0,
                         "0:0:"+ nFlashCount1.toPrecision(2),
                         "0:0:"+ nFlashCount2.toPrecision(2),
                         "callComplete"
                         );
     
    }
    
    // Set maximum scroll to 0
    var nMaxScroll = 0;
    
    // If there objects in the list
    if (this.aResultListItems.length > 0) {
        // Set maximum scroll to the bottom of the last item
        nMaxScroll = this.aResultListItems[this.aResultListItems.length-1].absoluteBottom;
        
    }
    
    if(nMaxScroll <= 412) {
        this.listScroller.eHandle.Visibility = "Collapsed";
    } else {
        this.listScroller.eHandle.Visibility = "Visible";
    }
    
    // Update and re-initialise listScroller
    this.listScroller.updateMaxScroll(nMaxScroll);
    this.listScroller.init();
}



// Perform Filter, return number of results found
DemoBrowser.Page.prototype.filterResults = function(aFilters) 
{
    // Compile filters into array
    var aFilters = [
        this.stateFilter,
        this.productFilter
    ];
	
	// Fill array with filter results
    this.aResults = this.demoList.filter(aFilters);
    trace(this.aResults.length + " items matched");
    
    // Return the length of results
    return this.aResults.length;

}

//**********************************************************************************
// MORE INFO PROPERTIES
//***********************************************************************************
DemoBrowser.Page.prototype.displayVideoDetails = function(oListItemSelected)
{   

    
    //INSERT COPY
    this.listItemTitle.text = "Name: " + oListItemSelected.Name;
    
    this.listItemCategory.text = "Product: " + oListItemSelected.Product + " with " + oListItemSelected.Name + " from " + oListItemSelected.State;
    
    this.listItemDescription.text = "Community Group: " + oListItemSelected.CommunityGroup;
   
    this.listItemDemoTopic.text = "Demo Topic: " + oListItemSelected.DemoTopic;
    this.listItemDate.text = "Date Submitted: " + oListItemSelected.Date;
    var listFlashSpeed = 0.5;
    var nListKey1 = 0;
    var nListKey2 = listFlashSpeed;
    
    // Set vertical spacing
    this.stackElements("vertical", 7, [
            this.listItemTitle,
            this.listItemDemoTopic,
            this.listItemCategory,
            this.listItemDescription,
            this.listItemDate,
            this.listItemBottomLine
        ]
    );
    
    //List Highlight

    this.highlight = this._tFade.fade(this.furtherDetails,
                         0,
                         1,
                         "0:0:"+ nListKey1.toPrecision(2),
                         "0:0:"+ nListKey2.toPrecision(2)

                         );
    
}


DemoBrowser.Page.prototype.stackElements = function(sOrientation ,nSpace, aElements) {
    
    var nFinalTop;
    
    for (var i=0; i<aElements.length; i++) {
        
        if (typeof(aElements[i-1]) != "undefined") {
            var sElementType = aElements[i-1].toString();
            switch (sElementType) {
                case "TextBlock":
                    nFinalTop = aElements[i-1]["Canvas.Top"] + aElements[i-1].ActualHeight + nSpace;
                break;
                default:
                    nFinalTop = aElements[i-1]["Canvas.Top"] + aElements[i-1].Height + nSpace;
                break;
            }
            
            aElements[i]["Canvas.Top"] = nFinalTop;
        }

    }
}