/**
 * 
 * 임시 플레이 리스트 저장하기
 * 
 */
var imsiPLCategory  = null;

var TTPrgBagSave = Class.create();
TTPrgBagSave.prototype = {
	_cateElement	: null,
	_divElement		: null,
	oForm : null,
	oInput : null,
	
	initialize : function() {
		this._storage	= cStorageMgr.getInstance();
	},
	
	set : function(parent) {
		this._parent		= parent;
		this._bagInfo		= this._storage.getChild('bagInfo');
		this._language		= rsTBagLang[chInfoJson['clientLang']];
		
		this.setEventListener();
	},
	
	getJSON : function() {
		var oForm = document.createElement("FORM");
		with(oForm) {
			method = "post";
			target = "ifrmBag";
			action = variable.getChild("chHost") + variable.getChild("pathChIsapi") + "playlist" + variable.getChild("isapiExt") + "/addPrg";
		}

		var oInput = document.createElement("INPUT");
		with(oInput) {
			type = "hidden";
			name = "json";  
			value = this._getParam();
		}
		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;
		
		switch (json['isAdd']) {
			case '1' : 
				this._parent.saveComplete();
				
				if(confirm(this._language['cap_temp_saveok'])) this.clickGoTo();
			break;
			case '0' :
				this._parent.saveComplete();
				
				if(confirm(this._language['cap_temp_saveok'])) this.clickGoTo();
				
				/* modify by rhio.kim 2008.03.17 */
//				if(json['prg_id'].length > 0) {
//					alert(this._language['cap_have_prg']);
//					
//					json['prg_id'].each( function(n){
//						this._parent.clickRemove($('iBAG_'+n));
//					}).bind(this);
//				}				
//				else alert(this._language['cap_have_all']);
			break;
			case '-1' :
			break;
		}
	},
	
	_getParam : function() {
		var param = '{ "userid": "'+ this._bagInfo['userid'] +'",' +
		            ' "categ_id": "'+ this._bagInfo['categ_id']+'",' +
		            ' "new_categ_name": "'+ this._bagInfo['new_categ_name'] +'",' +
		            ' "new_categ_index": "'+ this._bagInfo['new_categ_index'] +'",' +
		            ' "new_categ_open_pub": "'+ this._bagInfo['new_categ_open_pub'] +'",' +
		            ' "prg_info": '+ this._bagInfo['prg_info'] +' }';
//		return Object.toJSON(param);
		return param;
	},
	
	clickSave : function(element) {
		//haven't temprory list
		if(this._parent._cookieInfo == null || this._parent._cookieInfo.length == 0) {			
			alert(this._language['msg_no_list']);
			return false;
		}
		
		//save list!!  login check		
		if(this._bagInfo['userid'] == 'null') {
			this.clickCheckLogin();
			return false;
		}

		if(this._cateElement == null) this._cateElement = this._parent._cateElement;
		
		if(this._cateElement.selectedIndex == 0) {
			alert(this._language['msg_sel_cate']);
			return false;
		} else {
			this._bagInfo['categ_id'] = this._cateElement.options[this._cateElement.selectedIndex].value;
			this._bagInfo['new_categ_name'] = '';//this._cateElement.options[this._cateElement.selectedIndex].readAttribute('order');
			this._bagInfo['new_categ_index'] = '';
			this._bagInfo['new_categ_open_pub'] = '';//this._cateElement.options[this._cateElement.selectedIndex].readAttribute('pub');
			this._bagInfo['prg_info'] = this.getPrgIds();
		}
		
		this.getJSON();
	},
		
	clickAddCate : function() {
		//check login
		if(this._bagInfo['userid'] == 'null') {
			this.clickCheckLogin();
			return false;
		}

		var cateInfo = this._storage.getChild('cateInfo');
		if(cateInfo != undefined && cateInfo.length >= this._parent.cateLength) {
			alert(this._parent.cateLength + this._language['msg_over_cate']);
			return false;
		}
		
		$('BAG_DESC').hide();
		$('BAG_DESC_ADD').show();
	},
		
	clickCheckLogin : function() {
		if(this._bagInfo['userid'] == 'null')
		if(confirm(this._language['cap_temp_login'])) {			
			//oLogin.memActive('login');
			loginGo();
			return;
		} else return;
	},
	
	clickGoTo : function() {
		window.location.href = variable.getChild('chHost')+'channel/playlist.ptv?ch_userid='+ this._bagInfo['userid'] +'&categ_id='+ this._bagInfo['categ_id'];
	},
	
	clickBtnCancle : function() {
		$('BAG_DESC').show();
		$('BAG_DESC_ADD').hide();
	},
			
	//쿠키에 저장된 prg_id 얻어오기
	getPrgIds : function() {
		var prg_id = [];
		
		this._parent._cookieInfo.each( function(n) {
			prg_id.push([n[0],n[4],n[3]]);
		}.bind(this));

		return prg_id.toJSON();
	},
	
	occurError : function(err) {
		switch (err) {
			case 'sqlError' : alert(this._language['move_cate_sqlerr']);
				break;
			case 'progError' : alert(this._language['move_cate_progerr']);
				break;
			case 'keyError' : alert(this._language['move_cate_keyerr']);
				break;
		}
	},
	
	clickDivElement : function(event) {
		var element = Event.element(event);

		switch (element.id) {
			case 'BTN_NEW_CATEG' : 
				break;
			case 'BTN_CANCEL' : this.clickBtnCancle();
				break;
			case 'NEW_CATEG_NAME' : element.value = '';
				break;
			case 'BTN_GO' : this.clickGoTo();
				break;
		}
		Event.stop(event);
	},
	
	setEventListener : function() {
		//this._divElement.observe('click', this.clickDivElement.bindAsEventListener(this));
	}
}

/** Single Pattern - get only once Instance */
TTPrgBagSave.__instance__ = null; // static property
TTPrgBagSave.getInstance = function () {
	if (this.__instance__ == null) {
		this.__instance__ = new TTPrgBagSave();
	}
	return this.__instance__;
}

/**
 * 
 * 임시 플레이 리스트 사용자 카테고리 목록 가져오기
 * 
 */
var TTPrgBagCate = Class.create();
TTPrgBagCate.prototype = {
	tryCnt : 0,
	initialize : function() {
		//html	= cStorageMgr.getInstance();
		this._storage	= cStorageMgr.getInstance();
	},
	
	set : function(parent) {
		this._parent	= parent;
		this._language	= rsTBagLang[chInfoJson['clientLang']];
		this._bagInfo	= this._storage.getChild('bagInfo');
	},
	
	getJSON : function() {
		if(imsiPLCategory == null) {
			if(this.tryCnt == 0) {
				var oScript = document.createElement("SCRIPT");
				with(oScript) {
					setAttribute("type", "text/javascript");
					setAttribute("language", "javascript");
					setAttribute("charset", "utf-8");
					setAttribute("src", variable.getChild("chHost") + variable.getChild("pathChIsapi") + "mplaylist" + variable.getChild("isapiExt") + "/tmplist?userId=" + this._bagInfo['userid']);
				}
				document.getElementsByTagName('head')[0].appendChild(oScript);
			}
			if(this.tryCnt < 10) {
				setTimeout(function() {this.getJSON();}.bind(this), 200);
			}
			this.tryCnt ++;
		} else {
			this._setJSON(imsiPLCategory);
		}
/*
		new Ajax.Request( '/json/v001/mplaylist.dll/list', {
			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._storage.appendHash('cateInfo', json['list']);

		var tmp = new Template('<option value="#{plcId}" order="#{vorder}" pub="#{plcOpenPub}">#{plcTitle}</option>')
		
		var design = new pandora.util.StringBuffer();
		json['list'].each( function(n, i){
			var dat = $H(n);
			dat.merge({plcTitle: n.plcTitle.truncate(30)})
			design.append((tmp.evaluate(dat)));
			
			if(json['list'].length == i+1) this._bagInfo['new_categ_index'] = n['vorder'];
		}.bind(this));
		
		this._parent._cateElement.replace('<select id="BAG_CATES" name="BAG_CATES" style="width:180px"><option>'+this._language['cap_sel_mycate']+'</option>'+design+'</select>');
		this._parent._cateElement = $('BAG_CATES');
	},
	
	_getParam : function() {
		var param = { userId: this._bagInfo['userid'] };
		return Object.toJSON(param);
	},
	
	loadCate : function() {
		this.getJSON();
	}
}

/** Single Pattern - get only once Instance */
TTPrgBagCate.__instance__ = null; // static property
TTPrgBagCate.getInstance = function () {
	if (this.__instance__ == null) {
		this.__instance__ = new TTPrgBagCate();
	}
	return this.__instance__;
}

/**
 * 
 * 임시 플레이 리스트 카테고리 추가
 * 
 */
var TTPrgBagCateAdd = Class.create();
TTPrgBagCateAdd.prototype = {
	_divElement	: null,
	oForm : null,
	oInput : null,
	
	initialize : function() {
		//html	= cStorageMgr.getInstance();
		this._storage	= cStorageMgr.getInstance();
	},
	
	set : function(parent) {
		this._parent		= parent;		
		this._divElement	= $('BAG_DIV');
		this._language		= rsTBagLang[chInfoJson['clientLang']];
		
		this._bagInfo		= this._storage.getChild('bagInfo');
		this._cateInfo		= this._storage.getChild('cateInfo') || null;
	},
	
	getJSON : function() {
		var oForm = document.createElement("FORM");
		with(oForm) {
			method = "post";
			target = "ifrmBag";
			action = variable.getChild("chHost") + variable.getChild("pathChIsapi") + "playlist" + variable.getChild("isapiExt") + "/addCate";//variable.getChild("chHost") + "json/v001/playlist.dll/addCate";
		}

		var oInput = document.createElement("INPUT");
		with(oInput) {
			type = "hidden";
			name = "json";  
			value = this._getParam();
		}
		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/addCate', {
			parameters	: { json : this._getParam()},
			onSuccess	: function(transport) { this._setJSON(transport.responseText.evalJSON()); }.bind(this),
			onFailure	: function() {}
		});
*/
	},

	_setJSON : function(json) {
		this.oForm = null;
		this.oInput = null;

		if(json['isAdd'] == '1') {
			var setData = this._storage.getChild('cateInfo');
			var dat = { "plcId":json['new_categ_id'], "plcTitle":this._bagInfo['new_categ_name'], "plcOpenPub":this._bagInfo['new_categ_open_pub'], "vorder":this._bagInfo['new_categ_index'] }
			setData.push(dat);
			
			var tmp = new Template('<option value="#{plcId}" order="#{vorder}" pub="#{plcOpenPub}">#{plcTitle}</option>')
			var design = new pandora.util.StringBuffer();
			setData.each( function(n, i){
				var dat = $H(n);
					dat.merge({plcTitle: n.plcTitle.truncate(30)})
					design.append((tmp.evaluate(dat)));
				
				if(setData.length == i+1) this._bagInfo['new_categ_index'] = n['vorder'];
			}.bind(this));

			this._parent._cateElement.replace('<select id="BAG_CATES" name="BAG_CATES" style="width:180px"><option>'+this._language['cap_sel_mycate']+'</option>'+design+'</select>');
			this._parent._cateElement = $('BAG_CATES');
			
			//카테고리 추가하기 레이어 초기화
			var descAdd = $('BAG_DESC_ADD');
				descAdd.hide();
				descAdd.down(0).value = this._language['cap_temp_title'];
			var desc = $('BAG_DESC');
				desc.show();
			
			this._setAutoSelect();
		} else this.occurError(json['exception']);
	},
	
	_getParam : function() {
		var param = { userid: this._bagInfo['userid'], new_categ_name: this._bagInfo['new_categ_name'], 
						new_categ_index: this._bagInfo['new_categ_index'], new_categ_open_pub: this._bagInfo['new_categ_open_pub'] };
		return Object.toJSON(param);
	},
	
	_getFinalIndex : function() {
		this._bagInfo['new_categ_index'] = parseInt(this._bagInfo['new_categ_index'], 10) + 1;
		return this._bagInfo['new_categ_index'];
	},
	
	_setAutoSelect : function() {
		this._parent._cateElement.selectedIndex = this._parent._cateElement.length-1;
	},
	
	occurEvent : function(element) {
		var ipt_categ_name = element.previous(1);
		
		this._bagInfo['new_categ_name'] = ipt_categ_name.value;
		this._getFinalIndex();

		if(this._bagInfo['new_categ_name'].blank() || (this._language['cap_temp_title'] == this._bagInfo['new_categ_name'])) {
			alert(this._language['cap_temp_title']);
			ipt_categ_name.value = '';
			ipt_categ_name.focus();
			return false;
		}

		this.getJSON();
	},
	
	occurError : function(err) {
		switch (err) {
			case 'sqlError' : alert(this._language['move_cate_sqlerr']);
				break;
			case 'progError' : alert(this._language['move_cate_progerr']);
				break;
			case 'keyError' : alert(this._language['move_cate_keyerr']);
				break;
		}
	}
}

/** Single Pattern - get only once Instance */
TTPrgBagCateAdd.__instance__ = null; // static property
TTPrgBagCateAdd.getInstance = function () {
	if (this.__instance__ == null) {
		this.__instance__ = new TTPrgBagCateAdd();
	}
	return this.__instance__;
}

