var newbay = newbay || {};
newbay.pva = newbay.pva || {};

/**
 * @class SystemExtensions
 *
 * A class to extend/manipulate core functionality within the PVA Web Client for USCC.
 * This extentions should be included before any others in production.
 */

newbay.pva.SystemExtentions = {

    /* private sys ext members */

    isMmsDialogInit : false,
    lastMMSGridItemRef: false,
    lastMMSGridRef: false,

    /* end private sys ext members */

    enableAlbumPrivacy : false,          // album public/private switch
    enableMediaPrivacy : false,          // media public/private switch
    enableVideoEditing : false,
    enableCommentLcidToNameTransform : true,
    enablePromptAddToNAB : false,       // ask user to enter any unrecognised contacts on invites send
    enableProfilePreferences : false,    // preferences link above welcome profile section
    generateProfilePreferencesUrl : function () {return "";}, // preferences link above welcome profile section
    generateSNActivationUrl : function () { return newbay.pva.systemSettings.contextWebApp+"/ext/"+newbay.pva.systemSettings.lcid+"/settings/accountsettings#tab=3"}, // sn settings link
    getSkinsPath : function () { return "/skins/uscc/"},




    // reference to an instantiated AddressBook widget to use, this is set to use the standard SAB address book here
	//someone changed this to PVAAddressBook which does not exist and breaks USCC functionality
    getNABInstance : function () {
        return newbay.pva.widget.PVAInviteAddressBook ();
    },
    
    /* Pass-through function for USCC profile pictures... required due to the server-side context naming shenanigans */
    convertProfilePicture : function(logoUrl) {
        var ss = newbay.pva.systemSettings;
        if (typeof logoUrl == "string" && ss.mediaServerContext && ss.thumbnailerContext) {
            logoUrl = logoUrl.replace(new RegExp("/" + ss.mediaServerContext + "/"), "/" + ss.thumbnailerContext + "/").replace(/[a-z]{3,5}:\/\/[^\/]+/,"");
        }
        return logoUrl;
    },

    /* Rest API responsefilter, check for session expiry */
    usccResponseFilter : function(xhr) {
        if (xhr.status == 401 && location.pathname.indexOf(newbay.pva.systemSettings.contextWebApp + "/invite") != 0) {
            var _dialog = newbay.pva.widget.OKDialog;
            _dialog.setText("Your login session has timed out, you will now be redirected to the login page.")
                          .open()
                          .setDialogOption("title", "Session timeout");  //TODO: convert to l10n string
            _dialog.subscribe("okclick", function(){
                var cookie = new newbay.util.Cookie();
                cookie.deleteCookie('NWB');
                cookie.deleteCookie('NWB_NS');
                cookie.deleteCookie('NWB_LCID');
                cookie.deleteCookie('NWB_LEGACY');
                cookie.deleteCookie('fpusername');
                location.href = "https://" + location.host + newbay.authentication.systemSettings.contextWebApp+"/intro";
            });
            return false;
        }

        return true;
    },

    /**************************************************
     * thumbMenuContents
     * Dynamically generates the thumbnail menu
     *
     * @params gridItemData : data representing the thumbnail the menu is for (gridItemData.type is the type of thumb: "album" or "media"
     * @returns JSON representing the menu contents given the gridItemData provided
     * 
     *    Each menu entry has the following format:
     *    "uniqueMenuEntryId" : {
     *        label: "Menu Item Name",                            // mandatory
     *        seperator: true | false,                            // optional - if true will place a seperator after this menu item
     *        clickHandler: function (gridContainer, gridData) {   // optional - if not provided assumes core code will handle it
     *            // gridContainer - instance of GridContainer.js (can be used to refresh grid, highlight thumb on success etc - see public interface)
     *            // gridData - json on what the thumb represents (e.g. a media entry details)
     *        }
     *
     * @important note that this json is dynamically injected into the DOM on each menu render. It is important to ensure it is as efficient as possible
     */

    thumbMenuContents : function (gridItemData) {

        if (gridItemData.type === "media") {

            var menu = {
                "view" :    { label: "View", seperator: true },
                "rename" :  { label: "Rename"}
            }

            var sys = newbay.pva.systemSettings;
            if (sys.album && sys.album !== newbay.pva.locale["allUploadsAlbumIdentifier"]) {
                menu["albumRemove"] = { label: "Remove From Album"};
            }

            if (gridItemData.mediaType == "photo") {
                menu["del"] = { label: "Delete", seperator: true};
                menu["edit"] = { label: "Edit"};
            }
            else {
                menu["del"] = { label: "Delete"};
            }

            // TODO ANDY: heres an example of extra functionality on media thumb (see on USCC welcome page for now)
            if (gridItemData.mediaType == "photo") {
                menu["message"] =  { label: "Send",
                    clickHandler: function (gridContainer, gridItem) {

                        var mmsDialog = uscc.pva.widget.MMSDialog,
                            self = newbay.pva.SystemExtentions;

                        self.lastMMSGridRef = gridContainer;
                        self.lastMMSGridItemRef = gridItem;

                        if (!self.isMmsDialogInit) {
                            mmsDialog.bind ("onMessageSent.MMSDialog", function () {
                                var self = newbay.pva.SystemExtentions;
                                self.lastMMSGridRef.highlightEntry (self.lastMMSGridItemRef.id, {anim: {color: "green"}});
                            });

                            self.isMmsDialogInit = true;
                        }

                        mmsDialog.openMMSDialog({type: "compose", catFeedId: gridItem.id, thumbnailUrl:gridItem.thumbUrl, entryId: gridItem.feedId.replace(/\?.*$/,"")});
                    }
                };
            }

            return menu;
        }

        else if (gridItemData.type === "album") {
            return {
                "open" :    { label: "Open", seperator: true },
                "rename" :  { label : "Rename" },
                "del" :     { label : "Delete", seperator: true },
                "upload" :  { label : "Upload" },
                "download" : { label : "Download", seperator: true },
                "share" :   { label : "Share" }
            };
        }

        return null;

    },

    /*
    * Album Contents View Page: Socialnetworks and drop handlers
     */

    socialNetworks : [{

            id: "fb",
            label: "Facebook",
            onBeforeTransfer: function ($snMenuElement, sns, gridEntries) {

                var onlyPhotos = [];
                for (var i=0, len=gridEntries.length; i<len; i++) {
                    if (gridEntries[i].mediaType == "photo") {
                        onlyPhotos.push(gridEntries[i]);
                    }
                }

                if (onlyPhotos.length == 0) {
                    newbay.pva.widget.OKDialog.setText("Only photos can be uploaded to Facebook.")
                          .open()
                          .setDialogOption("title", "Invalid Content");  //TODO: convert to l10n string                    
                    return false;
                }
                else
                    return onlyPhotos;
            }
        },

        {
            id: "ms",
            label: "Myspace",
            onBeforeTransfer: function ($snMenuElement, sns, gridEntries) {

                var onlyPhotos = [];
                for (var i=0, len=gridEntries.length; i<len; i++) {
                    if (gridEntries[i].mediaType == "photo") {
                        onlyPhotos.push(gridEntries[i]);
                    }
                }

                if (onlyPhotos.length == 0) {
                    newbay.pva.widget.OKDialog.setText("Only photos can be uploaded to MySpace.")
                          .open()
                          .setDialogOption("title", "Invalid Content");  //TODO: convert to l10n string
                    return false;
                }
                else
                    return onlyPhotos;
            }
        },

        {
            id: "pb",
            label: "Photobucket",
            onBeforeTransfer: function ($snMenuElement, sns, gridEntries) {

                var onlyPhotos = [];
                for (var i=0, len=gridEntries.length; i<len; i++) {
                    if (gridEntries[i].mediaType == "photo") {
                        onlyPhotos.push(gridEntries[i]);
                    }
                }

                if (onlyPhotos.length == 0) {
                    newbay.pva.widget.OKDialog.setText("Only photos can be uploaded to Photobucket.")
                          .open()
                          .setDialogOption("title", "Invalid Content");  //TODO: convert to l10n string
                    return false;
                }
                else
                    return onlyPhotos;
            }
        }
    ]
};






