/*
 * OnOffMix Widget plugin v1.0.0
 * 
 * Filename		: OnOffMix.js
 * Last updated	: 2008-06-17
 * Programmer	: dino/onoffmix.com
 *
 * COPYRIGHT 2008 (C) ONOFFMIX.COM, ALL RIGHTS RESERVED.
 *
 */


function __onoffMix(oom1, oom2, limit) {
	// 한번에 표시될 자료의 갯수
	this.limit = limit;

	// 현재 출력되는 자료의 위치
	var oomPos = 0;
	this.oomPos = 0;

	// Type B 의 경우 사용자 아이디
	var oomUser = "";

	// OnOffMix.COM 에서 가져온 데이터 수
	var oomTotal = 0;

	// 기본 XML 호출 주소
	var getURL = "http://www.onoffmix.com/api.aspx";

	// 데이터 호출 방식에 따라서 URL을 설정하는 부분
	this.setURL = function ( oom1, oom2 ) {
		getURL = "http://www.onoffmix.com/api.aspx?ing=Y";
		switch ( oom1 ) {
		/* For Type A */
		case 1: default:
			if ( oom2 )
				getURL += "&category=" + oom2;
			break;
		/* For Type B */
		case 2:
			if ( oom2 ) {
				getURL += "&userid=" + oom2;
				oomUser = oom2;
			}
			else
				oom1 = 1;
			break;
		}
		this.oom1 = oom1;
		this.oom2 = oom2;
		this.getURL = getURL;
	}

	// 시작시 사용될 기본 URL 설정
	this.setURL(oom1,oom2);


	// 다음 자료 검색
	this.prev = function () {
		if ( oomPos <= 0 ) {
			alert("더 이상 이전 자료가 없습니다.");
			return;
		}
		this.setPosition(oomPos-this.limit);
	}

	// 이전 자료 검색
	this.next = function () {
		if ( (oomPos+this.limit) >= oomTotal ) {
			alert("더 이상 다음 자료가 없습니다.");
			return;
		}
		this.setPosition(oomPos+this.limit);
	}

	// 자료가 출력된 위치를 설정
	this.setPosition = function ( nPosition ) {
		this.oomPos = nPosition;
		oomPos = nPosition;
		this.setURL(this.oom1,this.oom2);
		this.get();
	}

	// 출력될 카테고리를 설정
	this.setCategory = function ( nCategory ) {
		this.oom2 = nCategory;
		oom2 = nCategory;
		this.setURL(1,nCategory);
		this.get();
	}

	// 데이터를 가져오고 출력하는 부분
	this.get = function() {
		var REQ = new newXMLHttpRequest();

		// 데이터를 출력하는 부분
		REQ.onreadystatechange = function() {
			if(REQ.readyState == 4) {
				if(REQ.status == 200) {

					var item = REQ.responseXML.getElementsByTagName("event");

					// 만약 가져온 행사 내용이 없다면 안내 메세지를 출력한다.
					if ( !item.length || item.length == 0 )
					{
						switch ( oom1 )
						{
						case 1: default:
							_contents = "<p style=\"margin-left:10px;\"><a href=\"http://www.onoffmix.com/\" target=\"_blank\">현재 진행 중인 행사가 없습니다. <br />온오프믹스에서 새로운 행사를 개설해 보세요!</a></p>";
							break;
						case 2:
							_contents = "<p style=\"margin-left:10px;\"><a href=\"http://www.onoffmix.com/\" target=\"_blank\">참여하는 내용이 없습니다. <br />온오프믹스에서 다양한 행사에 참여하세요!</a></p>";
							break;
						}
						document.getElementById("onoffMixList").innerHTML = _contents;
						return;
					}

					// 가져온 데이터의 전체 수를 설정
					var cnt = item.length;
					oomTotal = cnt; 
					// 한페이지에 보여줄 갯수
					var climit = limit;
					// 페이지 수 계산
					var pages = Math.ceil(cnt / climit);

					// 데이터 출력
					for(var i = 0, _contents = ""; i+oomPos < cnt; i++) {
						if ( climit && i >= climit ) break; // 한페이지 표시 수를 넘어가면 중단
						p = oomPos + i;

						// 이벤트 ID 가져옴. 없을 경우 표시안함
						try {
							var eventid = item[p].getElementsByTagName("eventid")[0].firstChild.nodeValue;
							if(!eventid) { cnt++; climit++; continue; }
						} catch(e) { cnt++; climit++; continue; }

						// 등록자
						try {
							var owner = item[p].getElementsByTagName("owner")[0].firstChild.nodeValue;
						} catch(e) { var owner = ""; }

						// 카테고리
						try {
							var category = item[p].getElementsByTagName("category")[0].firstChild.nodeValue;
						} catch(e) { var category = ""; }

						// 제목을 가져옴 없을 경우 표시안함
						try {
							var subject = item[p].getElementsByTagName("subject")[0].firstChild.nodeValue;
							if(subject.trim() == "") {
								subject = item[p].getElementsByTagName("subject")[0].textContent;
							}
							subject = subject.trim().replace('"', '&quot;').replace(/<.*>/g, '');
							if(!subject) { cnt++; climit++; continue; }
						} catch(e) { cnt++; climit++; continue; }

						// 장소
						try {
							var place = item[p].getElementsByTagName("place")[0].firstChild.nodeValue;
						} catch(e) { var place = ""; }

						// 날짜와 시간
						try {
							var date = item[p].getElementsByTagName("date")[0].firstChild.nodeValue;
							var fulldate = date;
							date = date.replace(/[0-9]+[년 ]+/g,"");
							date = date.replace(/[0-9]+[시]+/g,"");
							date = date.replace(/[0-9]+[분]+/g,"");
							date = date.replace(/[\s ]+/g,"");
							date = date.replace(/[0]([0-9])/g,"$1");
							if ( date.indexOf("~") > 0 ) {

							} else {

							}
							date = date.replace(/[~\s ]+$/,"");
						} catch(e) { var date = ""; }

						// 정원 신청인원 대기인원
						try {
							var quota = item[p].getElementsByTagName("quota")[0].firstChild.nodeValue;
							quota = quota.replace(/[ ]+/,"");
							quota = quota.replace(/총|대기|참석|명/g,"");
							quotaArr = quota.split(",");
							quotaTotal = quotaArr[0] *1;
							quotaApp = quotaArr[1] *1;
							quotaWait = quotaArr[2] *1;
						} catch(e) {
							var quota = "";
							quotaTotal = 0;
							quotaApp = 0;
							quotaWait = 0;
						}

						// 행사 종료 여부
						try {
							var closing = item[p].getElementsByTagName("closing")[0].firstChild.nodeValue;
						} catch(e) { var closing = ""; }

						// 이벤트 링크 주소
						try {
							var url = item[p].getElementsByTagName("url")[0].firstChild.nodeValue;
						} catch(e) { var url = ""; }


						// Type B 출력
						if ( oom1 == 2 ) {
							_contents += "			<ul class=\"wgBodr";
							if ( p == oomPos )
								_contents += "1st";
							_contents += "\" style=\"margin-top:6px\">";
							_contents += "				<li><a href=\""+url+"\" onclick=\"window.open(this.href); return false;\" class=\"";

							if ( oomUser == owner ) // 자신이 등록한 행사
								_contents += "wgLkred";
							else if ( owner == "tistory" ) // 티스토리 등록 행사
								_contents += "wgLk3";
							else // 그외 행사
								_contents += "wgLkblu";
							_contents += "\" id=\"oomSubject"+i+"\" title=\""+subject+"\">"+subject+"</a></li>";
							_contents += "				<li>";
							// 정원이 다 차면 마감으로 표시
							if ( quotaTotal != 0 && quotaTotal == quotaApp ) {
								_contents += "<img src=\"" +  pluginURL + "/images/b_end.gif\" align=\"absmiddle\" alt=\"마감\" /> ";
							}
							_contents += "<span class=\"wgFt66\">"+date+"</span><span class=\"wgFtplac2\">|</span><span class=\"wgFtplac\" id=\"oomPlace"+i+"\" title=\""+place+"\">"+place+"</span></li>";
							_contents += "<li class=\"wgFt4e\">총<strong>"+quotaTotal+"</strong>명 : 참석<strong>"+quotaApp+"</strong>명, 대기<strong>"+quotaWait+"</strong>명</li>";


							// 끝까지 표시했을 경우 네비게이션을 출력
							if ( pages > 1 && ( (i+1) >= climit || (p+1) == cnt ) )
								_contents += "<li><a href=\"JavaScript:;\" onClick=\"oomWidget.next();\" class=\"wgBtn wgr\" title=\"다음\"><span>[다음]</span></a><a href=\"JavaScript:;\" onClick=\"oomWidget.prev();\" class=\"wgBtn wgl\" title=\"이전\"><span>[이전]</span></a></li>";

							_contents += "			</ul>";
						
						// Type A 출력
						} else {
							_contents += "			<ul class=\"wgBodr";
							if ( p == oomPos )
								_contents += "1st";
							_contents += "\" style=\"margin-top:6px\">";
							_contents += "				<li><a href=\""+url+"\" onclick=\"window.open(this.href); return false;\" id=\"oomSubject"+i+"\" title=\""+subject+"\">"+subject+"</a></li>";
							_contents += "				<li>";
							// 정원이 다 차면 마감으로 표시
							if ( quotaTotal != 0 && quotaTotal == quotaApp ) {
								_contents += "<img src=\"" +  pluginURL + "/images/b_end.gif\" align=\"absmiddle\" alt=\"마감\" /> ";
							}
							_contents += "<span class=\"wgFtday\" title='"+fulldate+"'>"+date+"</span><span class=\"wgFtplac\">|</span><span class=\"wgFtplac\" id=\"oomPlace"+i+"\" title=\""+place+"\">"+place+"</span></li>";
							_contents += "<li class=\"wgFt4e\">총<strong>"+quotaTotal+"</strong>명 : 참석<strong>"+quotaApp+"</strong>명, 대기<strong>"+quotaWait+"</strong>명</li>";

							// 끝까지 표시했을 경우 네비게이션을 출력
							if ( pages > 1 && ( (i+1) >= climit || (p+1) == cnt ) )
								_contents += "<li><a href=\"JavaScript:;\" onClick=\"oomWidget.next();\" class=\"wgBtn wgr\" title=\"다음\"><span>[다음]</span></a><a href=\"JavaScript:;\" onClick=\"oomWidget.prev();\" class=\"wgBtn wgl\" title=\"이전\"><span>[이전]</span></a></li>";

							_contents += "			</ul>";
						}

					}
					document.getElementById("onoffMixList").innerHTML = _contents;

					// 장소는 1줄, 제목은 2줄로 자름
					for ( j = 0; j < i ; j++ )
					{
						if ( window.ActiveXObject ) {
							objPlace = document.all["oomPlace"+j];
							objSubject = document.all["oomSubject"+j];
						} else { 
							objPlace = document.getElementById("oomPlace"+j);
							objSubject = document.getElementById("oomSubject"+j);
						}
						oomStrCut(objPlace,24);
						oomStrCut(objSubject,24);
					}

				} else {
					alert(REQ.statusText);
				}
			}

		};

		// 외부 데이터를 가져오는 부분
		REQ.open("GET", "/plugins/OnOffMix/OnOffMix.php?url=" + escape(this.getURL), true);
		REQ.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		REQ.send(null);
	}
}

// 문자열을 줄단위로 자르는 함수
// String oomStrCut ( String oomObjText, Int oomHeight )
function oomStrCut (oomObjText,oomHeight)
{
	text = oomObjText.innerHTML;
	while( oomObjText.scrollHeight > oomHeight  ) // 원하는 픽셀 안으로 맞춰지는지 확인
	{
		text = text.substring( 0, text.length - 1 );
		oomObjText.innerHTML = text + ".."; // 값을 수정한다.
	}
}

// XMLHTTPREQUEST 호출 함수
function newXMLHttpRequest() {
	var xmlReq = false;

	if(window.XMLHttpRequest) {
		xmlReq = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		try {
			xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e1) {
			try {
				xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e2) {
			}
		}
	}

	return xmlReq;
}

function addEvent(obj, event, listener) {
	try	{
		obj.addEventListener(event, listener, false);
	} catch(e) {
		try {
			obj.attachEvent("on"+event, listener);
		} catch(e) { }
	}
}

// 앞뒤 공백을 제거하는 함수
String.prototype.trim = function () {
	return this.replace(/^\s*/g, "").replace(/\s*$/g, "");
}
