var Cookies = {
	get:function(name, alt) {
		var dc = document.cookie;
		var prefix = name + "=";
		var begin = dc.indexOf("; " + prefix);
		if (begin == -1) {
			begin = dc.indexOf(prefix);
			if (begin != 0) return alt;
		} else {
			begin += 2;
		}
		var end = dc.indexOf(";", begin);
		if (end == -1) end = dc.length;
		if (unescape(dc.substring(begin + prefix.length, end))){
			return unescape(dc.substring(begin + prefix.length, end));
		} else {
			return alt;
		}
	},
	set:function(name, value, expires, path, domain, secure) {
		document.cookie=name+"="+escape(value)+((expires)?"; expires="+expires.toGMTString():"")+((path)?"; path="+path:"")+((domain)?"; domain="+domain:"")+((secure)?"; secure":"");
	}
}

var EventHandler = {
	addEvent:function(el, event, callback) {
		
		if (!el) {
			return;
		}
		if (el.addEventListener)
			el.addEventListener(event, callback, false);
		else
			el.attachEvent('on'+event, callback);
	},
	removeEvent:function(el, event, callback) {
		if (!el) return;
		if (el.removeEventListener)
			el.removeEventListener(event, callback, false);
		else
			el.detachEvent('on'+event, callback);
	}
}
var Browser = {
	isIE: navigator.appName == "Microsoft Internet Explorer",
	isIE6: navigator.userAgent.toLowerCase().indexOf('msie 6') != -1,
	isMac: navigator.userAgent.toLowerCase().indexOf('mac') != -1,
	isUbuntu: navigator.userAgent.toLowerCase().indexOf('ubuntu') != -1,
	isSafari: navigator.userAgent.toLowerCase().indexOf('safari') != -1,
	isChrome: navigator.userAgent.toLowerCase().indexOf('chrome') != -1,
	
	width: function() {
		return window.innerWidth || document.body.parentNode.clientWidth
	},

	height: function() {
		return window.innerHeight || document.body.parentNode.clientHeight
	},

	scrollY: function() {
		if (this.isIE) {
			return document.body.parentNode.scrollTop
		} else {
			return window.scrollY
		}
	},
	locale: function(){
		var lang;
	    if (typeof navigator.userLanguage != "undefined") {
	        lang = navigator.userLanguage.toUpperCase();
	    } else if (typeof navigator.language != "undefined") {
	        lang = navigator.language.toUpperCase();
	    } else {
	    	lang = "EN"
	    }
	    return lang
	}
}

var TodayNews={
	check: function() {
		var div=$('div_today');
		if (!div || (div && div.style.display!='none')) return;
		
		var isDefaultTextSize = (document.getElementById('fontSizeSample').offsetHeight == '12')
		var isSupportBrowser = (navigator.userAgent.indexOf('MSIE 6') !== -1 || navigator.userAgent.indexOf('MSIE 7') !== -1 || navigator.userAgent.indexOf('Firefox') !== -1 || navigator.userAgent.toLowerCase().indexOf('iceweasel') !== -1 || navigator.userAgent.indexOf('MSIE 8') !== -1)
				
		var release=div.className.match(/release([0-9]+)/);
		var check = Cookies.get('todayClose');
		if (check == release[1]) return;
		
		var msg = null;
		if (isDefaultTextSize && isSupportBrowser && sabalmyon && sabalmyon.randomTip && !Browser.isIE6)
			msg = sabalmyon.randomTip;
		if (!isDefaultTextSize)
			msg = getText('The text size is too big or small. – see <a href=\'http://helpcenter.springnote.com/pages/487399\'>Manual</a>');
		if (!isSupportBrowser)
			msg = getText('Your browser may not support some features in Springnote. <a href=\'http://helpcenter.springnote.com/pages/818682\'>Click here to read about supporting browsers</a>');
		
		if(msg) {
			$('today_content').innerHTML = msg;
			div.style.display="block";
			$("div_content").className +=" isToday2_true";
			//if (Browser.isIE6) Layout.init_ie6($("content-wrapper"));
		}				
	},
	close: function() {
		var div=$('div_today');
		if (!div) return;
		div.style.display='none';
		
		$('div_content').removeClassName('isToday2_true');
		if (Browser.isIE6) Layout.resize();
		
		var release=div.className.match(/release([0-9]+)/);
		var date=new Date;
		date.setMonth(date.getMonth()+3);
		Cookies.set('todayClose', release[1], date, '/');
	}
};
function selectAllCheck(check, checkName) {
	var input=document.getElementsByTagName('INPUT');
	for (var i=0; i < input.length; i++) {
		if (input[i].type == 'checkbox' && input[i].name == checkName)
			input[i].checked=check.checked;
	}
}

function drawSideMenu() {
	var idx=Cookies.get('Navi_idx', '1');
	if (idx == '0') {
		treeForRecentPages.requestAndDrawRecent(true);
	} else if (idx == '2'){
		TagTree.request(TagTree.tagOrderDir);
	} else { // idx == '1'
		treeForAllPages.draw(!sabalmyon.isWritableNote);
	}
}

function backupConfirm() {
	var confirmed = confirm(getText('Due to the burden on our servers you need to apply for using the feature Download All') + "\n" + getText('After applying for downloading all pages, we will send an email with a link you can download all your pages and attached files within 24 hours.') + "\n" + getText('Do you want to apply to download all pages?'))
	if (confirmed) {
		new Ajax.Request('/backups', {
			method:'post',
		sanitizeJSON: false,
		evalJSON: false
		})
		alert(getText('Due to the burden on our servers to download all your pages and attached files you need to get a ticket for this feature. After submitting this request, we will send an email with a link you can download all your pages and attached files within 24 hours.'))
	}
}

function completeId(input, login_url) {
	var inputValue = $(input) && $(input).value
	if (!inputValue || inputValue.length == 0) {
		window.location = login_url
		return false
	}

	inputValue = inputValue.split(".")[1];
	if (inputValue == null) {
		document.getElementById(input).value += ".myid.net";
		return false;
	}
	return true;
}
/*
setTimeout(function() {
	if ($("openid") && $("openid").offsetHeight > 0 && !$("__openidselector") && location.href.indexOf("#") == -1) $("openid").focus();
	if ($("id") && $("id").offsetHeight > 0 && location.href.indexOf("#") == -1 ) $('id').value ? $('pw').focus() : $('id').focus();
}, 1000);
*/

function convertDateSpan(name){
	var el = $(name);
	if (!el) return
	var val = parseInt(el.getAttribute('value'))
	time = new Date(val - (new Date().getTimezoneOffset()))
	el.innerHTML= getText.date(time, (el.className && el.className == "dateOnly"))
}

Date.interprete = function(s, date) {
	if(s.indexOf("지금") != -1) return Date.today()
	if(s.indexOf("언젠가") != -1) return Date.SOMEDAY
	
	var range = Date.getRange(s)
	s = s.replace("~", "")
	
	var date = date || Date.today()
	
	date = date.applyCommonCounter(s)
	date = date.applyWeek(s)
	date = date.applyWeekday(s)
	date = date.applyAbsoluteDate(s)
	date = date.applyAbsoluteTime(s)
	date = date.applyPlainRelatives(s)
	date = date.applyYearCounter(s)
	date = date.applyDayCounter(s)
	date = date.applyAmPm(s)
	date = date.applyRange(range)
	date.setMilliseconds(0)
	
	return date
}
Date.prototype.category = function() {
	var order1 = [
		"그제","어제","오늘","내일","모레",
		"지난주","다음주",
		"지난달","다음달",
		"작년","내년"
	]
	for(var i = 0; i < order1.length; i++) {
		if(this.isIn(Date.interprete(order1[i] + "~"), Date.interprete("~" + order1[i]))) return order1[i]
	}

	if(this.isIn(Date.interprete("이번주~"), Date.interprete("~이번주"))) return this.getTime() < Date.today().getTime() ? "며칠 전" : "며칠 후"
	if(this.isIn(Date.interprete("이번달~"), Date.interprete("~이번달"))) return this.getTime() < Date.today().getTime() ? "몇 주 전" : "몇 주 후"
	if(this.isIn(Date.interprete("올해~"), Date.interprete("~올해"))) return this.getTime() < Date.today().getTime() ? "몇 달 전" : "몇 달 후"

	return this.getTime() < Date.today().getTime() ? "몇 년 전" : "몇 년 후"
}
Date.prototype.isIn = function(from, to) {
	return from.getTime() <= this.getTime() && this.getTime() <= to.getTime()
}
Date.prototype.applyRange = function(range) {
	if(range == "none") return this
	var date = this.clone()
	var defaults = range == "from" ?
		{month:01-1, week:"일요일", day:"1일", hour:00, min:00, sec:00, msec:000} :
		{month:12-1, week:"토요일", day:"말일", hour:23, min:59, sec:59, msec:999}
	
	switch(date.getPrecision()) {
	case "year":
		date.setMonth(defaults.month)
	case "month":
		date = Date.interprete(defaults.day, date)
	case "week":
	case "day":
		date.setHours(defaults.hour)
	case "hour":
		date.setMinutes(defaults.min)
	case "min":
		date.setSeconds(defaults.sec)
	case "sec":
		date.setMilliseconds(defaults.msec)
	}

	if(date.getPrecision() == "week") {	
		date = Date.interprete(defaults.week, date)
	}
	
	return date
}
Date.getRange = function(str) {
	var index = str.indexOf("~")
	if(index == 0) return "to"
	if(index == str.length - 1) return "from"
	return "none"
}
Date.prototype.getPrecision = function() {
	return this._precision || "msec"
}
Date.prototype.setPrecision = function(p) {
	var precisions = "msec,sec,min,hour,day,week,month,year"
	this._precision =
		precisions.indexOf(precisions.indexOf(p) > this.getPrecision()) ?
		p : this._precision 
}
Date.prototype.applyAbsoluteDate = function(str) {
	var p = /(?:(\d+)(?:년|년 ))?(?:(\d+)(?:월|월 ))?(?:(\d+)일)(?!전|후)/
	var p2 = /(?:(\d+)\/)?(\d+)\/(\d+)(?!전|후)/
	var p3 = /(\d+)(?:년|년 )(?:(\d+)(?:월|월 ))?(?!전|후)/
	
	var date = this.clone()
	if(str.match(p)) {
		m = p.exec(str)
		if(m[1]) {
			date.setFullYear(m[1])
			date.setPrecision("year")
		}
		if(m[2]) {
			date.setMonth(m[2] - 1)
			date.setPrecision("month")
		}
		if(m[3]) {
			date.setDate(m[3])
			date.setPrecision("day")
		}
	} else if(str.match(p2)) {
		m = p2.exec(str)
		if(m[1]) {
			date.setFullYear(m[1])
			date.setPrecision("year")
		}
		if(m[2]) {
			date.setMonth(m[2] - 1)
			date.setPrecision("month")
		}
		if(m[3]) {
			date.setDate(m[3])
			date.setPrecision("day")
		}
	} else if(str.match(p3)) {
		m = p3.exec(str)
		date.setFullYear(m[1])
		date.setPrecision("year")
		if(m[2]) {
			date.setMonth(m[2] - 1)
			date.setPrecision("month")
		}
	}
	return date
}
Date.prototype.applyAbsoluteTime = function(str) {
	var p = /(\d+)(?:시|:)(?!간)(?:(\d+)(?:분|:)?(?:(\d+)초?)?)?(?!전|후)/
	var date = this.clone()
	if(str.match(p)) {
		m = p.exec(str)
		date.setHours(m[1])
		date.setMinutes(m[2] || 0)
		date.setSeconds(m[3] || 0)
		date._precision = "msec"
	}
	return date
}
Date.prototype.applyAmPm = function(str) {
	var p = /(오후|PM)/i
	var date = this.clone()
	if(str.match(p)) {
		date = date.add(12, "시간")
	}
	return date
}
Date.prototype.applyPlainRelatives = function(str) {
	var plainRelatives = /((\d+)\s?(년|해|월|개월|달|주일|주|일|시간|분|초)[^오]*(전|후))/
	var date = this
	if(str.match(plainRelatives)) {
		var m = plainRelatives.exec(str)
		var matched = m[1]
		var dir = matched.substring(matched.length - 1) == "전" ? -1 : +1
		var tokens = matched.match(/(\d+)\s?(년|해|월|개월|달|주일|주|일|시간|분|초)/)
		
		var num = this.interpreteCounter(tokens[1])
		var unit = tokens[2].replace(' ', '')
		date = date.add(num * dir, unit)
		switch(unit) {
			case "년":
			case "해":
			case "월":
			case "개월":
			case "달":
			case "주일":
			case "주":
			case "일":
				date._precision = "day"
				break
			case "시간":
			case "분":
			case "초":
				date._precision = "msec"
				break
		}
	}
	return date
}
Date.prototype.applyWeek = function(str) {
	var counters = {
		"첫째": 0, "둘째": 1, "셋째":2, "넷째":3, "다섯째":4
	}
	var p = /(첫째|둘째|셋째|넷째|다섯째|마지막)\s?주/
	if(str.match(p)) {
		var m = p.exec(str)
		var date = this.clone()
		if("마지막" == m[1]) {
			date.setMonth(date.getMonth() + 1)
			date.setDate(-1)
		} else {
			date.setDate(1)
			date = date.add(counters[m[1]], "주")
		}
		return date
	}
	return this
}
Date.prototype.applyWeekday = function(str) {
	var p = /(월|화|수|목|금|토|일)요일/
	if(str.match(p)) {
		var date = this.setWeekday(p.exec(str)[1])
		date._precision = "day"
		return date
	} else {
		return this
	}
}
Date.prototype.interpreteCounter = function(str) {
	var counters = {
		"지지난": -2,
		"지난": -1,
		"이번": 0,
		"다음": +1,
		"다다음": +2
	}
	
	return counters[str] != null ? counters[str] : parseInt(str)
}

Date.prototype.applyCommonCounter = function(str) {
	var p = /(지지난|지난|이번|다음|다다음)\s?(해|달|주|날)/
	var date = this
	if(str.match(p)) {
		var m = p.exec(str)
		var num = this.interpreteCounter(m[1])
		var unit = m[2]
		date = date.add(num, unit)
		switch(unit) {
		case "해": date._precision = "year";break
		case "달": date._precision = "month";break
		case "주": date._precision = "week";break
		case "날": date._precision = "day";break
		}
	}
	return date
}

Date.prototype.applyYearCounter = function(str) {
	var counters = {
		"재작년": -2,
		"작년": -1,
		"올해": 0,
		"금년": 0,
		"내년": +1,
		"내후년": +2
	}
	
	for(var k in counters) {
		if(str.match(k)) {
			var date = this.add(counters[k], "년")
			date._precision = "year"
			return date
		}
	}
	return this
}
Date.prototype.applyDayCounter = function(str) {
	if(str.match("말일")) {
		var date = this.clone()
		date.setDate(1)
		date.setMonth(date.getMonth() + 1)
		return date.add(-1, "일")
	}
	
	var counters = {
		"그끄제": -3,
		"그끄저께": -3,
		"그제": -2,
		"그저께": -2,
		"아레": -2,
		"어제": -1,
		"오늘": 0,
		"금일": 0,
		"내일": +1,
		"모레": +2,
		"그글피": +4,
		"글피": +3,
		
		"하루": 1,
		"이틀": 2,
		"사흘": 3,
		"나흘": 4,
		"닷세": 5,
		"엿세": 6
	}
	
	for(var k in counters) {
		if(str.match(k)) {
			var date = this.add(counters[k], "일")
			date._precision = "day"
			return date
		}
	}
	return this
}

Date.prototype.formatWithPrecision = function() {
	var s = this.format()
	switch(this.getPrecision()) {
		case "year":
			return s.substring(0, 4)
		case "month":
			return s.substring(0, 7)
		case "week":
		case "day":
			return s.substring(0, 10)
		case "hour":
		case "min":
			return s.substring(0, 16)
	}
	return s
}
Date.prototype.format = function() {
	return this.formatDate() + " " + this.formatTime()
}
Date.prototype.formatDate = function() {
	var year = ('0000' + this.getFullYear()).right(4)
	var month = ('00' + (this.getMonth() + 1)).right(2)
	var day = ('00' + this.getDate()).right(2)
	return year + "/" + month + "/" + day
}
Date.prototype.formatTime = function() {
	return this.toTimeString().split(' ')[0]
}
Date.prototype.equals = function(target) {
	return this.getTime() == target.getTime()
}
Date.prototype.diff = function(target) {
	var localHour = new Date(0).getHours()
	var localMin = new Date(0).getMinutes()
	var localMsec = (localHour * 60 + localMin) * 60 * 1000
	return new Date(this - target - localMsec)
}
Date.prototype.add = function(num, unit) {
	var units = {
		"주일":	1000 * 60 * 60 * 24 * 7,
		"주":	1000 * 60 * 60 * 24 * 7,
		"일":	1000 * 60 * 60 * 24,
		"시간":	1000 * 60 * 60,
		"분":	1000 * 60,
		"초":	1000
	}
	if(units[unit]) {
		var newDate = new Date(this.getTime() + (num * units[unit]))
		newDate._precision = this._precision
		return newDate
	}
	
	var date = this.clone()
	if("년" == unit || "해" == unit) {
		date.setYear(date.getFullYear() + num)
	} else if("달" == unit || "개월" == unit) {
		date.setMonth(date.getMonth() + num)
	}
	return date
}
Date.prototype.time = function() {
	return Date.parseTime(this.formatTime())
}
Date.preset = null
Date.get = function() {
	return Date.preset == null ? new Date() : Date.preset
}
Date.pass = function(str) {
	if(Date.preset == null) return
	Date.preset = new Date(Date.preset.getTime() + msec)
}
Date.today = function() {
	if(Date.preset == null) {
		var date = Date.get()
		date._precision = "msec"
		return date
	} else {
		return Date.preset.clone()
	}
}
Date.parseTime = function(str) {
	var time = Date.parse('1970/01/01 ' + str)
	return new Date(time)
}
Date.weekdays = {
	"Sun":0, "일":0,
	"Mon":1, "월":1,
	"Tue":2, "화":2,
	"Wed":3, "수":3,
	"Thu":4, "목":4,
	"Fri":5, "금":5,
	"Sat":6, "토":6
}
Date.prototype.getWeekday = function() {
	return Date.weekdays[this.toDateString().split(' ')[0]]
}
Date.prototype.setWeekday = function(n) {
	if(Date.weekdays[n] != null) n = Date.weekdays[n]
	return this.add(n - this.getWeekday(), "일")
}
Date.prototype.clone = function() {
	var cloned = new Date(this.getTime())
	cloned._precision = this._precision
	return cloned
}
Date.prototype.elapsed = function(msec) {
	return Date.get().getTime() - this.getTime() >= msec
}
Date.prototype.timeInWords = function(isLater) {
	var from_time = parseInt(Date.get().getTime() / 1000)
	var to_time = parseInt(this.getTime() / 1000)
	distance_in_minutes = parseInt(Math.abs(to_time - from_time) / 60.0 + 0.5)
	distance_in_seconds = Math.abs(to_time - from_time)

	if(0 <= distance_in_minutes && distance_in_minutes <= 1) {
		if(distance_in_seconds == 0) {
			return getText('Now');
		} else {
			return distance_in_seconds + getText((isLater)? " seconds later":" seconds ago")
		}
	} else if(2 <= distance_in_minutes && distance_in_minutes <= 59) {
		return distance_in_minutes + getText((isLater)? ' minutes later':' minutes ago')
	} else if(60 <= distance_in_minutes && distance_in_minutes <= 60*24) {
		return getText((isLater)? '$1 hours and $2 minutes later':'$1 hours and $2 minutes ago', parseInt(distance_in_minutes/60), (distance_in_minutes%60));
	} else if(60*24 <= distance_in_minutes && distance_in_minutes <= 60*24*2) {
		return getText((isLater)? 'tomorrow, $1 hours later':'yesterday, $1 hours ago', Date.get().getHours());
	} else if(60*24*2 <= distance_in_minutes && distance_in_minutes <= 60*24*5) {
		return getText((isLater)? '$1 days and $2 hours later':'$1 days and $2 hours ago', parseInt(distance_in_minutes/60/24), Date.get().getHours());
	} else {
		return getText('on $1',this.format());
	}
}

Date.SOMEDAY = new Date(Date.parse("2050/12/31 23:59:59"))
Date.LONGAGO = new Date(Date.parse("1970/01/01 00:00:00"))

function getSecofWeek(date) {
	date = date || new Date()
	var firstDate = new Date(date.getFullYear(), date.getMonth(), 1);
	return Math.ceil((parseInt(date.getDate()) + firstDate.getDay()) / 7);
}

String.prototype.right = function(len) {
	return this.substring(this.length - len)
}
String.prototype.merge = function(data) {
	var newString = this
	for(var k in data) {
		newString = newString.replace("{" + k + "}", data[k])
	}
	return newString
}
String.prototype.lastIndexOfChars = function(s) {
	var max = -1;
	var temp;
	for(var i = 0; i < s.length; i++) {
		temp = this.lastIndexOf(s.charAt(i));
		max = Math.max(max, temp);
	}
	return max;
}

String.prototype.indexOfChars = function(s) {
	var min = 1000000; // big enough len
	
	for(var i = 0; i < s.length; i++) {
		var temp = this.indexOf(s.charAt(i));
		if(temp != -1) min = Math.min(min, temp);
	}
	return min == 1000000 ? -1 : min;
}

var asEventSource = function(object, prefix, events) {
	object._listeners = []
	object._registerEventFirer = function(prefix, name) {
		this["_fireOn" + name] = function() {
			var listener, func;
			for(var i = 0; i < this._listeners.length; i++) {
				listener = this._listeners[i]
				func = listener["on" + prefix + name]
				if(func) func.apply(listener, $A(arguments))
			}
		}
	}
	object.addListener = function(l) {
		this._listeners.push(l)
	}
	
	for(var i = 0; i < events.length; i++) {
		object._registerEventFirer(prefix, events[i])
	}
}

// fix IE bug: style background-image cache bug
try {document.execCommand("BackgroundImageCache", false, true)} catch(ignored) {}

function copy(url) {
	var flashcopier = 'flashcopier';
	if(!document.getElementById(flashcopier)) {
		var divholder = document.createElement('div');
		divholder.id = flashcopier;
		//divholder.style.display='none';
		document.body.appendChild(divholder);
	}
	document.getElementById(flashcopier).innerHTML = '';
	var divinfo = '<embed src="/javascripts/clipboard.swf" FlashVars="clipboard='+encodeURIComponent(url)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
	document.getElementById(flashcopier).innerHTML = divinfo;
}
var JSversion = "2"

function trim(str) {
  if (str == null) 
    return null;

  var startingIndex = 0;
  var endingIndex   = str.length-1;
  
  while (str.substring(startingIndex, startingIndex+1) == ' ')
    startingIndex++;

  while (str.substring(endingIndex, endingIndex+1) == ' ')
    endingIndex--;

  if (endingIndex < startingIndex) 
    return '';

  return str.substring(startingIndex, endingIndex+1);
}
var headerUtil = {
	divNavMenus:'',
	toggleMynote: function(){
		if($("myNoteLayer")) $("myNoteLayer").style.display = ($("myNoteLayer").style.display != "block")? "block":"none"
	},
	offMynote: function(){
		setTimeout('if($("myNoteLayer") && $("myNoteLayer").style.display!="none") $("myNoteLayer").style.display = "none";',300);
	},
	ieDesignTuning: function() {
		if (document.getElementById('groupnoteList')) {
		var groupnoteListEl = document.getElementById('groupnoteList')
		if (groupnoteListEl.offsetHeight > 192) {
			groupnoteListEl.style.height = 192 + 'px';
			groupnoteListEl.style.overflowY = 'auto';
			groupnoteListEl.style.overflowX = 'hidden';
			}				
		}		
	},
	tweakGnbForIE: function(){
		if (Browser.isIE) {
			var _headerMenuTimer={};
			var _findMenuItem=function(e) {
				var li=e.srcElement;
				while (li && li.parentNode && li.parentNode.id != 'div_nav_menus')
					li=li.parentNode;
				return li;
			};
			EventHandler.addEvent($('div_nav_menus'), 'mouseover', function(e) {
				headerUtil.offMynote();
				var li=_findMenuItem(e);
				if (li) {
					if (!li.id) li.id='TMP_'+Math.round(Math.random()*10000);
					clearTimeout(_headerMenuTimer[li.id]);
				}
				if (li && li.className != 'loginLi firstChild') li.className='selected';
				if (!headerUtil.divNavMenus && li.id == "groupnoteWrapper") {
					headerUtil.ieDesignTuning();
					headerUtil.divNavMenus = "called";
				}
			});
			EventHandler.addEvent($('div_nav_menus'), 'mouseout', function(e) {
				var li=_findMenuItem(e);
				if (li)
					clearTimeout(_headerMenuTimer[li.id]);
				if (li && li.className != 'loginLi firstChild' && li.className == 'selected')
					_headerMenuTimer[li.id]=setTimeout(function() {li.className='';}, 10);
			});
		} else {
			EventHandler.addEvent($('div_nav_menus'), 'mouseover', function(e) {
				headerUtil.offMynote();
				return false;
			});
		}	
	}
}

function tweakAnchors(){
	if (!$("contentContainer") || typeof($("contentContainer").getElementsByTagName)== 'undefined') return;

	var anchors = $("contentContainer").getElementsByTagName('A');
	if (!anchors) return;
	
	for (var i = 0; i < anchors.length; i++){
		// new window
		if (anchors[i].className.indexOf("newWindow") != -1) {
			anchors[i].onclick = function(e){
				window.open(this.href, "_blank");
				return false;
			}
		}
		
		// open new page dialog
		var href = anchors[i].href;
		if(sabalmyon && sabalmyon.isWritableNote && href.indexOf("/pages/search?") != -1 && (href.indexOf("&parent_id=") != -1 || href.indexOf("&amp;parent_id=") != -1)) {
			anchors[i].onclick = function(e){
				var text=decodeURIComponent(this.href.match(/\?q=([^&]+)/).pop());
				openNewPageDialogWithText(text);
				return false;
			}
		}
	}
}

function openNewPageDialogWithText(text){
	toggleNewPageDialog('child');
    $('newPageDialogInputBox').focus();
	$('newPageDialogInputBox').value = text;
}
function toRight(){
	$('allTreeContainer').style.left = ($('allTreeContainer').style.left.replace('px','') - 5) + 'px';
}
function toLeft(){
	if(Number($('allTreeContainer').style.left.replace('px','')) < -4) {
		$('allTreeContainer').style.left = (Number($('allTreeContainer').style.left.replace('px','')) + 5) + 'px';
	}
}
function initSearchQuery(){
	if (!$('searchQuery')) return;
	
	var search_ac = new Autocompleter.Local("searchQuery", "searchQuery_choices", sabalmyon.pagenames, {
		frequency: 0.1, 
		afterUpdateElement: function(element, select) {
			element.form['fulltext'].value='';
			element.form.submit();
		}
	});

	search_ac.options.onShow = function(element, update) {
		element.form['fulltext'].value = '1';
		update.style.left = element.offsetLeft + 'px';
		update.style.width = element.offsetWidth - 2+'px';
		update.style.top = element.offsetTop + element.offsetHeight + 2 +'px';
		//update.style.height = Layout.left.clientHeight-$('div_navi').offsetTop-12+'px';
		Effect.Appear(update,{duration:0.15});
	};
	
	new Form.Element.Observer(search_ac.element.id, 0.1, search_ac.onKeyPress.bindAsEventListener(search_ac));
}
function toggleLinkedList(elem){
	if (!$("related-page")) return;
	var ul = $("related-page").getElementsByTagName("UL")[0]
	elem.innerHTML = (ul.className)? getText('less'):getText('more')
	ul.className = (ul.className)? '':'default';
	
}
function scrollIntoCurrentPageNode (){
	if (typeof($("allTreeContainer").select) == 'undefined') return
	if (!$("allTreeContainer").select(".currentPageLiNode").length) return;
	if ($("pageTreeContent").offsetHeight + 15 > $("allTreeContainer").select(".currentPageLiNode")[0].offsetTop) return
	$("allTreeContainer").select(".currentPageLiNode")[0].scrollIntoView(true);
	$("pageTreeContent").scrollLeft = 0
}
function checkEnableEdit(pageNum){
	if (!sabalmyon.shared){
		return true;
	} else {
		var returnValue = false;
		var url = (pageNum)? "/pages/" + pageNum + "/lock.json" : sabalmyon.jsonLockUrl
		var ajax = new Ajax.Request(url, {
			method:'get',
			asynchronous: false,
			onSuccess: function(transport, param){
				eval('var response = ' + transport.responseText)
				if(!response.creator || response.creator == sabalmyon.curUserOpenId) {
					returnValue = true;
				} else {
					display.displayMessage($("bubbleMessageDialog"), getText('$1 is editing now. Please wait.<br />Lock expiration: $2',response.creator_nickname.escapeHTML(), new Date(response.date_expired).timeInWords(true)),{duration:5})
				}
			},
			onFailure: function(transport, param){
				eval('var response = ' + transport.responseText)
				if (response[0].error){
					display.displayMessage($("bubbleMessageDialog"),"Error: " + response[0].error.description,{duration:5})
				}
				returnValue = false;
			},
			sanitizeJSON: false,
			evalJSON: false
		});		
		return returnValue;
	}
}

function switchTab(element){
	var selectedTab = element.className;
	if (selectedTab.indexOf('on') + 1) return;
	var unselectedTab = (selectedTab == 'total-page')? 'recent-page':'total-page';
	$("titles").select("." + unselectedTab)[0].className = unselectedTab
	element.className += " on";
	
	$(selectedTab).style.display = "block";
	$(unselectedTab).style.display = "none";
	
	var date= new Date();
	date.setMonth(date.getMonth()+3);
	
	Cookies.set('leftTabIndex', selectedTab, date, '/');
	
}

function getURLParam(strParamName, url){
  var strReturn = "";
  var strHref = url || window.location.href;
  if (strHref.indexOf("?") > -1){
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return unescape(strReturn);
}

var GuideDialog = {
	currentNum:0,
	currentGuideType:'',
	type: {
		'news':['notetype','dashboard','sharedpage','comment','viewmode'],
		'personal':['personalnote','dashboard','organization','sharedpage','privacy-setting','history','viewmode'],
		'group':['groupnote','dashboard','organization','groupmember','comment','history','viewmode'],
		'open':['opennote','dashboard','organization','viewmode']
	}, 
	start: function(guideType){
		this.currentGuideType = (!guideType)? sabalmyon.noteType : guideType
		if (!$('guide-' + this.type[this.currentGuideType][0])) Partial.load('guide_dialogs');
		Dialog.show('guide-' + this.type[this.currentGuideType][0], {absolute:true, center: true, dimmed: true});
		this.currentNum = 0;
		if (Browser.isIE) {
			setTimeout(function(){
				Button.init('bodys')
			}.bind(this),0)
		}
	},
	prev: function(){
		var previousNum = (this.currentNum)? this.currentNum - 1:this.type[this.currentGuideType].length - 1
		Dialog.close('guide-' + this.type[this.currentGuideType][this.currentNum]);
		Dialog.show('guide-' + this.type[this.currentGuideType][previousNum], {absolute:true, dimmed: true});
		this.currentNum = previousNum
	},
	next: function(){
		var nextNum = (this.type[this.currentGuideType].length > this.currentNum + 1)? this.currentNum + 1:0
		Dialog.close('guide-' + this.type[this.currentGuideType][this.currentNum]);
		Dialog.show('guide-' + this.type[this.currentGuideType][nextNum], {absolute:true, dimmed: true});
		this.currentNum = nextNum
	}
}
