function onContent(f){//(C)webreflection.blogspot.com
var a=onContent,b=navigator.userAgent,d=document,w=window,c="onContent",e="addEventListener",o="opera",r="readyState",
s="<scr".concat("ipt defer src='//:' on",r,"change='if(this.",r,"==\"complete\"){this.parentNode.removeChild(this);",c,".",c,"()}'></scr","ipt>");
a[c]=(function(o){return function(){a[c]=function(){};for(a=arguments.callee;!a.done;a.done=1)f(o?o():o)}})(a[c]);
if(d[e])d[e]("DOMContentLoaded",a[c],false);
if(/WebKit|Khtml/i.test(b)||(w[o]&&parseInt(w[o].version())<9))(function(){/loaded|complete/.test(d[r])?a[c]():setTimeout(arguments.callee,1)})();
else if(/MSIE/i.test(b))d.write(s);
};

/**************************
 *
 * PeepMeat Javascript
 *
 *************************/
 
 var PM = new Object();
 
 Object.extend(PM, {
    currentRestaurant: '',
    restaurants: new Hash(),
    
    getRestaurantHTML: function(id)
    {
        var restaurant = this.restaurants.get(id);
        if(restaurant == null)
        {
            //load the data from the server
            $data = new Ajax.Request("json_restaurant_info.php?id="+id,
                {
                    onSuccess: function(transport, json)
                    {
                        //turn the json resquest into a properly formatted address
                        var html = "<span style='font-weight:bold'>" + json.restaurant_name + "</span><br>";
                        
                        if(json.rating != null)
                        	html += this.getSmallStarRating(json.rating, json.user_rating);
                        	
                        html += "<br>" +json.street1;
                        
                        if(json.street2 != null)
                            html += "<br>" + json.street2;
                        
                        if(json.city != null)
                            html += "<br>" + json.city;
                            
                        if(json.state != null)
                            html += ", " + json.state;
                            
                        if(json.zip != null)
                            html += ", " + json.zip;
                    
                        if(json.country != null)
                            html += "<br>" + json.country;
                        
                        if(json.phone != null)
                            html += "<br>" + json.phone;
                        
                        this.restaurants.set(id, html);
                        
                    }.bind(this)
                }
            );
        }
        
        return restaurant;
    },
    
    getRestaurantPanel: function()
    {
        if(this.restaurantInfoPanel == null)
        {
            var div = document.createElement('div');
            div.className = 'restaurantInfoPanel';
            div.style.display = 'none';
            Element.extend(div);
            document.body.appendChild(div);
            this.restaurantInfoPanel = div;
        }
        
        return this.restaurantInfoPanel;
    },
    
    /**
     * Print out HTML for the small star rating
     */
    getSmallStarRating: function(rating, user_rating)
    {
    	if(user_rating == null)
    	{
    		user_rating = 0;
    	}
    	
    	if(rating == null || user_rating != 0)
    	{
    		rating = 0;
    	} 
    	
    	var width = rating * 12;
    	var user_width = user_rating*12;
    	
    	var html = '<span class="small-inline-rating"><ul class="star-rating">';
    	html += '<li class="current-rating" style="width:' + width + 'px;">Currently ' + rating +'/5 Stars.</li>';
    	html += '<li class="current-user-rating" style="width:'+ user_width +'px;">You have current rated this ' + user_rating + '/5 Stars.</li></ul></span>';
    	
    	return html;
    },
    
    hideRestaurantInfo: function(id)
    {
        if(id == PM.currentRestaurant)
        {
            PM.getRestaurantPanel().hide();
            PM.currentRestaurant = '';
        }
    },
    
    navigate: function(url)
    {
        if(url != null && url != '')
           window.location = url;
    },
    
    /**
     * Hide the right side of the header and show the login controls
     */
    showMiniLoginForm: function(e)
    {
    	if(e == null)
    		e = window.event;
    	
    	if(e != null)
    		Event.stop(e);
    	
    	$('headerControls').hide();
    	
    	var login = $('miniLoginForm');
    	login.show();
    	login.select('input')[0].focus();
    	
    },
    
    /**
     * Show a restaurant information popup 
     * but only after the user has hovered 
     * over the image for 2 seconds. While the user
     * is hovering, load the restaurant information
     * @param link The HTML A object that launched the request
     * @param id Restaurant Id
     */
    showRestaurantInfo: function(link, id)
    {
        //store the current restaurant id
        PM.currentRestaurant = id;
        
        //preload the restaurant information
        PM.getRestaurantHTML(id);
        
        //wait for 1 second
        setTimeout(function(){
            if(id == PM.currentRestaurant)
            {
            	try
            	{
	                var panel = PM.getRestaurantPanel();
	                var linkImage = link.getElementsByTagName('img')[0];
	                Position.clone(linkImage, panel, {setWidth: false, setHeight: false, offsetLeft: 140, offsetTop: 30});
	                var data = PM.getRestaurantHTML(id);
	                
	                //if we found data show the information popup
	                if(data != null && data != undefined)
	                {
	                    panel.innerHTML = data;
	                    panel.show();  
                }     
            	} catch (e){};
            }
        }, 1000);
        
    },
    
    /**
     * This method is called when the page loads. Anything
     * that needs to be called then for every page load needs to be
     * put in here.
     */
    startup: function()
    {
        //init the start rating controls
        PM.StarRating.initialize();
    },
    
    /**
     * This is attached to the onclick methods of links
     * and buttons that lead to pages that require the user to be logged in.
     * @param url An optional parameter. If it is specified, then activate the ur
     */
    validateSecureLink: function(url)
    {
        if(PM.LoginBox.available())
        {
            //user is not logged in
            PM.LoginBox.show();
            return false;
        }
        
        //see if we need to redirect
        if(url != null)
        {
            PM.navigate(url);
        }
    }
    
 });
 
 /**
  * Setup the map capabilities for PeepMeat
  * 
  */
 PM.Address = new Object();
 
 Object.extend(PM.Address, {
 
    /**
     * Called when the country drop down is changed
     */
    changeCountry: function(el)
    {
        var dropDown = $(el);
        if(dropDown == null)
            return;
            
        var name = dropDown.options[dropDown.selectedIndex].text;
        if(name == 'United States')
        {
            this.showState();
        } else
        {
            this.hideState();
        }
    },
 
    /**
     * Hide the state label and input filed
     */
    hideState: function()
    {
        $('stateFields').hide();
    },
    
    /**
     * Show the state label and input filed
     */
    showState: function()
    {
        $('stateFields').show();
    }
 
 }); 
 
 
 /**
  * Code to the control the paging of the gallery
  */
 PM.Gallery = new Object();

 Object.extend(PM.Gallery, {
 
	 width: 680,
	current_page: 1,
	gallery_size: 40,
	loaded_slides: {1: true},
	slides: $H(),
	moving: false, //is an animation currently taking place
	
	/**
	 * A cache for the slide element objects
	 */
	getSlideEl: function(page_num)
	{
		var slide = this.slides.get(page_num);
		if(slide == null)
		{
			var slide = $('leftcol').select('div.slide')[ (page_num-1) ];
			this.slides.set(page_num, slide);
		}
		return slide;
	},
 
	/**
	 * Move the requested gallery slide into the viewer
	 */
	movePage: function(el, page_num, e)
	{
		//kill the click event to prevent the history token from being updated
	 	if(e == null)
	 		e = window.event;
	 	
	 	if(e != null)
	 		Event.stop(e);
	 
	 	if(page_num == this.current_page || this.moving == true)
	 	{
	 		//we're already on the current page so do nothing
	 		return;
	 	}
	 	
	 	//deselect all page numbers
	 	$('leftcol').select('.pages a').each(function(anchor){
	 		anchor.removeClassName('selected');
	 	});
	 	
	 	//fill slide with gallery data if needed
	 	var loaded = this.loaded_slides[page_num];
	 	if( loaded != true)
	 	{
	 		
	 		//make ahah call to load image data
	 		var gallery_start = page_num * this.gallery_size - this.gallery_size;
	 		var url = 'ahah_gallery_grid.php?gallery_size='+ this.gallery_size + '&gallery_start=' + gallery_start;
	 		var target = this.getSlideEl(page_num);
	 		
	 		ahah(url, target);
	 		
	 		//mark that we have loaded data for this
	 		this.loaded_slides[page_num] = true;
	 	}
	 	
	 	//move the desired page to the viewer
	 	
	 	//calculate the slide
	 	var current_position = parseInt(this.current_page) * this.width - this.width;
	 	var desired_position = parseInt(page_num) * this.width - this.width;
	 	var needed_movement =  current_position - desired_position;	 	
	 	
	 	//perform move
	 	this.moving = true;
	 	new Effect.Move('gallerySlides', { x:  needed_movement, y: 0, transition: Effect.Transitions.sinoidal, mode: 'relative', afterFinish: function(){this.moving = false}.bind(this) });
	 	
	 	//select the current item
	 	this.current_page = parseInt(page_num);
	 	Element.Methods.addClassName(el,'selected');
	}
	
 });
 
  /**
  * Setup the hover login box
  * 
  */
PM.LoginBox = new Object();
 
Object.extend(PM.LoginBox, {
    
    name: 'popupLogin',

    /**
     * If the popupLogin box is not available,
     * that means that the user is logged in
     */
    available: function()
    {
        return this.getWindow() != null;
    },
    
    /**
     * Cache the popupLogin box el
     */
    getWindow: function()
    {
        if(this.popupLogin == null)
        {
            this.popupLogin = $(this.name);
        }
        
        return this.popupLogin;
    },
    
    /**
     * Hide the login box popup window
     */
    hide: function()
    {
        //return the login box to it's container
        this.getWindow().hide();
        $('popupLoginContainer').appendChild(this.getWindow());
        
        //re-enable the screen
        PM.Screen.enable();
    
        return false;
    },

    /**
     * Show the login and registration box
     */
    show: function()
    {
        //disable the screen
        PM.Screen.disable();
        
        var top = 0;
        
        //add the container for the login box
        if ( ! (D = $('shDisplay')) ) {
            D = document.createElement('div');
            D.setAttribute('id','shDisplay');
            document.getElementsByTagName('body')[0].appendChild(D);
        }
        
        //set the position of the box to the vertical middle of the screen
        var screenHeight = PM.Screen.height();
        var popupLoginHeight = this.getWindow().getHeight();  
        var scrollOffset = document.all ? document.documentElement.scrollTop  : window.pageYOffset;
        if(screenHeight > popupLoginHeight)
        {
            top = (screenHeight/2) - (popupLoginHeight/2) + scrollOffset;
        }
            
        //set the position
        D.style.top = top + 'px';
        
        //add the center element
        var centerEl = document.createElement('center')
        D.appendChild(centerEl);
        
        //add the login box
        centerEl.appendChild(this.getWindow());
        
        //show the login form
        this.getWindow().show();
    }

});
 
 
 /**
  * Setup the map capabilities for PeepMeat
  * 
  */
 PM.Map = new Object();
 
 Object.extend(PM.Map, {
 
    /**
     * Add a point to a google map
     * @param map The map to add the point to
     * @param address The address to show
     * @param cityAddress An address that is just the city and country
     * @return The point object
     */
    addPoint: function(map, options)
    {
        if(options == null)
            options = {};
         
        //default options
        options.centerMap = options.centerMap || false;
        options.zoomLevel = options.zoomLevel || 15;
        options.map = map;
    
        if(options.gps != null)
        {
            //show gps point
            var point = new GLatLng(options.gps.lat, options.gps.lng);
            PM.Map.displayPoint(point, map, options);
            return;
        }
        
        //lookup the gps infor using the address
        var geocoder = new GClientGeocoder();
        geocoder.getLatLng(options.fullAddress, function(point){PM.Map.displayPoint(point, map, options);});
    },
    
    displayPoint: function(point, map, options)
    {
        if (!point && options.cityAddress != null && options.cityAddress != "") 
        {
           //attempt to show a point of just the city and country
           options.fullAddress = options.cityAddress;
           options.cityAddress = null;
           return PM.Map.addPoint(map, options);
        } else if(!point)
        {
           return;
        }else 
        {
            if(options.centerMap)
            {
                map.setCenter(point, options.zoomLevel);
            }
                    
            var marker = new GMarker(point);
            map.addOverlay(marker);
                    
            if(options.html != null)
            {
             GEvent.addListener(marker, 'click', function() {  
               marker.openInfoWindowHtml(options.html);
               }); 
            }
        }
    },
 
    initializeMap: function()
    {
        var mapContainer = $('map');
        if(mapContainer == null || !GBrowserIsCompatible())
            return;
            
        //intialize the map
        var map = new GMap2(mapContainer);
        map.addControl(new GLargeMapControl());
        map.enableScrollWheelZoom(); 
        map.setCenter(new GLatLng(0, 0), 2);
        map.addControl(new GMapTypeControl());

        
        return map;
    },
 
    /**
     * Look for a map div and show the passed address
     * @param address The address to show
     * @param cityAddress An address that is just the city and country
     */
    showAddress: function(fullAddress, cityAddress, html)
    {
        var mapContainer = $('map');
        if(mapContainer == null || fullAddress == null || fullAddress == '' || !GBrowserIsCompatible())
            return;
            
        //intialize the map
        var map = new GMap2(mapContainer);
        //map.disableInfoWindow();
        map.addControl(new GSmallMapControl());
        map.enableScrollWheelZoom(); 
        
        //add the address to the map
        PM.Map.addPoint(map,{fullAddress:fullAddress, cityAddress:cityAddress, centerMap:true, html:html});
        
    },
    
    /**
     * Look for a map div and show the passed address
     * @param longitude The longitude to show
     * @param latitude The latitude to show
     */
    showGPSPoint: function(longitude, latitude)
    {
        var mapContainer = $('map');
        if(mapContainer == null || longitude == null || latitude == null || !GBrowserIsCompatible())
            return;
            
        //intialize the map
        var map = new GMap2(mapContainer);
        //map.disableInfoWindow();
        map.addControl(new GSmallMapControl());
        map.enableScrollWheelZoom(); 
        
        //add the address to the map
        PM.Map.addPoint(map,{gps:{lat:latitude, lng: longitude}, centerMap:true});
        
    }
 
 });

PM.Restaurant = new Object();

Object.extend(PM.Restaurant, {
	
	/**
	 * Called by the restaurant name autocompletor on the upload page
	 * @param el The li element that is selected
	 */
	selectAutocompleter: function(el)
	{
		var restaurantNameEl = $('restaurant');
		
		if(el== null || el == "" || restaurantNameEl == null)
			return;
			
		//set the restaurant name to the input box
		restaurantNameEl.value = el.select('.title')[0].innerHTML;
		
		//place the existing address on the screen
		var existingAddressEl= $('existingAddress');
		existingAddressEl.innerHTML = "<label>Address</label><br>"+el.select('.address')[0].innerHTML;
		existingAddressEl.show();
		
		//save the restaurant id
		$('restaurantId').value = el.getAttribute('rid');
	},
	
	showUploadScreen: function()
	{
		if(PM.LoginBox.available())
        {
            //user is not logged in
            PM.LoginBox.show();
            return false;
        } else if(PM.UploadBox.available())
        {
        	PM.UploadBox.show();
        	return false;
        }
	}
	
});


 
PM.Screen = new Object();
 
/**
 * A group of methods that are used to modify the screen
 */
Object.extend(PM.Screen, {

        
    /**
     * Place an overlay over the screen
     */
    disable: function()
    {
        if ( ! (S = $('shShutter')) ) {
            S = document.createElement('div');
            S.setAttribute('id','shShutter');
            document.getElementsByTagName('body')[0].appendChild(S);
        }
        
        //resize the overloay to the size of the screen
        S.style.height = PM.Screen.windowHeight() + 'px';
    },
    
    /**
     *Remove the overlay that is over the screen
     */
    enable: function()
    {
        Element.remove($('shShutter'));
    },
    
    /**
     * Get the visible height of the window
     */
    height: function()
    {
        if (typeof window.innerWidth != 'undefined')
        {
            return window.innerHeight;
        } else if (typeof document.documentElement != 'undefined' 
        && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
        {
            // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
            return document.documentElement.clientHeight;
        } else 
        {
            return document.getElementsByTagName('body')[0].clientHeight;
        }

    },
    
    /**
     * Get the height of the window including scroll height
     */
    windowHeight: function()
    {
        return Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);
    }
});


PM.Search = new Object();

Object.extend(PM.Search, {

	/**
	 * If there is no entered value, the add the search text and add the not active class
	 */
	disable: function()
	{
		if(this.el.value == '')
		{
			this.el.addClassName('notActive');
			this.el.value = 'Search';
		}
	},
	
	/**
	 * The user has clicked the saerch input for the first time
	 */
	enable: function(el)
	{
		if(el.className == 'notActive')
		{
			this.el = $(el);
			this.el.value = '';
			this.el.removeClassName('notActive');
			
			if(this.el.autocompleter != true)
			{
				new Ajax.Autocompleter(el.id, "search_choices", "autocomplete_restaurants.php", {
					paramName: "value", 
					minChars: 2, 
					parameters: "nr=1",
					//indicator: 'indicator1',
					updateElement: PM.Search.select.bind(this)
					
				});
				this.el.autocompleter = true;
			}
		}
	},
	
	//the user has selected a value from the drop down
	select: function(el)
	{		
		if(el== null || el == "")
			return;
			
		
		//save the restaurant id
		var restaurantId = el.getAttribute('rid');
		
		if(restaurantId != null)
			window.location = 'restaurant.php?id=' + restaurantId;
		else
			this.el.focus();
	}

});

 /**
  * Setup the star rating capabilities for PeepMeat
  * 
  */
PM.StarRating = new Object();
 
Object.extend(PM.StarRating, {
    
    /**
     * Find all of the star rating objects on the page
     * and extend them with the star rating class;
     *
     */
    initialize: function()
    {
        var ratings = $$('.inline-rating');
        for(var i = 0; i < ratings.length; i++)
        {
            new PM.StarRating.StarRatingControl(ratings[i]);
        }
    }

});

/*******************
 *
 * The star rating html control class
 *
 *******************/
PM.StarRating.StarRatingControl = Class.create({

    /****
     * Constructor
     * @param el The star rating element
     ****/
    initialize: function(el)
    {
        if(el == null)
            return;
    
        this.el = el;
        
        //store the important elements
        this.list = $$('ul.star-rating')[0];
        this.rating = $$('li.current-rating')[0];
        this.userRating = $$('li.current-user-rating')[0];
        
        //attach user interaction listeners
        this._attachListeners();
    },
    
    /**
     * Setup Mouse over listeners
     */
    _attachListeners: function()
    {
        //mouse over list
        this.listMouseOverListener = this.hideRating.bindAsEventListener(this);
        Event.observe(this.list, 'mouseover', this.listMouseOverListener);
        
        //mouse out of list
        this.listMouseOutListener = this.showRating.bindAsEventListener(this);
        Event.observe(this.list, 'mouseout', this.listMouseOutListener);
        
        //click/rating listener
        this.listClickListener = this.listClicked.bindAsEventListener(this);
        Event.observe(this.list, 'click', this.listClickListener);
    },
    
    /**
     * hide the global rating
     * @param e Event  
     */
    hideRating: function(e)
    {
        this.rating.hide();
        this.userRating.hide();
    },
    
    /**
     * The list has been clicked. Figure out the 
     * rating and then set it
     */
    listClicked: function(e)
    {
        if(e != null)
            Event.stop(e);

        //do we need to show the login box?
        if(PM.LoginBox.available())
        {
            //not logged in. Make the user login
            PM.LoginBox.show();
            return;
        }
            
        var item = Event.element(e);
        var rating = 0;
        var cssClass = item.className;
        if(cssClass == "one-star")
            rating = 1;
        else if(cssClass =="two-stars")
            rating = 2;
        else if(cssClass =="three-stars")
            rating = 3;
        else if(cssClass =="four-stars")
            rating = 4;
        else if(cssClass =="five-stars")
            rating = 5;  
            
        this.setRating(rating);
        
        item.blur();
    },
    
    /**
     * Show the global rating
     * @param e Event 
     */
    showRating: function(e)
    {
        this.rating.show();
        this.userRating.show();
    },

    /**
     * Set the rating on the db side
     * @param rating The rating to set
     */
    setRating: function(rating)
    {
        //the restaurant id
        var restaurantIdEl = $('restaurantId');
    
        if(rating == null || restaurantIdEl == null)
            return;
            
        //set the width of the user rating object
        this.setUserRatingWidth(rating);
        
        //set the rating on the server
        new Ajax.Request('json_add_restaurant_user_rating.php?id='+restaurantIdEl.value+"&rating="+rating, { method: 'get'});
    },
    
    /**
     * Set the width of the user rating object. Also
     * set the width of the global rating to 0
     * @param rating The rating to set
     */
    setUserRatingWidth: function(rating)
    {
        var width = rating * 18;
        this.rating.style.width = '0px';
        this.userRating.style.width = width + 'px';
    }
    
});


/**
 * Setup the hover image upload box
 * 
 */
PM.UploadBox = new Object();

Object.extend(PM.UploadBox, {
   
   name: 'popupUpload',
   showButtons: false,

   /**
    * Add a section so that the user can upload 
    * a 2nd, 3rd, or 4th image
    */
   SelectFile: function(event, seq, el)
   {
		if(event == null)
			event = window.event;
		
		//stop the hash from showing up in the url
		if(event != null)
			Event.stop(event);
	
		var imageUpload = document.createElement('div');
		imageUpload.className = 'imageUpload';
		var html = "";	
		
		//add upload box iframe
		var uploadIframe = $('upload' + seq);
		var url = 'imageupload/image_upload.php?seq='+ seq;
		var selectFile = $('uploads').select('.selectFile')[0];
		
		if(uploadIframe == null)
		{
			html += "<iframe id='upload"+ seq +"' src='"+ url +"' class='inline uploadFrame' FRAMEBORDER='0'></iframe>";
			html += '<div id="final'+seq+'" style="display:none"></div>';
			
			imageUpload.innerHTML = html;
			
			//attach to dom
			selectFile.appendChild(imageUpload);
		} else
		{
			uploadIframe.src = url;
			uploadIframe.style.display = '';
			
			imageUpload = $('upload' + seq).parentNode;
		}
		
		//move the uploadIFrame to the top
		if(selectFile.childNodes.length > 1)
		{
			selectFile.insertBefore(imageUpload, selectFile.childNodes[0]);	
		}
		
		//hide the type drop down
		   var dropDownWrapperEl = $('type'+seq); 
		   if(dropDownWrapperEl != null)
		   {
			   dropDownWrapperEl.hide();
		   }
		
		
		//hide the footer
		//$('popupUpload').select('.footer')[0].hide();
		
		//show the file selection
		selectFile.show();
		
		//move the arrow to point to the el
		el = $(el);
		var uploadArrow = selectFile.select('.uploadArrow')[0];
		var elPosition = el.positionedOffset();
		var selectFilePosition = selectFile.positionedOffset();
		
		//set arrow position
		uploadArrow.style.top = (selectFilePosition.top - uploadArrow.getHeight()) + "px";
		uploadArrow.style.left = (elPosition.left + el.getWidth()/2 - uploadArrow.getWidth()/2) + "px";
		
		uploadArrow.show();
   },
   
   /**
    * If the popupUpload box is not available,
    * that means that the user is logged in
    */
   available: function()
   {
       return this.getWindow() != null;
   },
   
   /**
    * Display an error to the user
    */
   error: function(message)
   {   
	   //show the new error
	   $('uploads').select('div.errors')[0].innerHTML = message;
   },
   
   /**
    * Cache the popupUpload box el
    */
   getWindow: function()
   {
       if(this.popupUpload == null)
       {
           this.popupUpload = $(this.name);
       }
       
       return this.popupUpload;
   },
   
   /**
    * Hide the upload box popup window
    */
   hide: function()
   {
       //return the login box to it's container
       this.getWindow().hide();
       $('popupUploadContainer').appendChild(this.getWindow());
       
       //re-enable the screen
       PM.Screen.enable();
   
       return false;
   },

   /**
    * Show the upload box
    */
   show: function()
   {
       //disable the screen
       PM.Screen.disable();
       
       var top = 0;
       
       //add the container for the upload box
       if ( ! (D = $('shDisplay')) ) {
           D = document.createElement('div');
           D.setAttribute('id','shDisplay');
           document.getElementsByTagName('body')[0].appendChild(D);
       }
       
       //set the position of the box to the vertical middle of the screen
       var screenHeight = PM.Screen.height();
       var popupLoginHeight = this.getWindow().getHeight();  
       var scrollOffset = document.all ? document.documentElement.scrollTop  : window.pageYOffset;
       if(screenHeight > popupLoginHeight)
       {
           top = (screenHeight/2) - (popupLoginHeight/2) + scrollOffset;
       }
           
       //set the position
       D.style.top = top + 'px';
       
       
       //add the center element
       var centerEl = document.createElement('center')
       D.appendChild(centerEl);
       
       //add the upload box
       centerEl.appendChild(this.getWindow());
       
       //show the upload form
       this.getWindow().show();
   },
   
   finishUpload: function(thumbName, fileName, mime, seq)
   {
	   this.hideProgress(seq);
	
	   var image = $('uploadImage' + seq).childNodes[0];
	   if(image != null)
	   {
		   image.setAttribute('src','images/uploads/'+thumbName);
		   image.setAttribute('original', fileName);
		   image.className = 'uploadedImage';
	   }
	   
	   //show the type drop down
	   var dropDownWrapperEl = $('type'+seq); 
	   if(dropDownWrapperEl != null)
	   {
		   dropDownWrapperEl.show();
	   }
	   
	   var realProgressFrame = document.getElementById('realProgress' + seq);
	   realProgressFrame.src = "blank.html";
	   this.showButtons = true;
	   this.toggleButtons();
	   this.updateArrowVerticalPosition();
   },
   
   hideProgress: function(seq)
   {
	   var uploadIframe = document.getElementById('upload' + seq);
	   //uploadIframe.style.height = "110px";
	   //uploadIframe.style.display="";
	   var progressArea = document.getElementById('progress' + seq);
	   progressArea.style.display = 'none';
   },
   
   /**
    * Reload the current page
    */
   reload: function()
   {
	   var restaurant_id = $('restaurantId').value;
	   window.location = 'restaurant.php?id='+restaurant_id;
   },
   
   /**
    * Save the uploaded images to the current restaurant
    */
   save: function()
   {
	   //perform validation to make sure that type has been selected for each image
	   var errorFound = false;
	   var restaurant_id = $('restaurantId').value
	   var url = 'id=' + restaurant_id;
	   
	   //first figure out how many images have been added
	   var images = $('uploads').select('.uploadedImage');
	   for(var i = 0; i < images.length; i++)
	   {
		   var el = images[i];
		   
		   //find the type drop down for this image
		   var selectEl = $(el.parentNode.parentNode).select('select')[0];
		   var selectValue = $F(selectEl);
		   var seq = i+1;
		   
		   if(selectValue == null || selectValue == "")
		   {
			   Element.addClassName(el, 'error');
			   this.error("Please specify the type of image.");
			   errorFound = true;
			   return;
		   } else
		   {
			   url += "&img"+ seq + "=" + el.getAttribute('original') + "&type"+ seq + "=" + selectValue;
			   
			   //remove any error markers
			   Element.removeClassName(el, 'error');
		   }
		   
	   }
	   
	   if(errorFound)
		   return;
	   else
		   this.error("");
	   
	   //disable save button
	   $('uploads').select('.saveButton').disabled = true;
	   
	   //perform save
       $data = new Ajax.Request("json_save_restaurant_image.php?"+url,
           {
               onSuccess: function(transport, json)
               {
    	   		 if(json.error)
    	   		 {
    	   			 this.error(json.error);
    	   			$('uploads').select('.saveButton').disabled = false;
    	   			
    	   		 } else if(json.success)
                 {
                	 this.reload();
                 }
                   
               }.bind(this),
               
               onFailure: function(transport, json)
               {
                 this.error('Ooops. There was a problem with the upload. Please reload the page and try again.');
                   
               }.bind(this)
           }
       );
	   
   },
   
   /**
    * Show the progress meter for the given URL
    */
   showProgress: function(seq, baseUrl)
   {
	   var uploadIframe = document.getElementById('upload' + seq);
	   uploadIframe.style.display="none";
	   var realProgress1Frame = document.getElementById('realProgress' + seq);
	   realProgress1Frame.src = baseUrl;
	   var progressArea = document.getElementById('progress' + seq);
	   progressArea.style.display = '';
	   var selectFile = $('uploads').select('.selectFile')[0];
	   selectFile.style.display = 'none';
	   
	   this.toggleButtons();
   },
   
   /**
    * Show the save and cancel buttons
    */
   toggleButtons: function()
   {
	   
	   if(this.showButtons)
	   {
		   var footer = this.getWindow().select('.footer')[0];
		   footer.style.display = '';
	   }
   },
   
   /**
    * Reposition the arrow vertically 
    */
   updateArrowVerticalPosition: function()
   {  
	   var selectFile = $('uploads').select('.selectFile')[0];
	   var uploadArrow = selectFile.select('.uploadArrow')[0];
	   var selectFilePosition = selectFile.positionedOffset();

	   if(uploadArrow.visible())
		   uploadArrow.style.top = (selectFilePosition.top - uploadArrow.getHeight()) + "px";
	   
   },
   
   updateProgress: function(seq, fileSize, percent, timeReamining)
   {
	   
	   //window.console.log("Seq: "+ seq + " Size: " + fileSize +  "Progress: "+percent+ " Time: " + timeReamining);
	   
	   var progressContent = $('progress' + seq);
	   if(progressContent != null)
	   {
		   var progressEl = progressContent.select('.progress')[0];
		   var textEl = progressContent.select('.progressText')[0];
		   var mbSize = Math.round(fileSize/1048576*100000)/100000; //convert to MB
		   mbSize = Math.round(mbSize*Math.pow(10,2))/Math.pow(10,2); //trim to two decimal places
		   
		   progressEl.style.width = percent + "%";
		   textEl.innerHTML = mbSize + 'MB &nbsp;&nbsp;&nbsp;' + timeReamining + ' rem';
	   }
   }

});





/** Always at the bottom of this file **/
onContent(PM.startup);






/*******************
*
* ahah code
*
*********************/


function ahah(url,target) {
    //document.getElementById(target).innerHTML = 'loading data...';
	target = $(target);
	
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = function() {ahahDone(target);};
        req.open("GET", url, true);
        req.send(null);
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() {ahahDone(target);};
            req.open("GET", url, true);
            req.send();
        }
    }
} 

function ahahDone(target) {
   // only if req is "loaded"
   if (req.readyState == 4) {
       // only if "OK"
       if (req.status == 200 || req.status == 304) {
           results = req.responseText;
           target.innerHTML = results;
       } else {
           target.innerHTML="ahah error:\n" +
               req.statusText;
       }
   }
}


/*******************
*
* Shutter.js code
*
*********************/
/*
Shutter Reloaded
http://www.laptoptips.ca/javascripts/shutter-reloaded/
Version: 2.0.1

Acknowledgement: some ideas are from: Shutter by Andrew Sutherland - http://code.jalenack.com, WordPress - http://wordpress.org, Lightbox by Lokesh Dhakar - http://www.huddletogether.com, the icons are from Crystal Project Icons, Everaldo Coelho, http://www.everaldo.com

Released under the GPL, http://www.gnu.org/copyleft/gpl.html

    Copyright (C) 2007  Andrew Ozz

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
*/

shutterReloaded = {

// ***************************************************************************

//    edit below to change the text buttons/titles for the menu (use html entities for non-ascii characters)
      L10n : ['Previous','Next','Close','Full Size','Fit to Screen','Image','of','Loading...'],
      
//    change to "true/false" to enable/disable showing the number of images in a set.
      imageCount : true,
      
//    change to true/false to enable/disable text buttons instead of images
      textBtns : false,
      
//    change the path to Shutter's image buttons directory if needed
      shImgDir : './images/',
      
// ***************************************************************************
  
  I : function (a) {
    return document.getElementById(a);
  },

  Init : function (a) {
    var L, T, ext, i, setid, inset, shfile, shMenuPre, k, img;
    for ( i = 0; i < document.links.length; i++ ) {
      L = document.links[i];
      ext = ( L.href.indexOf('?') == -1 ) ? L.href.slice(-4).toLowerCase() : L.href.substring( 0, L.href.indexOf('?') ).slice(-4).toLowerCase();
      if ( ext != '.jpg' && ext != '.png' && ext != '.gif' && ext != 'jpeg' ) continue;
      if ( a == 'sh' && L.className.toLowerCase().indexOf('shutter') == -1 ) continue;
      if ( a == 'lb' && L.rel.toLowerCase().indexOf('lightbox') == -1 ) continue;

      if ( L.className.toLowerCase().indexOf('shutterset') != -1 ) 
        setid = ( L.className.indexOf(' ') != -1 ) ? L.className.slice(0,L.className.indexOf(' ')) : L.className;
      else if ( L.rel.toLowerCase().indexOf('lightbox[') != -1 ) 
        setid = L.rel;
      else setid = 0, inset = -1;
      
      if( setid ) {
        if ( ! shutterSets[setid] ) shutterSets[setid] = []; 
        inset = shutterSets[setid].push(i);
      }
      
      shfile = L.href.slice(L.href.lastIndexOf('/')+1);
      T = ( L.title && L.title != shfile ) ? L.title : '';
      
      shutterLinks[i] = {link:L.href,num:inset,set:setid,title:T}
      L.onclick = new Function('shutterReloaded.Make("'+i+'");return false;');
    }
    
    if ( ! this.textBtns ) {
      shMenuPre = ['close.gif','prev.gif','next.gif','resize1.gif','resize2.gif','loading.gif'];
      for ( k = 0; k < shMenuPre.length; k++ ) {
        img = new Image();
        img.src = this.shImgDir+shMenuPre[k];
      }
    }
  },

  Make : function(ln,fs) {
    var prev, next, prevlink = '', nextlink = '', previmg, nextimg, prevbtn, nextbtn, D, S, W, NB, fsarg = '', imgNum, closebtn, fsbtn, fsLink;

    if ( ! this.Top ) {
      if ( typeof window.pageYOffset != 'undefined' ) this.Top = window.pageYOffset;
      else this.Top = (document.documentElement.scrollTop > 0) ? document.documentElement.scrollTop : document.body.scrollTop;
    }
    
    if ( typeof this.pgHeight == 'undefined' ) 
      this.pgHeight = Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);
    
    if ( fs ) this.FS = true;
    else this.FS = null;
    
    if ( this.resizing ) this.resizing = null;
    window.onresize = new Function('shutterReloaded.Resize("'+ln+'");');
    
    document.documentElement.style.overflowX = 'hidden';
    if ( ! this.VP ) {
      this._viewPort();
      this.VP = true;
    }
    
    if ( ! (S = this.I('shShutter')) ) {
      S = document.createElement('div');
      S.setAttribute('id','shShutter');
      document.getElementsByTagName('body')[0].appendChild(S);
      this.fixTags();
    }

    if ( ! (D = this.I('shDisplay')) ) {
      D = document.createElement('div');
      D.setAttribute('id','shDisplay');
      D.style.top = this.Top + 'px';
      document.getElementsByTagName('body')[0].appendChild(D);
    }

    S.style.height = this.pgHeight + 'px';    
    
    var dv = this.textBtns ? ' | ' : '';
    if ( shutterLinks[ln].num > 1 ) {
      prev = shutterSets[shutterLinks[ln].set][shutterLinks[ln].num - 2];
      prevbtn = this.textBtns ? this.L10n[0] : '<img src="'+this.shImgDir+'prev.gif" title="'+this.L10n[0]+'" />';
      prevlink = '<a href="#" onclick="shutterReloaded.Make('+prev+');return false">'+prevbtn+'</a>'+dv;
      previmg = new Image();
      previmg.src = shutterLinks[prev].link;
    }
    
    if ( shutterLinks[ln].num != -1 && shutterLinks[ln].num < (shutterSets[shutterLinks[ln].set].length) ) {
      next = shutterSets[shutterLinks[ln].set][shutterLinks[ln].num];
      nextbtn = this.textBtns ? this.L10n[1] : '<img src="'+this.shImgDir+'next.gif" title="'+this.L10n[1]+'" />';
      nextlink = '<a href="#" onclick="shutterReloaded.Make('+next+');return false">'+nextbtn+'</a>'+dv;
      nextimg = new Image();
      nextimg.src = shutterLinks[next].link;
    }
    
    closebtn = this.textBtns ? this.L10n[2] : '<img src="'+this.shImgDir+'close.gif" title="'+this.L10n[2]+'" />';
    
    imgNum = ( (shutterLinks[ln].num > 0) && this.imageCount ) ? ' '+this.L10n[5]+'&nbsp;'+shutterLinks[ln].num+'&nbsp;'+this.L10n[6]+'&nbsp;'+shutterSets[shutterLinks[ln].set].length : '';
    if ( imgNum && this.textBtns ) imgNum += ' |';

    if ( this.FS ) {
      fsbtn = this.textBtns ? this.L10n[4] : '<img src="'+this.shImgDir+'resize2.gif" title="'+this.L10n[4]+'" />';
    } else {
      fsbtn = this.textBtns ? this.L10n[3] : '<img src="'+this.shImgDir+'resize1.gif" title="'+this.L10n[3]+'" />';
      fsarg = ',1';
    }
    
    fsLink = '<span id="fullSize"><a href="#" onclick="shutterReloaded.Make('+ln+fsarg+');return false">'+fsbtn+'</a>'+dv+'</span>';
    
    if ( ! (NB = this.I('shNavBar')) ) {
      NB = document.createElement('div');
      NB.setAttribute('id','shNavBar');
      document.getElementsByTagName('body')[0].appendChild(NB);
    }
    
    NB.innerHTML = dv+prevlink+'<a href="#" onclick="shutterReloaded.hideShutter();return false">'+closebtn+'</a>'+dv+fsLink+nextlink+imgNum;
    
    D.innerHTML = '<div id="shWrap"><img src="'+shutterLinks[ln].link+'" id="shTopImg" onload="shutterReloaded.ShowImg();" onclick="shutterReloaded.hideShutter();" /><div id="shTitle">'+shutterLinks[ln].title+'</div></div>';
    
    window.setTimeout(function(){shutterReloaded.loading();},2000);
  },
  
  loading : function() {
    var S, WB, W;
    if ( (W = this.I('shWrap')) && W.style.visibility == 'visible' ) return;
    if ( ! (S = this.I('shShutter')) ) return;
    if ( this.I('shWaitBar') ) return;
    WB = document.createElement('div');
    WB.setAttribute('id','shWaitBar');
    WB.style.top = this.Top + 'px';
    WB.innerHTML = '<img src="'+this.shImgDir+'loading.gif" title="'+this.L10n[7]+'" />';
    S.appendChild(WB);
  },
  
  hideShutter : function() {
    var D, S, NB;
    if ( D = this.I('shDisplay') ) D.parentNode.removeChild(D);
    if ( S = this.I('shShutter') ) S.parentNode.removeChild(S);
    if ( NB = this.I('shNavBar') ) NB.parentNode.removeChild(NB);
    this.fixTags(true);
    window.scrollTo(0,this.Top);
    window.onresize = this.FS = this.Top = this.VP = null;
    document.documentElement.style.overflowX = '';
  },

  Resize : function(ln) {
    if ( this.resizing ) return;
    if ( ! this.I('shShutter') ) return;
    var W = this.I('shWrap');
    if ( W ) W.style.visibility = 'hidden';
    
    window.setTimeout(function(){shutterReloaded.resizing = null},500);
    window.setTimeout(new Function('shutterReloaded.VP = null;shutterReloaded.Make("'+ln+'");'),100);
    this.resizing = true;
  },
  
  _viewPort : function() {
    var wiH = window.innerHeight ? window.innerHeight : 0;
    var dbH = document.body.clientHeight ? document.body.clientHeight : 0;
    var deH = document.documentElement ? document.documentElement.clientHeight : 0;
      
    if( wiH > 0 ) {
      this.wHeight = ( (wiH - dbH) > 1 && (wiH - dbH) < 30 ) ? dbH : wiH;
      this.wHeight = ( (this.wHeight - deH) > 1 && (this.wHeight - deH) < 30 ) ? deH : this.wHeight;
    } else this.wHeight = ( deH > 0 ) ? deH : dbH;

    var deW = document.documentElement ? document.documentElement.clientWidth : 0;
    var dbW = window.innerWidth ? window.innerWidth : document.body.clientWidth;
    this.wWidth = ( deW > 1 ) ? deW : dbW;
  },
  
  ShowImg : function() {
    var S, W, WB, D, T, TI, NB, wHeight, wWidth, capH, shHeight, maxHeight, itop, mtop, resized = 0;
    if ( ! (S = this.I('shShutter')) ) return;
    if ( (W = this.I('shWrap')) && W.style.visibility == 'visible' ) return;
    if ( WB = this.I('shWaitBar') ) WB.parentNode.removeChild(WB);
    
    D = this.I('shDisplay');
    TI = this.I('shTopImg');
    T = this.I('shTitle');
    NB = this.I('shNavBar');
    S.style.width = D.style.width = '';
    T.style.width = (TI.width - 4) + 'px';
    
    capH = NB.offsetHeight ? T.offsetHeight + NB.offsetHeight : 30;
    shHeight = this.wHeight - 7 - capH;

    if ( this.FS ) {
      if ( TI.width > (this.wWidth - 10) ) 
        S.style.width = D.style.width = TI.width + 10 + 'px';
        document.documentElement.style.overflowX = '';
    } else {
      window.scrollTo(0,this.Top);
      if ( TI.height > shHeight ) {
        TI.width = TI.width * (shHeight / TI.height);
        TI.height = shHeight;
        resized = 1;
      }
      if ( TI.width > (this.wWidth - 16) ) {
        TI.height = TI.height * ((this.wWidth - 16) / TI.width);
        TI.width = this.wWidth - 16;
        resized = 1;
      }
      T.style.width = (TI.width - 4) + 'px';
      NB.style.bottom = '0px';
    }

    maxHeight = this.Top + TI.height + capH + 10;
    if ( maxHeight > this.pgHeight ) S.style.height = maxHeight + 'px'; 
    window.scrollTo(0,this.Top);
    if ( (this.FS && (TI.height > shHeight || TI.width > this.wWidth)) || resized ) this.I('fullSize').style.display = 'inline';
    
    itop = (shHeight - TI.height) * 0.45;
    mtop = (itop > 3) ? Math.floor(itop) : 3;
    D.style.top = this.Top + mtop + 'px';
    NB.style.bottom = '0';
    W.style.visibility = 'visible';
  },

  fixTags : function(arg) {
	var sel = document.getElementsByTagName('select');
	var obj = document.getElementsByTagName('object');
	var emb = document.getElementsByTagName('embed');
    
    if ( arg ) var vis = 'visible';
    else var vis = 'hidden';
    
    for (i = 0; i < sel.length; i++) sel[i].style.visibility = vis;
    for (i = 0; i < obj.length; i++) obj[i].style.visibility = vis;
    for (i = 0; i < emb.length; i++) emb[i].style.visibility = vis;
  }
}

if (typeof shutterOnload == 'function') {
  var shutterLinks = {}, shutterSets = {};
  oldonload = window.onload;
  if( typeof window.onload != 'function' ) window.onload = shutterOnload;
  else window.onload = function(){shutterOnload();if(oldonload){oldonload();}};
}

//load when the page loads
var shutterLinks = {}, shutterSets = {};
onContent(function(){shutterReloaded.Init();});