/* AMS_BANNER : 검색 입력상자 광고용  */
var userAgent = navigator.userAgent.toLowerCase();
var	browser = {
version: (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
safari: /webkit/.test(userAgent),
opera: /opera/.test(userAgent),
msie: /msie/.test(userAgent) && !/opera/.test(userAgent),
mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)
};	
var os ={
isXP : /nt 5.1/.test(userAgent),
isVista : /nt 6.0/.test(userAgent)	
}

/* GNB 검색 */
var gnbSearch = {
	config: {
		input: 'q',
		option: 'svctype',
		action: {
			a0: '/search/Top.do',
			a1: '/search/Tvpot.do',
			a4: '/search/Playlist.do',
			a3: '/search/Video.do',
			a5: '/search/Mypot.do'
		}
	},
	// input background(ad.) clear
	clearBg: function(bForce, f) {
		var config=gnbSearch.config;
		if (!f || !f[config.input]) return false;
		var q = f[config.input];
	    if (bForce || q.value != "") { q.style.backgroundImage=''; }
	},
	// input field validation
	isValidate: function(f) {
		var config=gnbSearch.config;
		if (!f || !f[config.input]) return false;
		return f[config.input].value.replaceAll2(' ','') !== '';
	},
	// tvpot search
	searchTvpot: function(f) {
		var config=gnbSearch.config;
		if (!f || !f[config.input] || !f[config.option]) return false;
		var q = f[config.input];
		if (!gnbSearch.isValidate(f)) {
			if (q.style.backgroundImage == '') {
				alert('검색어를 입력해주세요.');
				q.focus();
			} else {
	    		AmsLink2();
        	}
        	return false;
        }
        f.action=config.action['a'+f.svctype.value];
        f.target='_self';
		return true;
	},
	// daum search
	searchDaum: function(f) {
		var config=gnbSearch.config;
		if (!f || !f[config.input] || !f[config.option]) return false;
		var q = f[config.input];
		if (!gnbSearch.isValidate(f)) {
			alert('검색어를 입력해주세요.');
			q.focus();
        	return false;
        }
        f.action='/search/SearchDaum.do?nil_profile=tvpot&nil_ch=sskey';
        f.target='_blank';
        f.submit();
	}
};

function search_clearbg(bForce ) {
    var q = document.top_search.q;
    var qs = q.style;
    if ( bForce || q.value != "" )
	    qs.backgroundImage = '';
}

// 랭킹 사용: 삭제

// pop
	function openPopup(url,id,w,h) {
		window.open(url,id,'toolbar=no,scrollbars=no,top=10,left=10,width='+w+',height='+h+'');
	}
// my
	function showTab() {
		var tabLayer = document.getElementById('mytabList');
		tabLayer.style.display="block"
	}
	function hideTab() {
		var tabLayer = document.getElementById('mytabList');
		tabLayer.style.display="none"
	}
//page
	function daum_paging_rollover(obj, img, type) {
		var imgurl = "http://image.daum-img.net/hanmail/2006_ui/";
		var tmp
		if (type == "on") {
			obj.src = imgurl + img + "_over.gif";
		} else {
			obj.src = imgurl + img + ".gif";
		}
	}
	function pdgo(page,totalpage){
		var page = document.getElementById("list_"+page);
		for (var i=1;i<=totalpage;i++){
			document.getElementById("list_"+i).style.display="none";
		}
		page.style.display="block";
	}
// channel
	function show(e) {
		if (! e) e = window.event ;		
		var pntX = e.pageX ? e.pageX : document.documentElement.scrollLeft + e.clientX - document.body.clientLeft;
		var pntY = e.pageY ? e.pageY : document.documentElement.scrollTop + e.clientY - document.body.clientTop-1;
		pntX = pntX-120;
		pntY = pntY+5;
		document.getElementById('chMoreArea').style.display = "block" ;
		document.getElementById('chMoreArea').style.left = pntX + "px";
		document.getElementById('chMoreArea').style.top = pntY + "px";

	}
	function init_channel() {
		document.getElementById('showMore').onclick = show;
	}
	function hide() {
		document.getElementById('chMoreArea').style.display = "none" ;
	}
	function chGo(type){
		document.location.href="/clip/ClipList.do?cateId="+type;
	}

//search
	var s_state = true;
	function valueInit(){
		if(s_state == true) {
			document.getElementById("searchValue").value="";
			s_state = false;
		}
	}
	
//clipid url
	function openClip(clipid,lu) {
		document.locationForm.action = "/clip/ClipView.do";
		document.locationForm.clipid.value = clipid;
		document.locationForm.lu.value = lu;
		document.locationForm.submit();
	}	
	
//sourceid url
	function openSource(sourceid,lu) {
		document.locationForm.action = "/source/Top.do";
		document.locationForm.srcId.value = sourceid;
		document.locationForm.lu.value = lu;
		document.locationForm.submit();
	}	
		
//common
	function AmsLink() { return false; }
	function AmsLink2() { return false; }
	
	String.prototype.replaceAll2 = function(findstring, newstring){  
	   return this.replace(new RegExp(findstring, "gi"), newstring);
	}
	function goSearchKnowhow(f)	{
		var q=f.q.value;
		var temp = q.replaceAll2(" ","");
		if (temp=="") q="";
 		if(q=="" && f.q.style.backgroundImage == '' ){
			alert('검색어를 입력해주세요.');
			f.q.value= "";
			f.q.focus();
			return false;
		}		
		var localSearch="http://tvpot.daum.net/search/SearchPot.do?q="+q;		
	    if (q == '' &&  f.q.style.backgroundImage != '' ){
        	AmsLink();
        	return false;
        }
		f.action = localSearch;
		return ;
	}
	
// TODO 가능하면 합쳐보자
function swf(src,w,h){
	html = '';
	html += '<object type="application/x-shockwave-flash" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" id="param" width="'+w+'" height="'+h+'">';
	html += '<param name="movie" value="'+src+'">';
	html += '<param name="quality" value="high">';
	html += '<param name="allowScriptAccess" value="always">';
	html += '<param name="bgcolor" value="#ffffff">';
	html += '<param name="wmode" value="transparent">';
	html += '<param name="menu" value="true">';
	html += '<param name="swliveconnect" value="true">';
	html += '<embed src="'+src+'" wmode=transparent quality=high menu="false" allowScriptAccess="always" width="'+w+'" height="'+h+'" swliveconnect="true" id="param" name="param" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"><\/embed>';
	html += '<\/object>';
	document.write(html);
}	
 
function swf_(src,w,h){
	html = '';
	if(browser.msie){
		html += '<object  id="'+arguments[3]+'" name="'+arguments[3]+'" type="application/x-shockwave-flash" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'+w+'" height="'+h+'">';
		html += '<param name="movie" value="'+src+'">';
		html += '<param name="quality" value="high">';
		html += '<param name="allowScriptAccess" value="always">';
		html += '<param name="bgcolor" value="#ffffff">';
		html += '<param name="menu" value="true">';
		html += '<param name="swliveconnect" value="true">';
		for(var p in arguments[4]){
		html += '<param name="'+p+'" value="'+arguments[4][p]+'">';
		}		
		html += '<\/object>';
	}
	else{
		html += '<embed';
		html += ' id="'+arguments[3]+'" name="'+arguments[3]+'" src="'+src+'"  quality="high" menu="false" allowScriptAccess="always" width="'+w+'" height="'+h+'" swliveconnect="true"  type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"';
		for(var p in arguments[4]){
		html += ' '+p+'="'+arguments[4][p]+'" ';
		}			
		html += '><\/embed>';
	}
	document.write(html);
}  
function swfElection(src,w,h,depth1,depth2 ){
	html = '';
	html += '<object type="application/x-shockwave-flash" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" id="param" width="'+w+'" height="'+h+'">';
	html += '<param name="movie" value="'+src+'">';
	html += '<param name="quality" value="high">';
	html += '<param name="allowScriptAccess" value="always">';
	html += '<param name="bgcolor" value="#ffffff">';
	html += '<param name="wmode" value="transparent">';
	html += '<param name="menu" value="true">';
	html += '<param name="swliveconnect" value="true">';
	html += '<param name="FlashVars" value="depth1='+depth1+'&depth2='+depth2+'">';
	html += '<embed src="'+src+'" FlashVars="depth1=3&depth2=1" wmode=transparent quality=high menu="false" width="'+w+'" height="'+h+'" swliveconnect="true" id="param" name="param" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"><\/embed>';
	html += '<\/object>';
	document.write(html);
}	


//TODO 합치자~~~

//채널서브페이지 상단박스  명근님...
var thumb ={
	EXid : 1,
	over : function(id,img,url){
				var EXnumberObj=document.getElementById('num'+thumb.EXid)	
				var EXlistObj=document.getElementById('list_'+thumb.EXid)						 
				EXlistObj.className="noBG";
				EXnumberObj.className="num"+thumb.EXid+" "+"num"+thumb.EXid+"off";				
				
				var imgObj=document.getElementById('thumbImg')						
				var listObj=document.getElementById('list_'+id)						
				var numberObj=document.getElementById('num'+id)	
				imgObj.src=img;
				imgObj.onclick=function(){location.href=url;}
				listObj.className="BG";
				numberObj.className="num"+id+" "+"num"+id+"on";
			},
	out : function(id){
				thumb.EXid=id;
			}
}
//채널서브페이지 상단박스2  준성님...
var thumb2 ={
	EXid : 1,
	over : function(id, img, url){

				var EXnumberObj=document.getElementById('num'+this.EXid)
				var EXlistObj=document.getElementById('list_'+this.EXid)
				if (this.EXid!=1)
				{
					EXlistObj.className="noBG";
				}else{
					EXlistObj.className="noBG li1";
				}										 
				EXnumberObj.className="num"+thumb.EXid+" "+"num"+this.EXid+"off";				

				var imgObj=document.getElementById('thumbImg');
				imgObj.src=img;
				imgObj.onclick=function(){location.href=url;}
				
				var listObj=document.getElementById('list_'+id)						
				var numberObj=document.getElementById('num'+id)		
				if (id!=1)
				{
					listObj.className="BG";
				}else{
					listObj.className="BG li1";
				}		
				numberObj.className="num"+id+" "+ "num"+id+"on";
			},
	out : function(id){
		this.EXid=id;
	}
}

// 채널today 전광판  -> 텍스트 링크 롤링 -> 
// TODO 공통 모듈로 빼보
var channelToday ={
	list : null,
  	pointer: 1,
	contents: null,
	set  : function(){
					 this.list = document.getElementById('today').getElementsByTagName("div");
					 this.contents= new Array();
					 for(var i=0;i<this.list.length;i++){				 
 						 this.contents[i]=document.getElementById(this.list[i].id).innerHTML;
		}					
	},	
	change: function() {
	document.getElementById('today').innerHTML= this.contents[this.pointer];
	this.pointer = this.pointer==(this.contents.length-1)?0:this.pointer+1; 

	}
}

// prototype AJAX call
function getAjaxData(url,pars,func){ 
    var myAjax = new Ajax.Request(
        url,
        {
            method: 'get', 
            parameters: pars, 
            onComplete: eval(func)
        });
}

// 오른쪽 날개 탭(tv팟, 노하우팟, 비디오팟 전환)
var rightLiveList ={
	list : null,
  	pointer: 1,
	contents: null,
	set  : function(){
		this.list = document.getElementById('rightLiveList').getElementsByTagName("span");
		this.contents= new Array();
		for(var i=0;i<this.list.length;i++){				 
 			this.contents[i]=document.getElementById(this.list[i].id).innerHTML;
 		}					
	},
	change: function() {
	document.getElementById('rightLiveList').innerHTML= "<span>"+this.contents[this.pointer]+"</span>";
	this.pointer = this.pointer==(this.contents.length-1)?0:this.pointer+1; 
	}
}
function changeRightPotList(pclass,  menu ){
	 var deselectedMenu=(menu % 2)+1;
	 var layerList= new Array();
	 if(pclass=="tvpot"){
	  layerList[1]= "rightKnowhowpotList"; 
	  layerList[2]= "rightVideopotList";	
	 }
	 else if(pclass=="knowhowpot"){
	 
	  layerList[1]= "rightTvpotList"; 
	  layerList[2]= "rightVideopotList";		 
	 } 
	 else if(pclass=="videopot"){
	 
	  layerList[1]= "rightTvpotList"; 
	  layerList[2]= "rightKnowhowpotList";		 
	 } 	 
	 document.getElementById(pclass+"Menu"+menu).className=pclass+"Menu"+menu+"On" 
	 document.getElementById(pclass+"Menu"+deselectedMenu).className=pclass+"Menu"+deselectedMenu+"Off" 
	 document.getElementById(layerList[menu]).style.display="block";
	 document.getElementById(layerList[deselectedMenu]).style.display="none";
} 

// 전광판, 오디션, 등등등에서 마니 사용됨... 
// TODO 공통모듈로 뺄수 있게...
var broadcast = {
	wrapperId:' ',
	list: null,
	contents: null,
	flag: true,
	delayingTime: 2500,
	activated: false,
	externalFunction:	null,
	create: function (wrapperId,delayingTime,externalFunction){
		this.wrapperId=wrapperId;
		this.delayingTime=delayingTime;
		this.externalFunction=externalFunction;
		this.activate();setInterval("broadcast.activate()",this.delayingTime);},
	changePosition: function changePosition(obj,p){
		$(obj).setStyle({top: -1 * p + 'px'});
	},
	activate: function (){	
		if(!this.flag){return false;}
		var changeRange = $R(1, 24, false);
		var obj=$(this.wrapperId);
		var intervalTime=""

		this.list = obj.immediateDescendants();
		var tmp = this.list.shift();
		
		this.list.push(tmp);
		this.contents="";
		obj.appendChild(tmp);
					 
		for(var i=0;i<this.list.length;i++) {				 
	 		this.contents += '<div>'+$(this.list[i]).innerHTML+'</div>';
		}	
		
		obj.hide();
		obj.update(this.contents)
		obj.style.top='0px';	
		obj.show();

		changeRange.each(
			function(value,index){
				intervalTime=20*value;
				setTimeout("broadcast.changePosition('"+obj.id+"','"+value+"')",intervalTime);
			} 
		) 		
	} 
}

/* 툴팁 박스 -> 공통사용
 * TODO 개선 사항은 : 스타일을 class로 빼기, 태그 처리 어떻게 할지...
   by junsung park */
var bTooltip = 
{
	tip_id : "btooltip",
	makeLayer : function (str)
	{
		var tip_obj = document.getElementById(this.tip_id);
		if (tip_obj==undefined)
		{
			var tip = document.createElement("div");
			tip.id = this.tip_id;
			tip.style.backgroundColor= "#FFFFE1";
			tip.style.fontFamily= "돋움";
			tip.style.fontSize= "12px";
			tip.style.padding= "2px";
			tip.style.color= "#000";
			tip.style.border= "1px solid #000";
			tip.style.position= "absolute";
			tip.style.zIndex= "99999";
			tip.style.display= "none";
	 
			document.body.appendChild(tip);
			tip.appendChild(document.createTextNode(unescape(str)));
		}
	},
	moveLayer : function (e)
	{
		var xp = 0, yp = 0;
		if (document.all)
		{
			xp = event.clientX + document.documentElement.scrollLeft;
			yp = event.clientY + document.documentElement.scrollTop;
		}
		else
		{
			xp = e.pageX; 
			yp = e.pageY; 
		}
		xp += 10;
		yp += 10;
		var tip_obj = document.getElementById(this.tip_id);
		if (tip_obj!=undefined)
		{
			tip_obj.style.top = yp + "px";
			tip_obj.style.left = xp + "px";
			tip_obj.style.display= "block";
		}

	},
	hiddenLyaer : function (e)
	{
		var to = e?e.relatedTarget:event.toElement; 
		var to_id = null;		
		try
		{
			to_id = to.id;
		}
		catch (e)
		{
			to_id = null;
		}

		if (this.tip_id==to_id)
		return;

		if (document.all) 
		{
			try
			{
				document.getElementById(this.tip_id).removeNode(true);	
			}
			catch (e){}			
		}
		else
		{
			try
			{
				document.body.removeChild(document.getElementById(this.tip_id));
			}
			catch (e){}	
		}
	},
	on : function (tg)
	{
		var str = escape(tg.title);
		tg.title= "";
		bTooltip.makeLayer(str);
		tg.onmouseover = new Function("bTooltip.makeLayer('" + str + "')");
		tg.onmousemove = new Function("bTooltip.moveLayer(arguments[0])");
		tg.onmouseout = new Function("bTooltip.hiddenLyaer(arguments[0])");
	}
}
var domHelper = {
	// Add event handler
	addEvent : function(elm, evType, fn, useCapture, obj, override) {
		if (typeof elm == 'string') elm = document.getElementById(elm);
		var scope = elm;
		if (override) {
			if (override === true) scope = obj;
			else scope = override;
		}
		var wrappedFn = function(e) { return fn.call(scope, domHelper.getEvent(e), obj); };
		
		if (elm.addEventListener)
			elm.addEventListener(evType, wrappedFn, useCapture);
		else if (elm.attachEvent)
			elm.attachEvent('on' + evType, wrappedFn);
		else
			elm['on' + evType] = wrappedFn;
		return true;
	},
	removeEvent : function(elm, evType, fn) {
		
	},
	// getEvent
	getEvent: function(e, boundEl) {
		var ev = e || window.event;
		if (!ev) {
			var c = this.getEvent.caller;
			while (c) {
				ev = c.arguments[0];
				if (ev && Event == ev.constructor) break;
				c = c.caller;
			}
		}
		return ev;
	},
	// Get key
	getKey : function(e) {
		if (window.event)
			return window.event.keyCode;
		else if (e)
			return e.which;
		else
			return 0;
	},
	// Stop event propagation
	stopBubble : function(e) {
		if (window.event && window.event.cancelBubble) {
			window.event.cancelBubble = true;
		} 
		if (e && e.stopPropagation) {
			e.stopPropagation();
		}
	},
	
	// Prevent event default action
	stopDefault : function(e){
		if(window.event && window.event.returnValue){
			window.event.returnValue = false;
		} 
		if (e && e.preventDefault){
			e.preventDefault();
		}
	},
	
	// Stop event propagation + Prevent event default action
	cancelClick : function(e) {
		if (window.event) {
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
		if (e && e.stopPropagation && e.preventDefault) {
			e.stopPropagation();
			e.preventDefault();
		}
	},
	// Get event target
	getTarget : function(e) {
		var target = window.event ? window.event.srcElement : e ? e.target : null;
		if (!target) { return false; }
		while (target.nodeType != 1 && target.nodeName.toLowerCase() != 'body') {
			target = target.parentNode;
		}
		return target;
	},
	// Get related event target
	getRelatedTarget : function(e) {
		var target = window.event ? window.event.fromElement : e ? e.relatedTarget : null;
		if (!target) { return false; }
		/*
		while (target.nodeType != 1 && target.nodeName.toLowerCase() != 'body') {
			target = target.parentNode;
		}
		*/
		return target;
	},
	// Key related
	isPrintable : function(key) {
		return (key >= 32 && key < 127);
	},
	
	// Dom Element navigation method
	lastSibling:function(node) {
		var tempObj=node.parentNode.lastChild;
		while(tempObj.nodeType!=1 && tempObj.previousSibling!=null){
			tempObj=tempObj.previousSibling;
		}
		return (tempObj.nodeType==1)?tempObj:false;
	},
	firstSibling:function(node) {
		var tempObj=node.parentNode.firstChild;
		while(tempObj.nodeType!=1 && tempObj.nextSibling!=null){
			tempObj=tempObj.nextSibling;
		}
		return (tempObj.nodeType==1)?tempObj:false;
	},
	getText:function(node){
		if(!node.hasChildNodes()){return false;}
		var reg=/^\s+$/;
		var tempObj=node.firstChild;
		while(tempObj.nodeType!=3 && tempObj.nextSibling!=null || reg.test(tempObj.nodeValue)){
			tempObj=tempObj.nextSibling;
		}
		return tempObj.nodeType==3||tempObj.nodeType==4?tempObj.nodeValue:false;
	},
	setText:function(node,txt){
		if(!node.hasChildNodes()){return false;}
		var reg=/^\s+$/;
		var tempObj=node.firstChild;
		while(tempObj.nodeType!=3 && tempObj.nextSibling!=null || reg.test(tempObj.nodeValue)){
			tempObj=tempObj.nextSibling;
		}
		if(tempObj.nodeType==3){tempObj.nodeValue=txt}else{return false;}
	},
	createLink:function(to,txt){
		var tempObj=document.createElement('a');
		tempObj.appendChild(document.createTextNode(txt));
		tempObj.setAttribute('href',to);
		return tempObj;
	},
	createTextElm:function(elm,txt){
		var tempObj=document.createElement(elm);
		tempObj.appendChild(document.createTextNode(txt));
		return tempObj;
	},
	closestSibling:function(node,direction){
		var tempObj;
		if(direction==-1 && node.previousSibling!=null){
			tempObj=node.previousSibling;
			while(tempObj.nodeType!=1 && tempObj.previousSibling!=null){
				 tempObj=tempObj.previousSibling;
			}
		}else if(direction==1 && node.nextSibling!=null){
			tempObj=node.nextSibling;
			while(tempObj.nodeType!=1 && tempObj.nextSibling!=null){
				 tempObj=tempObj.nextSibling;
			}
		}
		return tempObj.nodeType==1?tempObj:false;
	},
	// class management
	cssjs:function(a,o,c1,c2) {
		switch (a){
			case 'swap':
				o.className=!domHelper.cssjs('check',o,c1)?o.className.replace(c2,c1):o.className.replace(c1,c2);
			break;
			case 'add':
				if(!domHelper.cssjs('check',o,c1)){o.className+=o.className?' '+c1:c1;}
			break;
			case 'remove':
				var rep=o.className.match(' '+c1)?' '+c1:c1;
				o.className=o.className.replace(rep,'');
			break;
			case 'check':
				var found=false;
				var temparray=o.className.split(' ');
				for(var i=0;i<temparray.length;i++){
					if(temparray[i]==c1){found=true;}
				}
				return found;
			break;
		}
	},
	// get computed style value and set style - from http://www.elektronaut.no/articles/2006/06/07/computed-styles require test!
	getComputedStyle : function(element,cssRule) {
		if (document.defaultView && document.defaultView.getComputedStyle) {
	    	var value = document.defaultView.getComputedStyle(element, '').getPropertyValue(
	    		cssRule.replace(/[A-Z]/g, function(c) { return "-" + c.toLowerCase(); }));
	  	} else if (element.currentStyle)
	  		var value = element.currentStyle[cssRule];
	  	else
	  		var value = false;
		return value;
	},
	setStyle : function(element,cssRule,value) {
  		element.style[cssRule] = value;
		return element;
	},
	getElementsByClassName : function(element, className, tag) {
		tag = tag ? tag.toUpperCase() : '*';
		if (element.getElementsByClassName) {
			var elms = element.getElementsByClassName(className);
			if (tag === '*') {
				return elms;
			} else {
				var res = [];
				for (var i=0; i < elms.length; i++) {
					if (elms[i].nodeName.toUpperCase() === tag) {
						res[res.length] = elms[i];
					}
				}
				return res;
			}
		} else {
			var elms = element.getElementsByTagName(tag);
			var nodes = [];
			for (var i = 0; i < elms.length; i++) {
				if (domHelper.cssjs('check', elms[i], className)) nodes[nodes.length] = elms[i];
			}
		}
		return nodes;
	},
	
	// set & get acitve titled stylesheet(LINK)
	setActiveTitledCss : function(t) {
		var ls=document.getElementsByTagName("link");
		for(var i=0;i<ls.length,l=ls[i];i++) {
			if (l.getAttribute("rel").indexOf("style")!=-1 && l.getAttribute("title")) {
				l.disabled = true;
				if (l.getAttribute("title")==t) l.disabled=false;
			}
		}
	},
	getActiveTitledCss : function() {
		var ls=document.getElementsByTagName("link"),t;
		for(var i=0;i<ls.length,l=ls[i];i++) {
			t=l.getAttribute("title");
			if (l.getAttribute("rel").indexOf("style")!=-1 && t && !l.disabled) return t;
		}
		return null;
	},
	getPreferredCss : function() {
		var ls=document.getElementsByTagName("link"),t;
		for (var i=0;i<ls.length,l=ls[i];i++) {
			t=l.getAttribute("title");
			if (l.getAttribute("rel").indexOf("style")!=-1 && l.getAttribute("rel").indexOf("alt")==-1 && t) return t;
		}
		return null;
	},
	// inheritance from yui
	extend : function(subc, superc, overrides) {
        if (!superc||!subc) return;
        var F = function() {};
        F.prototype=superc.prototype;
        subc.prototype=new F();
        subc.prototype.constructor=subc;
        subc.superclass=superc.prototype;
        if (superc.prototype.constructor == Object.prototype.constructor)
            superc.prototype.constructor=superc;
        if (overrides) {
            for (var i in overrides)
            	subc.prototype[i]=overrides[i];
        }
    },
    
    // get pageXOffset
    getPageXOffset : function() {
    	if (window.innerWidth) {
	    	return window.pageXOffset;
    	} else if (document.documentElement && document.documentElement.clientWidth) {
    		return document.documentElement.scrollLeft;
    	} else if (document.body.clientWidth) {
    		return document.body.scrollLeft;
    	}
    },
    // get pageYOffset
    getPageYOffset : function() {
    	if (window.innerWidth) {
	    	return window.pageYOffset;
    	} else if (document.documentElement && document.documentElement.clientWidth) {
    		return document.documentElement.scrollTop;
    	} else if (document.body.clientWidth) {
    		return document.body.scrollTop;
    	}
    },
    // get [pageXOffset,pageYOffset]
    getPageOffset : function() {
    	return [domHelper.getPageXOffset(), domHelper.getPageYOffset()];
    }
}
/* Custom event(from YUI)
===SAMPLE(from ydn)===
function TestObj(name) {
    this.name = name;
    this.event1 = new domHelper.customEvent("event1", this);
}
function Consumer(name, testObj) {
    this.name = name;
    this.testObj = testObj;
    this.testObj.event1.subscribe(this.onEvent1, this);
}
Consumer.prototype.onEvent1 = function(type, args, me) {
    alert(" this: " + this +
          "\n this.name: " + this.name +
          "\n type: " + type +
          "\n args[0].data: " + args[0].data +
          "\n me.name: " + me.name);
}
function TestData(data) {
    this.data = data;
}
// create an instance of our test object
var t1 = new TestObj("mytestobj1");
// create the event consumer, passing in the custom 
// object so that it can subscribe to the custom event
var c1 = new Consumer("mytestconsumer1", t1);
// create a data object that will be passed to the consumer when the event fires
var d1 = new TestData("mydata1");
// fire the test object's event1 event, passing the data object as a parameter
t1.event1.fire(d1);
=== //SAMPLE(from ydn) ===
*/
domHelper.customEvent = function(type, scope) {
	this.type = type;
	this.scope = scope || window;
	this.subscribers = [];
}
domHelper.customEvent.prototype = {
	subscribe : function(f,o,s) {
		this.subscribers[this.subscribers.length] = {fn:f,obj:o,scope:s};
	},
	fire : function() {
		var args=[].slice.call(arguments, 0);
		var subs=this.subscribers.slice();
		for (var i=0;i<subs.length;i++) {
			if (subs[i]) {
				var s=this.scope;
				if (subs[i].scope) s=subs[i].scope; 
				subs[i].fn.call(s,this.type,args,subs[i].obj);
			}
		}
	}
}

function simpleAjaxByuli() {
	var XmlHttp= null;
	var statusSuccessHandler= null;
	var onErrer= null;

	// 기본 에러 핸들러 입력
	onErrer= function (msg){
		try{
			Error.onScriptError(msg);
		}catch(e){}
	}

	try {
		if (window.XMLHttpRequest) {
			XmlHttp = new XMLHttpRequest();
			if (XmlHttp.readyState == null) {
				XmlHttp.readyState = 1;
				XmlHttp.addEventListener("load", function () {
					XmlHttp.readyState = 4;
					if (typeof XmlHttp.onreadystatechange == "function"){
						tmpXmlHtp.onreadystatechange();
					}
				}, false);
			}
		} else {
			XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	catch (e) {	}

	this.openXML =  function (key, method, url, async, uname, pswd) {
		if (XmlHttp != null) {
			function readystatechange() {
				if (XmlHttp.readyState == 4) {
					if (XmlHttp.status == 200) {
						if (statusSuccessHandler!=null){ statusSuccessHandler(XmlHttp.responseXML,key); }
					} else {
						onErrer("XML 파일을 읽는데 실패하였습니다.");
					}
				}
			}

			if (uname == undefined) {
				XmlHttp.open(method, url, async, uname, pswd);
			} else {
				XmlHttp.open(method, url, async);
			}
			XmlHttp.onreadystatechange = readystatechange; 
		}
	}
	this.openTEXT =  function (method, url, async, uname, pswd) {
		if (XmlHttp != null) {
			if (uname == undefined) {
				XmlHttp.open(method, url, async, uname, pswd);
			} else {
				XmlHttp.open(method, url, async);
			}
			XmlHttp.onreadystatechange = function () {
				if (XmlHttp.readyState == 4) {
					if (XmlHttp.status == 200) { 
						if (statusSuccessHandler!=null){ statusSuccessHandler(XmlHttp.responseText); }
					} else {
						onErrer("TEXT 파일을 읽는데 실패하였습니다.");
					}
				}
			}
		}
	}
	this.setStatusSuccessHandler = function (funcname) {
		statusSuccessHandler = funcname;
	}
	this.send = function (content) {
		if (content == undefined){
			XmlHttp.send(null);
		}else{
			XmlHttp.send(content);
		}
	}
	this.setErrerHandler = function (funcname) {
		onErrer= funcname;
	}
	this.setHeader = function (label, value) {
		XmlHttp.setRequestHeader(label, value);
	}
}

var logodeco_banner = {
	loadXML : function(domid, url, func) {
		var aobj= new simpleAjaxByuli();
		aobj.openTEXT('GET', url, true);
		aobj.setHeader('Content-Type', 'application/x-www-form-urlencoded;');
		aobj.setHeader("Accept-Language","ko");
		aobj.setStatusSuccessHandler(func);
		aobj.send(null);
	},
	
	setLIST : function (obj) {
		try {
			var data = eval('(' + obj + ')');
		}catch(e){ return; }

		// logo banner
		try {
			var banners = data.logodecos;
			var bannerTags = [];
			var bannerCnt = 0;
			for (var i=0; i < banners.length; i++) {
				if (banners[i].img_url.indexOf("http://") != -1 ) {
					bannerTags[i] = '<a href="' + banners[i].link_url + '" target="' + banners[i].link_target + '"><img src="' + banners[i].img_url + '" alt="" /></a>';
					bannerCnt++;
				}
			}
			if (bannerCnt > 0) {
				var random = parseInt(Math.random()*10) % bannerCnt;
				document.getElementById('logodecoArea').innerHTML = bannerTags[random];
			}
		} catch(e) {}

		// left ad link
		/*
		try {	
			var leftads = data.leftads;
			if (leftads.length > 0)
				document.getElementById('gnb_leftAd').innerHTML = '<a href="' + leftads[0].link_url + '" target="' + leftads[0].link_target + '">' + leftads[0].copy + '</a>';
		} catch(e) {}
		
		*/
		// right ad link
		try {
			var rightads = data.rightads;
			if (rightads.length > 0) {
				var html = [];
				for (i = 0; i < 2 && i < rightads.length; i++)
				 	html[i] = ('<a href="' + rightads[i].link_url + '" target="' + rightads[i].link_target + '">' + rightads[i].copy + '</a>');
				//document.getElementById('gnb_rightAd').innerHTML = html.join('');
			}
		} catch(e) {}
	},
	
	init : function (id) {
			
		// 임시 로고데코 ams연동
		/*		
		var rand = Math.random().toString(); 
		var ordval = rand.substring(2,rand.length); 
		var clintAgent = navigator.userAgent;
		document.getElementById('logodecoArea').innerHTML = "<span style='float:left; margin:0 11px 0 11px;'><img src='http://deco.daum-img.net/service_title/line_n.gif' /></span><iframe src=\"http://amsv2.daum.net/cgi-bin/adcgi?corpid=46&secid=05N48&type=cpm&tag=iframe&mkvid=1&ord=" + ordval + "\" width=200 height=39 border=0 frameborder=0 scrolling=no marginheight=0 marginwidth=0 id=tvpot_AMS style='float:left;'></iframe>";
		*/
		this.sel_tg = id;
		this.loadXML(id, "/LogoDeco.do", logodeco_banner.setLIST);			
	}	
}

//--video팟 
function miniDaum(category){
	var category= category==null? "see": category;
	if (typeof(document.getElementById("DAUMCOMMON_MINIDAUM")) == "object")	document.getElementById("DAUMCOMMON_MINIDAUM").innerHTML = '<iframe src="http://go.daum.net/bin/minidaum2006.cgi?category='+category+'&amp;body_id=MiniBodyff3&amp;utf8&amp;tag=iframe" width="100%" height="20" frameborder="0" scrolling="no"></iframe>';
}

 
if(/msie/.test(navigator.userAgent.toLowerCase()) && !/opera/.test(navigator.userAgent.toLowerCase())){
	var console ={
	log : function(str){document.title += " , " + str}
	} 
}

// [FIXME] url 포맷이 잘못되었을 경우 처리요.
var UrlUtil = {
	// url get parameter parsing
	parseParams : function(url) {
		var p = {};
		var u = (url === undefined ? location.href : url);
		
		// ? 위치 다음부터 substring
		var s = u.indexOf("?");
		if (s == -1) return p;
		u = u.substring(s+1);
		if (u.length == 0) return p;
		
		// # 이전까지 substring
		s = u.lastIndexOf("#");
		if (s > -1) u = u.substring(0,s);
		if (u.length == 0) return p;
		
		var us = u.split('&');
		if (us.length == 1 && us[0] == '') return p;
		for (var i = 0; i < us.length; i++) {
			s = us[i].indexOf('=');
			if (s == 0) continue;
			if (s == -1)
				p[us[i]] = '';
			else
				p[us[i].substring(0, s)] = us[i].substring(s+1); 					
		}
		return p;
	},
	// 파라미터 추가, 동일한 이름의 파라미터가 있을 경우 치환, url이 거지같이 들어오면 대책없다.
	addParam:function(arg, value, url) {
		url = (url === undefined ? location.href : url);
		
		var hash = '';
		var pt=url.lastIndexOf('#');
		if (pt > -1) hash=url.substring(pt+1);
		
		var params = UrlUtil.parseParams(url);
		if (params === {}) url += '?'; else url = url.substring(0,url.indexOf('?')+1);
		var found = false;
		for (var p in params) {
			if (p === arg) {
				params[p] = value;
				found = true;
			}
		}
		if (!found) params[arg]=value;
		var ps = [];
		for (var p in params) ps.push(p + '=' + params[p]);
		url += ps.join('&');
		if (hash!='') url += '#' + hash;
		return url;
	},
	// 파라미터 삭제, url이 거지같이 들어오면 대책없다.
	removeParam:function(arg, url) {
		url = (url === undefined ? location.href : url);
		var params = UrlUtil.parseParams(url);
		if (params === {} || params[arg] === undefined) return url;
		delete params[arg];
		
		var hash = '';
		var pt=url.lastIndexOf('#');
		if (pt > -1) hash=url.substring(pt+1);
		
		url = url.substring(0,url.indexOf('?')+1);
		var ps = [];
		for (var p in params) ps.push(p + '=' + params[p]);
		url += ps.join('&');
		
		if (hash!='') url += '#' + hash;
		
		return url;
	}
};

// trim string
function trim(s) {
	return s.replace(/(^\s*)|(\s*$)/gi, "");
}


// Cookie library
var cookieLib = {
	set:function(name, value, expires, path, domain, secure) {
		cookieLib.del(name, path, domain);
		var today = new Date();
		today.setTime( today.getTime() );
		if (expires) { expires = expires * 1000 * 60 * 60 * 24; }
		var expires_date = new Date( today.getTime() + (expires) );
		document.cookie = name + "=" +escape( value ) +
			( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
			( ( path ) ? ";path=" + path : "" ) + 
			( ( domain ) ? ";domain=" + domain : "" ) +
			( ( secure ) ? ";secure" : "" );
	},
	del:function(name, path, domain) {
		if ( cookieLib.get( name ) ) {
			document.cookie = name + "=" +
				( ( path ) ? ";path=" + path : "") +
				( ( domain ) ? ";domain=" + domain : "" ) +
				";expires=Thu, 01-Jan-1970 00:00:01 GMT";
		}
	},
	get:function(name) {
		var start = document.cookie.indexOf( name + "=" );
		var len = start + name.length + 1;
		if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) { return null; }
		if ( start == -1 ) { return null; }
		var end = document.cookie.indexOf( ";", len );
		if ( end == -1 ) { end = document.cookie.length; }
		return unescape( document.cookie.substring( len, end ) );
	}
}
function set_Cookie(name,value,expires,path,domain,secure){cookieLib.set(name,value,expires,path,domain,secure);}
function get_Cookie(name){return cookieLib.get(name);}
function Delete_Cookie(name,path,domain){cookieLib.del(name,path,domain);}

// 플레이리스트 관련 클래스 by junsung
var PlaylistClipManager = 
{
	getParentElement : null,
	cookieName : "TVPOT_PLAYLIST_TEMP",
	iconOnUrl  : "http://icon.daum-img.net/see/2008/200710_re/sub/pl/ico_get.gif",
	iconOffUrl : "http://icon.daum-img.net/see/200710_re/sub/pl/ico_getprev.gif",
	listLayerHeight : 175,
	clipListStr : "",
	clipListTitle : {},
	clipListTitleFlag : false,
	alertTimerObj : null,
	alertTimerMotionObj : new Array(),
	newClipid : null,
	positionListLayerTimerObj :null,
	loadTitleObject : function(param) 
	{
		var url = "/clip/InfoOfClipList.do"; // ?cliplist=6151347_6260142_";
		var aobj= new simpleAjaxByuli();
		aobj.openTEXT('POST', url, true);
		aobj.setHeader('Content-Type', 'application/x-www-form-urlencoded;');
		aobj.setHeader("Accept-Language","ko");
		aobj.setStatusSuccessHandler(PlaylistClipManager.setTitle);
		aobj.send("cliplist=" + param);
	},
	setTitle : function (obj)
	{
		var titleObj = null;
		obj = obj.split("\r\n").join("");
		try{
			titleObj = eval('(' + obj + ')');
		}catch(e){}
		PlaylistClipManager.clipListTitle = titleObj;
		PlaylistClipManager.clipListTitleFlag = true;
		PlaylistClipManager.showListLayerTag(titleObj);				
	},	
	submitData : function () 
	{
		var param = "";
		var joinString = "|_";
		var clipid_list = get_Cookie(this.cookieName);
		param = joinString + clipid_list.split("_").join(joinString);
		
		var pop = window.open(
			"/my/playlist/PopupAddPlaylist.do?type=3&selectedVids=" + param + "&sourcePlaylist=empty&fromlayer=true","tvpot_playlist_pop",
			"width=500,height=400"
		);
		this.offlistLayer();
	},
	clearData: function () 
	{
		var flag = confirm("찜한 동영상 전체를 비우시겠습니까?         ");
		if (flag)
		{
			this.deleteClip("all");
		}		
	},
	offlistLayer : function ()
	{
		
		this.motionListLayer(false, this.listLayerHeight);
		clearTimeout(this.positionListLayerTimerObj);
		
	},
	outLayer : function (e,obj)
	{
	    var to = e?e.relatedTarget:event.toElement; 
	
	    while(to) { 
	        if(to == obj) return; 
	        to = to.parentNode; 
	    } 
   	 	//this.listlayerOnOff();

	},
	listlayerOnOff : function ()
	{
		var wapperEle = document.getElementById("playlistWapper");
		var btnEle = document.getElementById("playlistLayerBtn");
		if (wapperEle.style.display != "block")
		{
			btnEle.className = "pcmbox_btn pcmbox_btn2";
			this.startlistLayer()
			
		}else
		{
			btnEle.className = "pcmbox_btn";
			this.offlistLayer()
		}
	},
	startlistLayer : function ()
	{
		this.clipListStr = get_Cookie(this.cookieName);
		
		if (this.clipListStr==null || this.clipListStr=="null")
		{
			this.showListLayerTag(null);
		}		
		if (this.clipListTitleFlag)
		{
			this.showListLayerTag(this.clipListTitle);
		}else{
			this.loadTitleObject(this.clipListStr);
		}
	},
	showListLayerTag : function (listTitle)
	{
		var wapEle = document.getElementById("playlistWapper");
		
		var boxEle = document.getElementById("playlistBox");
		var frameEle = document.getElementById("playlistFrame");
		
		var clipid_array = new Array() ;
		var list_tag = ""; 
				
		if ( this.clipListStr == undefined || this.clipListStr == null || this.clipListStr =="" || this.clipListStr=="null")
		{
			frameEle.className = "no_playlist";
		}else{
			clipid_array = this.clipListStr.split("_");
			frameEle.className = "in_playlist";
		}
		for ( var i=0; i<clipid_array.length - 1; i++)
		{
			var tag = this.getListTemplate();
			
			
			if (this.newClipid==clipid_array[i])
			{
				tag = tag.replace("$NEWCATCH", " id=\"pl_NEWCLIP_" + clipid_array[i] + "\" class=\"pl_newclip\" " );
			}
			tag = tag.split("$CLIPID").join(clipid_array[i]);
			if(this.clipListTitle[clipid_array[i]])
			{
				tag = tag.replace("$TITLE", this.clipListTitle[clipid_array[i]]);
			}else{
				tag = "";
			}
			list_tag += tag;
		}
		boxEle.innerHTML = list_tag;
		
		if(wapEle.style.display != "block")
		{
			frameEle.style.height = "0px";
			this.motionListLayer(true, 0);	
		}else{
			frameEle.style.height = this.listLayerHeight + "px";
		}

		this.positionListLayer(wapEle);
		wapEle.style.display = "block";

		if(this.newClipid!=null)
		{
			var tmp = setTimeout("PlaylistClipManager.catchNewClip('pl_NEWCLIP_" + this.newClipid + "')", 1000);
			this.newClipid = null;	
		}
		
	},
	catchNewClip : function (id)
	{
		try{
			document.getElementById(id).className= "";
		}catch(e){}
		
	},
	motionListLayer : function (flag, num)
	{
		var frameEle = document.getElementById("playlistFrame");
		if(flag)
		{
			num = num + 20;
			if(num> this.listLayerHeight)
			{
				frameEle.style.height = this.listLayerHeight + "px";
				return;
			}
		}else{
			num = num - 20;
			if(num < 0)
			{
				document.getElementById("playlistWapper").style.display = "none";
				frameEle.style.height = "0px";
				return;
			}
		}
		frameEle.style.height = num + "px";
		var tmp = setTimeout("PlaylistClipManager.motionListLayer(" + flag + "," + num +  ")", 1);	
					
	},
	positionListLayer : function ()
	{
		var wapEle = document.getElementById("playlistWapper");
		var y = 128;
		
		var scrollY = document.documentElement.scrollTop;
/*
		var scrollY;
		if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
			scrollY = self.pageYOffset;
		} else if( document.documentElement ) {
		//IE 6+ in 'standards compliant mode'
			scrollY = document.documentElement.scrollTop;
		} else if( document.body ) {
		//IE 4 compatible
			scrollY = document.body.scrollTop;
		}
*/	
		if (scrollY > 128)
		{
			y = scrollY;
		}
		wapEle.style.top = parseInt(y) + "px";
		this.positionListLayerTimerObj = setTimeout("PlaylistClipManager.positionListLayer()", 500);
	},
	getListTemplate : function ()
	{
		var tag = "";
		tag += "<dl $NEWCATCH ><dd onclick=\"PlaylistClipManager.deleteClip('$CLIPID',this)\">";
		tag += "<span>del</span></dd><dt><a href=\"/clip/ClipView.do?clipid=$CLIPID&lu=v_playlistclipt\">$TITLE</a></dt></dl>";
		return tag;
	},
	formSubmitPageDelete : function (url)
	{
		if (url.indexOf("fromlayer=true")!=-1)
		{
			PlaylistClipManager.deleteClip("all");
		}
	},
	deleteClip : function (id, tg)
	{
		var list = null;
		if (id != "all")
		{
			if(tg!=undefined)
			{
				var dlEle= this.getParentElement(tg)
				this.getParentElement(dlEle).removeChild(dlEle);
				
			}			
			list = get_Cookie(this.cookieName).replace(id + "_", "");
			if (list == "" || list == "null" || list == null)
			{
				if (document.getElementById("playlistFrame"))
				{
					document.getElementById("playlistFrame").className = "no_playlist";	
				}
				list = null;	
			}
		}else{
			if (document.getElementById("playlistFrame"))
			{
				document.getElementById("playlistFrame").className = "no_playlist";	
			}			
		}
		set_Cookie( this.cookieName, list, '', '/', '', '' );
	},
	goHelp : function ()
	{
		var tmp = window.open("http://blog.daum.net/ahahvideo/15512545");
	},
	send : function (tg, url)
	{

		var clipid = this.getClipid(url);
		var clipid_list = get_Cookie(this.cookieName);
		var clipid_array = new Array() ;
		var maxClipCount = 50;
		
		if ( clipid_list != undefined )
		{
			clipid_array = clipid_list.split("_");
		}else{
			clipid_list = "";
		}
		
		if ( clipid_array.length <= maxClipCount  && clipid_list.indexOf(clipid) == -1 )
		{
			this.setAddClipCookie(clipid_list, clipid);
			this.clipListTitle[clipid] = tg.title; 
			this.showAlert("찜한 동영상에 담았습니다. <p>찜한 동영상은 tv팟 우측 상단에서 확인할 수 있습니다. </p>");
			this.startlistLayer();			
		}else if ( clipid_array.length > maxClipCount )
		{
			this.showAlert("찜한 동영상은 " + maxClipCount + "개 까지 담을 수 있습니다. <p>찜한 동영상의 영상들을 플레이 리스트로 저장해주세요.</p>");	
		}else{
			this.showAlert("찜한 동영상에 이미 담겨있습니다. <p>찜한 동영상은 tv팟 우측 상단에서 확인할 수 있습니다.</p>");			

		}
		if(tg.src)
		{
			tg.src = this.iconOffUrl;
		}
		
	},
	setAddClipCookie : function (list, clipid)
	{
		this.newClipid = clipid;
		var clipid_list =  clipid + "_" + list;
		set_Cookie( this.cookieName, clipid_list, 7, '/', '', '' );
	},
	copyClipboard : function ()
	{
		var clipid_array = new Array();
		var tempStr = "";
		if ( this.clipListStr != undefined || this.clipListStr != null )
		{
			clipid_array = this.clipListStr.split("_");
		}		
		for ( var i=0; i<clipid_array.length - 1 && i<20 ; i++)
		{
			tempStr += this.clipListTitle[clipid_array[i]].replace(/<.+?>/g,'') + "\r\n";
			tempStr += "http://tvpot.daum.net/clip/ClipView.do?clipid=" + clipid_array[i] + "&lu=out_copy\r\n";
			tempStr += "\r\n";
		}
		//document.getElementById('urlCopier').SetClipboard(tempStr); 
		this.showAlert(' 찜한동영상의 주소가 복사되었습니다. <p>친구들에게 메신저로 보내보세요. 붙여넣기만 하면 <br />최대 20개까지 동영상제목과 주소가 한번에 보여요!</p>' , "83px", 4500 );
		return tempStr; 

	},
	alertMotion : function (flag, num)
	{
		var tg = PlaylistClipManager.alertTimerMotionObj[0];
		tg.className ="plAddMsgM" + num;
			
		if (flag)
		{
			tg.style.display= "inline";
			num = num + 1;
			if(num==5)
			{
				return
			}			
		}else {
			num = num - 1;
			if(num==0)
			{
				tg.style.display= "none";
				return
			}
		}

		this.alertTimerMotionObj[1] = setTimeout("PlaylistClipManager.alertMotion(" + flag + "," + num +  ")", 50);
	},
	offAlert : function ()
	{
		this.alertMotion(false, 5);
		//this.offlistLayer(false, 0);
	},	
	showAlert : function (msg, height, time)
	{
		var obj = document.getElementById("playlistAddMsg");
		var offTime = 2000;
		if(time!=undefined)
			offTime = time;
		if(height!=undefined)
		{
			obj.style.height = height;
		}else{
			obj.style.height = "60px";
		}		
		var x = ((document.documentElement.clientWidth - 340) / 2) + document.documentElement.scrollLeft;
		var y = ((document.documentElement.clientHeight - 90) / 2)  + document.documentElement.scrollTop;
		
		document.getElementById("playlistAddMsgStr").innerHTML = msg;

		if (!document.all)
		{
			if (document.documentElement.scrollTop < 800 && location.href.toUpperCase().indexOf("CLIPVIEW.DO")!=-1 )
			{
				x = x + 350;
			}
		}		
		
		obj.style.left = parseInt(x) + "px";
		obj.style.top = parseInt(y) + "px";
		
		this.alertMotion(true, 1)
		clearTimeout(this.alertTimerObj);
		this.alertTimerObj = setTimeout("PlaylistClipManager.offAlert()", offTime);
	},	
	getClipid : function (url)
	{
		var idx = url.toUpperCase().indexOf("CLIPID=");
		var id = url.substring(idx + 7, url.length );
		idx = id.indexOf("&");
		if (idx != -1)
		{
			id = id.substring(0, idx);
		}
		return id;
	},	
	overIcon : function (tg, flag)
	{
		
		var sizeText = "addplayerlistbtn";;
		if (flag)
		{
			sizeText = "addplayerlistbtn2";
		}
		tg.className = sizeText;
	},
	makePlusIcon : function(url, imgEle, option)
	{
		var jsClassName = "PlaylistClipManager";
		if(option=="frame")
		{
			jsClassName = "parent.PlaylistClipManager";
		}
		var imgtag = document.createElement("img");		
		imgtag.src = this.iconOnUrl;
		imgtag.className = "addplayerlistbtn";
		imgtag.onmouseover = new Function (jsClassName + ".overIcon(this, true)");
		imgtag.onmouseout = new Function (jsClassName + ".overIcon(this, false)");
		imgtag.title = imgEle.title == "" ? imgEle.alt : imgEle.title;
		//imgtag.title = "찜한 동영상에 담기";
		imgtag.onclick = new Function (jsClassName + ".send(this,'" + url + "', '" + option + "')");
		return imgtag;
	},
	setParnetElement : function ()
	{
		if (document.all)
		{
			this.getParentElement = function (tg)
			{
				return tg.parentElement;
			}
		}else{
			this.getParentElement = function (tg)
			{
				return tg.parentNode;
			}
		}
	}, 
	start : function (option)
	{
		var eventFlag = false;
		var tg = document;
		if (option && option.indexOf("ID_")>0 )
		{
			var temp = option.split("_");
			tg = document.getElementById(temp[1]);	
		}		
		
		var list = tg.getElementsByTagName("IMG");
		
		for ( var i=0 ; i<list.length && i<500 ; i++ )
	 	{
			var parentE = this.getParentElement(list[i]);
			var url = this.getParentElement(list[i]).href;
			
			if(
				url 
				&& url.toUpperCase().indexOf("CLIPVIEW.DO")!=-1 
				&& eval(list[i].width) <= 170
				&& eval(list[i].height) > 40
				&& !parentE.className.match("disableAddClip")	// 클립에 플레이리스트에 추가하기 버튼추가를 하지 않을경우엔 클립이미지의 상위 a태그 class속성에 "disableAddClip"을 준다. 
			)
	 		{
				this.getParentElement(parentE).style.position = "relative";
				if(!(parentE.nextSibling && parentE.nextSibling.nodeName == "IMG" && parentE.nextSibling.getAttribute("class") == "addplayerlistbtn")){
					 this.getParentElement(parentE).appendChild(this.makePlusIcon(url, list[i], option));
				}
				eventFlag = true;
	 		}
	 	}
		this.alertTimerMotionObj[0] = document.getElementById("playlistAddMsg");

		if(option=="")
		{	
			// document.getElementById('gnb_rightAd').style.display = "block";
			// PlaylistClipEvent.init(); // event
		}
	}, 
	init : function (option)
	{	
		var tem = setTimeout("PlaylistClipManager.start('" + option + "')",1);
	}
}
PlaylistClipManager.setParnetElement();

var rollingSearchKeyword = function (id) { 
	document.getElementById("search_keyword_page" + id).onclick(); 
	if(id==1){ id=2 }else{ id=1 } 
	rollingSearchKeywordObj = setTimeout("rollingSearchKeyword('" + id + "')", 4000); 
}
var neviSearchKeyword = {
	nowpage : 1,
	click : function (){
		var btn = document.getElementById('realTimeIssueList');
		if(btn.className.indexOf("1")!=-1) this.nowpage=2; else this.nowpage=1;		
		btn.className='li_tab' + this.nowpage;
	}	
}

// defer load
var deferLoadRegistry=[];
var deferLoadCompleted=[];
var registDeferImg = function(id,img,src){
	deferLoadRegistry[deferLoadRegistry.length]=[id,img,src];
	deferLoadCompleted[id]=false;
}
var deferLoad = function(id) {
	if(!deferLoadCompleted[id]) {
		deferLoadCompleted[id]=true;
		for(var i=0;i<deferLoadRegistry.length;i++){
			if(deferLoadRegistry[i][0]==id){
				deferLoadRegistry[i][1].onload="";
				deferLoadRegistry[i][1].src=deferLoadRegistry[i][2];
			}
		}
	}
}

String.prototype.trim = function (){
    return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

// copy player url for pasting to WYSIWYG Editor
// only for IE
function copyPlayerUrlToClipboardForWYSIWYG(embedSrc) {
	// <embed src='http://flvs.daum.net/flvPlayer.swf?vid=u3kMF6PohL4$' width='402px' height='324px' allowScriptAccess='always' type='application/x-shockwave-flash' allowFullScreen='true'></embed>
	var tmpPlayerUrlDivWISIWYG = document.createElement('div');
	tmpPlayerUrlDivWISIWYG.id = 'tmpPlayerUrlDivWISIWYG';
	document.body.appendChild(tmpPlayerUrlDivWISIWYG);
	tmpPlayerUrlDivWISIWYG.style.visibility='hidden';
	tmpPlayerUrlDivWISIWYG.style.height = 0;
	tmpPlayerUrlDivWISIWYG.style.width = 0;
	tmpPlayerUrlDivWISIWYG.innerHTML = embedSrc;
					
	var tmpTextRange = document.body.createTextRange();
	tmpTextRange.moveToElementText(document.getElementById('tmpPlayerUrlDivWISIWYG'));
	tmpTextRange.select();
	tmpTextRange.execCommand('copy');
	tmpTextRange = null;
	tmpPlayerUrlDivWISIWYG.innerHTML = '';
	document.body.removeChild(tmpPlayerUrlDivWISIWYG);
	tmpPlayerUrlDivWISIWYG= null;
}

// popup open functions
var popupOpener = {
	// 팟플레이어
	potpl:function(url){return window.open(url,'LivePopup','width=560,height=260,scrollbars=no,resizable=yes,status=yes');},
	// 댓글신고
	blind:function(url){return window.open(url,'CommentBlind','width=400,height=300,scrollbars=no,resizable=yes,status=yes');},
	// 텍스티콘
	texticon:function(url){return window.open(url,'texticon','width=630,height=530,scrollbars=no,resizable=yes,status=yes');},
	// 즐겨찾기추가
	addfavorite:function(url){return window.open(url,'addfavorite','width=420,height=265,scrollbars=no,resizable=yes,status=yes');},
	// 메일보내기
	sendmail:function(url){return window.open(url,'sendmail','width=500,height=390,scrollbars=no,resizable=no,status=yes');},
	// 플레이리스트담기
	storepl:function(url){return window.open(url,'storepl','width=520,height=278,scrollbars=yes,resizable=yes,status=yes');},
	// 플레이리스트편집기
	pleditor:function(url){return window.open(url,'pleditor','width=802,height=445,scrollbars=no,resizable=no,status=yes');}
}
var printAmsDoongBanner = 
{
	print : function (locate)
	{
		var locate = location.href.toUpperCase();
		
		function getCookies(name) {
		    var nameOfCookie = name + "=";
		    var x = 0;
		    while ( x <= document.cookie.length ) {
		        var y = (x+nameOfCookie.length);
		        if ( document.cookie.substring( x, y ) == nameOfCookie ) {
		            if ((endOfCookie=document.cookie.indexOf( ";", y )) == -1 )
		                endOfCookie = document.cookie.length;
		                return unescape( document.cookie.substring( y, endOfCookie ) );
		            }
		            x = document.cookie.indexOf( " ", x ) + 1;
		            if ( x == 0 )
		            break;
		        }
		    return "";
		}

		// 우측 여백 광고
		if(screen.width >= 1152)
		{
			// 섹션 월페이퍼 광고 집행시 주석처리 필요
			//document.write('<iframe src="http://amsv2.daum.net/cgi-bin/adcgi?corpid=46&secid=05N44&type=cpm&tag=iframe" width="80" height="105" name="RightAmsBanner" id="RightAmsBanner" scrolling="no" frameborder="0"></iframe>');
		}

		// 클립뷰 좌측 배너 
		if(locate.indexOf(".NET/CLIP/CLIPVIEW.DO")!=-1 && document.getElementById("vodshowArea"))
		{
			var rand = Math.random().toString(); 
			var ordval = rand.substring(2,rand.length); 
			document.write("<style> #AmsBannerWebPlayerLeft { position:absolute; top:170px; left:-20px; display:block;  background-color:transparent; } </style>");
			//document.write("<div id='AmsBannerWebPlayerLeft' style='width:88px; height:125px; background-color:red'></div>");
			//document.write("<iframe src=\"http://amsv2.daum.net/cgi-bin/adcgi?corpid=46&secid=05N09&type=cpm&tag=iframe&mkvid=1&ord=&ver=2" + ordval + "\" width=100 allowtransparency=true height=100 border=0 frameborder=0 scrolling=no marginheight=0 marginwidth=0 id='AmsBannerWebPlayerLeft'></iframe>");
		}		
		
		// 둥둥이
		var bannerVal = getCookies('inactiveAD');
		if (bannerVal!=1) 
		{
			var topPx = 0; // (parseInt(Math.random()*60)) *10;
			var leftPx = 0; // (parseInt(Math.random()*95)) *10;
			
			var bannerPosition = { 
				".NET/TOP.DO" : { "left" : "600", "top" : "230" } 
			};
			
			for ( var item in bannerPosition){
				if(locate.indexOf(item)!=-1)
				{
					leftPx =bannerPosition[item].left;
					topPx =bannerPosition[item].top;
					break;
				}				
			}
			if(locate.indexOf(".DO")==-1 && locate.indexOf(".HTM")==-1)
			{
				leftPx =bannerPosition[".NET/TOP.DO"].left;
				topPx =bannerPosition[".NET/TOP.DO"].top;
			}		
			if(topPx==0) return;

			document.write("<style> #float_banner { position:absolute; top:" + topPx + "px; left:" + leftPx + "px; display:block; } </style>");
			//document.write("<div id='float_banner' style='border:1px solid; width:50px; height:50px; background-color:red'></div>");
			document.write("<script type=\"text/javascript\" src=\"http://amsv2.daum.net/cgi-bin/adcgi?corpid=46&amp;secid=05N32&amp;type=cpm&amp;tag=javascript&mkvid=1&amp;charset=utf-8\"><\/script>");
			
		}
	},
	init : function ()
	{
		var locate = location.href.toUpperCase();
		this.print(locate);	
	}
}

/*
* 내 즐겨찾기 마이팟, main process: ajax call & box open/close animation
*/
var MypotFavorite = {
	boxWrapper : null,
	box : null,
	loaded : false,
	config : {
		favoriteButtonId : 'f_favorite', // 버튼 id
		favoriteBoxWrapperId : 'fb_wrapper', // box wrapper id - 실제 size가 변하는 요소
		favoriteBoxId : 'favorite_box', // contents box
		favoriteBoxHeight : 133, // box height
		animDuration : 0.2, // box hide/show animation duration
		hideClassName : 'hidden', // hide class name
		openClassName : 'open', // box가 열려 있을때의 버튼 class name
		xmlUrl : '/favorite/FavoriteXml.do' // 즐겨찾기 xml action
	},
	popup : function() {
		var mf = MypotFavorite;
		var conf = mf.config;
		
		if (!mf.boxWrapper) return;
		
		var button = document.getElementById(conf.favoriteButtonId);
		
		if (domHelper.cssjs('check', mf.boxWrapper, conf.hideClassName)) {
			// open favorite box
			var anim = new Anim(mf.boxWrapper, {height:{to:conf.favoriteBoxHeight}}, conf.animDuration, Easing.easeNone);
			anim.onStart.subscribe(function(){ domHelper.cssjs('remove', mf.boxWrapper, conf.hideClassName); });
			anim.onComplete.subscribe(function(){ domHelper.cssjs('add', button, conf.openClassName); });
			anim.animate();
		} else {
			// close favorite box
			var anim = new Anim(mf.boxWrapper, {height:{to:0}}, conf.animDuration, Easing.easeNone);
			anim.onComplete.subscribe(function(){
				domHelper.cssjs('add', mf.boxWrapper, conf.hideClassName);
				domHelper.cssjs('remove', button, conf.openClassName); });
			anim.animate();
		}
	},
	notLoginHtml : function() {
		var html = [];
		html.push('<div class="msg">');
		html.push('<p><strong>로그인되어 있지 않습니다.</strong><br />로그인 후 즐겨찾을 팟을 등록해보세요.</p>');
		html.push('<a href="http://www.daum.net/Mail-bin/login.html" class="login" onclick="location.href=this.href+\'?url=\'+encodeURIComponent(location.href);return false;" title="로그인 페이지">로그인 하기</a>');
		html.push('</div>');
		html.push('<p class="tools">');
		html.push('<a href="#" id="fb_close" onclick="MypotFavorite.popup();return false;">닫기</a>');
		html.push('</p>');
		return html.join('');
	},
	noFavoriteHtml : function() {
		var html=[];
		html.push('<div class="msg">');
		html.push('<p><strong>즐겨찾는 팟이 없습니다.</strong><br />즐겨찾을 팟을 등록해보세요.</p>');
		html.push('<a href="/my/Gate.do?srcid=rand" class="random" title="마이팟 랜덤가기">마이팟 랜덤가기</a>');
		html.push('</div>');
		html.push('<p class="tools">');
		html.push('<a href="#" id="fb_close" onclick="MypotFavorite.popup();return false;">닫기</a>');
		html.push('</p>');
		return html.join('');
	},
	favoritesHtml : function(favs) {
		if (favs == 'undefined' || favs == null) return '';
		var html=[];
		html.push('<ul>');
		var newIcon = "";
		for (var i=0;i<favs.length;i++){
			if (favs[i].update == "1"){
				newIcon = '<img height="8" width="8" alt="new" src="http://icon.daum-img.net/see/2008/icon/i_n.gif"/>';
			} else {
				newIcon = "";
			}
			html.push('<li><a href="'+favs[i].link+'">'+favs[i].name+'</a> '+newIcon+'</li>');
		}
		html.push('</ul>');
		html.push('<p class="tools">');
		html.push('<a href="/my/config/Favorite.do" id="fb_mng">즐겨찾기 관리</a>');
		html.push('<a href="/my/Gate.do?srcid=rand" id="fb_random">마이팟 랜덤가기</a>');
		html.push('<a href="#" id="fb_close" onclick="MypotFavorite.popup();return false;">닫기</a>');
		html.push('</p>');
		return html.join('');
	},
	loadFavorites : function() {
		var mf = MypotFavorite;
		var conf = mf.config;
		
		if (!mf.box) return;
		
		// xml callback function - parse FavoriteXml xml & view
		var loadHandler=function(xml) {
			
			mf.loaded = true;
			
			// login check
			if (xml.getElementsByTagName('isLogin')[0].firstChild.data == 'false') {
				mf.box.innerHTML = mf.notLoginHtml();
				domHelper.cssjs('add', mf.box, 'none');
				return;
			}
			
			var list=xml.getElementsByTagName('Favorite');
			var favs=[];
			for (var i=0;i<list.length;i++){
				var name=list[i].getElementsByTagName('name')[0].firstChild.data;
				var link=list[i].getElementsByTagName('link')[0].firstChild.data;
				var update=list[i].getElementsByTagName('new')[0].firstChild.data;
				favs.push({'name':name, 'link':link, 'update':update});
			}
			
			if (favs.length > 0) {
				domHelper.cssjs('remove', mf.box, 'none');
				mf.box.innerHTML = mf.favoritesHtml(favs);
			} else {
				domHelper.cssjs('add', mf.box, 'none');
				mf.box.innerHTML = mf.noFavoriteHtml();
			}
		}
		// call ajax
		var ajax = new simpleAjaxByuli();
		ajax.openXML(conf.favoriteBoxId, 'GET', conf.xmlUrl, true);
		ajax.setHeader('Content-Type', 'application/x-www-form-urlencoded;');
		ajax.setHeader('Accept-Language', 'ko');
		ajax.setStatusSuccessHandler(loadHandler);
		ajax.send(null);
	},
	init : function() {
		var mf = MypotFavorite;
		var conf = mf.config;
		
		mf.boxWrapper = document.getElementById(conf.favoriteBoxWrapperId);
		mf.box = document.getElementById(conf.favoriteBoxId);
		
		if (mf.boxWrapper == null || mf.box == null) return;
		
		mf.boxWrapper.style.height='0';
		domHelper.cssjs('add', mf.boxWrapper, conf.hideClassName);
	
		// toggle handler
		var button = document.getElementById(conf.favoriteButtonId);
		if (button) domHelper.addEvent(button, 'click', function(e) {
			if (!mf.loaded) mf.loadFavorites();
			mf.popup();
			domHelper.cancelClick(e);
		},false);
	}
}
function useFirebugLite(){
	var pi=document.createElement('script');
	pi.setAttribute('src','/n/js/firebugLite/pi.js');
	document.body.appendChild(pi);

	var firebug=document.createElement('script');
	firebug.setAttribute('src','/n/js/firebugLite/firebug-lite.js');
	document.body.appendChild(firebug);
	
	var keycode=document.createElement('script');
	keycode.setAttribute('src','/n/js/keycode.js');
	document.body.appendChild(keycode);
	var previousKeycode;
	document.onkeypress=function(event){
		var evt = event || window.event;	
		if(previousKeycode==Keycode["escape"] && evt.keyCode==Keycode["escape"]){
			window.firebug.init();
		}
		previousKeycode = evt.keyCode;
	}
}
