////////////////////////////////////////////////
/// Fits.me Virtual Fitting Room integration
////////////////////////////////////////////////

function fm_isTestMode(k) {
    if (k === undefined) k = 'fmtest';
    return window.location.href.indexOf(k) > 0;
}

function fm_loadLib(filename) {
    var fileref = document.createElement('script');
    fileref.setAttribute("type", "text/javascript");
    fileref.setAttribute("src", filename);
    document.getElementsByTagName("head")[0].appendChild(fileref);
}

//p - js file prefix
//t - manually set test mode on/off
function fm_loadShopLib(jsFilePrefix, isTestMode) {
    var u = (document.location.protocol == "https:" ? 'https:' : 'http:') + '//www.fits.me/' + jsFilePrefix + (isTestMode ? '_test' : '') + '.js';
    fm_loadLib(u);
}

function fm_addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function () {
            if (oldonload) {
                oldonload();
            }
            func();
        };
    }
}

/////// NEWER CLIENTS WILL BE IDENTIFIED BY THE SHOP URL
if(typeof(FM_ID) == 'undefined') {
	if(window.location.href.toLocaleLowerCase().indexOf('ghost.co.uk') >= 0) fm_loadShopLib('ghost');
} 


////// LEGACY SUPPORT FOR MANUALLY IDENTIFIED CLIENTS
if (typeof(FM_ID) != 'undefined' && FM_ID == 'dunhill') { 
    fm_loadShopLib('dunhill');
}

if (typeof(FM_ID) != 'undefined' && FM_ID == 'sangar') {
    fm_loadShopLib('sangar');
}

if (typeof(FM_ID) != 'undefined' && FM_ID == 'barbour') {
    fm_loadShopLib('barbour');
}

if (typeof(FM_ID) != 'undefined' && FM_ID == 'griffinstudios') {
    fm_loadShopLib('griffin');
}

if (typeof(FM_ID) != 'undefined' && FM_ID == 'johnsmedley') {
    fm_loadShopLib('smedley');
}

if (typeof(FM_ID) != 'undefined' && FM_ID == 'hawesandcurtis') {
    $(document).ready(function () {
        fm_loadShopLib('curtis', fm_isTestMode('fitsme'));
    });
}

if (typeof(FM_ID) != 'undefined' && (FM_ID == 'soulrevolver' || FM_ID == 'soulrevolveruk')) {
    fm_loadShopLib('soulrevolver');
}

if (typeof(FM_ID) != 'undefined' && FM_ID == 'thomaspink') {
    fm_loadShopLib('thomaspink');
}

if (typeof(FM_ID) != 'undefined' && FM_ID == 'zegna') {
    fm_loadShopLib('zegna');
}

if (typeof(FM_ID) != 'undefined' && FM_ID == 'prettygreen') {
    fm_loadShopLib('prettygreen');
}

var fm_Cookie = new (function () {
    function createCookie(name, value, days) {
        if (days === undefined) days = 365;
        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 readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    function eraseCookie(name) {
        createCookie(name, "", -1);
    }

    this.create = createCookie;
    this.read = readCookie;
    this.erase = eraseCookie;
})();

function fm_LogErr(err) {
    if (window['console']) console.log(err);
}

function fm_LocationContains(s) {
    return window.location.href.indexOf(s) > 0;
}

// cookieName : string
// trackFn : function(action, label)
function fm_getSplitIdx(cookieName, trackFn) {
    var cn = cookieName;
    if (!cn) return 0;

    var cv = fm_Cookie.read(cn);
    if (cv != null) {
        var n = Number(cv);
        if (isNaN(n)) return 0;
        return n;
    }
    var i = Math.round(Math.random());
    fm_Cookie.create(cn, i);
    if (trackFn) trackFn(cn, i);
    return i;
}

function fm_trackEvent(cl, ev, a, b, c) {
    try {
        if (cl === undefined || ev === undefined) return;
        var url = 'http://tracking.fits.me/?cl=' + cl + '&ev=' + ev + '';
        if (a !== undefined || b !== undefined || c !== undefined) {
            url = addParam(url, 'a', a);
            url = addParam(url, 'b', b);
            url = addParam(url, 'c', c);
        }
        (new Image()).src = url;
    }
    catch (err) {
    }

    function addParam(url, name, value) {
        if (url === undefined) return;
        if (name === undefined || value === undefined) return url;
        return url + '&' + name + '=' + encodeURIComponent(value);
    }
}

var FitsMe = FitsMe || {};

FitsMe.VFR = function () {
    var baseUrl = null;
    var fileName = null;
    var parameters = null;

    var width = 920;
    var height = 650;

    var frameUrl = null;

    var parentUrl = null;

    var animationDuration = 100;
    var animationInterval = 25;

    var bgTransparancy = 75;

    var closeHeight = 50;
    var closeWidth = 50;
    var closeOffset = 10;

    // when window is small where the top of iframe is 
    // best if: smallTop-(closeHeight-closeOffset)>=0
    var smallTop = 41;

    var callbackResult;
    var callbackClose;

    var interval_id,
    last_hash,
    attached_callback,
    window = this;

    function open(BaseUrl, FileNameOpt, Parameters, HeightOpt, WidthOpt) {
        if (document.getElementById("FitsMe_VFR_Background") == null) {
            if (BaseUrl != null) {
                baseUrl = BaseUrl;
            }
            if (FileNameOpt != null && FileNameOpt != "undefined" && FileNameOpt != "") {
                fileName = FileNameOpt;
            }
            if (Parameters != null) {
                parameters = Parameters;
            }
            if (HeightOpt != null && HeightOpt != "undefined" && HeightOpt != "") {
                height = HeightOpt;
            }
            if (WidthOpt != null && WidthOpt != "undefined" && WidthOpt != "") {
                width = WidthOpt;
            }

            parentUrl = document.location.href;

            // Leiab akna suuruse
            // Pärast vaatab kui iframe suurus on suurem kui akna suurus siis ei pane keskele vaid 0
            var winWidth = 0, winHeight = 0;
            if (typeof (window.innerWidth) == 'number') {
                //Non-IE
                winWidth = window.innerWidth;
                winHeight = window.innerHeight;
            } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                //IE 6+ in 'standards compliant mode'
                winWidth = document.documentElement.clientWidth;
                winHeight = document.documentElement.clientHeight;
            } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                //IE 4 compatible
                winWidth = document.body.clientWidth;
                winHeight = document.body.clientHeight;
            }


            var bgdiv = document.createElement("div");
            bgdiv.id = "FitsMe_VFR_Background";
            bgdiv.style.position = "fixed";
            bgdiv.style.height = "100%";
            bgdiv.style.width = "100%";
            bgdiv.style.top = "0";
            bgdiv.style.left = "0";
            bgdiv.style.backgroundColor = "Black";
            bgdiv.style.zIndex = "3000";
            bgdiv.style.zoom = "1";
            bgdiv.style.display = "none";

            var iframe = document.createElement("iframe");
            iframe.id = "FitsMe_VFR_IFrame";
            iframe.name = "FitsMe_VFR_IFrame";
            iframe.frameBorder = "0";
            iframe.scrolling = "no";
            iframe.allowTransparency = "true";
            iframe.style.position = "absolute";
            iframe.style.background = "transparent";
            iframe.style.zIndex = "3001";
            iframe.style.height = height + "px";
            iframe.style.width = width + "px";
            iframe.style.display = "none";
            if (winHeight >= height) {
                iframe.style.top = "50%";
                iframe.style.marginTop = "-" + (height / 2) + "px";
            }
            else {
                iframe.style.top = smallTop + "px";
            }
            if (winWidth >= width) {
                iframe.style.left = "50%";
                iframe.style.marginLeft = "-" + (width / 2) + "px";
            }
            else {
                iframe.style.left = "0";
            }


            var iframeClose = document.createElement("iframe");
            iframeClose.id = "FitsMe_VFR_Close";
            iframeClose.frameBorder = "0";
            iframeClose.scrolling = "no";
            iframeClose.allowTransparency = "true";
            iframeClose.style.position = "absolute";
            iframeClose.style.background = "transparent";
            iframeClose.style.zIndex = "3002";
            iframeClose.style.height = closeHeight + "px";
            iframeClose.style.width = closeWidth + "px";
            iframeClose.style.display = "none";
            if (winHeight >= height) {
                iframeClose.style.top = "50%";
                iframeClose.style.marginTop = "-" + (height / 2 + (closeHeight - closeOffset)) + "px";
            }
            else {
                iframeClose.style.top = smallTop - (closeHeight - closeOffset) + "px";
            }
            if (winWidth >= width) {
                iframeClose.style.left = "50%";
                iframeClose.style.marginLeft = (width / 2 - closeOffset) + "px";
            }
            else {
                iframeClose.style.left = (width - closeOffset) + "px"; ;
            }

            if (parameters.substr(0, 1) != "?") {
                parameters = "?" + parameters;
            }

            frameUrl = baseUrl;
            if (fileName != null) {
                frameUrl += fileName;
            }
            frameUrl += parameters + "&pu=" + encodeURIComponent(parentUrl);

            iframe.src = frameUrl;
            iframeClose.src = baseUrl + "CloseIFrame.htm";

            var childHost = iframe.src.replace(/([^:]+:\/\/[^\/]+).*/, '$1');

            receiveMessage(function (message) {
                var msgs = message.data.split("=");
                var msg = msgs[0];
                var addData = null;
                if (msgs.length > 0) {
                    addData = msgs[1];
                }

                switch (msg) {
                    case "Close":
                        if (callbackClose) {
                            callbackClose();
                        }
                        animate("hide", 0);
                        break;
                    case "Result":
                        if (callbackResult) {
                            callbackResult(addData);
                        }
                        animate("hideRemove", 0);
                        break;
                }
            }, childHost);

            document.body.appendChild(bgdiv);
            document.body.appendChild(iframe);
            document.body.appendChild(iframeClose);
        }
        animate("show", 0);
    }

    function animate(command, time_elapsed) {
        var bgdiv = document.getElementById("FitsMe_VFR_Background");
        var iframe = document.getElementById("FitsMe_VFR_IFrame");
        var iframeClose = document.getElementById("FitsMe_VFR_Close");

        if (bgdiv == null || iframe == null || iframeClose == null) return;

        if (time_elapsed <= animationDuration) {
            if (command == "show") {
                var bg_now_transparancy = time_elapsed * bgTransparancy / animationDuration;
                bgdiv.style.filter = "alpha(opacity = " + bg_now_transparancy + ")";
                bgdiv.style.opacity = bg_now_transparancy / 100;

                var now_transparancy = time_elapsed * 100 / animationDuration;
                iframe.style.filter = "alpha(opacity = " + now_transparancy + ")";
                iframe.style.opacity = now_transparancy / 100;

                iframeClose.style.filter = "alpha(opacity = " + now_transparancy + ")";
                iframeClose.style.opacity = now_transparancy / 100;

                if (time_elapsed == 0) {
                    bgdiv.style.display = "block";
                    iframe.style.display = "block";
                    iframeClose.style.display = "block";
                }
            }
            else {
                var bg_now_transparancy = bgTransparancy - time_elapsed * bgTransparancy / animationDuration;
                bgdiv.style.filter = "alpha(opacity = " + bg_now_transparancy + ")";
                bgdiv.style.opacity = bg_now_transparancy / 100;

                var now_transparancy = 100 - time_elapsed * 100 / animationDuration;
                iframe.style.filter = "alpha(opacity = " + now_transparancy + ")";
                iframe.style.opacity = now_transparancy / 100;

                iframeClose.style.filter = "alpha(opacity = " + now_transparancy + ")";
                iframeClose.style.opacity = now_transparancy / 100;
            }

            setTimeout(function () { animate(command, time_elapsed + animationInterval); }, animationInterval);
        }
        else {
            if (command == "show") {
                bgdiv.style.filter = "alpha(opacity = " + bgTransparancy + ")";
                bgdiv.style.opacity = bgTransparancy / 100;

                iframe.style.filter = null;
                iframe.style.opacity = null;
                iframeClose.style.filter = null;
                iframeClose.style.opacity = null;
            }
            else {
                bgdiv.style.display = "none";
                iframe.style.display = "none";
                iframeClose.style.display = "none";

                if (command == "hideRemove") {
                    document.body.removeChild(bgdiv);
                    document.body.removeChild(iframeClose);
                    document.body.removeChild(iframe);

                    receiveMessage(null); //Remove message receiver
                }
            }
        }
    }

    /* 
    * a backwards compatable implementation of postMessage
    * by Josh Fraser (joshfraser.com)
    * released under the Apache 2.0 license.  
    */
    function receiveMessage(callback, source_origin) {
        // browser supports window.postMessage
        if (window['postMessage']) {
            // bind the callback to the actual event associated with window.postMessage
            if (callback) {
                attached_callback = function (e) {
                    if ((typeof source_origin === 'string' && e.origin !== source_origin)
                        || (Object.prototype.toString.call(source_origin) === "[object Function]" && source_origin(e.origin) === !1)) {
                        return !1;
                    }
                    callback(e);
                };
            }
            if (window['addEventListener']) {
                window[callback ? 'addEventListener' : 'removeEventListener']('message', attached_callback, !1);
            } else {
                window[callback ? 'attachEvent' : 'detachEvent']('onmessage', attached_callback);
            }
        } else {
            // a polling loop is started & callback is called whenever the location.hash changes
            interval_id && clearInterval(interval_id);
            interval_id = null;

            if (callback) {
                interval_id = setInterval(function () {
                    var hash = document.location.hash,
                        re = /^#?\d+&/;
                    if (hash !== last_hash && re.test(hash)) {
                        last_hash = hash;
                        callback({ data: hash.replace(re, '') });
                    }
                }, 100);
            }
        }
    }
	
    return {
        open: open
    };
} ();
