// JavaScript Document

var iframe_host = 'http://www.bestmenu.com.au';
var iframe_uri = '/restaurant/widget/iframe/';
var iframe_width = 800;
var iframe_height = 600;
var iframe_max_width = iframe_width;
var css_url = iframe_host + iframe_uri + '../embed/styles.css';
var body_scroll_locked = false;
var body_original_overflow_css = null;
var bestmenuwidget_iframePopupOpen = false;

if (typeof(console) == 'undefined') {
    console = new Object();
    console.log = function(o){};
}

// Load jQuery if this website isn't already using it or if the embed code has been
// placed before the jQuery script tag in the code.

if (typeof jQuery == "undefined") {
	//console.log("loading jQuery...");
    (function(url, target_node) {
		var loaded = false;
        var script = document.createElement("script");
		
        script.type = "text/javascript";
        script.async = 1;
        script.src = url;
		script.onload = script.onreadystatechange = function() {
			if (!loaded && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
			    script.onload = script.onreadystatechange = null;
				
				if (typeof jQuery != "undefined") {
                    //console.log("jQuery loaded.");
                    loaded = true;
                    jQuery.noConflict();
                    bestmenuwidget_init();
                }
			};
		};
		
		target_node.parentNode.insertBefore(script, target_node);
	})("https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.min.js", document.getElementsByTagName("script")[0]);
} else {
    //console.log("jQuery already loaded.");
	bestmenuwidget_init();
};

function bestmenuwidget_unlockbody() {
    body_scroll_locked = false;
    
    jQuery('#bestmenuwidget-wrapper').children().unwrap();
    jQuery('body').css('overflow', body_original_overflow_css);
}

function bestmenuwidget_windowresize(event) {
    var left, top, $wrapper;
    
    jQuery('#bestmenuwidget-button').toggleClass('mobile', is_mobile || jQuery(window).width() < 800);
    
    if (bestmenuwidget_iframePopupOpen) {
        iframe_width = Math.min(jQuery(window).width(), iframe_max_width);
        
        left = (jQuery(window).width() > iframe_max_width) ? ((jQuery(window).width() * 0.5) - (iframe_max_width * 0.5)) : 0;
        top = (jQuery(window).height() > iframe_height) ? ((jQuery(window).height() * 0.5) - (iframe_height * 0.5)) : 0;
        
        // Lock scrolling behind the iframe if it's taking up the whole screen.
        
        if (jQuery(window).width() > iframe_max_width || jQuery(window).height() > iframe_height) {
            if (body_scroll_locked) {
                bestmenuwidget_unlockbody();
            }
        } else {
            if (!body_scroll_locked) {
                body_scroll_locked = true;
                
                $wrapper = jQuery(document.createElement('div'));
                $wrapper
                    .attr('id', 'bestmenuwidget-wrapper')
                    .css('overflow', 'hidden');
                jQuery('body').children().not('script, [id^=\'bestmenuwidget-\']').wrapAll($wrapper);
                body_original_overflow_css = jQuery('body').css('overflow');
                jQuery('body').css('overflow', 'hidden');
            } else {
                $wrapper = jQuery('#bestmenuwidget-wrapper');
            }
            
            $wrapper.css({
                'width': jQuery(window).width() + 'px',
                'height': jQuery(window).height() + 'px'
            });
        }
        
        jQuery('#bestmenuwidget-iframewrapper')
            .css({
                'left': left + 'px',
                'top': top + 'px',
                'width': iframe_width + 'px',
                'height': Math.min(iframe_height, jQuery(window).height()) + 'px'
            });
    }
}

function bestmenuwidget_arrangetotop($element) {
    var z = 1;
    
    jQuery('*')
        .filter(function(index, element) {
            return jQuery(element).css('z-index') > 0;
        })
        .each(function(index, element) {
            z = Math.max(z, parseInt(jQuery(element).css('z-index')) + 1);
        });
    
    $element.css('z-index', z);
}

// This function will be called as soon as jQuery support is confirmed.

function bestmenuwidget_init() {
    jQuery(function() {
        
        // Load the CSS into the head of the page.
        // Tries first to put it after the last <link> tag in the <head>,
        // then at the end of the <head>, if there's no <head> tag
        // it tries to put it at the end of the <body> and finally
        // defaults to the last tag other than <html>.
        
        var $css_link = jQuery(document.createElement('link'));
        
        $css_link
            .attr('type', 'text/css')
            .attr('rel', 'stylesheet')
            .attr('href', css_url)
            .insertAfter(jQuery('head:first').find('link:last') || jQuery('head:first').children('*:last') || jQuery('body:first').children('*:last') || jQuery('*:not(html):first'));
        
        // Create a button that is fixed to the bottom right for desktops,
        // or absolute to bottom at full width for mobiles. Styling for this
        // is in the external CSS file. Appends to the end of the <body> tag.
        
        var $button = jQuery(document.createElement('a'));
        
        $button
            .attr('id', 'bestmenuwidget-button')
            .attr('href', '#')
            .attr('onClick', 'return false;')
            .html(bookingButtonLabel)
            .on('click', function(event) {
                var extra_params = '';
                if (typeof bestmenu_booking_widget_settings == 'object') {
                    extra_params = '&' + jQuery.param(bestmenu_booking_widget_settings);
                }

                if (!is_mobile && jQuery(window).width() > iframe_width && jQuery(window).height() > iframe_height) {
                    
                    // The window is bigger than the iframe default size. Launch the iframe in a popup div...
                    
                    bestmenuwidget_iframePopupOpen = true;
                    
                    // Create curtain. Styles in the external CSS.
                    // Appends to the end of the <body> tag.
                    // Clicking it will destroy it, along with the iframe.
                    
                    var $curtain = jQuery("<div id='bestmenuwidget-curtain'></div>");
                    
                    $curtain
                        .fadeTo(0, 0.75)
                        .on('click', function(event) {
                            bestmenuwidget_iframePopupOpen = false;
                            if (body_scroll_locked) {
                                bestmenuwidget_unlockbody();
                            }
                            jQuery('#bestmenuwidget-curtain, #bestmenuwidget-iframewrapper').remove();
                        })
                        .appendTo('body');
                    
                    bestmenuwidget_arrangetotop($curtain);
                    
                    // Create a wrapper for the iframe.
                    
                    var $iframe_wrapper = jQuery(document.createElement('div'));
                    
                    $iframe_wrapper
                        .attr('id', 'bestmenuwidget-iframewrapper')
                        .appendTo('body');
                    
                    bestmenuwidget_arrangetotop($iframe_wrapper);
                    
                    // Create iframe. Default styles in the external CSS.
                    // Appends to the end of the <body> tag.

                    var $iframe = jQuery(document.createElement('iframe'));
                    $iframe
                        .attr('id', 'bestmenuwidget-iframe')
                        .attr('src', iframe_host + iframe_uri + '?id=' + int_id + extra_params)
                        .appendTo($iframe_wrapper);
                    
                    // Position and scale the iframe.
                    
                    $iframe.on("load", function(event) {
                        $iframe.context.contentWindow.postMessage('ping', iframe_host);
                    });
                    
                    jQuery(window).trigger('resize.bestmenuwidget');
                    
                } else {
                    
                    // The window's not very big, probably mobile. Just link to the source page instead of opening an iframe.
                    
                    window.location = iframe_host + iframe_uri + '?id=' + int_id + '&np' + extra_params;
                    
                }
            })
            .appendTo('body');
        
        bestmenuwidget_arrangetotop($button);
        
        // Setup event listener to watch for changes to the window size
        
        jQuery(window)
            .on('resize.bestmenuwidget', bestmenuwidget_windowresize)
            .trigger('resize.bestmenuwidget');
    });
}

// After creating the iframe, this script will ping the inner window object.
// When it receives this message it should reply with it's current height.
// It should also send these messages each time the body height changes.

if (typeof(window.addEventListener) == 'function') {
    window.addEventListener('message', function(event) {
        var a, n;
        
        if (event.origin == iframe_host) {
            if (typeof(event.data) == 'string') {
                if (event.data == 'close') {
                    jQuery('#bestmenuwidget-curtain').trigger('click');
                } else if (event.data.indexOf(':') > -1) {
                    a = event.data.split(':');
                    if (a[0] == 'bodyHeight') {
                        n = a[1];
                        if (!isNaN(n)) {
                            iframe_height = n;
                            jQuery(window).trigger('resize.bestmenuwidget');
                        }
                    }
                }
            }
        }
    });
}

var int_id = 3;
var bookingButtonLabel = 'Online Reservation';
var is_mobile = false;
