/**
 * @projectDescription Preview Panel for SquareScope
 * 
 * @author rhio.kim@gmail.com, tizie80@nate.com
 * @author rhio.kim www.itovi.com
 * @version 0.1.03
 * @usage 
 * @import prototype_1.6
 * 
 **/

 /**
  * class for videoScreen area display controll
  */
 var TPreviewSwitch = Class.create({
 	options: {
		state: false,
		stageWidth: 984,//976
		stageHeight: undefined,
		width: undefined,
		height: undefined
	},
	
	/**
	 * constructor
	 * @param	{Object}	config	custom configuration 
	 */
 	initialize: function(config) {
		this.options = Object.extend(this.options, config || {});
		
		this.initComponent();
	},
	
	btnEnable : function() {
		if(this.options.on.style.display == "none" && this.options.off.style.display == "none") {
			this.options.off.show();
		}
	},
	
	/**
	 * private
	 * intialize component
	 */
	initComponent: function() {
		this.options.off = $(this.options.off);
		this.options.on = $(this.options.on);
		this.options.target = $(this.options.target);
		this.options.ss = $(this.options.ss);
		
		this._setBounce();
		this.addEventListener();
	},
	
	_setBounce: function() {
		this.options.width = this.options.target.getWidth();
		this.options.height = this.options.target.getHeight();
		
//		this.options.stageWidth = this.options.ss.getWidth();
		this.options.stageHeight = this.options.ss.getHeight();
	},
	
	/**
	 * public
	 * preview panel component display ON
	 * @param {Object} event
	 */
	on: function(event) {
		var ua = navigator.userAgent.toLowerCase();
		var ie6 = !(/opera/.test(ua)) && /msie 6/.test(ua);
		//var gap = ie6 ? 30 : 10;
		//var gap = ie6 ? 16 : 16;
		var gap = 16;

		var width = this.options.stageWidth - this.options.width - gap;
		
		this.options.ss.setStyle({width:width +"px"});
//		JSTweener.addTween(this.options.ss, { width: 661 });
		
		this.options.off.hide();
		this.options.on.show();
		this.options.target.show();
		
		this.options.state = true;
	},
	
	
	/**
	 * public
	 * preview panel component display OFF
	 * @param {Object} event
	 */
	off: function(event) {
		var width = this.options.stageWidth;

		this.options.ss.setStyle({width:width +"px"});
		
		this.options.off.show();
		this.options.on.hide();
		this.options.target.hide();
		
		this.options.state = false;
	},
	
	/**
	 * public [getter]
	 * preview panel component' display state
	 * @return	Boolean
	 */
	getState : function() {
		return this.options.state;
	},
	
	/**
	 * private
	 * register event listener
	 */
	addEventListener: function() {
		this.options.off.observe('click', this.on.bindAsEventListener(this));
		this.options.on.observe('click', this.off.bindAsEventListener(this));
	},
	
	/**
	 * private
	 * unregister event listener
	 */
	removeEventListener: function() {
		this.options.off.stopObserving('click', this.on.bindAsEventListener(this));
		this.options.on.stopObserving('click', this.off.bindAsEventListener(this));
	}
 });
 
 
 /**
  * PrivewList Manager Component
  * StateProvider handling and sub component handling
  */
 var TPreviewList = Class.create({
 	options: {},
	
	/**
	 * constructor
	 * @param	{Object}	config	custom configuration 
	 */
 	initialize: function(config) {
		this.options = Object.extend(this.options, config || {});
		
		this.initComponent();
	},
	
	/**
	 * private
	 * intialize component
	 */
	initComponent: function() {
		/* <img src="#{THUMB}" ... /> Image SRC attribute recognize on FireFox browser follow pattern
		 * <img src="#%7BTHUMB%7D" /> So. <img src="#/THUMB/" ... />
		 */
//		var syntax = /(^|.|\r|\n)(#\/(.*?)\/)/;
		var temp = $('tpl_ViewedMovie').innerHTML;
			temp = temp.replace(/!--/g, '');
			temp = temp.replace(/--/g, '');
		this.options.tpl = new Template(temp);
		this.options.target = $(this.options.target);
		
		this.addEventListener();
	},
	
	/**
	 * public 
	 * render items used by "tpl_ViewedMovie" template
	 * @param {Object} items
	 */
	render: function(items) {
		var len = items.length;
		var html = [];
		var item;
		
		for(var i=0; i< len; i++) {
			item = Object.clone(items[i]);
			item.TITLE = decodeURIComponent(item.TITLE);
			html.push(this._evaluate(item));
		}
		
		this.options.target.insert(html.join(''));
	},
	
	/**
	 * public
	 * append item use by "tpl_ViewMovie" template
	 * @param {Object} item
	 */
	append: function(item) {
		this.options.target.insert( { "top":this._evaluate(item)} );
	},
	
	/**
	 * priate
	 * evaluate item used by template
	 * @param {Object} item
	 * @return {String}	evaluated template
	 */
	_evaluate: function(item) {
		return this.options.tpl.evaluate(item);
	},
	
	/**
	 * public
	 * remove passed id element on document
	 * @param {Object} pid
	 */
	remove: function(pid) {
		var el = $(this.options.elementPrefix + pid);
		if(el) el.remove();
	},
	
	/**
	 * private
	 * mouse click event handler
	 * @param {Object} event
	 */
	_clickEventHandler: function(event) {
		var target = event.target;
		var pid = target.getAttribute('pid');
		var type = target.getAttribute('type');
		
		if(!pid) return;
		
		switch(type) {
			case "title" :
				this.options.target.fire("PreviewList:clicktitle", { PID: pid });
			break;
			case "thumb" :
				this.options.target.fire("PreviewList:clickthumb", { PID: pid });
			break;
			case "remove":
				this.options.target.fire("PreviewList:clickremove", { PID: pid });
			break;
		}
	},
	
	/**
	 * private
	 * mouse move event handler
	 * @param {Object} event
	 */
	_overEventHandler: function(event) {
		var target = event.target;
		var pid = target.getAttribute('pid');
		var type = target.getAttribute('type');
		
		if(!pid) return;

		switch(type) {
			case "thumb" :
				this.options.target.fire("PreviewList:overthumb", { PID: pid, target: target });
			break;
		}
	},
	
	/**
	 * private
	 * register event listener
	 */
	addEventListener: function() {
		this.options.target.observe("click", this._clickEventHandler.bindAsEventListener(this));
		/* 썸네일 프리뷰 이벤트 리스너 등록 */
		this.options.target.observe("mouseover", this._overEventHandler.bindAsEventListener(this));
	},
	
	/**
	 * private
	 * unregister event listener
	 */
	removeEventListener: function() {
		this.options.target.stopObserving("click", this._clickEventHandler.bindAsEventListener(this));
		this.options.target.stopObserving("mouseover", this._overEventHandler.bindAsEventListener(this));
	}
 });
 
 
/**
 * PreviewPanel Error Class
 */
 var TPreivewError = Class.create({
 	options: {},
	
 	initialize: function(config) {
		this.options = Object.extend(this.options, config || {});
		
		this.initComponent();
	},
	
	initComponent: function() {
		this.options.target = $(this.options.target);
	},
	
	showMessage: function(type) {
		switch(type) {
			case '':
				this.options.target.update(_LG[28][0]);
			break;
			default :
				this.options.target.update(_LG[28][1]);
			break;
		}
		
		this.show();
	},
	
	hide: function() {
		this.options.target.hide();
	},
	
	show: function() {
		this.options.target.show();
		
//		window.setTimeout(this.hide.bind(this), 3000);
	}
 });
 
 /**
  * PreviewPanel main controller
  */
 var TPreviewPanel = Class.create({
 	options: {
		MAX_TITLE_LENGTH: 40,
		domain: 'cat.dev.itovi.com',
		app: '/app/preview.php',
		max:40,
		isPanelFixed:false,
		pageMode:"main"	// main, blog
	},
	items: undefined,
	initVideo : 0,
	LAST_PID : undefined,
	
 	initialize: function(config) {
		this.options = Object.extend(this.options, config || {});
		
		this.initComponent();
	},
	
	initComponent: function() {
		this.listMgr = new TPreviewList({target:"area_ViewedMovie", elementPrefix:'item_'});
		if(this.options["isPanelFixed"] == false) {
			// squarescope view
			this.switchMgr = new TPreviewSwitch({ target:"area_PreviewPanel", ss:"area_SquareScope", on:"btn_OpenScreen", off:"btn_CloseScreen"});
		} else {
			// list view
			this.switchMgr = null;
		}
//		this.errorMgr = new TPreivewError({target:"area_ErrorMsg"});
		
		this.addEventListener();
		this.videoMessage = $('videoMessage');
		this.videoScreen = $('videoScreen');
		this.totalCounter = $('area_ViewedCount');
		
		this.options.path = 'http://'+ this.options.domain + this.options.app +'?ctt_id=';

		TStateProvider.getItem('list');
		//TStateProvider.removeItem('list');
		/* overwrited squareScope.watch method */
		//squareScope.watch = this.watch.bind(this);
	},
	
	isItem: function(pid) {
		for(var i=0; i<this.items.length; i++) {
			if (this.items[i].PID == pid) {
				return i;
			}
		}
		
		return false;
	},
	
	/**
	 * public
	 * call by flash & other external interface
	 * @param {Object} item	{ PID:123, OPID:321, TITLE:"", PCNT:3, RTIME:25000, THUMBINDEX:2 }
	 * 		item.PID : Content Primary Key
	 * 		item.OPID : Content Original ID
	 * 		item.TITLE : Content Title
	 * 		item.PCNT : Content Preview Count
	 * 		item.RTIME : Content Runtime
	 * 		item.THUMBINDEX : Content Preview Index at click on flash interface
	 */
	watch: function(item) {
		if(this.switchMgr != null && !this.switchMgr.getState()) this.switchMgr.on();
		
		if(this.LAST_PID == item.PID) return;
		this.LAST_PID = item.PID;
		
		var title = item.TITLE.cut(this.options.MAX_TITLE_LENGTH);
		item = { PID:item.PID, OPID:item.OPID, USID:item.USID, TITLE:title, RTIME:item.RTIME, PCNT:item.PCNT, THUMB:item.THUMB, THUMBINDEX:item.THUMBINDEX };

		this.listMgr.append(item);
		this.append(this._encode(item));
		//this.view(item.PID);
	},
	
	view: function(pid) { return;
		if(this.initVideo == 0) {
			this.videoMessage.hide();
			this.videoScreen.show();
			this.initVideo = 1;
		}
		
		this.videoScreen.setAttribute('src', this.options.path + pid);
	},
	
	append: function(item) {
		this.remove(item.PID); 
		
		this.items.splice(0,0, item);

		this._isOver();
		this._syncToProvider();
	},
	
	remove: function(pid) {
		var idx = this.isItem(pid);

		if (typeof idx != 'boolean') {
			this.items.splice(idx, 1);
			this.listMgr.remove(pid);
		}
	},
	
	removeAll: function() {
		var len = this.items.length;
		for(var i=0; i< len; i++) {
			this.remove(this.items[0].PID);
		}
		this.items.length = 0;
		
		this._syncToProvider();
	},
	
	getItem: function(pid) {
		var idx = this.isItem(pid);
		return (typeof idx == 'boolean') ? null : this.items[idx];
	},
	
	_syncToProvider: function() {
		TStateProvider.setItem('list', this.items.toJSON());
		
		this._syncTotalCount();
	},
	
	_syncTotalCount: function() {
		if(this.totalCounter) this.totalCounter.update("("+ this.items.length +")");
	},
	
	_isOver: function() {
		if(this.items.length > this.options.max) {
			var item = this.items[this.options.max] || {};
			this.remove(item.PID);
		}
	},
	
	_encode: function(item) {
		item.TITLE = encodeURIComponent(item.TITLE).replace("'", "\'");
		//delete item.THUMB;
		return item;
	},
	
	_decode: function() {
		var len = this.items.length;
		var item;
		
		for(var i=0; i< len; i++) {
			item = this.items[i];
			
//			item.TITLE = decodeURIComponent(item.TITLE);
//			item.THUMB = variable.vodRoot + "/" + G.getThumb(item.OPID, item.USID, item.THUMBINDEX);
		}
	},
	
	_getHandler: function(event) {
		this.items = event.memo && event.memo.value && event.memo.value.evalJSON() || [];
		this._decode();
		
		if(this.items.length > 0) {
			//if(this.switchMgr != null) this.switchMgr.btnEnable();
			this.view(this.items[0]["PID"]);
			this.listMgr.render(this.items);
		}
//		else this.errorMgr.showMessage();

		this._syncTotalCount();
	},
	
	_setHandler: function(event) {
//		alert(event.memo.value);
	},
	
	_clickHandler: function(event) {
		if(this.LAST_PID == event.memo.PID) return;
		this.LAST_PID = event.memo.PID;
		
		this.view(event.memo.PID);
	},
	
	_removeHandler: function(event) {
		this.remove(event.memo.PID);
		this._syncToProvider();
	},
	
	_overHandler: function(event) {
		var item = this.getItem(event.memo.PID);
	},
	
	_manageHanler: function() {
		var tpl = new Template('최근에 봤던 영상(#{count}개) 목록을 지우시겠습니까?');
		var msg = tpl.evaluate({count:this.items.length});
		if(confirm(msg)) {
			this.removeAll();
		}
	},
	
	_tabClick : function(event) {
		var el = event.target;
		if(el.tagName.toLowerCase() != "a") {
			el = $(el).up();
		}
		
		switch(el.id) {
			case "ppTabVideo" :
					$("area_Mylink").hide();
					$("area_ViewedMovie").show();
					
					$("btn_removeAll").show();
					if($("btn_vodMng")) {
						$("btn_vodMng").hide();
						$("btn_cateMng").hide();
					}
					
					this.tabReset($("ppTabCategory").immediateDescendants(), "off");
				break;
			case "ppTabCategory" :
					$("area_Mylink").show();
					$("area_ViewedMovie").hide();
					
					$("btn_removeAll").hide();
					if($("btn_vodMng")) {
						$("btn_vodMng").show();
						$("btn_cateMng").show();
					}
					
					this.tabReset($("ppTabVideo").immediateDescendants(), "off");
				break;
		}
		this.tabReset(el.immediateDescendants(), "on");
	},
	
	_clickCategory : function(event) {
		var className = "cate_item_on";
		
		var el = $(event.target);
		var cateid = el.getAttribute("cateid");
		if(cateid == null) {
			return false;
			//cateid = 0;
		}
		
		// multivision call
		if(oSquareScope) {
			if(!oSquareScope.changeCategory(el)) {	//cateid
				return false;
			}
			
			var parent = el.up();
			var els = parent.immediateDescendants();
			for(var i=0;i<els.length;i++) {
				if(els[i].hasClassName(className)) {
					els[i].removeClassName(className);
					break;
				}
			}
			
			el.addClassName(className);
		}
	},
	
	tabReset : function(els, flag) {
		var style = {"on":["btnRlt1L", "btnRlt1BG", "btnRlt1R"], "off":["btnRlt1L2", "btnRlt1BG2", "btnRlt1R2"]};
		var on = style[flag];
		var off = style[((flag == "on") ? "off" : "on")];
		for(var i=0;i<els.length;i++) {
			els[i].addClassName(on[i]);
			els[i].removeClassName(off[i]);
		}
	},
	
	addEventListener: function() {
		document.observe("TStateProvider:get", this._getHandler.bindAsEventListener(this));
		
		document.observe("PreviewList:clicktitle" ,this._clickHandler.bindAsEventListener(this));
		document.observe("PreviewList:clickthumb" ,this._clickHandler.bindAsEventListener(this));
		document.observe("PreviewList:clickremove" ,this._removeHandler.bindAsEventListener(this));
		document.observe("PreviewList:overthumb" ,this._overHandler.bindAsEventListener(this));
		Event.observe("btn_removeAll", "click", this._manageHanler.bind(this));
		
		if(this.options["pageMode"] == "blog") {
			Event.observe("ppTabVideo", "click", this._tabClick.bindAsEventListener(this));
			Event.observe("ppTabCategory", "click", this._tabClick.bindAsEventListener(this));
			Event.observe("area_Mylink", "click", this._clickCategory.bindAsEventListener(this));
		}
	},
	
	removeEventListener: function() {
		document.stopObserving("TStateProvider:get", this._getHandler.bindAsEventListener(this));
		
		document.stopObserving("PreviewList:clicktitle" ,this._removeHandler.bindAsEventListener(this));
		document.stopObserving("PreviewList:clickthumb" ,this._removeHandler.bindAsEventListener(this));
		document.stopObserving("PreviewList:clickremove" ,this._removeHandler.bindAsEventListener(this));
		document.stopObserving("PreviewList:overthumb" ,this._overHandler.bindAsEventListener(this));
		Event.stopObserving("btn_removeAll", "click", this._manageHanler.bind(this));
		
		if(this.options["pageMode"] == "blog") {
			Event.stopObserving("ppTabVideo", "click", this._tabClick.bindAsEventListener(this));
			Event.stopObserving("ppTabCategory", "click", this._tabClick.bindAsEventListener(this));
			Event.stopObserving("area_Mylink", "click", this._clickCategory.bindAsEventListener(this));
		}
	}
 });
 
 
//document.observe("dom:loaded", function() { 
Event.observe(window, "load", function() { 
	/* SharedObject controller for JavaScript */
	TStateProvider.create();
	TStateProvider.setup("*");
});
