////////////////////////////////////////////////////////////
// MEMBER & REWARD v5.5
////////////////////////////////////////////////////////////

/*!
 * 
 * MEMBER & REWARD SETTING CUSTOMIZATION START
 * 
 */

var memberSettings = {
	enableMembership:true, //enable membership
	scoreDisplay:{
		type:true, //true for point, false for currency display
		point:'[NUMBER]PTS',
		currency:'$[NUMBER]'
	},
	userIDType:"email", //user ID type 'email' or 'mobile' field
	mobileFormat:{
		matches:"999-99999999", //mobile format
		minLength:10, //mobile min length
		maxLength:12 //mobile max length
	},
	enableConnectFacebook:false, //enable connect facebook login
	fbAppID:'', //Facebook App ID

	enableRewards:true, //enable rewards item
	enableTopup:true, //enable buy points
	enableRedeemCode:true, //enable redeem code
	enableMoreGames:true, //enable more games

	enableScoreboard:true, //enable scoreboard
	scoreRank_arr:['1st','2nd','3rd','4th','5th','6th','7th','8th','9th','10th'], //scoreboard ranking list
	scoreReverse:false, //reverse scoreboard list in descending
	scoreListingFormat:'', //return score in daily, weekly or monthly, empty string for all time (daily, weekly, monthly)
	totalScorePage:1, //total score pages, .e.g. 2 for 20 listing
	wideBackground:true, //disable for narrow background for some old HTML5 Game

	text:{
		enterName:"*Please enter your name.",
		enterEmail:"*Please enter your email.",
		enterMobile:"*Please enter your mobile no.",
		enterPassword:"*Please enter your password.",
		enterConfirmPassword:"*Please enter your confirm password.",
		passwordNotMatch:"*Your password does not match.",
		enterValidEmail:"*Please enter a valite email.",
		enterValidMobile:"*Please enter a valite mobile no.",
		sessionTimeout:"Login session timeout, please login again.",
		enterRedeemCode:"*Please enter your redeem code",
		connecting:"Connecting server...",
		connectionError:"Connection error.",
	}
}


/*!
 * 
 * MEMBER & REWARD SETTING CUSTOMIZATION END
 * 
 */
 
var memberContainer;
var memberData = {type:'', login:false, member_id:'', fb_id:'', member_name:'', member_email:'', member_points:'', token:'', gameType:'', ready:true, callback:null};

/*!
 * 
 * MEMBER & REWARD ASSETS - This is the function that runs to add member reward assets
 * 
 */
function addMemberRewardAssets(){
	manifest.push({src:'memberrewards/assets/button_memberreward.png', id:'userButton'});
	manifest.push({src:'memberrewards/assets/button_scoreboard.png', id:'scoreboardButton'});
}

/*!
 * 
 * MEMBER REWARD CANVAS - This is the function that runs to build member reward canvas
 * 
 */
function buildMemberRewardCanvas(){
	if(!memberSettings.enableMembership){
		return;	
	}
	
	//buttons
	userButton = new createjs.Bitmap(loader.getResult('userButton'));
	centerReg(userButton);
	userButton.visible = false;
	
	scoreboardButton = new createjs.Bitmap(loader.getResult('scoreboardButton'));
	centerReg(scoreboardButton);
	scoreboardButton.visible = false;
	
	memberLoaderContainer = new createjs.Container();
	memberLoaderBg = new createjs.Shape();	
	memberLoaderBg.graphics.beginFill("#000").drawRect(0, 0, 1280, 1024);
	memberLoaderBg.alpha = .2;
	memberLoaderBg.addEventListener("click", function(evt) {
		
	});

	var loaderBg = {w:250, h:60, radius:15}
	memberTxtBg = new createjs.Shape();	
	memberTxtBg.graphics.beginFill("#EFF1F1").drawRoundRectComplex(-(loaderBg.w/2), -(loaderBg.h/2), loaderBg.w, loaderBg.h, loaderBg.radius, loaderBg.radius, loaderBg.radius, loaderBg.radius);
	memberTxtShadowBg = new createjs.Shape();	
	memberTxtShadowBg.graphics.beginFill("#C5C9C9").drawRoundRectComplex(-(loaderBg.w/2), -(loaderBg.h/2), loaderBg.w, loaderBg.h, loaderBg.radius, loaderBg.radius, loaderBg.radius, loaderBg.radius);
	
	memberLoaderTxt = new createjs.Text();
	memberLoaderTxt.font = "30px barlow_condensedsemibold";
	memberLoaderTxt.lineHeight = 50;
	memberLoaderTxt.color = "#000";
	memberLoaderTxt.textAlign = "center";
	memberLoaderTxt.textBaseline='alphabetic';

	memberLoaderContainer.visible = false;
	memberLoaderContainer.addChild(memberLoaderBg, memberTxtShadowBg, memberTxtBg, memberLoaderTxt);
	
	canvasContainer.addChild(userButton, scoreboardButton, memberLoaderContainer);
	
	/*if(typeof buttonFullscreen != 'undefined'){
		canvasContainer.addChild(buttonFullscreen, buttonSoundOn, buttonSoundOff);	
	}*/
	
	if(typeof $.editor != 'undefined'){
		if(!$.editor.enable){
			
		}
	}
	
	$.get('memberrewards/index.php', function(data){
		$('#canvasHolder').append(data);
		
		if(typeof forPortrait != 'undefined'){
			if(forPortrait){
				rewardsData.totalPerPages = 2;
				$('#memberHolder').addClass('portrait');
				$('#memberBg').attr('src','memberrewards/assets/background_portrait.png');
			}
		}

		if(!memberSettings.wideBackground){
			$('#memberBg').attr('src','memberrewards/assets/background_narrow.png');	
		}

		if(memberSettings.userIDType == 'email'){
			$('.forEmail').show();
			$('.forMobile').hide();
		}else{
			$('.forEmail').hide();
			$('.forMobile').show();
			$('#uMobile').attr('placeholder', memberSettings.mobileFormat.matches);
			$('#uMobile').attr('maxlength', memberSettings.mobileFormat.maxLength);
			$('#uSMobile').attr('placeholder', memberSettings.mobileFormat.matches);
			$('#uSMobile').attr('maxlength', memberSettings.mobileFormat.maxLength);
		}
		
		buildUserButtons();
		buildGamesLists();
		resizeMemberReward();
		toggleMemberLoader(false);

		checkLoginSession();
	});
}

/*!
 * 
 * BUTTONS - This is the function that runs to build buttons
 * 
 */
function buildUserButtons(){
	$('.forLogin').show();
	$('.forExtraLogin').hide();

	if(memberSettings.enableConnectFacebook){
		$('.forLogin').hide();
		$('.forExtraLogin').show();
		initFBConnect();
	}

	var buttonVisible = 3;
	if(!memberSettings.enableRewards){
		buttonVisible--;
		$('#buttonUserRewards').hide();
	}
	
	if(!memberSettings.enableTopup){
		buttonVisible--;
		$('#buttonUserTopup').hide();
	}
	
	if(!memberSettings.enableRedeemCode){
		buttonVisible--;
		$('#buttonUserRedeemCode').hide();
	}
	
	if(buttonVisible >= 3){
		$('#sectionUser .userAction').addClass('threeButton');	
	}else if(buttonVisible >= 2){
		$('#sectionUser .userAction').addClass('twoButton');	
	}

	//more games
	if(!memberSettings.enableMoreGames){
		$('.userActionMore').removeClass('twoButton');
		$('#buttonMoreGames').hide();
	}
	
	//login
	$('#buttonDefaultLogin').click(function(event){
		event.preventDefault();
		goMemberPage('login');
	});
	
	$('#buttonConnectFacebook').click(function(event){
		event.preventDefault();
		FB.login(updateFbLoginCallback);
	});
	
	$('#btnLoginBack').click(function(event){
		event.preventDefault();
		goMemberPage('option');
	});
	
	$('#buttonSubmitLogin').click(function(event){
		event.preventDefault();
		postLogin();
	});
	
	$('#btnSignupNow, #btnLoginSignupNow').click(function(event){
		event.preventDefault();
		goMemberPage('signup');
	});
	
	$('#btnForgotPassword').click(function(event){
		event.preventDefault();
		goMemberPage('forgotpassword');
	});
	
	$('#btnForgotPasswordBack').click(function(event){
		event.preventDefault();
		goMemberPage('login');
	});
	
	//signup
	$('#buttonSubmitSignup').click(function(event){
		event.preventDefault();
		postSignup();
	});
	
	$('#btnSignupBack').click(function(event){
		event.preventDefault();
		if(memberSettings.enableConnectFacebook){
			goMemberPage('option');
		}else{
			goMemberPage('login');	
		}
	});
	
	//thankyou
	$('#thankyouLoginNow').click(function(event){
		event.preventDefault();
		goMemberPage('login');
	});
	
	//forgot password
	$('#buttonSubmitForgot').click(function(event){
		event.preventDefault();
		postForgot();
	});
	
	//forgot password thankyou
	$('#thankyouForgotLoginNow').click(function(event){
		event.preventDefault();
		goMemberPage('login');
	});
	
	//reset
	$('#buttonSubmitReset').click(function(event){
		event.preventDefault();
		postReset();
	});
	
	//reset thankyou
	$('#thankyouResetLoginNow').click(function(event){
		event.preventDefault();
		goMemberPage('login');
	});
	
	//user
	$('#buttonUserTopup').click(function(event){
		event.preventDefault();
		goMemberPage('topup');
	});
	
	$('#buttonUserRewards').click(function(event){
		event.preventDefault();
		goMemberPage('rewards');
	});
	
	$('#buttonUserRedeemCode').click(function(event){
		event.preventDefault();
		goMemberPage('redeemcode');
	});
	
	$('#buttonUserContinue').click(function(event){
		event.preventDefault();
		toggleUserDetails(false);
	});

	$('#buttonMoreGames').click(function(event){
		event.preventDefault();
		goMemberPage('moregames');
	});
	
	$('#buttonUserLogout').click(function(event){
		event.preventDefault();
		postLogout();
	});
	
	//redeem
	$('#buttonRedeemCancel').click(function(event){
		event.preventDefault();
		goMemberPage('user');
	});
	
	$('#buttonRedeemHistory').click(function(event){
		event.preventDefault();
		goMemberPage('loading');
		historyListsData.newPage = 1;
		loadRedemptionHistory();
	});
	
	$('#buttonRedeemItemConfirm').click(function(event){
		event.preventDefault();
		postRedeem();
	});
	
	$('#buttonRedeemItemCancel').click(function(event){
		event.preventDefault();
		goMemberPage('rewards');
	});
	
	$('#buttonRedeemCompleteContinue').click(function(event){
		event.preventDefault();
		goMemberPage('user');
	});
	
	$('.btnRedeemLeft').click(function(event){
		event.preventDefault();
		togglerewardLists(false);
	});
	
	$('.btnRedeemRight').click(function(event){
		event.preventDefault();
		togglerewardLists(true);
	});
	
	//redemption history
	$('#buttonHistoryClose').click(function(event){
		event.preventDefault();
		goMemberPage('rewards');
	});
	
	$('#buttonHistoryNext').click(function(event){
		event.preventDefault();
		toggleHistoryPage(true);
	});
	
	$('#buttonHistoryPrev').click(function(event){
		event.preventDefault();
		toggleHistoryPage(false);
	});
	
	//buy
	$('#buttonBuyCancel').click(function(event){
		event.preventDefault();
		goMemberPage('user');
	});
	
	$('#buttonTransactionCompleteContinue').click(function(event){
		event.preventDefault();
		goMemberPage('user');
	});
	
	//scoreboard
	$('#buttonScoreboardClose').click(function(event){
		event.preventDefault();
		goMemberPage();
	});
	
	$('#buttonScoreboardNext').click(function(event){
		event.preventDefault();
		toggleScorePage(true);
	});
	
	$('#buttonScoreboardPrev').click(function(event){
		event.preventDefault();
		toggleScorePage(false);
	});
	
	userButton.cursor = "pointer";
	userButton.addEventListener("click", function(evt) {
		toggleUserDetails(true);
	});
	
	scoreboardButton.cursor = "pointer";
	scoreboardButton.addEventListener("click", function(evt) {
		scoreListsData.newPage = 1;
		loadScoreboard();
	});
	
	//redeem code
	$('#buttonRedeemCodeCancel').click(function(event){
		event.preventDefault();
		goMemberPage('user');
	});
	
	$('#buttonRedeemCode').click(function(event){
		event.preventDefault();
		//goMemberPage('loading');
		//historyListsData.newPage = 1;
		//loadRedemptionHistory();
		postRedeemCode();
	});
	
	$('#buttonRedeemCodeCompleteContinue').click(function(event){
		event.preventDefault();
		goMemberPage('user');
	});

	//more games
	$('#buttonGamesCancel').click(function(event){
		event.preventDefault();
		goMemberPage('user');
	});

	$('.btnMoreGamesLeft').click(function(event){
		event.preventDefault();
		toggleGamesLists(false);
	});
	
	$('.btnMoreGamesRight').click(function(event){
		event.preventDefault();
		toggleGamesLists(true);
	});
}

function radioHighigt(){
	$('.buyOption').each(function(index, element) {
        var imgRadio = 'memberrewards/assets/radio.png';
		var imgRadioSelected = 'memberrewards/assets/radiocheck.png';
			
		if($(this).find('input').is(":checked")){
			$(this).find('.radioOpt').attr('src', imgRadioSelected);
		}else{
			$(this).find('.radioOpt').attr('src', imgRadio);	
		}
    });	
}


/*!
 * 
 * DISPLAY MEMBER PAGE - This is the function that runs to display member page
 * 
 */

function goMemberPage(page){
	var targetContainer;
	$('#memberHolder').hide();
	$('.memberInnerContent').hide();
	$('.errMsg').html('');
	
	switch(page){
		case 'user':
			targetContainer = null;
			
			$('#userName').html(memberData.member_name);
			$('.scoreDisplay').removeClass('hideChance');
			
			updateMemberScore();
			$('#memberHolder').show();
			$('#sectionUser').show();
		break;
			
		case 'option':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionLoginOption').show();
		break;
		
		case 'login':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionLogin').show();
		break;
		
		case 'signup':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionSignup').show();
		break;
		
		case 'rewards':
			targetContainer = null;
			
			rewardsData.currentPage = 1;
			updateMemberRewardScore();
			updateReddemItems();
			loadRewardsItem();
			$('#memberHolder').show();
			$('#sectionRewards').show();
		break;
		
		case 'history':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionRewardHistory').show();
		break;
		
		case 'rewardsconfirm':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionRewardsConfirm').show();
		break;
		
		case 'redeemcomplete':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionRedeemComplete').show();
		break;
		
		case 'thankyou':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionThankyou').show();
		break;
		
		case 'forgotpassword':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionForgotPassword').show();
		break;
		
		case 'forgotpasswordthankyou':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionForgotThankyou').show();
		break;
			
		case 'resetpassword':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionResetPassword').show();
		break;
		
		case 'resetpasswordthankyou':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionResetPasswordThankyou').show();
		break;
		
		case 'topup':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionBuy').show();
			loadProducts();
		break;
		
		case 'processing':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionProcessing').show();
			$('#textDisplay').html('Processing...');
		break;
		
		case 'loading':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionProcessing').show();
			$('#textDisplay').html('Loading...');
		break;
		
		case 'transactionComplete':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionTransactionComplete').show();
		break;
			
		case 'scoreboard':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionScoreboard').show();
		break;
			
		case 'redeemcode':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionRedeemCode').show();
		break;
			
		case 'redeemcodeComplete':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionRedeemCodeComplete').show();
		break;

		case 'moregames':
			targetContainer = null;
			
			$('#memberHolder').show();
			$('#sectionMoreGames').show();
		break;
		
		case '':
			targetContainer = null;
		break;
	}
	
	resizeMemberReward();
}


/*!
 * 
 * CHECK LOGIN - This is the function that runs to check login session
 * 
 */

function checkLoginSession(){
	goMemberPage('loading');
	
	$.ajax({
	  type: "POST",
	  url: 'memberrewards/m_session.php',

	  success: returnLoginSession,
	  dataType  : 'json'
	});
}

function returnLoginSession(data){
	if(data.status == true){
		readyUserLogin(data);
	}else{
		handleMemberServerError(data, false);

		memberData.reset_token = getParameterValue(window.location.href,'reset');
		if(memberData.reset_token != ''){
			goMemberPage('resetpassword');
		}else{
			if(memberSettings.enableConnectFacebook){
				goMemberPage('option');
			}else{
				goMemberPage('login');	
			}
		}
	}
}

function getParameterValue(source, name ){
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec(source);
	if( results == null )
		return "";
	else
		return decodeURIComponent(results[1].replace(/\+/g, " "));
}

/*!
 * 
 * REGISTER DATA - This is the function that runs to register user
 * 
 */
function postSignup(){
	var errorCon = false;
	var errorMessage = '';
	var userIDValue = '';

	if($('#uSName').val().length == 0){
		errorCon = true;
		if(errorMessage == '')
		errorMessage = memberSettings.text.enterName;
	}
	
	if(memberSettings.userIDType == 'email'){
		if($('#uSEmail').val().length == 0){
			errorCon = true;
			if(errorMessage == '')
			errorMessage = memberSettings.text.enterEmail;
		}
	}else{
		if($('#uSMobile').val().length == 0){
			errorCon = true;
			if(errorMessage == '')
			errorMessage = memberSettings.text.enterMobile;
		}
	}
	
	if($('#uSPassword').val().length == 0){
		errorCon = true;
		if(errorMessage == '')
		errorMessage = memberSettings.text.enterPassword;
	}
	
	if($('#uSConfirmPassword').val().length == 0){
		errorCon = true;
		if(errorMessage == '')
		errorMessage = memberSettings.text.enterConfirmPassword;
	}
	
	if($('#uSPassword').val() != $('#uSConfirmPassword').val()){
		errorCon = true;
		if(errorMessage == '')
		errorMessage = memberSettings.text.passwordNotMatch;
	}
	
	if(memberSettings.userIDType == 'email'){
		if(!validateEmail($('#uSEmail').val())){
			errorCon = true;
			if(errorMessage == '')
			errorMessage = memberSettings.text.enterValidEmail;
		}

		userIDValue = $('#uSEmail').val();
	}else{		
		if(!validateMobile($('#uSMobile').val())){
			errorCon = true;
			if(errorMessage == '')
			errorMessage = "\n" + memberSettings.text.enterValidMobile;
		}

		userIDValue = $('#uSMobile').val();
	}
	
	if(errorCon){
		$('#sectionSignup .errMsg').html(errorMessage);
	}else{
		goMemberPage('loading');
		
		//proceed	
		$.ajax({
		  type: "POST",
		  url: 'memberrewards/m_register.php',
		  data: { type: 'default', name: $('#uSName').val(), email: userIDValue, password: $('#uSPassword').val()},
		  success: returnSignup,
		  dataType  : 'json'
		});
	}
}

function validateEmail($email) {
  var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
  return emailReg.test( $email );
}

function validateMobile($mobile) {
	var validMobile = true;

	if($mobile.length < memberSettings.mobileFormat.minLength){
		validMobile = false;
	}

	for(var n=0; n<$mobile.length; n++){
		var curMatch = memberSettings.mobileFormat.matches.substring(n, n+1);
		var curField = $mobile.substring(n, n+1);
		if(curMatch == '9'){
			if(isNaN(curField)){
				validMobile = false;
			}
		}else if(curMatch != '9'){
			if(curMatch != curField){
				validMobile = false;
			}
		}
	}
	return validMobile;
  }

function returnSignup(data){
	if(data.status == true){
		goMemberPage('thankyou');
	}else{
		handleMemberServerError(data, false);

		goMemberPage('signup');
		$('#sectionSignup .errMsg').html(data.message);
	}
}

/*!
 * 
 * LOGIN DATA - This is the function that runs to login user
 * 
 */
function postLogin(){
	var errorCon = false;
	var errorMessage = '';
	var userIDValue = '';
	
	if(memberSettings.userIDType == 'email'){
		if($('#uEmail').val().length == 0){
			errorCon = true;
			if(errorMessage == '')
			errorMessage = "\n" + memberSettings.text.enterEmail;
		}
	}else{
		if($('#uMobile').val().length == 0){
			errorCon = true;
			if(errorMessage == '')
			errorMessage = "\n" + memberSettings.text.enterMobile;
		}
	}
	
	if($('#uPassword').val().length == 0){
		errorCon = true;
		if(errorMessage == '')
		errorMessage = "\n" + memberSettings.text.enterPassword;
	}
	
	if(memberSettings.userIDType == 'email'){
		if(!validateEmail($('#uEmail').val())){
			errorCon = true;
			if(errorMessage == '')
			errorMessage = "\n" + memberSettings.text.enterValidEmail;
		}

		userIDValue = $('#uEmail').val();
	}else{		
		if(!validateMobile($('#uMobile').val())){
			errorCon = true;
			errorMessage = "\n" + memberSettings.text.enterValidMobile;
		}

		userIDValue = $('#uMobile').val();
	}
	
	if(errorCon){
		$('#sectionLogin .errMsg').html(errorMessage);
	}else{
		goMemberPage('loading');
		
		//proceed	
		$.ajax({
		  type: "POST",
		  url: 'memberrewards/m_login.php',
		  data: { type:'default', email: userIDValue, password: $('#uPassword').val()},
		  success: returnLogin,
		  dataType  : 'json'
		});
	}
}

function returnLogin(data){
	if(data.status == true){
		readyUserLogin(data);
	}else{
		handleMemberServerError(data, false);

		goMemberPage('login');
		$('#sectionLogin .errMsg').html(data.message);
	}
}

function readyUserLogin(data){
	memberData.member_name = data.member_name;
	memberData.member_email = data.member_email;
	memberData.member_id = data.member_id;
	memberData.token = data.token;
	memberData.gameType = data.game_type;
	
	
	memberData.chance = memberData.point = memberData.score = 0;
	readyUserPoint(data);
	
	toggleUserDetails(true);
}

/*!
 * 
 * LOGOUT - This is the function that runs to logout user
 * 
 */

function postLogout(){
	goMemberPage('loading');
	
	$.ajax({
	  type: "POST",
	  url: 'memberrewards/m_logout.php',
	  success: returnLogout,
	  dataType  : 'json'
	});	
}

function returnLogout(data){
	if(data.status == true){
		location.reload();
	}
}

/*!
 * 
 * FORGOT PASSWORD - This is the function that runs to retrieve password
 * 
 */
function postForgot(){
	var errorCon = false;
	var errorMessage = '';
	
	if($('#uForgotEmail').val().length == 0){
		errorCon = true;
		if(errorMessage == '')
		errorMessage = memberSettings.text.enterEmail;
	}
	
	if(!validateEmail($('#uForgotEmail').val())){
		errorCon = true;
		if(errorMessage == '')
		errorMessage = memberSettings.text.enterValidEmail;
	}
	
	if(errorCon){
		$('#sectionForgotPassword .errMsg').html(errorMessage);
	}else{
		goMemberPage('loading');
		
		$.ajax({
		  type: "POST",
		  url: 'memberrewards/m_email.php',
		  data: { member_email:$('#uForgotEmail').val()},
		  success: returnForgot,
		  dataType  : 'json'
		});	
	}
}

function returnForgot(data){
	if(data.status == true){
		goMemberPage('forgotpasswordthankyou');
	}else{
		handleMemberServerError(data, false);

		goMemberPage('forgotpassword');
		$('#sectionForgotPassword .errMsg').html(data.message);	
	}
}

/*!
 * 
 * RESET PASSWORD - This is the function that runs to reset password
 * 
 */
function postReset(){
	var errorCon = false;
	var errorMessage = '';
	
	if($('#uRPassword').val().length == 0){
		errorCon = true;
		if(errorMessage == '')
		errorMessage = memberSettings.text.enterPassword;
	}
	
	if($('#uRConfirmPassword').val().length == 0){
		errorCon = true;
		if(errorMessage == '')
		errorMessage = memberSettings.text.enterConfirmPassword;
	}
	
	if($('#uRPassword').val() != $('#uRConfirmPassword').val()){
		errorCon = true;
		if(errorMessage == '')
		errorMessage = memberSettings.text.passwordNotMatch;
	}
	
	if(errorCon){
		$('#sectionResetPassword .errMsg').html(errorMessage);
	}else{
		goMemberPage('loading');
		
		$.ajax({
		  type: "POST",
		  url: 'memberrewards/m_reset_password.php',
		  data: { member_password:$('#uRPassword').val(), reset_token:memberData.reset_token},
		  success: returnReset,
		  dataType  : 'json'
		});	
	}
}

function returnReset(data){
	if(data.status == true){
		goMemberPage('resetpasswordthankyou');
		
		window.history.pushState(null, null, removeParams('reset'));
	}else{
		handleMemberServerError(data, false);
		
		goMemberPage('resetpassword');
		$('#sectionResetPassword .errMsg').html(data.message);	
	}
}

function removeParams(sParam)
{
	var url = window.location.href.split('?')[0]+'?';
	var sPageURL = decodeURIComponent(window.location.search.substring(1)),
		sURLVariables = sPageURL.split('&'),
		sParameterName,
		i;

	for (i = 0; i < sURLVariables.length; i++) {
		sParameterName = sURLVariables[i].split('=');
		if (sParameterName[0] != sParam) {
			url = url + sParameterName[0] + '=' + sParameterName[1] + '&'
		}
	}
	return url.substring(0,url.length-1);
}

/*!
 * 
 * TOGGLE MEMBER LOADER - This is the function that runs to toggle member loader
 * 
 */


/*!
 * 
 * UPDATE USER DATA - This is the function that runs to update user game data
 * 
 */
function updateUserPoint(func, data){
	toggleMemberInGameLoader(true, memberSettings.text.connecting);
	memberData.ready = false;
	memberData.callback = func;
	updateUserPointData();
	
	//proceed
	$.ajax({
	  type: "POST",
	  url: 'memberrewards/m_update_point.php',
	  data: {member_id:memberData.member_id, member_chance:memberData.chance, member_point:memberData.point, member_score:memberData.score, bet:data.bet, win:data.win, status:data.status, token:memberData.token},
	  success: returnUpdateUserPoint,
	  dataType  : 'json'
	});
}

function returnUpdateUserPoint(data){
	if(data.status == true){
		toggleMemberInGameLoader(false);
		memberData.token = data.token;
		readyUserPoint(data);
		memberData.ready = true;

		if(memberData.callback != undefined){
			var updateFunc = window[memberData.callback];
			updateFunc();
		}
	}else{
		//error
		toggleMemberInGameLoader(true, memberSettings.text.connectionError);
		handleMemberServerError(data);
	}
}

/*!
 * 
 * GET USER RESULT - This is the function that runs to get user result
 * 
 */
function getUserResult(func, result){
	toggleMemberInGameLoader(true, memberSettings.text.connecting);
	memberData.ready = false;
	memberData.callback = func;
	
	//proceed
	$.ajax({
	  type: "POST",
	  url: 'memberrewards/m_result.php',
	  data: {member_id:memberData.member_id, token:memberData.token, result_data:JSON.stringify(result)},
	  success: returnGetUserResult,
	  dataType  : 'json'
	});
}

function returnGetUserResult(data){
	if(data.status == true){
		toggleMemberInGameLoader(false);
		memberData.token = data.token;
		memberData.match = data;
		memberData.ready = true;

		if(memberData.callback != undefined){
			var updateFunc = window[memberData.callback];
			updateFunc(data.result);
		}
	}else{
		//error
		toggleMemberInGameLoader(true, memberSettings.text.connectionError);
		handleMemberServerError(data);
	}
}

function matchUserResult(func, data){
	var matchedResult = false;
	if(memberData.match.debug){
		matchedResult = true;
	}else{
		if(gameTypeBothArr.indexOf(memberData.gameType)!=-1){
			if(memberData.match.member_chance == data.chance && memberData.match.member_score == data.score){
				matchedResult = true;
			}
		}else if(gameTypeChanceArr.indexOf(memberData.gameType)!=-1){
			if(memberData.match.member_chance == data.chance && memberData.match.member_point == data.point){
				matchedResult = true;
			}
		}else if(gameTypePointArr.indexOf(memberData.gameType)!=-1){
			if(memberData.match.member_point == data.point){
				matchedResult = true;
			}
		}
	}

	if(matchedResult){
		readyUserPoint(memberData.match);
		if(func != undefined){
			var updateFunc = window[func];
			updateFunc();
		}
	}else{
		toggleMemberInGameLoader(true, memberSettings.text.connectionError);
	}
}

/*!
 * 
 * LOAD USER DATA - This is the function that runs to load user game data
 * 
 */
function loadUserPoint(){
	//proceed
	$.ajax({
	  type: "POST",
	  url: 'memberrewards/m_load_point.php',
	  data: {token:memberData.token},
	  success: returnLoadPoint,
	  dataType  : 'json'
	});
}

function returnLoadPoint(data){
	if(data.status == true){
		memberData.token = data.token;
		
		readyUserPoint(data);
	}else{
		//error
		handleMemberServerError(data);
	}
}

function toggleUserDetails(con){
	userButton.visible = true;
	
	if(memberSettings.enableScoreboard){
		scoreboardButton.visible = true;	
	}
	
	if(con){
		goMemberPage('user');
	}else{
		goMemberPage();
	}
}

/*!
 * 
 * LOAD MORE GAMES - This is the function that runs to load more games
 * 
 */
var moreGamesData = {id:0, totalPages:0, currentPage:1, totalItems:0, totalPerPages:4};
function buildGamesLists(){
	$('.gameEmptyItem').remove();

	moreGamesData.currentPage = 1;
	moreGamesData.totalItems = $('.columnGame').length;
	moreGamesData.totalPages = moreGamesData.totalItems/moreGamesData.totalPerPages;
	if (String(moreGamesData.totalPages).indexOf('.') > -1){
		moreGamesData.totalPages=Math.floor(moreGamesData.totalPages)+1;
	}
	
	var totalDisplayItem = moreGamesData.totalPages * moreGamesData.totalPerPages;
	var missingItem = totalDisplayItem - $('.gameItem').length;

	for(var n=0; n<missingItem; n++){
		$('#gamesLists tr').eq(0).append('<td class="columnGame gameItem gameEmptyItem"></td>');
	}
	
	displayGamesItems();
}

function toggleGamesLists(con){
	if(con){
		moreGamesData.currentPage++;
		moreGamesData.currentPage = moreGamesData.currentPage > moreGamesData.totalPages ? moreGamesData.totalPages : moreGamesData.currentPage;
	}else{
		moreGamesData.currentPage--;
		moreGamesData.currentPage = moreGamesData.currentPage < 1 ? 1 : moreGamesData.currentPage;
	}
	
	displayGamesItems();
}

function displayGamesItems(){
	var startItem = (moreGamesData.currentPage - 1) *  moreGamesData.totalPerPages
	var endItem = startItem + moreGamesData.totalPerPages;
	
	$('.gameItem').each(function(index, element) {
		if(index >= startItem && index < endItem){
			$(this).show();
		}else{
			$(this).hide();	
		}
    });
	
	$('.gamesListNo').html(moreGamesData.currentPage+'/'+moreGamesData.totalPages);
	
	$('.btnMoreGamesLeft').show();
	$('.btnMoreGamesRight').show();	
	if(moreGamesData.currentPage <= 1){
		$('.btnMoreGamesLeft').hide();	
	}
	
	if(moreGamesData.currentPage >= moreGamesData.totalPages){
		$('.btnMoreGamesRight').hide();	
	}
}

/*!
 * 
 * POST REDEEM - This is the function that runs to post redeem
 * 
 */
function postRedeem(){
	goMemberPage('loading');
	
	$.ajax({
	  type: "POST",
	  url: 'memberrewards/m_redeem.php',
	  data: { reward_id:rewardsData.id, token:memberData.token},
	  success: returnRedeem,
	  dataType  : 'json'
	});
}

function returnRedeem(data){
	if(data.status == true){
		memberData.token = data.token;
		loadUserPoint();
		goMemberPage('redeemcomplete');
		goPage('main');
	}else{
		handleMemberServerError(data);
		goMemberPage('rewardsconfirm');
		$('#sectionrewardsconfirm .errMsg').html(data.message);
	}	
}

/*!
 * 
 * LOAD PRODUCTS - This is the function that runs to load products
 * 
 */
function loadProducts(){
	$('#sectionBuy .loadingList').show();
	$('#productLists').hide();
	
	$.ajax({
	  type: "POST",
	  url: 'memberrewards/m_get_product_items.php',
	  success: returnProducts,
	  dataType  : 'json'
	});
}

function returnProducts(data){
	$('#sectionBuy .loadingList').hide();
	$('#productLists').empty().show();
	
	if(data.status == true){
		var productList = data.datas;
		
		if(productList.length>0){
			for(var i=0; i<productList.length; i++){
				if(typeof productList[i] != "undefined"){
					var productHTML = '<label for="'+productList[i].order_id+'"><div class="buyOption fontLink radioSelected" data-fontsize="30" data-lineheight="40"><input id="'+productList[i].order_id+'" type="radio" checked="checked" name="buyOption" value="'+productList[i].order_price+'" hidden><img class="radioOpt" src="memberrewards/assets/radio.png"><span class="textOpt">'+productList[i].order_name+'</span></div></label>';
					
					$('#productLists').append(productHTML);
				}
			}
		}
		
		buildBuyButton();
		resizeMemberReward();
	}else{
		handleMemberServerError(data);
	}
}

/*!
 * 
 * BUILD BUY BUTTON - This is the function that runs to build buy button
 * 
 */
function buildBuyButton(){
	$('.buyOption').each(function(index, element) {
        $(this).click(function(){
			$(this).find('input').prop("checked", true);
			radioHighigt();
		});
    });
	radioHighigt();
}

/*!
 * 
 * POST TRANSACTION - This is the function that runs to post transaction
 * 
 */
function postTransaction(){
	toggleMemberLoader(true);

	$.ajax({
	  type: "POST",
	  url: 'memberrewards/m_transaction.php',
	  data: { type:'create', order_id: $('input[name=buyOption]:checked').attr('id'), token:memberData.token},
	  success: returnPostTransaction,
	  dataType  : 'json'
	});
}

function returnPostTransaction(data){
	toggleMemberLoader(false);

	if(data.status == true){
		memberData.order_created_id = data.order_created_id;
		memberData.token = data.token;
	}else{
		handleMemberServerError(data);
	}	
}

/*!
 * 
 * UPDATE TRANSACTION - This is the function that runs to update transaction
 * 
 */
function updateTransaction(payment_id){
	toggleMemberLoader(true);

	$.ajax({
	  type: "POST",
	  url: 'memberrewards/m_transaction.php',
	  data: { type:'update', payment_id:payment_id, order_created_id: memberData.order_created_id, order_id: $('input[name=buyOption]:checked').attr('id'), token:memberData.token},
	  success: returnUpdateTransaction,
	  dataType  : 'json'
	});
}

function returnUpdateTransaction(data){
	toggleMemberLoader(false);

	if(data.status == true){
		memberData.token = data.token;
		loadUserPoint();
		goMemberPage('transactionComplete');
		goPage('main');
	}else{
		handleMemberServerError(data);
	}	
}

/*!
 * 
 * CHECK GAME FUNC - This is the function that runs to check game func
 * 
 */

var gameTypeBothArr = ['luckywheels','superplinko','extremeplinko'];
var gameTypeChanceArr = ['lotterynumbers','bingobash'];
var gameTypePointArr = ['junglescratch','slotmachine','dicegame','scratchandwin','powerkeno','horseracing','luckyballs'];

function readyUserPoint(data){
	if(gameTypeBothArr.indexOf(memberData.gameType)!=-1){
		var getGameType;
		if(typeof gamePlayType != 'undefined'){
			getGameType = gamePlayType;
		}else{
			getGameType = gameSettings.gamePlayType;
		}

		if(getGameType){
			memberData.chance = playerData.chance = Number(data.member_chance);
			memberData.score = playerData.score = Number(data.member_point);
			memberData.point = playerData.point = Number(data.member_point);
		}else{
			memberData.score = Number(data.member_score);
			memberData.point = playerData.point = Number(data.member_point);
			memberData.chance = playerData.chance = Number(data.member_chance);	
		}
	}else if(gameTypeChanceArr.indexOf(memberData.gameType)!=-1){
		memberData.score = Number(data.member_score);
		memberData.point = Number(data.member_point);
		memberData.chance = playerData.chance = Number(data.member_chance);
	}else if(gameTypePointArr.indexOf(memberData.gameType)!=-1){
		memberData.point = playerData.credit = Number(data.member_point);
	}
}

/*!
 * 
 * UPDATE GAME DATA - This is the function that runs to update game data
 * 
 */
function updateUserPointData(){
	if(gameTypeBothArr.indexOf(memberData.gameType)!=-1){
		var getGameType;
		if(typeof gamePlayType != 'undefined'){
			getGameType = gamePlayType;
		}else{
			getGameType = gameSettings.gamePlayType;
		}

		if(getGameType){
			memberData.chance = playerData.chance;
			memberData.point = playerData.score;
		}else{
			memberData.point = playerData.point;
		}
	}else if(gameTypeChanceArr.indexOf(memberData.gameType)!=-1){
		memberData.chance = playerData.chance;
		memberData.point += playerData.score;
	}else if(gameTypePointArr.indexOf(memberData.gameType)!=-1){
		memberData.point = playerData.creditSum;
	}
}

function checkMemberGameType(){
	if(gameTypeBothArr.indexOf(memberData.gameType)!=-1){
		var getGameType;
		if(typeof gamePlayType != 'undefined'){
			getGameType = gamePlayType;
		}else{
			getGameType = gameSettings.gamePlayType;
		}

		if(getGameType){
			if(playerData.chance > 0){
				return true;
			}else{
				return false;	
			}
		}else{
			if(playerData.point > 0){
				return true;
			}else{
				return false;	
			}
		}
	}else if(gameTypeChanceArr.indexOf(memberData.gameType)!=-1){
		if(playerData.chance > 0){
			return true;
		}else{
			return false;	
		}
	}else if(gameTypePointArr.indexOf(memberData.gameType)!=-1){
		if(playerData.credit > 0){
			return true;
		}else{
			return false;	
		}
	}
}

function updateMemberScore(){
	var thisScore = getUserScore(memberData.point);
	if(gameTypeBothArr.indexOf(memberData.gameType)!=-1){
		if(typeof gamePlayType != 'undefined'){
			getGameType = gamePlayType;
		}else{
			getGameType = gameSettings.gamePlayType;
		}

		if(getGameType){
			$('#userChances').html(memberData.chance);
			$('#userPoints').html(addScoreCommas(thisScore));
		}else{
			$('.scoreDisplay').addClass('hideChance');
			$('#userPoints').html(addScoreCommas(thisScore));
		}
	}else if(gameTypeChanceArr.indexOf(memberData.gameType)!=-1){
		$('#userChances').html(memberData.chance);
		$('#userPoints').html(addScoreCommas(thisScore));	
	}else if(gameTypePointArr.indexOf(memberData.gameType)!=-1){
		$('.scoreDisplay').addClass('hideChance');
		$('#userChances').html(memberData.point);
		$('#userPoints').html(addScoreCommas(thisScore));	
	}
}

function updateMemberRewardScore(){
	var thisScore = getUserScore(memberData.point);
	$('.redeemPoints').html(addScoreCommas(thisScore));
}

/*!
 * 
 * LOAD SCOREBOARD - This is the function that runs to load and display scoreboard
 * 
 */
var scoreListsData = {page:1, newPage:1};
function toggleScorePage(con){
	if(con){
		scoreListsData.newPage++;
		scoreListsData.newPage = scoreListsData.newPage > memberSettings.totalScorePage ? memberSettings.totalScorePage : scoreListsData.newPage;
	}else{
		scoreListsData.newPage--;
		scoreListsData.newPage = scoreListsData.newPage < 1 ? 1 : scoreListsData.newPage;	
	}
	
	loadScoreboard();
}

function detectScorePage(){
	if(memberSettings.totalScorePage <= 1){
		$('#buttonScoreboardNext').hide();
		$('#buttonScoreboardPrev').hide();
	}else{
		$('#buttonScoreboardNext').hide();
		$('#buttonScoreboardPrev').hide();
		if(scoreListsData.page > 1){
			$('#buttonScoreboardPrev').show();
		}
		
		if(scoreListsData.page < memberSettings.totalScorePage){
			$('#buttonScoreboardNext').show();
		}
	}
}

function loadScoreboard(){
	toggleMemberLoader(true);

	if(scoreListsData.newPage != scoreListsData.page){
		scoreListsData.page = scoreListsData.newPage;	
	}
	
	detectScorePage();
	
	var pageLimit = String(((scoreListsData.page-1) * 10)+','+((scoreListsData.page) * 10));
	$.ajax({
	  type: "POST",
	  url: 'memberrewards/m_scoreboard.php',
	  data: {reverse:memberSettings.scoreReverse, limit:pageLimit, format:memberSettings.scoreListingFormat},
	  success: returnScoreboard,
	  dataType  : 'json'
	});	
}

function returnScoreboard(data){
	toggleMemberLoader(false);
	$('.scoreboardDisplay').empty();
	
	var fontsize = 20;
	var lineheight = 25;
	var listHTML = '<tr class="columnDisplayColor"><td class="columnRank"><div class="label fontLink" data-fontsize="'+fontsize+'" data-lineheight="'+lineheight+'">Rank</div></td><td class="columnName"><div class="label fontLink" data-fontsize="'+fontsize+'" data-lineheight="'+lineheight+'">Name</div></td><td class="columnScore"><div class="label fontLink" data-fontsize="'+fontsize+'" data-lineheight="'+lineheight+'">Score</div></td></tr>';
	$('.scoreboardDisplay').append(listHTML);
	
	var count = (scoreListsData.page-1) * 10;
	for(var i=0; i<10; i++){
		var listCount = memberSettings.scoreRank_arr[count] == undefined ? count+1 : memberSettings.scoreRank_arr[count];
		var listHTML = '<tr><td class="columnRank"><div class="label fontLink" data-fontsize="'+fontsize+'" data-lineheight="'+lineheight+'">'+listCount+'</div></td><td class="columnName"><div class="label fontLink" data-fontsize="'+fontsize+'" data-lineheight="'+lineheight+'"></div></td><td class="columnScore columnScoreColor"><div class="label fontLink" data-fontsize="'+fontsize+'" data-lineheight="'+lineheight+'"></div></td></tr>';
		$('.scoreboardDisplay').append(listHTML);
		count++;
	}
	
	if(data.status == true){
		var scoreList = data.datas;
		
		if(scoreList.length>0){
			for(var i=0; i<scoreList.length; i++){
				if(typeof scoreList[i] != "undefined"){
					var thisScore = getUserScore(scoreList[i].member_point);
					$('.columnName .label').eq(i+1).html(scoreList[i].member_name);
					$('.columnScore .label').eq(i+1).html(addScoreCommas(thisScore));
				}
			}
		}
		
		goMemberPage('scoreboard');
		resizeMemberReward();
	}else{
		handleMemberServerError(data);
		goMemberPage('scoreboard');
		resizeMemberReward();
	}
}

/*!
 * 
 * REDEMPTION HISTORY - This is the function that runs to load redemption history
 * 
 */
var historyListsData = {page:1, newPage:1, total:0};
function toggleHistoryPage(con){
	if(con){
		historyListsData.newPage++;
		historyListsData.newPage = historyListsData.newPage > historyListsData.total ? historyListsData.total : historyListsData.newPage;
	}else{
		historyListsData.newPage--;
		historyListsData.newPage = historyListsData.newPage < 1 ? 1 : historyListsData.newPage;	
	}
	
	loadRedemptionHistory();
}

function detectRedemptionHistory(){
	if(historyListsData.total <= 1){
		$('#buttonHistoryNext').hide();
		$('#buttonHistoryPrev').hide();
	}else{
		$('#buttonHistoryNext').hide();
		$('#buttonHistoryPrev').hide();
		if(historyListsData.page > 1){
			$('#buttonHistoryPrev').show();
		}
		
		if(historyListsData.page < historyListsData.total){
			$('#buttonHistoryNext').show();
		}
	}
}

function loadRedemptionHistory(){
	if(historyListsData.newPage != historyListsData.page){
		historyListsData.page = historyListsData.newPage;	
	}
	
	var pageLimit = String(((historyListsData.page-1) * 10)+','+((historyListsData.page) * 10));
	$.ajax({
	  type: "POST",
	  url: 'memberrewards/m_redemption_history.php',
	  data: {reverse:false, limit:pageLimit},
	  success: returnRedemptionHistory,
	  dataType  : 'json'
	});
}

function returnRedemptionHistory(data){
	$('.redemptionHistoryDisplay').empty();
	
	var fontsize = 20;
	var lineheight = 25;
	var listHTML = '<tr class="columnHistoryDisplayColor"><td class="columnHistoryNo"><div class="label fontLink" data-fontsize="'+fontsize+'" data-lineheight="'+lineheight+'">No</div></td><td class="columnHistoryName"><div class="label fontLink" data-fontsize="'+fontsize+'" data-lineheight="'+lineheight+'">Name</div></td><td class="columnHistoryPoint"><div class="label fontLink" data-fontsize="'+fontsize+'" data-lineheight="'+lineheight+'">Points</div></td><td class="columnHistoryDate"><div class="label fontLink" data-fontsize="'+fontsize+'" data-lineheight="'+lineheight+'">Date</div></td></tr>';
	$('.redemptionHistoryDisplay').append(listHTML);
	
	var count = (historyListsData.page-1) * 10;
	for(var i=0; i<10; i++){
		var listHTML = '<tr><td class="columnHistoryNo"><div class="label fontLink" data-fontsize="'+fontsize+'" data-lineheight="'+lineheight+'">'+(count+1)+'</div></td><td class="columnHistoryName"><div class="label fontLink" data-fontsize="'+fontsize+'" data-lineheight="'+lineheight+'"></div></td><td class="columnHistoryPoint columnHistoryPointColor"><div class="label fontLink" data-fontsize="'+fontsize+'" data-lineheight="'+lineheight+'"></div></td><td class="columnHistoryDate"><div class="label fontLink" data-fontsize="'+fontsize+'" data-lineheight="'+lineheight+'"></div></td></tr>';
		$('.redemptionHistoryDisplay').append(listHTML);
		count++;
	}
	
	if(data.status == true){
		var historyList = data.datas;
		historyListsData.total = data.total/10;
		if (String(historyListsData.total).indexOf('.') > -1){
			historyListsData.total=Math.floor(historyListsData.total)+1;
		}
		
		if(historyList.length>0){
			for(var i=0; i<historyList.length; i++){
				if(typeof historyList[i] != "undefined"){
					var thisPoint = getUserScore(historyList[i].reward_points);
					$('.columnHistoryName .label').eq(i+1).html(historyList[i].reward_name);
					
					$('.columnHistoryPoint .label').eq(i+1).html(addScoreCommas(thisPoint));
					$('.columnHistoryDate .label').eq(i+1).html(historyList[i].date_created);
				}
			}
		}
		
		goMemberPage('history');
		resizeMemberReward();
	}else{
		handleMemberServerError(data);
		goMemberPage('history');
		resizeMemberReward();
	}
	
	detectRedemptionHistory();
}

/*!
 * 
 * LOAD REWARDS - This is the function that runs to load rewards
 * 
 */
var rewardsData = {id:0, totalPages:0, currentPage:1, totalItems:0, totalPerPages:4};

function loadRewardsItem(){
	$('#sectionRewards .loadingList').show();
	$('#rewardLists').hide();
	
	$.ajax({
	  type: "POST",
	  url: 'memberrewards/m_get_reward_items.php',
	  success: returnRewardsItem,
	  dataType  : 'json'
	});
}

function returnRewardsItem(data){
	$('#sectionRewards .loadingList').hide();
	$('#rewardLists').show();
	$('#rewardLists tr').eq(0).empty();
	
	if(data.status == true){
		var rewardLists = data.datas;
		rewardsData.totalItems = rewardLists.length;
		
		if(rewardLists.length>0){
			for(var i=0; i<rewardLists.length; i++){
				if(typeof rewardLists[i] != "undefined"){
					var thisScore = getUserScore(rewardLists[i].reward_points);
					
					var rewardNameSize = 25;
					var rewardNameLineheight = 30;
					var rewardScoreSize = 30;
					var rewardScoreLineheight = 40;
					var rewardItemHTML = '<td class="columnReward redeemItem"><img class="redeem_image" src="'+rewardLists[i].reward_image+'" /><div class="redeem_name fontLink" data-fontsize="'+rewardNameSize+'" data-lineheight="'+rewardNameLineheight+'">'+rewardLists[i].reward_name+'</div><div class="redeem_points fontLink" data-fontsize="'+rewardScoreSize+'" data-lineheight="'+rewardScoreLineheight+'">'+addScoreCommas(thisScore)+'</div><div class="btnRedeem buttonRedeem" data-id="'+i+'" data-redeem-id="'+rewardLists[i].id+'" data-points="'+rewardLists[i].reward_points+'"><img alt="'+rewardLists[i].reward_name+'" src="memberrewards/assets/button_redeem_item.png" /></div><div class="buttonRedeem"><img src="memberrewards/assets/button_redeem_item_disabled.png" /></div></td>';
					
					$('#rewardLists tr').eq(0).append(rewardItemHTML);
				}
			}
		}
		
		buildrewardLists();
		resizeMemberReward();
	}else{
		//no reddem items
		handleMemberServerError(data);
	}
}

function buildrewardLists(){
	rewardsData.totalPages = rewardsData.totalItems/rewardsData.totalPerPages;
	if (String(rewardsData.totalPages).indexOf('.') > -1){
		rewardsData.totalPages=Math.floor(rewardsData.totalPages)+1;
	}	
	
	$('.btnRedeem').each(function(index, element) {
		$(this).click(function(){
			rewardsData.id = $(this).attr('data-redeem-id');
			loadRedeemSingle($(this).attr('data-id'));
			goMemberPage('rewardsconfirm');
		});
	});
	
	var totalDisplayItem = rewardsData.totalPages * rewardsData.totalPerPages;
	var missingItem = totalDisplayItem - $('.redeemItem').length;
	for(var n=0; n<missingItem; n++){
		$('#rewardLists tr').eq(0).append('<td class="columnReward redeemItem"></td>');
	}
	
	displayRedeemItems();
}

function loadRedeemSingle(id){
	$('.columnRewardSingle .redeem_image').attr('src', $('.redeemItem').eq(id).find('.redeem_image').attr('src'));
	$('.columnRewardSingle .redeem_name').html($('.redeemItem').eq(id).find('.redeem_name').html());
	$('.columnRewardSingle .redeem_points').html($('.redeemItem').eq(id).find('.redeem_points').html());
}

function togglerewardLists(con){
	if(con){
		rewardsData.currentPage++;
		rewardsData.currentPage = rewardsData.currentPage > rewardsData.totalPages ? rewardsData.totalPages : rewardsData.currentPage;
	}else{
		rewardsData.currentPage--;
		rewardsData.currentPage = rewardsData.currentPage < 1 ? 1 : rewardsData.currentPage;
	}
	
	displayRedeemItems();
}

function displayRedeemItems(){
	var startItem = (rewardsData.currentPage - 1) *  rewardsData.totalPerPages
	var endItem = startItem + rewardsData.totalPerPages;
	 
	$('.redeemItem').each(function(index, element) {
		if(index >= startItem && index < endItem){
			$(this).show();
		}else{
			$(this).hide();	
		}
    });
	
	$('.redeemListNo').html(rewardsData.currentPage+'/'+rewardsData.totalPages);
	
	$('.btnRedeemLeft').show();
	$('.btnRedeemRight').show();	
	if(rewardsData.currentPage <= 1){
		$('.btnRedeemLeft').hide();	
	}
	
	if(rewardsData.currentPage >= rewardsData.totalPages){
		$('.btnRedeemRight').hide();	
	}
	
	updateReddemItems();
}

function updateReddemItems(){
	$('.redeemItem').each(function(index, element) {
		var thisItemPoint = Number($(this).find('.btnRedeem').attr('data-points'));
		if(thisItemPoint <= memberData.point){
			$(this).find('.buttonRedeem').eq(0).show();	
			$(this).find('.buttonRedeem').eq(1).hide();
		}else{
			$(this).find('.buttonRedeem').eq(0).hide();	
			$(this).find('.buttonRedeem').eq(1).show();	
		}
    });	
}

/*!
 * 
 * RESIZE MEMBER - This is the function that runs to resize member
 * 
 */
function resizeMemberReward(){
	if(typeof viewport != 'undefined'){
		if(viewport.isLandscape){
			rewardsData.totalPerPages = 4;
			moreGamesData.totalPerPages = 4;
			$('#memberHolder').removeClass('portrait');
			$('#memberBg').attr('src','memberrewards/assets/background.png');
		}else{
			rewardsData.totalPerPages = 2;
			moreGamesData.totalPerPages = 2;
			$('#memberHolder').addClass('portrait');
			$('#memberBg').attr('src','memberrewards/assets/background_portrait.png');
		}

		buildGamesLists();
	}
	
	var safezone = {w:1024, h:576};
	
	$('.fontLink').each(function(index, element) {
		$(this).css('font-size', Math.round(Number($(this).attr('data-fontsize'))*scalePercent)+'px');
		$(this).css('line-height', Math.round(Number($(this).attr('data-lineheight'))*scalePercent)+'px');
	});
	
	$('#memberHolder').css('width',stageW*scalePercent);
	$('#memberHolder').css('height',stageH*scalePercent);
	
	$('#memberHolder').css('left', (offset.left/2));
	$('#memberHolder').css('top', (offset.top/2));
	
	$('#memberHolder .memberInnerContent').css('width',safezone.w*scalePercent);
	$('#memberHolder .memberInnerContent').css('height',safezone.h*scalePercent);
	
	var spaceTop = (stageH - safezone.h)/2;
	var spaceLeft = (stageW - safezone.w)/2;
	$('#memberHolder .memberInnerContent').css('left', spaceLeft*scalePercent);
	$('#memberHolder .memberInnerContent').css('top', spaceTop*scalePercent);
	
	if (typeof userButton != "undefined") {
		userButton.x = offset.x + 50;
		userButton.y = offset.y + 40;
		scoreboardButton.x = offset.x + 115;
		scoreboardButton.y = offset.y + 40;

		memberTxtBg.x = canvasW/2;
		memberTxtBg.y = canvasH/2;
		memberTxtShadowBg.x = memberTxtBg.x;
		memberTxtShadowBg.y = memberTxtBg.y + 8;
		memberLoaderTxt.x = memberTxtBg.x;
		memberLoaderTxt.y = memberTxtBg.y + 10;
	}
}

/*!
 * 
 * ADDTIONAL FUNC - This is the function that runs for additional func
 * 
 */
function addScoreCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}


/*!
 * 
 * FACEBOOK FUNC - This is the function that runs for facebook func
 * 
 */	
function initFBConnect(){
	$.ajaxSetup({ cache: true });
	$.getScript('//connect.facebook.net/en_US/sdk.js', function(){
		FB.init({
		  appId: memberSettings.fbAppID,
		  version: 'v2.5'
		});
	});
 }

function updateFbLoginCallback(response){
	if (response.status === 'connected') {
		FB.api('/me', {fields: 'first_name,last_name,name,id,picture.width(150).height(150)'}, function(response) {
			console.log(response);
			memberData.fb_id = response.id;
			memberData.member_name = response.name;
			memberData.type = 'fb';
			
			postFbConnect();
		});
	}else{
		console.log('Facebook not connected');
	}
}

function postFbConnect(){
	//proceed	
	$.ajax({
	  type: "POST",
	  url: 'memberrewards/m_facebook.php',
	  data: { type:'fb', name: memberData.member_name, fb_id: memberData.fb_id},
	  success: returnFbConnect,
	  dataType  : 'json'
	});
}

function returnFbConnect(data){
	if(data.status == true){
		readyUserLogin(data);
	}else{
		goMemberPage('option');
		$('#sectionLoginOption .errMsg').html(data.message);
	}
}

/*!
 * 
 * MISC FUNC - This is the function that runs for misc func
 * 
 */	
function handleMemberServerError(data, session){
	var checkSession = session == false ? false : true;

	if(data.error){
		alert(data.message);
	}else if(data.session == false){
		if(checkSession){
			alert(memberSettings.text.sessionTimeout);
			location.reload();
		}
	}
}

function getUserScore(score){
	if(memberSettings.scoreDisplay.type){
		return memberSettings.scoreDisplay.point.replace('[NUMBER]', score);
	}else{
		return addPointCommas(memberSettings.scoreDisplay.currency.replace('[NUMBER]', formatRewardCurrency(score)));	
	}	
}

function addPointCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function formatRewardCurrency(total) {
	/*var neg = false;
    if(total < 0) {
        neg = true;
        total = Math.abs(total);
    }
	return (neg ? "-" : '') + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "1,").toString();*/
	total = Number(total).toFixed(2);
	return total.toLocaleString("en");
}

/*!
 * 
 * INIT GAME FUNC - This is the function that runs for init game func
 * 
 */	
function initGameSettings(){
	$.ajax({
	  type: "POST",
	  url: 'memberrewards/m_settings.php',
	  data:{},
	  success: returnGameSettings,
	  dataType  : 'json',
	  error: function (request, status, error) {
			alert(request.responseText);
		}
	});
}

function returnGameSettings(data){	
	if(data.status == true){
		var settingsList = data.datas;
		if(settingsList.length>0){
			for(var i=0; i<settingsList.length; i++){
				if(typeof settingsList[i] != "undefined"){
					window[settingsList[i].setting_name] = settingsList[i].setting_value;
				}
			}
		}
		
		initPreload();
	}else{
		initPreload();
	}
}

/*!
 * 
 * REDEEM CODE DATA - This is the function that runs to redeem code
 * 
 */
function postRedeemCode(){
	var errorCon = false;
	var errorMessage = '';
	
	if($('#uRedeemCode').val().length == 0){
		errorCon = true;
		if(errorMessage == '')
		errorMessage = "\n" + memberSettings.text.enterRedeemCode;
	}
	
	if(errorCon){
		$('#sectionRedeemCode .errMsg').html(errorMessage);
	}else{
		toggleMemberLoader(true);
		goMemberPage('loading');
		
		//proceed	
		$.ajax({
		  type: "POST",
		  url: 'memberrewards/m_redeem_code.php',
		  data: { redeemcode: $('#uRedeemCode').val(), token:memberData.token},
		  success: returnRedeemCode,
		  dataType  : 'json'
		});
	}
}

function returnRedeemCode(data){
	toggleMemberLoader(false);

	if(data.status == true){
		memberData.token = data.token;
		readyUserPoint(data);
		goMemberPage('redeemcodeComplete');
		
		var redeemList = data.datas;
		if(redeemList.length>0){
			for(var i=0; i<redeemList.length; i++){
				if(typeof redeemList[i] != "undefined"){
					$('#sectionRedeemCodeComplete .label').addClass('extraTopContentL');
					$('#sectionRedeemCodeComplete .redeem_image').hide();
					if(redeemList[i].redeem_image != ''){
						$('#sectionRedeemCodeComplete .label').removeClass('extraTopContentL');
						$('#sectionRedeemCodeComplete .redeem_image').show();
						$('#sectionRedeemCodeComplete .redeem_image').attr('src',redeemList[i].redeem_image);
					}
					$('#sectionRedeemCodeComplete .redeem_name').html(redeemList[i].redeem_name);
				}
			}
		}
	}else{
		goMemberPage('redeemcode');
		$('#sectionRedeemCode .errMsg').html(data.message);
	}
}

/*!
 * 
 * TOGGLE MEMBER LOADER - This is the function that runs to toggle member loader
 * 
 */
function toggleMemberLoader(con){
	if(con){
		$('#sectionLoader').show();
	}else{
		$('#sectionLoader').hide();
	}
}

function toggleMemberInGameLoader(con, message){
	memberLoaderTxt.text = message;
	memberLoaderContainer.visible = con;
}