// written by Dean Edwards, 2005
// with input from Tino Zijdel, Matthias Miller, Diego Perini
// http://dean.edwards.name/weblog/2005/10/add-event/
// 2007-07-10 TKO - Removed check for body in schedule because of problems with Firefox 2.0
// 2008-14-02 TKO - Added support for Vista 64.

/*global DOMContentLoadedCustom */

function addEvent(element, type, handler) {
	// Modification by Tanny O'Haley, http://tanny.ica.com to add the
	// DOMContentLoaded for all browsers.
	if (type === "DOMContentLoaded" || type === "domload") {
		addDOMLoadEvent(handler);
		return;
	}
	
	if (element.addEventListener) {
		element.addEventListener(type, handler, false);
	} else {
		// assign each event handler a unique ID
		if (!handler.$$guid) {
			handler.$$guid = addEvent.guid++;
		}
		// create a hash table of event types for the element
		if (!element.events) {
			element.events = {};
		}
		// create a hash table of event handlers for each element/event pair
		var handlers = element.events[type];
		if (!handlers) {
			handlers = element.events[type] = {};
			// store the existing event handler (if there is one)
			if (element["on" + type]) {
				handlers[0] = element["on" + type];
			}
		}
		// store the event handler in the hash table
		handlers[handler.$$guid] = handler;
		// assign a global event handler to do all the work
		element["on" + type] = handleEvent;
	}
}
// a counter used to create unique IDs
addEvent.guid = 1;

function removeEvent(element, type, handler) {
	if (element.removeEventListener) {
		element.removeEventListener(type, handler, false);
	} else {
		// delete the event handler from the hash table
		if (element.events && element.events[type]) {
			delete element.events[type][handler.$$guid];
		}
	}
}

function handleEvent(event) {
	var returnValue = true;
	// grab the event object (IE uses a global event object)
	event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
	// get a reference to the hash table of event handlers
	var handlers = this.events[event.type];
	// execute each event handler
	for (var i in handlers) {
		this.$$handleEvent = handlers[i];
		if (this.$$handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
}

function fixEvent(event) {
	// add W3C standard event methods
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
}
fixEvent.preventDefault = function() {
	this.returnValue = false;
};
fixEvent.stopPropagation = function() {
	this.cancelBubble = true;
};

// End Dean Edwards addEvent.

// Tino Zijdel - crisp@xs4all.nl This little snippet fixes the problem that the onload attribute on 
// the body-element will overwrite previous attached events on the window object for the onload event.
if (!window.addEventListener) {
	document.onreadystatechange = function(){
		if (window.onload && window.onload !== handleEvent) {
			addEvent(window, 'load', window.onload);
			window.onload = handleEvent;
		}
	};
}

// Here are my functions for adding the DOMContentLoaded event to browsers other
// than Mozilla.

// Array of DOMContentLoaded event handlers.
window.onDOMLoadEvents = [];
window.DOMContentLoadedInitDone = false;

// Function that adds DOMContentLoaded listeners to the array.
function addDOMLoadEvent(listener) {
	// If the DOMContentLoaded event has happened, run the function.
	if(window.DOMContentLoadedInitDone){
		listener();
		return;
	}

	window.onDOMLoadEvents[window.onDOMLoadEvents.length]=listener;
}

// Function to process the DOMContentLoaded events array.
function DOMContentLoadedInit() {
	// quit if this function has already been called
	if (window.DOMContentLoadedInitDone) {
		return;
	}

	// flag this function so we don't do the same thing twice
	window.DOMContentLoadedInitDone = true;

	// iterates through array of registered functions 
	for (var i=0; i<window.onDOMLoadEvents.length; i++) {
		var func = window.onDOMLoadEvents[i];
		func();
	}
}

function DOMContentLoadedScheduler() {
	// quit if the init function has already been called
	if (window.DOMContentLoadedInitDone) {
		return true;
	}
	
	// First, check for Safari or KHTML.
	// Second, check for IE.
	//if DOM methods are supported, and the body element exists
	//(using a double-check including document.body, for the benefit of older moz builds [eg ns7.1] 
	//in which getElementsByTagName('body')[0] is undefined, unless this script is in the body section)
	if(/KHTML|WebKit/i.test(navigator.userAgent)) {
		if(/loaded|complete/.test(document.readyState)) {
			DOMContentLoadedInit();
		} else {
			// Not ready yet, wait a little more.
			setTimeout("DOMContentLoadedScheduler()", 250);
		}
	} else if(document.getElementById("__ie_onload")) {
		return true;
	}

	// Check for custom developer provided function.
	if(typeof DOMContentLoadedCustom === "function") {
		if(typeof document.getElementsByTagName !== 'undefined' && (document.getElementsByTagName('body')[0] !== null || document.body !== null)) {
			// Call custom function.
			if(DOMContentLoadedCustom()) {
				DOMContentLoadedInit();
			} else {
				// Not ready yet, wait a little more.
				setTimeout("DOMContentLoadedScheduler()", 250);
			}
		}
	}

	return true;
}

// If addEventListener supports the DOMContentLoaded event.
if(document.addEventListener) {
	document.addEventListener("DOMContentLoaded", DOMContentLoadedInit, false);
}

// Schedule to run the init function.
setTimeout("DOMContentLoadedScheduler()", 250);

// Just in case window.onload happens first, add it there too.
addEvent(window, "load", DOMContentLoadedInit);

/* for Internet Explorer */
/*@cc_on
	@if (@_win32 || @_win64)
	document.write("<script id=__ie_onload defer src=\"//:\"><\/script>");
	var script = document.getElementById("__ie_onload");
	script.onreadystatechange = function() {
		if (this.readyState == "complete") {
			DOMContentLoadedInit(); // call the onload handler
		}
	};
	@end
@*/



addEvent(window, 'DOMContentLoaded', function(){

    // If we are on the enquiries page for TigerTiger then we also want
    // to update the numbers box

    if($('xmas-tel-TT-small') != undefined && $('venue') != undefined)
    {
        Event.observe('venue', 'change', function(){
            update_numbers($('venue').value,'xmas-tel-TT-small','xmas-tel-TT-venue-small')
        })
    }
    
    if($('xmas-venue-select'))
    {
        $('pricing').hide();

        function attach_radio_events()
        {
            $$('input[name=menu]').each(function(element){
                // note: change does not work on Safari
                Event.observe(element, 'click', update_menu_results)
            })
        }

        var parent_height = 0;
        var set_height = true;

        /**
         * update_menu_results 
         *
         * Update the results list if a field changes
         * 
         */
        function update_menu_results()
        {
            if (parent_height > 0 && set_height)
            {
                $('pricing').parentNode.style.height = parent_height + 'px';
                set_height = false;
            }
            $('pricing').hide();

            // grab the field values
            var venue_id  = $F('xmas-venue-select');
            var menu_name = null;
            
            $$('input[name=menu]').each(function(element){
                if(element.checked) menu_name = element.value
            })

            var day = $F('meal-day')
            var time = $F('meal-time')

            // check we can make the request (Not NULL)
            valid = true

            // each loop doesnt seem to work here
            if(venue_id  == null || venue_id  == "") return
            if(menu_name == null || menu_name == "") return
            if(day == null || day == "") return
            if(time == null || time == "") return

            $('spinner').show();

            // if we made it this far fire off the request complete with nasty hard coded date
            var version = $('lookup').className ;
            var url = '/christmas/menu-results/' + version + '/' + venue_id + '/' + menu_name + '/' + day + '/' + time

            new Ajax.Request(url, {
                onSuccess: function(transport) {
                    if (version == 'venue' && Prototype.Browser.IE)
                    {
                        var func = document.createElement('div');
                        var the_text = "<table>" + transport.responseText + "</table>"
                        func.innerHTML = the_text;
                        $('pricing').parentNode.replaceChild(func.firstChild.tBodies[0].rows[0], $('pricing'));
                    }
                    else
                    {
                        $('pricing').replace(transport.responseText);
                    }
                    $('spinner').hide();
                    $('pricing').show();
                    set_day_buttons();
                    parent_height = $('pricing').parentNode.getHeight();
                }
            });
        }

        function set_day_buttons()
        {
            if ($('prev_day_button'))
            {
                $('prev_day_button').observe('click', function(e){
                    Event.stop(e || window.event);
                    var idx = $('meal-day').selectedIndex;
                    if (idx > 0)
                    {
                        $('meal-day').selectedIndex = idx -1;
                        update_menu_results();
                    }
                });
            }
            if ($('next_day_button'))
            {
                $('next_day_button').observe('click', function(e){
                    Event.stop(e || window.event);
                    var idx = $('meal-day').selectedIndex;
                    if (idx < $('meal-day').options.length)
                    {
                        $('meal-day').selectedIndex = idx +1;
                        update_menu_results();
                    }
                });
            }

        }
        
        Event.observe($('xmas-venue-select'), 'change', function(){
    
            var version = $('lookup').className 
            new Ajax.Request('/christmas/menu_query/' + version + '/' + $('xmas-venue-select').value, {
              method: 'get',
              onSuccess: function(transport) {
                    $('menu-selector').replace(transport.responseText);
                    attach_radio_events();
              }
            });
        
            $('pricing').hide()

            // Addition for the Jan 09 campaign 
            // TT only: update telephone number depending on which venue
            // is selected

            update_numbers($('xmas-venue-select').value,'xmas-tel-TT', 'xmas-venue-tel-TT')
        });

        attach_radio_events()
        Event.observe('meal-day', 'change', update_menu_results)
        Event.observe('meal-time', 'change', update_menu_results)

        target_blank() 
    }
});

function target_blank() 
{
    $$('a[rel="external"]').each(function(link){
        if(link != undefined)
        {
            if(link.readAttribute('href') != '' && link.readAttribute('href') != '#'){
                link.target = '_blank'
            }
        }
    });
}

function update_numbers(venue_id, main_box_id, venue_box_id)
{
    var phone_numbers = {
        73: '020 7930 1885',
        61: '029 2039 1944',
        2:  '020 8662 4949',
        65: '0113 236 6999',
        67: '0161 385 8080',
        69: '0191 235 7065',
        71: '02392 882244',
        59: '01224 252 434',
        63: '0141 553 4888'
    }

            //alert(venue_id)
    if(venue_box_id != undefined)
    {
        if(venue_id == '')
        {
            return
        }
        else
        {
        /*
             if(phone_numbers[venue_id] != undefined)
             {
                 $(main_box_id).hide()
                 $(venue_box_id).show()
                 $('venue-telephone-number').update(phone_numbers[venue_id])
             }
             else 
             { 
                 $(main_box_id).show()
                 $(venue_box_id).hide()
             } */
         }
    }
}
