/*
 *	Focus Pvideo Library
 *
 *	Copyright (c) 2009 Focus Imaging Limited - http://www.focus-global.com
 */


pvideo = {
	
	langData: null,
	init: function( current_time ){
		pvideo.clock.init( current_time );
		
		$('img.rollover')
			.bind('mouseover',function(event){ pvideo.img.mouseover(this); })
			.bind('mouseout',function(event){ pvideo.img.mouseout(this); });
		

		pvideo.langData = new Array();
		//alert('');
		$.get('/common/lang/', '', function(xml){
			var result = $(xml).find('data').each(function(){
				var data = $(this);
				pvideo.langData[ data.attr('id') ] = data.text();
			});			
		}, 'xml');
	},

	bookmarksite: function(){
		if (window.sidebar) // firefox
		{
			window.sidebar.addPanel(document.title, location.href, "");
		}
		else if(window.opera && window.print) // opera
		{
			var elem = document.createElement('a');
			elem.setAttribute('href',location.href);
			elem.setAttribute('title',document.title);
			elem.setAttribute('rel','sidebar');
			elem.click();
		} 
		else if(document.all) // ie
		{
			window.external.AddFavorite(location.href, document.title);
		}
	},
	
	clock: {
		current: null,
		init: function( current_time )
		{
			pvideo.clock.current = new Date(current_time);
			setInterval("pvideo.clock.refresh()", 1000);
		},
		padZero: function(what){
			return (what.toString().length==1) ? '0' + what : what;
		},
		refresh: function()
		{
			pvideo.clock.current.setSeconds( pvideo.clock.current.getSeconds()+1 );
			var s = pvideo.clock.padZero(pvideo.clock.current.getHours())+":"+ pvideo.clock.padZero(pvideo.clock.current.getMinutes())+":"+ pvideo.clock.padZero(pvideo.clock.current.getSeconds());
			$('#pvideo_clock').html( s );
		}
	},
		
	dialogSystem : {
		selector: '#dialogSystem_div',
		close: function(){
			//$(this.selector).dialog('close');
			//alert('close' + this.selector);
			$(this.selector).dialog('close');
			//alert('closed');
		},
		showLoading: function(){
			$(this.selector)
				.html('Loading...')
				.dialog( {bgiframe:true,closeOnEscape:false,modal:true,resizable:false} )
				.dialog('option', 'buttons', {  } )
				.dialog('open');
		},
		showFailed: function( msg ){	
			msg = pvideo.lang(msg);
			$(this.selector)
				.html( 'Error:' + msg )
				.dialog( {bgiframe:true,closeOnEscape:false,modal:true,resizable:false} )
				.dialog('option', 'buttons', {'Close': function(){pvideo.dialogSystem.close();} } )
				.dialog('open');
		},
		showMsg: function( msg, action, url, msg2 ){
			msg = pvideo.lang(msg);
			if( typeof(msg2)!='undefined' ){
				if( typeof(pvideo.lang(msg2))!='undefined' ){
					msg += "\n" + pvideo.lang(msg2);
				}
			}
			
			var func_str;
			switch (action){
				case 'url':
					func_str = 'pvideo.dialogSystem.close();window.location.href=\'' +url +'\';';
					break;
				case 'quit_to_home':
					func_str = 'pvideo.dialogSystem.close();window.location.href=\'/\';';
					break;
				case 'reload':
					func_str = 'void(0);window.location.reload();';
					break;	
				default:
					func_str = 'pvideo.dialogSystem.close();';
					break;
			}
			$(this.selector)
				.html( msg )
				.dialog( {bgiframe:true,closeOnEscape:false,modal:true,resizable:false} )
				.dialog('option', 'buttons', {'Close': function(){ eval(func_str); } } )
				.dialog('open');
		},
		showMsgOnTheFly: function( msg ){
			msg = pvideo.lang(msg);
			var func_str;
			func_str = 'void(0);window.location.href = window.location.href;';
			var div = document.createElement('div');
			div.id = 'div_msg_onthefly';
			$("div:first").prepend(div);
			$("div#div_msg_onthefly")
				.html( msg )
				.dialog( {bgiframe:true,closeOnEscape:false,modal:true,resizable:false} )
				.dialog('option', 'buttons', {'Close': function(){ eval(func_str); } } )
				.dialog('open');
		}
	},

	friend: {
		doAction: function(uname, mode, id){
			if (uname != '')
			{
				var proceed = true;
				if ( (mode == 'remove') && (!confirm('確定嗎?')) )
				{
					proceed = false;
				}
				if(proceed)
				{
					$.post( "/purl/" +uname +"/friends", { action: mode, id: id }, function(xml){ pvideo.general.result(xml, '#friends', 'reload') }, 'xml' );
				}
			}
		}
	},
	
	general: {
		result: function( xml, hash_id, action ){
			var result = $(xml).find(hash_id).text();
			if( result=='failed' )
			{
				pvideo.dialogSystem.close();
				pvideo.dialogSystem.showFailed('LANG_FAILED');
			}
			else
			{
				pvideo.dialogSystem.showMsg('LANG_SUCCESS', action);
			}
		}
	},
	
	img: {
		mouseover: function( el ){
			var el = $(el);
			el.attr('src', el.attr('src').replace('rollout', 'rollover') );
		},
		mouseout: function( el ){
			var el = $(el);
			el.attr('src', el.attr('src').replace('rollover', 'rollout') );
		}
	},

	lang: function( s )
	{
		return pvideo.langData[s];
		//return s;
	},
	
	pm: {
		send: function( usernmae ){
			pvideo.dialogSystem.showLoading();
			var data = { 
				msg_recipient_name: $("#f_pm_editor input[name=msg_recipient_name]").val(), 
				msg_title: $("#f_pm_editor input[name=msg_title]").val(), 
				msg_content: $("#f_pm_editor textarea[name=msg_content]").val()
			};
			$.post( $('#f_pm_editor').attr('action'), data, function(xml){  pvideo.pm.sendResult(xml, usernmae) }, 'xml' );
		},
		sendResult: function( xml, uname ){
			var result = $(xml).find("#pm").text();
			if( result.indexOf('success') >= 0 ){
				pvideo.dialogSystem.showMsg( 'LANG_SUCCESS', 'url', '/purl/' + uname.replace(/'/gi, '\\\'')+ '/pm/outbox');
			}
			else{
				pvideo.dialogSystem.close();
				pvideo.dialogSystem.showFailed('LANG_FAILED');
			}
		}
	},
	
	login: function(){
		//alert( 'login' );
		pvideo.dialogSystem.showLoading();
		var data = { username: $('#frm_login input[name=username]').val(), password: $('#frm_login input[name=password]').val(), url: $('#frm_login input[name=url]').val() };
		//alert( $('#frm_login').attr('action') );
		$.post( $('#frm_login').attr('action'), data, function(xml){ pvideo.session.loginResult(xml) }, 'xml' );
	},
	
	logout: function(){
		$.post( '/member/logout', '', function(xml){ pvideo.session.logoutResult(xml) }, 'xml' );
	},
	
	session: {
		loginResult: function( xml ){
			var result = $(xml).find('#login').text();
			var prompt_url = $(xml).find('#prompt_url').text();
			if( result=='success' )
			{
				if( (typeof(prompt_url)!='undefined') && (prompt_url!='') ){
					$('#frm_login input[name=url]').val(prompt_url);
				}
				setTimeout("pvideo.session.loginRedirect()",1000);
			}
			else
			{
				pvideo.dialogSystem.close();
				pvideo.dialogSystem.showFailed('LANG_LOGIN_FAILED');
			}
		},
		loginRedirect: function(){
			window.location.href = ( $('#frm_login input[name=url]').val()=='/member/login' ) ? '/' : $('#frm_login input[name=url]').val();
			//window.location.href = '/purl/' + $('#frm_login input[name=username]').val();
		},
		logoutResult: function( xml ){
			var result = $(xml).find('#logout').text();
			if( result=='success' )
			{
				//window.location.reload();
				window.location.href = '/';
			}
			else
			{
				pvideo.dialogSystem.showFailed('LANG_LOGOUT_FAILED');
			}
		},
		
		
		/*to be assimilated*/
		pmResult: function( xml, uname ){
			var result = $(xml).find("#pm").text();
			if( result.indexOf('success') >= 0 ){
				pvideo.dialogSystem.showMsg('LANG_SUCCESS', 'url', '/purl/' + uname.replace(/'/gi, '\\\'')+ '/pm/outbox');
			}
			else{
				pvideo.dialogSystem.close();
				pvideo.dialogSystem.showFailed('LANG_FAILED');
			}
		},
		registerResult: function( xml ){
			var result = $(xml).find('#register').text();
			//alert(result);
			if( result=='success' )
			{
				pvideo.dialogSystem.showMsg('LANG_EMAIL_SENT', 'quit_to_home');
			}
			else
			{
				pvideo.dialogSystem.close();
				pvideo.dialogSystem.showFailed(result);
			}
		},
		generalResult: function( xml, hash_id, action ){
			var result = $(xml).find(hash_id).text();
			if( result=='failed' )
			{
				pvideo.dialogSystem.close();
				pvideo.dialogSystem.showFailed('LANG_FAILED');
			}
			else
			{
				pvideo.dialogSystem.showMsg('LANG_SUCCESS', action);
			}
		},
		generalResult2: function( xml, hash_id, action, param1 ){
			var result = $(xml).find(hash_id).text();
			if( result=='failed' )
			{
				pvideo.dialogSystem.close();
				pvideo.dialogSystem.showFailed('LANG_FAILED');
			}
			else
			{
				pvideo.dialogSystem.showMsg('LANG_SUCCESS', action, param1);
			}
		},
		updateProfileResult: function( xml, action ){
			var result_info = $(xml).find('#profile_update').text();
			var result_pwd = $(xml).find('#password_update').text();
			
			var pmsg;
			if (result_pwd=='success'){
				pmsg = 'LANG_CHANGE_PASSWORD_SUCCESS';
			}else if(result_pwd=='failed'){
				pmsg = 'LANG_CHANGE_PASSWORD_FAILED';
			}
			if( result_info=='success' )
			{
				pvideo.dialogSystem.showMsg('LANG_PROFILE_CHANGE_SUCCESS', action, pmsg);
			}
			else
			{
				pvideo.dialogSystem.close();
				pvideo.dialogSystem.showFailed('LANG_PROFILE_CHANGE_FAILED');
			}
		},
		changePasswordResult: function( xml ){
			var result = $(xml).find('#change_password').text();
			//alert(result);
			if( result=='failed' )
			{
				pvideo.dialogSystem.close();
				pvideo.dialogSystem.showFailed('LANG_CHANGE_PASSWORD_FAILED');
			}
			else
			{
				pvideo.dialogSystem.showMsg('LANG_CHANGE_PASSWORD_SENT', 'quit_to_home');
			}
		}
		
	},
	
	scroller: {
		intval: null,
		init: function( selector, speed ){
			if( typeof(speed)=='underfind' )
			{
				speed = 50;
			}
			var parentBox = $(selector);
			parentBox.find('.scroller-forward')
				.bind('mouseover',function(event){ pvideo.scroller.next( selector, speed ); })
				.bind('mouseout',function(event){ pvideo.scroller.stop(); });
			parentBox.find('.scroller-backward')
				.bind('mouseover',function(event){ pvideo.scroller.prev( selector, speed ); })
				.bind('mouseout',function(event){ pvideo.scroller.stop(); })
				.css('display', 'none');
		}, 
	
		move: function( mode, selector) {		
			var parentBox = $(selector);
			var box = parentBox.find('.scroller-mainbody');
			var max = box.attr('scrollWidth') - box.width();
			
			if (mode == 'next') {
				if ( box.scrollLeft() == max ) {
					parentBox.find('.scroller-forward').css('display', 'none');
				}
				else {
					parentBox.find('.scroller-backward').css('display', '');
					box.scrollLeft(box.scrollLeft() + 1 );
				}										
			}
			else {
				if ( box.scrollLeft() == 0) {
					parentBox.find('.scroller-backward').css('display', 'none');
				}
				else {	
					parentBox.find('.scroller-forward').css('display', '');
					box.scrollLeft(box.scrollLeft() - 1 );										
				}
			}
		},
		
		next: function( selector, speed ){
			pvideo.scroller.intval = setInterval("pvideo.scroller.move('next', '"+ selector +"')", speed );
		},
		
		prev: function( selector, speed ){
			pvideo.scroller.intval = setInterval("pvideo.scroller.move('prev', '"+selector+"')", speed );
		},
		
		stop: function(){
			window.clearInterval(pvideo.scroller.intval);
		}
	
	},
	
	vscroller: {
		intval: null,
		init: function( selector, speed ){
			if( typeof(speed)=='underfind' )
			{
				speed = 50;
			}
			var parentBox = $(selector);
			parentBox.find('.vscroller-up')
				.bind('mouseover',function(event){ pvideo.vscroller.up( selector, speed ); })
				.bind('mouseout',function(event){ pvideo.vscroller.stop(); })
				.css('display', 'none');
			parentBox.find('.vscroller-down')
				.bind('mouseover',function(event){ pvideo.vscroller.down( selector, speed ); })
				.bind('mouseout',function(event){ pvideo.vscroller.stop(); });			
		}, 
	
		move: function( mode, selector) {		
			var parentBox = $(selector);
			var box = parentBox.find('.vscroller-mainbody');
			var max = box.attr('scrollHeight') - box.height();
			
			if (mode == 'down') {
				if ( box.scrollTop() == max ) {
					parentBox.find('.vscroller-down').css('display', 'none');
				}
				else {
					parentBox.find('.vscroller-up').css('display', '');
					box.scrollTop(box.scrollTop() + 1 );
				}										
			}
			else {
				if ( box.scrollTop() == 0) {
					parentBox.find('.vscroller-up').css('display', 'none');
				}
				else {	
					parentBox.find('.vscroller-down').css('display', '');
					box.scrollTop(box.scrollTop() - 1 );										
				}
			}
		},
		
		up: function( selector, speed ){
			pvideo.vscroller.intval = setInterval("pvideo.vscroller.move('up', '"+ selector +"')", speed );
		},
		
		down: function( selector, speed ){
			pvideo.vscroller.intval = setInterval("pvideo.vscroller.move('down', '"+selector+"')", speed );
		},
		
		stop: function(){
			window.clearInterval(pvideo.vscroller.intval);
		}
	
	},
				
	register_submit: function(){
		pvideo.dialogSystem.showLoading();
		var data = { 
			login: $('#registerform input[name=login]').val(), 
			login_chk: $('#registerform input[name=login_chk]').val(), 
			nickname: $('#registerform input[name=nickname]').val(), 
			email: $('#registerform input[name=email]').val(), 
			password: $('#registerform input[name=password]').val(), 
			password2: $('#registerform input[name=password2]').val(), 
			sex: $('#registerform select[name=sex]').val(),
			first_name: $('#registerform input[name=first_name]').val(), 
			last_name: $('#registerform input[name=last_name]').val(), 
			birthday_year: $('#registerform select[name=birthday_year]').val(), 
			birthday_month: $('#registerform select[name=birthday_month]').val(), 
			birthday_day: $('#registerform select[name=birthday_day]').val()
		};
		
		$.post( $('#registerform').attr('action'), data, function(xml){ pvideo.session.registerResult(xml) }, 'xml' );
	},
	
	join_student_channel: function(){
		pvideo.dialogSystem.showLoading();
		var data = { 
			school_id_P: $('#registerform input[name=school_id_P]').val(), 
			school_id_S: $('#registerform input[name=school_id_S]').val(), 
			school_id_U: $('#registerform input[name=school_id_U]').val()
		};
		$.post( $('#registerform').attr('action'), data, function(xml){ pvideo.session.generalResult2(xml, '#join_channel', 'url', '/') }, 'xml' );
	},
	
	/*to be assimilated*/
	send_pm: function( usernmae ){
		pvideo.dialogSystem.showLoading();
		var data = { 
			msg_recipient_name: $("#f_pm_editor input[name=msg_recipient_name]").val(), 
			msg_title: $("#f_pm_editor input[name=msg_title]").val(), 
			msg_content: $("#f_pm_editor textarea[name=msg_content]").val()
		};
		$.post( $('#f_pm_editor').attr('action'), data, function(xml){  pvideo.session.pmResult(xml, usernmae) }, 'xml' );
	},
	doFriendsAction: function(uname, mode, id){
		if (uname != '')
		{
			var proceed = true;
			if ( (mode == 'remove') && (!confirm('確定嗎?')) )
			{
				proceed = false;
			}
			if(proceed)
			{
				$.post( "/purl/" +uname +"/friends", { action: mode, id: id }, function(xml){ pvideo.session.generalResult(xml, '#friends', 'reload') }, 'xml' );
			}
		}
	},
	profile_edit_submit: function(f){
		var f = $(f);
		//alert(f);
		switch( f.find("input[name=about]").val() ){
			case 'account':
				var data = {
					about: f.find("input[name=about]").val(), 
					nick: f.find("input[name=nick]").val(), 
					email: f.find("input[name=email]").val(),
					npw_current: f.find("input[name=npw_current]").val(), 
					npw: f.find("input[name=npw]").val(), 
					npw_chk: f.find("input[name=npw_chk]").val()
				};
				$.post( f.attr('action'), data, function(xml){  pvideo.session.updateProfileResult(xml, 'reload') }, 'xml' );
				//$.post( f.attr('action'), data, function(xml){ alert(xml) ; pvideo.session.updateProfileResult(xml, 'reload') }, 'text' );
				break;
			case 'general':
				var ctrls_int = f.find("input[name=inte[]]:checked");
				var int_vals = '';
				for( var i=0; i<ctrls_int.length; i++ )
				{
					int_vals += ',' + ctrls_int.eq(i).val();
				}
				var data = {
					about: f.find("input[name=about]").val(), 
					fn: f.find("input[name=fn]").val(), 
					ln: f.find("input[name=ln]").val(), 
					sx: f.find("input[name=sx]:checked").val(), 
					bd_y: f.find("select[name=bd_y]").val(), 
					bd_m: f.find("select[name=bd_m]").val(), 
					bd_d: f.find("select[name=bd_d]").val(), 
					occ: f.find("input[name=occ]").val(), 
					inte: int_vals, 
					inf: f.find("textarea[name=inf]").val(), 
					des: f.find("textarea[name=des]").val(), 
					phone: f.find("input[name=phone]").val(), 
					mob: f.find("input[name=mob]").val(), 
					fax: f.find("input[name=fax]").val(), 
					web: f.find("input[name=web]").val(), 
					cfr: f.find("input[name=cfr]").val(),
					add: f.find("input[name=add]").val()
				};
				//$.post( f.attr('action'), data, function(xml){ alert(xml); pvideo.session.updateProfileResult(xml, 'reload') }, 'text' );
				$.post( f.attr('action'), data, function(xml){ pvideo.session.generalResult(xml, '#profile_update', 'reload') }, 'xml' );
				
				break;
			case 'student_channel':
				var data = {
					about: f.find("input[name=about]").val(), 
					school_id_P: f.find("input[name=school_id_P]").val(), 
					school_id_S: f.find("input[name=school_id_S]").val(), 
					school_id_U: f.find("input[name=school_id_U]").val()
				};
				$.post( f.attr('action'), data, function(xml){ pvideo.session.generalResult(xml, '#profile_update', 'reload') }, 'xml' );
				break;
			default:
			break;
		}

	},
	reset_password_submit: function(){
		pvideo.dialogSystem.showLoading();
		var data = { 
			login: $('#frm_reset_password input[name=login]').val(), 
			password: $('#frm_reset_password input[name=password]').val(), 
			confirm_code: $('#frm_reset_password input[name=confirm_code]').val() 
		};
		$.post( $('#frm_reset_password').attr('action'), data, function(xml){ pvideo.session.generalResult(xml, '#reset_password', 'quit_to_home') }, 'xml' );
	},
	change_password: function(){
		pvideo.dialogSystem.showLoading();
		var data = { nickname: $('#frm_login input[name=nickname]').val(), email: $('#frm_login input[name=recover_email]').val() };
		$.post( $('#frm_login').attr('action'), data, function(xml){  pvideo.session.changePasswordResult(xml) }, 'xml' );
	},
	/*
	login: function(){
		pvideo.dialogSystem.showLoading();
		var data = { username: $('#frm_login input[name=username]').val(), password: $('#frm_login input[name=password]').val() };
		$.post( $('#frm_login').attr('action'), data, function(xml){ pvideo.session.loginResult(xml) }, 'xml' );
	},
	logout: function(){
		$.post( '/member/logout', '', function(xml){ pvideo.session.logoutResult(xml) }, 'xml' );
	},
	*/
	'dummy': ''
};

