var TipFinder = Class.create({
	initialize: function(container) {
		this.container = $(container);
		this.form      = this.container.down("form");
		this.selects   = this.form.select("select");
		this.fields    = this.container.select("div.field");
		this.total     = this.fields.length;
		this.setup();
	},
	setup: function() {
		this.fields.each(function(el, i) {
			options = this.selects[i].select("option")
			if (i < 2 || options.length > 1) return;
			el.addClassName("disable");
			this.selects[i].disable();
		}.bind(this));
		
		this.selects.each(function(el, i) {
			el.observe("change", this.update.bind(this, i)); }.bind(this));
	},
	update: function(i) {
		// NOTE SEVENWIRE CHANGES BELOW
		var target = i + 1;
		if (i == 0) return;
		
		geo_id = this.selects[i].options[this.selects[i].selectedIndex].value;
		if (target == 2){
			is_regional = 1;
		}
		else{
			is_regional = 0;
		}
		if (this.fields[target]) {
                        if (geo_id == 'all') {
                          //If setting a field to 'All', it should reset any fields underneath it. No need to make AJAX call either
                          this.selects[target].options.length = 0;
                          this.selects[target].options[0] = new Option('All', 'all');
                          this.selects[target].disable();
                          this.fields[target].addClassName("disable");
                        }
                        else {
			this.fields[target].removeClassName("disable");
			this.selects[target].enable();
			this.target = target;
			
			new Ajax.Request("/tip_listings/tips_geos", {
				method:     "get",
				parameters: "geo_id=" + geo_id + "&is_regional=" + is_regional,
				onComplete: this.populate.bind(this)
			});}
		}
                if (is_regional == 1) {
                  //Reset the city field when the region is updated
                  this.selects[target+1].options.length = 0;
                  this.selects[target+1].options[0] = new Option('All', 'all');
                  this.selects[target+1].disable();
                  this.fields[target+1].addClassName("disable");
                }
	},
	populate: function(transport) {
		var json   = transport.responseText.evalJSON();
		var target = this.target;
		
		this.selects[target].options.length = 0;
		for (var i = 0; i < json.length + 1; i++) {
			if (i == 0) {
				this.selects[target].options[i] = new Option('All', 'all');
				i++;
			}
			this.selects[target].options[i] = new Option(json[i-1].name, json[i-1].label);
		}
	}
});

/* ---------------------------------------------------------------- */

var PostTip = Class.create(PopOut, {
	initialize: function(trigger, target) {
		this.trigger = $(trigger);
		this.target  = $(target);
		this.options      = this.target.select("div.option");
		this.locations    = this.target.down("div.tip-locations");
		this.new_location = this.target.down("a.new-location");
		this.cancel_btn   = this.target.down("a.cancel");
		this.setup();
	},
	setup: function($super) {
		this.options.each(function(el) {
			el.observe("click", this.toggle.bindAsEventListener(this))}.bind(this));
		// this.new_location.observe("click", this.add_location.bindAsEventListener(this));
		this.cancel_btn.observe("click", this.flip.bindAsEventListener(this));
		this.create_location();
		$super();
	},
	toggle: function(event) {
		var option   = event.findElement("div.option");
		var checkbox = option.down("input.checkbox");
		
		option.toggleClassName("checked");
		checkbox.checked = !checkbox.checked;
		
		event.stop();
	},
	add_location: function(event) {
		new Ajax.Updater(this.locations, "/partials/tips/post.location.html", {
			method: "get",
			insertion: Insertion.Bottom
		});
		this.create_location();
		event.stop();
	},
	create_location: function() {
		var location = this.locations.select("div.row").last()
		new PostTip.Location(location)
	}
});

/* ---------------------------------------------------------------- */

var PostGuideTip = Class.create(PopOut, {
	initialize: function(trigger, target) {
		this.trigger = $(trigger);
		this.target  = $(target);
		this.options      = this.target.select("div.option");
		this.cancel_btn   = this.target.down("a.cancel");
		this.setup();
	},
	setup: function($super) {
		this.options.each(function(el) {
			el.observe("click", this.toggle.bindAsEventListener(this))}.bind(this));
		// this.new_location.observe("click", this.add_location.bindAsEventListener(this));
		this.cancel_btn.observe("click", this.flip.bindAsEventListener(this));
		$super();
	},
	toggle: function(event) {
		var option   = event.findElement("div.option");
		var checkbox = option.down("input.checkbox");
		
		option.toggleClassName("checked");
		checkbox.checked = !checkbox.checked;
		
		event.stop();
	}
});

/* ---------------------------------------------------------------- */

PostTip.Location = Class.create({
	initialize: function(container) {
		this.container = container;
		this.selects   = this.container.select("select");
		this.setup();
	},
	setup: function() {
		this.selects.each(function(el, i) {
			if (i > 0) {
				el.disable();
			};
			el.observe("change", this.update.bind(this, i));
		}.bind(this));
	},
	update: function(i) {
		var target = i + 1;
		
		geo_id = this.selects[i].options[this.selects[i].selectedIndex].value;
		if (target == 1){
			is_regional = 1;
		}
		else{
			is_regional = 0;
		}
		if(!!this.selects[target]) this.selects[target].enable();
		this.target = target;
		
		new Ajax.Request("/tip_listings/tips_geos", {
			method:     "get",
			parameters: "geo_id=" + geo_id + "&is_regional=" + is_regional,
			onComplete: this.populate.bind(this)
		});
	},
	populate: function(transport) {
		var json   = transport.responseText.evalJSON();
		var target = this.target;
		var label  = this.selects[target].options[0].innerHTML;
		this.selects[target].options.length = 0;
		for (var i = 0; i < json.length; i++) {
			if (i == 0) {
				this.selects[target].options[i] = new Option(label, '');
				i++;
			}
			this.selects[target].options[i] = new Option(json[i-1].name, json[i-1].id);
		}
	}
})

/* ---------------------------------------------------------------- */

// The dom:loaded event is blowing up in IE6 during Enumerable, so skip the ProtoType stuff.
if (!(navigator.userAgent.indexOf("MSIE 6") != -1 && navigator.userAgent.indexOf("Opera") == -1) )
    document.observe("dom:loaded", function() {
	var err;
	
	if ($("tip-finder")) 
	{
		try
		{
			new TipFinder("tip-finder");
		}
		catch (err) { alert(err.description); }
	}
	
	// if ($("add-tip-toggler") && $("add-a-tip") && !$("guide-tip")) {
	// 	new PostTip("add-tip-toggler", "add-a-tip");	
	// }

	// if ($("add-tip-toggler") && $("add-a-tip") && $("guide-tip")) {
	// 	new PostGuideTip("add-tip-toggler", "add-a-tip");	
	// }
	
	if ($("filter-toggle") && $("filter-by-theme")) 
	{
		try
		{
			new Filter("filter-toggle", "filter-by-theme", "");	
		}
		catch (err)
		{
			alert(err.description);
		}
		
	}
   
  new Accordion("accordion");	
  
});

//function exists to pass value over to HAML add_tips

function add_tips_select_topic(topic)
{
  topics_array.push(topic);
  print_topics_list();
  $("topics_list_input").value = topics_array;
}

function remove_tips_select_topic(topic)
{
  topics_array = topics_array.without(topic);
  print_topics_list();
  $("topics_list_input").value = topics_array;
}

function print_topics_list()
{
  para = document.createElement("p");
  para.setAttribute("id", "topic-list");
  
  topics_array.each(function(n) {
    ex   = document.createTextNode("x");
    delete_link = document.createElement('a');delete_link.href = "javascript:void(0)"
    //delete_link.setAttribute('onclick', "remove_tips_select_topic('" + String(n) + "')");
	// IE6 won't recognize the onclick handler if set by setAttribute
	eval("delete_link.onclick = function () { remove_tips_select_topic('" + String(n) + "'); }")
    delete_link.appendChild(ex);
    link_name = document.createTextNode(String(n) + " ");
    
    para.appendChild(link_name);
    para.appendChild(delete_link);
  });
  
  old_list = $("topic-list")
  $("topic-list-div").replaceChild(para, old_list);
}

/* ---------------------------------------------------------------- */


function populate_child_location_select(parent_select,child_select)
{
	if(!parent_select || !child_select || (typeof child_select == "string" && child_select == ""))
	   return;
	if(typeof child_select == "string") 
	   child_select = document.getElementById(child_select);
	var parent_geo = get_selected_value(parent_select);
    var err;
	try
	{
		child_select.disabled = false;
	    parent_select.child_id = child_select.id;
        //child_select.disabled = true;
	}
	catch (err) { /* fail silently */ }
	if(parent_geo == "")
	{
		child_select.selectedIndex = 0;
		clear_options(child_select,1);
		child_select.disabled = true;
		try
		{	
		    if(!!child_select.child_id)
                populate_child_location_select(child_select,child_select.child_id);
                }
		catch (err) { /* fail silently */ }
		return;
	}
	// var url = "http://" + location.host + "/tips/select_options/" + parent_geo + "|" + child_select.id;
	var url = "http://" + location.host + "/tip_listings/tips_geos/" + child_select.label;
	var msg = document.getElementById("tip_body"); //alert("populating " + child_select.name);
	//msg.value = "AJAX call initiated.\n" + url;

		    new Ajax.Request(url, {
		        method: 'post',
		        onSuccess: function(transport) {
			try
			{ 
		                //msg.value += "\n\nAJAX call succeeded." + "\nresponseText: " + transport.responseText;
			    // alert(transport.responseText); 
				var a,aa = transport.responseText;
				var aa = aa.split("^");
				var start = 1;
				while (child_select.options.length > start)
				    clear_options(child_select,start); // not instantaneous, so needs the loop
				// create the options if records are returned, disable if not
				if(transport.responseText.replace(/^\s+/,"").replace(/\s+$/,"") != "")
				    for(var i = 0; i < aa.length; i++)
				    {
				        a= aa[i].split("|");
				        add_option(child_select,a[1],a[2]);
				    }
				else child_select.disabled = true;	
		                                }
			catch (err)
			{ 
			    //msg.value += "\n\nERROR: " + err.description + "\nresponseText: " + transport.responseText; //window.alert(msg.value);
			}
		
		        },
		onFailure: function(transport) 
		{
			//msg.value += "\n\nAJAX call failed."; //window.alert(msg.value);
		},
		onComplete: function (transport)
		{
			//msg.value += "\ntransport.status: " + transport.status; //window.alert(msg.value);
		}
		
		    });
}

function get_selected_value(select)
{
	var v = "",err,opts;
	try
	{
		v = select.options[select.selectedIndex].value;
	}
	catch (err)
	{
		alert(err.description);
	}
	finally
	{
		return v;
	}
	   
}

function add_option(select,val,txt)
{
	if(typeof select == "string")
	   select = document.getElementById(select);
	var opt = new Option(txt,val);
	select.options[select.options.length] = opt;
	return opt;
}

function clear_options(select,start)
{
    if(typeof select == "string")
       select = document.getElementById(select);
	for (var i = (!start ? 0 : start); i < select.options.length; i++)
	   select.removeChild(select.options[i]);
}

