﻿/// <reference path="jquery-1.5-vsdoc.js" />
//this should be integrated in the plugin or create another jQuery plugin...
var pinnedSiteDetection = new (function () {

    // ***CUSTOMIZE***
    var trackerName = "pinSiteLastAccess"; 	// specify the name of the pin site actvity tracker 

    // -- Logic to measure the level of pinning support by your OS
    this.supportLevel = { none: 0, upgradeable: 1, limited: 2, full: 3 };
    this.getOSPinSupportLevel = function () {
        try {
            var userAgent = navigator.userAgent;

            if (userAgent.indexOf("Windows NT 6.1") !== -1)
                return this.supportLevel.full;
            else if (userAgent.indexOf("Windows NT 6.0") !== -1)
                return this.supportLevel.limited;
            else if (userAgent.indexOf("Windows NT") !== -1)
                return this.supportLevel.upgradeable;
            else
                return this.supportLevel.none;
        } catch (exc) {
            return this.supportLevel.none;
        }
    };

    // -- Logic to measure the level of pin-ability by your Browser
    this.abilityLevel = { none: 0, limited: 1, full: 2 };
    this.getBrowserPinAbilityLevel = function () {
        try {
            var appVersion = navigator.appVersion;

            if (this.browserCanPin) {
                if (appVersion.indexOf("Windows NT 6.0") !== -1)
                    return this.abilityLevel.limited;
                else
                    return this.abilityLevel.full;
            }
            else
                return this.abilityLevel.none;
        } catch (exc) {
            return this.abilityLevel.none;
        }
    };

    // -- Logic to help you track your user's pin activity
    this.getDaysSincePinAccess = function () {
        if (this.browserCanPin) {
            if ('localStorage' in window && window['localStorage'] !== null) {
                var daysSince = -1;
                try {
                    var storage = window.localStorage;

                    if (storage[trackerName] != undefined) {
                        var lastDate = new Date(storage[trackerName]);

                        var daysSince = Math.round(((new Date()).getTime() - lastDate.getTime()) / 86400000);
                        if (isNaN(daysSince)) {
                            daysSince = -1;
                        }
                    }
                } catch (ex) {
                    daysSince = -1;
                }
                return daysSince;
            }
        } else {
            return -1;
        }
    };

    // we stablish the last time the user access the site in pinned mode
    this.setSiteHasBeenPinnedFlag = function () {
        try {
            if ('localStorage' in window && window['localStorage'] !== null && this.browserCanPin) {
                window.localStorage[trackerName] = new Date();
                return true;
            }
            else {
                return false;
            }
        } catch (ex) {
            return false;
        }
    }

    // if user has been accessing your site in normal mode, you should probably assume 
    // site is no longer pinned. It will always return true, even if it wasn't pinned before
    this.removeSiteHasBeenPinnedFlag = function () {
        try {
            if ('localStorage' in window && window['localStorage'] !== null && this.browserCanPin) {
                window.localStorage.removeItem(trackerName);
                return true;
            } else {
                return true;
            }
        } catch (ex) {
            return false;
        }
    }

    // -- all the "simplified" T/F logic
    // -- all built on the above more complex pieces of logic
    this.browserCanPin = ('external' in window && 'msIsSiteMode' in window.external);
    this.viewingFromPin = ('external' in window && 'msIsSiteMode' in window.external && window.external.msIsSiteMode());
    this.siteHasBeenPinned = (this.getDaysSincePinAccess() > -1);

    this.hasFullPinAbilityBrowser = (this.getBrowserPinAbilityLevel() === this.abilityLevel.full);
    this.hasLimitedPinAbilityBrowser = (this.getBrowserPinAbilityLevel() === this.abilityLevel.limited);
    this.hasNoPinAbilityBrowser = (this.getBrowserPinAbilityLevel() === this.abilityLevel.none);

    this.hasFullPinSupportOS = (this.getOSPinSupportLevel() === this.supportLevel.full);
    this.hasLimitedPinSupportOS = (this.getOSPinSupportLevel() === this.supportLevel.limited);
    this.hasUpgradeablePinSupportOS = (this.getOSPinSupportLevel() === this.supportLevel.upgradeable);
    this.hasNoPinSupportOS = (this.getOSPinSupportLevel() == this.supportLevel.none);
});

(function ($) {
    var settings = {
        mode: 'expand'
    };
    var actionButton;
    var instructionsDisplayed = false;
    var infoAttached = false;    

    var methods = {
        init: function (callerSettings) {
            settings = $.extend(settings, callerSettings);            
            settings.element = this;
            settings.instructions = null;
            showBannerIfNeed();
        },
        destroy: function () {
            settings.element.find('.showMore').unbind('click');
            settings.element.find('.closePin').unbind('click');
            settings.element.find('.closePin').show();
            if (settings.mode === 'lightbox') {
                settings.instructions.unbind('clickoutside');
                settings.instructions.dialog('destroy');
            }
            instructionsDisplayed = false;
            infoAttached = false;
            settings.mode = 'expand';
            settings.element = undefined;
        }
    };

    function setMode() {
        if (infoAttached) {
            return;
        }

        switch (settings.mode) {
            case 'expanded': addExpand(); break;
            case 'lightbox': addLightbox(); break;
            case 'dedicated': addRedirects(); break;
            default: throw 'mode ' + settings.mode + ' is not supported'; break;
        }

        infoAttached = true;
    }

    function switchBigBox(){
        var bigBox1 = settings.instructions.find('#bigBox1');
        var bigBox2 = settings.instructions.find('#bigBox2');
        if(bigBox1.css('display') === 'none')
        {
            bigBox1.show();
            bigBox2.hide();
        }else{
            bigBox2.show();
            bigBox1.hide();
        }
    }
    var interval;
    function addExpand() {
        settings.element.find('.showMore').click(function (evt) {
            evt.preventDefault();
            if (!instructionsDisplayed) {
                settings.instructions.slideDown('slow');
                interval = setInterval(switchBigBox,7500);
            } else {
                settings.instructions.slideUp('slow');
                clearInterval(interval);
            }
            instructionsDisplayed = !instructionsDisplayed;
        });
        
    }

    function addLightbox() {
        settings.element.find('.showMore').click(function (evt) {
            evt.preventDefault();
            settings.instructions.dialog({
                modal: true,
                height: 'auto',
                width: 'auto',
                resizable: false,
                open: function () {
                    settings.instructions.bind('clickoutside', function () {
                        if (instructionsDisplayed) {
                           settings.instructions.dialog('close');
                        }
                        instructionsDisplayed = !instructionsDisplayed;
                    });
                },
                beforeClose: function () {
                    settings.instructions.unbind('clickoutside');
                }
            });
        });
    }

    function addRedirects() {
        var link = $('a.showMore');
        jQuery('.showMore').click(function () {
            window.location = link.attr('href');
        });
    }

    function setElements(identifier){
         settings.instructions = settings.element.find(identifier).find('.discoverability-instructions');
        settings.element = settings.element.find(identifier).find('.discoverability-topbar');
    }

    function showBannerIfNeed() {
        try {            
            if(pinnedSiteDetection.viewingFromPin)
            {
                //we update the date when the site was last pinned
                pinnedSiteDetection.setSiteHasBeenPinnedFlag();
            }else{
                if(pinnedSiteDetection.browserCanPin){
                    //we are on IE9!
                    if(pinnedSiteDetection.hasFullPinSupportOS){
                        // we are on W7!
                        //check if it was pinned
                        if(pinnedSiteDetection.getDaysSincePinAccess() > -1){
                            setElements('#discoverability-wasPinned');
                        }else{
                            setElements('#discoverability-notPinned');
                        }
                    }else{
                        // we are on vista
                    }   
                }else if(pinnedSiteDetection.hasFullPinSupportOS){
                    // we are in W7 but browser is not IE9 :(
                    setElements('#discoverability-otherBrowser');
                    
                }else if(pinnedSiteDetection.hasNoPinSupportOS){
                    //we are on XP
                    setElements('#discoverability-winxp');
                }else if(pinnedSiteDetection.hasLimitedPinSupportOS){
                    //we are on Vista
                }
            }        
                        
            if(settings.element !== null)
            {
                settings.element.find('.closePin').click(function () {
                                settings.element.slideUp('fast');
                                $(this).slideUp('fast');
                            });
                settings.element.show();
                setMode();
            }
        }
        catch (ex) {
            //something weird happened
        }
    }

    $.fn.ie9pinable = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.tooltip');
        }
    }
})(jQuery);
