// ===================================================================================
//
//  ADOBE CONFIDENTIAL
//
//  Copyright © 2015 Adobe Systems Incorporated
//  All Rights Reserved.
//
//  NOTICE:  All information contained herein is, and remains
//  the property of Adobe Systems Incorporated and its suppliers,
//  if any.  The intellectual and technical concepts contained
//  herein are proprietary to Adobe Systems Incorporated and its
//  suppliers and are protected by all applicable intellectual property
//  laws, including trade secret and copyright laws.
//
//  Dissemination of this information or reproduction of this material
//  is strictly forbidden unless prior written permission is obtained
//  from Adobe Systems Incorporated.
//
// ===================================================================================

/**
 * Globals
 */
var __adobe_hello = (void 0);
var __I18N        = (void 0);

/** 
 * The includes() method determines whether one string may be found within 
 * another string, returning true or false as appropriate. The method is 
 * case sensitive.  This method has been added to the ECMAScript 6 
 * specification and may not be available in all JavaScript implementations yet.
 *
 * @param searchString       string to be searched for within this string
 * @param position           optional param specifying the position in this 
 *                           string at which to begin searching for searchString; 
 *                           [defaults to 0]
 * @return A boolean value indicating true if the search string was found, 
 *          false otherwise.
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
 */
if ( typeof String.prototype.includes === "undefined" ) 
{
    String.prototype.includes = function() 
    {
        'use strict';
        return String.prototype.indexOf.apply(this, arguments) !== -1;
    };
}

/**
 * Determine the pixel width of a string object on the current page.  This
 * method requires the 'pxtextruler' tag object in the page to be setup
 * with the proper font face and point size before the results will be
 * accurate.
 *
 * @param str               string object to measure width in pixel units
 * @return Integer value indicatating the width of the string in pixel units.
 */
if ( typeof String.prototype.includes === "undefined" ) 
{
    String.prototype.pixelLength = function()
    {
        var ruler = document.getElementById("pxtextruler");

        if ( (typeof ruler === "undefined") || ( this === '') ) { return 0; }

        ruler.innerHTML = this;
        return ruler.offsetWidth;
    }
}

$(document).bind( 'touchmove', function(e) { e.preventDefault(); } );  // disable rubber-band bounce

$(document).dblclick(function (e) { e.preventDefault(); });  // disable double-click

/**
 * Handle window resize operation - the mbox need a slight adjustment during resize.
 */
$(window).resize(function() {
    // fixup the footer by resizing the full cards/title contatiner to fill the empty window space
    // so the "footer" container is always pushed to the bottom of the container
    var recentHeight    = $("#openRecentContainer").height() + $(".create_base_wrapper").height();
    var heroHeight      = $("#hero_block").height();
    var footerHeight    = $(".create_base_footer").height();
    var fullCardBlock   = $("#HelloCards").height();
    var blockHeight     = ((recentHeight > heroHeight) ? recentHeight : heroHeight) + footerHeight;
    var containerHeight = ($(window).height() - blockHeight);

    containerHeight = ((containerHeight > fullCardBlock) ? containerHeight : fullCardBlock);

//    HelloLog.debug( " window: "+ $(window).height()+"   hero: "+heroHeight+"  block: "+fullCardBlock+"   foot:"+footerHeight+"   container:"+containerHeight);
    $("#card_block").css({height: containerHeight+"px"});
});

/**
 * window object loads.
 */
$(window).load(function ()
{
    try
    {
        document.oncontextmenu = function() { return false; }  // turn off right click context menu

        // setup a link to the master translation table contained in the parent's DOM
        __I18N = parent.__I18N;
        if ( typeof __I18N === "undefined") { throw new Error("Undefined I18N in Create"); }
 
        // attach AdobeHello to local global, it should already be attached to the window object
        // but this is just to make it more uniform in calling conventions between modules.
        if ( typeof parent.window.__adobe_hello !== "undefined" && parent.window.__adobe_hello != null )
        {
            __adobe_hello = parent.window.__adobe_hello;
        }
        else { throw new Error("Undefined AdobeHello in Create"); }

        // load the content
        loadCreateContent();
    }
    catch( e ) { HelloLog.exception( e ); }
});

/**
 * Ellipsis a text string in the middle based on a certain pixel width.
 *
 * @param str               string object to ellipsize
 * @param maxPxWidth        width to clip the string to in pixel units
 * @return A string object containing the ellipsized string.
 */
var middleEllipsis = function( str, maxPxWidth )
{
    var ellipsisStr = "";

    if ((typeof str !== "undefined" && typeof maxPxWidth !== "undefined")
        && (( str.length > 1 ) && ( maxPxWidth > 0 )))
    {
        var pxWidth  = str.pixelLength();
        ellipsisStr  = str;

        if ( pxWidth > maxPxWidth )
        {
            var middle      = Math.ceil( ellipsisStr.length / 2 );
            var remainder   = ellipsisStr.length - middle;
            var subLeft     = ellipsisStr.substring( 0, remainder );
            var subRight    = ellipsisStr.substring( middle );

            for ( var i = 0; i < remainder; i++ )
            {
                ellipsisStr = subLeft + "..." + subRight;
                pxWidth     = ellipsisStr.pixelLength();

                if ( pxWidth > maxPxWidth )
                {
                    subLeft  = subLeft.substring( 0, subLeft.length - 1 );
                    subRight = subRight.substring( 1 );
                }
                else { break; }
            }
            
        }
    }
    return ellipsisStr;
}

/**
 * Load and localize the "Create" panel.
 */
function loadCreateContent()
{
    try
    {
        // get the host product info, options and list of recent files set up
        var productID         = __adobe_hello.getHostProductID();
        var productConfig     = __adobe_hello.getProductConfiguration();

        // check product interface options
        if ( typeof productConfig === "undefined" ) { throw new Error("Host product configuration is not defined" ); }

        var options           = __adobe_hello.getOptions();
	    var recentFiles       = parent.personalizationProperties["recentFiles"];
        var usingStarters     = ( typeof parent.personalizationProperties.createUsesStarters !== "undefined"
                                 && (parent.personalizationProperties.createUsesStarters === "true"
                                     || parent.personalizationProperties.createUsesStarters === true) ) ? true : false;

        var contentpath       = (typeof options.contentpath !== "undefined") ? options.contentpath : "";
        var useOptionalColumn = false;
        var idx               = 0;

        // check for optional middle ellipsis of file names
        var middleEllipsizeNames = ( typeof options.middleEllipsisFilenames !== "undefined"  ) ?  options.middleEllipsisFilenames : false;

        // localize the content strings
        $("#HelloGreeting").html( __I18N.getLocalizedString("create_hello_greeting") );
        $("#HelloCardDesc").html( __I18N.getLocalizedString("create_hello_card_desc") );
        $("#recents_col_label").html( __I18N.getLocalizedString("create_recents_col_label") );
        $("#newdocs_col_label").html( __I18N.getLocalizedString("create_newdocs_col_label") );
        $(".NewDocButton").html( __I18N.getLocalizedString("create_hello_newdoc_button") );
        $(".OpenDocButton").html( __I18N.getLocalizedString("create_hello_opendoc_button") );

        // set the card title based on point product
        $("#HelloCardTitle").html( __I18N.getLocalizedString("create_hello_card_title_"+productID) );
        $(".NewDocButton").html( __I18N.getLocalizedString("create_hello_newdoc_button_"+productID) );

        // check for optional 3rd colunm use
        if ( typeof options.createPanelUseOptionalColumn !== "undefined"  )
        {
            useOptionalColumn   = options.createPanelUseOptionalColumn;
            optionalColumnLabel = "create_optional_col_label_"+productID;
        }

        // check for which version of the create panel to show
	    if (( typeof recentFiles.length === "undefined"
                || recentFiles.length == null 
                || recentFiles.length == "" 
                || recentFiles.length < 1 )
            && usingStarters === false )  // per Brian/Sung no default on Starters
	    {
            // default screen without recent files view
            var createTabBackgroundImage = productConfig.ui.create.backgroundImage;
            var createTabBackgroundColor = productConfig.ui.create.backgroundColor;
            var backgroundImageOffsetX   = -20;
            var elementContainer         = $(".create_heroblock");

            // set some styling for the different version of create
            if ( usingStarters !== true ) // default to not using Starters
            {
                elementContainer        = $("body");
                backgroundImageOffsetX  = -10;
            }

            // set background color and image based on product
		    $(".create_base_wrapper").css("display","none");
            elementContainer.attr("style", "background:url('"+createTabBackgroundImage+"') no-repeat;"
                                        + "background-position:"+ backgroundImageOffsetX+"px 0px;"
                                        + "background-color:"+createTabBackgroundColor+";");
		    $(".create_base_wrapper_new").removeAttr( "style" );	
            
            // set card divider line color based on product
            $("#HelloCardDividerLine").css("border-color", productConfig.ui.create.dividerColor);
	    }
	    else
	    {
            $(".create_base_wrapper_new").css("display","none");
            $(".create_base_wrapper").removeAttr( "style" );
            $("body").removeAttr( "style" );
						
            // add in new document types
		    var newDocTypes = parent.personalizationProperties["newDocTypes"];		

            for ( idx = 0; idx < newDocTypes.length; idx++ )
            {
                var docType     = newDocTypes[idx]["docType"];
                var docTypeName = newDocTypes[idx]["name"];
                var docTypeTip  = (typeof newDocTypes[idx]["tip"] !== "undefined") ? newDocTypes[idx]["tip"] : docTypeName;

                // skipping emoji check because document types shouldn't have them
                var docHTMLObj = $( '<a class="new_site_button" data-toggle="tooltip" data-html="true" data-placement="bottom" onClick="processNewDocClick(event,\'' + docType + '\')"><img src="'+contentpath+'images/' + newDocTypes[idx]["icon"] + '.png"/><p> ' + docTypeName + '</p></a>' );

                docHTMLObj.attr( 'title', docTypeTip );
                $("#createNewContainer").append( docHTMLObj );
		    }	
				
            // bounds check max number of recent files to display
            var kMaxNumRecentFiles   = 14;
            var recentFilesCount     = (recentFiles.length <= kMaxNumRecentFiles) ? recentFiles.length : kMaxNumRecentFiles;

            // process recent files list
            for ( idx = 0; idx < recentFilesCount; idx++ )
            {
                var fileName = (! middleEllipsizeNames) ? recentFiles[idx]["name"] : middleEllipsis( recentFiles[idx]["name"], 248 );
                var fileTip  = (typeof recentFiles[idx]["tip"] !== "undefined") ? recentFiles[idx]["tip"] : recentFiles[idx]["name"];
                
                var recentFileHTMLObj = $('<a class="new_site_button" data-toggle="tooltip" data-html="true" data-placement="bottom" onClick="processRecentDocClick(event,\'' + idx + '\')"><img src="'+contentpath+'images/' + recentFiles[idx]["icon"] + '.png" /><p>' + fileName + '</p></a>');

                recentFileHTMLObj.attr( 'title', fileTip );

                // add to container
                $("#openRecentContainer").append( recentFileHTMLObj );
		    }			
            // "Open" is always the last entry - so add it here...
            $("#openRecentContainer").append( '<a class="new_site_button" data-toggle="tooltip" data-html="true" data-placement="bottom" title="'+__I18N.getLocalizedString("create_recents_col_open_tip") +'" onClick="processRecentDocClick(event,' + "'open'" + ')"><img src="'+contentpath+'images/openicon@2x.png" /><p>' + __I18N.getLocalizedString("create_recents_col_open_label") + '</p></a>');
	    }

		// setup Starters info
        if ( usingStarters === true )
        {
           $("#cardsTitle").html( __I18N.getLocalizedString("create_starter_title") );

            var starterCount  = parent.personalizationProperties.starterTemplates.templates.length;
            
            for ( idx = 0; idx < starterCount; idx++ )
            {
                var starter = parent.personalizationProperties.starterTemplates.templates[idx];

                // set default filter if necessary
                if ( typeof starter.filter === "undefined"
                    ||  starter.filter === ""
                    ||  starter.filter == null )
                {
                    starter.filter = "all";
                }

                var starterCard = $('<div class="categoryCard" filter="'+starter.filter+'">'
                                    +     '<a href="#" onclick="processNewDocWithStarterClick(\''+starter.file+'\');" data-toggle="tooltip" data-html="true" data-placement="bottom" title="'+starter.tip+'">'
                                    +         '<img class="cardImage" src="'+starter.thumb+'" >'
                                    +     '</a>'
                                    +     '<div class="categoryCardFooter">'
                                    +         '<h2 class="cardTitle">'+starter.title+'</h2>'
                                    +         '<a class="cardTitleLink" href="#" onclick="processPreviewStarterClick(\''+starter.previewurl+'\');" data-toggle="tooltip" data-html="true" data-placement="bottom" title="'+__I18N.getLocalizedString("create_starter_preview_tip")+'">'
                                    +               __I18N.getLocalizedString("create_starter_preview")
                                    +         '</a>'
                                    +     '</div>'
                                    + '</div>');

                // add to container
                $("#BlockOfSixID1").append( starterCard );
            }
        }
        // load the offline footer info (in hello-footer.js)
        loadOffineFooter("create", __adobe_hello.getFooterData());

        // fade?
	    setTimeout(function() { $('#shell_wrapper').fadeIn(300); }, 9000);
    }
    catch ( e ) { HelloLog.exception( e ); }
}

/**
 * Handle the new document action click.
 *
 * @param e             event object
 * @param docType       string object containing the new document type name
 */
function processNewDocClick( e, docType ) 
{		
	parent.window.projectHello.hostAppCreateNewDoc( docType, e.altKey );
}
		
/**
 * Handle the recent document action click.
 *
 * @param e             event object
 * @param documentID    string object containing the recent document index/path
 */
function processRecentDocClick( e, documentID ) 
{
	parent.window.projectHello.hostAppOpenDoc( documentID );
}
	
/**
 * Handle the default new document action click.
 *
 * @param e             event object
 */
function handleDefaultDocumentClick(e)
{
	//var newDocTypes = parent.personalizationProperties["newDocTypes"];
	//var docType = newDocTypes[0]["docType"];
	parent.window.projectHello.hostAppCreateNewDoc( parent.personalizationProperties.newDocTypes[0].docType, e.altKey);
}	

/**
 * Handle the new document from Starter template action click.
 *
 * @param documentID    string object containing the starter document index/path
 */
var clicklock = false;  // kludging Watson:3990823 - lock will prevent
                        // multiple clicks from firing in the cases where the
                        // $.dblclick block function isnt called fast enough.
                        // variable resets automatically after doc open
function processNewDocWithStarterClick( documentID )
{
    if ( clicklock === false )
    {
        parent.window.projectHello.newDocumentFromTemplate( documentID );
        clicklock = true;
    }
}

/**
 * Handle the preview Starter template action click.
 *
 * @param url    string object containing the starter document preview url
 */
function processPreviewStarterClick( url )
{
    if ( typeof parent.window.projectHello.openURLInDefaultBrowser !== "undefined" ) 
    { parent.window.projectHello.openURLInDefaultBrowser(url) }
}
