'use strict';
if ( !sigallery_embed && typeof sigallery == 'undefined' ) {
    var sigallery_embed = ( function() {

        //Add Post Message Event Listener
        window.addEventListener('message', function(e) {
            var message = e.data;
            if ( message.hasOwnProperty('usatsi_gallery') ) {
               var gallery_el = document.getElementById('sigallery-wrapper-' + message.usatsi_gallery.gallery_id);
                if ( !document.getElementById('sigallery-modal-dialog') ||  document.getElementById('sigallery-modal-dialog').style.display === 'none' ) {
                    enter_flyout_mode(message);
                }
            }
            if ( message.hasOwnProperty('usatsi_gallery_orientation') ) {
                console.log(message.usatsi_gallery_orientation.gallery_id);
                getScreenSize();
                if (screen_width <= 1024){
                    document.getElementById('sigallery-modal-close-btn').click();
                    document.getElementById('sigallery-fs-btn-' + message.usatsi_gallery_orientation.gallery_id).click();
                }
            }
        });

        var is_touch_device = function() {
            return (('ontouchstart' in window)
            || (navigator.MaxTouchPoints > 0)
            || (navigator.msMaxTouchPoints > 0));
        };



        var DOMAIN = '//development.imagn.com';

        //Serialze usatsi_gallery_options as query params!
        var serialize = function(obj) {
            var str = [];
            for(var p in obj)
                if (obj.hasOwnProperty(p)) {
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                }
            return str.join("&");
        };

        //Utag data for tealium tracking!
        var utag_data_params = '';
        //Lawrence options for tracking and ads!
        var lawrence_options_params = '';

        //Deep linking - Check for _escaped_fragement_ param
        var getParameterByName = function(name) {
            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
                results = regex.exec(location.search);
            return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        };

        var removeParam = function(key, sourceURL) {
            var rtn = sourceURL.split("?")[0],
                param,
                params_arr = [],
                queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
            if (queryString !== "") {
                params_arr = queryString.split("&");
                for (var i = params_arr.length - 1; i >= 0; i -= 1) {
                    param = params_arr[i].split("=")[0];
                    if (param === key) {
                        params_arr.splice(i, 1);
                    }
                }
                if (params_arr.length > 0 ) {
                    rtn = rtn + "?" + params_arr.join("&");
                }

            }
            return rtn;
        };

        var deeplink_query = '';
        var escaped_fragment = getParameterByName('_escaped_fragment_');
        var share_url = removeParam('_escaped_fragment_', document.location.href);

        if ( escaped_fragment !== '' ) {
            if ( escaped_fragment.indexOf('sigallery') > -1 ) {
                share_url = encodeURIComponent(share_url);
                var deeplink_photo_id = escaped_fragment.split('-');
                deeplink_photo_id = deeplink_photo_id[ deeplink_photo_id.length-1 ];

                deeplink_query = '&deeplink=true&deeplink_photo_id=' + deeplink_photo_id + '&share_url=' + share_url;
            }

        } else {
            share_url = document.location.href;
            deeplink_query = '&share_url=' + share_url;

        }

        var iframe_src = '',
            iframe_orig = '',
            iframe_el = '',
            screen_width = 1280,
            screen_height = 1050,
            image_width = 600,
            image_height = 450,
            galleries = [],
            gallery_count = 0,
            ga_analytics_params = '',
            gaid = '',
            originating_parent_container = {};

        // Modal Overlay Elements!
       var overlay_el = document.createElement('div');
        overlay_el.setAttribute('id', 'sigallery-modal-overlay');
        overlay_el.setAttribute('class', 'sigallery-modal-overlay');

        // Modal Overlay Elements!
       var overlay_article_el = document.createElement('div');
        overlay_article_el.setAttribute('id', 'sigallery-modal-article-overlay');
        overlay_article_el.setAttribute('class', 'sigallery-modal-article-overlay');


        var overlay_close_btn = document.createElement('div');
            overlay_close_btn.setAttribute('id', 'sigallery-modal-close-btn');
            overlay_close_btn.setAttribute('class', 'sigallery-modal-close-btn');

        var overlay_close_btn_trans = document.createElement('a');
            overlay_close_btn_trans.setAttribute('id', 'sigallery-modal-close-btn-trans');
            overlay_close_btn_trans.setAttribute('class', 'sigallery-modal-close-btn-trans');


            overlay_close_btn_trans.addEventListener('click', function(e) {
                e.stopPropagation();
                exit_fullscreen(e);
            });

            if (!is_touch_device()) {
                overlay_close_btn_trans.addEventListener('touchend', function (e) {
                    e.stopPropagation();
                    exit_fullscreen(e);
                });
            }


        var dialog_el = document.createElement('div');
        dialog_el.setAttribute('id', 'sigallery-modal-dialog');
        dialog_el.setAttribute('class', 'sigallery-modal-fullscreen');

        var dialog_content_el = document.createElement('div');
        dialog_content_el.setAttribute('id', 'sigallery-modal-dialog-content');
        dialog_content_el.setAttribute('class', 'sigallery-modal-dialog-content');

        // Create Stylesheet Element!
        var appendCss = function(galleryid) {
            var ss = document.createElement('link');
                ss.type = 'text/css';
                ss.rel = 'stylesheet';
                ss.href= DOMAIN + '/galleries/css/sigallery_embed.css';
            document.getElementsByTagName('head')[0].appendChild(ss);
            sigalleries(galleryid);
        };

        // Enter Fullscreen!
        var enter_fullscreen = function(e) {
            e.stopPropagation();
            //If gallery is in modal/flyout mode then exit flyout first
            if ( e.currentTarget.parentElement.getAttribute('data-modal') ) {
                if ( e.currentTarget.parentElement.getAttribute('data-modal') == 'true' && screen_width >= 1024 && screen.width > 1024) {
                    exit_flyout_mode(e);
                }
            }

            var gallery_id = e.currentTarget.getAttribute('data-gallery-id');

            var iframe_fullscreen_src = DOMAIN + '/galleries/#/gallery/%s?thumbs=1&modal=true&fullscreen=true&width=' + screen_width + '&height=' + window.innerHeight + ga_analytics_params + lawrence_options_params + utag_data_params  + deeplink_query;
                iframe_fullscreen_src = iframe_fullscreen_src.replace('%s', gallery_id);

            var iframe_fullscreen_html = document.createElement('iframe');
                iframe_fullscreen_html.setAttribute( 'scrolling', 'no' );
                iframe_fullscreen_html.setAttribute( 'frameborder', '0' );
                iframe_fullscreen_html.setAttribute( 'style', 'border: none; margin: 0; padding: 0; overflow: hidden;height: 100%; width: 100%;' );

            create_model_overlay();

            generateIframe( dialog_content_el, iframe_fullscreen_html, iframe_fullscreen_src, 'sigallery-modal-dialog-content' );

        };

        var getClosest = function ( elem, selector ) {

            // Element.matches() polyfill
            if (!Element.prototype.matches) {
                Element.prototype.matches =
                    Element.prototype.matchesSelector ||
                    Element.prototype.mozMatchesSelector ||
                    Element.prototype.msMatchesSelector ||
                    Element.prototype.oMatchesSelector ||
                    Element.prototype.webkitMatchesSelector ||
                    function(s) {
                        var matches = (this.document || this.ownerDocument).querySelectorAll(s),
                            i = matches.length;
                        while (--i >= 0 && matches.item(i) !== this) {}
                        return i > -1;
                    };
            }

            // Get closest match
            for ( ; elem && elem !== document; elem = elem.parentNode ) {
                if ( elem.matches( selector ) ) return elem;
            }

            return null;

        };

        var create_model_overlay = function(type, galleryId) {
            var isWordpress = true;

            var scripts = document.getElementsByTagName('script');
            for (var i = scripts.length; i--;) {
                if (scripts[i].getAttribute("data-oembed") == "true") {
                    var isWordpress = false;
                }
            }

            if ( !document.getElementById('sigallery-modal-overlay') ) {
                overlay_el.setAttribute('style', 'width: ' + screen_width + 'px;height: ' + screen_height +'px;');
                document.body.appendChild(overlay_el);


                
                if (isWordpress == false){
                    document.getElementById('sigallery-modal-overlay').style.display = 'none';

                    var elem = document.querySelector('#sigallery-wrapper-' + galleryId);
                    var closestElem = getClosest(elem, 'article');
                    if (closestElem != null)
                        closestElem.appendChild(overlay_article_el);
                }
                else
                    document.getElementById('sigallery-modal-overlay').style.display = 'block';

                if ( type === 'flyout' ) {
                    overlay_close_btn.setAttribute('style', 'display: none;');
                    overlay_close_btn_trans.setAttribute('style', 'display: none;');
                    dialog_el.setAttribute('style', 'display: none');
                } else {
                    overlay_close_btn.setAttribute('style', 'display: block;');
                    overlay_close_btn_trans.setAttribute('style', 'display: block;');
                    dialog_el.setAttribute('style', 'display: block');
                }

                document.body.appendChild(overlay_close_btn);
                document.body.appendChild(overlay_close_btn_trans);
                document.body.appendChild(dialog_el);
                document.getElementById('sigallery-modal-dialog').appendChild(dialog_content_el);


            } else {
                if (isWordpress == false){
                    document.getElementById('sigallery-modal-overlay').style.display = 'none';

                    if (document.getElementById('sigallery-modal-article-overlay') !== null)
                        document.getElementById('sigallery-modal-article-overlay').style.display = 'block';
                    else{
                        var elem = document.querySelector('#sigallery-wrapper-' + galleryId);
                        var closestElem = getClosest(elem, 'article');
                        if (closestElem != null)
                            closestElem.appendChild(overlay_article_el);

                        if (document.getElementById('sigallery-modal-article-overlay') !== null)
                            document.getElementById('sigallery-modal-article-overlay').style.display = 'block';                    
                    }

                }
                else
                    document.getElementById('sigallery-modal-overlay').style.display = 'block';



                if ( type !== 'flyout') {
                    document.getElementById('sigallery-modal-overlay').style.display = 'block';
                    document.getElementById('sigallery-modal-dialog').style.display = 'block';
                    document.getElementById('sigallery-modal-close-btn').style.display = 'block';
                    document.getElementById('sigallery-modal-close-btn-trans').style.display = 'block';
                }
            }

            if ( type === 'flyout' ) {
                document.getElementById('sigallery-modal-overlay').setAttribute('class','sigallery-flyout-overlay');
                if (isWordpress == false){
                    if (document.getElementById('sigallery-modal-article-overlay') !== null)
                        document.getElementById('sigallery-modal-article-overlay').setAttribute('class','sigallery-flyout-article-overlay');
                }
                //document.getElementById('sigallery-modal-dialog').setAttribute('class','sigallery-flyout-modal');
                //document.getElementById('sigallery-modal-dialog-content').setAttribute('class','sigallery-modal-dialog-content sigallery-flyout')
            }


        };

        var exit_fullscreen = function(e) {
            document.getElementById('sigallery-modal-overlay').style.display = 'none';
            if (document.getElementById('sigallery-modal-article-overlay') !== null)
                document.getElementById('sigallery-modal-article-overlay').style.display = 'none';
            document.getElementById('sigallery-modal-dialog').style.display = 'none';
            document.getElementById('sigallery-modal-close-btn').style.display = 'none';
            document.getElementById('sigallery-modal-close-btn-trans').style.display = 'none';
            document.getElementById('sigallery-modal-dialog-content').innerHTML = '';
        };

        window.linker;
        var add_iframe_ga = function(divId, url, opt_hash, gallery_container_el, iframe_el, element_id) {

            return function(tracker) {

                window.linker = window.linker || new window.gaplugins.Linker(tracker);
                var iFrame = iframe_el;
                iFrame.src = window.linker.decorate(url, opt_hash);
                gallery_container_el.appendChild(iFrame);
            };
        };

        var add_iframe = function( gallery_container_el, iframe_el, iframe_src, element_id  ) {
            var iFrame = iframe_el;
            iFrame.src = iframe_src;
            gallery_container_el.appendChild( iframe_el );
        };


        // Embeds the Gallery
        var sigalleries = function(galleryid) {

            getScreenSize();

            if (galleryid) {
                galleries = document.querySelectorAll('[data-gallery-id="' + galleryid + '"]');
            } else {
                galleries = document.getElementsByClassName('sigallery');
            }

            var embed_html = '';

            for ( var i=0; i<galleries.length; i++ ) {

                //Set Custom Options if any and create query string to pass in iframe URL
                var options_array = [];
                var options_query = '';
                var gallery_options = {};
                if ( galleries[i].hasAttribute('data-gallery-options') ) {
                    gallery_options = JSON.parse(galleries[i].getAttribute('data-gallery-options'));
                    for ( var key in gallery_options ) {
                        if ( gallery_options.hasOwnProperty(key) ) {
                            options_array.push( encodeURIComponent( key ) + "=" + encodeURIComponent( gallery_options[key] ) );
                        }
                    }

                    options_query = '&' + options_array.join('&');
                }
  

                //Adjust size of gallery
                var aryResults =  calculateGallerySize( galleries[i], gallery_options );
                var container_styles = aryResults[0];
                var marginoff = aryResults[1];
                galleries[i].setAttribute('style', container_styles);

                //Google Analytics ID!
                if ( galleries[i].hasAttribute('data-gaid') ) {
                    gaid = galleries[i].getAttribute('data-gaid');
                    // If no lawrence params we assume its not a site on Lawrence and pass in google ga params for tracking
                    if ( lawrence_options_params === '' ) {
                        ga_analytics_params = '&ga_id=' + gaid;
                    }
                }

                var gallery_id = galleries[i].getAttribute('data-gallery-id');

                var gallery_mode_param = '';

                if ( galleries[i].getAttribute('data-modal') === 'true' && screen_width > 1024 && screen.width > 1024) {
                    gallery_mode_param = '&type=modal';

                    if ( galleries[i].getAttribute('data-modal-dir') ) {
                        gallery_mode_param = gallery_mode_param  + '&dir=' + galleries[i].getAttribute('data-modal-dir');
                    }
                }
                image_width += marginoff * -2;
                iframe_src = DOMAIN + '/galleries/#/gallery/%s?thumbs=1&width=' + image_width + '&height=' + image_height + gallery_mode_param + options_query + ga_analytics_params +  lawrence_options_params + utag_data_params + deeplink_query;
                iframe_src = iframe_src.replace(/%s/g, gallery_id);
                var iframe_html = document.createElement('iframe');
                    iframe_html.setAttribute( 'scrolling', 'no' );
                    iframe_html.setAttribute( 'frameborder', '0' );
                    iframe_html.setAttribute( 'style', 'border: none; margin: 0; padding: 0; overflow: hidden;height: 100%; width: 100%;' );
                    iframe_html.setAttribute( 'id', 'sigallery_iframe_' + gallery_id);
                var element_id = galleries[i].getAttribute('data-gallery-id');

                // Create Enter Full Screen Button
                var fullscreen_btn_el = document.createElement('a');
                    fullscreen_btn_el.setAttribute('data-gallery-id', gallery_id);
                    fullscreen_btn_el.setAttribute('title', 'Fullscreen');

                    var fs_btn_el_class = 'sigallery-fs-btn';
                    if ( galleries[i].getAttribute('data-modal-dir') ) {
                        fs_btn_el_class = fs_btn_el_class + ' ' + galleries[i].getAttribute('data-modal-dir');
                    }
                    fullscreen_btn_el.setAttribute('class', fs_btn_el_class);

                    fullscreen_btn_el.setAttribute('id', 'sigallery-fs-btn-' + gallery_id);
                    fullscreen_btn_el.addEventListener('click', function(e) {
                            enter_fullscreen(e);
                    });
                    if (!is_touch_device()) {
                        fullscreen_btn_el.addEventListener('touchend', function(e) {
                            enter_fullscreen(e);
                        });
                    }

                    galleries[i].appendChild(fullscreen_btn_el);

                if ( galleries[i].getAttribute('data-modal') === 'true' && screen_width > 1024 && screen.width > 1024) {

                    galleries[i].setAttribute('class', 'sigallery sigallery-modal');

                    //hide inline fullscreen button before modal is launched
                    fullscreen_btn_el.setAttribute('style','display: none;');


                    var flyout_btn_close_el = document.createElement( 'a' );
                        flyout_btn_close_el.setAttribute( 'data-gallery-id',  galleries[i].getAttribute('data-gallery-id') );
                        flyout_btn_close_el.setAttribute( 'title',  'Close Gallery' );

                        var el_close_btn_class = 'sigallery-flyout-close-btn';
                        if ( galleries[i].getAttribute('data-modal-dir') ) {
                            el_close_btn_class = el_close_btn_class + ' ' + galleries[i].getAttribute('data-modal-dir');
                        }
                        flyout_btn_close_el.setAttribute( 'class', el_close_btn_class );
                        flyout_btn_close_el.setAttribute( 'id', 'sigallery-flyout-close-btn-' + gallery_id);
                        flyout_btn_close_el.addEventListener( 'click', function(e) {
                           exit_flyout_mode(e);
                        });
                        galleries[i].appendChild( flyout_btn_close_el );

                        //hide inline fullscreen button before modal is launched
                        flyout_btn_close_el.setAttribute( 'style', 'display: none');

                }

                embed_html = iframe_html;

                generateIframe( galleries[i], embed_html, iframe_src, element_id );

                embed_html = '';

            };
        };

        var exit_flyout_mode = function(e) {

            if ( e.currentTarget.parentElement.getAttribute('class').indexOf('sigallery-modal') ) {
                var arrowLeft = document.getElementsByClassName("overlay-content-arrows")[0];
                if (arrowLeft !== undefined)
                    arrowLeft.style.zIndex = 120;

                var arrowRight = document.getElementsByClassName("overlay-content-arrows")[1];
                if (arrowRight !== undefined)
                    arrowRight.style.zIndex = 120;
                
                var close = document.getElementsByClassName("close-wrap")[0];
                if (close !== undefined)    
                    close.style.display = "block";      

                var gallery_id = e.currentTarget.getAttribute( 'data-gallery-id');
                var gallery_iframe_el = document.getElementById( 'sigallery_iframe_' + gallery_id);
                var gallery_height = e.currentTarget.parentElement.clientHeight;

                gallery_iframe_el.src = gallery_iframe_el.src.replace('flyout_active', 'flyout_inactive');
                e.currentTarget.parentElement.setAttribute('style',
                    'position: relative;' +
                    'border: none;' +
                    'margin: 0;' +
                    'padding: 0;' +
                    'overflow: hidden;' +
                    'height: ' + gallery_height + 'px;' +
                    'max-height: 707px;'
                );
                exit_fullscreen();

            }

        };

        var enter_flyout_mode = function(e) {
            var gallery_id = e.usatsi_gallery.gallery_id;


            var arrowLeft = document.getElementsByClassName("overlay-content-arrows")[0];
            if (arrowLeft !== undefined)
                arrowLeft.style.zIndex = 99;

            var arrowRight = document.getElementsByClassName("overlay-content-arrows")[1];
            if (arrowRight !== undefined)
                arrowRight.style.zIndex = 99;
            
            var close = document.getElementsByClassName("close-wrap")[0];
            if (close !== undefined)    
                close.style.display = "none";           

            create_model_overlay( 'flyout' , gallery_id );

            var gallery_element = document.getElementById('sigallery-wrapper-' + e.usatsi_gallery.gallery_id);
            var gallery_index = e.usatsi_gallery.current_slide;

            var gallery_width = gallery_element.clientWidth;
            var gallery_height = gallery_element.clientHeight;
            var flyout_width = 338;
            var flyout_height = gallery_height;
            var gallery_total_width = gallery_width + flyout_width;
            var gallery_left_offset = ( (window.outerWidth - gallery_total_width) / 2 );
            var gallery_top_offset = ( (window.innerHeight - gallery_height) / 2 );


            var gallery_iframe_el = document.getElementById( 'sigallery_iframe_' + gallery_id);

            //Updates the hash on the URL that the gallery is listening for!
            if ( gallery_iframe_el.src.indexOf('flyout_inactive') != -1 ) {
                gallery_iframe_el.src = gallery_iframe_el.src.replace('flyout_inactive', 'flyout_active');
                var new_string = gallery_iframe_el.src.substring( 0, gallery_iframe_el.src.lastIndexOf('_'));
                gallery_iframe_el.src = new_string + '_' + gallery_index;
            } else {
                var gallery_src_hash = gallery_iframe_el.src + '#flyout_active_' + gallery_width + '_' + gallery_height + '_' + gallery_index;
                document.getElementById( 'sigallery_iframe_' + gallery_id).src = gallery_src_hash;
            }   

                //Show close button and full screen buttons
                if ( document.getElementById('sigallery-flyout-close-btn-' + gallery_id) ) {
                    document.getElementById('sigallery-flyout-close-btn-'+ gallery_id).setAttribute('style', 'display: block');
                }

                document.getElementById('sigallery-fs-btn-'+ gallery_id).setAttribute('style', 'display: block');

                gallery_element.setAttribute( 'style',
                    'position: fixed; z-index: 2147483646;' +
                    'width: ' + gallery_total_width + 'px;' +
                    'height: ' + gallery_height + 'px;' +
                    'left: ' + gallery_left_offset + 'px;' +  'top: ' + gallery_top_offset + 'px;' +
                    'margin: 0;' +
                    'display: block;'
                );
        };
        
        //Listener for clicks outside of iframe to close flyout
        parent.document.addEventListener('click', function(e){
            //only on non mobile
            if (screen_width > 1024){               
                var gallery = parent.document.getElementsByClassName("sigallery");
                if (gallery.length >0){
                    var gallery_id = gallery[0].getAttribute("data-gallery-id");
                    if (gallery_id != null){
                        var gallery_iframe_el = document.getElementById( 'sigallery_iframe_' + gallery_id);
                        var gallery_height = gallery[0].style.height;

                        console.log(gallery_id);
                        console.log(gallery_height);
                        gallery_iframe_el.src = gallery_iframe_el.src.replace('flyout_active', 'flyout_inactive');
                        
                        gallery[0].setAttribute('style',
                            'position: relative;' +
                            'border: none;' +
                            'margin: 0;' +
                            'padding: 0;' +
                            'overflow: hidden;' +
                            'height: ' + gallery_height + ';' + 
                            'max-height: 707px;'
                        );

                        var arrowLeft = document.getElementsByClassName("overlay-content-arrows")[0];
                        if (arrowLeft !== undefined)
                            arrowLeft.style.zIndex = 120;

                        var arrowRight = document.getElementsByClassName("overlay-content-arrows")[1];
                        if (arrowRight !== undefined)
                            arrowRight.style.zIndex = 120;
                        
                        var close = document.getElementsByClassName("close-wrap")[0];
                        if (close !== undefined)    
                            close.style.display = "block";     

                        exit_fullscreen();
                    }
                }
            }
//document.getElementById('sigallery-modal-close-btn').click();

            });

        var generateIframe = function( element_obj, embed_html, iframe_src, element_id ) {
            //If Lawrence Platform setup GA and create gallery
            if ( window._usmgOptions || gaid ) {

                (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
                })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

                if ( window._usmgOptions ) {
                    ga('create', window._usmgOptions.gaid, 'auto', {'allowLinker': true});
                    window.ga( sigallery_embed.add_iframe_ga( element_id, iframe_src, true, element_obj, embed_html, element_id ) );
                } else if ( gaid !== '' ) {
                    ga('create', gaid, 'auto', {'allowLinker': true});
                    window.ga( sigallery_embed.add_iframe_ga( element_id, iframe_src, true, element_obj, embed_html, element_id ) );
                } else {
                    add_iframe( element_obj, embed_html, iframe_src, element_id );
                }

            } else {
                add_iframe( element_obj, embed_html, iframe_src, element_id );
            }


        };

        var getScreenSize = function(e) {
            screen_height = document.documentElement.scrollHeight;
            screen_width = window.innerWidth;
            if ( document.getElementById('sigallery-modal-overlay') != null ) {
                document.getElementById('sigallery-modal-overlay').style.width= screen_width + 'px';
                document.getElementById('sigallery-modal-overlay').style.height= screen_height + 'px';
            }
        };



        var calculateGallerySize = function( gallery_el, gallery_options ) {

          function getElementContentMargin(element) {
            var styles = window.getComputedStyle(element);
            var margin = (parseInt(styles.marginLeft) + parseInt(styles.marginRight)) / 2;

            return margin;
          }

          if (screen_width <= 1024)
          {
            var gallery_elements_height = 46;
            var gallery_elements_width = 0; //width of padding on right and left of widget
      
          }

          else{
              var gallery_elements_height = 184; //total height of elements that include header, subheader, thumbnails and spacing
              var gallery_elements_width = 40; //width of padding on right and left of widget
          }
          if ( typeof gallery_options.showWidgetTitle !== "undefined" && gallery_options.showWidgetTitle === false)   {
              gallery_elements_height = gallery_elements_height - 30;
          }
          if ( typeof gallery_options.showGalleryTitle !== "undefined" &&  gallery_options.showGalleryTitle === false)   {
              gallery_elements_height = gallery_elements_height - 46;
          }

          var gallery_elements_width = 0; //width of padding on right and left of widget
          var ratio_x = 4.5;
          var ratio_y = 3;

          function getElementContentWidth(element) {
            var styles = window.getComputedStyle(element);
            var padding = parseFloat(styles.paddingLeft) + parseFloat(styles.paddingRight);

            return element.clientWidth - padding;
          }

          function getElementContentPadding(element) {
            var styles = window.getComputedStyle(element);
            var padding = Math.round(parseFloat(styles.paddingLeft) + parseFloat(styles.paddingRight)) / 2;

            return padding;
          }

          var parent_width = getElementContentWidth(gallery_el.parentNode);
          var parent_padding = getElementContentPadding(gallery_el.parentNode);
          console.log("parent_padding=" + parent_padding);
          /*set default min width if parent node width is very small or is set to auto causing offsetWidth not to work properly.
          Ideally the parent page should have an element wrapping the embed code with a set width
          example: On lawrence with viewport less than 999 has content-entry container set to auto width this causing offsetwidth to fail if no other content is in the parent
          embed code should generate a container with a set width for the content area the gallery will go.
           */

            if (parent_padding == 20 && screen_width <= 667){
                var marginoff = -Math.ceil(parent_padding);
                var paddingTop = 0;
            }
            else{
                var marginoff = 0;   
                var paddingTop = 0;
            } 

           //Added screen_width so this only applies to desktop
          if ( parent_width < 320 && screen_width > 1024) {
              parent_width = 540; //set for presto oembed
          }
          image_width = Math.round(parent_width) - gallery_elements_width;
          image_height =   Math.round( ( ( image_width / ratio_x ) ) * ratio_y );

          var gallery_height_total = image_height + gallery_elements_height;
          var style_attr = 'position: relative;border: none;margin-left: ' + marginoff + 'px;margin-right:' + marginoff + 'px;padding: 0;overflow: hidden;height: ' + gallery_height_total +'px;max-height: ' + gallery_height_total +'px;padding-top:'+ paddingTop + 'px;';

          return [style_attr, marginoff];
        };
        var retries = 0;
        var numRetries = 3;

        var init = function() {
console.log("sigallery_embed-init")
console.log("sigallery_embed-window-usatsi_gallery_options")
console.log(window.usatsi_gallery_options);
            if ( (!window.tealium_url && (window.usatsi_gallery_options === undefined || !window.usatsi_gallery_options.tealium_url) && !window._usmgOptions) || (window.usatsi_gallery_options && serialize( window.usatsi_gallery_options ) == "tealium_url=&dfp_tag_name=&dfp_id=&ga_id=")) {
console.log("sigallery_embed-init-if")
                initGallery();
            }  else {
console.log("sigallery_embed-init-else")            
                if ( !window.utag_data && retries < numRetries  ) {
                    retries++; 
                        setTimeout('sigallery_embed.init()', 500);
                    return;
                } else {


                    //Check for lawrence options object
                    if ( window.usatsi_gallery_options ) {
                        // tealium_url & dfp_tag_name params!
                        lawrence_options_params = serialize( window.usatsi_gallery_options );
                        console.log("lawrence_options_params-precheck");
                        console.log(lawrence_options_params);
                        //No values entered
                        if (lawrence_options_params == "tealium_url=&dfp_tag_name=&dfp_id=&ga_id=")
                                lawrence_options_params = "";

                        var lawrence_split = lawrence_options_params.split("&");

                        for(var i = 0; i < lawrence_split.length; i++) {
                            var param_split = lawrence_split[i].split("=");
                            if (param_split.length == 2 && param_split[1] == ""){
                                console.log("Lawrence parameter value is blank string for " + param_split[0] + ": using usatsi company defined");
                                lawrence_options_params = "";
                                break;
                            }
                            else if (param_split.length == 1){ 
                                console.log("Lawrence parameter value is missing for " + param_split[0] + ": using usatsi company defined");                                
                                lawrence_options_params = "";
                                break;
                            }

                        }

                        lawrence_options_params = '&' + lawrence_options_params;

                        console.log("lawrence_options_params-final");
                        console.log(lawrence_options_params);
                    //Check for presto's tealium url
                    } else if ( window.tealium_url ) {
                        var tealium_params = [
                            'pageName',
                            //'pathName',
                            'ssts',
                            'subcategory',
                            'subsection',
                            'topic',
                            'taxonomykeywords',
                            'dom.pathname',
                            'assetid'
                        ];
                        var tealium_obj = [];
                        for ( var prop in window.utag_data ) {

                            if ( tealium_params.indexOf( prop.toString() ) > -1 ) {
                                tealium_obj[prop] = utag_data[prop];
                            }

                        }


                        tealium_obj['tealium_url'] = window.tealium_url;
                        tealium_obj['dfp_id'] = ( window.site_vars.ADS.dfp.account_id ? window.site_vars.ADS.dfp.account_id : '7103');
                        tealium_obj['dfp_tag_name'] = 'usatoday/poster_gallery_companion' + '/' + window.utag_data.cst.replace(':','/');

                    } else {
                        tealium_obj['tealium_url'] = '';
                    }

                    utag_data_params = serialize(tealium_obj);
                    utag_data_params = '&' + utag_data_params;

                    initGallery();

                }
            }


        };

        var initGallery = function(galleryid) {
            var loadAysc = true;
            window.addEventListener('resize', function(event) {
                getScreenSize(event);
            });

            if ( gallery_count === 0 ) {
                appendCss(galleryid);

            } else {
                sigalleries(galleryid);
            }

            gallery_count++;
        };

        return {
            init: init,
            add_iframe_ga: add_iframe_ga,
            sigalleries: sigalleries
        }
    })();
        if ( window.siGalleryInit && typeof window.siGalleryInit == 'function') {
            window.siGalleryInit();
        }
};
