/**
 * @author Poowanai Suwanahong, Mobus Development Team
 * @copyright: Mobus Co., Ltd.
 * @package: WOS Page library
 * @license: Mobus Co., Ltd.
 * @url: http://www.mobus.co.th
 * @version: 1.00
 * @dependencies prototype.js, scriptaculous.js
 * @Revision 1, Complete
 */

/*** ***/

/********* SMS box  *********/
var gSMSChatEnabled = false;				// TEST
var gSMSVoteEnabled = false;				// TEST
var gMobileAppEnabled = false;

var smsChatPaging;
var mobileFanclubPaging;
var mobileBlockPaging;
				
var smsChatPaging;
var gSmsChatListUrl;
var gSmsChatCodeDlg;
var gSmsVoteCodeDlg;
var gRegisterMobileDlg;
var gMobileFanclubDlg;
var gMobileBlockListDlg;
var gSmsCodeContentId;
var gMobileAppType;

function initSMSContent(t, id) {
	gMobileAppType = t;
	gSmsCodeContentId = id;
	getProfileMobileApp();
}

function enableSMSContent() {
	if (gSMSChatEnabled) {
		initSMSChat();
	}
	if (gSMSVoteEnabled) {
		initSMSVote();
	}
	if (gMobileAppEnabled) {
		initMobileDlg();
		initSmsControlBox();
		getSmsChatList(gSmsCodeContentId);	
	}
}

function getProfileMobileApp() {
	var dtRf = new Date().getTime();
	var url = '';
	var urlParam = '';
	if (gMobileAppType == 'user') {
		url = encodeAjaxParamUrl('getProfileMobileApplicationTypeByUserId', 'rf', dtRf);
		urlParam = {'userId':gSmsCodeContentId};	
	} else if (gMobileAppType == 'audio') {
		url = encodeAjaxParamUrl('getAudioMobileApplicationTypeByAudioId', 'rf', dtRf);
		urlParam = {'audioId':gSmsCodeContentId};	
	} else if (gMobileAppType == 'video') {
		url = encodeAjaxParamUrl('getVideoMobileApplicationTypeByVideoId', 'rf', dtRf);
		urlParam = {'videoId':gSmsCodeContentId};	
	} else if (gMobileAppType == 'photo') {
		url = encodeAjaxParamUrl('getPhotoMobileApplicationTypeByPhotoId', 'rf', dtRf);
		urlParam = {'photoId':gSmsCodeContentId};	
	}
	
	var wosAjax = new Ajax.Request(url,{
		method: 'post',
		parameters: urlParam,
		onComplete: function(transport) {
			var sJSON = transport.responseText;
			var json = window.decodeJSON(sJSON);
			if (json.notification.summary.type=="ERROR") {					
				window.requestPageCompleteWithError(json.notification.summary.value);
			} else if(json.notification.summary.type=="INFO") {
				decodeMobileAppType(json.data.mobileApplicationType);
				enableSMSContent();
			}
		}, 
		onFailure: function(error) {
			window.requestPageFailure(error);
		}
	});
}

function decodeMobileAppType(enType) {
		var s = enType;
		if (s == "") {
			gMobileAppEnabled = false;
		} else {
			gMobileAppEnabled = true;
			var appType = s.split(",");
			for (var i = 0; i < appType.length; i ++) {
				if (appType[i] == "VOTE") {
					gSMSVoteEnabled = true;
				}
				if (appType[i] == "CHAT") {
					gSMSChatEnabled = true;
				}
				if (appType[i] == "ITEM") {
				}
			} 
		}
}

function initSMSChat() {
	$('mobileAppBox').show();
}

function initSMSVote() {
	$('mobileVoteBtn').show();
}

function initSmsControlBox() {
	if(gAuthority) {
		$('sms-list-edit').show();
	}
}


function getSmsChatList(cId) {
	var dtRf = new Date().getTime();	
	var urlParam = '';
	if (gMobileAppType == 'user') {
		gSmsChatListUrl = window.encodeAjaxParamUrl('getSmsChatProfileList', 'rf', dtRf);
		urlParam = {'userId':cId};	
	} else if (gMobileAppType == 'audio') {
		gSmsChatListUrl = window.encodeAjaxParamUrl('getSmsChatAudioList', 'rf', dtRf);
		urlParam = {'audioId':cId};
	} else if (gMobileAppType == 'video') {
		gSmsChatListUrl = window.encodeAjaxParamUrl('getSmsChatVideoList', 'rf', dtRf);
		urlParam = {'videoId':cId};
	} else if (gMobileAppType == 'photo') {
		gSmsChatListUrl = window.encodeAjaxParamUrl('getSmsChatPhotoList', 'rf', dtRf);
		urlParam = {'photoId':cId};
	}
	window.smsChatPaging = new WosPagination({
		objName: 'smsChatPaging',
		firstResult: 0,
		maxResults: 5,
		pagingRange: 0,
		recordDisplay: 5,
		preLink: 'prev_smsChatPage',																			
		nextLink: 'next_smsChatPage',																			
		url: gSmsChatListUrl,
		params: urlParam,			
		pageNumView: 'currentPageRange_smsChatPage',								
		pageControl: 'currentRec_smsChatPage',												
		dataView: 'view_smsListBox',																				
		drawTable: function(page, contain) {
			var data = "data";
			var recordList = '';
			if (gMobileAppType == 'user') {
				recordList = '<ol class="smsProfileList">';	
			} else {
				recordList = '<ol class="smsContentList">';	
			}
			for(var i =0; i < page[data].records.length; i++) {
				recordList += '<li>' +
						'<div class="smsDetailBox" style="clear:both;">' +
							'<div class="smsHeadPanel" style="clear:both;">' +
								'<span class="left"><strong>'+ page[data].records[i].simName + '</strong> <b>'+ page[data].records[i].simNumber + '</b>';
				if (gAuthority) {
				recordList += '<em>&nbsp;sent&nbsp;'+ window.renderDateTime(page[data].records[i].dateCreated) + '</em></span>';
				} else {
				recordList += '<em>&nbsp;sent&nbsp;'+ window.renderDateTime(page[data].records[i].dateCreated) + '</em></span>';	
				}
				if (gAuthority) {
					if (page[data].records[i].simState == 'UNBLOCK') {
	recordList += 	'<span class="right"><a onclick="javascript:autoHideSmsChatForPhoneNumber(\''+ page[data].records[i].id + '\');" href="javascript:void(0);" title="Block SMS from this mobile number">Block</a></span>';
					} else if (page[data].records[i].simState == 'BLOCK') {
	recordList += 	'<span class="right"><a onclick="javascript:updateBlockedSimStateBySmsId(\''+ page[data].records[i].id + '\');" href="javascript:void(0);" title="Unblock SMS from this mobile number">Unblock</a></span>';
					}
				}
	recordList += '</div>';
				if (page[data].records[i].displayState == 'SHOW') {							
	recordList += '<p class="smsText">'+ page[data].records[i].inboundText + '</p>';
				} else if (page[data].records[i].displayState == 'HIDE') {		
	recordList += '<p class="smsText" style="color: #DDDDDD">'+ page[data].records[i].inboundText + '</p>';				
				}
	recordList += '<div class="smsPanel">' +
								'<span class="left">' +
									// '<a onclick="javascript:reportAbusedSmsChat(\''+ page[data].records[i].id + '\');" href="javascript:void(0);" title="Report abuse this SMS">Report abuse</a>' +
								'</span>' +
								'<span class="right">';
		if (gAuthority) {
				if (page[data].records[i].displayState == 'SHOW') {
					recordList += '<a onclick="javascript:hideSmsChat(\''+ page[data].records[i].id + '\');" href="javascript:void(0);"  title="Hide this SMS">Hide this SMS</a>';	
				} else if (page[data].records[i].displayState == 'HIDE') {
					recordList += '<a onclick="javascript:showSmsChat(\''+ page[data].records[i].id + '\');" href="javascript:void(0);" title="Show this SMS">Show this SMS</a>';
				}
		}
		if (page[data].records[i].acknowledgeState == 'NO') {
			if (gAuthority) {
			recordList += '&nbsp;|&nbsp;<a onclick="javascript:toggleSmsReplyBox(\''+ page[data].records[i].id + '\');" href="javascript:void(0);" title="Reply this SMS">Reply this SMS</a>';
			}
		} else {
			if (gAuthority) {
				recordList += '&nbsp;|&nbsp;<a onclick="javascript:toggleSmsReplyBox(\''+ page[data].records[i].id + '\');" href="javascript:void(0);" title="Reply this SMS">Show replied</a>';
			} else {
				recordList += '&nbsp;<a onclick="javascript:toggleSmsReplyBox(\''+ page[data].records[i].id + '\');" href="javascript:void(0);" title="Reply this SMS">Show replied</a>';	
			}
		}
		recordList += '</span>' +
							'</div>' +
						'</div>' +
						'<div style="display: none;" class="replyBox" id="sms_reply'+ page[data].records[i].id + '">';
	if (page[data].records[i].acknowledgeState == 'YES') {
		recordList += '<div class="repliedText"><p>' + window.pUsername + ' replied </p><p id="sms_reply'+ page[data].records[i].id + '">'+ page[data].records[i].outboundText + '</p></div>';
	} else {
	recordList += '<form id="replyForm'+ page[data].records[i].id + '" name="replyForm'+ page[data].records[i].id + '" class="replyForm">' +
								'<div>' +
									'<p><label class="reply">Reply to '+ page[data].records[i].simName + '</label></p>' +
									'<p><textarea name="replyBody" id="i_sms_reply'+ page[data].records[i].id + '" wrap="physical" onKeyDown="javascript:window.textCounter(document.replyForm'+ page[data].records[i].id + '.i_sms_reply'+ page[data].records[i].id + ',document.replyForm'+ page[data].records[i].id + '.remLen'+ page[data].records[i].id + ',140);" onKeyUp="javascript:window.textCounter(document.replyForm'+ page[data].records[i].id + '.i_sms_reply'+ page[data].records[i].id + ',document.replyForm'+ page[data].records[i].id + '.remLen'+ page[data].records[i].id + ',140);"></textarea></p>' +
									'<p><input class="remLen" readonly type="text" name="remLen'+ page[data].records[i].id + '" size="3" maxlength="3" value="140"  onkeypress="return focusNext(this.form, \'reply-btn-'+ page[data].records[i].id + '\', event)"> characters left</p>' +
								'</div>' +
								'<div>' +
									'<p class="replyPanel">' +
										'<input  id="reply-btn-'+ page[data].records[i].id + '" type="button" class="reply_btn" onclick="javascript:sendSmsReply(\''+ page[data].records[i].id + '\');" value="Add Reply" />' +
										'<input type="button" class="reply_btn" onclick="javascript:hideSmsReplyBox(\''+ page[data].records[i].id + '\');" value="Cancel" />' +
									'</p>' +
								'</div>' +
							'</form>';
	}					
recordList += '</div>' +
					'</li>';
			}
			recordList += '</ol>';
			contain.update(recordList);
			if (page[data].totalRecords == 0) {
				disableSmsChatPageController();
			} else if (page[data].totalRecords <= 5) {
				disableSmsChatPageController();
			} else {
				enableSmsChatPageController();
			}
		}
	});	
}

function disableSmsChatPageController() {
	$('smsChatPageController').hide();
}

function enableSmsChatPageController() {
	$('smsChatPageController').show();
}

function resetSMSChatParam() {
	window.smsChatPaging.firstResult = 0;
	window.smsChatPaging.maxResults = 5;
	window.smsChatPaging.pagingRange = 0;
	window.smsChatPaging.recordDisplay = 5;
	window.smsChatPaging.startPage = 1;
	window.smsChatPaging.getTableData();
}

function getSmsChatInvitation(cType, cId) {
	
}

function updateSmsChatInvitation(cType, cId) {
	
}


/** SMS Code dialogue **/

function initMobileDlg() {
	gSmsChatCodeDlg = new Control.Modal(false, {
		containerClassName: 'beta',
		overlayClassName: 'blue',
		width: 820,
		height: 300,
		overlayCloseOnClick: true,
		contents: function() {
			return  '<div class="dlgWhiteBox_container">' +
								'<div class="dlgWhiteBox_top"><span class="right"><input  id="sms-chat-close-button" type="button" value="Close" /></span></div>' +
								'<div class="dlgWhiteBox_middle">' +
									'<div class="sms_codeInfo_container">' + 
										'<div id="smsChatCodeInfo">' +
											'<div class="mobileCode">' +
												'<h4>ให้กำลังใจโดยการพูดคุยผ่านระบบ SMS</h4>' +
												'<div id="view_chatCode" ></div>' +
											'</div>' +
											'<div class="mobile-remark">เพื่อนๆ สามารถเข้าร่วม Fan Club ของ ' + window.pUsername + ' ได้ทันทีหลังส่ง SMS (ส่วนหนึ่งของทุก SMS จะเป็นแรงใจกลับคืนสู่ ' + window.pUsername + ' )</div>' +
											'<p style="text-align:right;"></p>' +
										'</div>' +
									'</div>' +
								'</div>' +
								'<div class="dlgWhiteBox_bottom">&nbsp;</div>' +
							'</div>';
		},		
		afterOpen: function() {
			var _closeButton = $('sms-chat-close-button');
			Event.observe(_closeButton, 'click', closeSmsDialogue.bindAsEventListener(this));
			getSmsChatCode(gSmsCodeContentId);
		}						
	});
	
	gSmsVoteCodeDlg = new Control.Modal(false, {
		containerClassName: 'beta',
		overlayClassName: 'blue',
		width: 820,
		height: 300,
		overlayCloseOnClick: true,
		contents: function() {
			return  '<div class="dlgWhiteBox_container">' +
								'<div class="dlgWhiteBox_top"><span class="right"><input  id="sms-vote-close-button" type="button" value="Close" /></span></div>' +
								'<div class="dlgWhiteBox_middle">' +
									'<div class="sms_codeInfo_container">' + 
										'<div id="smsVoteCodeInfo">' +
											'<div class="mobileCode">' +
												'<h4>ให้กำลังใจโดยการโหวตผ่านระบบ SMS</h4>' +
												'<div id="view_voteCode" ></div>' +
											'</div>' +
											'<div class="mobile-remark">เพื่อนๆ สามารถเข้าร่วม Fan Club ของ ' + window.pUsername + ' ได้ทันทีหลังส่ง SMS (ส่วนหนึ่งของทุก SMS จะเป็นแรงใจกลับคืนสู่ ' + window.pUsername + ' )</div>' +
											'<p style="text-align:right;"></p>' +
										'</div>' +
									'</div>' +
								'</div>' +
								'<div class="dlgWhiteBox_bottom">&nbsp;</div>' +
							'</div>';
		},		
		afterOpen: function() {
			var _closeButton = $('sms-vote-close-button');
			Event.observe(_closeButton, 'click', closeSmsDialogue.bindAsEventListener(this));
			getSmsVoteCode(gSmsCodeContentId);
		}						
	});
	
	gRegisterMobileDlg = new Control.Modal(false, {
		containerClassName: 'beta',
		overlayClassName: 'blue',
		width: 820,
		height: 400,
		overlayCloseOnClick: true,
		contents: function() {
			return  '<div class="dlgWhiteBox_container">' +
								'<div class="dlgWhiteBox_top"><span class="right"><input  id="register-mobile-close-button" type="button" value="Close" /></span></div>' +
								'<div class="dlgWhiteBox_middle">' +
									'<div class="sms_codeInfo_container">' + 
										'<div id="registerMobileInfo">' +
											'<div>' +
												'<p>ลงทะเบียนมือถือโดยพิมพ์ชื่อ แล้วส่งมาที่</p>' +
												'<img src="" />' +
											'</div>' +
											'<p style="text-align:right;"></p>' +
										'</div>' +
									'</div>' +
								'</div>' +
								'<div class="dlgWhiteBox_bottom">&nbsp;</div>' +
							'</div>';
		},		
		afterOpen: function() {
			var _closeButton = $('register-mobile-close-button');
			Event.observe(_closeButton, 'click', closeSmsDialogue.bindAsEventListener(this));
		}						
	});
	
	gMobileFanclubDlg = new Control.Modal(false, {
		containerClassName: 'beta',
		overlayClassName: 'blue',
		width: 820,
		height: 420,
		overlayCloseOnClick: true,
		contents: function() {
			return  '<div class="dlgWhiteBox_container">' +
								'<div class="dlgWhiteBox_top"><span class="right"><input  id="mobile-fanclub-close-button" type="button" value="Close" /></span></div>' +
								'<div class="dlgWhiteBox_middle">' +
									'<div class="sms_codeInfo_container">' + 
										'<div id="mobileFCInfo">' +
											'<div id="mobileFCBoxList">' +
												'<h4>' + window.pUsername +'\'s Mobile Fanclub</h4>' +
												'<div id="mobileFCTitle">' +
													'<ol class="mobileFCList">' +
														'<li><div class="sNumber title"><b>Mobile NO.</b></div><div class="sName title"><b>Name</b></div><div class="scAudio title"><b>Chat Audio</b></div><div class="scVideo title"><b>Chat Video</b></div><div class="scPhoto title"><b>Chat Photo</b></div><div class="scProfile title"><b>Chat Profile</b></div><div class="svAudio title"><b>Vote Audio</b></div><div class="svVideo title"><b>Vote Video</b></div><div class="svPhoto title"><b>Vote Photo</b></div><div class="svProfile title"><b>Vote Profile</b></div><div class="netTotal title"><b>Total</b></div></li>' +
													'</ol>'+
												'</div>' +
												'<div id="view_mobileFCList"><img src="/resources/graphics/general/sprite_loading_small.gif" style="margin-left:5px;" /></div>' +
												'<div id="mobileFCPageController" class="paginationTextLarge center" style="display:none;">' +
													'<a id="prev_mobileFCPage" title="previous" href="javascript:void(0);" class="previous">Previous</a>' +
													'<span id="currentPageRange_mobileFCPage"></span>' +
													'<span id="currentRec_mobileFCPage"></span>' +
													'<a id="next_mobileFCPage" title="next" href="javascript:void(0);" class="next">Next</a>' +
												'</div>' +
											'</div>' +
											'<p style="text-align:right;"></p>' +
										'</div>' +
									'</div>' +
								'</div>' +
								'<div class="dlgWhiteBox_bottom">&nbsp;</div>' +
							'</div>';
		},		
		afterOpen: function() {
			var _closeButton = $('mobile-fanclub-close-button');
			Event.observe(_closeButton, 'click', closeSmsDialogue.bindAsEventListener(this));
			getMobileFanClubListByUser();
		}						
	});
	
	gMobileBlockListDlg = new Control.Modal(false, {
		containerClassName: 'beta',
		overlayClassName: 'blue',
		width: 820,
		height: 420,
		overlayCloseOnClick: true,
		contents: function() {
			return  '<div class="dlgWhiteBox_container">' +
								'<div class="dlgWhiteBox_top"><span class="right"><input  id="mobile-blocklist-close-button" type="button" value="Close" /></span></div>' +
								'<div class="dlgWhiteBox_middle">' +
									'<div class="sms_codeInfo_container">' + 
										'<div id="mobileBlockInfo">' +
											'<div id="mobileBlockBoxList">' +
												'<h4>Manage your fan club</h4>' +
												'<div id="mobileBlockTitle"><ol class="mobileBlockList">' +
													'<li><div class="simNumber"><b>Mobile Number</b></div><div class="simName"><b>Name</b></div><div class="simState"><b>State</b></div></li>' +
												'</ol></div>' +
												'<div id="view_mobileBlockList"><img src="/resources/graphics/general/sprite_loading_small.gif" style="margin-left:5px;" /></div>' +
												'<div id="mobileBlockPageController" class="paginationTextLarge center" style="display:none;">' +
													'<a id="prev_mobileBlockPage" title="previous" href="javascript:void(0);" class="previous">Previous</a>' +
													'<span id="currentPageRange_mobileBlockPage"></span>' +
													'<span id="currentRec_mobileBlockPage"></span>' +
													'<a id="next_mobileBlockPage" title="next" href="javascript:void(0);" class="next">Next</a>' +
												'</div>' +
											'</div>' +
											'<p style="text-align:right;"></p>' +
										'</div>' +
									'</div>' +
								'</div>' +
								'<div class="dlgWhiteBox_bottom">&nbsp;</div>' +
							'</div>';
		},		
		afterOpen: function() {
			var _closeButton = $('mobile-blocklist-close-button');
			Event.observe(_closeButton, 'click', closeSmsDialogue.bindAsEventListener(this));
			getMobileBlockListByUser();
		}						
	});
}

function showSmsCodeDlg() {
	gSmsChatCodeDlg.open();
}

function showSmsVoteCodeDlg() {
	gSmsVoteCodeDlg.open();
}

function registerMobileDlg() {
	gRegisterMobileDlg.open();
}

function showMobileFanclubDlg() {
	gMobileFanclubDlg.open();
}

function showBlockListDlg() {
	gMobileBlockListDlg.open();	
}

function closeSmsDialogue() {
	Control.Modal.close();
}

/** Mobile FC **/
function getMobileFanClubListByUser() {
	window.mobileFanclubPaging = new WosPagination({
		objName: 'mobileFanclubPaging',
		firstResult: 0,
		maxResults: 20,
		pagingRange: 0,
		recordDisplay: 20,
		preLink: 'prev_mobileFCPage',																			
		nextLink: 'next_mobileFCPage',																			
		url: encodeAjaxParamUrl('getMobileFanClubListByUser','rf', new Date().getTime()),
		params: {'userId':window.pUserId},
		pageNumView: 'currentPageRange_mobileFCPage',								
		pageControl: 'currentRec_mobileFCPage',												
		dataView: 'view_mobileFCList',																				
		drawTable: function(page, contain) {
			var data = "data";
			var recordList = '<ol class="mobileFCList">';  															
			for(var i =0; i < page[data].records.length; i++) {
					recordList += '<li><div class="sNumber">' + page[data].records[i].simNumber + '</div><div class="sName">' + renderMobileFCName(page[data].records[i].simName) + '</div><div class="scAudio num">' + page[data].records[i].totalSmsChatAudio + '</div><div class="scVideo num">' + page[data].records[i].totalSmsChatVideo + '</div><div class="scPhoto num">' + page[data].records[i].totalSmsChatPhoto + '</div><div class="scProfile num">' + page[data].records[i].totalSmsChatProfile + '</div><div class="svAudio num">' + page[data].records[i].totalSmsVoteAudio + '</div><div class="svVideo num">' + page[data].records[i].totalSmsVoteVideo + '</div><div class="svPhoto num">' + page[data].records[i].totalSmsVotePhoto + '</div><div class="svProfile num">' + page[data].records[i].totalSmsVoteProfile + '</div><div class="netTotal num">' + page[data].records[i].netTotal + '</div></li>';		
			}
			recordList += '</ol>';
			contain.update(recordList);
			if (page[data].totalRecords == 0) {
				noMobileFC();
			}
			if (page[data].totalRecords > 20) {
				enableMobileFCPageController();
			}
		}
	});
	Object.extend(window.mobileFanclubPaging, {
		callExternalFn: function() {
		}
	});
}

function renderMobileFCName(name) {
	if (name == '') {
		return '&nbsp;'
	} else {
		return name;
	}
}

function enableMobileFCPageController() {
	$('mobileFCPageController').show();
}

function noMobileFC() {
	$('view_mobileFCList').update('<span style="text-align:center;color: #FF0099;">No mobile fan club for ' + window.pUsername + '</span>');
}

/** Block List **/

function getMobileBlockListByUser() {
	window.mobileBlockPaging = new WosPagination({
		objName: 'mobileBlockPaging',
		firstResult: 0,
		maxResults: 10,
		pagingRange: 0,
		recordDisplay: 10,
		preLink: 'prev_mobileBlockPage',																			
		nextLink: 'next_mobileBlockPage',																			
		url: encodeAjaxParamUrl('getBlockedSimByUser','rf', new Date().getTime()),
		params: {'userId':window.pUserId},
		pageNumView: 'currentPageRange_mobileBlockPage',								
		pageControl: 'currentRec_mobileBlockPage',												
		dataView: 'view_mobileBlockList',																				
		drawTable: function(page, contain) {
			var data = "data";
			var recordList = '<ol class="mobileBlockList">';  															
			for (var i =0; i < page[data].records.length; i++) {
				if (page[data].records[i].simState == 'BLOCK') {
					recordList += '<li id="' + page[data].records[i].blockedSimId + '" class="block"><div class="simNumber">' +  page[data].records[i].simNumber + '</div><div class="simName">' +  page[data].records[i].simName + '</div><div class="simState">' +  renderSimState(page[data].records[i].simState) + '</div><div class="simSet"><a href="javascript:void(0);" onclick="javascript:updateBlockedSimStateByBlockedSimId(\'' +  page[data].records[i].blockedSimId + '\', \'unblock\')">Unblock this mobile</a></div></li>';
				} else if (page[data].records[i].simState == 'UNBLOCK') {
					recordList += '<li id="' + page[data].records[i].blockedSimId + '" class="unblock"><div class="simNumber">' +  page[data].records[i].simNumber + '</div><div class="simName">' +  page[data].records[i].simName + '</div><div class="simState">' +  renderSimState(page[data].records[i].simState) + '</div><div class="simSet"><a href="javascript:void(0);" onclick="javascript:updateBlockedSimStateByBlockedSimId(\'' +  page[data].records[i].blockedSimId + '\', \'block\')">Block this mobile</a></div></li>';
				}
			}
			recordList += '</ol>';
			contain.update(recordList);
			if (page[data].totalRecords == 0) {
				noMobileBlockSim();
			}
			if (page[data].totalRecords > 10) {
				enableMobileBlockPageController();
			}
		}
	});
	Object.extend(window.mobileBlockPaging, {
		callExternalFn: function() {
		}
	});
}

function resetMobileBlockParam() {
	window.mobileBlockPaging.firstResult = 0;
	window.mobileBlockPaging.maxResults = 10;
	window.mobileBlockPaging.pagingRange = 0;
	window.mobileBlockPaging.recordDisplay = 10;
	window.mobileBlockPaging.startPage = 1;
	window.mobileBlockPaging.getTableData();
}

function renderSimState(s) {
	if (s == 'BLOCK') {
		return 'Blocked';
	} else if (s == 'UNBLOCK') {
		return '&nbsp';
	}
}

function enableMobileBlockPageController() {
	$('mobileBlockPageController').show();
}

function noMobileBlockSim() {
	$('view_mobileBlockList').update('<span style="text-align:center;color: #666666;">No blocked mobile number.</span>');
}

/** SMS Chat **/

function getSmsChatCode(cId) {
	var dtRf = new Date().getTime();
	var url = '';
	var urlParam = '';
	if (gMobileAppType == 'user') {
		url = window.encodeAjaxParamUrl('getSmsChatProfileMobileServiceInfo', 'rf', dtRf);
		urlParam = {'userId':cId,'limit.first':0,'limit.max':5};
	} else if (gMobileAppType == 'audio') {
		url = window.encodeAjaxParamUrl('getSmsChatAudioMobileServiceInfo', 'rf', dtRf);
		urlParam = {'audioId':cId,'limit.first':0,'limit.max':5};
	} else if (gMobileAppType == 'video') {
		url = window.encodeAjaxParamUrl('getSmsChatVideoMobileServiceInfo', 'rf', dtRf);
		urlParam = {'videoId':cId,'limit.first':0,'limit.max':5};
	} else if (gMobileAppType == 'photo') {
		url = window.encodeAjaxParamUrl('getSmsChatPhotoMobileServiceInfo', 'rf', dtRf);
		urlParam = {'photoId':cId,'limit.first':0,'limit.max':5};
	}
	
	var up = this;
	var wosAjax = new Ajax.Request(url, {
		method: 'post',
		parameters: urlParam,
		onComplete: function(transport) {
			var sJSON = transport.responseText;
			var json = window.decodeJSON(sJSON);
			if (json.notification.summary.type=="ERROR") {					
				window.requestPageCompleteWithError(json.notification.summary.value);
			} else if(json.notification.summary.type=="INFO") {
				up.renderSmsChatCode(json);
			}
		}, 
		onFailure: function(error) {
			window.requestPageFailure(error);
		}
	});	
}

function renderSmsChatCode(json) {					// using for-loop pagination for 3-4 operators		
	var preText1 = 'โทรศัพท์มือถือระบบ';
	var preText2 = 'โดยพิมพ์';
	var preText3 = 'เว้นวรรคแล้วตามด้วยข้อความ';
	var preText4 = 'แล้วส่งมาที่เบอร์';
	var postText1 = '(ครั้งละ';
	var postText2 = 'บาท ไม่รวมภาษีมูลค่าเพิ่ม)';
	var recordList = '<ul>';
	for (var i = 0; i < json.data.records.length; i++) {
			recordList += '<li>';
			if (json.data.records[i].operatorType == "AIS") {
				recordList += '<img class="operator" src="/resources/graphics/general/operator_ais.png" />';
			} else if (json.data.records[i].operatorType == "DTAC") {
				recordList += '<img class="operator" src="/resources/graphics/general/operator_dtac.png" />';
			} else if (json.data.records[i].operatorType == "TRUE") {
				recordList += '<img class="operator" src="/resources/graphics/general/operator_truemove.png" />';
			}
			recordList += '<div class="codeContainer">' +
										'<div class="preText">' + preText1 +' ' + json.data.records[i].operatorType + ' ' + preText2 + ' <b>' + json.data.records[i].usage + '</b> ' + preText3 + '</div>' +
										'<div class="codeNumber">' + preText4 + ' <b>' + json.data.records[i].serviceCode + '</b> <span class="postText">' + postText1 + ' ' + renderPrice(json.data.records[i].price) + ' ' + postText2 + '</span></div>' +
									'</div>' +
								'</li>';
	}
	recordList += '</ul>';
	$('view_chatCode').update(recordList);
}

function renderPrice(p) {
	var stang = p.substring(p.length, (p.length-2));
	var baht = p.substring(0, (p.length-2));
	var price = baht + '.' + stang;
	return price;
}

/** SMS Vote **/
function getSmsVoteCode(cId) {
	var dtRf = new Date().getTime();
	var url = '';
	var urlParam = '';
	if (gMobileAppType == 'user') {
		url = window.encodeAjaxParamUrl('getSmsVoteProfileMobileServiceInfo', 'rf', dtRf);
		urlParam = {'userId':cId,'limit.first':0,'limit.max':5};
	} else if (gMobileAppType == 'audio') {
		url = window.encodeAjaxParamUrl('getSmsVoteAudioMobileServiceInfo', 'rf', dtRf);
		urlParam = {'audioId':cId,'limit.first':0,'limit.max':5};
	} else if (gMobileAppType == 'video') {
		url = window.encodeAjaxParamUrl('getSmsVoteVideoMobileServiceInfo', 'rf', dtRf);
		urlParam = {'videoId':cId,'limit.first':0,'limit.max':5};
	} else if (gMobileAppType == 'photo') {
		url = window.encodeAjaxParamUrl('getSmsVotePhotoMobileServiceInfo', 'rf', dtRf);
		urlParam = {'photoId':cId,'limit.first':0,'limit.max':5};
	}
	var up = this;
	var wosAjax = new Ajax.Request(url, {
		method: 'post',
		parameters: urlParam,
		onComplete: function(transport) {
			var sJSON = transport.responseText;
			var json = window.decodeJSON(sJSON);
			if (json.notification.summary.type=="ERROR") {					
				window.requestPageCompleteWithError(json.notification.summary.value);
			} else if(json.notification.summary.type=="INFO") {
				up.renderSmsVoteCode(json);
			}
		}, 
		onFailure: function(error) {
			window.requestPageFailure(error);
		}
	});
}

function renderSmsVoteCode(json) {					// use for-loop pagination for 3-4 operators
	var preText1 = 'โทรศัพท์มือถือระบบ';
	var preText2 = 'โดยพิมพ์';
	var preText3 = 'แล้วส่งมาที่เบอร์';
	var postText1 = '(ครั้งละ';
	var postText2 = 'บาท ไม่รวมภาษีมูลค่าเพิ่ม)';
	var recordList = '<ul>';
	for (var i = 0; i < json.data.records.length; i++) {
			recordList += '<li>';
			if (json.data.records[i].operatorType == "AIS") {
				recordList += '<img class="operator" src="/resources/graphics/general/operator_ais.png" />';
			} else if (json.data.records[i].operatorType == "DTAC") {
				recordList += '<img class="operator" src="/resources/graphics/general/operator_dtac.png" />';
			} else if (json.data.records[i].operatorType == "TRUE") {
				recordList += '<img class="operator" src="/resources/graphics/general/operator_truemove.png" />';
			}
			recordList += '<div class="codeContainer">' +
										'<div class="preText">' + preText1 +' ' + json.data.records[i].operatorType + ' ' + preText2 + ' <b>' + json.data.records[i].usage + '</b></div>' +
										'<div class="codeNumber">' + preText3 + ' <b>' + json.data.records[i].serviceCode + '</b> <span class="postText">' + postText1 + ' ' + renderPrice(json.data.records[i].price) + ' ' + postText2 + '</span></div>' +
									'</div>' +
								'</li>';
	}
	recordList += '</ul>';
	$('view_voteCode').update(recordList);
}

/*** SMS Manager ***/
function toggleSmsReplyBox(id) {
	var _id = 'sms_reply' + id;
	$(_id).toggle();
}

function hideSmsReplyBox(id) {
	var _id = 'sms_reply' + id;
	var _replyForm = 'replyForm' + id;
	$(_id).hide();
	$(_replyForm).reset();
}

function sendSmsReply(id) {
	var _id = 'i_sms_reply' + id;
	var s = $(_id).value;
	var dtRf = new Date().getTime();
	var url = '';
	if (gMobileAppType == 'user') {
		url = window.encodeAjaxParamUrl('replySmsChatProfileViaWeb', 'rf', dtRf);
	} else if (gMobileAppType == 'audio') {
		url = window.encodeAjaxParamUrl('replySmsChatAudioViaWeb', 'rf', dtRf);
	} else if (gMobileAppType == 'video') {
		url = window.encodeAjaxParamUrl('replySmsChatVideoViaWeb', 'rf', dtRf);
	} else if (gMobileAppType == 'photo') {
		url = window.encodeAjaxParamUrl('replySmsChatPhotoViaWeb', 'rf', dtRf);
	}
	var up = this;
	if(s != '') {
		var wosAjax = new Ajax.Request(url, {
			method: 'post',
			parameters: {'smsChatId':id,'message':s},
			onComplete: function(transport) {
				var sJSON = transport.responseText;
				var json = window.decodeJSON(sJSON);
				if (json.notification.summary.type=="ERROR") {					
					window.requestPageCompleteWithError(json.notification.summary.value);
				} else if(json.notification.summary.type=="INFO") {
					up.resetSMSChatParam();
				}
			}, 
			onFailure: function(error) {
				window.requestPageFailure(error);
			}
		});	
	}
}

function autoHideSmsChatForPhoneNumber(id) {			
	var dtRf = new Date().getTime();
	var url = '';
	if (gMobileAppType == 'user') {
		url = window.encodeAjaxParamUrl('updateBlockSimStateBySmsChatProfile', 'rf', dtRf);	
	} else if (gMobileAppType == 'audio') {
		url = window.encodeAjaxParamUrl('updateBlockSimStateBySmsChatAudio', 'rf', dtRf);
	} else if (gMobileAppType == 'video') {
		url = window.encodeAjaxParamUrl('updateBlockSimStateBySmsChatVideo', 'rf', dtRf);
	} else if (gMobileAppType == 'photo') {
		url = window.encodeAjaxParamUrl('updateBlockSimStateBySmsChatPhoto', 'rf', dtRf);
	}
	var up = this;
	var wosAjax = new Ajax.Request(url, {
		method: 'post',
		parameters: {'smsId':id,'state':'BLOCK'},
		onComplete: function(transport) {
			var sJSON = transport.responseText;
			var json = window.decodeJSON(sJSON);
			if (json.notification.summary.type=="ERROR") {					
				window.requestPageCompleteWithError(json.notification.summary.value);
			} else if(json.notification.summary.type=="INFO") {
				up.resetSMSChatParam();
			}
		}, 
		onFailure: function(error) {
			window.requestPageFailure(error);
		}
	});	
}

function updateBlockedSimStateBySmsId(id) {
	var dtRf = new Date().getTime();
	var url = '';
	if (gMobileAppType == 'user') {
		url = window.encodeAjaxParamUrl('updateBlockSimStateBySmsChatProfile', 'rf', dtRf);	
	} else if (gMobileAppType == 'audio') {
		url = window.encodeAjaxParamUrl('updateBlockSimStateBySmsChatAudio', 'rf', dtRf);
	} else if (gMobileAppType == 'video') {
		url = window.encodeAjaxParamUrl('updateBlockSimStateBySmsChatVideo', 'rf', dtRf);
	} else if (gMobileAppType == 'photo') {
		url = window.encodeAjaxParamUrl('updateBlockSimStateBySmsChatPhoto', 'rf', dtRf);
	}
	var up = this;
	var wosAjax = new Ajax.Request(url, {
		method: 'post',
		parameters: {'smsId':id,'state':'UNBLOCK'},
		onComplete: function(transport) {
			var sJSON = transport.responseText;
			var json = window.decodeJSON(sJSON);
			if (json.notification.summary.type=="ERROR") {					
				window.requestPageCompleteWithError(json.notification.summary.value);
			} else if(json.notification.summary.type=="INFO") {
					up.resetSMSChatParam();
			}
		}, 
		onFailure: function(error) {
			window.requestPageFailure(error);
		}
	});	
}

function updateBlockedSimStateByBlockedSimId(bId, s) {
	var state = s;
	if (s == 'block') {
		state = 'BLOCK';
	} else if (s == 'unblock') {
		state = 'UNBLOCK';
	}
	var dtRf = new Date().getTime();
	var url = window.encodeAjaxParamUrl('updateBlockedSimState', 'rf', dtRf);
	var up = this;
	var wosAjax = new Ajax.Request(url, {
		method: 'post',
		parameters: {'blockedSimId':bId,'state':state},
		onComplete: function(transport) {
			var sJSON = transport.responseText;
			var json = window.decodeJSON(sJSON);
			if (json.notification.summary.type=="ERROR") {					
				window.requestPageCompleteWithError(json.notification.summary.value);
			} else if(json.notification.summary.type=="INFO") {
				up.resetMobileBlockParam();
				up.resetSMSChatParam();
			}
		}, 
		onFailure: function(error) {
			window.requestPageFailure(error);
		}
	});	
}

function hideSmsChat(id) {
	var dtRf = new Date().getTime();
	var url = '';
	if (gMobileAppType == 'user') {
		url = window.encodeAjaxParamUrl('hideSmsChatProfile', 'rf', dtRf);	
	} else if (gMobileAppType == 'audio') {
		url = window.encodeAjaxParamUrl('hideSmsChatAudio', 'rf', dtRf);
	} else if (gMobileAppType == 'video') {
		url = window.encodeAjaxParamUrl('hideSmsChatVideo', 'rf', dtRf);
	} else if (gMobileAppType == 'photo') {
		url = window.encodeAjaxParamUrl('hideSmsChatPhoto', 'rf', dtRf);
	}
	var up = this;
	var wosAjax = new Ajax.Request(url, {
		method: 'post',
		parameters: {'smsChatId':id},
		onComplete: function(transport) {
			var sJSON = transport.responseText;
			var json = window.decodeJSON(sJSON);
			if (json.notification.summary.type=="ERROR") {					
				window.requestPageCompleteWithError(json.notification.summary.value);
			} else if(json.notification.summary.type=="INFO") {
				up.resetSMSChatParam();
			}
		}, 
		onFailure: function(error) {
			window.requestPageFailure(error);
		}
	});	
}

function showSmsChat(id) {
	var dtRf = new Date().getTime();
	var url = '';
	if (gMobileAppType == 'user') {
		url = window.encodeAjaxParamUrl('showSmsChatProfile', 'rf', dtRf);	
	} else if (gMobileAppType == 'audio') {
		url = window.encodeAjaxParamUrl('showSmsChatAudio', 'rf', dtRf);
	} else if (gMobileAppType == 'video') {
		url = window.encodeAjaxParamUrl('showSmsChatVideo', 'rf', dtRf);
	} else if (gMobileAppType == 'photo') {
		url = window.encodeAjaxParamUrl('showSmsChatPhoto', 'rf', dtRf);
	}
	var up = this;
	var wosAjax = new Ajax.Request(url, {
		method: 'post',
		parameters: {'smsChatId':id},
		onComplete: function(transport) {
			var sJSON = transport.responseText;
			var json = window.decodeJSON(sJSON);
			if (json.notification.summary.type=="ERROR") {					
				window.requestPageCompleteWithError(json.notification.summary.value);
			} else if(json.notification.summary.type=="INFO") {
				up.resetSMSChatParam();
			}
		}, 
		onFailure: function(error) {
			window.requestPageFailure(error);
		}
	});	
}

function reportAbusedSmsChat(id) {					// TODO: wait for actual API
}

// TODO: refractor to wosapplication.js
function focusNext(form, elemName, evt) {
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode :
        ((evt.which) ? evt.which : evt.keyCode);
    if (charCode == 13) {
        form.elements[elemName].focus();
        return false;
    }
    return true;
}




/*** mobile number renderer ***/
var codeCollection = [];

function renderMobileNumber(oCode, cCode, digit) {	
	var allCode = oCode + cCode;
	var n = allCode.length/digit;
	var x = allCode.substr(0,digit);
	codeCollection.push(x);
	for (var i = 0; i < (n-1); i++) {
		allCode = allCode.substring(digit);
		x = allCode.substr(0,digit);	
		codeCollection.push(x);
	}
	var code = renderMobileCode();
	return code;
} 

function renderMobileCode() {
	var color = ['#FF0099','#000000','#0099FF','#000000','#FF0099','#000000','#0099FF']
	var code = '';
	var _codeCollection = codeCollection;
	for (var i = 0; i <(_codeCollection.length); i ++) {
		code += '<span color="' + color[i]+ '">' + _codeCollection[i] +'</span>';
	}
	_codeCollection = [];
	return code;
}

function destroyMobilePaging() {
	smsChatPaging = null;
	mobileFanclubPaging = null;
	mobileBlockPaging = null;
}

Event.stopObserving(window, 'unload', destroyMobilePaging, false);