//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2008 Valerio Proietti, <http://mad4milk.net>, MIT Style License.

var Asset=new Hash({javascript:function(F,D){D=$extend({onload:$empty,document:document,check:$lambda(true)},D);var B=new Element("script",{src:F,type:"text/javascript"});
var E=D.onload.bind(B),A=D.check,G=D.document;delete D.onload;delete D.check;delete D.document;B.addEvents({load:E,readystatechange:function(){if(["loaded","complete"].contains(this.readyState)){E();
}}}).setProperties(D);if(Browser.Engine.webkit419){var C=(function(){if(!$try(A)){return ;}$clear(C);E();}).periodical(50);}return B.inject(G.head);},css:function(B,A){return new Element("link",$merge({rel:"stylesheet",media:"screen",type:"text/css",href:B},A)).inject(document.head);
},image:function(C,B){B=$merge({onload:$empty,onabort:$empty,onerror:$empty},B);var D=new Image();var A=$(D)||new Element("img");["load","abort","error"].each(function(E){var F="on"+E;
var G=B[F];delete B[F];D[F]=function(){if(!D){return ;}if(!A.parentNode){A.width=D.width;A.height=D.height;}D=D.onload=D.onabort=D.onerror=null;G.delay(1,A,A);
A.fireEvent(E,A,1);};});D.src=A.src=C;if(D&&D.complete){D.onload.delay(1);}return A.setProperties(B);},images:function(D,C){C=$merge({onComplete:$empty,onProgress:$empty},C);
if(!D.push){D=[D];}var A=[];var B=0;D.each(function(F){var E=new Asset.image(F,{onload:function(){C.onProgress.call(this,B,D.indexOf(F));B++;if(B==D.length){C.onComplete();
}}});A.push(E);});return new Elements(A);}});/*
Script: Drag.js
    The base Drag Class. Can be used to drag and resize Elements using mouse events.

    License:
        MIT-style license.

    Authors:
        Valerio Proietti
        Tom Occhinno
        Jan Kassens
*/

var Drag = new Class({

    Implements: [Events, Options],

    options: {/*
        onBeforeStart: $empty(thisElement),
        onStart: $empty(thisElement, event),
        onSnap: $empty(thisElement)
        onDrag: $empty(thisElement, event),
        onCancel: $empty(thisElement),
        onComplete: $empty(thisElement, event),*/
        snap: 6,
        unit: 'px',
        grid: false,
        style: true,
        limit: false,
        handle: false,
        invert: false,
        preventDefault: false,
        modifiers: {x: 'left', y: 'top'}
    },

    initialize: function(){
        var params = Array.link(arguments, {'options': Object.type, 'element': $defined});
        this.element = $(params.element);
        this.document = this.element.getDocument();
        this.setOptions(params.options || {});
        var htype = $type(this.options.handle);
        this.handles = ((htype == 'array' || htype == 'collection') ? $$(this.options.handle) : $(this.options.handle)) || this.element;
        this.mouse = {'now': {}, 'pos': {}};
        this.value = {'start': {}, 'now': {}};

        this.selection = (Browser.Engine.trident) ? 'selectstart' : 'mousedown';

        this.bound = {
            start: this.start.bind(this),
            check: this.check.bind(this),
            drag: this.drag.bind(this),
            stop: this.stop.bind(this),
            cancel: this.cancel.bind(this),
            eventStop: $lambda(false)
        };
        this.attach();
    },

    attach: function(){
        this.handles.addEvent('mousedown', this.bound.start);
        return this;
    },

    detach: function(){
        this.handles.removeEvent('mousedown', this.bound.start);
        return this;
    },

    start: function(event){
        if (this.options.preventDefault) event.preventDefault();
        this.mouse.start = event.page;
        this.fireEvent('beforeStart', this.element);
        var limit = this.options.limit;
        this.limit = {x: [], y: []};
        for (var z in this.options.modifiers){
            if (!this.options.modifiers[z]) continue;
            if (this.options.style) this.value.now[z] = this.element.getStyle(this.options.modifiers[z]).toInt();
            else this.value.now[z] = this.element[this.options.modifiers[z]];
            if (this.options.invert) this.value.now[z] *= -1;
            this.mouse.pos[z] = event.page[z] - this.value.now[z];
            if (limit && limit[z]){
                for (var i = 2; i--; i){
                    if ($chk(limit[z][i])) this.limit[z][i] = $lambda(limit[z][i])();
                }
            }
        }
        if ($type(this.options.grid) == 'number') this.options.grid = {x: this.options.grid, y: this.options.grid};
        this.document.addEvents({mousemove: this.bound.check, mouseup: this.bound.cancel});
        this.document.addEvent(this.selection, this.bound.eventStop);
    },

    check: function(event){
        if (this.options.preventDefault) event.preventDefault();
        var distance = Math.round(Math.sqrt(Math.pow(event.page.x - this.mouse.start.x, 2) + Math.pow(event.page.y - this.mouse.start.y, 2)));
        if (distance > this.options.snap){
            this.cancel();
            this.document.addEvents({
                mousemove: this.bound.drag,
                mouseup: this.bound.stop
            });
            this.fireEvent('start', [this.element, event]).fireEvent('snap', this.element);
        }
    },

    drag: function(event){
        if (this.options.preventDefault) event.preventDefault();
        this.mouse.now = event.page;
        for (var z in this.options.modifiers){
            if (!this.options.modifiers[z]) continue;
            this.value.now[z] = this.mouse.now[z] - this.mouse.pos[z];
            if (this.options.invert) this.value.now[z] *= -1;
            if (this.options.limit && this.limit[z]){
                if ($chk(this.limit[z][1]) && (this.value.now[z] > this.limit[z][1])){
                    this.value.now[z] = this.limit[z][1];
                } else if ($chk(this.limit[z][0]) && (this.value.now[z] < this.limit[z][0])){
                    this.value.now[z] = this.limit[z][0];
                }
            }
            if (this.options.grid[z]) this.value.now[z] -= ((this.value.now[z] - this.limit[z][0]) % this.options.grid[z]);
            if (this.options.style) this.element.setStyle(this.options.modifiers[z], this.value.now[z] + this.options.unit);
            else this.element[this.options.modifiers[z]] = this.value.now[z];
        }
        this.fireEvent('drag', [this.element, event]);
    },

    cancel: function(event){
        this.document.removeEvent('mousemove', this.bound.check);
        this.document.removeEvent('mouseup', this.bound.cancel);
        if (event){
            this.document.removeEvent(this.selection, this.bound.eventStop);
            this.fireEvent('cancel', this.element);
        }
    },

    stop: function(event){
        this.document.removeEvent(this.selection, this.bound.eventStop);
        this.document.removeEvent('mousemove', this.bound.drag);
        this.document.removeEvent('mouseup', this.bound.stop);
        if (event) this.fireEvent('complete', [this.element, event]);
    }

});

Element.implement({

    makeResizable: function(options){
        var drag = new Drag(this, $merge({modifiers: {x: 'width', y: 'height'}}, options));
        this.store('resizer', drag);
        return drag.addEvent('drag', function(){
            this.fireEvent('resize', drag);
        }.bind(this));
    }

});
/*
Script: Drag.Move.js
    A Drag extension that provides support for the constraining of draggables to containers and droppables.

    License:
        MIT-style license.

    Authors:
        Valerio Proietti
        Tom Occhinno
        Jan Kassens*/

Drag.Move = new Class({

    Extends: Drag,

    options: {/*
        onEnter: $empty(thisElement, overed),
        onLeave: $empty(thisElement, overed),
        onDrop: $empty(thisElement, overed, event),*/
        droppables: [],
        container: false,
        precalculate: false,
        includeMargins: true,
        checkDroppables: true
    },

    initialize: function(element, options){
        this.parent(element, options);
        this.droppables = $$(this.options.droppables);
        this.container = $(this.options.container);
        if (this.container && $type(this.container) != 'element') this.container = $(this.container.getDocument().body);

        var position = this.element.getStyle('position');
        if (position=='static') position = 'absolute';
        if ([this.element.getStyle('left'), this.element.getStyle('top')].contains('auto')) this.element.position(this.element.getPosition(this.element.offsetParent));
        this.element.setStyle('position', position);

        this.addEvent('start', this.checkDroppables, true);

        this.overed = null;
    },

    start: function(event){
        if (this.container){
            var ccoo = this.container.getCoordinates(this.element.getOffsetParent()), cbs = {}, ems = {};

            ['top', 'right', 'bottom', 'left'].each(function(pad){
                cbs[pad] = this.container.getStyle('border-' + pad).toInt();
                ems[pad] = this.element.getStyle('margin-' + pad).toInt();
            }, this);

            var width = this.element.offsetWidth + ems.left + ems.right;
            var height = this.element.offsetHeight + ems.top + ems.bottom;

            if (this.options.includeMargins) {
                $each(ems, function(value, key) {
                    ems[key] = 0;
                });
            }
            if (this.container == this.element.getOffsetParent()) {
                this.options.limit = {
                    x: [0 - ems.left, ccoo.right - cbs.left - cbs.right - width + ems.right],
                    y: [0 - ems.top, ccoo.bottom - cbs.top - cbs.bottom - height + ems.bottom]
                };
            } else {
                this.options.limit = {
                    x: [ccoo.left + cbs.left - ems.left, ccoo.right - cbs.right - width + ems.right],
                    y: [ccoo.top + cbs.top - ems.top, ccoo.bottom - cbs.bottom - height + ems.bottom]
                };
            }

        }
        if (this.options.precalculate){
            this.positions = this.droppables.map(function(el) {
                return el.getCoordinates();
            });
        }
        this.parent(event);
    },

    checkAgainst: function(el, i){
        el = (this.positions) ? this.positions[i] : el.getCoordinates();
        var now = this.mouse.now;
        return (now.x > el.left && now.x < el.right && now.y < el.bottom && now.y > el.top);
    },

    checkDroppables: function(){
        var overed = this.droppables.filter(this.checkAgainst, this).getLast();
        if (this.overed != overed){
            if (this.overed) this.fireEvent('leave', [this.element, this.overed]);
            if (overed) this.fireEvent('enter', [this.element, overed]);
            this.overed = overed;
        }
    },

    drag: function(event){
        this.parent(event);
        if (this.options.checkDroppables && this.droppables.length) this.checkDroppables();
    },

    stop: function(event){
        this.checkDroppables();
        this.fireEvent('drop', [this.element, this.overed, event]);
        this.overed = null;
        return this.parent(event);
    }

});

Element.implement({

    makeDraggable: function(options){
        var drag = new Drag.Move(this, options);
        this.store('dragger', drag);
        return drag;
    }

});


LIVENATION.module.blockbuster = function(item_data) {

    var module_id = item_data.module_id;
    var custom_dd = item_data.custom_dd;
    var google_map_url = 'http://www.google.com/jsapi?key=' + item_data.google_api_key;
    var form_submitted = item_data.form_submitted;
    var iframe;

    var map;
    var map_canvas;
    var gdir;
    var url;

    var locations_html = "";

    var myDrag = new Drag.Move($(module_id + '_popup'), {
        handle: $(module_id + '_mydrag'),
        container: $('body')
    });

    $(module_id + '_close_popup').addEvent('click', function() {
        $(module_id + '_popup').setStyle('display', 'none');
        $("map_table").setStyle('display', 'none');
        $("popup_directions").setStyle('display', 'block');
        $('popup_directions').removeEvents();
        if ($(module_id + '_iframe')) {
            $(module_id + '_iframe').dispose();
        } 
        if ($('map_canvas')) {
            $('map_canvas').empty();
            $('map_canvas').setStyle('background-color', '');
        }
    });

    $('bb_store_list_link').addEvent('click', function() {
        $('bb_store_list').setStyles({
        position: 'absolute',
        left: '25em',
        top: '10em',
        display: 'block'
        });
    });
    $('bb_store_list_close').addEvent('click', function() {
        $('bb_store_list').setStyle('display', 'none');
    });

    if(form_submitted == 'true') {
        new Asset.javascript(google_map_url, {
            onload: function() {
                $('search_results').setStyle('display', 'block');
                $('blockbuster_popup').setStyles({
                    position: 'absolute',
                    left: '20em',
                    top: '16em'
                });
                loadMaps(item_data.gmarkers_lat, item_data.gmarkers_long);
            }
        });
    }
    
    var loadMaps = function(gmarkers_lat, gmarkers_long) {     
        google.load("maps", "2", {
            "callback" : function() {
                mapsLoaded(gmarkers_lat, gmarkers_long);
            }
        });
    }

    // Creates a marker whose info window displays the letter corresponding to the given index.
    var createMarker = function(point, index, baseIcon, map) {
        // Create a lettered icon for this point using our icon class
        var letter = String.fromCharCode("A".charCodeAt(0) + index);
        var letterIcon = new GIcon(baseIcon);
        var markerImg = "http://www.google.com/mapfiles/marker" + letter + ".png";
        letterIcon.image = markerImg;
          
        // Putting the marker next to the store listing and giving it an event handler
        var letterMarker = new Asset.image(markerImg, {alt: letter});
        $('store_locations').insertBefore(letterMarker, $('store_' + index));

        var the_marker = new GMarker(point, {icon:letterIcon});

        var html = '<strong>' + $('store_name_'+ i).innerHTML + '</strong><br/>';
        html += $('address_1_'+ i).innerHTML + '<br/>';
        if ($('address_2_'+ i).nodeValue != null) {
            html += $('address_2_'+ i).innerHTML + '<br/>';
        }
        html += $('city_state_'+ i).innerHTML + '<br/>';
        html += $('phone_number_'+ i).innerHTML;

        // Event handler for marker on the map
        GEvent.addListener(the_marker, "click", function() {
            map.setCenter(point, 13);
            the_marker.openInfoWindowHtml(html);
        });
        
        // Event handler for marker on the sidenav
        letterMarker.addEvent('click', function() {
            map.setCenter(point, 13);
            the_marker.openInfoWindowHtml(html);
        });

        return {
            new_marker: the_marker
        }
    }

    var mapsLoaded = function(gmarkers_lat, gmarkers_long, address) {
        var map = new GMap2($("map"));
        var bounds = new GLatLngBounds(); // Used for centering the map around the results

        var myLoc = new GLatLng((0,0), 0);
        map.setCenter(myLoc, 15);
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());

        // Create a base icon for our markers that specifies the shadow, icon dimensions, etc.
        // Necessary for A, B, C,... gMarkers
        var baseIcon = new GIcon();
        baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        baseIcon.iconSize = new GSize(20, 34);
        baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(9, 34);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);
        baseIcon.infoShadowAnchor = new GPoint(18, 25);

        for (var i=0; i < 10; i++) {
            var point = new GLatLng(gmarkers_lat[i].toFloat(), gmarkers_long[i].toFloat());
            var addMarker = createMarker(point, i, baseIcon, map);
            map.addOverlay(addMarker.new_marker);
            bounds.extend(point); // Used to center the map to its markers
        }

        // Determine the zoom level from the bounds and center the map on it
        map.setZoom(map.getBoundsZoomLevel(bounds));
        map.setCenter(bounds.getCenter());

        // Driving Directions event handler
        var dd = $$('p.driving_directions').addEvent('click', function(p){
            $(module_id + '_popup').setStyle('display', 'block');

			// THIS DOESN'T WORK IN IE, PLEASE USE if ($(p.target).get('tag') != 'p') {
            //if ($type(p.target) != 'p') {

			if ($(p.target).get('tag') != 'p') {
                this_p = p.target.getParent('p');
            } else {
                this_p = p.target;
            }

            var store_lat = this_p.getElement('input.store_lat').value;
            var store_long = this_p.getElement('input.store_long').value;

            var popup_name = this_p.getPrevious('.store_name').innerHTML;
            var popup_address = this_p.getPrevious('.address_1').innerHTML + '<br/>';
            if (this_p.getPrevious('.address_2').nodeValue != null) {
                popup_address += this_p.getPrevious('.address_2').innerHTML + '<br/>';
            }
            popup_address += this_p.getPrevious('.city_state').innerHTML + '<br/>';
            popup_address += this_p.getPrevious('.phone_number').innerHTML;
            $('popup_store_name').innerHTML = popup_name;
            $('popup_store_address').innerHTML = popup_address;
            
            handleForm(store_lat, store_long);
        });
    }

	var handleForm = function(store_lat, store_long) {
        var submit_form = function(store_lat, store_long) {
            return function(e) {
                $('error_address').innerHTML = '';
                $('error_city').innerHTML = '';
                $('error_postal_code').innerHTML = '';

                var pass = false;
                if ( ($('popup_address').value != '') &&  ($('popup_city').value != '') ) {
                    pass = true;
                } else if (($('popup_postal_code').value != '')) {
                    pass = true;
                }

                if (!pass) {
                    if ( (!pass) && ($('popup_address').value == '')) {
                        $('error_address').innerHTML = 'Please enter a street address';
                    }
                    if ( (!pass) && ($('popup_city').value == '')) {
                        $('error_city').innerHTML = 'Please enter a city';
                    }
                    if ( (!pass) && ($('popup_postal_code').value == '')) {
                        $('error_postal_code').innerHTML = 'Please enter a zip or postal code';
                    }
                }

                if (pass) {
                    if ( ($('popup_city').value == '') && ($('popup_address').value == '')) 
                        var fromAddress = $('popup_postal_code').value;
                    else 
                        var fromAddress = $('popup_address').value + ', ' + $('popup_city').value + ', ' + $('popup_state').value + ', ' + $('popup_postal_code').value;

                    setDirections(fromAddress, store_lat, store_long, $('locale').value);
					
                }
              return false;
            }
        }
        $('popup_directions').addEvent('submit', submit_form(store_lat, store_long));
    }

    var setDirections = function(fromAddress, lat, _long, locale) {
        $('directions').innerHTML = '';

        var map_canvas = new GMap2($("map_canvas"));
        var gdir = new GDirections(map_canvas, $("directions"));
        var ddLoc = new GLatLng((lat, _long), 0);
        map_canvas.setCenter(ddLoc, 15);
        map_canvas.addControl(new GSmallMapControl());
        map_canvas.addControl(new GMapTypeControl());

        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);

        gdir.load("from: " + fromAddress  + " to: " + lat + " " + _long,  { "locale": locale });

        url = 'http://maps.google.com/maps?f=d&saddr=' + fromAddress + '&daddr=' + lat + ',' + _long + '&hl=en&ie=UTF8&z=14&pw=2';
    }

    var handleErrors = function(gdir) {
/*
       if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.");
       else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.");
       
       else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.");

       else if (gdir.getStatus().code == G_GEO_BAD_KEY)
     alert("The given key is either invalid or does not match the domain for which it was given.");

       else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
     alert("A directions request could not be successfully parsed.");
    
       else alert("An unknown error occurred.");
*/

        if (gdir.getStatus().code == '604') $('error_address').innerHTML = 'There was a problem building directions <br>to the venue from entered address.';
        else if (gdir.getStatus().code != '') $('error_address').innerHTML = 'Address can not be found. Please try again';
    }

    var onGDirectionsLoad = function(gdir){ 
        if (gdir.getStatus().code == 200) {
            $("map_table").setStyle('display', 'block');
            $("popup_directions").setStyle('display', 'none');

            if ((url != '') && ($('print') == null)) {
                var _print = new Element('a', {
                    'id' : 'print',
                    'html' : 'Print Directions',
                    'href' : url,
                    'target' : '_blank'
                }).inject($('directions'));
            }
        } 
    }

}

window.addEvent('domready', function() {
        if (LIVENATION.instances.blockbuster != 'object') {
            LIVENATION.instances.blockbuster = new Array(); 
        }
        for (i = 0; i < LIVENATION.registry.blockbuster.length; i++) {
            LIVENATION.instances.blockbuster.push(new LIVENATION.module.blockbuster(LIVENATION.registry.blockbuster[i]));
        }
})
