(function(){
var version="200";
    (function(){
        var lastTime = 0;
        var vendors = ['ms', 'moz', 'webkit', 'o'];
        for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
            window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
            window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
                || window[vendors[x]+'CancelRequestAnimationFrame'];
        }

        if (!window.requestAnimationFrame)
            window.requestAnimationFrame = function(callback, element) {
                var currTime = new Date().getTime();
                var timeToCall = Math.max(0, 16 - (currTime - lastTime));
                var id = window.setTimeout(function() { callback(currTime + timeToCall); },
                    timeToCall);
                lastTime = currTime + timeToCall;
                return id;
            };

        if (!window.cancelAnimationFrame)
            window.cancelAnimationFrame = function(id) {
                clearTimeout(id);
            };
    }());

    // if is safari and we are coming from a back button reload the page
    if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1 && navigator.userAgent.indexOf('Android') == -1) {
        window.onpageshow = function(event) {
            if (typeof event.persisted !== "undefined" && event.persisted) {
                window.location.reload();
            }
        };
    }

    // check if to show loader
    if(document.getElementById("prod-widget-sfly").src.toLowerCase().indexOf("noloader=") != -1) {
        loadMainSDK();
        return;
    }

    if(window.location.href.indexOf("mgBreak") != -1) {
        debugger;
    }

    var PicHeightCurrentValue = 0;
    var CounterPicHeight;
    var StopMgLoad;

    var mgDiv = document.getElementById("MagicShopFull");
    if(mgDiv){
        var useCDN = true;
        if( (window.location.href.indexOf("beta.shutterfly.com") != -1)  || (window.location.href.indexOf("stage.shutterfly.com") != -1) || (window.location.href.indexOf("dev.shutterfly.com") != -1)  )
            useCDN = false;

        var fileref = document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", (GetServerUrl(useCDN) +"css/mgStyle3.css"));
        document.getElementsByTagName("head")[0].appendChild(fileref);

        var innerHtml = [
            ,'<div id="mg_displayArea">'
            ,'<div id="mg_mainDiv">'
            ,'<div id="mg_animnTitleNew"><h5 class="sfly_wgt_listview_embedded_caption" style="height: 40px"></h5></div>'
            ,'<div id="mg_LoadingDiv">'
            ,'<div id="mg_animColorImg"></div>'
            ,'<div id="mg_animGrayImg"></div>'
            ,'</div>'
            ,'</div>'
            ,'<div id="mgHiddenText"></div>'
            ,'</div>'].join("");

        StopMgLoad = false;
        mgDiv.style.position = "relative";
        mgDiv.style.height = "290px";
        mgDiv.style.width = "980px";
        mgDiv.className += " mg_MagicShopDivStyle"; 
        mgDiv.innerHTML = innerHtml;

        PicHeightCurrentValue = 85;
        CounterPicHeight = 100;
        animPicHeight();
    }
    PicHeightCurrentValue -= 40;
    
    // Special use case for HP a/b test 
    if( (window.location.href.indexOf("home") != -1) && (window.location.href.indexOf("home-decor") === -1))
    {
        var res = LoadSDKIfContainerVisible();
        if(!res)
        {
            window.addEventListener('scroll', LoadSDKIfContainerVisible, true);
            window.addEventListener('resize', LoadSDKIfContainerVisible, true);
        }
    }   
    else
    {   
        loadMainSDK();
    }

    PicHeightCurrentValue -= 35;

    function LoadSDKIfContainerVisible()
    {
        var mgDiv = $('#MagicShopFull');
        var mgTop = mgDiv.offset().top;
        var screenHeight = (window.pageYOffset + window.innerHeight);

        //console.log("mgTop", mgTop, "screenHeight", screenHeight);
        if(mgTop < screenHeight)
        {
            window.removeEventListener('scroll', LoadSDKIfContainerVisible, true);
            window.removeEventListener('resize', LoadSDKIfContainerVisible, true);
            loadMainSDK();
            return true;
        }
        else
        {
            return false;
        }
    }

    function GetServerUrl(useCDNin) {
        var mgServerUrl = "";
        if(useCDNin)
        {
            var CDNVer = "5.1";
            mgServerUrl = "https://d22bbwxztp2lry.cloudfront.net/v"+CDNVer+"/";
        }
        else
        {
            mgServerUrl = "https://magic.photoccino.com/";
            if((window.location.href.indexOf("beta.shutterfly.com") != -1) || (window.location.href.indexOf("172.24.66.1") != -1) || (window.location.href.indexOf("stage.shutterfly.com") != -1) || (window.location.href.indexOf("dev.shutterfly.com") != -1) || (window.location.href.indexOf("172.20.24.167") != -1) || (window.location.href.indexOf("amsingh.dev.shutterfly.com") != -1) || (window.location.href.indexOf("www.photoccino.com") != -1) )
            {
                mgServerUrl = "https://dev-magic.photoccino.com/";
            }
            if( window.location.href.indexOf("mgUI=stage") != -1)
            {
                mgServerUrl = "https://stage-magic.photoccino.com/";
            }
            if( window.location.href.indexOf("mgUI=beta") != -1)
            {
                mgServerUrl = "https://beta-magic.photoccino.com/";
            }
            mgServerUrl += "ServerMain/";
        }
        return mgServerUrl;
    }
    function animPicHeight() {
        var element =  document.getElementById("mg_animGrayImg");
        if(!element || (typeof element == "undefined"))
            return;

        if(StopMgLoad)
            return;

        if(CounterPicHeight > PicHeightCurrentValue)
        {
            CounterPicHeight -= 1;
            element.style.height = CounterPicHeight + '%';
            if(CounterPicHeight <= 0)
            {
                element.style.height = 0 + '%';
                return;
            }
        }
        window.requestAnimationFrame(animPicHeight);
    }
    var counterMainDiv = 0;
    function animMainDivTop() {
        var element =  document.getElementById("mg_mainDiv");
        counterMainDiv -= 7;
        element.style.top = counterMainDiv + 'px';
        if(counterMainDiv <= -289)
        {
            element.style.top = -289 + 'px';
            return;
        }
        window.requestAnimationFrame(animMainDivTop);
    }
    function parse_query_vars(text)
    { // Extract name=value pairs from URL query string.
        text = text.toLowerCase();
        // Empty object to store name, value pairs.
        var qvars = {},
        // Capture non-empty query string in $1.
            re_q = /\?([^#]+)/, // From '?' up to '#' or EOS.
        // Capture variable name in $1 and value in $2.
            re_nv = /([^=]+)=([^&]*)(?:&(amp;)?|$)/gi,
        // Match array for query string con va=val pairs.
            m =  text.match(re_q),
        // Query string plucked from URL
            q = '';
        // If there is a query string, copy to q var.
        if (m) q = m[1];
        while (m = re_nv.exec(q)) {
            qvars[m[1]] = m[2];
        }

        return qvars; // Return results in object
    }
    function loadMainSDK()
    {
        // Prevent for loading twice
        if(typeof window.mgShop !== "undefined")
        {
            return;
        }

        var endPoint = 'https://d22bbwxztp2lry.cloudfront.net';
        var env = 'prod';
        var scriptParams = parse_query_vars(document.getElementById("prod-widget-sfly").src);
        if(typeof scriptParams.env !== void 0){
            env =  scriptParams.env;
        } else {
            if (window.location.href.indexOf("dev.shutterfly.com") != -1) {
                env = 'dev';
            }
            else if (window.location.href.indexOf("beta.shutterfly.com") != -1) {
                env = 'beta';
            }
            else if (window.location.href.indexOf("stage.shutterfly.com") != -1) {
                env = 'stage';
            }
        }
        switch(env) {
            case 'dev':
                endPoint = 'https://s3.amazonaws.com/magicshopfiles';
                break;
            case 'beta':
                endPoint = 'https://s3.amazonaws.com/magicshopfiles';
                break;
        }
        var sc = document.createElement("script");
        sc.src = endPoint+'/productswidget/Shutterfly/sidewidget/v1.1/'+env+'/v'+version+'/sdkm.min.js';
        document.body.appendChild(sc);
        window.mgShop = { timeSdk : Date.now() };
    }
})()
