var autocomplete;
var current_id = 0;
var cur_text;

// Document Ready
$(function() 
{
	// Init the auto complete
	autocomplete = new ac('category_search', "/json/category_autocomplete/", ac_callback);

	// Init text box stuff
		var o_ask = $('#ask_form textarea[@name=question_text]');
		textCounter(o_ask[0], 255, 'charcount');
		o_ask.focus();
		o_ask.keyup(function(e) 
		{
			textCounter(o_ask[0], 255, 'charcount');

			window.setTimeout(function()
				{
					get_similiar(o_ask);
				}, 
			1000);

		});
		get_similiar(o_ask);

	var categoryid = document.getElementById("categoryid");
	if(categoryid.value) {
		ac_callback("", categoryid.value);
	} else {
		ac_callback("", 1);
	}
	set_events();
});


function validate(o_form)
{
	var valid = true;

	$('#error_question').empty();
	$('#error_question').css({padding: "0"});
	$('#error_category').empty();
	
	if(o_form.question_text.value.length < 10)
	{
		$('#error_question').html('A question must be longer than 10 characters.');
		$('#error_question').css({padding: "5px 0"});
		valid = false;		
	}
	// if(!/^[a-zA-Z0-9_\-\+\?\(\)\[\]\.@"\'\s]+$/i.test(user_val)) {
	if(o_form.url.value && (!/http:\/\/[^\s<>]+$/i.test(o_form.url.value)) )
	{
		$('#error_url').html('You must submit a valid URL beginning with http://');
		$('#error_url').css({padding: "5px 0"});
		valid = false;		
	}


	if(!o_form.categoryid.value || o_form.categoryid.value == 1)
	{
		$('#error_category').html('Please provide a category to continue.');
		valid = false;
	}

	if(!valid)
		return false;
	return true;
}

// Gets similar questions
function get_similiar(o)
{
	var text = o.attr('value');
	// Check for empty string or same string
	if(!text || cur_text == text)
		return;
	cur_text = text;

	var params = {text: text};
	$.get("/json/ask_similiar_questions", params, function(html)
		{
			$('#similar_questions_list').html(html);
		}
	);

}


var current_col = 2;

function ac_callback(value, id) 
{
	var categoryid = document.getElementById("categoryid");
	categoryid.value = id;

	// Make a RPC to get the category's ancestors
	var url = '/json/category_tree';
	var params = { cid: id, full: true };
	$.getJSON(url, params, print_tree);
}

// Places » 
// North America » 
// United States » 
// States » 
// Makes A - Z » 
// Makes A - H » 
// Cadillac » 
// DeVille
function print_tree(json) 
{
	var i;
	var num_children = json.length;

	// Remove unused fields.
	for(i=1; i<15; i++) {
		var unneeded_ul = document.getElementById("cat_col_" + i);
		if(unneeded_ul) {
			var p = unneeded_ul.parentNode;
			p.removeChild(unneeded_ul);
			unneeded_ul = null;
		}
	}
	
	// Resets the counter, leave this here.
	current_col = 1;

	for(i=1; i<num_children; i++) 
	{
		add_cat_col(json[i]["children"], json[i]["categoryid"]);
	}
}

function click_callback(id) 
{
	// Make a RPC to get the category's ancestors
	// $.getJSON(url, params, add_cat_col);
	current_id = id;

	$.ajax({
		type: "GET",
		url: "/json/category_tree",
		data: { cid: id },
		dataType: "json",
		success: add_cat_col,
		error:  function(xmlhttprequest) 
				{
					// printd(xmlhttprequest);
					if(xmlhttprequest.responseText == "null") {
					// $("#cat_list").append('<div class="cat_col">You are DONE!</div>');
				}
			}
		});
}

// Adds in the HTML for each select and options.
function add_cat_col(category_list, hilight_id) 
{
	var children_str = "";
	var num_children = category_list.length;
	for(var i=0; i<num_children; i++) {
		children_str += '<option ';

		if(category_list[i].num_children > 0) {
			children_str += ' class="more" ';
		}

		// This hilight each field if its the current one.
		if(category_list[i].categoryid == hilight_id) {
			var category_search = document.getElementById("category_search");
			category_search.value = category_list[i].category.replace("&amp;", "and");
			
			children_str += ' selected="selected" ';
		}

		children_str += ' value="' + category_list[i].categoryid + '_' + category_list[i].title + '"';
		children_str += '>' + category_list[i].category;

		if(category_list[i].num_children > 0 && $.browser.msie) {
			children_str += ' &rarr;';
		}

		children_str += '</option>';
	}

	$("#cat_list").append('<select id="cat_col_' + current_col + '" class="cat_col" size="15">' + children_str + '</select>');
	
	set_events();
	$('#cat_col_' + current_col).focus();
	
	var category_search = document.getElementById("category_search");
 	category_search.ac.hide_list[category_search.ac.hide_list.length] = document.getElementById('cat_col_' + current_col);
	current_col++;
}

function set_events() 
{
	var ul_list = document.getElementById("cat_list").getElementsByTagName("select");
	var num_ul = ul_list.length;

	for(var i=0; i<num_ul; i++) {

		// When the user clicks on one of the elements
		// in the multi-select box.
		ul_list[i].onclick = function() {
			
			var current_values = this.value.split("_");

			if(current_id == current_values[0]) {
				return;
			}
			
			var col_id = this.id.split("_")[2];
			col_id++;

			// Remove unused fields.
			for(var i=col_id; i<15; i++) {
				var unneeded_ul = document.getElementById("cat_col_"+i);
				if(unneeded_ul) {
					var p = unneeded_ul.parentNode;
					p.removeChild(unneeded_ul);
					unneeded_ul = null;
				}
			}

			current_col = col_id;


			// This will set the current section in the input field above.
			// 
			// Should I replace & symbols with "and"
			// food & dining -> food and dining
			// utensils & tools -> utensils & tools
			// var category_search = document.getElementById("category_search");
			// category_search.value = this.options[this.options.selectedIndex].text;
			var category_search = document.getElementById("category_search");
			var categoryid = document.getElementById("categoryid");
			categoryid.value = current_values[0];
			category_search.value = current_values[1];

			if(current_values[0] > 0) {
				click_callback(current_values[0]);
			}
		}
	}	
	
	// Hilights the category that the mouse is over.
	// This will only work in FireFox and NOT IE 6
	$("#cat_list .cat_col option").hover(
		function(){
			$(this).css("backgroundColor", "#DDDDDD");
		},
		function(){
			$(this).css("backgroundColor", "#FFFFFF");
		}
	);

	$("#question_text").change(function(){
		textCounter(document.frmQuestion.questiontext, 255, 'charcount');
	});
}

function displayDuplicateInput(el)
{   
     document.getElementById("duplicate_id_container").style.display = (el.value == 3) ? "block" : "none";
}