(function () {
    "use strict";

    /**
    * Iphone Detection and Redirection to the IOS Mobile app

    ****************************************************************************************************
    WARNING!!!!  WARNING!!!!  WARNING!!!!  WARNING!!!!  WARNING!!!!  WARNING!!!!  
    This file is shared by the player, catalog and showcase applications.  This file is copied to the
    catalog and showcase apps using a postbuild event.  Any changes to this file could affect
    how all these applications function.  After making a change to this file please test in the player, catalog and
    showcase using either a small iOS device or using device emulation in Chrome.
    ****************************************************************************************************

    The IosAppDetection will check to see if you are running Mobile Safari on an iPhone or iPod Touch
    and display a message asking you to lauch the Mediasite Mobile App for a better experience.  If the
    user closes the message without trying to lauch the app, we write a cookie with the current time.
    After an hour or if the browser is closed, the cookie will be reset and subsequent loads of the
    IosAppDetection will trigger the message to display again.

    If the message is closed, we are assuming the user wants to continue in the mobile browser and we 
    won't bug him again for 1 hour or a new browser session starts.

    Some apps may want to prompt the user even if the message was closed earlier.  In this case, add
    the property AppCookieOverrideName to the options object passed in the constructor.  This property
    is just a string naming another cookie to check.

    */
    var IosAppDetection = function (iosAppDetectionOptions) {

        var overlayContainer;
        var promptContainer;
        var playCover;
        var body;
        var getAppContainer;
        var playInAppContainer;
        var appDismissedCookieName = "MediasiteAppDismissed";
        var self = this;
        var originalBodyHeight;

        this.Run = function () {

            if (!isIosVersionLessThanTen())
            {
                $(this).trigger('NotIosAppCandidate');
            }
            else if (isEmbedded() && isSmallIosDevice()) {
                buildIosPlayCover();
            } else if (isAppCandidate()) {
                buildDetectionPrompt();
            } else {
                $(this).trigger('NotIosAppCandidate');
            }
        };

        function isAppCandidate() {

            var appDismissed = getCookie(appDismissedCookieName);

            if (appDismissed) {

                //Check if cookie is 1 hour old
                var currentTime = new Date().valueOf();
                var cookieDate = parseInt(appDismissed);  //1 hour

                if (currentTime > cookieDate) {
                    //clear all cookie values
                    createCookie(appDismissedCookieName, "", undefined);

                    if (iosAppDetectionOptions.AppCookieOverrideName) {
                        createCookie(iosAppDetectionOptions.AppCookieOverrideName, "", undefined);
                    }
                }
                else {  //Date is not old

                    //check to see if an app is requiring the message display again
                    if (iosAppDetectionOptions.AppCookieOverrideName) {
                        var appOverrideDismissed = getCookie(iosAppDetectionOptions.AppCookieOverrideName);

                        if (appOverrideDismissed) {
                            return false;
                        }
                    }
                    else {
                        return false;
                    }
                }
            }
            
            return isSmallIosDevice() && isIosVersionLessThanTen() && iosAppDetectionOptions.AppEnabled;
        }

        function isEmbedded() {
            try {
                return (window.self !== window.top);
            } catch (e) {
                return true;
            }
        }

        function isSmallIosDevice() {
            var userAgent = navigator.userAgent || '';
            return (!(userAgent.toLowerCase().indexOf("windows phone") > -1)) && (!(userAgent.toLowerCase().indexOf("windows") > -1)) && (userAgent.indexOf("iPhone") > -1 || userAgent.indexOf("iPod") > -1) && userAgent.indexOf("Safari") > -1;
        }

        function isIosVersionLessThanTen() {

            var results = /(?:iPhone|iPod|iPad).*OS (\d+)_/.exec(navigator.userAgent);
            var version = 0;
            if (results && results.length > 1) {
                version = Number(results[1]);
            } 

            return version < 10;
        }

        function buildIosPlayCover() {


            body = $('body');
            playCover = $('<a class="IosPlayCover-Overlay" href="' + window.location.href + '" target="_blank">' + iosAppDetectionOptions.IPhonePlayCoverLinkText + '</a>'); // Watch this presentation.
            playCover.prependTo(body);

            body.css({ height: overlayContainer.height() + 'px', overflow: 'hidden' });
        }

        function buildDetectionPrompt() {

            body = $('body');
            overlayContainer = $('<div class="IosAppDetection-Overlay"><div class="IosAppDetection-PromptContainer"></div></div>');
            promptContainer = overlayContainer.find('.IosAppDetection-PromptContainer');
            overlayContainer.prependTo(body);

            getAppContainer = $('<div class="IosAppDetection-GetAppInfo"><p>' + iosAppDetectionOptions.InstallTheIosAppText + '</p><p><button class="IosAppDetection-GetAppInfoLink">' + iosAppDetectionOptions.GetTheAppButtonText + '</button></p></div>');
            playInAppContainer = $('<div id="IosAppDetection-PlayPresentation"><p>' + iosAppDetectionOptions.InstallTheIosAppText + '</p><p><button class="IosAppDetection-PlayPresentationLink">' + iosAppDetectionOptions.PlayInAppButtonText + '</button></p></div>');
            var getAppLink = getAppContainer.find('button');
            var playInAppLink = playInAppContainer.find('button');

            getAppContainer.appendTo(promptContainer);
            playInAppContainer.appendTo(promptContainer);

            var continueInBrowserContainer = $('<div id="IosAppDetection-ContinueInBrowser"><p>' + '' + '</p><p><button class="IosAppDetection-ContinueInBrowserLink">' + iosAppDetectionOptions.ContinueInSafariButtonText + '</button></p></div>');
            var getBrowserLink = continueInBrowserContainer.find('button');
            continueInBrowserContainer.appendTo(promptContainer);
            getBrowserLink.on('click', closePrompt);

            //add event handlers
            getAppLink.on('click', getAppClicked);
            playInAppLink.on('click', tryAppLaunch);

            body.css({ height: overlayContainer.height() + 'px', overflow: 'hidden' });
        }

        function closePrompt(event) {

            $(self).trigger('IosAppMessageClosed');

            var cookieDate = new Date().valueOf() + (60000 * 60);  //Date 1 hour in the future
            createCookie(appDismissedCookieName, cookieDate, undefined);

            if (iosAppDetectionOptions.AppCookieOverrideName) {
                createCookie(iosAppDetectionOptions.AppCookieOverrideName, cookieDate, undefined);
            }

            promptContainer.empty();
            promptContainer.remove();
            overlayContainer.remove();
            body.css({ height: '', overflow: '' });

        }

        var failoverDelay = 1500;
        var appAttemptTime;

        function tryAppLaunch(event) {

            appAttemptTime = new Date();

            //try to load the app
            window.location = iosAppDetectionOptions.AppContentUrl;

            // We've got a plan, in case app launch fails.
            window.setTimeout(function () {
                var now = new Date();

                if (now.valueOf() < (appAttemptTime.valueOf() + 2 * failoverDelay)) {
                    showGetAppButton();
                } else {
                    // We're going to interpret this lost time 
                    // as caused by a successful app launch 
                    // from which the user is just returning 
                    // to the browser.
                    showPlayInAppButton();
                }
            }, failoverDelay);
        }

        function getAppClicked(event) {
            playInAppContainer.show();
            getAppContainer.hide();
            window.location = iosAppDetectionOptions.AppStoreUrl;
        }

        function showPlayInAppButton() {
            getAppContainer.hide();
            playInAppContainer.show();
        }

        function showGetAppButton() {
            playInAppContainer.hide();
            getAppContainer.show();
        }


        var createCookie = function (name, value, days) {
            var expires;
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toGMTString();
            } else {
                expires = "";
            }
            document.cookie = name + "=" + value + expires + "; path=/";
        };

        function getCookie(c_name) {
            if (document.cookie.length > 0) {
                var c_start = document.cookie.indexOf(c_name + "=");
                if (c_start != -1) {
                    c_start = c_start + c_name.length + 1;
                    var c_end = document.cookie.indexOf(";", c_start);
                    if (c_end == -1) {
                        c_end = document.cookie.length;
                    }
                    return unescape(document.cookie.substring(c_start, c_end));
                }
            }
            return "";
        }
    };

    window.IosAppDetection = IosAppDetection;

})();