///////////////////////////////////////////////////////////////////
// Copyright (C) Dao Trung Kien 2004-2006
// coded for http://www.thivien.net/
// using this code without my authorisation is illegal



function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	} else if (obj.x) curleft += obj.x;
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	} else if (obj.y) curtop += obj.y;
	return curtop;
}



function SendExclamation() {
	var c=document.createElement("<div>");
	document.body.appendChild(c);
	c.innerHTML='<form method="POST" action="addexclamation.php" name="ExclamationForm">'+
				'<input type="hidden" name="URL" value="">'+
				'</form>';
	document.ExclamationForm.URL.value=window.location;
	document.ExclamationForm.submit();
}


function MailPoemNotLogedIn() {
	alert("Hãy đăng nhập để gửi bài thơ");
}


///////////////////////////////////////////////////////////////////
// <SELECT>

function AddSelectOption(sel,name,value) {
	var opt=document.createElement("OPTION");
	opt.text=name;
	opt.value=value;
	sel.options.add(opt);
	return opt;
}

function ClearSelectOptions(sel) {
	sel.options.length=0;
}

// <SELECT>
///////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////
// Popup windows

function OpenModifyMemberTitlePopup(MemberID) {
	window.open("popup_modifymembertitle.php?ID="+MemberID,"ModifyMemberTitle",
			"width=400,height=200,menubar=no,toolbar=no,status=yes,scrollbars=yes");
}

function OpenBrowseAvatarGalleryPopup(MemberID) {
	window.open("popup_browseavatargallery.php?ID="+MemberID,"BrowseAvatarGallery",
			"width=500,height=400,menubar=no,toolbar=no,status=yes,scrollbars=yes");
}

function OpenUploadAvatarPopup(MemberID) {
	window.open("popup_uploadavatar.php?ID="+MemberID,"UploadAvatar",
			"width=500,height=400,menubar=no,toolbar=no,status=yes,scrollbars=yes");
}

// Popup windows
///////////////////////////////////////////////////////////////////





///////////////////////////////////////////////////////////////////
// Blink

BLINK_MODE_COLOR	=1;
BLINK_MODE_SHOW_HIDE=2;

var BlinkList=new Array();
var BlinkFlag=false;
var Blink_oldonload=null;

function BlinkAdd(obj,mode) {
	obj.BlinkMode=mode;
	BlinkList.push(obj);

	if (Blink_oldonload==null) {
		Blink_oldonload=window.onload;
		window.onload=Blink_onload;
	}
}

function BlinkTimer() {
	for (i=0; i<BlinkList.length; i++) {
		obj=BlinkList[i];
		switch(obj.BlinkMode) {
		case BLINK_MODE_SHOW_HIDE:	obj.style.display=BlinkFlag ? 'inline':'none';	break;
		case BLINK_MODE_COLOR:		obj.style.color=BlinkFlag ? '':'#3366FF';	break;
		}
	}

	BlinkFlag=!BlinkFlag;
	window.setTimeout(BlinkTimer,400);
}

function Blink_onload() {
	if (Blink_oldonload) Blink_oldonload();
	window.setTimeout(BlinkTimer,400);
}


// Blink
///////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////
// Show/Hide

function ShowHideApply(Link,Content) {
	if (Link.SHState=="show") {
		Link.innerHTML=Link.SHShowName;
		Content.style.display="block";
	} else {
		Link.innerHTML=Link.SHHideName;
		Content.style.display="none";
	}
}

function ShowHideInit(Link,Content,Name1,Name2,show) {
	Link.SHShowName=Name2;
	Link.SHHideName=Name1;
	Link.SHState=show ? "show":"hide";
	ShowHideApply(Link,Content);
}

function ShowHideOnClick(Link,Content) {
	Link.SHState=(Link.SHState=="show") ? "hide":"show";
	ShowHideApply(Link,Content);
}

// Show/Hide
///////////////////////////////////////////////////////////////////





///////////////////////////////////////////////////////////////////
// Popup tips


var POPUP_POS_MOUSE			=0;
var POPUP_POS_BELOW_LEFT	=1;
var POPUP_POS_BELOW_RIGHT	=2;

var PopupList=new Array();
var PopupIndex=-1;

function PopupListItem(btn,wnd,wndPos) {
	this.wnd=wnd;
	this.btn=btn;
	this.wndPos=wndPos;
}

function PopupWindowIn(evt) {
	evt = evt ? evt:window.event;
	var obj=evt.srcElement ? evt.srcElement:evt.target;
	if (obj.Old_onmouseover!=null) obj.Old_onmouseover();
	while (obj.PopupIndex==null) obj=obj.parentElement;

	if (PopupIndex!=-1) {
		if (PopupIndex==obj.PopupIndex) return;
		PopupList[PopupIndex].btn.style.display="none";
	}
	btn=PopupList[obj.PopupIndex].btn;
	wnd=PopupList[obj.PopupIndex].wnd;
	if (btn==null || wnd==null) return;

	PopupIndex=obj.PopupIndex;
	wnd.style.display="block";
	if (wnd.OnPopup!=null) wnd.OnPopup(btn,wnd);

	if (PopupList[PopupIndex].wndPos==POPUP_POS_MOUSE) {
		wndLeft=evt.clientX+document.body.scrollLeft;
		wndTop=evt.clientY+document.body.scrollTop;
	} else if (PopupList[PopupIndex].wndPos==POPUP_POS_BELOW_LEFT) {
		wndLeft=findPosX(btn);
		wndTop=findPosY(btn)+btn.offsetHeight-1;
	} else if (PopupList[PopupIndex].wndPos==POPUP_POS_BELOW_RIGHT) {
		wndLeft=findPosX(btn)+btn.offsetWidth-wnd.offsetWidth;
		wndTop=findPosY(btn)+btn.offsetHeight-1;
	}
	wndRight=wndLeft+wnd.offsetWidth;
	wndBottom=wndTop+wnd.offsetHeight;
	scrLeft=document.body.scrollLeft;
	scrRight=scrLeft+document.body.clientWidth;
	scrTop=document.body.scrollTop;
	scrBottom=scrTop+document.body.clientHeight;
	if (wndRight>scrRight) wndLeft-=wndRight-scrRight;
	if (wndBottom>scrBottom) wndTop-=wndBottom-scrBottom;
	if (wndLeft<scrLeft) wndLeft=scrLeft;
	if (wndTop<scrTop) wndTop=scrTop;

	wnd.style.left=wndLeft;
	wnd.style.top=wndTop;
}

// Is y a descendant of x ?
function Mozilla_contains(x,y) {
	for (; y!=null; y=y.parentNode)
		if (x==y) return true;
	return false;
}

function PopupWindowOut(evt) {
	evt = evt ? evt:window.event;
	if (evt==null) return;

	var obj=evt.srcElement ? evt.srcElement:evt.target;
	if (obj.Old_onmouseout!=null) obj.Old_onmouseout();
//	while (obj.PopupIndex==null) obj=obj.parentElement;

	if (PopupIndex==-1) return;
	btn=PopupList[PopupIndex].btn;
	wnd=PopupList[PopupIndex].wnd;
	if (btn==null || wnd==null) return;

	if (evt.toElement) {
		if (btn.contains(evt.toElement) || wnd.contains(evt.toElement)) return;
	} else if (evt.relatedTarget) {
		if (Mozilla_contains(btn,evt.relatedTarget) || Mozilla_contains(wnd,evt.relatedTarget)) return;
	}
	wnd.style.display="none";
	PopupIndex=-1;
}


function PopupInit(btnName,wndName,wndPos) {
	PopupList.push(new PopupListItem(btnName,wndName,wndPos));
}

Popup_Old_onload=window.onload;
window.onload=function() {
	if (Popup_Old_onload!=null) Popup_Old_onload();

	for (i=0; i<PopupList.length; i++) {
		btn=document.getElementById(PopupList[i].btn);
		PopupList[i].btn=btn;
		wnd=document.getElementById(PopupList[i].wnd);
		PopupList[i].wnd=wnd;
		if (btn==null || wnd==null) continue;

		btn.PopupIndex=i;
		wnd.PopupIndex=i;
		btn.Old_onmouseover=btn.onmouseover;	btn.onmouseover=PopupWindowIn;
		btn.Old_onmouseout=btn.onmouseout;		btn.onmouseout=PopupWindowOut;
		wnd.Old_onmouseout=btn.onmouseout;		wnd.onmouseout=PopupWindowOut;

		wnd.className="PopupWindow";
	}
}


// See also: FormatPopupWindow(..) in common.inc.php
function PopupWindowOnPopup(btn,wnd,reset_title,pre_title) {
	var Title=document.getElementById(wnd.getAttribute("id")+"_Title"),
		Panel=document.getElementById(wnd.getAttribute("id")+"_Panel");
	if (!Title || !Panel) return;
	if (reset_title) Title.innerHTML=pre_title+btn.innerHTML;

	if (parseInt(Panel.offsetWidth)<parseInt(wnd.style.width))
		wnd.style.width=Panel.offsetWidth;
}

// Popup tips
///////////////////////////////////////////////////////////////////




///////////////////////////////////////////////////////////////////
// Change style of all texts and textareas

function TSChangeStyle(obj) {
//	obj.className="input";
	obj.onfocus=function() {obj.className="textbox_on";}
	obj.onblur=function() {obj.className="input";}
}

TSOldOnload=onload;
onload=function() {
	if (TSOldOnload!=null) TSOldOnload();

	var list=document.getElementsByTagName("TEXTAREA");
	if (list!=null)
		for (var i=0; i<list.length; i++) TSChangeStyle(list[i]);

	list=document.getElementsByTagName("INPUT");
	if (list!=null)
		for (var i=0; i<list.length; i++) {
			type=list[i].type.toLowerCase();
			if (type=="text" || type=="button" || type=="submit" || type=="reset"
				|| type=="password" || type=="file") TSChangeStyle(list[i]);
			if (type=="checkbox") list[i].className='p';
		}
}


// Change style of all texts and textareas
///////////////////////////////////////////////////////////////////






///////////////////////////////////////////////////////////////////
// Scrolling Widget


SW_TIMER_INTERVAL=50;
SW_SCROLL_STEP=2;
var SWWidgets=new Array();
var SWTimerSet=false;
var SW_inited=false;
var SW_oldonload=window.onload;
window.onload=SWonload;

/* class ScrollingWidget:
ScrollingWidget.container
ScrollingWidget.content
ScrollingWidget.scrolling
*/

function ScrollingWidget(container_name,content_name) {
	this.container=document.getElementById(container_name);
	this.content=document.getElementById(content_name);
	this.scrolling=true;

	if (!this.container || !this.content || SWFindWidget(this.container)) return;
	SWWidgets.push(this);

	if (SW_inited && !SWTimerSet) {
		SWTimerSet=true;
		window.setTimeout(SWScroll,SW_TIMER_INTERVAL);
	}
}

function SWRemove(container_name) {
	c=document.getElementById(container_name);
	for (i=0; i<SWWidgets.length; i++)
		if (SWWidgets[i].container==c) {
			SWWidgets.splice(i,1);
			return true;
		}
	return false;
}

function SWonload() {
	if (SW_oldonload) SW_oldonload();

	working=false;
	for (i=0; i<SWWidgets.length; i++) {
		w=SWWidgets[i];
		if (w.scrolling && w.content.offsetHeight>w.container.offsetHeight) working=true;
	}

	if (working) {
		SWTimerSet=true;
		window.setTimeout(SWScroll,SW_TIMER_INTERVAL);
	}

	SW_inited=true;
}

function SWFindWidget(obj) {
	for (i=0; i<SWWidgets.length; i++)
		if (SWWidgets[i].container==obj) return SWWidgets[i];
	return null;
}

function SWScroll() {
	working=false;
	for (i=0; i<SWWidgets.length; i++) {
		w=SWWidgets[i];
		if (!w.scrolling || w.content.offsetHeight<=w.container.offsetHeight) continue;

		w.content.style.top=w.content.offsetTop-SW_SCROLL_STEP;
		if (w.content.offsetTop+w.content.offsetHeight<0)
			w.content.style.top=w.container.offsetHeight;
		working=true;
	}

	if (working) window.setTimeout(SWScroll,SW_TIMER_INTERVAL);
	else SWTimerSet=false;
}

function SWonmouseover(container) {
	if (!SW_inited || (w=SWFindWidget(container))==null) return;
	w.scrolling=false;
}

function SWonmouseout(container) {
	if (!SW_inited || (w=SWFindWidget(container))==null) return;
	w.scrolling=(w.content.offsetHeight>w.container.offsetHeight);

	if (w.scrolling && !SWTimerSet) {
		SWTimerSet=true;
		window.setTimeout(SWScroll,SW_TIMER_INTERVAL);
	}
}

// Scrolling Widget
///////////////////////////////////////////////////////////////////





///////////////////////////////////////////////////////////////////
// AJAX
// based on the code at http://developer.apple.com/internet/webcontent/xmlhttpreq.html

var XMLReq=false;
var XMLReqCallbackFunc=null;
var XMLReqCallbackData=null;
var XMLReqQueue=new Array();

function XMLReqQueueNode(url,func,data) {
	this.url=url;
	this.func=func;
	this.data=data;
}

function XMLReqCallback() {
	try {
		if (!XMLReq) {	// XMLHttpRequest not supported by browser
			XMLReqCallbackFunc(null,XMLReqCallbackData);
		} else {
			_XMLReq=XMLReq;
			if (XMLReq.readyState==4) XMLReq=false;
			XMLReqCallbackFunc(_XMLReq,XMLReqCallbackData);
		}
	} catch(err) {
	}

	// process requests in queue
	if (!XMLReq && XMLReqQueue.length>0) {
		node=XMLReqQueue.pop();
		LoadXMLDoc(node.url,node.func,node.data);
	}
}


// method = GET, POST
function AJAXRequest(method,url,POSTparam,callbackFunction,callbackData) {
	if (XMLReq) {	// processing another request, queue this one
		XMLReqQueue.push(new XMLReqQueueNode(url,callbackFunction,callbackData));
		return;
	}

	if(window.XMLHttpRequest) {	// branch for native XMLHttpRequest object
		try {
			XMLReq=new XMLHttpRequest();
		} catch(e) {
			XMLReq=false;
		}
	} else if(window.ActiveXObject) {	// branch for IE/Windows ActiveX version
	   	try {
			XMLReq=new ActiveXObject("Msxml2.XMLHTTP");
	  	} catch(e) {
			try {
		  		XMLReq=new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
		  		XMLReq=false;
			}
		}
	}

	if(XMLReq) {
		XMLReqCallbackFunc=callbackFunction;
		XMLReqCallbackData=callbackData;
		XMLReq.onreadystatechange=XMLReqCallback;
		XMLReq.open(method,url,true);
		if (method=="POST") {
			XMLReq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//			XMLReq.setRequestHeader("Content-length",POSTparam.length);
//			XMLReq.setRequestHeader("Connection","close");
			XMLReq.send(POSTparam);
		} else if (method=="GET") {
			XMLReq.send("");
		}
	} else XMLReqCallback();
}

function LoadXMLDoc(url,callbackFunction,callbackData) {
	AJAXRequest("GET",url,null,callbackFunction,callbackData);
}


// AJAX
///////////////////////////////////////////////////////////////////





///////////////////////////////////////////////////////////////////
// Quick search

var QS_oldonload=null;
var QuickSearchChooser=null;
var QuickSearchChooser_width=150;
var QuickSearchResult=null;
var QuickSearchInput=null;
var QuickSearchInput_oldonkeyup=null;


function QS_Show() {
	if (QuickSearchChooser.style.display=='block') return;
	QuickSearchChooser.style.top=findPosY(QuickSearchInput)+QuickSearchInput.clientHeight+2;
	QuickSearchChooser.style.left=findPosX(QuickSearchInput)+QuickSearchInput.clientWidth-QuickSearchChooser_width;
	QuickSearchChooser.style.width=QuickSearchChooser_width;
	QuickSearchChooser.style.display='block';
}

function QS_Hide() {
	if (QuickSearchChooser.style.display=='none') return;
	QuickSearchChooser.style.display='none';
}

function QS_QuickResult_callback(req,data) {
	var HTML='';
	if (!req || (req.readyState==4 && req.status!=200)) HTML="Lỗi!";
	else if (req.readyState==4 && req.status==200)
		HTML=req.responseXML.getElementsByTagName('content').item(0).childNodes.item(0).nodeValue;

	if (HTML!='') QuickSearchResult.innerHTML='<hr size=1>'+HTML;
}

function QS_QuickResult(core,param,page) {
	QuickSearchResult.innerHTML='<hr size=1><img src="image/icon_wait.gif" alt="" /> Đang tìm...';
	LoadXMLDoc('qsearch_'+core+'.xml.php?Field='+param+'&Value='+encodeURIComponent(QuickSearchInput.value)+'&Page='+page,QS_QuickResult_callback,0);
}
function QS_SearchResult(core,param) {
	window.location='search'+core+'.php?'+param+'='+encodeURIComponent(QuickSearchInput.value);
}
function QS_UseGoogle() {
	window.location='http://www.google.com/custom?domains=www.thivien.net&q='+encodeURIComponent(QuickSearchInput.value)+
					'&sa=Search&sitesearch=www.thivien.net&client=pub-7606866580787718&forid=1&ie=UTF-8&oe=UTF-8&cof=GALT%3A%23008000%3BGL%3A1%3BDIV%3A%23336699%3BVLC%3A663399%3BAH%3Acenter%3BBGC%3AFFFFFF%3BLBGC%3A336699%3BALC%3A0000FF%3BLC%3A0000FF%3BT%3A000000%3BGFNT%3A0000FF%3BGIMP%3A0000FF%3BFORID%3A1%3B&hl=en';
}

function QS_onkeyup() {
	if (QuickSearchInput_oldonkeyup!=null) QuickSearchInput_oldonkeyup();

	QuickSearchResult.innerHTML='<hr size=1><b>Chú ý:</b> gõ đúng chữ hoa/thường với các ký tự có dấu trong tiếng Việt!';

	if (QuickSearchInput.value=='') QS_Hide();
	else QS_Show();
}

function QS_onload() {
	if (QS_oldonload!=null) QS_oldonload();

	QuickSearchChooser=document.getElementById('QuickSearchChooser');
	QuickSearchResult=document.getElementById('QuickSearchResult');
	QuickSearchInput=document.getElementById('QuickSearchInput');
	if (QuickSearchInput!=null) {
		QuickSearchInput_oldonkeyup=QuickSearchInput.onkeyup;
		QuickSearchInput.onkeyup=QS_onkeyup;
	}
}

QS_oldonload=window.onload;
window.onload=QS_onload;



// Quick search
///////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////
// Poem Vote

function VotePoemCallback(req,Poem) {
	var HTML='';
	if (!req || req.status!=200) HTML="Lỗi!";
	else if (req.readyState==4 && req.status==200) {
		HTML=req.responseXML.getElementsByTagName('content').item(0).childNodes.item(0).nodeValue;
	}

	if (HTML!='') {
		obj=document.getElementById("PoemVoteInfo"+Poem);
		if (obj) obj.innerHTML=HTML;
	}
	return true;
}

function VotePoem(Poem,Score) {
	obj=document.getElementById("PoemVoteInfo"+Poem);
	if (obj) obj.innerHTML='<img src="image/icon_wait.gif" alt="" /> Đợi...';
	LoadXMLDoc('votepoem.xml.php?ID='+Poem+'&Score='+Score,VotePoemCallback,Poem);
}

function VotePoemNotLoggedIn() {
	alert("Bạn cần đăng nhập để tham gia bầu chọn!");
}

// Poem Vote
///////////////////////////////////////////////////////////////////




///////////////////////////////////////////////////////////////////
// Show All Poem

function ShowAllPoemCallback(req,Poem) {
	var HTML='';
	if (!req || req.status!=200) HTML="Lỗi!";
	else if (req.readyState==4 && req.status==200) {
		HTML=req.responseXML.getElementsByTagName('content').item(0).childNodes.item(0).nodeValue;
	}

	if (HTML!='') {
		obj=document.getElementById("PoemBody"+Poem);
		if (obj) obj.innerHTML=HTML;
	}
	return true;
}

function ShowAllPoem(Poem) {
	obj=document.getElementById("ShowAllPoemLink"+Poem);
	if (obj) obj.innerHTML='<img src="image/icon_wait.gif" alt="" /> Đợi...';
	LoadXMLDoc('showallpoem.xml.php?ID='+Poem,ShowAllPoemCallback,Poem);
}

// Show All Poem
///////////////////////////////////////////////////////////////////




///////////////////////////////////////////////////////////////////
// Send Thanks

function SendThanks_callback(req,data) {
	result=document.getElementById("ThanksLink_"+data.Type+"_"+data.ID);
	if (result==null) return;
	if (!req || (req.readyState==4 && req.status!=200)) {
		result.innerHTML='&nbsp;&nbsp;&nbsp;<a href="javascript:SendThanks('+data.Type+','+data.ID+')"><img border="0" alt="x" title="Cảm ơn" src="image/icon_thanks.gif" /> Cảm ơn</a>';
		alert('Lỗi, cảm ơn chưa được gửi!');
	} else if (req.readyState==4 && req.status==200) {
		msg=req.responseXML.getElementsByTagName('content').item(0).childNodes.item(0).nodeValue;
		if (msg=='OK') {
			result.innerHTML='&nbsp;&nbsp;&nbsp;<img border="0" alt="x" title="Cảm ơn" src="image/icon_thanks.gif" /> Đã cảm ơn';
//			result.style.display="none";
		} else {
			result.innerHTML='&nbsp;&nbsp;&nbsp;<a href="javascript:SendThanks('+data.Type+','+data.ID+')"><img border="0" alt="x" title="Cảm ơn" src="image/icon_thanks.gif" /> Cảm ơn</a>';
			alert('Lỗi, cảm ơn chưa được gửi!');
		}
	}
}
function SendThanks(Type,ID) {
	result=document.getElementById("ThanksLink_"+Type+"_"+ID);
	result.innerHTML='<img src="image/icon_wait.gif" alt="" /> Đợi...';
	data=new Object();
	data.Type=Type;
	data.ID=ID;
	LoadXMLDoc("thanks.xml.php?Type="+Type+"&Target="+ID,SendThanks_callback,data);
}

// Send Thanks
///////////////////////////////////////////////////////////////////
