// find near history
Event.observe(window, "load", function(){
	$$(".focusless").each(function(e){
		Event.observe(e, "focus", function() {this.blur();});
	});
});


//
// url query serialize
//
var ArraySerialize = function(value, join_string) {

	if(!join_string) {
		join_string = ", ";
	}

	var values = new Array();
	for(var _key in value) {

		values.push(_key + "=" + value[_key]);
	}

	return values.join(join_string);
}

//
// Static HyperText Url generator
//

var RegenStaticLink = function(tagname, attribute, match_string)  {

	var _a = document.getElementsByTagName(tagname);
	var _patt = null;
	var _cur_url = new SynkiUrlParser();
	_cur_url.query.searching_keyword = encodeURI(_cur_url.query.searching_keyword)

	for(var i=0; i<_a.length; i++) {

		_patt = new RegExp(match_string, "g");

		if(!_a[i].id) continue;

		if(_patt.test(_a[i].id)) {

			_dst = _a[i].id.replace(match_string, "");

			_rkey = {};
			if(_dst == "search_type") {
				var _s = _dst.split("_");
				var _sub_action = _s[0];
				var _query_key = _s[1];

				_rkey[_sub_action] = " ";
				_cur_url.query[_query_key] = _a[i].rel

				_rkey['query'] = ArraySerialize(_cur_url.query, "&");
			} else {
				_rkey[_dst] = (_a[i].rel) ? _a[i].rel : " ";
			}

			_link = SynkiUrlBuilder(_rkey);
			switch(_a[i].tagName.toLowerCase()) {
				case "a":
					_a[i].href = _link;
				break
				case "form":
					_a[i].action = _link;
				break
			}

			_patt = null;
		}
	}

//	var _a = document.evaluate("//"+tagname+"[contains(@"+attribute+",'"+match_string+"')]", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); 

//	var i =0;
//	while((a = _a.snapshotItem(i)) != null) {
//
//		_dst = a.id.replace(match_string, "");
//
//		_rkey = {};
//		_rkey[_dst] = (a.rel) ? a.rel : " ";
//		_link = SynkiUrlBuilder(_rkey);
//		a.href = _link;
//
//		i++;
//	}
}

//
// Changeable Image change to dimmed image when offline
//
var ToggleOfflineImage = function(offline_logoff_flag) {
	var v_images = $(".variable_image");
	for(var i=0; i<v_images.length; i++){
		var obj = v_images[i];

		if(offline_logoff_flag == "logoff") {
			var _p = /not_public/;
			if(_p.test(obj.className)) continue;
		}
		switch(obj.tagName.toLowerCase()) {
			case "div" :
			case "li" :
				var before_bg = obj.style.backgroundImage;
				before_bg = before_bg.split("/");
				file_name = before_bg[before_bg.length - 1];
				file_path = obj.style.backgroundImage.replace(file_name, "");
				file_name = file_name.replace(/^tamako_/, '');
				obj.style.backgroundImage = file_path + "tamako_" + file_name
			break;

			case "img" :
				var before_img = obj.src;
				before_img = before_img.split("/");
				file_name = before_img[before_img.length - 1];
				file_path = obj.src.replace(file_name, "");
				file_name = file_name.replace(/^tamako_/, '');
				obj.src = file_path + "tamako_" + file_name
			break;

			case "input" :
				obj.style.borderColor = "#cbcbcb";
				obj.style.backgroundColor = "#ebebeb";
				obj.readOnly = "readOnly";
			break;

			case "a" :
				obj.removeAttribute("href");
				obj.style.textDecoration = "none";
				$(obj).toggleClass("thickbox");
				$(obj).addClass("d_gray");
				obj.onclick = function() { return false; };
			break;
		}

	}
}


//Todo: must Refactorying
var ToggleOnlineImage = function(_id) {
	var v_images = $("#" + _id);
	for(var i=0; i<v_images.length; i++){
		var obj = v_images[i];

		switch(obj.tagName.toLowerCase()) {
			case "div" :
			case "li" :
				var before_bg = obj.style.backgroundImage;
				before_bg = before_bg.split("/");
				file_name = before_bg[before_bg.length - 1];
				file_path = obj.style.backgroundImage.replace(file_name, "");
				file_name = file_name.replace(/^tamako_/, '');
				obj.style.backgroundImage = file_path + file_name
			break;

			case "img" :
				var before_img = obj.src;
				before_img = before_img.split("/");
				file_name = before_img[before_img.length - 1];
				file_path = obj.src.replace(file_name, "");
				file_name = file_name.replace(/^tamako_/, '');
				obj.src = file_path + file_name
			break;

			case "input" :
				obj.style.borderColor = "#cbcbcb";
				obj.style.backgroundColor = "#ebebeb";
				obj.readOnly = "readOnly";
			break;

			case "a" :
				obj.removeAttribute("href");
				obj.style.textDecoration = "none";
				$(obj).toggleClass("thickbox");
				$(obj).addClass("d_gray");
				obj.onclick = function() { return false; };
			break;
		}

	}
}


//
// HTML view templates
//

function div_navigation() {
	var navs = $A(arguments);
	
	var e = $("Navigation");
	var divider = "<span class=\"NavigationBar\"> /</span> ";
	
	var current = navs.pop(); 
	var navs_list = [e.innerHTML];
	
	navs.each(function(t) {
		if (typeof(t) == "string")
			navs_list.push(t);
		else
			navs_list.push("<a href=\"" + t[1] + "\">" + t[0] + "</a>")
	});
	
	if (current) {
		if (typeof(current) == "string")
			navs_list.push(current);
		else
			navs_list.push("<a href=\"" + current[1] + "\"><strong id=\"CurrentPosition\">" + current[0] + "</strong></a>")
	}
	
	var html = navs_list.join(divider);
	e.innerHTML = html;
};



////////////////////////////////////////////////////////////////////////////////////////////////////////
//

var WatchPageToggleButton = function(msg_watch, msg_loading, msg_unwatch) {
	this.msg_watch = msg_watch || "";
	this.msg_loading = msg_loading || "";
	this.msg_unwatch = msg_unwatch || this.msg_watch;
};

WatchPageToggleButton.prototype = {
	bind: function(dom_id, page_obj, initial_value) {
		this.element = $(dom_id);
		this.page = page_obj;


		// button HTML
		this.element.innerHTML = this.render(initial_value);
		
		// bind events
		var c = this.element.childElements();
		var _offline_action = (tom_and_jerry) ? "_at_offline" : "";
		Event.observe(c[0], "click", this["click_unwatch_page" + _offline_action].bindAsEventListener(this));
		Event.observe(c[2], "click", this["click_watch_page" + _offline_action].bindAsEventListener(this));
	},
	render: function(initial_value) {
		var img_watch = ImageTag(WatchIcons.get(true), {"class": "watch_toggle_button variable_image"});
		var img_unwatch = ImageTag(WatchIcons.get(false), {"class": "watch_toggle_button variable_image"});

		var is_watched = (initial_value != null);

		var span_watch = ContentTag("span", img_watch + " " + this.msg_watch, (is_watched) ? {"class": "watched"} : {"class": "watched Hide"});
		var span_unwatch = ContentTag("span", img_unwatch + " " + this.msg_unwatch, (is_watched) ? {"class": "Hide"} : {});
		var span_loading = ContentTag("span", this.msg_loading, {"class": "Hide"});
		
		return span_watch + span_loading + span_unwatch;
	},
	
	//
	// DOM click event handler
	click_watch_page: function() {
		var c = this.element.childElements();
		
		// click element -> ajax call to create
		var ub = new URLBuilder;
		var url = ub.workspace_path(this.page) + "/watched_pages";
		
		new Ajax.Request(url, {
			method: "post",
			parameters: $H({"page_id": this.page.id}).toQueryString(),
			onLoading: this.waiting_msg.bind(this),
			onSuccess: this.watch_page.bind(this),
			onFailure: this.unwatch_page.bind(this)
		})

		// update obj
		if (this.obj) this.obj.watch = false;
	},
	click_unwatch_page: function() {

		// click element -> ajax call to destroy
		var ub = new URLBuilder;
		var url = ub.workspace_path(this.page) + "/watched_pages/" + this.page.id;
		
		new Ajax.Request(url, {
			method: "delete",
			onLoading: this.waiting_msg.bind(this),
			onSuccess: this.unwatch_page.bind(this),
			onFailure: this.watch_page.bind(this)
		})
		
		// update obj
		if (this.obj) this.obj.watch = true;
	},

	// offline watch, unwatch handler
	click_watch_page_at_offline: function() {
		this.waiting_msg();

		try {
			var user = Tamako.tables.users.find_one();
			var df = new SynkiDateFormatter(0, "ko");
			var _current_date = df.formattingDate(new Date().toUTCString());
			var watched = Tamako.tables.watched_pages.find_one("page_id=" + this.page.id, {"condition": "user_id=" + user.id});
			var command = (watched) ? "update" : "save";
			var _max = Tamako.tables.execute("select max(id) as max_wid from watched_pages");

			var _watched_pages = new Object;
			if(command == "save") _watched_pages["id"] = Number(_max[0].max_wid) + 1;
			_watched_pages["user_id"] = user.id;
			_watched_pages["user_login"] = user.login;
			_watched_pages["page_id"] = this.page.id;
			_watched_pages["page_title"] = this.page.title;
			_watched_pages["workspace_id"] = this.page.workspace_id;
			_watched_pages["created_at"] = _watched_pages["updated_at"] = _current_date;
			_watched_pages["local_created"] = "true";

			Tamako.tables.watched_pages[command](_watched_pages);
		} catch(e) {
			this.unwatch_page();
			return;
		} 

			this.watch_page();
			// update obj
			if (this.obj) this.obj.watch = false;
		},

		click_unwatch_page_at_offline: function() {
		this.waiting_msg();

		try {
			var user = Tamako.tables.users.find_one();
			var watched = Tamako.tables.watched_pages.find_one("page_id=" + this.page.id, {"condition": "user_id=" + user.id});
			if(watched.local_created == "true") {
				Tamako.tables.watched_pages.remove("page_id=" + this.page.id);
			} else {
				watched.local_deleted = "true";
				Tamako.tables.watched_pages.update(watched);
			}
		} catch(e) {
			this.watch_page();
			return;
		}

		this.unwatch_page();

		// update obj
		if (this.obj) this.obj.watch = true;
	},
	
	//
	// update DOM element
	watch_page: function(transport) {
		var c = this.element.childElements();
		c[0].removeClassName("Hide");
		c[1].addClassName("Hide");
		c[2].addClassName("Hide");
	},
	unwatch_page: function(transport) {
		var c = this.element.childElements();
		c[0].addClassName("Hide");
		c[1].addClassName("Hide");
		c[2].removeClassName("Hide");
	},
	waiting_msg: function(transport) {
		var c = this.element.childElements();
		c[0].addClassName("Hide");
		c[1].removeClassName("Hide");
		c[2].addClassName("Hide");
		
	}
}

String.prototype.__encode_entities = function() {
	return this.replace(/[<>&"]/g, function(_m) {
		return { '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;'}[_m] || _m;
	});
}

String.prototype.__decode_entities = function() {
	return this.replace(/&([a-z]{2,4});/gi, function(_m, _w) {
		return {'amp': '&', 'quot': '"', 'lt': '<', 'gt': '>'}[_w] || _m;
	})
}

String.prototype.__encode = function() {
	return encodeURIComponent(this);
}

String.prototype.__decode = function() {
	return decodeURIComponent(this);
}
