/**
 * Á¦ÀÛ»ç: BraunSton Interactive Co.
 * ÆÄÀÏID: $Id: locator.js,v 1.21 2008/06/03 10:27:16 dev08 Exp $
**/

/****************************************************************************************
 * Constant
 ****************************************************************************************/

/* Context Path */
var LOC_CONTEXT_PATH = '';

/* Parameter Name */
var LOC_PARAM_CURR_PAGE = 'currentPage';
var LOC_PARAM_SORT = 'sort';
var LOC_PARAM_SORT_FIELD = 'sortField';
var LOC_PARAM_SORT_ORDER = 'sortOrder';
/* URL */
var LOC_URL_EXTENSION = '.jsp';
var LOC_PTN_CONTEXTPATH = new RegExp("^(/\w+)(/.+)$");
var LOC_PTN_FILEPATH = new RegExp("[w\.]+$");

/****************************************************************************************
 * Parameter Function
 ****************************************************************************************/
/*
 * getContextPath
 */
function getContextPath() {

	return '';
	
//	var pn = self.location.pathname;
//	//alert(pn);
//	var p = pn.indexOf('/', 1);
//
//	if(p>1) {
//		return pn.substring(0, p);
//	}
//	else {
//		return '';
//	}
}

/*
 * location.pathname
 */
function getPathname(a) {
	var pn = self.location.pathname;
	//alert(pn + ":" + LOC_PTN_FILEPATH);
	return pn.replace(LOC_PTN_FILEPATH, a);
}

/*
 * location.search
 */
function getSearch() {
	
	var args = getSearch.arguments;
	if(args.length==0) {
		return location.search;
	}

	var s = args.length>1? args[0]: location.search;
	var arg = '?' + (args.length>1? args[1]: args[0]);
	//alert(arg);
	if(!s) {
		return arg;
	}

	var search = arg;
	
	if(s.indexOf('?')==0) {
		s = s.substr(1);
	}
	
	var a = s.split('&');
	var p, k;
	for(var i=0; i<a.length; i++) {
		
		p = a[i].indexOf('=');
		if(p<=0) {
			continue;
		}

		k = a[i].substring(0, p+1);
		if(arg.indexOf(k)<0) {
			search += '&' + a[i];
		}
	}

	return search;
}

/*
 * location.search
 */
function getQueryString() {

	var args = getQueryString.arguments;
	if(args.length==0) {
		return location.search;
	}

	var search;
	if(args.length%2==1) {
		search = args[0];
		args.remove(0);
	}
	else {
		search = location.search;
	}
	
	var k, r, s = search;
	for(var i=0, l=args.length-1; i<l; i=i+2) {

		k = args[i];
		r = new RegExp('\\b' + k + '=([^&]*)');
		if(r.test(search)) {
			s = s.replace(r, k + '=' + args[i+1]);
		}
		else {
			s += (s? '&' : '?') + k + '=' + args[i+1];
		}
	}

	return s;
}

/*
 * return the value of given parameter extracted from URL QueryString.
 */
function getParameter(name) {

	var s, i, j, k;
	s = self.location.search;
	i = s.indexOf(name + '=');
	if(i<0) {
		return null;
	}

	j = i + name.length + 1;
	k = s.indexOf('&', j);

	return (k<0)? s.substr(j) : s.substring(j, k);
}

/*
 * another logic of implementating getParameter function.
function getParameter(n) {

	var s = new String(self.location.search);

	ss = s.substr(1).split('&');
	for(var i=0; i<ss.length; i++) {
		var pair = ss[i].split('=');
		if(pair[0]==n) {
			return pair[1];
		}
	}

	return null;
}
*/

/****************************************************************************************
 * navigation
 ****************************************************************************************/

/**
 * paging
 *
 * argument, paging
 * argument,
 */
function paging() {

	var a = paging.arguments;
	
	var prefix = "";
	
	if(a.length==0) {
		a[0] = 1;
	}
	else if(a.length == 2 && a[1] != "")
	{
		prefix = a[1] + ".";
	}
	
	self.location.search = getSearch(prefix + LOC_PARAM_CURR_PAGE + '=' + a[0]);

	/*
	var panel = Event.element(event).up('.pagingpanel');
	if(!panel) {
		self.location.search = getSearch(LOC_PARAM_CURR_PAGE + '=' + a[0]);
	}
	else {
		var target = panel.readAttribute('target');
		var path = panel.readAttribute('path');
		var search = panel.readAttribute('search');

		if(!target) {
			target = panel.id;
		}
		
		if(!search) {
			search = '';
		}

		loadPage(target, path, getSearch(search, LOC_PARAM_CURR_PAGE + '=' + a[0]));
	}
	*/
}
	
/**
 * change location
 */
function locating() {

	var a = locating.arguments;
	if(a.length==0) {
		return;
	}

	var pathname = ((a[0].charAt(0)=='/')? a[0]: getPathname(a[0]));

	self.location = LOC_CONTEXT_PATH + pathname + getSearch(LOC_PARAM_CURR_PAGE + '=' + 1 + '&' + LOC_PARAM_SORT_FIELD + '=&' + LOC_PARAM_SORT_ORDER + '=');
}

function sorting(field, order) {

	var currField = getParameter(LOC_PARAM_SORT_FIELD);
	var currOrder = getParameter(LOC_PARAM_SORT_ORDER);
	if(field!=currField || currOrder==null) {
		vcOrder = order;
		if(vcOrder==null) {
			vcOrder = 'desc';
		}
	}
	else if(currOrder=='asc') {
			vcOrder = 'desc';
	}
	else if(currOrder=='desc') {
			vcOrder = 'asc';
	}
	else {
		vcOrder = 'desc';
	}
	
	self.location.search = getSearch(LOC_PARAM_SORT_FIELD + '=' + field + '&' + LOC_PARAM_SORT_ORDER + '=' + vcOrder + '&' + LOC_PARAM_CURR_PAGE + '=' + 1);
}

// Search
function searching(oForm) {

	var oColl = oForm.elements;
	var query;
	
//  alert(query);
	if(oColl) for(var i=0; i<oColl.length; i++) {
		var o = oColl.item(i);

		switch(o.tagName) {
		case 'SELECT' :
			query = getSearch(o.name + '=' + o.options(o.selectedIndex).value);
			break;

		case 'TEXTAREA' :
			break;

		case 'INPUT' :
			switch(o.type) {
			case 'radio' :
				break;

			case 'checkbox' :
				break;

			case 'hidden' :
			case 'text' :
				query = getSearch(o.name + '=' + o.value);
				break;

			default :
			}
			break;

		default :
		}
	}

	self.location.search = query;
	return false;
}

var Nav = Class.create({
	
	pathnamePattern: /[a-z]+([A-Z][A-Za-z]+)*(?:!\w+)*\.(\w+)/,

	initialize: function() {
		this.pathname = window.location.pathname;
		this.search = window.location.search;
	},
	getPathname: function(p) {
		return this.pathname.sub(this.pathnamePattern, p + "#{1}.#{2}");
	},
	getPathnameInput: function(p) {
		return this.pathname.sub(this.pathnamePattern, p + "#{1}.#{2}");
	},
	getPathnamesInput: function(p) {
		return this.pathname.sub(this.pathnamePattern, p + "#{1}.#{2}");
	},
	list: function() {
		//alert(this.getPathname("list"));
		//alert(self.location.pathname);
		//alert(getSearch());		
		//alert(this.getPathname("list") + getSearch());		
		window.location.href = this.getPathname("list") + getSearch();
		//window.location.pathname = this.getPathname("list");
	},
	listKey: function(s) {
		if(s) {
			this.search = getSearch(s);
		}
		window.location.href = this.getPathnameInput("list") + this.search;
	},
	lists: function() {
		window.location.href = this.getPathname("list");
	},

	view: function(s) {

		if(s) {
			this.search = getSearch(s);
		}

		window.location.href = this.getPathname("view") + this.search;
	},

	make: function() {
		window.location.href = this.getPathnameInput("make") + this.search;
	},

	write: function(s) {

		if(s) {
			this.search = getSearch(s);
		}

		window.location.href = this.getPathnameInput("write") + this.search;
	},
	
	update: function(s) {

		if(s) {
			this.search = getSearch(s);
		}

		window.location.href = this.getPathnameInput("update") + this.search;
	},	

	edit: function(s) {

		if(s) {
			this.search = getSearch(s);
		}

		window.location.href = this.getPathnameInput("edit") + this.search;
	},

	erase: function(s) {

		if(s) {
			this.search = getSearch(s);
		}

		if(!confirm("»èÁ¦ÇÏ½Ã°Ú½À´Ï±î?")) {
			return;
		}

		window.location.href = this.getPathname("delete") + this.search;
	},

	eraseall: function(oform, id) {

		var g = document.all(id);
		var n = '';

		if(g.length) for(var i=0; i<g.length; i++) {
			if(g[i].checked) n += ', '+g[i].value;
		}
		else if(g) {
			n = ', '+g.value;
		}

		if(n=='') {
			alert('.');
			return false;
		}

		if(!confirm("?")) {
			return false;
		}

		var node = document.createElement("INPUT");
		node.type = 'hidden';
		node.name = 'ns';
		node.value = n.substring(2);
		oform.appendChild(node);

		oform.action = getPathname('deleteall') + self.location.search;
	},

	saveall: function(oform, id) {

		var g = document.all(id);
		var n = '';

		if(g.length) for(var i=0; i<g.length; i++) {
			if(g[i].checked) {
				n += ', '+g[i].value;
			}
		}
		else if(g) {
			n = ', ' + g.value;
		}

		if(n=='') {
			alert('.');
			return false;
		}

		var node = document.createElement("INPUT");
		node.type = 'hidden';
		node.name = 'ns';
		node.value = n.substring(2);
		oform.appendChild(node);

		oform.action = getPathname('keepall') + self.location.search;
	},

	cancel: function() {
		window.history.back();
	}
});

var nav = new Nav();

function toggleAllCheckBox(ochk, name) {
	
	var v = "input[" + (name? "name='" + name: "type='checkbox") + "']";
	var g = $(ochk).up('form').select(v);
	for(var i=0, s=g.length; i<s; i++) {
		if(!g[i].disabled) {
			g[i].checked = ochk.checked;
		}
	}
}

/****************************************************************************************
 *  window, dialog window - open and close
 ****************************************************************************************/

/*
 * popup window.
 */
function openWindow() {

    var a = openWindow.arguments;
    if(a.length==0) {
        return;
    }

    var u = a[0];
    if(u.indexOf('/')==0) {
        u = getContextPath() + u;
    }

    var p = (a.length>1)? a[1]: '';
    //alert(p);

	//toolbar=no,directories=no,scrollbars=no,resizable=no,status=no,menubar=no
    var o = (a.length<=6)? 'directories=0, location=0, menubar=0, toolbar=0, scrollbars=0, statusbar=0, resizable=0' : a[6];
    if(a.length>2) o +=', width='+a[2];
    if(a.length>3) o +=', height='+a[3];
    if(a.length>4) o +=', left='+a[4];
    if(a.length>5) o +=', top='+a[5];

    var win = window.open(u, p, o);
    win.focus();

    return win;
}

function popupLoginUserList(userType) {

	var u = '/jsp/popup/listLogin' + userType + '.action?search.userType=';
	u += (userType=='Teachers')? 'TEACHER': 'OPERATOR';
	//alert(u);
	openWindow(u, '', 760, 400);
}

/*
 * popup window.
 */
function openDialog() {

	var a = openDialog.arguments;
	var u = a[0];
	if(u==null) {
		return;
	}

	var p = a[1];
	var o = (a[6]!=null)? a[6]: 'edge: raised; center: yes; help: no; resizable: no; status: no;';
	if(a[2]!=null) o +=' dialogWidth: '+a[2] + 'px;';
	if(a[3]!=null) o +=' dialogHeight: '+a[3] + 'px;';
	if(a[4]!=null) o +=' dialogLeft: '+a[4] + 'px;';
	if(a[5]!=null) o +=' dialogTop: '+a[5] + 'px;';

	return window.showModelessDialog(u, p, o);
}

/*
 * popup window.
 */
function winCloseAndReload() {
	opener.window.location.reload();
	self.close();
}

function changeLanguage(lang) {

	var p = {'currLocale': lang};
	new Ajax.Request('/dcfront/changeLanguage.wyz', {
		method: 'get',
		parameters: p,
		onSuccess: function() {
			location.reload();
		}
	});
}

/****************************************************************************************
 * submit form check
 ****************************************************************************************/
function checkformLogin(oform) {

	var userId = $('login_user_mailId');
	var passwd = $('login_user_passwd');
	
	if (!userId || !userId.present()) {
		message.alert("¾ÆÀÌµð¸¦ ÀÔ·ÂÇØ ÁÖ¼¼¿ä.");
		userId.focus();
		return false;
	}

	if (!passwd || !passwd.present()) {
		message.alert("ÆÐ½º¿öµå¸¦ ÀÔ·ÂÇØ ÁÖ¼¼¿ä.");
		passwd.focus();
		return false;
	}

	return true;
}

function isValidPostForm(oform) {
	oform.action += self.location.search;
	return true;
}

function isValidQuickLinkLinkDeleteForm(oform) {
	oform.action += getSearch("keyword" + '=' + oform.elements['keyword'].value);
	return true;
}

function submitGetForm(oform) {
	copySearchStringToHiddenInput(oform);
}

function submitSearchForm(oform) {
	var query = $(oform).serialize();
	return true;
}

function checkFormOnSubmit(oform) {

	var g = $(oform).getElements();
	var name, max, min, len;

	for (var i=0, s=g.size(); i<s; i++) {

		name = g[i].readAttribute('NAME');
		if (!name) {
			continue;
		}

		if (g[i].disabled) {
			continue;
		}

		if(!g[i].visible()) {
			continue;
		}

		switch (g[i].tagName) {

		case 'SELECT':
		case 'select':
			min = g[i].readAttribute('minlength');
			if (min){
				if(min > 0) {
					if(!g[i].present()) {
						message.alert(getTitleContext(g[i], 'À»(¸¦) ') + '¼±ÅÃÇØ ÁÖ½Ê½Ã¿À.');
						g[i].activate();
						return false;
					}
				}
			}
			break;

		case 'TEXTAREA':
		case 'textarea':
			if (g[i].hasClassName('EditCtrl')) {
			}
			else if (!checkTextElement(g[i])) {
				g[i].activate();
				return false;
			}
			break;

		case 'INPUT':
		case 'input':
			switch (g[i].readAttribute('type')) {
			case 'FILE':
			case 'file':
				min = g[i].readAttribute('minlength');
				if (min){
					if(min > 0) {
						if(!g[i].present()) {
							message.alert('ÆÄÀÏÀÌ ÇÊ¿äÇÕ´Ï´Ù.');
							g[i].activate();
							return false;
						}
					}
				}
				break;
			default:
				if (!checkTextElement(g[i])) {
					g[i].activate();
					return false;
				}
			}

			break;
		default:
		}
	}

	return true;
}

function checkTextElement(obj) {

	var pattern = obj.readAttribute('pattern');
	if (pattern) {
		var re = new RegExp(pattern);
		//alert(pattern);
		//alert($F(obj));
		if (!re.test($F(obj))) {
			message.alert('ÀÔ·Â ±ÔÁ¤À» ÁöÅ°ÁÖ½Ê½Ã¿À.');
			return false;
		}
	}

	len = ($F(obj))? $F(obj).length: 0;
	min = obj.readAttribute('minlength');
	if (min){
		if(min == 1) {
			if(!obj.present()) {
				message.alert(getTitleContext(obj, 'À»(¸¦) ') + 'ÀÔ·ÂÇÏ¿©¾ß ÇÕ´Ï´Ù.');
				obj.activate();
				return false;
			}
		}
		else if(min > 1) {
			if(len < min) {
				message.alert(min + 'ÀÚ ÀÌ»ó ÀÔ·ÂÇÏ¿©¾ß ÇÕ´Ï´Ù.');
				obj.activate();
				return false;
			}
		}
	}

	max = obj.readAttribute('maxlength');
	if (max){
		if(len > max) {
			message.alert(min + 'ÀÚ±îÁö¸¸ ÀÔ·Â°¡´ÉÇÕ´Ï´Ù.');
			obj.activate();
			return false;
		}
	}

	return true;
}

function getTitleContext(obj, aux) {

	var m = '', t = obj.up().previous('th');
	if(t) {
		m = t.innerText + (aux? aux: ' ');
	}

	return m;
}

function matchPattern(obj) {

	if(!$F(obj)) {
		return true;
	}

	var pattern = $(obj).readAttribute('pattern');
	if (!pattern) {
		return true;
	}

	var re = new RegExp(pattern);
	return re.test($F(obj));
}

/****************************************************************************************
 * Ajax ÀÏ¹Ý
 ****************************************************************************************/

/**
 * Ajax ÆäÀÌÁö ºÒ·¯¿À±â - GET ¹æ½Ä
 * target : È£ÃâÇÏ´Â °÷¿¡¼­ º¯È­°¡ ÀÏ¾î³¯ ID
 * path : È£Ãâ ÆäÀÌÁö...
 * search : ³Ñ¾î°¥ ÆÄ¶ó¹ÌÅÍ
 */
function loadPage(target, path, search) {

	//alert('"' + getContextPath() + '"');
	if(path.indexOf('/')==0) {
		path = getContextPath() + path;
	}

	new Ajax.Updater(target, path, {
		method: 'GET',
		evalScripts: true,
		parameters: search
	});
}

/**
 * Ajax ÆäÀÌÁö ºÒ·¯¿À±â - POST ¹æ½Ä
 */
function submitForm(target, path, oform) {

	if(!path) {
		path = oform.action;
	}

	if(path.indexOf('/')==0) {
		path = getContextPath() + path;
	}

	new Ajax.Updater(target, path, {
		parameters: $(oform).serialize(true)
	});
}

/**
 * Ajax ÆäÀÌÁö ºÒ·¯¿À±â - POST ¹æ½Ä
 */
function submitPost(target, oform) {

	var path = oform.action;
	if(path.indexOf('/')==0) {
		path = getContextPath() + path;
	}

	new Ajax.Updater(target, path, {
		parameters: $(oform).serialize(true)
	});
}

/****************************************************************************************
 * Message Ã³¸®
 ****************************************************************************************/

/**
 * Message Ã³¸®
 */
var Message = Class.create();
Message.prototype = {

	frameUrl: '/main/message/alert.wyz',
	frameId: null,
	
	initialize: function(frameId) {
		this.frameId = frameId;
		
//		this.alert.bind(obj);
//		this.show.bind(obj);
	},

	alert: function(obj) {
		
//		if (typeof obj == 'object') {
//			var m = obj.readAttribute('message');
//			if(m) {
//				this.show(eval(m));
//				return;
//			}
//			
//			return;
//		}
		
		if($(this.frameId)) {
			this.show(obj);
			return;
		}
		
		new Ajax.Updater(document.body, this.frameUrl, {
			
			insertion: Insertion.Top,
			onException: function(request, exception) {
				//alert(exception.message);
				alert(obj);
			},
			onFailure: function() {
				alert(obj);
			},
			onSuccess: function() {
				//this.frame = $(this.frameId);
				//this.show(obj);
				message.show(obj);
			}
		});
		
	},
	
	show: function(m) {
		
		try {
			$('messageLine').update(m);
		}
		catch(e) {
			alert(m);
			return;
		}
		
		var w = $(this.frameId);
		try {
			var d = w.down('div');
			var offset = document.viewport.getScrollOffsets();
			
			w.offsetWidth = document.viewport.getWidth();
			w.offsetHeight = document.viewport.getHeight();
			//w.offsetLeft = offset.left;
			w.offsetTop = offset.top;
			w.style.paddingTop = (w.offsetHeight - d.offsetHeight)/2;
			//d.offsetLeft = (w.offsetWidth - d.offsetWidth)/2;
		}
		catch(e) {
			alert(m);
			return;
		}
		
		w.show();
	}
};

var message = new Message('messageWindow');
//message.alert.bind(message);
//message.show.bind(message);
