// indexComm.js
// Example PDK4 port
tpSetCommManagerID("communicationwidget");  // Set communications manager ID

// Global variables used throughout handling
var currentCat = "";
var selectedPID = 0;
var mainPIDs = new Array();
var browsePIDs = new Array();

var browseInitialized = false;
var mainInitialized = false;

// Watches for both release models to receive their first refresh
function onInitialRefreshReleaseModel(pdkEvent)
{
    if ( pdkEvent.originator.controlId == "releasemodelwidget" ) {
        saveMainPIDs(pdkEvent);
        mainInitialized = true; 
    }
    
    if ( pdkEvent.originator.controlId == "browsereleasemodelwidget" ) 
    { 
        saveBrowsePIDs(pdkEvent);
        browseInitialized = true;
    }
    
    if ( mainInitialized && browseInitialized) 
    {
        // Delete initialization handler
        tpController.removeEventListener("OnRefreshReleaseModel", "onInitialRefreshReleaseModel", ["main","browse"]);
        // Intercept UI interaction event so we can determine which release list was clicked on.
        tpController.addEventListener("OnSetReleaseUrl", "onSetReleaseUrl", ['*']);
        // Set up listener for subsequent browse list refresh
        tpController.addEventListener("OnRefreshReleaseModel", "auditPIDs", ['browse']);
    }
}

//Creates a stack of release PIDs
function constructPIDArray(releaseList)
{
    var pidArray = new Array();
    
    for(var i=0;i<releaseList.length;i++) {
        pidArray.push(releaseList[i].PID);
    }
    
    return pidArray;
}

//Called for SetRelease regardless of source
function onSetReleaseUrl(pdkEvent)
{
    var params = pdkEvent.data.toQueryParams();
    selectedPID = params['pid'];


    
    // UI interaction is unscoped, so we need to check 
    // if this onSetReleaseUrl was caused by Browse component
    if ( isEventFromBrowseComponent(pdkEvent))
    {
        var otherPIDs = new Array();
        // Move all PIDs in the browse list to the top of the main list if they're in the bottom half
        for(var i=0; i<mainPIDs.length; i++)
        {
            var match = false;
            for(var j=0; j<browsePIDs.length; j++)
            {
                if (mainPIDs[i] == browsePIDs[j]) {
                    match = true;
                    break;
                }
            }
            
            if (!match) {
                otherPIDs.push(mainPIDs[i]);
            }
        }
        
        mainPIDs = browsePIDs.concat(otherPIDs);
    }

    // Move the selectedPID to the top of the main list array
    for (var i=0; i<mainPIDs.length; i++)
    {
        if (mainPIDs[i] == selectedPID)
        {
            mainPIDs.splice(i, 1);
            mainPIDs.unshift(selectedPID);
            break;
        }
    }
    
    if ( isEventFromBrowseComponent(pdkEvent))
    {
        // Update the main list
        onBrowseSetRelease();
    }

}

// Helper: Determines source of release request
function isEventFromBrowseComponent(evt)
{
    if ( evt.data.toLowerCase().indexOf("componentsrc=browse",0) != -1) {
        return true; 
    } else {
        return false; 
    }
}

//Executed when a release is set through the Browse releaseList.
function onBrowseSetRelease()
{   
    var browsequery = constructPIDQueryString(mainPIDs);
    releasesFromBrowse(browsequery);
}

//Creates an explicit byPID query
function constructPIDQueryString(myPIDs)
{
    var browsequery = constructPIDList(myPIDs);
    if ( selectedPID ) {
        return "query=PIDs|" + selectedPID + "," + browsequery;
    } else {
        return "query=PIDs|" + browsequery;
    }
}

function constructPIDList(myPIDs)
{
    var pidList = new Array();
    for (var i=0; i<myPIDs.length; i++) {
        if (myPIDs[i] != selectedPID) {
            pidList.push(myPIDs[i]);
        }
    }
    return pidList.join(",");
}

//Helper: causes main to refresh itself based on browse query
function releasesFromBrowse(browsequery) {
    tpController.refreshReleaseModel(null,null,null,null,null,[browsequery], ['main']); // emh-refresh releaseModel at Main scope based on browse query
}

// Category functionality
var currentCat = "";

function refreshCategory(category) {
	currentCat = category;
	tpController.refreshReleaseModel(category, null, null, null, null, null, null);	
}

function refreshSearch(terms) {
    currentCat = '';  // TBD:  Is blanking the search term what we want to do here?
	tpController.refreshReleaseModel('', terms, null, null, null, null, null);	
}

function refreshBrowseCategory(category, search, sort, range, params, secondaryParams) {
    currentCat = category;
    tpController.refreshReleaseModel(currentCat, search, sort, range, params, secondaryParams, ["browse"]);  
}

function refreshBrowseSearch(category, search, sort, range, params, secondaryParams) {
	tpController.refreshReleaseModel(null, search, null, null, null, null, ["browse"]);
}

function browseCat(selCat) {
    refreshBrowseCategory(selCat);
}

function browseTopRated() {
    var tpTotalRatingDataServicePrefix = 'http://totalratings.community.theplatform.com/totalrating/';
    tpCommunityManager.getTopRatings("1.0", tpTotalRatingDataServicePrefix, displayTopRated);
}

function displayTopRated(ratings){
    var items = ratings.items;
    var contentIDs = "";

    var tpMediaDataServicePrefix = 'http://mps.theplatform.com/';
    var prefix = tpMediaDataServicePrefix + "data/Media/";
    if (typeof items != "undefined" && typeof items.length != "undefined" && items.length > 0) {
        contentIDCount = 0;
        for (var i=0; i<items.length; i++) {
            var aboutID = items[i].aboutID;
            var IDStart = aboutID.indexOf(prefix);
            if (IDStart == 0) {
                var ID = aboutID.substr(IDStart + prefix.length, aboutID.length - prefix.length);
                var isNumeric = true;
                for (var j = 0; j < ID.length; j++) {
                    if (ID.charAt(j) < '0' || ID.charAt(j) > '9') {
                        isNumeric = false;
                        break;
                    }
                }                   
                if (isNumeric) {
                    if (contentIDs.length == 0) {
                        contentIDs = ID;
                    } else {
                        contentIDs += "," + ID;
                    }
                    // because of URL length limits, cap the total # of content IDs at 100
                    if (++contentIDCount == 100) {
                        break;
                    }
                }
            }
        }
    } else {
        contentIDs = "0";       
    }
    tpController.refreshReleaseModel("", "", null, null, null, ["query=ContentIDs|" + contentIDs], ['browse']); 
}


// Share NYI
function share()
{
	tpController.showEmailForm(true, "", "main");	// emh-Target to main scope
}
 
function send()
{
	tpController.showLinkForm(true, "", "main");    // emh-Target to main scope
}

// Called from external Search component
function searchBrowse(terms) {
	refreshBrowseSearch(null, terms);	// emh-No more cross-frame!
}

function onMediaLoadStart(pdkEvent) {
    // Check if embedding/sending is flagged as disabled
    checkCommunityControls(pdkEvent);  
}

//Helper: Analyzes an OnReleaseStart event
function checkCommunityControls(pdkEvent) {
    try {
        var customData = pdkEvent.data.baseClip.contentCustomData;

        if(customData.Network_Status != 'None') {
           tpController.disablePlayerControls(true, ['tpFullScreen', 'tpPlay', 'tpNext', 'tpPrevious', 'tpPause', 'tpVolume', 'tpScrubber']);
        } else {
           tpController.disablePlayerControls(false);
        }
    } catch (error) {
        //alert(error);
    }
}

function saveMainPIDs(pdkEvent) {
    mainPIDs = constructPIDArray(pdkEvent.data.releaseList);

    if (selectedPID == 0) {
        selectedPID = mainPIDs[0];
    }
}

function saveBrowsePIDs(pdkEvent) {
    browsePIDs = constructPIDArray(pdkEvent.data.releaseList);
}

function auditPIDs(pdkEvent) {
    try {
    // Update the browse list
    saveBrowsePIDs(pdkEvent);
    
    if (mainPIDs.length > 6) {
        
        // 1. Filter out duplicates from the the main list
        var newPIDs = new Array();
        
        for (var i=0; i<browsePIDs.length; i++)
        {
            var match = false;
            for(var j=0; j<mainPIDs.length; j++)
            {
                if (browsePIDs[i] == mainPIDs[j]) {
                    match = true;
                    break;
                }
            }
            
            if (!match) {
                newPIDs.push(browsePIDs[i]);
            }
        }
        
        // 2. Work through the bottom list and find any PID not in the newPIDs list
        var bottomPIDs = mainPIDs.slice(6, mainPIDs.length-6);
        var otherPIDs = new Array();
        
        for (var i=0; i<bottomPIDs.length; i++)
        {
            var match = false;
            
            for (var j=0; j<newPIDs.length; j++)
            {
                if (bottomPIDs[i] == newPIDs[j])
                {
                    match = true;
                    break;
                }
            }
            
            // Replace
            if (!match) {
                otherPIDs.push(bottomPIDs[i]);
            }
        }
        
        // 3. Merge the newPIDs with the otherPIDs to form the new bottom list
        bottomPIDs = otherPIDs.concat(newPIDs);
        
        if (bottomPIDs.length > 6) {
            bottomPIDs.splice(0, bottomPIDs.length - 6);
        }
        
    }
    
    mainPIDs.splice(6, bottomPIDs.length, bottomPIDs);
    
    var browsequery = constructPIDQueryString(mainPIDs);
    releasesFromBrowse(browsequery);
    } catch (error) { 
        //alert(error);
    }
}

// Declare handlers!
document.observe("dom:loaded", function(){
    tpController.addEventListener("OnRefreshReleaseModel", "onInitialRefreshReleaseModel", ["browse","main"]);  // emh - Wait for initial release model refreshes to finish
    tpController.addEventListener("OnMediaLoadStart", "onMediaLoadStart", ["*"]);
});

