var Tip = Class.create({
	initialize: function(container, tooltip, element) {
		this.container = $(container);
		this.tooltip   = $(tooltip);
		this.element   = $(element);
		this.setup();
	},
	setup: function() {
		this.element.observe("click", this.show.bindAsEventListener(this));
	},
	show: function(event) {
		this.container.makePositioned();
		
		var cpos  = this.container.cumulativeOffset();
		var epos  = this.element.positionedOffset();
		var edims = this.element.getDimensions();
		var tdims = this.tooltip.getDimensions();
		
		var left = epos.left - 18;
		var top  = epos.top - 45;
		
		if (left < 490) {
			left = epos.left + edims.width + 25;
			this.tooltip.removeClassName("reversed");
		} else {
			left = epos.left - tdims.width + -17;
			this.tooltip.addClassName("reversed");
		}
	  
		this.tooltip.setStyle({
			left:    (left) + "px",
			top:     (top) + "px"
		});
		
		if (Tip.Active) {
			Tip.Active.element.removeClassName("selected");
		}
		
		// NOTE SEVENWIRE CHANGES BELOW
		geo_id = this.element.href.match(/\/(\d+)\//)[1]		
		new Ajax.Updater(this.tooltip.down("div.content"), '/guides/' + geo_id + '/cities_for_state');
		
		this.tooltip.show();
		this.element.addClassName("selected");
		
		this.listener = this.hide.bindAsEventListener(this);
		Event.observe(document, "accordion:opened", this.listener);
		Event.observe(document, "accordion:closed", this.listener);
		Event.observe(document, "click", this.listener);
		Event.observe(this.tooltip, "click", function() {
			this.wait = true; }.bind(this));
		
		Tip.Active = this;
		event.stop();
	},
	hide: function(event) {
		if (this.wait) return;
		this.container.undoPositioned();
		Event.stopObserving(document, "accordion:opened", this.listener);
		Event.stopObserving(document, "accordion:closed", this.listener);
		Event.stopObserving(document, "click", this.listener);
		this.tooltip.hide();
		this.element.removeClassName("selected");
		Tip.Active = false;
		if (event) event.stop();
	}
});


/* ---------------------------------------------------------------- */

document.observe("dom:loaded", function(){
	new Accordion("accordion");
	
	$("tool-tip").hide();
	$$("#states-by-country a").each(function(el) {
		new Tip("smart-guide-on-regions", "tool-tip", el);
	});
	
	if($('search-destination')){
		new SearchSuggestion('search-destination', '/partials/search-suggestions.html');
	}
});
