// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function export_to_facebook(url) {
	var opened_window = window.open(url, new Date().getTime(), 'width=540,height=360');
	if(opened_window) opened_window.focus();
	zDone();
};
function export_to_twitter(url) {
	var opened_window = window.open(url, new Date().getTime(), '');
	if(opened_window) opened_window.focus();
	zDone();
};

function export_to(site, url, msg, tag, img) {
	var target_uri;
	if(site == "facebook") {
		target_uri = "http://www.facebook.com/sharer.php?u=" + url + "&t=" + encodeURIComponent(msg);
	} else if(site == "twitter") {
		target_uri = "http://twitter.com/home?status=" + encodeURIComponent(msg) + " " + encodeURIComponent(url);
	} else if(site == "me2day") {
		target_uri = "http://me2day.net/posts/new?new_post[body]=" + encodeURIComponent(msg) + " " + encodeURIComponent(url) + "&new_post[tags]=" + encodeURIComponent(tag);
	} else if(site == "yozm") {
		target_uri = "http://yozm.daum.net/api/popup/prePost?link=" + encodeURIComponent(url)+ "&prefix=" + encodeURIComponent(msg) + "&parameter=" + encodeURIComponent(msg);
	}

	if(site=="yozm") {
		var opened_window = window.open(target_uri, new Date().getTime(), 'width=598,height=368,scrollbars=no,resizable=no');
	} else if(site=="facebook") {
		var opened_window = window.open(target_uri, new Date().getTime(), 'width=480,height=320');
	} else {
		var opened_window = window.open(target_uri, new Date().getTime(), '');
	}

	if(opened_window) opened_window.focus();
	zDone();
} 

isMobile = /\/mobile/.test(location.href);

// if(!isMobile && navigator.userAgent.match(/iPad/) == null && navigator.userAgent.match(/Mobile|Windows CE|Windows Phone|Opera Mini|POLARIS/) != null) {

if(/\/mtnlive/.test(location.href)) {
	if(navigator.userAgent.match(/iPad/) != null) {
		location.href = "/?mtnlive=t"
		// alert("ipad");
  } else if(navigator.userAgent.match(/Mobile|Windows CE|Windows Phone|Opera Mini|POLARIS/) != null) {
		// alert("mobile");
	} else {
		location.href = "/?mtnlive=t"
	}
} else {
	if(!isMobile && navigator.userAgent.match(/Mobile|Windows CE|Windows Phone|Opera Mini|POLARIS/) != null) {
		if(!/mt_reply|mt_create|welcome_twitter|as_twitter_user/.test(location.href) && !/mtnlive=t/i.test(location.search)) {
			location.href = "http://" + location.host + "/mobile" + location.pathname + location.search
		}
	}
}

function masking() {
	//
};

function calc_max_quantity_to_buy() {
	var item_id = $('stock_item_id').value;
	if(!item_id) {
		alert("종목을 선택해주세요.")
	} else {
		zLoading();
		$('stock_quantity').disabled = 'disabled';
		zPost("/stocks/max_quantity_to_buy?item_id=" + item_id)
	}
};

function alert_new_memo(){
	if(confirm("새로운 쪽지가 도착했습니다.")){
		open_a_window("/memos/received");
	}
};


function shorten_url(field_name) {
	var _names = __A(field_name);
	for(var i=0;i<_names.length;i++) {

		var container = $(_names[i]);
		if(!container) return;
		container.disabled = "disabled";
		zLoading();

		var pt = /http(s)?:\/\/[^\s'")\]>]+/gi;
		
		var m = null;
		var new_text = text = container.value;
		while(m = pt.exec(text)) {
			res = zFetch("/main/shorten_url?lurl=" + m[0].__encode());
			if(res) {
				if(!/^error/.test(res.responseText)) {
					new_text = new_text.replace(m[0], res.responseText);
				}
			}
		}

		container.value = new_text
		container.disabled = "";

	} // end of for

	zDone();
};

function comment_rt_move( _title, _flag,  _user ){
	if( _flag == "1" )	{
		$("comment_content").value = _title;
	}else{
		$("comment_content").value ="RT @"+_user + " " + _title;
	}
	Effect.ScrollTo('comment_form', {duration: 0.1});
//	Effect.Pulsate('comment_content', { pulses: 5, duration: 0.8 });

}

function topic_rt_move( _title, _user ){
	$("comment_content").value ="RT @"+_user + " " + _title
}

function show_tab( _args ){
	if( _args == "m"){
		$('topics_wrapper').show();
		$('trades_wrapper').hide();
		$('btn_my_mtwts').addClassName("showing");
		$('btn_my_trades').removeClassName("showing");
	}else{
		$('topics_wrapper').hide();
		$('trades_wrapper').show();
		$('btn_my_trades').addClassName("showing");
		$('btn_my_mtwts').removeClassName("showing");
	}

}

function show_pop_rt() {
	$('hrtn').show();$('rrtn').hide();
	$('poprt').src = "/images/right_tab01_on.gif";
	$('recentrt').src = "/images/right_tab02.gif";
};

function show_recent_rt() {
	$('hrtn').hide();$('rrtn').show()
	var src = $('recentrt').src;
	$('poprt').src = "/images/right_tab01.gif";
	$('recentrt').src = "/images/right_tab02_on.gif";
};

function show_leader(el) {
	$$(".leader").each(function(l) {
		removeClass(l, "selected");
	});
	var leader = el.up(".leader");
	addClass(leader, "selected");

	var user_id = leader.getAttribute("rel");

	zGet("/list/leaders?user_id=" + user_id);
};

function showArticle(element) {
	var article_body = element.parentNode.down("div.mt_article_body");
	Effect.toggle(article_body, "appear", { duration:0.5 });
};

function _showArticle(element) {
	var current_showing = $$('li.related_mt_article.showing')[0];
		if(current_showing) {
		var showing_id = /([0-9]+)$/.exec(current_showing.id).last();

		var container = $(element).up("li.related_mt_article");
		container_id = /([0-9]+)$/.exec(container.id).last();

		if(showing_id == container_id) return;

		var showing_body = $(current_showing).down("div.mt_article_body");
		showing_body.hide();
		removeClass(current_showing, "showing");

		addClass(container, "showing");
		var dest_body = $(container).down("div.mt_article_body");
		dest_body.blindDown({duration: 0.5});
	} else {
		var container = $(element).up("li.related_mt_article");
		container_id = /([0-9]+)$/.exec(container.id).last();
		addClass(container, "showing");
		var current_body = container.down("div.mt_article_body");
		current_body.blindDown({duration: 0.5});
	}
};


function login_for_mt_reply(mtzk, no) {
	setCookie("mt_reply_path", "/mt_reply?mtzk="+mtzk+"&no="+no)
	location.href="/login/mtr_twitter";
};


function open_a_window(url, options) {
	if(!options) var options = {};
	var _t = options['title'] || "mtwt_popup_" + new Date().getTime();
	var _w = options['width'] || "480";
	var _h = options['height'] || "640";
	var _p = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width="+_w+",height="+_h+";";

	_win = window.open(url , _t, _p);
};

function casting(msg, error) {
	var st = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
	var wW = (Browser.safari && !document.evaluate) ? document.innerWidth : (Browser.opera) ? document.body.clientWidth : document.documentElement.clientWidth;
	var _board = document.getElementById("explanation");

	if(_board) {
		_board.innerHTML = "";
		_board.innerHTML = "<div class='flashNotice'><span id='notify_message'>" + msg + "</span><span class='closeNotifyBoard' onclick='uncasting();'> x </span></div>";
		_board.style.visibility = "visible";
		_board.style.display = "block";
		_board.style.top = st + "px"
		// _board.style.left = ((wW - parseInt(_board.offsetWidth)) / 2) + "px"
	}
};

function uncasting() {
  var _board = document.getElementById("explanation");
	if(_board) {
    _board.style.display = "none";
    _board.style.visibility = "hidden";
    _board.innerHTML = "";
  }
};

var Counter = new function() {
	this.count = null;
	this.element = null;
	this.monitor = null;
	this.workerID = null;
};
Counter.counting = function() {
	this.count = this.element.value.replace(/[\r\n]/g, '').length;
	this.update_display();
};
Counter.update_display = function() {
	var c = this.max - this.count;
	if(c < 0) addClass(this.monitor, "exceed");
	else removeClass(this.monitor, "exceed");
	this.monitor.innerHTML = c
};
Counter.roll = function(_element, _monitor, _max) {
	if(this.workerID) return;
	this.element = _element;
	this.monitor = document.getElementById(_monitor);
	this.max = parseInt(_max);

	try {
		this.workerID = this.timer().setInterval(Bind(this, function() {
			this.counting();
		}), 600);
	} catch(e) {
		this.stop();
	}
};
Counter.stop = function() {
	this.timer().clearInterval(this.workerID);
	this.workerID = null;
};
Counter.timer = function() {
	return window;
};

function hasClass(node, class_name) {
	return (new RegExp(class_name, "gi").test(node.className));
};

function replaceClass(node, _old, _new) {
	if(node) node.className = node.className.replace(new RegExp(_old, "gi"), _new)
};

function addClass(node, class_name) {
	if(new RegExp(class_name, "gi").test(node.className)) return;
	if(node) node.className += (node.className ? " " : "") + class_name
};

function removeClass(node, class_name) {
	if(node) node.className = node.className.replace(new RegExp("(\s)?" + class_name, "gi"), '')
};

function addOrRemoveClass(condition, node, class_name) {
	if(condition) addClass(node, class_name)
	else removeClass(node, class_name)
};

function mOver(_element_clue) {
	var target = (typeof _element_clue == "string") ?  document.getElementById(_element_clue) : _element_clue;
	if(target) addClass(target, "hover");
};

function mOut(_element_clue) {
	var target = (typeof _element_clue == "string") ?  document.getElementById(_element_clue) : _element_clue;
	if(target) removeClass(target, "hover");
};

function disableForm(__form) {
	addClass(__form, "in_action");
	var __trigger = $(__form).down(".trigger");
	if(__trigger) {
		addClass(__trigger, "in_action");
		var __submit = $(__trigger.rel);
		if(__submit) {
			addClass(__submit, "in_action");
			__submit.disabled = "disabled";
		}
	}
};

function enableForm() {
	var __form = $$("form.in_action").first();
	if(__form) {
		removeClass(__form, "in_action");
		var __trigger = $(__form).down(".trigger");
		if(__trigger) {
			removeClass(__trigger, "in_action");
			var __submit = $(__trigger.rel);
			if(__submit) {
				removeClass(__submit, "in_action");
				__submit.disabled = false;
			}
		}
	}
};

function thisSubmit(node) {
	if(/form/i.test($(node).tagName)) var __form = $(node);
	else var __form = $(node).up("form");

	if(__form) {
		if(!/in_action/i.test(__form.className)) {
			disableForm(__form);
			zLoading();
			if(typeof __form.onsubmit == "function") __form.onsubmit();
			else __form.submit();
		}
	}
};

function resetForm(form_id) {
	if(form_id) {
		document.getElementById(form_id).reset();
	} else {
		var forms = document.getElementsByTagName("form");
		for(var i=0; i<forms.length; i++) forms[i].reset();
	}

	enableForm();
};

function initSmartFocus() {
	var _is = __A(document.getElementsByTagName("input")).concat(__A(document.getElementsByTagName("textarea")))
	var _i = null;
	while(_i = _is.pop()) {
		if(/smart_focus/.test(_i.className)) {
			_i.blur();
			_i.focus();
			break;
		}
	}
};

function initVolatileInputs() {
	var _candidates = __A(document.getElementsByTagName("input")).concat(__A(document.getElementsByTagName("textarea")))
	for(var i=0;i<_candidates.length;i++) {
		var _i = _candidates[i];
		if(!/volatile/.test(_i.className)) continue;
		if(typeof _i.onclick == "function") continue;
		if(/volatile_value/.test(_i.className)) _i.onclick = function() { this.value = this.onclick = ""; }
		else if(/volatile_background/.test(_i.className)) _i.onclick = function() { this.style.backgroundImage = "none"; this.onclick = ""; }
	}
};

function initFragileLayer() {
	OnEvent.clear("__fragileLayer");
	OnEvent.add(window.document, "mousedown", BindEvent(this, function(_e) {
		var node = _e.target || _e.srcElement;

		// if(/html/i.test(node.tagName)) return;

		var __ev_refer = node;
		var __evade_case = false;
		do {
			if(/z(_select|Pin_canvas)/i.test(__ev_refer.className)) {
				__evade_case = true;
				break;
			}
		} while(__ev_refer = __ev_refer.parentNode)

		// close layer
		if((!__evade_case && !$(node).up(".fragile")) || /fragileBreaker/i.test(node.className)) {
			$$(".fragile").each(function(_f) {
				if(!_f.clientHeight || _f.clientHeight == 0) return;
				var _method = String(/do_[_a-z]+/i.exec(_f.className));
				switch(_method) {
					case "do_nullify":
						if(_f.innerHTML) _f.innerHTML = "";
						break;
					case "do_destroy":
						if(_f) _f.parentNode.removeChild(_f);
						break;
					case "do_hide":
						if(_f.style.display != "none") _f.style.display = "none"
						break;
					case "do_both":
						if(_f.innerHTML) _f.innerHTML = "";
						_f.style.display = "none";
						_f.style.visibility = "hidden";
						break;
					case "do_function":
						eval(_f.getAttribute("rel"))();
						break;
					default:
						//
				}

			})
		}

	}), "__fragileLayer");
};

function initLoadingImage() {
	var st = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
	var wW = (Browser.safari && !document.evaluate) ? document.innerWidth : (Browser.opera) ? document.body.clientWidth : document.documentElement.clientWidth;

	var load_bar = document.createElement("img");
	load_bar.className = "fragile do_hide";
	load_bar.id = "load_bar";
	load_bar.style.display = "none";
	load_bar.style.position = "absolute";
	load_bar.style.padding = "10px";
	load_bar.src = "/images/load_bar.gif";
	load_bar.style.backgroundColor = "#333";
	document.getElementsByTagName("body")[0].appendChild(load_bar);
	load_bar.style.top = st + "px"
	load_bar.style.left = ((wW - parseInt(load_bar.offsetWidth)) / 2) - 33 + "px"
};

