ums.mobile = null;

/**
 * Attaches an event to an element using appropriate function depending on browser
 * @param  element el    element to attach event
 * @param  Event event Event
 * @param  function func  Callback
 */
ums.attachEvent = function (el, event, func){
    if (el.addEventListener) {
        el.addEventListener(event, func, false);
    }
    else {
        el.attachEvent("on"+event, func);
    }
}

/**
 * Function to detect browser type and returns if it's a mobile browser
 * @return boolean true if mobile, false otherwise
 */
ums.isMobile = function(){
    var className = '';

    if(this.mobile !== null)
    {
        return this.mobile;
    }
    var a = navigator.userAgent||navigator.vendor||window.opera;
    if(/(iPad|android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))){
        this.mobile = true;
    }
    return this.mobile;
}

/**
 * Resizes views (called onresize)
 */
ums.resize = function(){
    this.resizeModal();
    this.resizeWidget();
}

/**
 * Resizes modal iframe
 */
ums.resizeModal = function(){
    if(this.overlay.clientHeight > 0 && this.modal.clientWidth > 0){
        if(this.isMobile())
        {
            this.overlay.style.height = window.innerHeight + 'px';
        }

        // this.modalIframe.style.height = '0';
        // this.modalIframe.style.height = (this.overlay.clientHeight - (this.isMobile() ? 0 : 60))+'px';
        // this.modalIframe.style.minWidth = "100%";
        // this.modalIframe.style.width = "0";
    }
}

/**
 * Resizes list widget iframe
 */
ums.resizeWidget = function(){
    if (this.type === 'list') {
        var padding = parseInt(window.getComputedStyle(this.div).paddingLeft) + parseInt(window.getComputedStyle(this.div).paddingRight);
        var iFrame = this.div.firstChild;

        // this is only for the Iframe with the list inside
        if (this.div.style.overflow == 'hidden') {
            iFrame.style.width = (this.div.clientWidth-padding) + 'px';
        }
    }
}

/**
 * Used to make ajax calls
 * @param  string   url
 * @param  function callback
 * @param  object   data
 */
ums.ajax = function (url, callback, data) {
    try {
        var x = new(XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
        x.open(data ? 'POST' : 'GET', url, true);
        x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        x.onreadystatechange = function () {
            x.readyState > 3 && callback && callback(x.responseText, x);
        };
        x.send(data)
    } catch (e) {
        window.console && console.log(e);
    }
}

/**
 * Loads ajax widget (float or fixed)
 * @param  string url
 */
ums.loadAJAXWidget = function(url) {
    var me = this;
    this.ajax(url, function(data) {
    
        if (url.search('float') == -1) {
            me.div.innerHTML = data;
        } else {
            me.newDiv.innerHTML = data;
        }
    });
}

/**
 * Loads all needed css files in client DOM
 */
ums.loadAJAXCss = function() {

    var cssResources = [
        'base.css',
        'global.css',
        'widget/widget.css',
        // 'jquery/magnific-popup.css'
    ]

    for (var ci = 0; ci < cssResources.length; ci++) {
        var link = document.createElement('link');
        // https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
        link.crossorigin = 'anonymous';
        link.rel = 'stylesheet';
        link.type = 'text/css';
        link.href = "https://www.upmyshop.com/css/"+cssResources[ci]
        document.getElementsByTagName('head')[0].appendChild(link);
    }

    /*
    {% stylesheets
        '@CLabsWidgetBundle/Resources/public/css/base.css'
        '@CLabsWidgetBundle/Resources/public/css/global.css'
        '@CLabsWidgetBundle/Resources/public/css/widget/widget.css'
        '@CLabsWidgetBundle/Resources/public/css/jquery/*'
        filter='cssrewrite'
            %}

    var link = document.createElement('link');
    // https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
    link.crossorigin = 'anonymous';
    link.rel = 'stylesheet';
    link.type = 'text/css';
    link.href = "https://"+"www.upmyshop.com"+"{{ asset_url }}"
    document.getElementsByTagName('head')[0].appendChild(link);

    {% endstylesheets %}
*/
    var googleFonts = document.createElement('link');
    // https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
    googleFonts.crossorigin = 'anonymous';
    googleFonts.rel = 'stylesheet';
    googleFonts.type = 'text/css';
    googleFonts.href = "https://fonts.googleapis.com/css?family=Open+Sans:400,600,700"

    document.getElementsByTagName('head')[0].appendChild(googleFonts);
}

ums.insertJSONLD = function() {
    this.ajax("https://www.upmyshop.com/widget/json-ld/"+this.apiKey+(this.externalVenueId?'/'+this.externalVenueId:''), function(data) {
        var div = document.createElement('div');
        div.innerHTML = data.trim();
        if (div.firstChild) {
            document.getElementsByTagName('head')[0].appendChild(div.firstChild);
        }
    });
}

/**
 * Inits float widget
 * @param  {string} id        id of div (not used here anymore)
 * @param  {string} env       environment (not used here anymore)
 * @param  {string} hPosition left or right
 * @param  {string} vPosition top or bottom
 */
ums.initFloat = function(id, env, hPosition, vPosition){
    var d = document;
    var w = d.createElement('div');
    var newDivCreated = d.createElement('div');
    div = 'floatumsdiv';
    newDiv = 'ums-div';
    w.setAttribute('id', div);
    w.setAttribute('class', 'floatwidget '+hPosition+' '+vPosition);
    newDivCreated.setAttribute('id', newDiv);
    newDivCreated.setAttribute('class', 'floatwidget '+hPosition+' '+vPosition);
    newDivCreated.setAttribute('style', 'position : fixed; '+hPosition+' : 0; '+vPosition+' : 0; z-index: 1000; letter-spacing: initial !important; font-size: initial; font-family: inherit; line-height: initial; -webkit-font-smoothing: initial; -moz-osx-font-smoothing: initial !important;');
    this.div = w;
    this.newDiv = newDivCreated;
    document.getElementsByTagName('body')[0].appendChild(w);
    document.getElementsByTagName('body')[0].appendChild(newDivCreated);

    this.loadAJAXCss();
    this.loadAJAXWidget(ums.getUrl('float', ['hPosition='+hPosition, 'vPosition='+vPosition]));
    ums.createIframeModal();
}

/**
 * Returns url of a type of widget
 * @param  {string} route list|float|fixed
 * @return {string}       Url
 */
ums.getUrl = function(route, addParams) {
    var params = [];
    if (typeof addParams != 'undefined') {
        params = addParams;
    }
    if (route === 'list') {
        params.push('inlinelist=true');
    }
    params.push('_locale='+this.locale);
    var metaKeys = [];
    var metaValues = [];
    if(this.metadata !== undefined && this.metadata){
        metaKeys = this.metadata.keys();
        metaValues = this.metadata.values();
    }

    return this.protocol + '://' + "www.upmyshop.com" + '/widget/widget/' + route + '/' + this.apiKey + (this.externalVenueId ? '/' + this.externalVenueId : '') + (this.metadata !== undefined && this.metadata ? '/'+ metaKeys.join(',')+'/'+ metaValues.join(',') : '') + '?' + params.join('&');
}

/**
 * Inits fixed widget
 * @param  {string} div id of div
 * @param  {string} id  (not used anymore)
 * @param  {string} env environment (not used here anymore)
 */
ums.initFixed = function(div, id, env){
    var d = document;
    this.div = d.getElementById(div);
    this.div.style.textAlign = 'center';
    this.loadAJAXCss();
    this.loadAJAXWidget(ums.getUrl('fixed'));

    ums.createIframeModal();
}

/**
 * Inits fixed widget
 * @param  {string} div id of div
 * @param  {string} id  (not used anymore)
 * @param  {string} env environment (not used here anymore)
 */
ums.initList = function(div, id, env){
    this.loadAJAXCss();
    var d = document;
    var w = d.getElementById(div);
    this.div = w;
    var i = d.createElement('iframe');

    i.src=ums.getUrl('list');
    i.style.height = '0px';
    i.setAttribute('name', 'umsmain');
    i.className = 'ums-frame';

    w.style.overflow = 'hidden';
    i.style.width = '100%';
    i.style.border = 'none';
    i.setAttribute('scrolling', "no");
    i.setAttribute('frameborder', "0");
    i.setAttribute('allowtransparency', "1");
    var me = this;

    i.onload = function() {
        i.contentWindow.postMessage("global:"+window.location.hostname, 'https://'+"www.upmyshop.com");
        ums.createIframeModal(true);
    };
    w.appendChild(i);
    this.div = w;
    this.iframe = i;
}

/**
 * Inits fixed widget
 * @param  {string} div id of div
 * @param  {string} id  (not used anymore)
 * @param  {string} env environment (not used here anymore)
 */
ums.initSelect = function(div, id, env){
    this.loadAJAXCss();
    var d = document;
    var w = d.getElementById(div);
    this.div = w;
    var i = d.createElement('iframe');

    i.src=ums.getUrl('select');
    i.style.height = '0px';
    i.setAttribute('name', 'umsmain');
    i.className = 'ums-frame';

    w.style.overflow = 'hidden';
    i.style.width = '100%';
    i.style.border = 'none';
    i.setAttribute('scrolling', "no");
    i.setAttribute('frameborder', "0");
    i.setAttribute('allowtransparency', "1");
    var me = this;

    i.onload = function() {
        i.contentWindow.postMessage("global:"+window.location.hostname, 'https://'+"www.upmyshop.com");
        ums.createIframeModal(true);
    };
    w.appendChild(i);
    this.div = w;
    this.iframe = i;
}

/**
 * Created modal with Up Form or List iframe inside
 * @param  {Boolean} isList true|false
 */
ums.createIframeModal = function(isList) {
    var d = document;
    if(typeof isList == 'undefined') {
        isList = false;
    }

    var overlay = d.createElement('div');
    overlay.className = 'ums-overlay';
    overlay.style.display = 'block';
    overlay.style.top = '10000px';
    overlay.style.zindex = 100;
    overlay.style['position']= 'fixed';
    overlay.style['right']= 0;
    overlay.style['bottom']= 0;
    overlay.style['left']= 0;
    overlay.style['-webkit-overflow-scrolling'] = 'touch';
    overlay.style['overflow-y'] = 'scroll';
    overlay.style['z-index'] = 100000; //Wordpress hack

    var spinner = d.createElement('div');
    spinner.style['position']= "absolute";
    spinner.style['height']= "100%";
    spinner.style['width']= "100%";
    spinner.style['backgroundPosition']= "center center";
    spinner.style['backgroundSize']= "100px";
    spinner.style['backgroundRepeat']= "no-repeat";

    //{% image '@CLabsWidgetBundle/Resources/public/images/loader.gif' %}
    //todo add spinner
    spinner.style['backgroundImage']= "url('https://www.upmyshop.com/images/loader.gif";
    //{% endimage %}

    overlay.appendChild(spinner);


    var modal = d.createElement('div');
    modal.style.display = 'block';
    modal.className = 'ums-modal' + (this.isMobile() ? ' ums-mobile' : '');

    var modalCloseButton = d.createElement('span');
    modalCloseButton.className = 'ums-modal-closer';
    var closeLink = d.createElement('a');
    closeLink.innerHTML = 'Fermer x';
    closeLink.href = "#";
    modalCloseButton.appendChild(closeLink);

    var modalIframe = d.createElement('iframe');
    modalIframe.name = 'ums-modal-iframe';
    modalIframe.className = 'ums-modal-iframe';
    // modalIframe.style.height = (window.innerHeight - (this.isMobile() ? 0 : 60))+'px';
    modalIframe.style.width = '100%';
    modalIframe.style.height = '100%';
    modalIframe.style.overflowY = 'hidden';
    modalIframe.scrolling = 'no';

    // Load it for SEO
    modalIframe.src = ums.getIframeModalUrl();

    var me = this;
    this.modalIframeLoaded = false;


    modalIframe.onload = function() {
        if (modalIframe.src) {
            me.modalIframeLoaded = true;
            modalIframe.style.width = '100%';
            modalIframe.style.height = '100%';
            modalIframe.contentWindow.postMessage("global:" + window.location.hostname, ums.protocol + '://' + "www.upmyshop.com");
        }
    }
    overlay.onclick = function() {
        document.getElementsByTagName('html')[0].style = 'overflow-y: scroll;';
        me.closeModal("www.upmyshop.com");
        return false;
    }
    // {#modalIframe.src = 'https://'+"www.upmyshop.com"+'/widget/widget/'+(ums.type == 'list' ? 'select' : 'list' )+'/'+ums.apiKey+'?_locale='+ums.locale + (ums.externalVenueId ? '&externalvenueid='+ums.externalVenueId : '') + (ums.type == 'list' ? '&inlinelist=true' : '' );#}

    modal.appendChild(modalCloseButton);

    if (modalCloseButton.parentElement.className == 'ums-modal ums-mobile') {
        closeLink.innerHTML = 'x';
    }

    modal.appendChild(modalIframe);
    overlay.appendChild(modal);

    this.modal = modal;
    this.modalIframe = modalIframe;
    this.closeLink = closeLink;
    this.modalCloseButton = modalCloseButton;
    this.overlay = overlay;

    document.getElementsByTagName('body')[0].appendChild(overlay);
}

ums.saveStat = function() {
    var me = this;
    this.ajax(this.getUrl('stat'), function(data) {
    }, []);
}

ums.saveRealStat = function() {
    var me = this;
    this.ajax(this.getUrl('realstat'), function(data) {
    }, []);
}

var uniqueRealView = false

ums.statOnScroll = function() {
    var element = document.getElementById(divWidgetId);
    if(element !== null) {
        var position = element.getBoundingClientRect();
        if(position.top - (window.innerHeight*2/3) < 0 && !uniqueRealView) {
            uniqueRealView = true;
            try {
                ums.saveRealStat();
            } catch (e) {
                window.console && console.log(e);
            }
        }
    }
}

ums.init = function(fn, div, id, env, type, hPosition, vPosition, externalVenueId, lang, metadata){
    divWidgetId = div;
    if(type === "list" || type === "fixed")
    {
        me = this;
        window.addEventListener("scroll", me.statOnScroll, false);
    }

    if(typeof type == 'undefined') {
        type = 'list';
    }
    if(typeof hPosition == 'undefined' || hPosition === '') {
        hPosition = 'right';
    }
    if(typeof vPosition == 'undefined' || vPosition === '') {
        vPosition =  'bottom';
    }

    this.apiKey = id;
    this.type = type;
    this.externalVenueId = typeof externalVenueId === 'undefined' ? null : externalVenueId;
    this.metadata = typeof metadata === 'undefined' ? null : metadata;

    var host = "www.upmyshop.com";
    HOST = host;
    this.protocol = 'https';
    var locale = typeof lang != 'undefined' && lang.length >= 2 ? lang : (document.getElementsByTagName('html').length > 0 && typeof document.getElementsByTagName('html')[0]['attributes']['lang'] != 'undefined' && document.getElementsByTagName('html')[0]['attributes']['lang'].value ? document.getElementsByTagName('html')[0]['attributes']['lang'].value : window.navigator.userLanguage || window.navigator.language);
    this.locale = locale.substring(0, 2);

    var d = document;
    var s = d.createElement('link');
    var w = d.getElementById(div);
    // https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
    s.crossorigin = 'anonymous';
    s.type = "text/css";
    s.rel = "stylesheet";

    // {# stylesheets '@CLabsWidgetBundle/Resources/public/css/widget/widget.css' filter='cssrewrite' %}
    // s.href = 'https://'+host+'{{ asset_url }}';
    // {% endstylesheets #}

    document.getElementsByTagName('head')[0].appendChild(s);

    var s2 = d.createElement('link');
    // https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity
    s2.crossorigin = 'anonymous';
    s2.type = "text/css";
    s2.rel = "stylesheet";

    // {# stylesheets '@CLabsWidgetBundle/Resources/public/css/*' filter='cssrewrite' %}
    // s2.href = 'https://'+host+'{{ asset_url }}';
    // {% endstylesheets #}

    document.getElementsByTagName('head')[0].appendChild(s2);

    switch (type) {
        case 'list':
            this.initList(div, id, env);
            break;
        case 'select':
            this.initSelect(div, id, env);
            break;
        case 'float':
            this.initFloat(id, env, hPosition, vPosition);
            this.insertJSONLD();
            this.saveStat();
            this.saveRealStat();
            break;
        default:
            this.initFixed(div, id, env);
            this.insertJSONLD();
            this.saveStat();
            break;
    }

    this.div = w;
    this.iframe = i;
    var me = this;

    window.onresize = function() {
        me.resize();
    }


    window.addEventListener("message", function(e){
        var data = e.data.split(':'),
            value = null,
            action = null;
        if(data.length >= 1)
        {
            action = data[0];
            if(data.length >= 2){
                value = data[1];
            }
        }
        else{
            return false;
        }
        switch(action){
            case 'showUpModal':
                var url = ums.getIframeModalUrl();
            // {#ums.modalIframe.src = +'?_locale='+ums.locale + (ums.externalVenueId ? '&externalvenueid='+ums.externalVenueId : '') + (ums.type == 'list' ? '&inlinelist=true' : '' );#}
                ums.modalIframe.src = url;
            // {#ums.modalIframe.onload = function() {#}
            //     {#ums.modalIframe.style.width = '100%';#}
            //     {#ums.modalIframe.style.height = '100%';#}
            //     {#}#}

                ums.overlay.style.top = '0px';
                document.getElementsByTagName('html')[0].style= "overflow-y: hidden";

                if(ums.isMobile())
                {
                    ums.oldviewport = document.querySelector("meta[name=viewport]");
                    if(ums.oldviewport){
                        ums.oldviewport.parentElement.removeChild(ums.oldviewport);
                    }
                    var metaTag=document.createElement('meta');
                    metaTag.name = "viewport";
                    metaTag.content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no";
                    document.getElementsByTagName('head')[0].appendChild(metaTag);

                    window.scrollTo(0,0);
                }

                me.resizeModal();
                break;

            case 'closeModal':
                me.closeModal(host);
                break;

            case 'updateHeight':
                var height = parseInt(value) + 50;
                ums.modalIframe.style.height = height+'px';
                break;
            case 'updateListHeight':
                var height = parseInt(value) + 50;
                if (type == 'list' || type == 'select') {
                    document.getElementsByClassName('ums-frame')[0].style.height = height+'px';
                    document.getElementById(div).style.height = height+'px';
                    w.style.height = height+'px';
                }
                break;
            case 'hideIframe':
                if (type == 'list') {
                    document.getElementById(div).style.display = 'none';
                }
                break;
        }
    });

};

ums.getIframeModalUrl = function()
{
    var url = 'https://www.upmyshop.com/widget/widget/'+(ums.type == 'list' ? 'select' : 'list' )+'/'+ums.apiKey;
    if (ums.externalVenueId) {
        if (ums.type == 'list') {
            url = url + '?inlinelist=true&externalvenueid=' + ums.externalVenueId + '&_locale='+ums.locale;
        } else {
            url = url + '/' + ums.externalVenueId + '?_locale='+ums.locale;
        }
    }
    return url + (url.indexOf('?') !== -1 ? '&' : '?') + 'modal=true'; // we add modal parameter to see if we need to inverse the process or not depending on widget parameters (in controller)
}

/**
 * Closes modal (called from iframe message)
 * @param  {string} host
 */
ums.closeModal = function(host) {
    if(this.isMobile())
    {
        var vp = document.querySelector("meta[name=viewport]");
        vp.parentElement.removeChild(vp);
        if(ums.oldviewport){
            document.getElementsByTagName('head')[0].appendChild(ums.oldviewport);
        }

    }
    this.overlay.style.position = 'fixed';
    this.overlay.style.top = '10000px';
    this.modalIframe.style.width = '0px';
    this.modalIframe.style.height = '0px';

    return false;
}

// Wait until script is loaded and interpreted
if(typeof ums != 'undefined' && typeof ums.queue != 'undefined' && ums.queue.length > 0)
{
    for(var i = 0; i < ums.queue.length; i++)
    {
        ums[ums.queue[i][0]].apply(ums, ums.queue[i]);
    }
}

/**
 * Used by float and fixed widgets to show list in popup
 */
function showListAction() {
    var protocol = window.location.href.split('/');
    // parent.postMessage("showUpModal:true", 'https://'+window.location.hostname);
    parent.postMessage("showUpModal:true", protocol[0]+'//'+window.location.hostname);
}