var TTPrgBagList = Class.create();
TTPrgBagList.prototype = {
	_targetElement	: null,
	_listElement	: null,
	_cateElement	: null,
	_errElement		: null,
	_cookieInfo		: false,
	oIFrame : null,

	initialize : function() {
		//html	= cStorageMgr.getInstance();
		this._storage	= cStorageMgr.getInstance();
		this.createIFrame();
	},

	createIFrame : function() {
		if(this.oIFrame == null) {
			var oDiv = document.createElement("DIV");
			with(oDiv) {
				with(style) {
					position = "absolute";
					left = "0px";
					top = "0px";
					display = "none";
				}
			}
			document.body.appendChild(oDiv);
			oDiv.innerHTML = "<iframe width=\"0\" height=\"0\" id=\"ifrmBag\" name=\"ifrmBag\" style=\"position:static;display:none;\"></iframe>";
		}
	},

	set : function(parent, uid) {
		this._controller		= parent;
		this.uid				= uid;
//		this._cookieInstance = parent.sharedObject;
//		this._cookieInstance	= parent.cookieInstance;
		this.cateLength			= 30;

		this._bagInfo			= this._storage.getChild('bagInfo');
		this._userInfo			= this._storage.getChild('userInfo');

		this._createArea();
		this.setEventListener();

//		this._cookieInfo		= eval(this._cookieInstance.getItem('glb_bsk'));
	},

	_createSubInstance : function() {
		this._saveInstance		= TTPrgBagSave.getInstance();
		this._saveInstance.set(this);

		this._cateInstance		= TTPrgBagCate.getInstance();
		this._cateInstance.set(this);

		this._cateAddInstance	= TTPrgBagCateAdd.getInstance();
		this._cateAddInstance.set(this);
	},

	_createArea : function() {
		new Insertion.Bottom(document.body, '<div id="FRM_BAG" style="position:fixed; _position:absolute; _top:expression(document.body.scrollTop+document.body.clientHeight-this.clientHeight); right: 1em; bottom: 0em; display:none;"></div>');

		this._targetElement = $('FRM_BAG');
	},

	//초기 레이어가 없을 경우 생성 또는
	_createBag : function() {
		this._targetElement.update(html.getChild('FRM_BAG'));

		this._listElement = $('BAG_PRG_LIST');
		this._createSubInstance();

		if(this._cookieInfo != []) this.drawCookie();
	},

	//영상 썸네일 생성
	_createThumbImg : function(prg_id, prg_org_userid, age) {
//		return getVodThumbnail(prg_id, prg_org_userid);

		switch(status) {
			case '30001' : return variable.getChild("designHost") + 'img/thumb_encode_failed.gif';//인코딩실패
			break;
			case '30002' : return variable.getChild("designHost") + 'img/thumb_encoding.gif'; //인코딩중
			break;
			case '30008' : return variable.getChild("designHost") + 'img/thumb_delete.gif'; //동영상삭제
			break;
			case '30009' : return variable.getChild("designHost") + 'img/thumb_delete.gif'; //동영상본인삭제
			break;
		}

		if(parseInt(age, 10) == 19) {
			var memAge = oCookie.get('glb_mem[age]');
			if(memAge == null || (memAge != null && memAge <= 19)) return variable["skinHost"] + 'static/19_over.gif';	//성인 영상일때
		}

		return getVodThumbnail(prg_id, prg_org_userid);
	},
	
	//영상 성인 아이콘
	_checkAdult: function(age) {
		var memAge = oCookie.get('glb_mem[age]');
		if(memAge != null && parseInt(age, 10) == 19) return '';
		
		return 'none';
	},

	//프로그램 직접 URL 생성
	_createPrgUrl : function(prg_id, prg_org_userid) {
		return variable.getChild('chHost')+ 'channel/video.ptv?ch_userid='+ prg_org_userid + '#prgid='+ prg_id;
	},

	//채널 URL 생성
	_createChUrl : function(prg_org_userid) {
		return variable.getChild('chHost')+'channel/video.ptv?ch_userid='+ prg_org_userid;
	},

	//일반 추가 템플릿
	evaluate : function() {
		var n = arguments;

		var tmp = new Template(html.getChild('BAG_PRG_LIST'));
//		var dat = { 'prg_id':n[0], 'prg_title':n[1], 'prg_runtime':n[2], 'prg_chname':n[4], 'prg_url':this._createPrgUrl(n[0],n[4]), 'src':this._createThumbImg(n[4], n[0]), 'ch_url':this._createChUrl(n[4]) };
		var dat = { 'prg_id':n[0], 'prg_title':n[1], 'prg_runtime':n[2], 'prg_chname':n[3], 'prg_url':this._createPrgUrl(n[0],n[4]), 'src':this._createThumbImg(n[4], n[0], n[5]), 'ch_url':this._createChUrl(n[4]), 'ad_on':this._checkAdult(n[5]) };

		return tmp.evaluate(dat);
	},

	//쿠키가 있을 때 추가
	evaluateCookie : function() {
		var tmp = new Template(html.getChild('BAG_PRG_LIST'));
		var dataSet = this._cookieInfo.reverse(false);

		var design = [];
		dataSet.each( function(n) {
//			var dat = { 'prg_id': n[0], 'prg_title' : n[1], 'prg_runtime' : n[2], 'prg_chname' : n[4 ], 'prg_url':this._createPrgUrl(n[0],n[4]), 'src':this._createThumbImg(n[4], n[0]), 'ch_url':this._createChUrl(n[4]) };
			var dat = { 'prg_id': n[0], 'prg_title' : n[1], 'prg_runtime' : n[2], 'prg_chname' : n[3], 'prg_url':this._createPrgUrl(n[0],n[4]), 'src':this._createThumbImg(n[4], n[0], n[5]), 'ch_url':this._createChUrl(n[4]), 'ad_on':this._checkAdult(n[5]) };
			design.push( tmp.evaluate(dat)+'\n\n');
		}.bind(this));

		return design.join('');
	},

	//일반 추가
	draw : function() {
		var n = arguments;
		new Insertion.Top(this._listElement, this.evaluate(n[0],n[1],n[2],n[3],n[4],n[5]));
		this._listElement.scrollTop = 0;
	},

	//쿠키가 있을 때
	drawCookie : function() {
		new Insertion.Top(this._listElement, this.evaluateCookie());
	},

	//로컬 변수에 전체 쿠키 정보 갱신
	_appendTempory : function(data) {
		this._cookieInfo.push(data)
		return this._cookieInfo;
	},

	_isOver : function() {
		if(this._cookieInfo == null) this._cookieInfo = SharedObject.getItem('glb_bsk') || [];
		if(this._cookieInfo.length >= parseInt(this._bagInfo['max'], 10)) {
			new Insertion.Top(this._listElement, html.getChild('IS_OVER'));
			return true;
		} else return false;
	},

	//쿠키에 존재여부 확인
	_isExist : function(prg_id) {
		var cnt = 0;
		for(var i=0, length=this._cookieInfo.length; i<length; i++) {
			if(this._cookieInfo[i][0] == prg_id) cnt++;
		}

		if(cnt > 0) {
			new Insertion.Top(this._listElement, html.getChild('IS_EXIST'));
			return true;
		} else return false;
	},

	_isFirst : function() {
		var elements = this._listElement.immediateDescendants();
		if(elements[0] != null) elements[0].removeClassName('playlist_on');
	},

	//공통 추가함수
	append : function(data) {
		if (!this._cookieInfo) this._cookieInfo = eval(SharedObject.getItem('glb_bsk')) || [];

		this._targetElement.show();

		//임시플레이 레이어 생성 체크 - 실제로 Append 하기 전에는 FRM_BAG division만 생성되게 된다.
		if(this._listElement == null) this._createBag();

		//에러 로그가 있으면 삭제
		if($('BAG_ERR_MENT') != null) $('BAG_ERR_MENT').remove();


		//쿠키에 담을 수 있는 개수 체크
		if(this._isOver()) return false;

		//이미 쿠키에 존재하는지 체크(실제로는 로컬 스토리지에서 체크)
		if(this._isExist(data[0]) || data.length == 0) return false;
		else {
			this.DATA = data;

			if(!data[3]) {
				this.getJSON(data);
				return;
			}
			
			this._complete();
		}
	},

	getJSON : function(data) {
		var oForm = document.createElement("FORM");
		with(oForm) {
			method = "post";
			target = "ifrmBag";
			action = variable.getChild("chHost") + variable.getChild("pathChIsapi") + "playlist" + variable.getChild("isapiExt") + "/getChName";
		}

		var oInput = document.createElement("INPUT");
		with(oInput) {
			type = "hidden";
			name = "json";  
			value = '{ prg_org_userid : "'+ data[3] +'"}';
		}

		oForm.appendChild(oInput);
		document.body.appendChild(oForm);

		document.domain = "pandora.tv";
		oForm.submit();

		this.oForm = oForm;
		this.oInput = oInput;
		
/*
		new Ajax.Request( '/json/v001/playlist.dll/addPrg', {
			method		: 'post',
			parameters	: { json : this._getParam()},
			onCreate	: function() {},
			onSuccess	: function(transport) { this._setJSON(transport.responseText.evalJSON()); }.bind(this),
			onComplete	: function() {},
			onFailure	: function() {}
		});
*/
	},
	
	setJSON : function(json) {
		this.oForm = null;
		this.oInput = null;
		
		this.DATA[3] = json['prg_chname'];
		this._complete();
	},
	
	_complete : function() {
		var data = this.DATA;
		
		//존재하지 않을 경우
		this._appendTempory([data[0],data[1].truncate(18),data[2],data[3],data[4],data[5]]);
		SharedObject.setItem('glb_bsk',this._cookieInfo.inspect());
		this.draw(data[0],data[1].truncate(18),data[2],data[3],data[4],data[5]);
	},

	//임시 영상 쿠키, 로컬변수, UI 삭제
	clickRemove : function(element) {
		var parent = element.up(4);
		var depth = parent.nextSiblings();
			parent.remove();

		this._cookieInfo.splice(depth.length, 1);
		SharedObject.removeItem('glb_bsk');
		SharedObject.setItem('glb_bsk',this._cookieInfo.inspect());
	},

	//해당 영상으로 이동
	clickGoUrl : function(url) {
		window.location.href = url;
	},

	//쿠키 전체 삭제
	clickDeleteAll : function() {
		this._cookieInfo = null;
		SharedObject.removeItem('glb_bsk');
		this._listElement.update('');
	},

	//이벤트 핸들러 분기
	clickBag : function(event) {
		var element = Event.element(event);

		switch (true) {
			case element.id.include('BAG_BTN_CLOSE') :
					this._saveInstance.clickBtnCancle();
					this._targetElement.hide();
				break;
			case element.id.include('BAG_THUMB') : this.clickGoUrl(element.readAttribute('href'));
				break;
			case element.id.include('BAG_PRG_DEL') : this.clickRemove(element);
				break;
			case element.id.include('BAG_NEW_CATE') : this._saveInstance.clickAddCate(element);
				break;
			case element.id.include('BAG_BTN_SAVE') : this._saveInstance.clickSave(element);
				break;
			case element.id.include('BAG_CLEAR') : this.clickDeleteAll();
				break;
			case element.id.include('BAG_PRG_TITLE') : this.clickGoUrl(element.href);
				break;
			case element.id.include('BAG_ORG_CH') : this.clickGoUrl(element.href);
				break;
			case element.id.include('BAG_CATES') : this._saveInstance.clickCheckLogin();

			/**
			 * TPrgBagSave event
			 */
			case element.id.include('BTN_CANCEL') : this._saveInstance.clickBtnCancle();
				break;
			case element.id.include('BTN_GO') : this._saveInstance.clickGoTo();
				break;

			/**
			 * TPrgBagCateAdd
			 */
			case element.id.include('BTN_NEW_SAVE') : this._cateAddInstance.occurEvent(element);
				break;
			case element.id.include('NEW_CATEG_NAME') : element.value = '';
				break;

			/**
			 * TPrgBagLogin
			 */
			case element.id.include('BTN_LOGIN') : loginGo();//oLogin.memActive('login');//window.location.href = 'http://glb.pandora.tv/sign/signup.ptv?retUrl=http://glb.pandora.tv/channel/playlist.ptv';
				break;
		}
		Event.stop(event);
	},

	_active : false,

	_mouseOverBag : function(event) {
		Event.stop(event);
		//로그인 체크 쿠키
		if(this._bagInfo['userid'] == 'null') {
			return false;
		}

		if(!this._active) {
			this._cateInstance.loadCate();

			this._cateElement = $('BAG_CATES');
			this._active = true;
			this.freeEventListener();
		} else {
			return false;
		}
	},
/*		9.28 edina.kim (bug list 64 ing..)
	_enterKeyBag : function(event) {
		var element = Event.element(event);
		if(element.id == 'NEW_CATEG_NAME' && event.keyCode == 13) {
			alert('kkk');
		}
	},
*/

	//이벤트 핸들러 설정
	setEventListener : function() {
		var mo1 = this.clickBag.bindAsEventListener(this);
		Event.observe('FRM_BAG', 'click', mo1);

		var mo2 = this._mouseOverBag.bindAsEventListener(this);
		Event.observe('FRM_BAG', 'mouseover', mo2);
/*		9.28 edina.kim (error list 64 ing..)
		var mo3 = this._enterKeyBag.bindAsEventListener(this);
		Event.observe('FRM_BAG', 'keydown', mo3);
*/
	},

	freeEventListener : function() {
		var mo1 = this._mouseOverBag.bindAsEventListener(this);
		Event.stopObserving('FRM_BAG', 'mouseover', mo1);
	},

	saveComplete : function() {
		this.clickDeleteAll();
	}
}

/** Single Pattern - get only once Instance */
TTPrgBagList.__instance__ = null; // static property
TTPrgBagList.getInstance = function () {
	if (this.__instance__ == null) {
		this.__instance__ = new TTPrgBagList();
	}
	return this.__instance__;
}
//Event.observe(window, 'load', TPrgBag.create.bind(TPrgBag));
