"use strict";

(function($){
	
	$( document ).bind( "mobileinit", function() {
    	// jQuery Mobile framework configuration changes!
    	$.mobile.allowCrossDomainPages = true;

    	//$.mobile.defaultPageTransition = 'slide';
	});

	var refreshLabels = function(){
		$('label').each(function(idx,elm){
			var jElm = $(elm);
			//console.log(jElm,jElm.parent());
			//console.log(jElm.parent().hasClass('ui-field-contain'));
			if(jElm.parent().hasClass('ui-field-contain')){
				
				jElm.removeClass('ui-hidden-accessible');
				
			}else{
				
				jElm.addClass('ui-hidden-accessible');
				
			}

		});
	}

	var recalcDates = function(){
		//console.log("recalcDates");
		jQuery("abbr.timeago").timeago();
	}

	var changeScreen = function(side){
		side = side === 'landscape' ? side : 'portrait';
		if(typeof window.plugins !== "undefined" && typeof window.plugins.orientationLock !== "undefined" && typeof window.plugins.orientationLock.lock !== "undefined"){
			window.plugins.orientationLock.lock(side);
		}
	}

	var loginUser = function (signin_username,signin_password) {
		console.log("loginUser : " + signin_username + "," + signin_password);
		if(typeof(signin_username) !== "undefined" && signin_username.length > 2 && typeof(signin_password)!== "undefined" && signin_password.length > 2){
			console.log("inside signin user");
			yumpod_service.showWaitLoader("Signing in " + signin_username);
			var userHash = serv_Base64.encode(signin_username + ":" + signin_password);
			//$.when(send_request("login",null,{"username":signin_username,"password":signin_password}))
			$.when(send_request("login",null,{"userHash":userHash,"username":signin_username,"password":signin_password}))
				.done(function(data){
					yumpod_service.hideWaitLoader();
					//console.log(data);
					data = parseJson(data);
					//console.log("Successful to get response for login ",arguments);
					if(data && data["data"] && data["data"]["status"] && data["data"]["status"] === "success" && data["data"]["user"]){
						//console.log("Writing to localStorage");
						var playerDict = data["data"]["user"];
						playerDict["userHash"] = userHash;
						yumpod_service.triggerEvent("login",playerDict);
					}else{
						console.log("No data found",data);
						if(data && data["data"] && data["data"]["statusMessage"]){
							yumpod_service.triggerEvent("popup","Login Unsuccessful",null,data["data"]["statusMessage"]);
						}
						yumpod_service.triggerEvent("logout");
						
					}
				}).fail(function(error){
					yumpod_service.hideWaitLoader();
					console.log("Failed to get response for login",arguments);
					yumpod_service.triggerEvent("popup","Login Unsuccessful",null,"Failed to get response for login",error);
					yumpod_service.triggerEvent("logout");
				});
		}else{
			yumpod_service.triggerEvent("popup","Login Unsuccessful",null,"Please enter username and password");
		}
	}

	var parseJson = function(data){
		try{
			data = JSON.parse(data);
		}catch(e){
			console.log("Exceoption parsing JSON",data);
			return null;
		}
		return data;
	}

	var jPages = {
		'login' : $("#loginPage"),
		'gameSelection' : $("#gameSelectionPage"),
		'gamerSignup': $("#gamerSignupPage"),
		'parentSignup': $("#parentSignupPage"),
		'me' : $("#mePage"),
		'timeline' : $("#timelinePage"),
		'challenge' : $("#challengePage"),
		'postStatus' : $("#postStatusPage"),
		'popupMsg' : $("#popupMsgPage"),
		'profile' : $("#profilePage"),
		'replyStatus' : $("#replyStatusPage"),
		'sendEmail' : $('#sendEmailPage'),
		'imageUpload' : $('#imageUploadPage'),
		'search':$('#searchPage'),
		'notification':$("#notificationPage"),
		'profileedit':$("#profileeditPage"),
		'gameresult' : $("#gameResultPage"),
		'forgotPassword' : $("#forgotPasswordPage"),
		'detailstatus' : $("#detailStatusPage")
	};

	var URLs = {
		"base" : "http://54.254.239.126/youvstheworld1/index.php/",
		//"base" : "http://localhost:8000/",
		//"base" : "http://ws.dev/yumpod-rest/public/index.php/",
		//"base" : "http://146.185.143.121/yumpod/yumpod-rest/public/index.php/",
		"login" : "userservice/login",
		"signup" : "userservice/sign_up",
		"forgotpassword" : "userservice/forgotpassword",

		"usernameexists" : "userservice/user_exist",
		"searchusername" : "userservice/searchusers",
		
		"games" : "userservice/games",
		"pushscore" : "userservice/get_game_details",
		"postgame" : "userservice/postgame",
		
		"addfollower" : "userservice/insert_follewer",
		"removefollower" : "userservice/unfollow_user",
		"getfollowers" : "userservice/getfollower",
		"unblockUser" : "userservice/unblock_user",
		"blockUser" : "userservice/block_user",
		
		"poststatus" : "userservice/add_status",
		"replystatus" : "userservice/reply",
		"likestatus" : "userservice/status_like",
		"sharestatus" : "userservice/share_status",
		"deletestatus" : "userservice/delete_status",
		
		"createchallenge" : "userservice/challenge",
		"acceptchallenge" : "userservice/challengeAccept",
		"declinechallenge" : "userservice/challengeDecline",
		"remindchallenge" : "userservice/challengeReminder",
		"getchallenges" : "userservice/getChallenges",
		"challengeresult" : "userservice/challengeWon",

		"searchuser" : "userservice/search_users",
		"getuserprofile" : "userservice/oneuserinfo",

		"me" : "userservice/myprofile",
		"updatebio" : "userservice/updateBio",
		"uploadPhoto" : "userservice/imageupload",
		"timeline" : "userservice/timeline",

		"notifications" : "userservice/notifications",

		"deviceregistration" : "userservice/device_registration",

		"pushpayment" : "userservice/payment_details"

	};

	
	
	//for common post function
	var send_request = function(url,method,data){
		
		method = (method !== "get") ? "POST" : "GET" ;
		data = data ? data : {} ;
		if(URLs && URLs[url]){
			return $.ajax({
			  type: method,
			  url: URLs["base"] + URLs[url],
			  data: data
			});
		}else{
			console.log("No uri found with name " + url);
		}
		return null;
	}

	var yumpod_pageload_service = function(){
		//console.log("loading yumpod_pageload events");
		var currentPage = "";
		var pageCount = 0;
		$( document ).on( "pagebeforechange", function( event , pageData) { 
			//console.log("pagebeforechange event init ", arguments);
			//console.log("pagebeforechange event on  " + pageData.toPage[0]['id'] , typeof (pageData.toPage),pageData.toPage);
			var pageId = null;
			if(typeof(pageData.toPage) === "string"){
				var pageNameArr = pageData.toPage.match("[.]*#([\\w]+)$");
				if(pageNameArr && typeof (pageNameArr[1]) !== "undefined" ){
					pageId = pageNameArr[1];
				}
			}else{
				pageId = pageData.toPage[0]['id'];
			}
			//console.log("pageId",pageId);
			if(currentPage !== pageId){
				pageCount = 0;
				currentPage = pageId;
			}
			if(pageCount === 1){
				yumpod_controllers.load(pageData.toPage[0]['id']);
				refreshLabels();
				
			}
			pageCount++;
		} );
		$( document ).on( "pagecreate", function( event , pageData) { 
			//console.log("page has changed",pageData);
			recalcDates();
			
		});
	}();

	/*
	var currentOrientation = 'landscape';
	var toggleOrientation = function(){
		currentOrientation = currentOrientation === 'landscape' ? 'portrait' : 'landscape';
		changeScreen(currentOrientation);
		setTimeout(toggleOrientation,4000);
	}
	*/


	var yumpod_controllers = function(){
		var r = {};
		var ctrl = {};

		ctrl.gameSelectionPage = function(){
			console.log("ctrl.gameSelectionPage called");
			changeScreen('portrait');
			yumpod_service.showWaitLoader("Getting game list");
			var player = yumpod_service.checkLoginAndGetPlayerDict();
			var userid = player? player["userid"] : null;
			var userHash = player? player["userHash"] : null;
			//console.log("userid=" + userid  + "&userHash=" + userHash);
			$.when(send_request("games",null,
					{"userid":userid,"userHash":userHash}
				)
			).done(function(data){
				yumpod_service.hideWaitLoader();
				//console.log("games list get success",arguments);
				data= parseJson(data);
				
				var games = data;
				
				for(var idx in games){
					var game = games[idx];
					//console.log("game.enabled:",game.enabled, typeof game.enabled)
					game.enabled = game.enabled === "true" ? true : false;
					game.bought = game.bought === "true" ? true : false;
				}
				//alert("Games : " + JSON.stringify(games));
				yumpod_store.set("games",games,true);
				yumpod_service.triggerEvent("loadGames",games);
			}).fail(function(error){
				yumpod_service.hideWaitLoader();
				console.log("games list get fail",arguments);
			});
		}

		ctrl.gameResultPage = function(){
			changeScreen('portrait');
			var player, userid, userHash, currentScore, currentSelectedGame;
			

			var fn_getGameScore = function(){
				changeScreen('portrait');
				if(userHash && currentSelectedGame){
					yumpod_service.showWaitLoader("Please wait. Getting game details.");
					$.when(send_request("postgame",null,
							{"gameid":currentSelectedGame,"userHash":userHash}
						)
					).done(function(data){
						yumpod_service.hideWaitLoader();
						console.log("gameResultPage list get success",arguments);

						try{
							data= parseJson(data);
							console.log("data",data);
							if(data["status"] && data["status"] === "success"){
								var gameName = "";
								if(data["game"]){
									gameName = data["game"];
								}

								jPages['gameresult'].find("#gameresult-gameimage").attr('src',"mobileimgs/game-screens/" + currentSelectedGame + ".png");
								jPages['gameresult'].find("#gameresult-gamename").html(gameName);
								console.log(jPages['gameresult'].find("#gameresult-gamename"),gameName);

								var gameCoins = 0;
								if(data["Coins"]){
									gameCoins = data["Coins"];
								}
								jPages['gameresult'].find("#gameresult-coins").html(gameCoins);

								var gameScore = 0;
								if(data["HighestScore"]){
									gameScore = data["HighestScore"];
								}
								jPages['gameresult'].find("#gameresult-highscore").html('High Score - ' + gameScore);
							}
						
						}catch(e){
							console.log("Error in getting game results",e);
						}
					}).fail(function(error){
						console.log("games list get fail",arguments);
						yumpod_service.hideWaitLoader();
					});
				}

			}

			var pushScoreToServer = function(csg, cs){
				currentSelectedGame = csg;
				currentScore = cs;
				player = yumpod_service.checkLoginAndGetPlayerDict();
				userid = player? player["userid"] : null;
				userHash = player? player["userHash"] : null;
				
				jPages['gameresult'].find("#gameresult-gameimage").attr('src',"mobileimgs/game-screens/" + currentSelectedGame + ".png");


				console.log("getting currentMission info : currentMission[currentSelectedGame:" + currentSelectedGame + ",currentScore:"  + currentScore + "]");
				if(userHash && currentSelectedGame && typeof currentScore !== "undefined"){
					yumpod_service.showWaitLoader("Please wait. Posting score to server.");
					$.when(send_request("pushscore",null,
							{"gameid":currentSelectedGame,"userHash":userHash,"score":currentScore,"coins":currentScore}
						)
					).done(function(data){
						console.log("push_score success",arguments);
						
						try{
							data= parseJson(data);
							console.log("data",data);
							//if(data["status"] && data["status"] === "success"){
								
							//}
						
						}catch(e){
							console.log("Error in getting push_score",e);
						}
						fn_getGameScore();
					}).fail(function(error){
						console.log("push_score fail",arguments);
						fn_getGameScore();
					});
				}
			}

			var cordovaReady = function(){
				console.log("Cordova Ready inside gameResultPage");
				yumpod_service.showWaitLoader("Please wait. Getting game results.");
				window.plugins.GetScore.getScore(
					function(args){
						currentScore = args[0];
						currentSelectedGame = args[1];
						yumpod_service.hideWaitLoader();
						
						pushScoreToServer(currentSelectedGame,currentScore);
						
					},function(){
						yumpod_service.hideWaitLoader();
						alert('error:' + arguments.length + "," + arguments);

					}
				);
			}
			//console.log("userid=" + userid  + "&userHash=" + userHash);
			//var currentMission = yumpod_store.get("dictMissions",true);
			document.addEventListener("deviceready", cordovaReady, false);
			/*
			window.onload = function () {
				if(! window.device){
				    cordovaReady();
				}
			}
			*/

			
			
			
		}

		ctrl.loginPage = function(){
			if(window.plugins && window.plugins.orientationLock && window.plugins.orientationLock.lock){
				window.plugins.orientationLock.lock("portrait");
			}
			//check for autologin
			if(typeof yumpod_service.playerDict !== "undefined" && yumpod_service.playerDict){
				var player = yumpod_service.checkLoginAndGetPlayerDict();
				var userid = player? player["userid"] : null;
				var userHash = player? player["userHash"] : null;
				console.log("userid",userid,",userHash",userHash);
				if( userid && userHash){
					yumpod_service.location_redirect("#gameSelectionPage");
				}
			}
		}

		ctrl.mePage = function(){
			if(window.plugins && window.plugins.orientationLock && window.plugins.orientationLock.lock){
				window.plugins.orientationLock.lock("portrait");
			}
			//console.log("MePage has started loading");
			var player = yumpod_service.checkLoginAndGetPlayerDict();
			var userid = player? player["userid"] : null;
			var userHash = player? player["userHash"] : null;
			yumpod_service.showWaitLoader("Getting user info");
			//console.log("userHash:",yumpod_service.playerDict);
			$.when(send_request("me",null,
					{"userHash":userHash,"userid":userid,"page":0}
				)
			).done(function(data){
				yumpod_service.hideWaitLoader();
				//console.log("myprofile get success",arguments);
				data = parseJson(data);
				if(typeof (data["data"]) !== "undefined"){
					data = data["data"];
				}
				yumpod_service.triggerEvent("loadMyProfile",data);
			}).fail(function(error){
				yumpod_service.hideWaitLoader();
				console.log("myprofile get fail",arguments);
			});
		}

		ctrl.timelinePage = function(){
			//console.log("timelinePage has started loading");
			var player = yumpod_service.checkLoginAndGetPlayerDict();
			var userid = player? player["userid"] : null;
			var userHash = player? player["userHash"] : null;
			$.when(send_request("timeline",null,
					{"userHash":userHash,"userid":userid,"page":0}
				)
			).done(function(data){
				//console.log("timeline get success",arguments);
				data = parseJson(data);
				if(typeof (data["data"]) !== "undefined"){
					data = data["data"];
				}
				if(data["user_status"]){
					yumpod_model.set("timeline",data["user_status"],"status_id");
				}
				yumpod_service.triggerEvent("loadTimeline",data);
			}).fail(function(error){
				console.log("timeline get fail",arguments);
			});	
		}

		ctrl.notificationPage = function(){
			var player = yumpod_service.checkLoginAndGetPlayerDict();
			var userid = player? player["userid"] : null;
			var userHash = player? player["userHash"] : null;
			$.when(send_request("notifications",null,
					{"userHash":userHash,"userid":userid,"page":''}
				)
			).done(function(data){
				//console.log("notification get success",arguments);
				try{
					
					data = parseJson(data);
					
					if(data && typeof (data["data"]) !== "undefined"){
						data = data["data"];
					}
					
					if(data && data["notification"]){
						yumpod_model.set("notification",data["notification"],"notification_id");
					}
					yumpod_service.triggerEvent("loadNotification",data);
				}catch(e){
					console.log("Error in reading notification",e);
				}
			}).fail(function(error){
				console.log("timeline get fail",arguments);
			});	
		}

		ctrl.challengePage = function(){
			//console.log("challengePage has started loading");
			var player = yumpod_service.checkLoginAndGetPlayerDict();
			var userid = player? player["userid"] : null;
			var userHash = player? player["userHash"] : null;
			$.when(send_request("getchallenges",null,
					{"userHash":userHash,"userid":userid}
				)
			).done(function(data){				
				//console.log("listchallenges get success",arguments);
				data = parseJson(data);
				if(typeof (data["data"]) !== "undefined"){
					data = data["data"];
				}
				yumpod_service.triggerEvent("loadChallenges",data);
			}).fail(function(error){
				console.log("listchallenges get fail",arguments);
			});	
		}
		
		ctrl.profilePage = function(){
			//console.log("Profile page loaded");
			if(yumpod_service["pageData"] && yumpod_service["pageData"]["search"]){
				//console.log("Profile page loaded 1");
				var searchData = yumpod_service["pageData"]["search"];
				if(searchData["userid"] || searchData['username']){
					//console.log("Profile page loaded 2");
					var selectedUserId = searchData["userid"] ? searchData["userid"] : "" ;
					var selectedUsername = searchData["username"] ? searchData["username"] : "";
					var player = yumpod_service.checkLoginAndGetPlayerDict();
					
					var userHash = player? player["userHash"] : null;
					
					if(selectedUserId || selectedUsername){
						$.when(send_request("getuserprofile",null,
							{"userHash":userHash,"userid":selectedUserId,"username":selectedUsername,"page":0}
						)
						).done(function(data){
							//console.log("profile get success",arguments);
							data = parseJson(data);
							if(typeof (data["data"]) !== "undefined"){
								data = data["data"];
							}
							yumpod_service.triggerEvent("loadProfile",data);
						}).fail(function(error){
							console.log("Profile get fail",arguments);
						});
					}
				}
			}
		}

		ctrl.replyStatusPage = function(){
			if(yumpod_service && yumpod_service["pageData"] && yumpod_service["pageData"]["replyPage"]){
				var replyData = yumpod_service["pageData"]["replyPage"];
				if(replyData['replyStatusId'] && replyData['replyUsername']){
			
					var replyStatusId = replyData['replyStatusId'];
					var replyUsername = replyData['replyUsername'];
					jPages["replyStatus"].find("#replystatus-id").val(replyStatusId);
					jPages["replyStatus"].find("#replystatus-head").html('Reply @' + replyUsername);
					jPages["replyStatus"].find("#replystatus-status").val('@' + replyUsername + ' ').focus();
				}
			}
		}

		ctrl.sendEmailPage = function(){
			var emailBody = "Hi,%0D%0A%0D%0A" +  

							"Join the coolest new social gaming app! You vs The World turns gaming into real money. Sign up today for 500 coins worth £2 %0D%0A%0D%0A" +

							"Thanks,%0D%0A" +
							yumpod_service["playerDict"]["name"] + "%0D%0A%0D%0A";
			var emailSubject = "Invitation to You vs the World"
			jPages["sendEmail"].find("#sendemail-btn").attr('href','mailto:?subject=' + emailSubject + '&body=' + emailBody);
		}

		ctrl.searchPage = function(){
			yumpod_service.triggerEvent("loadSearch");
		}

		r.load = function(ctrlName){
			//console.log("ctrlName:",ctrlName);
			$("#" + ctrlName).find("a[href=#" + ctrlName + "]").addClass("ui-btn-active");
			if(ctrl[ctrlName]){
				ctrl[ctrlName]();
			}
		}
		return r;
	}();

	
	//for model
	var yumpod_model = function(){
		var r = {};
		var model = {};
		
		var m_pre = "model_";
		var mi_pre = "modelidx_";
		window.model = model;
		//var modelIdx = modelIdx;
		var modelVersion = {};

		r.clearAll = function(){
			var model = {};
		}

		r.set = function(name,data,idField,reset){
			var dataMod = false;
			reset = (typeof reset !== "undefined" && reset === true) ? true : false; 
			idField = idField ? idField : 'id';

			console.log("set",name,data,idField,reset);

			if(!model[mi_pre + name] || reset){
				model[mi_pre + name] = {};
				dataMod = true;
			}

			if(!model[m_pre + name] || reset){
				model[m_pre + name] = [];
				dataMod = true;
			}
			
			//model[m_pre + name] = this[m_pre + name];
			//modelIdx[mi_pre + name] = this[mi_pre + name];

			for(var i in data){
				var dataObj = data[i];
				if(dataObj[idField]){
					if(typeof (model[mi_pre + name][dataObj[idField]]) !== "undefined"){
						model[m_pre + name][model[mi_pre + name][dataObj[idField]]] = dataObj;
					}else{
						model[mi_pre + name][dataObj[idField]] = model[m_pre + name].length;
						model[m_pre + name].push(dataObj);
					}
					dataMod = true;
				}
			}

			if(dataMod){
				modelVersion[m_pre + name] += (modelVersion[m_pre + name] ? modelVersion[m_pre + name] : 0);
			}
		}

		r.del = function(name,idFieldValue){
			var dataMod = false;
			if(model[mi_pre + name] && typeof model[mi_pre + name][idFieldValue] !== "undefined"){
				console.log("About to delete the data ");
				dataMod = true;
				delete model[m_pre + name][model[mi_pre + name][idFieldValue]];
				delete model[mi_pre + name][idFieldValue];
				
			}
			if(dataMod){
				modelVersion[m_pre + name] += (modelVersion[m_pre + name] ? modelVersion[m_pre + name] : 0);
				return true;
			}
			return false;
		}

		r.getIdx = function(name){
			if(model[mi_pre + name]){
				return model[mi_pre + name];
			}
			return null;
		}

		r.get = function(name){
			if(model[m_pre + name]){
				return model[m_pre + name];
			}
			return null;
		}
		return r;
	}();


	//for localStorage
	var yumpod_store = function(){
		var enabled = false;
		if(window.localStorage){
			enabled = true;
		}else{
			console.log("localStorage not found!");
		} 

		var set = function(key,val,doJsonParse,c2data){
			if(enabled && window.localStorage.setItem){
				if(c2data){
					switch (c2data){
						case 'd':
							val = {"c2dictionary":true,"data":val};
							break;
						case 'a':
							val = {"c2array":true,"data":val};
							break;
					}
				}
				
				if(doJsonParse){
					val = JSON.stringify(val);
				}
				window.localStorage.setItem(key,val);
			}
		}
		
		var get = function(key,doJsonParse,deepIdxArr){
			if(enabled && window.localStorage.getItem){
				
				var val = window.localStorage.getItem(key);
				if(doJsonParse){
					val = parseJson(val);
				}

				if(val && typeof val["c2dictionary"] !== "undefined" && val["c2dictionary"] === true && val["data"]){
					val = val["data"];
				}else if(val && typeof val["c2array"] !== "undefined" && val["c2array"] === true && val["data"]){
					val = val["data"];
				}

				var deepIdxArrCnt = 0;
				if(deepIdxArr){
					while(deepIdxArr !== true && deepIdxArrCnt < 10){
						deepIdxArrCnt++;
						val = getArrayDepth(deepIdxArr) ? val[getArrayDepth(deepIdxArr)] : val;
						deepIdxArr = deepIdxArr[getArrayDepth(deepIdxArr)];
					}
				}
				return val;
			}
		}

		var getArrayDepth = function(arr){
			if(arr){
				for(var i in arr){
					return i;
				}
			}
			return null;
		}

		var clear = function(){
			if(enabled && window.localStorage.clear){
				window.localStorage.clear();
			}
		}

		var remove = function(key){
			if(enabled && window.localStorage.removeItem){
				window.localStorage.removeItem(key);
			}
		}
		return {
			"set":set,
			"get":get,
			"remove":remove,
			"clear":clear
		};
	}();



	//yumpod service
	var yumpod_service = function(){
		var r = {};
		var serv = {};

		r.playerDict = yumpod_store.get("playerDict",true);
		r.pageData = {};

		var reloadJQMPage = function(jqmPageId){
			jPages[jqmPageId].page('destroy').page();

		}

		r.checkLoginAndGetPlayerDict = function(){
			if(typeof r.playerDict !== "undefined" && r.playerDict ){
				if(typeof r.playerDict["userid"] !== "undefined" && r.playerDict["userid"]
					&& typeof r.playerDict["username"] !== "undefined" && r.playerDict["username"]
					&& typeof r.playerDict["userHash"] !== "undefined" && r.playerDict["userHash"]){
					return r.playerDict;
				}
			}
			serv.func_logout();
		}

		r.postStatus = function(newStatus,jPageObj){
			var player = yumpod_service.checkLoginAndGetPlayerDict();
			var userid = player? player["userid"] : null;
			var userHash = player? player["userHash"] : null;
			$.when(send_request("poststatus",null,{"userHash":userHash,"status":newStatus}))
				.done(function(data){
					//console.log(data);
					data = parseJson(data);
					//console.log("Successful to get response for login ",arguments);
					if(data && data["status"] && data["status"] === "success" ){
						//console.log("Writing to localStorage",data);
						yumpod_model.set("timeline",[data],"status_id");
						//yumpod_service.triggerEvent("popup","Status Posted","your new status is successfully posted",newStatus,2);
						if(jPageObj){
							//console.log("pageObj:",jPageObj);
							//var jFormObj = $(jPageObj.find('.poststatus-form').get(0));
							var jPostStatusObj = $(jPageObj.find('.poststatus-main').get(0));
							//console.log("formObj:",jPostStatusObj);
							if(jPostStatusObj){
								jPostStatusObj.find(".poststatus-status").val("");
								jPostStatusObj.slideToggle();
								yumpod_service.triggerEvent("loadTimeline_status");
							}
						}

					}else{
						console.log("No data found",data);
						if(data && data["statusMessage"]){
							yumpod_service.triggerEvent("popup","Status posting is Unsuccessful",null,data["data"]["statusMessage"]);
						}
					}
				}).fail(function(error){
					//console.log("Failed to get response for login",arguments);
					yumpod_service.triggerEvent("popup","Status posting is Unsuccessful",null,"Failed to get response for posting status");
				});
		}

		r.postReply = function(replyContent,jPageObj,replyUsername,replyStatusId){
			if(replyStatusId && replyContent){
			
				var player = yumpod_service.checkLoginAndGetPlayerDict();
				var userHash = player? player["userHash"] : null;
	            $.when(send_request("replystatus",null,
						{"userHash":userHash,'status_id':replyStatusId,'status':replyContent}
					)
				).done(function(data){
					//console.log("status_reply success",arguments);
					
					try{
						data = parseJson(data);
						//console.log("status_reply success 2 ",data);
						if(data && data["status"] === "sucess"){
							//yumpod_model.set("timeline",[data['data']],"status_id");
							
							if(jPageObj){
								//console.log("pageObj:",jPageObj);
								//var jFormObj = $(jPageObj.find('.poststatus-form').get(0));
								var jPostStatusObj = $(jPageObj.find('.poststatus-main').get(0));
								//console.log("formObj:",jPostStatusObj);
								if(jPostStatusObj){
									jPostStatusObj.find(".poststatus-status").val("");
									jPostStatusObj.slideToggle();
									yumpod_service.triggerEvent("loadTimeline_status");
								}
							}
						}else{
							yumpod_service.triggerEvent("popup","Reply for Status is Unsuccessful",null,"Failed to get response for posting your reply");
						}
					}catch(e){
						console.log("status_reply error",e);
						yumpod_service.triggerEvent("popup","Reply for Status is Unsuccessful",null,"Failed to get response for posting your reply" , e);
					}

					
					//yumpod_service.triggerEvent("loadGames",data);
				}).fail(function(error){
					console.log("status_like fail",arguments);
				});
			}
		}

		serv.func_login = function(loginData){
			console.log("func_login called with ",loginData);
			yumpod_model.clearAll();
			r.playerDict = loginData;
			yumpod_store.set("playerDict",loginData,true,'d');
			r.location_redirect("#gameSelectionPage");
			setTimeout(yumpod_cordova.initUserUtilities,1000);
		}

		serv.func_logout = function(){
			yumpod_model.clearAll();
			r.playerDict = null;
			yumpod_store.remove("playerDict");
			r.location_redirect("#loginPage");
		}

		serv.func_loadGames = function(){
			var games = yumpod_store.get("games",true);
			var out = "";
			
			if(games && games.length > 0){
				for(var idx in games){
					var game = games[idx];
					//console.log("game.enabled:",game.enabled, typeof game.enabled)
					//game.enabled = game.enabled === "true" ? true : false;
					//game.bought = game.bought === "true" ? true : false;

					out += '<li data-game-id="' + game["gameid"] + '" data-icon="false" class="game-' + (game.enabled? (game.bought ? 'check' : 'shop') : 'forbidden') + '" >' +
							'<a href="#" class="gameselection-link" data-game-id="' + game["gameid"] + '">' + game.gamename + 
								'<p class="list-right">'+
									'<span class="list-right-el"><span class="game-status-icon game-' + (game.enabled? (game.bought ? 'check' : 'shop') : 'forbidden') + '" ></span></span>' + 
									'<span class="list-right-el"><span class="game-img game-img-' + game.gameid + '" ></span></span>' +
								'</p>'
							'</a>' +
							'</li>';
				}
			}
			jPages["gameSelection"].find("#listGames").html(out).listview('refresh');
			jPages["gameSelection"].find(".poststatus-main").addClass('ui-screen-hidden');


		}

		serv.func_loadMyProfile = function(profileData){
			
			
			jPages["me"].find("#me-page-username").html("@" + profileData.username);
			
			jPages["profileedit"].find("#profileedit-username").html("@" + profileData.username);
			
			jPages["me"].find("#mepage-profilepic").attr("src",profileData["userimage"]);
			var profileBio = '';
			if(profileData['bio'] && profileData['bio'].length > 0){
				profileBio = profileData['bio'];
			}else{
				profileBio = 'Update your profile picture and bio by tapping the \'Edit profile\' button';
			}
			jPages["profileedit"].find("#editbio-bio").html(profileData['bio']);

			jPages["me"].find("#me-page-num-updates").html( ((typeof profileData.updates !== "undefined")  ? profileData.updates : 0 ) );
			jPages["me"].find("#me-page-num-following").html( ((typeof profileData.following !== "undefined")  ? profileData.following : 0 ) );
			jPages["me"].find("#me-page-num-follower").html( ((typeof profileData.follower !== "undefined")  ? profileData.follower : 0 ) );

			/*jPages["me"].find("#me-profile-detail").html(out);//.listview("refresh");*/

			var jBioReadMoreBtn = jPages["me"].find(".read-more-btn");
			var jBioElement = jPages["me"].find("#me-profile-bio");
			var bioElement = jBioElement.get(0);

			//jBioElement.addClass('summary');
			jBioElement.html(profileBio);
			console.log(bioElement.offsetHeight,bioElement.scrollHeight,bioElement.offsetHeight < bioElement.scrollHeight);
			if( bioElement.offsetHeight < bioElement.scrollHeight || bioElement.offsetWidth < bioElement.scrollWidth){
			   // your element have overflow
			   jBioElement.addClass('summary');
			   jBioReadMoreBtn.show();
			}
			else{
			  //your element don't have overflow
			  jBioElement.removeClass('summary');
			  jBioReadMoreBtn.hide();
			}

			var out = "";
			//console.log("typeof profileData.status:",typeof profileData['user_status']);
			if(typeof profileData['user_status'] === "object"){
				for(var i in profileData['user_status']){
					var statusObj = profileData['user_status'][i];
					//New template as per the notification design
					out += '<li class="notification-tpl">' + 
								'<div class="ui-grid-a notification-outer ">' +

					
									'<p class="notificationpage-content">' +
										getUserLink('<img src="' + statusObj['userimage'] + '" />',statusObj['userid'],statusObj['username']) +
										'<span class="n-name">' + getUserLink('<strong>' + statusObj['name'] + '</strong> @' +  statusObj['username'],statusObj['userid'],statusObj['username']) + 
											(statusObj["userid"] === yumpod_service["playerDict"]['userid'] ? '<a class="ui-btn-right yvtw-delete-btn"  data-status-id="' + statusObj['status_id'] + '" href="#"></a>' : '') + 
										'</span>' +
										'<span class="n-content">' + formatStatus(statusObj['status'],statusObj['status_id'],statusObj) + '</span>' +
										'<span class="n-actions ui-grid-d">' + 
										
											'<span class="ui-block-a"><a href="#" class="yvtw-like-btn" data-status-like="' + statusObj["liked"] + '" data-status-id="' + statusObj['status_id'] + '"></a><em class="like-count">' + ( typeof statusObj['totallike'] !== "undefined" ? statusObj['totallike'] : '') + '</em></span>' +
											'<span class="ui-block-b"><a href="#replyStatusPage" data-username="' + statusObj['username'] + '" data-status-id="' + statusObj['status_id'] + '" >Reply</a></span>' +
											'<span class="ui-block-c"><a href="#" class="yvtw-share-btn" data-status-id="' + statusObj['status_id'] + '" >Share</a></span>' +
											'<span class="ui-block-d"><a href="#challengePage" class="yvtw-challenge-btn check-select-user" data-select-userid="' + statusObj['userid'] + '" data-select-username="' + statusObj['username'] + '" data-select-user-fn="loadChallengePageUserSelect" ></a></span>' +
											'<span class="ui-block-e time"><abbr class="timeago" title="' + statusObj.createdDate + '"></abbr></span>' +
										'</span>' +
									'</p>' +
								'</div>' +
							'</li>';
					/* Previous working template with green background as per original design
					out +=	'<li>' + 
								'<div class="ui-grid-a timeline-outer">' +
									'<div class="ui-block-a timeline-profile"><a href="#profilePage" data-rel="close" class="check-select-user" data-select-userid="' + statusObj["userid"] + '" data-select-username="' + statusObj["username"] + '" data-select-user-fn="loadProfilePageUserSelect"><img src="' + statusObj["userimage"] + '" alt="User icon" ></a></div>' +
									'<div class="ui-block-b timeline-content">' +
										'<div class="ui-grid-solo timeline-main-username">' +
											'<div class="ui-block-a"><a href="#profilePage" data-rel="close" class="check-select-user" data-select-userid="' + statusObj["userid"] + '" data-select-username="' + statusObj["username"] + '" data-select-user-fn="loadProfilePageUserSelect"><strong>' + (statusObj['name']? statusObj['name'] : 'Full Name') + ' </strong>@' + ( statusObj.username ? statusObj.username : 'username' ) + '</a>' + 
											(statusObj["userid"] === yumpod_service["playerDict"]['userid'] ? '<a class="ui-btn-right yvtw-delete-btn"  data-status-id="' + statusObj['status_id'] + '" href="#"></a>' : '') + 
											'</div>' +
										'</div>' +
										'<div class="ui-grid-solo timeline-main-content">' +
											'<div class="ui-block-a">' + statusObj['status'] + '</div>' +
										'</div>' +
										'<div class="ui-grid-d timeline-actions">' +
											'<div class="ui-block-a"><a href="#" class="yvtw-like-btn" data-status-like="' + statusObj["liked"] + '" data-status-id="' + statusObj['status_id'] + '"></a></div>' +
											'<div class="ui-block-b"><a href="#replyStatusPage" data-username="' + statusObj['username'] + '" data-status-id="' + statusObj['status_id'] + '" >Reply</a></div>' +
											'<div class="ui-block-c"><a href="#" class="yvtw-share-btn" data-status-id="' + statusObj['status_id'] + '" >Share</a></div>' +
											'<div class="ui-block-d"><a href="#challengePage" class="yvtw-challenge-btn check-select-user" data-select-userid="' + statusObj['userid'] + '" data-select-username="' + statusObj['username'] + '" data-select-user-fn="loadChallengePageUserSelect" ></a></div>' +
											'<div class="ui-block-e"><abbr class="timeago" title="' + ( statusObj.createdDate ? statusObj.createdDate : "2000-01-01T12:00:00Z" ) + '"></abbr></div>' +
										'</div>' +
								'</div>' +

							'</li>' ;
					*/
				}
			}
			jPages["me"].find("#me-profile-liststatus").html(out).listview("refresh");

			reloadJQMPage("me");

		}

		
		serv.func_loadProfile = function(profileData){
			var usertitle = profileData.firstname + ' ' + profileData.lastname;
			var out = "";
			/*
			out += '<table><tr><td rowspan="3"><img src="" alt="User pic" /></td><td colspan="3"><h3>' + usertitle + '</h3></td></tr>';
			out += '<tr><td>' + ( profileData.followers ? profileData.followers : 0 ) + '</td><td>' + ( profileData.following ? profileData.following : 0 ) + '</td><td><a href="#" class="follow-btn" data-user-id="' + profileData['userid'] + '"  data-mini="true" data-role="button" >Follow</a></td></tr>';
			out += '<tr><td>Followers</td><td>Following</td><td><a href="#" data-mini="true" data-role="button" >Block</a></td></tr></table>';
			*/

			var dataFollowAction = (typeof profileData["follow"] !== "undefined" && profileData["follow"] === "true") ? "Unfollow" : "Follow";
			var dataBlockAction = (typeof profileData["block"] !== "undefined" && profileData["block"] === "true") ? "Unblock" : "Block";

			out += 	'<div class="ui-grid-a">' + 
						'<div class="ui-block-a profile-img"><img src="' + profileData["userimage"] + '" alt="User pic" /><div class="clear"></div></div>' +
						'<div class="ui-block-b profile-abt">' +
							'<div class="ui-grid-solo">' + usertitle + '</div>' +
							'<div class="ui-grid-a">' + 
								'<div class="ui-grid-b">' + 
									'<div class="ui-block-a profile-stats">' +
										'<p>' + ( profileData.followers ? profileData.followers : 0 ) + '</p> Followers' +
									'</div>' +
									'<div class="ui-block-b profile-stats">' +
										'<p>' + ( profileData.following ? profileData.following : 0 ) + '</p> Following' +
									'</div>' +
									'<div class="ui-block-c">' +
										'<a data-role="button" data-mini="true" href="#" class="profile-action-btn" data-user-id="' + profileData['userid'] + '" data-action="' + dataFollowAction + '" >' + dataFollowAction + '</a>' +
										'<a data-role="button" data-mini="true" href="#" class="profile-action-btn" data-user-id="' + profileData['userid'] + '" data-action="' + dataBlockAction + '">' + dataBlockAction + '</a>' +
									'</div>' +
								'</div>' + 
								'<div class="ui-block-b"></div>' +
							'</div>' +
						'</div>' + 
					'</div>';
			/*
					</td><td colspan="3"><h3>' + usertitle + '</h3></td></tr>';
			out += '<tr><td>' + ( profileData.followers ? profileData.followers : 0 ) + '</td><td>' + ( profileData.following ? profileData.following : 0 ) + '</td><td><a href="#" class="follow-btn" data-user-id="' + profileData['userid'] + '"  data-mini="true" data-role="button" >Follow</a></td></tr>';
			out += '<tr><td>Followers</td><td>Following</td><td><a href="#" data-mini="true" data-role="button" >Block</a></td></tr></table>';
			
			*/
			jPages["profile"].find("#profilePage-profile-detail").html(out);//.listview("refresh");
			
			//console.log(jPages["profile"].find("#profilepage-name").html(),profileData,usertitle);
			jPages["profile"].find("#profilepage-name").html('@' + profileData.username);


			//jPages["profile"].find("#profilePage-profile-bio").html(profileData.bio);//.listview("refresh");
			var jBioReadMoreBtn = jPages["profile"].find(".read-more-btn");
			var jBioElement = jPages["profile"].find("#profilePage-profile-bio");
			var bioElement = jBioElement.get(0);

			//jBioElement.addClass('summary');
			jBioElement.html(profileData.bio);
			console.log(bioElement.offsetHeight,bioElement.scrollHeight,bioElement.offsetHeight < bioElement.scrollHeight);
			if( bioElement.offsetHeight < bioElement.scrollHeight || bioElement.offsetWidth < bioElement.scrollWidth){
			   // your element have overflow
			   jBioElement.addClass('summary');
			   jBioReadMoreBtn.show();
			}
			else{
			  //your element don't have overflow
			  jBioElement.removeClass('summary');
			  jBioReadMoreBtn.hide();
			}



			out = "";
			console.log("typeof profileData.status:",typeof profileData["user_status"]);
			if(typeof profileData["user_status"] === "object"){
				for(var i in profileData["user_status"]){
					var statusObj = profileData["user_status"][i];

					//New template as per the notification design
					out += '<li class="notification-tpl">' + 
								'<div class="ui-grid-a notification-outer ">' +

					
									'<p class="notificationpage-content">' +
										getUserLink('<img src="' + statusObj['userimage'] + '" />',statusObj['userid'],statusObj['username']) +
										'<span class="n-name">' + getUserLink('<strong>' + statusObj['name'] + '</strong> @' +  statusObj['username'],statusObj['userid'],statusObj['username']) + 
											(statusObj["userid"] === yumpod_service["playerDict"]['userid'] ? '<a class="ui-btn-right yvtw-delete-btn"  data-status-id="' + statusObj['status_id'] + '" href="#"></a>' : '') + 
										'</span>' +
										'<span class="n-content">' + formatStatus(statusObj['status'],statusObj['status_id'],statusObj) + '</span>' +
										'<span class="n-actions ui-grid-d">' + 
										
											'<span class="ui-block-a"><a href="#" class="yvtw-like-btn" data-status-like="' + statusObj["liked"] + '" data-status-id="' + statusObj['status_id'] + '"></a><em class="like-count">' + ( typeof statusObj['totallike'] !== "undefined" ? statusObj['totallike'] : '') + '</em></span>' +
											'<span class="ui-block-b"><a href="#replyStatusPage" data-username="' + statusObj['username'] + '" data-status-id="' + statusObj['status_id'] + '" >Reply</a></span>' +
											'<span class="ui-block-c"><a href="#" class="yvtw-share-btn" data-status-id="' + statusObj['status_id'] + '" >Share</a></span>' +
											'<span class="ui-block-d"><a href="#challengePage" class="yvtw-challenge-btn check-select-user" data-select-userid="' + statusObj['userid'] + '" data-select-username="' + statusObj['username'] + '" data-select-user-fn="loadChallengePageUserSelect" ></a></span>' +
											'<span class="ui-block-e time"><abbr class="timeago" title="' + statusObj.createdDate + '"></abbr></span>' +
										'</span>' +
									'</p>' +
								'</div>' +
							'</li>';
					/* Previous working template with green background as per original design
					out +=	'<li>' + 
								'<div class="ui-grid-a timeline-outer">' +
									'<div class="ui-block-a timeline-profile"><a href="#profilePage" data-rel="close" class="check-select-user" data-select-userid="' + statusObj["userid"] + '" data-select-username="' + statusObj["username"] + '" data-select-user-fn="loadProfilePageUserSelect"><img src="' + statusObj["userimage"] + '" alt="User icon" ></a></div>' +
									'<div class="ui-block-b timeline-content">' +
										'<div class="ui-grid-solo timeline-main-username">' +
											'<div class="ui-block-a"><a href="#profilePage" data-rel="close" class="check-select-user" data-select-userid="' + statusObj["userid"] + '" data-select-username="' + statusObj["username"] + '" data-select-user-fn="loadProfilePageUserSelect"><strong>' + (statusObj['name']? statusObj['name'] : 'Full Name') + ' @' + ( statusObj.username ? statusObj.username : 'username' ) + '</strong></a></div>' +
										'</div>' +
										'<div class="ui-grid-solo timeline-main-content">' +
											'<div class="ui-block-a">' + statusObj['status'] + '</div>' +
										'</div>' +
										'<div class="ui-grid-d timeline-actions">' +
											'<div class="ui-block-a"><a href="#" class="yvtw-like-btn" data-status-like="' + statusObj["liked"] + '" data-status-id="' + statusObj['status_id'] + '"></a><em class="like-count">' + ( typeof statusObj['totallike'] !== "undefined" ? statusObj['totallike'] : '') + '</em></div>' +
											'<div class="ui-block-b"><a href="#replyStatusPage" data-username="' + statusObj['username'] + '" data-status-id="' + statusObj['status_id'] + '" >Reply</a></div>' +
											'<div class="ui-block-c"><a href="#" class="yvtw-share-btn" data-status-id="' + statusObj['status_id'] + '" >Share</a></div>' +
											'<div class="ui-block-d"><a href="#challengePage" class="yvtw-challenge-btn check-select-user" data-select-userid="' + statusObj['userid'] + '" data-select-username="' + statusObj['username'] + '" data-select-user-fn="loadChallengePageUserSelect" ></a></div>' +
											'<div class="ui-block-e"><abbr class="timeago" title="' + statusObj.createdDate + '"></abbr></div>' +
										'</div>' +
								'</div>' +

							'</li>' ;
					*/
					/*
					out += '<li data-status-id="' + statusObj['status_id'] + '">' +
								'<div class="ui-grid-a">' +
									'<div class="ui-block-a profile-status-img"><img src="' + statusObj["userimage"] + '" /></div>' +
									'<div class="ui-block-b profile-status-c">' +
										'<div class="ui-grid-solo"><strong>@' + ( statusObj.username ? statusObj.username : 'username' ) + '</strong>' + statusObj.status + '</div>' +
										'<div class="ui-grid-c profilepage-status-btns">' +
											'<div class="ui-block-a"><a href="#" class="yvtw-like-btn" data-status-like="' + statusObj["liked"] + '" data-status-id="' + statusObj['status_id'] + '"></a><em class="like-count">' + ( typeof statusObj['totallike'] !== "undefined" ? statusObj['totallike'] : '') + '</em></a></div>' +
											'<div class="ui-block-b"><a href="#replyStatusPage" data-status-id="' + statusObj['status_id'] + '" >Reply</a></a></div>' +
											'<div class="ui-block-c"><a href="#">Share</a></a></div>' +
											'<div class="ui-block-d"><abbr class="timeago" title="' + statusObj.createdDate + '"></abbr></a></div>' +
										'</div>' +
									'</div>' +
								'</div>' 
								/*
								'<img src="" alt="User pic" />' +
								//'<span class="ui-li-count">' + statusObj.createdDate + '</span>' + 
								'<p class="myprofile-status-line1"><strong>@' + ( statusObj.username ? statusObj.username : 'username' ) + '</strong>' + statusObj.status + '</p>' + 
								'<p class="status-btns">' +
									'<span><a href="#" class="yvtw-like-btn" data-status-like="' + statusObj["liked"] + '" data-status-id="' + statusObj['status_id'] + '"></a><em class="like-count">' + ( typeof statusObj['totallike'] !== "undefined" ? statusObj['totallike'] : '') + '</em></span>' + 
									'<span><a href="#replyStatusPage" data-status-id="' + statusObj['status_id'] + '" >Reply</a></span>' + 
									'<span><a href="#">Share</a></span>' + 
									'<span><abbr class="timeago" title="' + statusObj.createdDate + '"></abbr></span>' +
								'</p>';
								*/
							//'</li>';
				}
			}
			jPages["profile"].find("#profilePage-profile-liststatus").html(out).listview("refresh");

			reloadJQMPage("profile");

		}

		/*

		//Old timeline template
		serv.func_loadTimeline_status = function(){
			var out ="";
			var statusColl = yumpod_model.get("timeline");
			if(statusColl && statusColl.length > 0){
				for(var i in statusColl){
					var statusObj = statusColl[i];
					
					out +=	'<li>' + 
								'<div class="ui-grid-a timeline-outer">' +
									'<div class="ui-block-a timeline-profile"><a href="#profilePage" data-rel="close" class="check-select-user" data-select-userid="' + statusObj["userid"] + '" data-select-username="' + statusObj["username"] + '" data-select-user-fn="loadProfilePageUserSelect"><img src="' + statusObj["userimage"] + '" alt="User icon" ></a></div>' +
									'<div class="ui-block-b timeline-content">' +
										'<div class="ui-grid-solo timeline-main-username">' +
											'<div class="ui-block-a"><a href="#profilePage" data-rel="close" class="check-select-user" data-select-userid="' + statusObj["userid"] + '" data-select-username="' + statusObj["username"] + '" data-select-user-fn="loadProfilePageUserSelect"><strong>' + (statusObj['name']? statusObj['name'] : 'Full Name') + '</strong> @' + ( statusObj.username ? statusObj.username : 'username' ) + '</a>' + 
											(statusObj["userid"] === yumpod_service["playerDict"]['userid'] ? '<a class="ui-btn-right yvtw-delete-btn"  data-status-id="' + statusObj['status_id'] + '" href="#"></a>' : '') + 
											'</div>' +
										'</div>' +
										'<div class="ui-grid-solo timeline-main-content">' +
											'<div class="ui-block-a">' + statusObj['status'] + '</div>' +
										'</div>' +
										'<div class="ui-grid-d timeline-actions">' +
											'<div class="ui-block-a"><a href="#" class="yvtw-like-btn" data-status-like="' + statusObj["liked"] + '" data-status-id="' + statusObj['status_id'] + '"></a><em class="like-count">' + ( typeof statusObj['totallike'] !== "undefined" ? statusObj['totallike'] : '') + '</em></div>' +
											'<div class="ui-block-b"><a href="#replyStatusPage" data-status-id="' + statusObj['status_id'] + '" >Reply</a></div>' +
											'<div class="ui-block-c"><a href="#" class="yvtw-share-btn" data-status-id="' + statusObj['status_id'] + '" >Share</a></div>' +
											'<div class="ui-block-d"><a href="#challengePage" class="yvtw-challenge-btn check-select-user" data-select-userid="' + statusObj['userid'] + '" data-select-username="' + statusObj['username'] + '" data-select-user-fn="loadChallengePageUserSelect" ></a></div>' +
											'<div class="ui-block-e"><abbr class="timeago" title="' + statusObj.createdDate + '"></abbr></div>' +
										'</div>' +
								'</div>' +

							'</li>' ;
							
				}

			}
			

			
			jPages["timeline"].find("#timeline-list-status").html(out).listview('refresh');
			recalcDates();
		}
		*/

		//new timeline template
		serv.func_loadTimeline_status = function(){
			var out ="";
			var statusColl = yumpod_model.get("timeline");
			if(statusColl && statusColl.length > 0){
				for(var i in statusColl){
					var statusObj = statusColl[i];
					
					/*
					out += '<li>' + 
								'<div class="ui-grid-a notification-outer ">'

									(statusObj['op_userid'] ? '<p class="notificationpage-message">' + getUserLink('<strong>@' + statusObj['second_username'] + '</strong>',statusObj['op_userid'],statusObj['op_username']) + ' Shared the status!</p>' : '') +
									'<p class="notificationpage-content">' +
										getUserLink('<img src="' + notificationObj['status']['userimage'] + '" />',notificationObj['status']['userid'],notificationObj['status']['username']) +
										'<span class="n-name">' + getUserLink('<strong>' + notificationObj['status']['name'] + '</strong> @' +  notificationObj['status']['username'],notificationObj['status']['userid'],notificationObj['status']['username']) + '</span>' +
										'<span class="n-content">' + notificationObj['status']['status'] + '</span>' +
									'</p>' +
								'</div>' +
							'</li>';
					*/
					out += '<li class="notification-tpl">' + 
								'<div class="ui-grid-a notification-outer ">' +

									( (statusObj['originalPoster'] && statusObj['shareFromUser'] ) ? '<p class="notificationpage-message">' + getUserLink('<strong>@' + statusObj['shareFromUser']['username'] + '</strong>',statusObj['shareFromUser']['userid'],statusObj['shareFromUser']['username']) + ' Shared the status!</p>' : '') +
									'<p class="notificationpage-content">' +
										getUserLink('<img src="' + statusObj['userimage'] + '" />',statusObj['userid'],statusObj['username']) +
										'<span class="n-name">' + getUserLink('<strong>' + statusObj['name'] + '</strong> @' +  statusObj['username'],statusObj['userid'],statusObj['username']) + 
											(statusObj["userid"] === yumpod_service["playerDict"]['userid'] ? '<a class="ui-btn-right yvtw-delete-btn"  data-status-id="' + statusObj['status_id'] + '" href="#"></a>' : '') + 
										'</span>' +
										'<span class="n-content">' + formatStatus(statusObj['status'],statusObj['status_id'],statusObj) + '</span>' +
										'<span class="n-actions ui-grid-d">' + 
										
											'<span class="ui-block-a"><a href="#" class="yvtw-like-btn" data-status-like="' + statusObj["liked"] + '" data-status-id="' + statusObj['status_id'] + '"></a><em class="like-count">' + ( typeof statusObj['totallike'] !== "undefined" ? statusObj['totallike'] : '') + '</em></span>' +
											'<span class="ui-block-b"><a href="#replyStatusPage" data-username="' + statusObj['username'] + '" data-status-id="' + statusObj['status_id'] + '" >Reply</a></span>' +
											'<span class="ui-block-c"><a href="#" class="yvtw-share-btn" data-status-id="' + statusObj['status_id'] + '" >Share</a></span>' +
											'<span class="ui-block-d"><a href="#challengePage" class="yvtw-challenge-btn check-select-user" data-select-userid="' + statusObj['userid'] + '" data-select-username="' + statusObj['username'] + '" data-select-user-fn="loadChallengePageUserSelect" ></a></span>' +
											'<span class="ui-block-e time"><abbr class="timeago" title="' + statusObj.createdDate + '"></abbr></span>' +
										'</span>' +
									'</p>' +
								'</div>' +
							'</li>';
									
					/*
					out +=	'<li>' + 
								'<div class="ui-grid-a timeline-outer">' +
									'<div class="ui-block-a timeline-profile"><a href="#profilePage" data-rel="close" class="check-select-user" data-select-userid="' + statusObj["userid"] + '" data-select-username="' + statusObj["username"] + '" data-select-user-fn="loadProfilePageUserSelect"><img src="' + statusObj["userimage"] + '" alt="User icon" ></a></div>' +
									'<div class="ui-block-b timeline-content">' +
										'<div class="ui-grid-solo timeline-main-username">' +
											'<div class="ui-block-a"><a href="#profilePage" data-rel="close" class="check-select-user" data-select-userid="' + statusObj["userid"] + '" data-select-username="' + statusObj["username"] + '" data-select-user-fn="loadProfilePageUserSelect"><strong>' + (statusObj['name']? statusObj['name'] : 'Full Name') + '</strong> @' + ( statusObj.username ? statusObj.username : 'username' ) + '</a>' + 
											(statusObj["userid"] === yumpod_service["playerDict"]['userid'] ? '<a class="ui-btn-right yvtw-delete-btn"  data-status-id="' + statusObj['status_id'] + '" href="#"></a>' : '') + 
											'</div>' +
										'</div>' +
										'<div class="ui-grid-solo timeline-main-content">' +
											'<div class="ui-block-a">' + statusObj['status'] + '</div>' +
										'</div>' +
										'<div class="ui-grid-d timeline-actions">' +
											'<div class="ui-block-a"><a href="#" class="yvtw-like-btn" data-status-like="' + statusObj["liked"] + '" data-status-id="' + statusObj['status_id'] + '"></a><em class="like-count">' + ( typeof statusObj['totallike'] !== "undefined" ? statusObj['totallike'] : '') + '</em></div>' +
											'<div class="ui-block-b"><a href="#replyStatusPage" data-status-id="' + statusObj['status_id'] + '" >Reply</a></div>' +
											'<div class="ui-block-c"><a href="#" class="yvtw-share-btn" data-status-id="' + statusObj['status_id'] + '" >Share</a></div>' +
											'<div class="ui-block-d"><a href="#challengePage" class="yvtw-challenge-btn check-select-user" data-select-userid="' + statusObj['userid'] + '" data-select-username="' + statusObj['username'] + '" data-select-user-fn="loadChallengePageUserSelect" ></a></div>' +
											'<div class="ui-block-e"><abbr class="timeago" title="' + statusObj.createdDate + '"></abbr></div>' +
										'</div>' +
								'</div>' +

							'</li>' ;
					*/
							
				}

			}else{
				out += '<p>Your timeline is empty, upload a status now</p>';
			}
			

			
			jPages["timeline"].find("#timeline-list-status").html(out).listview('refresh');
			recalcDates();
		}

		serv.func_loadTimeline = function(timelineData){
			serv.func_loadTimeline_status();
			jPages["timeline"].find(".poststatus-main").addClass('ui-screen-hidden');
			reloadJQMPage("timeline");
		}

		serv.func_loadSearch = function(){
			jPages["search"].find(".poststatus-main").addClass('ui-screen-hidden');
		}

		serv.func_loadChallenges = function(challengeData){
			var out = '';
			var lastChallengeSent = null;
			if(challengeData){
				jPages["challenge"].find("#challenge-display-coins").html(challengeData["coins"]);

				jPages["challenge"].find("#challenge-coins").attr("max",challengeData["coins"]);

				if(typeof challengeData["challenges"] !== "undefined" && challengeData["challenges"].length > 0){
					for(var i in challengeData["challenges"]){
						var challengeObj = challengeData["challenges"][i];
						challengeObj.challengeStatus = parseInt(challengeObj.challengeStatus,10);

						var challengeStatus = null;
						switch(challengeObj.challengeStatus){
							case 0:
								challengeStatus = 'Challenge Sent';
								break;
							case 1:
								challengeStatus = 'Challenge Accepted';
								break;
							case 2:
								challengeStatus = 'Challenge Completed';
								break;
							case -1:
								challengeStatus = 'Challenge Cancelled';
								break;
							case -2:
								challengeStatus = 'Challenge Declined';
								break;
						}

						var challengeActionButtons = null;
						
						var challengeString = "";
						var challengeSent = true;
						var challengeMsg = "";

						if(challengeObj["challengeFrom"] == yumpod_service["playerDict"]['userid']){
							challengeString = 'You challenged @' + challengeObj["challengeToUsername"];
							if(challengeObj.challengeStatus === 0){
								challengeActionButtons = '<a href="#" class="challenge-btn-cancel" data-challenge-id="' + challengeObj['challenge_id'] + '" >Cancel</a>' + 
														 '<a href="#" class="challenge-btn-play"  data-challenge-id="' + challengeObj['challenge_id'] + '"  >Play</a>';

							}else if(challengeObj.challengeStatus === 1){
								challengeActionButtons = '<a href="#" class="challenge-btn-play"  data-challenge-id="' + challengeObj['challenge_id'] + '" >Play</a>';
														/*'<a class="challenge-btn-accept" data-challenge-id="' + challengeObj['challenge_id'] + '" data-role="button" data-mini="true" data-inline="true">Accept</a>' + 
														 '<a class="challenge-btn-decline" data-challenge-id="' + challengeObj['challenge_id'] + '" data-role="button" data-mini="true" data-inline="true">Decline</a>';
														 */
							}
						}else{
							challengeSent = false;
							challengeString = '@' + challengeObj["challengeFromUsername"] + ' challenged you ';
							if(challengeObj.challengeStatus === 0){
								challengeActionButtons = '<a href="#" class="challenge-btn-accept" data-challenge-id="' + challengeObj['challenge_id'] + '" >Accept</a>' + 
														 '<a href="#" class="challenge-btn-decline" data-challenge-id="' + challengeObj['challenge_id'] + '" >Decline</a>';
							}else if(challengeObj.challengeStatus === 1){
								challengeActionButtons = '<a href="#" class="challenge-btn-play"  data-challenge-id="' + challengeObj['challenge_id'] + '" >Play</a>';
															//'<a class="challenge-btn-cancel" data-challenge-id="' + challengeObj['challenge_id'] + '" data-role="button" data-mini="true" data-inline="true" >Cancel</a>';
							}
						}

						var challengeClass = '';
						if(lastChallengeSent !== challengeSent){
							challengeClass = challengeSent? 'challenge-sent-top' : 'challenge-received-top';
						}
						out += '<li class="' + challengeClass + ' ' + (challengeSent ? 'challenge-sent-li' :'challenge-received-li') + '">' +
									'<div href="#" class="li-inner-div">' +
										'<img class="challengePage-challenge-pic-' + (challengeSent? 'from' : 'to') + '" src="' + (challengeSent?challengeObj['challengeToImage'] : challengeObj['challengeFromImage']) + '" alt="User icon" >' +
										'<p class="challengepage-challengestring"><span>' + (challengeString ? challengeString : '') + '</span></p>' + 
										
										'<p class="challengepage-coins"><span><strong>' + challengeObj.coins + '</strong> coins</span></p>' +
										'<p class="challengepage-statusaction">' +									  
										  //'<span class="challengepage-status">' + (challengeStatus ? challengeStatus : '') + ' <abbr class="timeago" title="' + challengeObj.createdDate + '"></abbr></span>' +
										  '<span class="challengepage-action">' + (challengeActionButtons ? challengeActionButtons : '') + '</span>' +
										  '<span class="challengepage-status">' + ' <abbr class="timeago" title="' + challengeObj.createdDate + '"></abbr></span>' +
										  
										'</p>' + 
									'</div>' +
								'</li>';
						lastChallengeSent = challengeSent;
					}
				}else{
					out += '<p>You don\'t have any challenges yet!</p><br/>' +
							'<p>You can get more points by sending challenges, playing and winning games!</p>';
				}
			}

			jPages["challenge"].find("#challenge-list-challenges").html(out).listview('refresh');

			var games = yumpod_store.get("games",true);
			out = "";
			for(var idx in games){
				var game = games[idx];
				out += '<option value="' + game.gameid + '">' + game.gamename + '</option>';
			}
			jPages["challenge"].find("#challenge-game").html(out);

			if(yumpod_service["pageData"]["challenge"] && yumpod_service["pageData"]["challenge"]["username"]){
				jPages["challenge"].find("#challengePage-createchallenge-collapse").collapsible({ 'collapsed': false });
				yumpod_service["pageData"]["challenge"] = {};
			}else{
				jPages["challenge"].find("#challengePage-createchallenge-collapse").collapsible({ 'collapsed': true });
			}



			reloadJQMPage("challenge");
		}

		serv.func_loadChallengePageUserSelect = function(username,userid){
			console.log("func_loadChallengePageUserSelect",username);
			try{
				yumpod_service["pageData"]["challenge"] = {"username":username,"userid":userid};
				$('#challenge-user').val(userid);
				$('#challenge-username').html('@' + username);
				$( "#searchPanel" ).panel( "close" );
			}catch(e){}
		}
		
		serv.func_loadProfilePageUserSelect = function(username,userid){
			if(yumpod_service && yumpod_service["pageData"]){
				//console.log("Going to select on the basis of ",username,userid);
				if(username || userid){
					yumpod_service["pageData"]["search"] = {"username":username,"userid":userid};
				}else{
					yumpod_service["pageData"]["search"] = {};
				}
			}
		}

		var getUserLink = function(content,userid,username){
			return '<a href="#profilePage" data-rel="close" class="check-select-user" data-select-userid="' + userid + '" data-select-username="' + username + '" data-select-user-fn="loadProfilePageUserSelect">' + content + '</a>';
		}

		//var i = 0;
		var formatStatus = function(statusContent,status_id,statusObj){
			/*
			i++;
			console.log("statusContent",statusContent);
			if (i === 1)
				window.statusContent = statusContent;
			*/
			statusContentRep[statusObj['statusid']] = statusObj;
			statusContent = statusContent.replace(/@([\w-]+)/g, '<a href="#profilePage" data-rel="close" class="check-select-user ui-link" data-select-username="$1" data-select-user-fn="loadProfilePageUserSelect">@$1</a>');
			statusContent = statusContent.replace(/\n/g, '<br />');
			statusContent = '<span class="status-content-span" data-status-id="' + status_id + '" >' + statusContent + '</span>';
			return statusContent;

		}

		serv.func_loadNotification = function(data){
			var out = '';
			var notificationColl = yumpod_model.get("notification");
			
			if(notificationColl && notificationColl.length > 0){
				for(var i in notificationColl){
					var notificationObj = notificationColl[i];
					var isActionButtonReq = false;
					if(notificationObj['status'] || notificationObj['action'] === 'F'){
						out +=	'<li>' + 
									'<div class="ui-grid-a notification-outer notification-action-' + notificationObj["action"] + '">';

						switch (notificationObj["action"]){
							case 'F':
								if(notificationObj["user_id"] == yumpod_service["playerDict"]['userid']){
									//You followed somebody
									out +='<p class="notificationpage-message">You followed ' + getUserLink('<strong>@' + notificationObj["following_username"] + '</strong>',notificationObj['following_userid'],notificationObj['following_username']) + '</p>';
								}else{
									//Somebody followed you
									out +='<p class="notificationpage-message">' + getUserLink('<strong>@' + notificationObj["username"] + '</strong>',notificationObj['userid'],notificationObj['username']) + ' Followed you!</p>';
								}
								
								break;
							case 'R':
								/*
								out += '<p><strong>@' + notificationObj['username'] + '</strong> Replied to your status!</p>' +
									'<p><strong>' + notificationObj['status']['name'] + ' @' +  notificationObj['status']['username'] + '</strong></p>' +
									'<p>' + notificationObj['status']['status'] + '</p>';
									*/
								out += '<p class="notificationpage-message">' + getUserLink('<strong>@' + notificationObj['username'] + '</strong>',notificationObj['userid'],notificationObj['username']) + ' Replied to your status!</p>' +
									'<p class="notificationpage-content">' +
										getUserLink('<img src="' + notificationObj['status']['userimage'] + '" />',notificationObj['status']['userid'],notificationObj['status']['username']) +
										'<span class="n-name">' + getUserLink('<strong>' + notificationObj['status']['name'] + '</strong> @' +  notificationObj['status']['username'],notificationObj['status']['userid'],notificationObj['status']['username']) + '</span>' +
										'<span class="n-content">' + formatStatus(notificationObj['status']['status'],notificationObj['status']['status_id'],notificationObj['status']) + '</span>';
									//'</p>';
								isActionButtonReq = true;
								break;

							case 'L':
								out += '<p class="notificationpage-message">' + getUserLink('<strong>@' + notificationObj['username'] + '</strong>', notificationObj['userid'],notificationObj['username']) +' Liked your status!</p>' +
									'<p class="notificationpage-content">' +
										getUserLink('<img src="' + notificationObj['status']['userimage'] + '" />',notificationObj['status']['userid'],notificationObj['status']['username']) +
										'<span class="n-name">' + getUserLink('<strong>' + notificationObj['status']['name'] + '</strong> @' +  notificationObj['status']['username'],notificationObj['status']['userid'],notificationObj['status']['username']) + '</span>';
										'<span class="n-content">' + formatStatus(notificationObj['status']['status'],notificationObj['status']['status_id'],notificationObj['status']) + '</span>' ;
									//'</p>';
								isActionButtonReq = true;
								break;

							case 'SS':
								/*
								out += '<p><strong>@' + notificationObj['username'] + '</strong> Shared your status!' +
									'<p><strong>' + notificationObj['status']['name'] + ' @' +  notificationObj['status']['username'] + '</strong></p>' +
									'<p>' + notificationObj['status']['status'] + '</p>';
									*/
								out += '<p class="notificationpage-message">' + getUserLink('<strong>@' + notificationObj['username'] + '</strong>',notificationObj['userid'],notificationObj['username']) + ' Shared your status!' +
									'<p class="notificationpage-content">' +
										getUserLink('<img src="' + notificationObj['status']['userimage'] + '" />',notificationObj['status']['userid'],notificationObj['status']['username']) +
										'<span class="n-name">' + getUserLink('<strong>' + notificationObj['status']['name'] + '</strong> @' +  notificationObj['status']['username'],notificationObj['status']['userid'],notificationObj['status']['username']) + '</span>' +
										'<span class="n-content">' + formatStatus(notificationObj['status']['status'],notificationObj['status']['status_id'],notificationObj['status']) + '</span>';
									//'</p>';
								isActionButtonReq = true;
								break;
									

						}

						if(isActionButtonReq){
							out += 		'<span class="n-actions ui-grid-d">' + 
											'<span class="ui-block-a"><a href="#" class="yvtw-like-btn" data-status-like="' + notificationObj['status']["liked"] + '" data-status-id="' + notificationObj['status']['status_id'] + '"></a><em class="like-count">' + ( typeof notificationObj['status']['totallike'] !== "undefined" ? notificationObj['status']['totallike'] : '') + '</em></span>' +
											'<span class="ui-block-b"><a href="#replyStatusPage" data-username="' + notificationObj['status']['username'] + '" data-status-id="' + notificationObj['status']['status_id'] + '" >Reply</a></span>' +
											'<span class="ui-block-c"><a href="#" class="yvtw-share-btn" data-status-id="' + notificationObj['status']['status_id'] + '" >Share</a></span>' +
											'<span class="ui-block-d"><a href="#challengePage" class="yvtw-challenge-btn check-select-user" data-select-userid="' + notificationObj['status']['userid'] + '" data-select-username="' + notificationObj['status']['username'] + '" data-select-user-fn="loadChallengePageUserSelect" ></a></span>' +
											'<span class="ui-block-e time"><abbr class="timeago" title="' + notificationObj['status']['createdDate'] + '" date="' + new Date(notificationObj['status']['createdDate']).toISOString() + '"></abbr></span>' +
										'</span>' +
									'</p>';
						}

						out += '</div>' + 
							'</li>';
					}
				}
			}else{
				out += '<p>You have no notifications yet</p><br/>' +
						'<p>You will receive notifications when someone likes, replies, shares or mentions you!</p>';
			}
			
			jPages["notification"].find("#notification-list-status").html(out).listview('refresh');
			
			reloadJQMPage("notification");
			
		}

		serv.func_deleteTimelineStatus = function(timelineStatusId){
			//console.log("func_deleteTimelineStatus",arguments);
			var deleteSuccess = yumpod_model.del("timeline",timelineStatusId);
			//console.log("deleteSuccess:",deleteSuccess);
			if(deleteSuccess){
				serv.func_loadTimeline_status();
			}
		}
		

		r.location_redirect = function(loc){
			$.mobile.changePage($(loc));
		}

		serv.func_popup = function(head,title,msg){
			head = head ? head : "";
			title = title ? title : "";
			msg = msg ? msg : "";
			jPages["popupMsg"].find("#popup-head").html(head);
			jPages["popupMsg"].find("#popup-title").html(title);
			jPages["popupMsg"].find("#popup-content").html(msg);
			$.mobile.changePage("#popupMsgPage", {
		        role: "dialog"
		    });
			
		}

		r.triggerEvent = function(eventName){
			//console.log("triggerEvent called",arguments);
			var args = Array.prototype.slice.call(arguments,1,arguments.length);
			//console.log(arguments, typeof(arguments),args);
			if(serv["func_" + eventName]){
				serv["func_" + eventName].apply(undefined,args);
			}
		}

		r.reloadPage = function(loc){
			//console.log("reloading the page");
			$('body').pagecontainer("load",loc,{'reload':true});
		}

		r.showWaitLoader = function(msgText){
			var options = {};
			if(msgText){
				options['text'] = msgText;
				options['textVisible'] = true;
			}

			$.mobile.loading( 'show' , options );
			/*, {
			  text: msgText,
			  textVisible: textVisible,
			  theme: theme,
			  textonly: textonly,
			  html: html
			});
			*/
		}

		r.hideWaitLoader = function(){
			$.mobile.loading( "hide" );
		}

		r.showPostStatusDialog = function(){
			var activePage = $(':mobile-pagecontainer').pagecontainer('getActivePage');
	    	if(activePage && activePage[0]){
	    		activePage = activePage[0];
	    		var jActivePage = $(activePage);
	    		var jPoststatusDiv = jActivePage.find(".poststatus-main");
	    		if(jPoststatusDiv.hasClass('ui-screen-hidden')){
	    			jPoststatusDiv.hide().removeClass('ui-screen-hidden');
	    		}
	    		
	    		jPoststatusDiv.slideToggle();
	    		$("body").animate({scrollTop:0},'500','swing',null);
	    		
	    		
	    		//console.log(activePage,activePage.find(".poststatus-main"),$(activePage),$(activePage).find(".poststatus-main"));
	    		return jActivePage;
	    	}
	    	return null;
		}

		return r;
	}();

	


	var serv_Base64 = function() {
	    var keyStr = 'ABCDEFGHIJKLMNOP' +
	        'QRSTUVWXYZabcdef' +
	        'ghijklmnopqrstuv' +
	        'wxyz0123456789+/' +
	        '=';
	    return {
	        encode: function (input) {
	            var output = "";
	            var chr1, chr2, chr3 = "";
	            var enc1, enc2, enc3, enc4 = "";
	            var i = 0;
	 
	            do {
	                chr1 = input.charCodeAt(i++);
	                chr2 = input.charCodeAt(i++);
	                chr3 = input.charCodeAt(i++);
	 
	                enc1 = chr1 >> 2;
	                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
	                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
	                enc4 = chr3 & 63;
	 
	                if (isNaN(chr2)) {
	                    enc3 = enc4 = 64;
	                } else if (isNaN(chr3)) {
	                    enc4 = 64;
	                }
	 
	                output = output +
	                    keyStr.charAt(enc1) +
	                    keyStr.charAt(enc2) +
	                    keyStr.charAt(enc3) +
	                    keyStr.charAt(enc4);
	                chr1 = chr2 = chr3 = "";
	                enc1 = enc2 = enc3 = enc4 = "";
	            } while (i < input.length);
	 
	            return output;
	        },
	 
	        decode: function (input) {
	            var output = "";
	            var chr1, chr2, chr3 = "";
	            var enc1, enc2, enc3, enc4 = "";
	            var i = 0;
	 
	            // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
	            var base64test = /[^A-Za-z0-9\+\/\=]/g;
	            if (base64test.exec(input)) {
	                alert("There were invalid base64 characters in the input text.\n" +
	                    "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
	                    "Expect errors in decoding.");
	            }
	            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
	 
	            do {
	                enc1 = keyStr.indexOf(input.charAt(i++));
	                enc2 = keyStr.indexOf(input.charAt(i++));
	                enc3 = keyStr.indexOf(input.charAt(i++));
	                enc4 = keyStr.indexOf(input.charAt(i++));
	 
	                chr1 = (enc1 << 2) | (enc2 >> 4);
	                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
	                chr3 = ((enc3 & 3) << 6) | enc4;
	 
	                output = output + String.fromCharCode(chr1);
	 
	                if (enc3 != 64) {
	                    output = output + String.fromCharCode(chr2);
	                }
	                if (enc4 != 64) {
	                    output = output + String.fromCharCode(chr3);
	                }
	 
	                chr1 = chr2 = chr3 = "";
	                enc1 = enc2 = enc3 = enc4 = "";
	 
	            } while (i < input.length);
	 
	            return output;
	        }
	    };
	}();


	window.fillLogin = function(){
		jPages["login"].find("input#signin-email").val('dipanshu@qsstechnosoft.com');
		jPages["login"].find("input#signin-password").val('qss123');
	}
	//for login on #loginPage
	jPages["login"].on("click","#signin-button",function(e){
		//console.log("Clicked on login btn",this,arguments);
		var signin_username = jPages["login"].find("input#signin-email").val();
		var signin_password = jPages["login"].find("input#signin-password").val();
		loginUser(signin_username,signin_password);

	});

	//for signup on #gamerSignupPage
	jPages["gamerSignup"].on("click","#gsignup-submit",function(e){
		var gsignup_name = jPages["gamerSignup"].find("input#gsignup-name").val();
		var gsignup_email = jPages["gamerSignup"].find("input#gsignup-email").val();
		var gsignup_username = jPages["gamerSignup"].find("input#gsignup-username").val();
		var gsignup_password = jPages["gamerSignup"].find("input#gsignup-password").val();
		if(typeof(gsignup_name) !== "undefined" && typeof(gsignup_email) !== "undefined" && typeof(gsignup_username) !== "undefined" && typeof(gsignup_password) !== "undefined"){
			yumpod_service.showWaitLoader("Please wait. Signing up..");
			$.when(send_request("signup",null,{
					"fullname":gsignup_name,
					"email":gsignup_email,
					"username":gsignup_username,
					"password":gsignup_password,
					"type":"Gamers"
				})
			).done(function(data){
				yumpod_service.hideWaitLoader();
				console.log("Successful to get response for gamers signup ",arguments);
				data = parseJson(data);
				if(data && data["data"] && data["data"]["status"] && data["data"]["status"] === "success" && data["data"]["user"]){
					//console.log("Writing to localStorage");
					loginUser(gsignup_email,gsignup_password);
				}else{
					//console.log("No data found");
					yumpod_service.triggerEvent("logout");
				}
			}).fail(function(error){
				yumpod_service.hideWaitLoader();
				//console.log("Failed to get response for gamer signup",arguments);
				yumpod_service.triggerEvent("logout");
			});
		}
	});

	//for signup on #parentSignupPage
	jPages["parentSignup"].on("click","#psignup-submit",function(e){
		var gsignup_name = jPages["parentSignup"].find("input#psignup-name").val();
		var gsignup_email = jPages["parentSignup"].find("input#psignup-email").val();
		var gsignup_username = jPages["parentSignup"].find("input#psignup-username").val();
		var gsignup_password = jPages["parentSignup"].find("input#psignup-password").val();
		if(typeof(gsignup_name) !== "undefined" && typeof(gsignup_email) !== "undefined" && typeof(gsignup_username) !== "undefined" && typeof(gsignup_password) !== "undefined"){
			yumpod_service.showWaitLoader("Please wait. Signing up..");
			$.when(send_request("signup",null,{
					"fullname":gsignup_name,
					"email":gsignup_email,
					"username":gsignup_username,
					"password":gsignup_password,
					"type":"children"
				})
			).done(function(data){
				yumpod_service.hideWaitLoader();
				console.log("Successful to get response for parents signup ",arguments);
				data = parseJson(data);
				if(data && data["data"] && data["data"]["status"] && data["data"]["status"] === "success" && data["data"]["user"]){
					//console.log("Writing to localStorage");
					loginUser(gsignup_email,gsignup_password);
					
				}else{
					//console.log("No data found");
					yumpod_service.triggerEvent("logout");
				}
			}).fail(function(error){
				yumpod_service.hideWaitLoader();
				//console.log("Failed to get response for parent signup",arguments);
				yumpod_service.triggerEvent("logout");
			});
		}
	});

	//for game selection on #gameSelectionPage
	jPages["gameSelection"].on("click","#listGames li>a, .yvtw-icon-getall",function(e){
		//console.log("Game selected with id",this);
		var jAnc = $(this);
		var dataGameId = jAnc.attr('data-game-id');
		if (typeof dataGameId !== "undefined" && dataGameId !== null){
			var games = yumpod_store.get("games",true)
			//console.log("Games in store:",games);
			var currentGame = null;
			for(var idx in games){
				var game = games[idx];
				if(game.gameid === jAnc.attr('data-game-id')){
					currentGame = game;
					break;
				}
			}

			if(currentGame && currentGame.enabled || dataGameId === "0"){
				//currentGame.enabled = currentGame.enabled === "true" ? true : false;
				//currentGame.bought = currentGame.bought === "true" ? true : false;
				if(dataGameId === "0"){
					console.log("About to buy all the games");
					yumpod_cordova.buyGame(dataGameId);
					return false;
				}
				if(!currentGame['bought']){
					console.log("About to buy the game - " + currentGame["gameid"]);
					yumpod_cordova.buyGame(currentGame['gameid']);
					return false;
				}
				if(currentGame.bought){
					var playerDict = yumpod_store.get("playerDict",true);
					//console.log("playerDict before writing",JSON.stringify(playerDict));
					playerDict["currentSelectedGame"] = jAnc.attr('data-game-id');
					yumpod_store.set("playerDict",playerDict,true,'d');
					changeScreen("landscape");

					var gameId = this.getAttribute('data-game-id');
					var player = yumpod_service.checkLoginAndGetPlayerDict();

					var username = player? player["username"] : null;
					var email = player? player['email'] : null;
					var name = player? player['name'] : null;
					var currentSelectedGame = gameId;
					if(currentSelectedGame && username && email && name){
						yumpod_service.showWaitLoader("Please wait. Loading game..");
						setTimeout(function(){
							window.plugins.Callgame.startGame(currentSelectedGame,username,email,name,function(){console.log('success')},function(){console.log('error')});
						},1000);
						//console.log("calling playGame [currentSelectedGame:",currentSelectedGame,",username:",username,",email:",email,",name:",name,"]");

						
						
					}
					//this.setAttribute('href','game' + dataGameId + '/index.html');
					return true;
				}
			}			
		}
		return false;
	});


	//for posting status
	/*jPages["postStatus"].on("click","#poststatus-submit",function(e){
		var newStatus = jPages["postStatus"].find("#poststatus-status").val();
		
		console.log("post status",newStatus);
		if(newStatus && newStatus.length > 2){
			yumpod_service.postStatus(newStatus,jPages["postStatus"]);
		}
		return false;
	});*/
	//for posting status
	$(document).on("click",".poststatus-btn",function(e){
		var jThis = $(this);
		var jForm = jThis.closest('form');
		
		var jPage = jThis.closest('[data-role=page]');
		var newStatus = jForm.find(".poststatus-status").val();
		var replyUsername = jForm.find(".poststatus-replyusername").val();
		var replyStatusId = jForm.find(".poststatus-replystatusid").val();

		
		if(newStatus && newStatus.length > 2){
			if(replyUsername && replyStatusId){
				yumpod_service.postReply(newStatus,jPage,replyUsername,replyStatusId);
			}else{
				yumpod_service.postStatus(newStatus,jPage);
			}
		}
		return false;
	});


	

	//for selecting user on any page and triggering the respective event
	$(document).on("click",".check-select-user",function(e){
		var jChallengeUserSelect = $(this);
		//console.log("check-select-user clicked",jChallengeUserSelect.attr('data-select-user') ,jChallengeUserSelect.attr('data-select-user-fn'));
		if((jChallengeUserSelect.attr('data-select-username') || jChallengeUserSelect.attr('data-select-userid')) && jChallengeUserSelect.attr('data-select-user-fn')){
			yumpod_service.triggerEvent(jChallengeUserSelect.attr('data-select-user-fn'),jChallengeUserSelect.attr('data-select-username'),jChallengeUserSelect.attr('data-select-userid'));

			if(jChallengeUserSelect.attr('data-load-page')){
				yumpod_controllers.load(jChallengeUserSelect.attr('data-load-page'));
			}
		}		
	});

	//for sending challenge
	jPages["challenge"].on("click","#send-challenge-btn",function(e){
		var userHash = yumpod_service["playerDict"]["userHash"];
		var challengeFromUserId = yumpod_service["playerDict"]["userid"];
		var challengeToUserId = jPages["challenge"].find("#challenge-user").val();
		var coins = jPages["challenge"].find("#challenge-coins").val();
		var challengeGameId = jPages["challenge"].find("#challenge-game").val();
		var challengeMessage = jPages["challenge"].find("#challenge-message").val();
		var challengeScore = 0;
		console.log(challengeFromUserId,challengeToUserId,coins,challengeGameId,challengeMessage);
		
		if(challengeFromUserId && challengeToUserId && coins && challengeGameId && challengeMessage){
			
			$.when(send_request("createchallenge",null,
					{
						"userHash":userHash,
						"challenge_from":challengeFromUserId,
						"challenge_to":challengeToUserId,
						"challenge_score":challengeScore,
						"game_id":challengeGameId,
						"challenge_coins":coins,
						"challengeFromMsg":challengeMessage
					}
				)
			).done(function(data){
				console.log("create challenge get success",arguments);
				data = parseJson(data);
				console.log("create challenge get success",data);
				if(data && typeof data["status"] !== "undefined" && data["status"] === "success"){
					//yumpod_service.reloadPage('#challengePage');
					yumpod_controllers.load("challengePage");
					
				}
				//yumpod_service.triggerEvent("loadGames",data);
			}).fail(function(error){
				console.log("create challenge get fail",arguments);
			});
		}
		
	});
	
	//for auto completing user search in Search Panel on Challenge Page
	$( "#search-user-list" ).on( "filterablebeforefilter", function ( e, data ) {
        var $ul = $( this ),
            $input = $( data.input ),
            value = $input.val(),
            html = "";
        	$ul.html( "" );
        if ( value && value.length > 2 ) {
            $ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
            $ul.listview( "refresh" );
            var userHash = yumpod_service.playerDict["userHash"];
            $.when(send_request("searchuser",null,
					{"userHash":userHash,"search":$input.val(),"page":0}
				)
			).done(function(data){
				console.log("user list get success",arguments);
				data = parseJson(data);
				console.log("user list get success",data);
				if(data && typeof data["status"] !== "undefined" && data["status"] === "success"){

					data = data["data"];
					console.log("user list get success",data);
					$.each(data, function( i, val ){
						html += '<li>' +
									'<a href="#challengePage" data-rel="close" class="check-select-user" data-select-userid="' + val.userid + '" data-select-username="' + val.username + '" data-select-user-fn="loadChallengePageUserSelect" >' +
										'<h4>' + val.name + '</h4>' +
										'<p>@' + val.username + ' | ' + val.email + '</p>' +
									'</a>' + 
								'</li>';
					});
	                $ul.html( html );
	                $ul.listview( "refresh" );
	                $ul.trigger( "updatelayout");
				}
				//yumpod_service.triggerEvent("loadGames",data);
			}).fail(function(error){
				console.log("user list get fail",arguments);
			});
        }
    });

	
	//for auto completing user search on Search Page
	$( "#searchpage-user-list" ).on( "filterablebeforefilter", function ( e, data ) {
        var $ul = $( this ),
            $input = $( data.input ),
            value = $input.val(),
            html = "";
        	$ul.html( "" );
        if ( value && value.length > 2 ) {
            $ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
            $ul.listview( "refresh" );
            var userHash = yumpod_service.playerDict["userHash"];
            $.when(send_request("searchuser",null,
					{"userHash":userHash,"search":$input.val(),page:0}
				)
			).done(function(data){
				console.log("user list get success",arguments);
				data = parseJson(data);
				console.log("user list get success",data);
				if(data && typeof data["status"] !== "undefined" && data["status"] === "success"){

					data = data["data"];
					console.log("user list get success",data);
					$.each(data, function( i, val ){
						html += '<li>' +
									'<a href="#profilePage" data-rel="close" class="check-select-user" data-select-userid="' + val.userid + '" data-select-username="' + val.username + '" data-select-user-fn="loadProfilePageUserSelect" >' +
										'<h4>' + val.name + '</h4>' +
										'<p>@' + val.username + ' | ' + val.email + '</p>' +
									'</a>' + 
								'</li>';
					});
	                $ul.html( html );
	                $ul.listview( "refresh" );
	                $ul.trigger( "updatelayout");
				}
				//yumpod_service.triggerEvent("loadGames",data);
			}).fail(function(error){
				console.log("user list get fail",arguments);
			});
        }
    });

	//for challenge accept btn actions on challenge page
	jPages["challenge"].on("click",".challenge-btn-accept",function(e){
		var jAnc = $(this);
		if(jAnc.attr('data-challenge-id')){
			var userHash = yumpod_service.playerDict["userHash"];
            $.when(send_request("acceptchallenge",null,
					{"userHash":userHash,"challenge_id":jAnc.attr('data-challenge-id')}
				)
			).done(function(data){
				console.log("acceptchallenge success",arguments);
				
				data = parseJson(data);
				//console.log("acceptchallenge success",data);
				if(data && typeof data["status"] !== "undefined" && data["status"] === "success"){
					yumpod_service.reloadPage('#challengePage');
				}
				
				//yumpod_service.triggerEvent("loadGames",data);
			}).fail(function(error){
				console.log("acceptchallenge fail",arguments);
			});
		}
	});

	//for challenge decline btn actions on challenge page
	jPages["challenge"].on("click",".challenge-btn-decline",function(e){
		var jAnc = $(this);
		if(jAnc.attr('data-challenge-id')){
			var userHash = yumpod_service.playerDict["userHash"];
            $.when(send_request("declinechallenge",null,
					{"userHash":userHash,"challenge_id":jAnc.attr('data-challenge-id')}
				)
			).done(function(data){
				console.log("declinechallenge success",arguments);
				/*
				data = parseJson(data);
				console.log("user list get success",data);
				if(data && typeof data["status"] !== "undefined" && data["status"] === "success"){

					data = data["data"];
					console.log("user list get success",data);
					$.each(data, function( i, val ){
						html += '<li>' +
									'<a href="#profilePage" data-rel="close" class="check-select-user" data-select-userid="' + val.userid + '" data-select-username="' + val.username + '" data-select-user-fn="loadProfilePageUserSelect" >' +
										'<h4>' + val.name + '</h4>' +
										'<p>@' + val.username + ' | ' + val.email + '</p>' +
									'</a>' + 
								'</li>';
					});
	                $ul.html( html );
	                $ul.listview( "refresh" );
	                $ul.trigger( "updatelayout");
				}
				*/
				//yumpod_service.triggerEvent("loadGames",data);
			}).fail(function(error){
				console.log("declinechallenge fail",arguments);
			});
		}
	});
	

	//For any anchor that is for "status like" service.
	$(document).on("click",".yvtw-like-btn",function(e){
		var jAnc = $(this);
		if(jAnc.attr('data-status-id')){
			//jAnc.attr('data-status-like',"false");
			var userHash = yumpod_service.playerDict["userHash"];
            $.when(send_request("likestatus",null,
					{"userHash":userHash,"statusid":jAnc.attr('data-status-id')}
				)
			).done(function(data){
				console.log("status_like success",arguments);
				
				try{
					data = parseJson(data);

					if(data && data["data"] && data["data"]["status"] === "success"){

						yumpod_model.set("timeline",[data["data"]["user_status"]],"status_id");
						yumpod_service.triggerEvent("loadTimeline_status");
						/*console.log("Changing status for like button",jAnc.attr('data-status-like'))
						jAnc.attr('data-status-like',"true");
						jAnc.next().html(data["data"]["user_status"]["totallike"]);
						console.log("Changing status for like button",jAnc.attr('data-status-like'))
						*/
					}
				}catch(e){
					console.log("status_like error",e);
				}

				
				//yumpod_service.triggerEvent("loadGames",data);
			}).fail(function(error){
				console.log("status_like fail",arguments);
			});
		}
	});

	$(document).on("click","[data-rel-count]",function(e){
		e.preventDefault();
		console.log("data-rel-count acivetd");
		var jAnc = $(this);
		if(jAnc.attr("data-rel-count")){
			var gobackCnt = jAnc.attr("data-rel-count");
			gobackCnt = parseInt("-" + gobackCnt,10);
			gobackCnt = 1;
			history.go(gobackCnt);
		}		
	});

	//for any click on reply button to call replyStatusPage
	$(document).on("click","[href='#replyStatusPage']",function(e){
		console.log("Reply status clicked");
		var replyStatusId = this.hasAttribute('data-status-id') ? this.getAttribute('data-status-id') : null;
		var replyUsername = this.hasAttribute('data-username') ? this.getAttribute('data-username') : null;
		if(replyStatusId && replyUsername && yumpod_service && yumpod_service['pageData']){
			yumpod_service['pageData']['replyPage'] = {'replyStatusId' : replyStatusId,'replyUsername':replyUsername};
			var jActivePage = yumpod_service.showPostStatusDialog();
			jActivePage.find(".poststatus-replyusername").val(replyUsername);
			jActivePage.find(".poststatus-replystatusid").val(replyStatusId);
			var postStatusTextarea = jActivePage.find(".poststatus-status").val("@" + replyUsername + ' ').get();
			jActivePage.find(".poststatus-btn").html("Reply @" + replyUsername);
			moveCursorToEnd(postStatusTextarea);

			//return true;
		}
		return false;
	});

	//for posting replay on an status via replayStatusPage
	jPages["replyStatus"].on("click","#replystatus-submit",function(){
		
		var replyStatusId = jPages["replyStatus"].find("#replystatus-id").val();
		var replyContent = jPages["replyStatus"].find("#replystatus-status").val();
		if(replyStatusId && replyContent){
			
			var userHash = yumpod_service.playerDict["userHash"];
            $.when(send_request("replystatus",null,
					{"userHash":userHash,'status_id':replyStatusId,'status':replyContent}
				)
			).done(function(data){
				console.log("status_reply success",arguments);
				
				try{
					data = parseJson(data);
					if(data && data["status"] === "sucess"){
						console.log("status_reply success",data);
						jPages["replyStatus"].find("#replystatus-status").val('');
						jPages["replyStatus"].find("#replystatus-id").val('');
						window.history.go(-1);
					}else{
						yumpod_service.triggerEvent("popup","Reply for Status is Unsuccessful",null,"Failed to get response for posting your reply");
					}
				}catch(e){
					console.log("status_reply error",e);
					yumpod_service.triggerEvent("popup","Reply for Status is Unsuccessful",null,"Failed to get response for posting your reply" , e);
				}

				
				//yumpod_service.triggerEvent("loadGames",data);
			}).fail(function(error){
				console.log("status_like fail",arguments);
			});
		}
	});

	//for follow btn
	$(document).on("click",".profile-action-btn",function(e){
		var jAnc = $(this);
		if(jAnc.attr('data-user-id')){
			
				var dataAction = jAnc.attr('data-action');
				var dataActions = {"Follow":"addfollower","Unfollow":"removefollower","Block":"blockUser","Unblock":"unblockUser"}
				if(dataAction && dataActions[dataAction]){
					var userHash = yumpod_service.playerDict["userHash"];
		            $.when(send_request(dataActions[dataAction],null,
							{"userHash":userHash,'userid':jAnc.attr('data-user-id')}
						)
					).done(function(data){
						
						console.log(dataActions[dataAction] + " success",arguments);
						
						try{
							data = parseJson(data);
							if(data && data["data"] && data["data"]["status"] === "success"){
								yumpod_controllers.load("profilePage");
								yumpod_service.reloadPage('#profilePage');
								
							}else{
								yumpod_service.triggerEvent("popup","Error occoured on action : " + dataActions[dataAction],null,"Failed to get response on action " + dataActions[dataAction],e);
							}
						}catch(e){
							console.log(dataActions[dataAction] + " error",e);
							yumpod_service.triggerEvent("popup","Error occoured on action : " + dataActions[dataAction],null,"Failed to get response on action " + dataActions[dataAction],e);
						}

						
						//yumpod_service.triggerEvent("loadGames",data);
					}).fail(function(error){
						console.log(dataActions[dataAction] + " failed",arguments);
					});
				}
			
		}
	});

	jPages["imageUpload"].on("click","#imageupload-btn",function(){
		console.log("imageUpload button clicked");
		yumpod_service.imageUploadRequest();
	});


	

    //for handling show/hide on "post status" button in header
    $(document).on("click",".yvtw-icon-poststatus",function(e){
    	console.log("Post Status button clicked");
    	var jActivePage = yumpod_service.showPostStatusDialog();
    	jActivePage.find(".poststatus-replyusername").val('');
		jActivePage.find(".poststatus-replystatusid").val('');
		var postStatusTextarea = jActivePage.find(".poststatus-status").val('');
		jActivePage.find(".poststatus-btn").html("Update Status");
		moveCursorToEnd(postStatusTextarea);
    	
    	return false;
    });


    //for handling "status share" button all over
    $(document).on("click",".yvtw-share-btn",function(e){
    	if(this.hasAttribute('data-status-id')){
    		var userHash = yumpod_service.playerDict["userHash"];
            $.when(send_request("sharestatus",null,
					{"userHash":userHash,'status_id':this.getAttribute('data-status-id')}
				)
			).done(function(data){
				console.log("share_status success",arguments);
				
				try{
					data = parseJson(data);
					if(data && typeof (data["data"]) !== "undefined" && typeof (data["data"]["status"]) !== "undefined" && data["data"]["status"] === "success"){
						console.log("share_status success",data);
						
					}else{
						yumpod_service.triggerEvent("popup","Error occoured when sharing status",null,"Failed to get response for sharing the status",e);
					}
				}catch(e){
					console.log("share_status error",e);
					yumpod_service.triggerEvent("popup","Error occoured when sharing status",null,"Failed to get response for sharing the status",e);
				}

				
				//yumpod_service.triggerEvent("loadGames",data);
			}).fail(function(error){
				console.log("share_status fail",arguments);
			});
    	}
    });
    
    //for handling delete status button on status object
    $(document).on("click",".yvtw-delete-btn",function(e){
    	var elm = this;
    	if(this.hasAttribute('data-status-id')){
    		navigator.notification.confirm("Do you want to delete this status?", function(btnResponse){
    			//console.log("Delete status",arguments,elm);
    			if(btnResponse === 1){
    			
		    		var userHash = yumpod_service.playerDict["userHash"];
		            $.when(send_request("deletestatus",null,
							{"userHash":userHash,'status_id':elm.getAttribute('data-status-id')}
						)
					).done(function(data){
						console.log("delete_status success",arguments);
						
						try{
							data = parseJson(data);
							if(data && typeof (data["data"]) !== "undefined" && typeof (data["data"]["status"]) !== "undefined" && data["data"]["status"] === "success"){
								console.log("delete_status success",data);
								yumpod_service.triggerEvent("deleteTimelineStatus",data["data"]["statusid"]);
							}else{
								yumpod_service.triggerEvent("popup","Error occoured when deleting status",null,"Failed to get response for sharing the status",e);
							}
						}catch(e){
							console.log("share_status error",e);
							yumpod_service.triggerEvent("popup","Error occoured when deleting status",null,"Failed to get response for sharing the status",e);
						}

						
						//yumpod_service.triggerEvent("loadGames",data);
					}).fail(function(error){
						console.log("delete_status fail",arguments);
					});
				}
				
			}, "Delete Status?", ["Yes","No"]);
    	}
    });
	

	//for updating the bio
	jPages["profileedit"].on("click",".editbio-submit",function(e){
		console.log("update the profile bio");
		var bioText = jPages["profileedit"].find("#editbio-bio").val();
		if(bioText){
			var userHash = yumpod_service.playerDict["userHash"];
		            $.when(send_request("updatebio",null,
							{"userHash":userHash,'bio':bioText}
						)
					).done(function(data){
						console.log("update_bio response",arguments);
						
						try{
							data = parseJson(data);
							if(data && typeof (data["data"]) !== "undefined" && typeof (data["data"]["status"]) !== "undefined" && data["data"]["status"] === "success"){
								console.log("update_bio success",data);
								yumpod_service.triggerEvent("popup","Bio Updated",null,"Your bio is updated!");
							}else{
								yumpod_service.triggerEvent("popup","Error occoured when updating bio",null,"Failed to get response for updating the bio",e);
							}
						}catch(e){
							console.log("update_bio error",e);
							yumpod_service.triggerEvent("popup","Error occoured when updating bio",null,"Failed to get response for updating the bio",e);
						}
						
						
						//yumpod_service.triggerEvent("loadGames",data);
					}).fail(function(error){
						console.log("update_bio fail",arguments);
					});
		}
	});
   $(document).on("click",".logout-btn",function(e){
   		yumpod_service.triggerEvent("logout");	
   });

   //for read-more button on profile and myprofile page
   $(document).on("click",".read-more-btn",function(e){
   		var jElm = $(this);
   		if(jElm.attr('data-readmore-elmid')){
   			$('#' + jElm.attr('data-readmore-elmid')).removeClass('summary');
   			jElm.hide();
   		}
   });

   jPages['profileedit'].on("click","#editbio-photo",function(e){
   		try{
   			yumpod_cordova.captureImage();
   		}catch(e){
   			try{
   				console.log("Error occoured in uploading & capturing image",e);
   				navigator.notification.alert("Error occoured in uploading & capturing image", null, 'Error in Upload');
   			}catch(er){
   				console.log("Error occoured in uploading & capturing image",er);
   			}
   		}

   });

   jPages['profileedit'].on("click","#editbio-photogallery",function(e){
   		try{
   			yumpod_cordova.getImage();
   		}catch(e){
   			try{
   				console.log("Error occoured in retrieving & uploading image",e);
   				navigator.notification.alert("Error occoured in retrieving & uploading image", null, 'Error in Upload');
   			}catch(er){
   				console.log("Error occoured in retrieving & uploading image",er);
   			}
   		}

   });

   


   var yumpod_cordova = function(){
   		var r = {};
   		//var game_inapp_products = {"0":"pgame_all","2":"pgame2_atb","3":"pgame3_stc","4":"pgame4_stud","1":"pgame1_myh"};
   		var game_inapp_products = {"0":"um_game_all","2":"um_game2_atb","3":"um_game3_stc","4":"um_game4_stud","1":"um_game1_myh"};

   		r.pushToken;
   		r.pushNotification;


   		// Called when capture operation is finished
	    r.captureSuccess = function (mediaFiles) {
	        var i, len;
	        console.log("Capture Success",mediaFiles);
	        for (i = 0, len = mediaFiles.length; i < len; i += 1) {
	            r.uploadFile(mediaFiles[i]);
	        }
	    }

    	// Called if something bad happens.
    	r.captureError = function (error) {
        	var msg = 'An error occurred during capture: ' + error.code;
        	navigator.notification.alert(msg, null, 'Uh oh!');
    	}

    	// A button will call this function
    	r.captureImage = function () {
        	// Launch device camera application,
        	// allowing user to capture up to 2 images
        	//navigator.device.capture.captureImage(r.captureSuccess, r.captureError, {limit: 1});
        	navigator.camera.getPicture(r.getImageSuccess, r.getImageFail, { quality : 75,
			  destinationType : Camera.DestinationType.FILE_URI,
			  sourceType : Camera.PictureSourceType.CAMERA ,
			  allowEdit : true,
			  encodingType: Camera.EncodingType.JPEG,
			  targetWidth: 300,
			  targetHeight: 300,
			  popoverOptions: CameraPopoverOptions,
			  saveToPhotoAlbum: false 
			});
    	}

    	// Upload files to server
    	r.uploadFile = function (mediaFile) {
    		console.log("Uploading file",mediaFile);
    		yumpod_service.showWaitLoader("Uploading image to server");
        	var ft = new FileTransfer(),
            path = mediaFile.fullPath,
            imageName = mediaFile.name;

            var userHash = yumpod_service.playerDict["userHash"];

            /*
        	ft.upload(path,
            	URLs["base"] + URLs["uploadPhoto"],
            	function(result) {
                	console.log('Upload success: ' + result.responseCode);
                	console.log(result.bytesSent + ' bytes sent');
            	},
            	function(error) {
                	console.log('Error uploading file ' + path + ': ' + error.code);
            	},
            	{ "image": imageName, "userHash" : userHash });

			*/
        	var options = new FileUploadOptions();
		    options.fileKey="image";
		    options.fileName=mediaFile.name + '.jpg';
		    options.mimeType="text/plain";

		    var params ={ "userHash" : userHash };

		    options.params = params;

		    var ft = new FileTransfer();
		    ft.upload(path, encodeURI(URLs["base"] + URLs["uploadPhoto"]), 
		    	function win(r) {
				    console.log("Code = " + r.responseCode);
				    console.log("Response = " + r.response);
				    console.log("Sent = " + r.bytesSent);
				    yumpod_service.hideWaitLoader();
				},
				function fail(error) {
				    alert("An error has occurred: Code = " + error.code);
				    console.log("upload error source " + error.source);
				    console.log("upload error target " + error.target);
				    yumpod_service.hideWaitLoader();
				}, 
				options);
    	}

    	r.getImage = function(){
		    navigator.camera.getPicture(r.getImageSuccess, r.getImageFail, { quality : 75,
			  destinationType : Camera.DestinationType.FILE_URI,
			  sourceType : Camera.PictureSourceType.PHOTOLIBRARY ,
			  allowEdit : true,
			  encodingType: Camera.EncodingType.JPEG,
			  targetWidth: 300,
			  targetHeight: 300,
			  popoverOptions: CameraPopoverOptions,
			  saveToPhotoAlbum: false 
			});
    	}

    	r.getImageSuccess = function(imageURI){
    		var username = yumpod_service.playerDict["username"];
    		var mediaObj = {"fullPath":imageURI,"name":username};
    		
    		r.uploadFile(mediaObj);
    	}

    	// result contains any message sent from the plugin call (result)
    	r.pushNotificationSuccessHandler = function(result){
    		//alert('result = ' + result);
		}

		// result contains any error description text returned from the plugin call
		r.pushNotificationErrorHandler = function (error) {
		    //alert('error = ' + error);
		}

		r.pushNotificationIosTokenHandler= function (result) {
		    // Your iOS push server needs to know the token before it can push to this device
		    // here is where you might want to send it the token for later use.
		    //alert('device token = ' + result);
		}

		// iOS
		window.onNotificationAPN = function (event) {
		    if ( event.alert ){
		        navigator.notification.alert(event.alert);
		    }

		    if ( event.sound ){
		        var snd = new Media(event.sound);
		        snd.play();
		    }

		    if ( event.badge ){
		        pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
		    }
		}



		// Android
		window.onNotificationGCM = function (e) {
		    //$("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>');

		    switch( e.event ){
		    case 'registered':
		        if ( e.regid.length > 0 ){
		            //$("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>");
		            // Your GCM push server needs to know the regID before it can push to this device
		            // here is where you might want to send it the regID for later use.
		            //console.log("regID = " + e.regid);
		            //alert('registration id = '+e.regid);
		            r.pushToken = e.regid;
		            r.registerDevice();
		        }
		    break;

		    case 'message':
		        // if this flag is set, this notification happened while we were in the foreground.
		        // you might want to play a sound to get the user's attention, throw up a dialog, etc.
		        if ( e.foreground ){
		            //$("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</li>');

		            // if the notification contains a soundname, play it.
		            var my_media = new Media("/android_asset/www/"+e.soundname);
		            my_media.play();
		        }else{  
		        	// otherwise we were launched because the user touched a notification in the notification tray.
		            if ( e.coldstart ){
		                //$("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>');
		            }else{
		                //$("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>');
		            }
		        }

		        //$("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>');
		        //Only works for GCM
		           //$("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>');
		           //Only works on Amazon Fire OS
		           //$status.append('<li>MESSAGE -> TIME: ' + e.payload.timeStamp + '</li>');
		        //alert('message = '+e.payload.m);
		    break;

		    case 'error':
		        //$("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>');
		        //alert('GCM error = '+e.msg);
		    break;

		    default:
		        //$("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');
		        //alert('An unknown GCM event has occurred');
		    break;
		  }
		}

		r.registerDevice = function(){
			//registering the device for recieving push notifications
        	var player = yumpod_service.checkLoginAndGetPlayerDict();
			var userid = player? player["userid"] : null;
			var userHash = player? player["userHash"] : null;
			if(player && r.pushToken){
				//console.log("now pushing token :" + r.pushToken);
	        	$.when(send_request("deviceregistration",null,
								//{"userHash":userHash,'userid':userid,'device_id':device.uuid,key:'AIzaSyA8j0UUAPDL7aAj6ebvGRm5DkANzYOTLZo','device_type':0}
								{"userHash":userHash,'userid':userid,'device_id':r.pushToken,key:'AIzaSyA8j0UUAPDL7aAj6ebvGRm5DkANzYOTLZo','device_type':0}
							)
						).done(function(data){
							console.log("deviceregistration success",arguments);
							
							try{
								
								data = parseJson(data);
								if(data && typeof (data["data"]) !== "undefined" && typeof (data["data"]["status"]) !== "undefined" && data["data"]["status"] === "success"){
									console.log("deviceregistration success",data);
									
								}else{
									yumpod_service.triggerEvent("popup","Error occoured when deviceregistration",null,"Failed to get response for deviceregistration",e);
								}
								
							}catch(e){
								console.log("deviceregistration error",e);
								//yumpod_service.triggerEvent("popup","Error occoured when deviceregistration",null,"Failed to get response for deviceregistration",e);
							}

							
							//yumpod_service.triggerEvent("loadGames",data);
						}).fail(function(error){
							console.log("deviceregistration fail",arguments);
						});
			}else{
				//alert("not able to push token ");
			}
		}

		r.paymentSuccessHandler = function (result) {
            var strResult = "";
            if(typeof result === 'object') {
                    strResult = JSON.stringify(result);
                } else {
                    strResult = result;
            }
            r.consumePurchase(result);
            //alert(JSON.stringify(arguments));

            var boughtGameId = null;
            for(var gameid in game_inapp_products){
            	if(game_inapp_products[gameid] == result){
            		boughtGameId = gameid;
            		break;
            	}
            }
            var player = yumpod_service.checkLoginAndGetPlayerDict();
			var userid = player? player["userid"] : null;
			var userHash = player? player["userHash"] : null;
			if(player && userHash && userid && boughtGameId){
				//alert("now pushing token :" + r.pushToken);
	        	$.when(send_request("pushpayment",null,
								//{"userHash":userHash,'userid':userid,'device_id':device.uuid,key:'AIzaSyA8j0UUAPDL7aAj6ebvGRm5DkANzYOTLZo','device_type':0}
								{"userHash":userHash,'gameid':boughtGameId,'transactionid':'dummytransactionid','price':'£1','paymentinfo':'123456789'}
							)
						).done(function(data){
							console.log("game bought success",arguments);
							//yumpod_service.triggerEvent("loadGames",games);
							yumpod_controllers.load('gameSelectionPage');
							try{
								
								data = parseJson(data);
								if(data && typeof (data["data"]) !== "undefined" && typeof (data["data"]["status"]) !== "undefined" && data["data"]["status"] === "success"){
									console.log("game bought success parsed",data);
									
								}else{
									yumpod_service.triggerEvent("popup","Error occoured when game_bought",null,"Failed to get response for game_bought",e);
								}
								
							}catch(e){
								console.log("game_bought error",e);
								//yumpod_service.triggerEvent("popup","Error occoured when deviceregistration",null,"Failed to get response for deviceregistration",e);
							}

							
							//yumpod_service.triggerEvent("loadGames",data);
						}).fail(function(error){
							console.log("game_bought fail",arguments);
							yumpod_controllers.load('gameSelectionPage');
						});
			}

            //alert("SUCCESS: \r\n"+strResult );
            
            console.log("paymentSuccessHandler: " + strResult);
            yumpod_service.triggerEvent("loadGames",games);
        }

        r.paymentAlreadyDoneSuccessHandler = function(result) {
        	var strResult = "";
            if(typeof result === 'object') {
            		var games = yumpod_store.get("games",true);
            		//alert("About to change game bought :" + JSON.stringify(games));
            		for(var prIdx in result){
            			var productBought = result[prIdx];
            			for(var prSeq in game_inapp_products){
            				if(game_inapp_products[prSeq] === productBought['productId']){
            					
								
								for(var idx in games){
									var game = games[idx];
									if(game.gameid === prSeq || prSeq === '0'){
										game['bought'] = true;
										//alert("game bought from google : " + JSON.stringify(game));
									}
								}
            				}
            			}
            		}
            		//alert("Changed game bought :" + JSON.stringify(games));
            		yumpod_store.set("games",games,true);
            		yumpod_service.triggerEvent("loadGames",games);
            	}
            	/*
                    strResult = JSON.stringify(result);
                } else {
                    strResult = result;
            }
            alert("SUCCESS: \r\n"+strResult );

            console.log("paymentAlreadyDoneSuccessHandler: " + strResult);
            */
        }

        r.paymentInitSuccessHandler = function(result) {
        	var strResult = "";
            if(typeof result === 'object') {
                    strResult = JSON.stringify(result);
                } else {
                    strResult = result;
            }
            //alert("SUCCESS: \r\n"+strResult );
            console.log("paymentInitSuccessHandler: " + strResult);
            //r.ownedProducts();
            
        }

        

        r.paymentAlreadyDoneErrorHandler = function (error) {
        	//alert("ERROR: \r\n"+error );
        	console.log("paymentAlreadyDoneErrorHandler: " + error);
        }

        r.paymentErrorHandler = function (error) {
            //alert("ERROR: \r\n"+error );
            console.log("paymentErrorHandler: " + error);
            yumpod_service.triggerEvent("loadGames",games);
        }

        r.paymentInitErrorHandler = function (error) {
            //alert("ERROR: \r\n"+error );
            console.log("paymentInitErrorHandler: " + error);
            //r.ownedProducts();
        }

        r.paymentAvailableProductsErrorHandler = function (error) {
        	console.log("paymentAvailableProductsErrorHandler : " + error);

        }

        //r.paymentConsumePurchaseSuccessHandler = 

        r.paymentConsumePurchaseErrorHandler = function(){
        	console.log("paymentConsumePurchaseErrorHandler: [" + JSON.stringify(arguments) + "]");
        }

        // Click on Consume purchase button
        r.consumePurchase = function(productId,retryBuy,productIdx){
        	inappbilling.consumePurchase(
        		//on success
        		function(){
        			console.log("paymentConsumePurchaseSuccessHandler: [" + JSON.stringify(arguments) + "]");
        			if(retryBuy && productIdx !== "undefined" && productIdx !== null){
        				r.buyGame(productIdx);
        			}
        		}, 
        		r.paymentConsumePurchaseErrorHandler, productId);
        }

        // Click on init button
        r.paymentinit = function (){
            // Initialize the billing plugin
            inappbilling.init(r.paymentInitSuccessHandler, r.paymentInitErrorHandler, {showLog:true});
        }

        // Click on purchase button
        r.buyGame = function(productId){
        	console.log("buying game : " + game_inapp_products[productId]);
            // make the purchase
            if(game_inapp_products[productId]){
            	inappbilling.buy(r.paymentSuccessHandler, 
            		//on error
            		function(error){
            			console.log("paymentErrorHandler: " + error);
            			r.consumePurchase(game_inapp_products[productId],true,productId);
            		},game_inapp_products[productId]);
        	}

        }

            
        // Click on ownedProducts button
        r.ownedProducts = function(){
            // Initialize the billing plugin
            if(typeof inappbilling !== "undefined" && inappbilling && inappbilling.getPurchases){
            	inappbilling.getPurchases(r.paymentAlreadyDoneSuccessHandler, r.paymentAlreadyDoneErrorHandler);
			}else{
				console.log("getPurchases - inappbilling not found!");
			}
        }

        // Click on Get Available Products button
        r.availableProducts = function(){
            // Get the products available for purchase.
            if(typeof inappbilling !== "undefined" && inappbilling && inappbilling.getPurchases){
            	inappbilling.getAvailableProducts(r.paymentAvailableProductsSuccessHandler, r.paymentAvailableProductsErrorHandler);
        	}else{
        		console.log("getAvailable - inappbilling not found");
        	}

        }   

            

            

            

        r.initUserUtilities = function(){
        	var player = yumpod_service.checkLoginAndGetPlayerDict();
			var userid = player? player["userid"] : null;
			var userHash = player? player["userHash"] : null;

			if(player && userid && userHash){
	        	r.pushNotification = window.plugins.pushNotification;

	        	r.paymentinit();

	        	//for registering the push notification
	        	if ( device.platform == 'android' || device.platform == 'Android' || device.platform == "Amazon" || device.platform == "amazon"){
				    r.pushNotification.register(
				        r.pushNotificationSuccessHandler,
				        r.pushNotificationErrorHandler, {
				            "senderID":"575520928829",
				            "ecb":"onNotificationGCM"
				        });
				}else{
				    pushNotification.register(
				        r.pushNotificationIosTokenHandler,
				        r.pushNotificationErrorHandler, {
				            "badge":"true",
				            "sound":"true",
				            "alert":"true",
				            "ecb":"onNotificationAPN"
				        });
				}
			}
        }                       

    	r.onDeviceReady = function() {
        	r.device = {"name":device.name,"cordova":device.cordova,"platform":device.platform,"uuid":device.uuid,"model":device.model,"version":device.version};
        	
        	r.initUserUtilities();
			

        	console.log("Device info ",r.device,":",device);
    	}

    	return r;
   }();
   

   document.addEventListener("deviceready", yumpod_cordova.onDeviceReady, false);

    
    

   var moveCursorToEnd = function (el) {
	    if (typeof el.selectionStart == "number") {
	        el.selectionStart = el.selectionEnd = el.value.length;
	    } else if (typeof el.createTextRange != "undefined") {
	        el.focus();
	        var range = el.createTextRange();
	        range.collapse(false);
	        range.select();
	    }
	}

	//for status link to detailStatusPage
	$(document).on("click",".status-content-span",function(e){
		var jThis = $(this);
		if(jThis.attr('data-status-id')){
			yumpod_service.pageData["detailStatus"] = {'status_id':jThis.attr('data-status-id')};
			yumpod_service.location_redirect("#detailStatusPage");
		}
	});

	/*
	jPages["gameSelection"].on("click",".listGames li",function(e){
		if(this.hasAttribute('data-game-id')){
			var games = yumpod_store.get("games",true);
			
			for(var idx in games){
				var game = games[idx];
				if(game["sequence"] === this.getAttribute('data-game-id')){
					if(game["bought"] !== true && game["enabled"] === true){
						console.log("About to buy the game - " + yumpod_cordova.game_inapp_products[game["sequence"]]);
						yumpod_cordova.buyGame(yumpod_cordova.game_inapp_products[game["sequence"]]);
						break;
					}
				}
			}
		}
		
	});
	*/

	

	//for implementing username uniqueness and availablilit on signup
	$(document).on("change",".signup-email",function(e){
		console.log("Value changed:",this.value);
		var newusername = this.value;
		if(typeof newusername !== "undefined" && newusername.length > 3){
				$.when(send_request("usernameexists",null,
						//{"userHash":userHash,'userid':userid,'device_id':device.uuid,key:'AIzaSyA8j0UUAPDL7aAj6ebvGRm5DkANzYOTLZo','device_type':0}
						{'username':boughtGameId}
					)
				).done(function(data){
					console.log("username_exists success",arguments);
					
					try{
						
						data = parseJson(data);
						if(data && typeof (data["data"]) !== "undefined" && typeof (data["data"]["status"]) !== "undefined" && data["data"]["status"] === "success"){
							console.log("username_exists success parsed",data);
							
						}else{
							yumpod_service.triggerEvent("popup","Error occoured when username_exists",null,"Failed to get response for username_exists",e);
						}
						
					}catch(e){
						console.log("username_exists error",e);
						//yumpod_service.triggerEvent("popup","Error occoured when deviceregistration",null,"Failed to get response for deviceregistration",e);
					}

					
					//yumpod_service.triggerEvent("loadGames",data);
				}).fail(function(error){
					console.log("username_exists fail",arguments);
				});
		}
	});

	//for forget password submit button handling
	jPages['forgotPassword'].on("click","#forgotpassword-submit",function(e){
		var email = jPages['forgotPassword'].find("#forgotpassword-email").val();
		
		if(typeof email !== "undefined" && email.length > 3){
				yumpod_service.showWaitLoader("Sending request for forgotten password..");
				$.when(send_request("forgotpassword",null,
						//{"userHash":userHash,'userid':userid,'device_id':device.uuid,key:'AIzaSyA8j0UUAPDL7aAj6ebvGRm5DkANzYOTLZo','device_type':0}
						{'email':email}
					)
				).done(function(data){
					yumpod_service.hideWaitLoader();
					console.log("forgot_password success",arguments);
					yumpod_service.triggerEvent("popup","Password reset success",null,"A new password has been mailed to your email. Please check and log back in.");
					

					
					//yumpod_service.triggerEvent("loadGames",data);
				}).fail(function(error){
					yumpod_service.hideWaitLoader();
					console.log("forgot_password fail",arguments);
				});
		}
	});
	
	/*
	var fillDictMission = function(gameid,score){
		var dictMissions = {"currentSelectedGame":gameid,"currentScore":score};
		yumpod_store.set("dictMissions",dictMissions,true);
	}

	fillDictMission(1,200);
	*/
	
})(jQuery);
