//===================================================================================
//
//  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.
//
// @author mortimer - inherited from salavi
//===================================================================================

/**
 * Globals
 */
var __adobe_hello               = (void 0);
var __I18N                      = new HelloI18N();
var personalizationProperties   = (void 0);
var args                        = [];
var cUpdateIntervalSec          = 10;
var secondsPerDay               = 86400;
var secondsPerHour              = 3600;
var secondsPerMinute            = 60;
var lastTabClicked              = "";
var gI18N = __I18N;//new HelloI18N();

// handle user keypress to close the UI
function handleUserKeyEvent(e)
{
    var code = e.keyCode ? e.keyCode : e.which;
        
    // esc keycode = 27 ; return keycode = 13
    if ( code == 27 || code == 13 )
        window.projectHello.hostAppNotifyDoneWithDialog();
}

/**
 * IE doesn't handle the jQuery "keyup" event in the same way as
 * other browsers - so we need to do a little bandaging to get
 * things to work properly as other browsers dont process esc
 * as part of the keypress binding like IE does, so we needed
 * a solution that handled both.  In order to do that we need
 * to detect IE correctly - but with IE11 they changed the
 * userAgent strings so we need a little incantation here...
 * @see http://msdn.microsoft.com/en-us/library/ie/hh869301(v=vs.85).aspx
 */
if ( HelloUtil.browserIsIE() )
{
    // IE based browser
    $(document).keypress(function(e) { handleUserKeyEvent(e); });
}
else
{
    // non-IE based browser
    $(document).keyup(function(e) { handleUserKeyEvent(e); });
}

/**
 * Audience Manager Profile trigger.
 *
 * @param profile           profile setting to pass along
 */
function processAudienceManagerProfile(profile) { $(window).trigger('generateMBoxes', profile); }

$(document).bind('touchmove', function (e) { e.preventDefault(); }); // disable rubber-band bounce
    
/**
 * Handle window resize operation - the mbox need a slight adjustment during resize.
 */
$(window).resize(function () {
    $('#mbox_iframe').css({ height: ($(window).height() - 45) + "px" });
});

/**
 * Document/dom ready.
 */
$(document).ready(function () {
    try 
    {
//		document.oncontextmenu = function() {return false;}


        // Dummy stub of the AdobeHello object just to get Muse working
        window.__adobe_hello = new (function()
        {
            var self = this;

            this.hostID         = "MUSE";    
            this.configuration  = {
                    /**
                        * Object configuration settings.
                        */
                    options : {
                          jsonHtmlEncodeDisplayString     : true     // HTML encoding required on recent file or document type display name
                        , jsonURIEncodeOpenPath           : false    // URI encoding required on recent file path
                        , middleEllipsisFilenames         : false    // middle ellipsize recent file names & template names
                        , createPanelUseOptionalColumn    : false    // use the optional 3rd column of the create panel template
                    }
                    /**
                        * UI element definitions.
                        */
                    , ui : {
                        create  :   {
                              backgroundColor : "#E5E1DE"
                            , dividerColor    : "#B3D618"
                            , backgroundImage : "images/MuseCreateInitialExp.jpg"
                        }
                        , footer  :   {
                              helpURL         : "https://www.adobe.com/go/hello_muse_help"
                            , helpLabel       : "footer_help_label_MUSE"
                            , forumsURL       : "https://www.adobe.com/go/hello_muse_help"
                            , forumsLabel     : "footer_forums_label"
                            , inspireURL      : "https://www.adobe.com/go/muse-site-of-the-day"
                            , inspireLabel    : "footer_inspire_label"
                            , blogURL         : "http://www.adobe.com/go/muse_add-ons"
                            , blogLabel       : "footer_addons_label"
                        }
                    }
            };

            this.getHostProductID = function() { return self.hostID; }
            this.getProductConfiguration = function() { return self.configuration; }
            this.getOptions = function() { return self.configuration.options; }
            this.getFooterData = function() 
            { 
                var footerData = { };
                try
                {
                    footerData = $.extend(true, footerData, self.configuration.ui.footer);
                    for ( var key in footerData )
                    {
                        if ( key.includes("Label") )
                        {
                            footerData[key] = __I18N.getLocalizedString(footerData[key]);
                        }
                    }
                }
                catch( e ) { HelloLog.exception( e ); }

                return footerData;
            };
            this.api = {
                retryLoadFromServer : function( failFn )
                {
                    try
                    {
                        if ( typeof failFn === "undefined" ) { failFn = function(){ }; }

                        HelloLog.logHelloInteractionPIPEvent( "RetryPageLoad" );
                        if ( window.navigator.onLine === true )
                        {
                            var retryURL = "https://helpx.adobe.com/muse/hello/v1_6/index.html";
                window.location = retryURL+"?hostID=MUSE";
                            HelloUtil.asyncCheckExists( retryURL, function(isReachable, jqxhr, textStatus)
                                    {
                                        try
                                        {
                                            if ( isReachable === true )
                                            {
                                                var search = "hostID=MUSE";//self.getURLParams();

                                                search = (search != null && search !== "") ? "?"+search : ""; // just in case we get a null

                                                HelloLog.log("Navigating to content URL: "+ retryURL + search, "DOM CHANGE");
                                                self.logHelloInteractionPIPEvent( "DisplayRemoteHello" );
                                                window.location = retryURL + search;
                                            }
                                            else
                                            {
                                                HelloLog.log("Unable to reach content URL: "+retryURL+" status:("+jqxhr.status+") "+textStatus);

                                                // notify caller of failure to reach destination server
                                                if ( typeof failFn === "function" && failFn != null) { failFn(); }
                                            }
                                        }
                                        catch( e ) { HelloLog.exception( e ); }
                                    });
                        }
                    }
                    catch( e ) { HelloLog.exception( e ); }
                }
            };
        })();

		jsonDataReceiver( window.projectHello.hostAppGetPersonalizationInfo() );
    }
    catch (e) { HelloLog.exception(e); }
});

/**
  * Host application JSON data reciever and preprocessor method.
  *
  * @param jsonData      string object containing the raw JSON data
  */
function jsonDataReceiver(jsonData)
{
    try
    {
        if ( typeof jsonData !== "undefined" && jsonData !== "" && jsonData != null )
        {
            personalizationProperties = JSON.parse(jsonData, function (key, val) {
                // the file display name and tooltip values  coming from the host app side need to be
                // properly encoded for display HTML - this is so that if XSS is tried to be passed
                // through the strings, it gets encoded away
                if (key === "name" || key === "tip")
                {
                    val = Encoder.XSSEncode(val);
                }
                    // if this app uses the full path to the file for the open command, 
                    // then encode it properly too.  More XSS protection.
                else if (key === "fullpath")
                {
                    val = encodeURI(decodeURI(val));
                }
                return val;
            });

            HelloLog.logJSON("Personalization JSON:", personalizationProperties);

            // load the localization strings & panels
            loadDefaultLanguage();
        }
    }
    catch ( e ) { HelloLog.exception( e ); }
}

/**
 * Load the localization XML that contains the resource strings and panel info.
 */
function loadDefaultLanguage()
{		
    // set the UI language locale
    var langStringSet = ( typeof personalizationProperties.language !== "undefined" && personalizationProperties.language.length > 0 )
                            ? personalizationProperties.language
                            : "en_US";

    // read the language XML file - it will contain both the string table and the panel/tab info
    HelloLog.log("Loading I18N resources for: "+langStringSet);
	$.get("language/"+langStringSet+".xml", {}, function(xml) {		
    try
    {
        // set up the localized string table
        $(xml).find("string").each(function() { gI18N.addLocalizedString($(this).attr("name"), $(this).text()); });

        // set up panels
		var visitCounter = "";
		$(xml).find("panel").each(function()
			{									
            try
            {
                var dataURL = $(this).attr("data-url");

                // switch to starters on create if necessary
                if ( dataURL === "create.html"
                        && ( typeof personalizationProperties.createUsesStarters !== "undefined"
                            && (personalizationProperties.createUsesStarters === true
                                || personalizationProperties.createUsesStarters === "true")) )
                {
                        dataURL = "create-starters.html";

                        // add the starters property member
                        if ( typeof personalizationProperties.starterTemplates === "undefined" )
                        {
                            personalizationProperties.starterTemplates =    { filters : {"all" : __I18N.getLocalizedString("create_starter_filter_all")}
                                                                            , templates  : [] };
                        }
                }

				if($(this).attr("counter") == "true")
				{
                    visitCounter += $(this).attr("name")+'Counter,'+$(this).attr("name")+'LUpdate,';
                }
				
                // the 'special offers tab should be the only one aligned to the left at this time
				if($(this).attr("align")=="left")
				{
					if(personalizationProperties["accountType"]=="trial" && $(this).attr("name") == "specialoffer")
					{
						$(".shell_nav ul").append('<li name="'+$(this).attr("name")+'" data-url="'+dataURL+'" counter="'+$(this).attr("counter")+'"><span id="tDaysLeft"></span>'+$(this).text()+'</li>');	
						loadTrialDaysRemaining();					
					}				
					else if($(this).attr("name") != "specialoffer") 
					{
						$(".shell_nav ul").append('<li name="'+$(this).attr("name")+'" data-url="'+dataURL+'" counter="'+$(this).attr("counter")+'">'+$(this).text()+'</li>');
					}					
				}
				else if($(this).attr("align")=="right")
				{
					if(personalizationProperties["accountType"]=="trial" && $(this).attr("name") == "specialoffer")
					{
						$(".shell_nav ul").append('<li name="'+$(this).attr("name")+'" style="float:right;" data-url="'+dataURL+'" counter="'+$(this).attr("counter")+'"><span id="tDaysLeft"></span> '+$(this).text()+'</li>');
						loadTrialDaysRemaining();
					}				
					else if($(this).attr("name") != "specialoffer") 
					{
						$(".shell_nav ul").append('<li name="'+$(this).attr("name")+'" style="float:right;" data-url="'+dataURL+'" counter="'+$(this).attr("counter")+'">'+$(this).text()+'</li>');
					}
				}	
            }
            catch ( e ) { HelloLog.exception( e ); }
			});
				
			$('.shell_nav ul li').on('click', function() {
                try 
                {
				    var liName	  = $(this).attr('name');	
                    var liDataurl = $(this).attr('data-url');

				    $("body").removeAttr( "style" );													
				    $(this).addClass('active').siblings().removeClass('active');		
				    $('#shell_wrapper').stop().fadeOut(300, function() {
					    loadContentPages( liName, liDataurl );				
				    });
                }
                catch ( e ) { HelloLog.exception( e ); }
			});			

			if(checkCookie('lastTabClicked') != 1)
			{
				$(".shell_nav ul li[name=create]").trigger( "click" );
			}
			else
			{	
				lastTabClickedCookie = getCookie('lastTabClicked').split("=");
				lastTabClicked = lastTabClickedCookie[1];
				
				if(lastTabClicked == "" || lastTabClicked == undefined || lastTabClicked == "none")
				{
					$(".shell_nav ul li[name=create]").trigger( "click" );
				}
				else 
				{
					$(".shell_nav ul li[name="+lastTabClicked+"]").trigger( "click" );
				}	
			}
        }
        catch ( e ) { HelloLog.exception( e ); }
	}, "xml");
}
	
/**
    * Fill in the content pages with localizations as necessary.
    *
    * @param liName        string containing the panel name ID
    * @param liDataurl     string containing the panel's url
    */
function loadContentPages(liName, liDataurl)
{	
    try
    {
        // load the URL contained in the tabs data
        if (liDataurl === "" || typeof liDataurl === "undefined" || liDataurl == null)
        {
            liDataurl = $(".shell_nav ul li[name="+liName+"]").attr('data-url');
            $(".shell_nav ul li[name="+liName+"]").addClass('active').siblings().removeClass('active');
        }

        // set the cookie to store the fact that we changed tabs
        setCookie('lastTabClicked',liName,365);
        personalizationProperties["lastTabClicked"] = liName;

        // handle loading the starters into the iframe
        var ifrm = document.getElementById("mbox_iframe");
        var url  = liDataurl;

        if (navigator.userAgent.indexOf("MSIE") > -1 && !window.opera)
        {
            ifrm.onreadystatechange = function(){ if (ifrm.readyState == "complete"){ $('#shell_wrapper').fadeIn(150); } }
        }
        else
        {
            ifrm.onload = function () { $('#shell_wrapper').fadeIn(150); }
        }

        ifrm.src = url+"?tabID="+liName;
        HelloLog.log( "Panel changed to '"+liName);
        window.projectHello.hostAppNotifyContentTabChanged( liName );
    }
    catch ( e ) { HelloLog.exception( e ); }
}

/**
 * Load trial days remaining if trial subscription from cookie.
 */
function loadTrialDaysRemaining() 
{
    var secondsPerDay  = 86400;
    var appTrialTime   = 0;
    var appStartTime   = 0;
    var sysCurrentTime = parseInt((new Date()).getTime()/1000);
    var elapsedTime    = 0;
    var remainingTime  = 0;
    var remainingDays  = 0;
    
    appTrialTime  = parseInt(personalizationProperties["secondsLeftInTrial"]);
    appStartTime  = parseInt(personalizationProperties["appStartClockTime"]);
    elapsedTime   = parseInt((sysCurrentTime - appStartTime));
    remainingTime = parseInt(appTrialTime - elapsedTime);		
    
    if ( remainingTime < 0 ) { remainingTime = 0; }

    remainingDays = Math.round(remainingTime / secondsPerDay);		
    $('#tDaysLeft').html(remainingDays)
}
	
/**
 * Get the requested cookie from the store if it exists.
 *
 * @param cname             string object containing the cookie's name
 * @param cvalue            object containing the cookie's value
 * @param exdays            number of days till the cookie expires
 */
function setCookie(cname,cvalue,exdays)
{
   var d = new Date();

    d.setTime(d.getTime()+(exdays*24*60*60*1000));

    var expires = "expires="+d.toGMTString();

    document.cookie = cname + "=" + cvalue + "; " + expires;
}
	
/**
 * Get the requested cookie from the store if it exists.
 *
 * @param cname             string object containing the cookie's name
 */
function getCookie(cname)
{
    var name  = cname + "=";
    var ca    = document.cookie.split(';');
    var calen = ca.length;

    for(var i = 0; i < calen; i++)
    {
        var c = ca[i].trim();

        if (c.indexOf(name) == 0) { return c; }
    }
	return "";
}
	
/**
 * Check the currently saved cookie.
 *
 * @param cname             string object containing the cookie's name
 */
function checkCookie(cname)
{
    var coname = getCookie(cname);

    return (typeof coname !== "undefined" && coname != "" && coname != null) ? true : false;
}