
function setSugRecEvents() {

	var target = $(this).attr("id").substr(7);
	$("#button_suggested_tags, #button_recent_tags").removeClass("active");
	$(this).addClass("active");
	$(".t_bot_w").hide();
	$("#"+target+"_wrapper").show();
}


function sugRecTags(what, url, isEng) {

	if (typeof(what) == 'object')
		what = 'recent';

	if (what == 'recent') {
		var id_this = $(this).attr("id");

		if (id_this !== undefined) {
			if (id_this.substr(12) == "right")
				recent_tags_step++;
			else
				recent_tags_step--;
		}

		var post_data = "s="+recent_tags_step+"&id_w="+$("#id_webpage").val();
	}
	else if (what == 'suggested') {
		var eng_title = isEng ? 1 : 0;
		var post_data = "u="+url+"&id_w="+$("#id_webpage").val()+"&lang="+lang+"&eng_title="+eng_title;
	}

	$.ajax({
		type: "POST",
		url: "/ajax/get_"+what+"_tags.php",
		data: post_data,
		success: function(msg) {

			if (msg != "") {

				if (what == "suggested") {
					$("#"+what+"_tags").html($("#"+what+"_tags").html()+msg);
					$("#"+what+"_tags .sug_ind").remove();
				}
				else
					$("#"+what+"_tags").html(msg);

				hideTagsRefresh((what == "suggested" ? $("#"+what+"_tags #sug_zem .tag_name") : $("#"+what+"_tags .tag_name")), $("#current_tags .tag_name, #sug_others .tag_name"));

				if (what == "recent") {
					$("#rt_link").html("");
					$("#rt_wp_temp").appendTo("#rt_link");
				}

				$("#"+what+"_tags .lo").remove();

				JT_init(".tag_name");
				$(".vote_up, .vote_down").bind("click", setSaveVoteEvent);
			}
			else
				$("#"+what+"_tags .sug_ind").remove();

			if (what = "recent") {
				if (recent_tags_step == 0) {
					$("#recent_tags_left").css("display", "none");
					$("#recent_tags_left_dis").css("display", "inline");
				}
				else {
					$("#recent_tags_left").css("display", "inline");
					$("#recent_tags_left_dis").css("display", "none");
				}
			}
		}
	});

	return false;
}


function hideTagsRefresh(hide_tags, leave_tags) {
	for (var i=0; i<leave_tags.length; i++) {
		for (var j=0; j<hide_tags.length; j++) {
			if ($(leave_tags[i]).attr("alt") == $(hide_tags[j]).attr("alt")) {
				$(hide_tags[j]).parent().hide();
				break;
			}
		}
	}
}


function saveVote(method, what, tag_name, tag_name_eng, tag_id, tag_url, url_title, url_desc) {

	$(".ac_results").hide();

	if (tag_name == '------------------------------------------')
		return false;

	//search
	if (what != 'tags') {

		if (what == "convert_tag") {
			$("#"+what).val(tag_name);
		}
		else {
			var jsonString = $("#"+what+"_temp").val();

			if (what == "object")
				jsonString += "{name: '"+addSlashes(tag_name)+"', nameEng: '"+addSlashes(tag_name_eng)+"'}, ";
			else //subject
				jsonString += "{name: '"+addSlashes(tag_name)+"'}, ";

			$("#"+what+"_temp").val(jsonString);

			var temp_ar = $("#"+what).val().split(";");

			for (var i =0; i < temp_ar.length; i++)
				temp_ar[i] = $.trim(temp_ar[i]);
			
			temp_ar[temp_ar.length-1] = tag_name;
			$("#"+what).val(temp_ar.join("; ")+"; ");

			setTimeout(function() {
				enableEnter = true;
			}, 750);
		}

		$("#"+what).focus();
	}
	//tags
	else {

		if (tag_name_eng == undefined)
			var tag_name_eng = tag_name;

		var tag_name_url = encodeURI(tag_name_eng.replace(/ /g,"_"));

		$("#"+what).val("");

		// ako je prazno (postoji span sa klasom "empty" brisemo ga)
		if ($("#webpage_tags .empty").size())
			$("#webpage_tags .empty").hide();

		var href_part ="id_w="+$("#id_webpage").val()+"&tag_name="+tag_name_url;

		var html_output = " <span class=\"tag uv1 tag_added\" ";

		if (tag_id != undefined && tag_id != false) {
			href_part += '&id_t='+tag_id;
			html_output += " id=\"t"+tag_id+"\"";
		}

		html_output += "><span id=\""+href_part+"&v=-1\" class=\"vote_down tag_name\" alt=\""+tag_name_eng+"\">"+unicode2string(tag_name)+"</span></span> ";

		$("#current_tags_content").html($("#current_tags_content").html()+html_output);
		document.getElementById("webpage_tags").scrollTop = document.getElementById("webpage_tags").offsetHeight;

		$(".vote_up, .vote_down").bind("click", setSaveVoteEvent);
		JT_init(".tag_name");

		var post_data = href_part+"&v=+1";

		if (tag_url != undefined && tag_url != false)
			post_data += '&tag_url='+tag_url;

		if (url_title != undefined)
			post_data += '&url_title='+escape(url_title);

		if (url_desc != undefined)
			post_data += '&url_desc='+escape(url_desc);

		if (top_urls != "") {
			post_data += '&top_urls='+escape(top_urls);
			top_urls = "";
		}

		if (method == "custom") {
			post_data += "&exact=false";
		}

		if (method == "sameas") {
			post_data += "&get_name=true";
		}

		$("#submit_save").attr("disabled", "disabled");

		$.ajax({
			type: "POST",
			url: "/ajax/save_vote.php",
			data: post_data,
			success: function(msg) {

				$("#submit_save").removeAttr("disabled");

				var error = '';
				if (msg == '' || msg == 'error')
					error = 'Sorry, can not add this as a tag.';
				else if (msg == "glasao_ranije")
					error = 'Hey, you\'ve already added this tag!';

				if (error != '') {
					$("#current_tags .tag:last").css("color", "#f00");
					alert(error);
					$("#current_tags .tag:last").remove();
					$("#tags").focus();
					return false;
				}

				if (msg.substr(0, 14) == "disambiguation") {
					tag_from = tag_name;
					$("#"+what).val(tag_name);
					$("#current_tags .tag:last").remove();
					googleSearch(tag_name, "wikipedia");
					return false;
				}
				else if (msg.substr(0, 8) == "redirect") {
					tag_name = msg.substr(9);
				}
				else if (msg.substr(0, 6) == "sameas") {

					tag_from = tag_name;

					if ($("#save").size()) {

						$("body").prepend(unescape(msg.substr(7)));

						$(".sameas_butt").bind("click", function() {

							$("#current_tags .tag:last").remove();
							var p_a = $(this).attr("rel").split('|||');

							if ($(this).attr("id") == "sameas_true") {
								var tag_id = p_a[0];
								saveTagURL(tag_id, p_a[1]);
								saveVote('sameas', 'tags', tag_name, tag_name_eng, tag_id);
							}
							else {
								saveVote('sameas', 'tags', tag_name, tag_name_eng, false, p_a[0], p_a[1], p_a[2]);
							}

							$("#popup").remove();
							$(".dark_z1").remove();
						});

						$("#popup .close").bind("click", function() {
							$("#popup").remove();
							$(".dark_z1").remove();
							$("#current_tags .tag:last").remove();
						});

						if ($("#sameas_wdesc").size()) {

							$.ajax({
								type: "GET",
								url: "/ajax/get_tag_desc.php?tag="+$("#sameas_title").text(),
								success: function(msg) {
									$("#sameas_wdesc").html(msg);
									$("#sameas_wdesc").addClass("nobg");
								}
							});
						}
					}
				}
				else {
					tag_name = msg;

					if (method == "sameas") {
						saveRedirect(tag_from, tag_name);
					}

					tag_name_url = encodeURI(tag_name.replace(/ /g,"_"));
					var last = $("#current_tags .tag:last span");
					last.attr("id", "id_w="+$("#id_webpage").val()+"&tag_name="+tag_name_url+"&v=-1").attr("alt", tag_name);

					hideTagsRefresh($("#suggested_tags .tag_name"), $("#current_tags .tag_name"));
					hideTagsRefresh($("#recent_tags .tag_name"), $("#current_tags .tag_name"));
				}

				$(".vote_up, .vote_down").bind("click", setSaveVoteEvent);
				$(".ac_results").hide();
				$('#JT').remove();
			}
		});
	}
}



function setSaveVoteEvent() {

	var button = $(this);
	var tag = button.parent();
	var is_suggest = (tag.attr("class") == "tag uv0 sug" || tag.attr("class") == "tag uv0 rec") ? true : false;

	if (button.attr("class").search("vote_up") != -1)
		$(tag).css("visibility", "hidden");
	else {
		$(tag).hide();
		if ($("#current_tags .tag:visible").size() == 0)
			$("#no_tags").fadeIn();
		$("#tags").focus();
	}

	var post_data = button.attr("id");
	
	var tag_name = $(".tag_name", tag).text();
	var tag_name_eng = $(".tag_name", tag).attr("alt");

	if (tag_name.search(/\(/) != -1 && tag_name == tag_name_eng) {
		var ar = /[^\(]*/.exec(tag_name);
		tag_name = $.trim(ar[0]);
		saveRedirect(tag_name, tag_name_eng);
	}


	if (button.attr("class").search("vote_up") != -1) {
		if (is_suggest)
			saveVote('sugrec', 'tags', tag_name, tag_name_eng);
		else
			$(tag).removeClass().addClass(msg == "ponisteno" ? "tag uv0" : "tag uv1");
	}
	else {
		var sug_tags = $("#suggested_tags .tag_name, #recent_tags .tag_name");
		for (var i=0; i<sug_tags.length; i++) {

			if ($(sug_tags[i]).attr("alt") == unescape(tag_name_eng)) {
				var parent_style = sug_tags[i].parentNode.style;
				if (parent_style.display == 'none')
					parent_style.display = 'inline';
				if (parent_style.visibility == 'hidden')
					parent_style.visibility = 'visible';
				break;
			}
		}

		$.ajax({
			type: "POST",
			url: "/ajax/save_vote.php",
			data: post_data,
			success: function(msg) {
			}
		});

		//return false;
	}

}


function unicode2string(str) {
	var reg = /&#([0-9]*);/;
	var ar = new Array();

	while (reg.test(str)) {
		ar = reg.exec(str);
		if (ar)
			str = str.replace(ar[0], String.fromCharCode(ar[1]));
	}

	return str;
}



function saveTagURL(id_tag, id_url, index) {

	$.ajax({
		type: "POST",
		url: "/ajax/save_tag_url.php",
		data: "id_tag="+id_tag+"&id_url="+id_url,
		success: function(msg) {

			if (index != undefined) {
				if (msg == "s") {
					var nu = parseInt($(".vote_tag_no:eq("+index+")").text());
					$(".vote_tag_no:eq("+index+")").text((nu+1)+" people");
					$(".vote_tag_url:eq("+index+")").text("thanks!");
				}
				else {
					$(".vote_tag_url:eq("+index+")").text("already voted!");
				}
			}
		}
	});
	return false;
}



function isTitleinEnglish(str) {
	str = encodeURIComponent(str);
	str = str.replace(/%E2%86%92|%E2%80%9C|%E2%80%9D|%E2%80%99|%E2%80%B0|%E2%82%AC|%E2%82%A4|%E2%84%96|%E2%84%A2|%E2%84%A6|%E2%80%93|%C2%A2|%C2%A3|%C2%A4|%C2%A5|%C2%BE|%C2%A9|%C2%AB|%C2%AE|%C2%BB|%C2%BA|%20|%21|%22|%23|%24|%25|%26|%27|%28|%29|%2A|%2C|%3A|%3B|%3C|%3E|%3F|%5B|%5D|%5E|%60|%7B|%7C|%7D|%40|%3D|%2B|%2F/gi, '');
	var isEng = str.search('%') == -1 ? true : false;
	return isEng;
}


function escapeRegex(text) {
	var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
	var nji = new RegExp('(\\' + specials.join('|\\') + ')', 'g');

	return text.replace(nji, '\\$1');
}


function string2unicode(str) {
	var str2 = "";
	for (var i=0; i<str.length; i++)
		str2 += (str.charCodeAt(i) > 122) ? "&#"+str.charCodeAt(i)+";" : str.charAt(i);

	return str2;
}


function addSlashes(str) {
	str=str.replace(/\'/g,'\\\'');
	//str=str.replace(/\"/g,'\\"');
	//str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}


function stripSashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}


function similar(a,b) {
	c = Math.max(a.length,b.length);
	d = 0;
	for(e=0; e<c; e++) {
		d += (a.charAt(e) == b.charAt(e)) ? 1 : 0;
	}
	return Math.round((d/c)*100);
}

function initAjaxInfo() {

	var showLoader = true;

	$("#success_info_position").ajaxStart(function() {
		if (showLoader)
			$(this).html("Just a second...").fadeIn("slow");
	});

	$("#success_info_position").ajaxStop(function() {
		if (showLoader) {
			$(this).text("Done.");
			setTimeout(function() {
				$("#success_info_position").fadeOut("slow");
			}, 1000);
		}
	});

}


function saveRedirect(tag_from, tag_to) {

	var post_data = "tag_from="+tag_from+"&tag_to="+tag_to+"&priority=1";

	$.ajax({
		type: "POST",
		url: "/ajax/save_redirect.php",
		data: post_data,
		success: function(msg) {
			//alert(msg);
		}
	});
}


function editType(tag_child, tag_parent_from, tag_parent_to) {
	var post_data = "tag_child="+tag_child+"&tag_parent_from="+tag_parent_from+"&tag_parent_to="+tag_parent_to;

	$.ajax({
		type: "POST",
		url: "/ajax/save_edit_type.php",
		data: post_data,
		success: function(msg) {
		}
	});
}


function addNewTypeButton() {

	var button = '<a href="#" id="make_new_type">Make new</a>';
	$("fieldset:first").before(button);
	$("#make_new_type").bind("click", function() {
		var new_group = '<fieldset id="newType" class="tag_group drop" style="position: relative;"><legend>New</legend><span id="object_bg"><input type="text" class="new_type" name="object" value="add new tag" /><a class="google_button" id="google_object" href="#" title="Google search from en.wikipedia.org">&nbsp;</a></span><input type="button" class="butt" id="submit_new_type" value="Add" /></fieldset>';
		
		if (!$("#newType").size())
			$(this).after(new_group);

		$(".new_type").autocomplete("../../ajax/get_tags.php", {
			extraParams : { all:'dojka', lang:lang },
			minChars: 1,
			max: 13,
			matchCase: true,
			mustMatch: true,
			matchContains: true,
			selectFirst: true,
			matchSubset: false
		});

	});
}


function googleSearch(tag_name, from) {

	if (from == undefined)
		from = "wikipedia";

	$("#tags").unbind();
	var disam = false;

	if (typeof tag_name != "string") {

		from = "wikipedia";

		if (google_object === true) {
			var field = $("#object");
			var field_arr = field.val().split(";");
			var tag_name = $.trim(field_arr[field_arr.length-1]);
		}
		else {
			var field = $("#tags");
			var tag_name = field.val();
		}
	}
	else {
		disam = true;
		var field = $("#tags");
	}

	if (tag_name != "" && tag_name != "add new tag") {

		field.attr("disabled", "disabled");
	
		//if ($("#searchcontrol").css("display") != "block")
			tag_from = tag_name;

		searchControl.execute(((tag_name.search(" ") != -1) ? "\""+tag_name+"\"" : tag_name)+(from == "wikipedia" ? " wikipedia site:en.wikipedia.org" : ""));

		enableEnter = false;
		var element = $("#searchcontrol");
		$("#searchcontrol h4, #searchcontrol .close").remove();

		$("#searchcontrol").append("<button class=\"close butt\">X</button>").prepend("<h4>results from "+(from=="web" ? "the ": "")+from+":</h4>").show();
		$("button.close, #button_edit").bind("click", googleClose);

		if (!google_object) {
			$("#whole_web").remove();
			element.append(" <a href=\"#\" id=\"whole_web\">Search "+(from == "wikipedia" ? "the whole web" : "Wikipedia")+"?</a>");
			$("#whole_web").bind("click", function() {googleSearch($("#tags").val(), (from == "wikipedia" ? "web" : "wikipedia")); getTopURLs(false);  return false;});

			$("#add_tag_label").addClass("emp").html((disam ? "What exactly do you mean by <strong>"+tag_name+"</strong> ?" : "Click on the tag to add it!"));
		}
	}
	else {
		alert("Type in a tag first!");
	}

	//field.focus();
	search_from = from;
	return false;
}


function setGoogleEvents() {

	$(".gsc-control").addClass("clearfix");

	var webpage_url = $("#webpage").val();
	var titles = $("#searchcontrol a.gs-title");
	var gooKey = true;

	$("#searchcontrol div.gs-title").bind("mouseover", function() {$("#searchcontrol div.gs-title").removeClass("hover");});

	titles.bind("click", function() {return false;}).each(function() {


		var th = this;
		var rem = false;
		var m = this.href.match(/^http[s]?:\/\/([^\/]*)/);
		var dom = (m[1] != null) ? m[1] : "";
		var is_dom = (this.href == 'http://'+dom+'/') ? true : false;

		if (this.href.search("wikipedia.org/") != -1) {
			var temp = $(this).text().split("- Wik");
			$(this).html(temp[0]);
			if (this.href == 'http://en.wikipedia.org/' || this.href.search(/.php|.html|(disambiguation)|Special:|Template:|Template_talk:|Talk:|Portal:|Wikipedia:|User:|Help:|User_talk:|Wikipedia_talk:|Category:|Category_talk:/) != -1) {
				rem = true;
			}
			if ($(this).html().search(/File:|Special:|Template:|Template talk:|Talk:|Portal:|Wikipedia:|User:|Help:|User talk:|Wikipedia talk:|Wikipedia:Talk|Category:|Category talk:/) != -1) {
				rem = true;
			}
		}
		else {

			if (is_dom) {
				titles.each(function() {
					if (this.href.search(dom) != -1 && this != th) {
						$(this).parent().parent().parent().remove();
					}
				});
			}
		}

		if (search_from == "web")
			$(this).html($(this).text()+" <em>"+dom+"</em>");

		if (rem)
			$(this).parent().parent().parent().remove();
		else
			$(this).addClass("vis");

	});


	JT_init("#searchcontrol_"+(google_object ? "object" : "tags")+"_container a.gs-title");

	titles.bind("click", googleEvent);

	$(".gsc-more-results-active").hide();
	if (search_from == "web")
		$(".gsc-cursor-box").hide();
	else {
		$(".gsc-cursor-box").show();
		$(".gsc-trailing-more-results").hide();

		if ($(".gsc-cursor div").length == 1) {
			$(".gsc-cursor").hide();
		}
	}

	$(".ac_results").hide();

	if (gooKey) {
		setTimeout(function() {
			googleKey();
		}, 100);
	}

}


function googleEvent(wtf) {

	var ths = (wtf.type != undefined) ? $(this) : wtf;

	var url_title, url_desc, tag_name, tag_url = "";
	var is_wiki = (ths.attr("href").search("en.wikipedia.org") == -1) ? false : true;

	if (!is_wiki) {

		//da li je vec user definisao tag sa ovim urlom?
		tag_url = ths.attr("href");
		url_title = tag_name_from_title = ths.text();
		url_desc = ths.parent().parent().children(".gs-snippet").text();
		tag_name = tag_from;

			//var make_name = false;

			$(".gsc-results b").each(function() {
				var b_text = $(this).text().replace("'s", "");
				if (b_text != "...") {
					if (b_text.toUpperCase() == tag_from.toUpperCase()) {
						tag_name = b_text;
						//make_name = true;
					}
				}
			});

		getTopURLs(true);

	}
	else {
		tag_name = rightWikiName($(ths).text(), ths.attr("href"), lang, false);
	}

	var what = (google_object == true) ? 'object' : 'tags';

	saveVote('google', what, tag_from, tag_name, false, tag_url, url_title, url_desc);
	googleClose();

	$("#add_tag_label.emp").removeClass("emp").html(add_tag_def_label);

	if (is_wiki && tag_from != '') {
		saveRedirect(tag_from, tag_name);
		tag_from = '';
	}

	$(".vote_up, .vote_down").bind("click", setSaveVoteEvent);
	

	return false;

}


function getTopURLs(na_pocetak) {
	$("a.vis").each(function() {
		var vis_url = $(this).attr("href");
		if (vis_url.search("en.wikipedia.org/wiki/") != -1) {
			vis_url = rightWikiName($(this).text(), vis_url, 'en', true);
		}
		
		top_urls = (na_pocetak) ?  vis_url+"|||"+top_urls : top_urls+vis_url+"|||";
	});
}


function rightWikiName(title, url, lang, ret_url) {

	name_url = url.replace("http://"+lang+".wikipedia.org/wiki/", "");
	name_url = decodeURI(name_url.replace(/_/g, " "));

	var temp = title.replace(' en.wikipedia.org', '').split(" - Wik");

	name_title = temp[0];

	if (name_url != name_title && name_title.search("...") != -1)
		name_url = name_title;

	return (ret_url) ? "http://en.wikipedia.org/wiki/"+encodeURI(name_url.replace(/ /g, "_")) : name_url;
}


function getGoogleOrder() {

	var i = 0;
	var j = -1;

	$("div.gs-title").each(function() {
		if (this.className.search("hover") != -1) {
			j = i;
		}
		i++;
	});

	return j;
}


function googleKey() {

	var what = "#searchcontrol_"+(google_object ? "object" : "tags")+"_container a.gs-title";

	$("div.gs-title:first").addClass("hover");
	$("a.vis:first").focus();
	JT_show($("a.vis:first")[0], what);

	//$("a.gs-title").unbind();
	$("a.vis").keydown(function (e) {

		var sel = getGoogleOrder();
		var len = $("div.gs-title").length;

		e.preventDefault();
		$("div.gs-title").removeClass("hover");

		switch(e.keyCode) {

			case 38:
				sel = (sel == -1 || sel == 0) ? len-1 : sel-1;
				break;

			case 40:
				sel = (sel == -1 || sel == len-1) ? 0 : sel+1;
				break;

			case 13:
				googleEvent($("a.vis:eq("+sel+")"));
				break;

			case 27:
				googleClose();
				break;

		}

		$("div.gs-title:eq("+sel+")").addClass("hover");
		JT_show($("a.vis:eq("+sel+")")[0], what);
	});

}


function googleClose() {

	top_urls = "";
	
	if (google_object === true) {
		$("#object").removeAttr("disabled").focus();
	}
	else {
		$("#tags").removeAttr("disabled");
		if ($(".tab_2").css("display") == "none")
			$("#tags").focus();
	}
	
	$("button.close").remove();
	$("#searchcontrol").hide();
	enableEnter = true;
	$("#add_tag_label.emp").removeClass("emp").html(add_tag_def_label);
	setTagsEvents();

	$(".vote_up, .vote_down").bind("click", setSaveVoteEvent);
	return false;
}


function fixSafari() {
	var is_chrome = /chrome/.test(navigator.userAgent.toLowerCase());
	if ($.browser.safari && !is_chrome) {

		$("#object_bg").css("paddingRight", "32px");
		$("#object_bg input").css("width", "465px");
		$("#search_submit").css("padding-top", "4px");
		$("#search_submit").css("padding-bottom", "4px");

		$("a#google_tags").css("top", "36px");
		$("a#google_object").css("top", "13px");

	}
}


function setTutEvents() {
	$("#add_tags_tut_o").bind("click", function() {
		$("#add_tags_w").show();
		return false;
	});

	$("#add_tags_tut_c").bind("click", function() {
		$("#add_tags_w").hide();
		return false;
	});
}