eat.restaurant = {
    init: function() {
		this.images.init();
    },
	
    images: {
    	first: true,
    	index: 0,
    	total: 0,
    	position: 0,
    	widths: [],
    
        init: function() {
			var self = this;
        
        	// calculate total
        	this.total = $('#restaurant-images .entry').length;
        
        	// collect widths
        	$('#restaurant-images .entry').each(function() {
				var imageWidth = $('img', this).attr('width');
				var entryWidth = $(this).attr('width');
				
				if(entryWidth) {
					self.widths.push(parseInt(entryWidth));						
				}
				else {
					self.widths.push(parseInt(imageWidth));	
				}
        	});
        
        	// bind controls
			$('#restaurant-images-previous').bind('click', function() {
				self.previousImage();
			});
			
			$('#restaurant-images-next').bind('click', function() {
				self.nextImage();
			});
			
			// hovers
			$('#restaurant-images .entry')
			.bind('mouseover', function() {
				$('.entry-caption', this).show();
			})
			.bind('mouseout', function() {
				$('.entry-caption', this).hide();
			});
			
			this.checkLinks();
			
			// finalize init
			this.first = false;
        },
        
        nextImage: function() {
			if(this.index<(this.total-2)) {
				this.position = this.position-(this.widths[this.index]+1);
				
				$('#restaurant-images .entries').animate({
					left:this.position
				}, 500);
				
				this.index++;
				
				this.checkLinks();
			};
        },
        
        previousImage: function() {
        	if(this.index>0) {
				this.position = this.position+(this.widths[this.index-1]+1);
				
				$('#restaurant-images .entries').animate({
					left:this.position
				}, 500);
				
				this.index--;
				
				this.checkLinks();
			};
        },
        
        checkLinks: function() {
        
			// check control visibilities
			if(this.index == 0 || this.total < 3) {
				this.hidePreviousLink();
			}
			else {
				this.showPreviousLink();			
			};
			
			if(this.index == (this.total-2) || this.total < 3) {
				this.hideNextLink();
			}
			else {
				this.showNextLink();			
			};
        },
        
        hidePreviousLink: function() {
			if (core.browser.msie6) {
				$('#restaurant-images-previous').hide();
			}
			else {
				$('#restaurant-images-previous').fadeOut(1000);
			}
        },
        
        showPreviousLink: function() {
        	if(this.first || core.browser.msie6) {
				$('#restaurant-images-previous').show();
			}
			else {
				$('#restaurant-images-previous').fadeIn(1000);			
			};
        },
        
        hideNextLink: function() {
			if(core.browser.msie6) {
				$('#restaurant-images-next').hide();					
			}
			else {
				$('#restaurant-images-next').fadeOut(1000);	
			}
        },
        
        showNextLink: function() {
        	if(this.first || core.browser.msie6) {
				$('#restaurant-images-next').show();
			}
			else {
				$('#restaurant-images-next').fadeIn(1000);			
			};
        }
    },
    
    livebookings: {    	
    	open: function(url) {
    		var win = window.open(url, 'livebookings', 'width=540,height=500,location=no,status=no,favorites=no,bookmarks=no');
    	}
    },
	
	features: {
        vote: function(url, id) {
            $.get(url, false, function(data) {
                var feature = $('#restaurant-feature-'+data.id);
                $('.feature-votecount', feature).hide();
                $('.feature-voteadded', feature).show();
            }, 'json');  
        }
	}
};

$(document).ready(function() {
	eat.restaurant.init();
});
eat.restaurantEditor = {    
    init: function() {

		// basic editor
		$('#restaurant-info').append(this.getOpenerHtml('basic', __('restaurant.editor.editBasicButton'))).bind('click', function() {
			core.frame.open(eat.settings.editorBasicUrl, __('restaurant.editor.basicLoading'));
		});
		
		// contact editor
		$('#restaurant-contact .entries').append(this.getOpenerHtml('contact', __('restaurant.editor.editContactButton'))).bind('click', function() {
			core.frame.open(eat.settings.editorContactUrl, __('restaurant.editor.contactLoading'));
		});

		// times editor
		$('#opening-times').append(this.getOpenerHtml('times', __('restaurant.editor.editTimesButton'))).bind('click', function() {
			core.frame.open(eat.settings.editorTimesUrl, __('restaurant.editor.timesLoading'));
		});
		
		// bind events
		$('.editor-opener')
		.bind('mouseover', function() {
			$(this).addClass('hover');
		})
		.bind('mouseout', function() {
			$(this).removeClass('hover');
		});
    },
	
	getOpenerHtml: function(id, text) {
		return '<div class="editor-opener" id="opener-'+id+'"><div class="editor-opener-data">'+text+'</div></div>';
	}
};

$(document).ready(function() {
	//eat.restaurantEditor.init();
});
eat.restaurantStreetView = {
    dom: {},
    settings: {},
    latlng: {},
    location: null,
    
    init: function() {
        this.dom.link = $("#street-view-link");
        
        if ("GBrowserIsCompatible" in window && GBrowserIsCompatible() && eat.restaurantStreetView.settings.enabled) {
            this.client = new GStreetviewClient();
            
            this.latlng.restaurant = new GLatLng(eat.restaurantStreetView.settings.lat, eat.restaurantStreetView.settings.lng);
            
            if (eat.restaurantStreetView.settings.viewLat !== null && eat.restaurantStreetView.settings.viewLng !== null) {
                // use custom values
                this.latlng.use = new GLatLng(eat.restaurantStreetView.settings.viewLat, eat.restaurantStreetView.settings.viewLng);
                
                if (eat.restaurantStreetView.settings.yaw === null) {
                    eat.restaurantStreetView.calculateYaw();
                }
                
                this.validate(this.latlng.use);
            } else {
                // get latlng by address
                this.geocoder = new GClientGeocoder();
                this.geocoder.getLatLng(eat.restaurantStreetView.settings.address, function(latlng) {
                    if (!!latlng) {
                        // use result from Google's reverse geocoder
                        eat.restaurantStreetView.latlng.use = latlng;
                        eat.restaurantStreetView.calculateYaw();
                    } else {
                        // no result, use restaurant's coordinates
                        eat.restaurantStreetView.latlng.use = eat.restaurantStreetView.latlng.restaurant;
                    }
                    eat.restaurantStreetView.validate(eat.restaurantStreetView.latlng.use);
                });
            }
            
            this.dom.link.click(this.open);
        } else {
            this.dom.link.hide();
        }
	},
	
	open: function() {
        core.frame.open(null, eat.locale.strings['restaurant.streetview.loading']);
        
        eat.restaurantStreetView.dom.container = $("#coreFrameContentWrapper");
        eat.restaurantStreetView.view = new GStreetviewPanorama(eat.restaurantStreetView.dom.container.get(0), {
            features: {
                streetView: true,
                userPhotos: false
	        }
        });
        GEvent.addListener(eat.restaurantStreetView.view, "error", eat.restaurantStreetView.handleError);
        GEvent.addListener(eat.restaurantStreetView.view, "initialized", function(location) {
            eat.restaurantStreetView.location = location;
        });
	    
        eat.restaurantStreetView.view.setLocationAndPOV(
            eat.restaurantStreetView.latlng.use, 
            {
                yaw: (eat.restaurantStreetView.settings.yaw || 0),
                pitch: (eat.restaurantStreetView.settings.pitch || 5),
                zoom: (eat.restaurantStreetView.settings.zoom || 0)
            }
        );
	    
        core.frame.loaded();
	},
	
	close: function() {
	    eat.restaurantStreetView.dom.container.hide();
	    eat.restaurantStreetView.view.remove();
	},
	
	validate: function(latlng) {
        this.client.getNearestPanorama(latlng, this.handleValidateResponse);
	},
    
    handleValidateResponse: function(data) {
        // Street View is not available for the current location
        if (data.code != 200) {
            eat.restaurantStreetView.settings.enabled = false;
            eat.restaurantStreetView.dom.link.hide();
        } else {
            eat.restaurantStreetView.dom.link.show();
        }
    },
    
    calculateYaw: function() {
        // calculate direction
        // http://gmaps-samples.googlecode.com/svn/trunk/streetview/angletowardsbuilding.html
        var dlat = eat.restaurantStreetView.latlng.restaurant.lat() - eat.restaurantStreetView.latlng.use.lat();
        var dlng = eat.restaurantStreetView.latlng.restaurant.lng() - eat.restaurantStreetView.latlng.use.lng();
        var yaw = Math.atan2(dlng * Math.cos(eat.restaurantStreetView.latlng.restaurant.lat() * 0.017453), dlat) * 57.2957795;
        
        if (yaw >= 360) {
            yaw -= 360;
        } else if (yaw < 0) {
            yaw += 360;
        }
        
        eat.restaurantStreetView.settings.yaw = yaw;
    },
    
	handleError: function(code) {
        if (code == 603) {
            alert("Flash Player is required to display Street View.");
        }
    },
    
    dump: function() {
        if (eat.restaurantStreetView.location) {
            return $.extend(eat.restaurantStreetView.location.pov, {
                lat: eat.restaurantStreetView.location.lat,
                lng: eat.restaurantStreetView.location.lng
            });
        } else {
            return null;
        }
    }
};

$(document).ready(function() {
	eat.restaurantStreetView.init();
});
