//var baseUrl="http://test.apalabrados.com/api";
var baseUrl="http://apalabrados.com/api";
angular.module('starter.controllers', ['ngStorage','ngAudio','luegg.directives'])
.controller('homeCtrl', function($scope, $state, $awordedFactory,$rootScope,$localStorage) {
	$scope.regForm =false;
	$scope.loadingIcon =false;	
	$scope.moveToAwordedLogin=function(){
		$state.go('awordedLogin');
	}
	$scope.regisform=function(){
		$scope.regForm =true;
	}
	$scope.cancelRefform=function(){
		$scope.regForm =false;
	}
	$scope.validate = function(data){
		var flag;
		$(".error").css({"display":"none"});
		var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);

		//console.log(data.user_rpassword +"=="+ data.user_password);
		if(data.user_name == undefined){
			$("#userError").css({"display":"block"});
			flag = true;
		}else if(data.user_email == undefined){
			$("#userEmail").css({"display":"block"});
			flag = true;
		}else if(emailReg.test(data.user_email)!=true){
			$("#userEmail").css({"display":"block"});
			flag = true;
		}else if(data.user_password == undefined){
			$("#userPassword").css({"display":"block"});
			flag = true;
		}else if(data.user_rpassword == undefined){
			$("#userRPassword").css({"display":"block"});
			flag = true;
		}else if(data.user_rpassword != data.user_password){
			$("#userRPassNot").css({"display":"block"});
			flag = true;
		}else {flag = false;}
		return flag;
	}
	$scope.registrationFun = function(data){
		$scope.loadingIcon =true;
		if(data != undefined){
			var vFlag =false;
			vFlag = $scope.validate(data);
			if(vFlag == true){}else{
				$scope.loginEmail = data.user_email;
				$scope.loginPass = data.user_password;
				var data = {"email":""+data.user_email,"username":""+data.user_name,"password":""+data.user_password,"site":"std"}
				var postHeaders = {
						'Content-Type': 'application/json',
						'Accept': 'application/json',
						'etergames-referer': "Access-Control-Request-Headers"
				};
				$awordedFactory.getPostReqData('POST', baseUrl+'/users', data,postHeaders)
					.then(function (response){
						var loginDetails = {"email":""+$scope.loginEmail ,"password":""+$scope.loginPass};
						//$awordedFactory.getPostReqData('POST', baseUrl+'/login', loginDetails, postHeaders).then(function (response){
						$awordedFactory.getLoginDetails(loginDetails).then(function (response){
							$scope.loadingIcon =false;
							if(response.id != ""){
								delete $localStorage.email;
								delete $localStorage.password;
								$localStorage.$default({
									  email:$scope.loginEmail,
									  password:$scope.loginPass
								});
								$state.go('menu.dashboard');
							}else{
								$state.go('home');
							}
						});
					},function(err){
						$scope.loadingIcon =false;
						alert("User already Exist");
					}
				);
			}
		}else{
			$scope.loadingIcon =false;
			alert("Please Enter the details for registration");
		}
	}
})
.controller('testCtrl', function($scope, $state, $awordedFactory, $rootScope,$localStorage,ngAudio,$timeout){
	$('#shuffle').mixItUp();
	$scope.loadAnimation=function(){
		$(".animateDiv").animate({left: 200}, 2000);			
	}
	$("#btn3").click(function(){
		$('#shuffle').mixItUp();
    });
	var test =true, ten = "Hello";
	$("#btn4").click(function(){
		if(test==true){
			ten = ten+ "10";
			$(".animateDiv").animate({left: 0}, 2000);
			$scope.loadAnimation();
		}
    });
	$scope.playSound=function(){
		//$scope.sound = ngAudio.play("sounds/BottleOpen.mp3");
	}
	$scope.getChatResponse =function(){
		$rootScope.getHeaders = {
				'Content-Type': 'multipart/form-data',
				'Accept': 'application/json',
				'etergames-referer': "Access-Control-Request-Headers"
			};
			$rootScope.getHeaders['Eter-Session'] = 'ap_session=a7b21ebb32f1a3a2c6aae659de90922349c0934f';
		var data ={};
		$awordedFactory.getReqData('GET', 'http://apalabrados.com/api/users/182025285/chatHeaders', data, $rootScope.getHeaders)
			.then(function (response){
					//console.log(response);
				},function(err){
					//console.log('error'+JSON.stringify(err));
				}
			);
	}
	$scope.items = ['1', '2', '3','4','5','6','7','8'];
	
	$scope.getUserdetails =function(){
		$rootScope.getHeaders = {
				'Content-Type': 'multipart/form-data',
				'Accept': 'application/json',
				'etergames-referer': "Access-Control-Request-Headers"
			};
			$rootScope.getHeaders['Eter-Session'] = 'ap_session=a7b21ebb32f1a3a2c6aae659de90922349c0934f';
		var data ={};
		$awordedFactory.getReqData('GET', 'http://apalabrados.com/api/users/182025285/profile', data, $rootScope.getHeaders)
			.then(function (response){
					//console.log(response);
				},function(err){
					//console.log('error'+JSON.stringify(err));
				}
			);
	}
	//$timeout(addItem, 1000);
})
.controller('checkloginctrl', function($scope, $state, $awordedFactory, $rootScope,$localStorage) {
	
	$scope.checklogin=function(){
		if($localStorage.email == undefined && $localStorage.password == undefined){
			$state.go('home');
		}else{
			var data = {"email":""+$localStorage.email,"password":""+$localStorage.password};
			$awordedFactory.getLoginDetails(data).then(function (response){
				if(response.signSucess == true){
					delete $localStorage.email;
					delete $localStorage.password;
					$localStorage.$default({
						  email:$localStorage.email,
						  password:$localStorage.password
					});
					$state.go('menu.dashboard');
				}else{
					$state.go('home');
				}
			});
		}
	}
})
.controller('awordedLoginCtrl', function($scope, $ionicHistory, $awordedFactory, $rootScope, $state,$localStorage) {
	$scope.forgotPasswordFlag= true;
	$scope.goToHome=function(){
		$ionicHistory.goBack();
	};

	$scope.signIn=function(){
		var data = {"email":""+$scope.user.username,"password":""+$scope.user.password };
		$awordedFactory.getLoginDetails(data).then(function (response){
			if(response.signSucess == true){
				delete $localStorage.email;
				delete $localStorage.password;
				$localStorage.$default({
					  email:$scope.user.username,
					  password:$scope.user.password
				});
				$state.go('menu.dashboard');
			}
		});
	};
	$scope.forgotPassword =function(){
		$scope.forgotPasswordFlag = false;
	}
	$scope.fpCancel =function(){
		$scope.forgotPasswordFlag = true;
	}
	$scope.validate = function(data){
		var flag;
		$(".error").css({"display":"none"});
		var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
		if(data == undefined){
			$("#fpuserEmail").css({"display":"block"});
			flag = true;
		}else if(emailReg.test(data)!=true){
			$("#fpuserEmail").css({"display":"block"});
			flag = true;
		}else {flag = false;}
		return flag;
	}
	$scope.sendPasswordsendPassword =function(data){
		var sendFlag = false
		sendFlag = $scope.validate(data.email);
		if(sendFlag == false)
		{
			var data = {"email":data.email};
			var postHeaders = {
					'Content-Type': 'application/json',
					'Accept': 'application/json',
					'etergames-referer': "Access-Control-Request-Headers"
			};
			$awordedFactory.getPostReqData('POST', baseUrl+'/reset-password', data, postHeaders)
				.then(function (response){
					alert("New password has been sent to your email");
				},function(err){
					alert("Error: "+ err.message);
				}
			);
		}
	}
})
.controller('userProfileCtrl', function($scope, $state, $awordedFactory, $rootScope) {
	var data = null;
	$awordedFactory.getReqData('GET', baseUrl+'/users/'+$rootScope.loginUserData.id+'/users/'+$rootScope.loginUserData.id, data, $rootScope.getHeaders)
					.then(function (response){
						$scope.userProfileData=response;
						if(response.facebook_name === undefined || response.fb_show_name == false){
							$scope.username = response.username;
						}else{
							$scope.username = response.facebook_name;
						}
						var lan;
						for(var j=0; j<response.games_by_language.length; j++){
							lan = response.games_by_language[j].language;
							lan = lan.toLowerCase();
							response.games_by_language[j].language = lan;
						}
						tGames = $scope.userProfileData.stats.games_played;
						lGames = $scope.userProfileData.stats.games_lost;
						rPrecent = lGames / tGames;
						rPer = Math.round(rPrecent * 100);
						$scope.resignedGames = rPer;
						
						if(response.facebook_id === undefined){
							$scope.imageSrc = "images/default-user-picture.png" ;
							$scope.imageFlag = false;
						}else{
							if(response.fb_show_picture!=false){
								$scope.imageSrc = "http://graph.facebook.com/"+response.facebook_id+"/picture" ;
								$scope.imageFlag = true;
							}else{
								$scope.imageSrc = "images/default-user-picture.png" ;
								$scope.imageFlag = false;
							}
						}
						
						var d1 = response.stats.last_move.play_date;
						var date1 = new Date(d1);
						var date2 = new Date();
						if (date2 < date1) {
							date2.setDate(date2.getDate() + 1);
						}
						var diff = date2 - date1;
						var msec = diff;
						var hh = Math.floor(msec / 1000 / 60 / 60);
						msec -= hh * 1000 * 60 * 60;
						
						var dd = Math.floor(hh/24);
						
						var mm = Math.floor(msec / 1000 / 60);
						msec -= mm * 1000 * 60;
						if(dd != 0){$scope.lastMove = dd +" days ago";}
						else if(hh != 0){$scope.lastMove = hh+" hours ago";}
						else if(mm != 0){$scope.lastMove = mm+" minutes ago";}else{$scope.lastMove = "A minutes ago";}
						
						//console.log('userProfileData '+JSON.stringify(response));
					},function(err){

					}
				);
})
.controller('settingsCtrl', function($scope, $state, $awordedFactory, $rootScope,$localStorage) {
	$scope.loadboard=function(){
		if(response.facebook_id === undefined){
			$scope.imageSrc = "";
			$scope.imageFlag = false;
		}else{
			if(response.fb_show_picture!=false){
				$scope.imageSrc = "http://graph.facebook.com/"+response.facebook_id+"/picture" ;
				$scope.imageFlag = true;
			}else{
				$scope.imageSrc = "";
				$scope.imageFlag = false;
			}
		}
	}
	$scope.updateUserName=function(name){
		var data= {"username":name};
		$awordedFactory.getPostReqData('PUT', baseUrl+'/users/'+$rootScope.loginUserData.id, data, $rootScope.postHeaders)
					.then(function (response){
						$rootScope.loginUserData.username=name;
						$scope.newProfileName="";
						//console.log('userProfileData '+JSON.stringify(response));
					},function(err){
						//console.log('error'+JSON.stringify(err));
					}
				);
	}
	$scope.signout = function(){
		$rootScope.postHeaders=[];
		$rootScope.getHeaders = [];
		$rootScope.profileData = [];
		$rootScope.gameStatisticsData = [];
		$rootScope.loginUserData = [];
		$rootScope.opponentId = "";
		$rootScope.type = "";
		$rootScope.language = "";
		delete $localStorage.email;
		delete $localStorage.password;
		$state.go('home');
	}
})
.controller('dashboardCtrl', function($scope, $state, $awordedFactory, $rootScope,$localStorage, $interval,ngAudio) {
	
	/******************** To display the chat reply ******************************/
	var chatTimer = $interval( function(){ $scope.chatFunction(); }, 10000);
	$scope.chatFunction =function(){
		$awordedFactory.getchatHeaders().then(function (response){
				if(response['count']==true){
					$('.chatLink').addClass('chaton');
					$('.chatLink').html(response['numberofchat']);
				}else{
					$('.chatLink').removeClass('chaton');
					$('.chatLink').html("");
				}
		},function(err){
			//console.log('error'+JSON.stringify(err));
		});
	}
	
	$scope.chatOption = function(){
		$state.go('menu.chat');
	}
	var listTimer = $interval( function(){ $scope.reloadData(); }, 30000);
	$scope.reloadData = function(){
		var data ={"smart_ready":"true","app_config_version":"0"};
		$awordedFactory.getReqData('GET', baseUrl+'/users/'+$rootScope.loginUserData.id+'/games', data, $rootScope.getHeaders)
			.then(function (response){
					$rootScope.profileData=response;
					$scope.loadData();
				},function(err){
					//console.log('error'+JSON.stringify(err));
				}
			);
	}
	
	$scope.loadData = function(){
		$scope.chatFunction();
		var jsobject=[], ended=[],frndAppro=[], penfirstMove=[],yourAppro=[],turnkey=[],myturn=[],oppturn=[];
		$scope.endFlag=false;
		$scope.myturnFlag=false;
		$scope.frndApproFlag=false;
		$scope.oppturnFlag=false;

		jsobject = $rootScope.profileData.list;
		//$scope.chatFunction();
		var obj;
		$scope.listdata = [];
		var temp ={}, values,imageSrc,lastMoved, opponentId, username,imageFlag;
		for(obj=0;obj<jsobject.length;obj++){
		
			if(jsobject[obj].opponent.id!=0){
				opponentId = jsobject[obj].opponent.id;
			}else{
				opponentId = 0;
			}
			if(jsobject[obj].opponent.facebook_id === undefined){
				imageSrc = "images/default-user-picture.png" ;
				imageFlag = false;
			}else{
				if(jsobject[obj].opponent.fb_show_picture!=false){
					imageSrc = "http://graph.facebook.com/"+jsobject[obj].opponent.facebook_id+"/picture" ;
					imageFlag = true;
				}else{
					imageSrc = "images/default-user-picture.png" ;
					imageFlag = false;
				}
			}
			if(jsobject[obj].opponent.username == ""){
				username = "Random Opponent";
			}else{
				if(jsobject[obj].opponent.facebook_id === undefined){
					username = jsobject[obj].opponent.username;
				}else{
					if(jsobject[obj].opponent.fb_show_name!=false){
						username = jsobject[obj].opponent.facebook_name;
					}else{
						username = jsobject[obj].opponent.username;
					}
				}
			}
			
			if(jsobject[obj].turns_played == 0 && jsobject[obj].my_turn == false ){
				lastMoved = "Waiting for Opponent Move";
			}else if(jsobject[obj].turns_played == 0 && jsobject[obj].my_turn == true ){
				lastMoved = "Make the first Move";
			}else{
				lastMoved = jsobject[obj].last_turn.words;
			}
			
			values = {game_status: jsobject[obj].game_status,id:jsobject[obj].id,imageSrc:imageSrc,lastMoved:lastMoved, my_turn: jsobject[obj].my_turn, opponentId: opponentId, remaining_tiles: jsobject[obj].remaining_tiles, username:username, imgFlag: imageFlag};
			$scope.listdata.push(values);
		}
		//console.log("listdata");
		//console.log($scope.listdata);
		
		
		ended = $awordedFactory.getJSONObjects(jsobject,'game_status','ENDED');
		frndAppro = $awordedFactory.getJSONObjects(jsobject,'game_status','PENDING_FRIENDS_APPROVAL');
		penfirstMove = $awordedFactory.getJSONObjects(jsobject,'game_status','PENDING_FIRST_MOVE');
		yourAppro = $awordedFactory.getJSONObjects(jsobject,'game_status','PENDING_MY_APPROVAL');
		turnkey = $awordedFactory.getJSONObjects(jsobject,'game_status','ACTIVE');
		oppturn = $awordedFactory.getJSONObjects(turnkey,'my_turn',false);
		myturn = $awordedFactory.getJSONObjects(turnkey,'my_turn',true);
		
		if(ended.length!=0){$scope.endFlag=true;}else{$scope.endFlag=false;}
		if(myturn.length!=0 || penfirstMove.length!=0 || yourAppro.length!=0 ){$scope.myturnFlag=true;}else{$scope.myturnFlag=false;}
		if(frndAppro.length!=0){$scope.frndApproFlag=true;}else{$scope.frndApproFlag=false;}
		if(oppturn.length!=0){$scope.oppturnFlag=true;}else{$scope.oppturnFlag=false;}
	}
	$scope.doRefresh=function(){
		var data ={"smart_ready":"true","app_config_version":"0"};
		$awordedFactory.getReqData('GET', baseUrl+'/users/'+$rootScope.loginUserData.id+'/games', data, $rootScope.getHeaders)
			.then(function (response){
					$rootScope.profileData=response;
					$scope.loadData();
					$state.transitionTo('menu.dashboard',"", {reload: true});
				},function(err){
					//console.log('error'+JSON.stringify(err));
				}
			);
		$scope.$broadcast('scroll.refreshComplete');
	}
	$scope.moveToShopPage=function(){
		$state.go('menu.shop');
	};
	$scope.showNewGamePopup=function(){
		$state.go('menu.newgame');
	}
	$scope.perticularGameLoading=function(gameId){
		if(gameId !=null){
			//$scope.sound = ngAudio.play("sounds/BottleOpen.mp3");
			var data ="";
			$awordedFactory.getReqData('GET', baseUrl+'/users/'+$rootScope.loginUserData.id+'/games/'+gameId, data, $rootScope.getHeaders)
					.then(function (response){
						$rootScope.gameStatisticsData=response;
						//console.log('gameStatisticsData '+JSON.stringify(response));
						$state.go('menu.board');
					},function(err){
						//console.log('error'+JSON.stringify(err));
					}
				);
		}
	}
})
.controller('newGameCtrl', function($scope, $state, $awordedFactory, $rootScope) {
	$rootScope.lang = "en"
	$scope.selectLang=function(lang){
		$(".marker").removeClass("selectimg");
		$("#"+lang).addClass("selectimg");
		$rootScope.lang = lang;
	}
	
	$scope.loadOptions=function(){
		$scope.newGameType="FAST";
		$scope.gameModeFlag =true;
		document.getElementById("fastGame").checked =true;
	}
	$scope.gameTypeClassic = function(){
		$scope.gameModeFlag =false;
		document.getElementById("classicGame").checked =true;
        $scope.newGameType="CLASSIC";
    }
	$scope.gameTypeFast = function(){
		$scope.gameModeFlag =true;
		document.getElementById("fastGame").checked =true;
		$scope.newGameType="FAST";
	}
	$scope.startNewGame = function(){
		var data= {"language":$rootScope.lang,"smart_ready":true,"type":$scope.newGameType};
		$awordedFactory.getPostReqData('POST', baseUrl+'/users/'+$rootScope.loginUserData.id+'/games', data, $rootScope.postHeaders)
			.then(function (response){
				$rootScope.gameStatisticsData=response;
				$state.go('menu.board');
			},function(err){
				//console.log('error'+JSON.stringify(err));
				alert("Notification: "+err.message);
			}
		);
    }
})
.controller('gameBoardCtrl', function($state, $scope, $rootScope, $sce, $awordedFactory,$interval,$timeout) {
	
	$scope.wildid = 10;
	var animateArr = [];
	var filetereddropped = [], wildLetter;
    var filetereddraggable = [];
	var racklist = [];
	$scope.my_turn = false;
	var recallflag =false;
	$scope.wildCardFlag =false;
	$scope.GameEnded = false;
  	$scope.wildid = "";
	$scope.tileBagAlertBox = false;
	$scope.SwapPopup = false;
	$scope.showGamesList = false;
	var specId;
	var tileplaceArr = [], fileteredTileplace = [], placedtiles=[],fileteredplacedTile=[],fileteredbroadtiles=[];
	var nearBy = {};
	var vervalue=[], horvalue=[];
	var validateHtml ="";
	var divHtml = "";
	
	
	/*********************Back button functionality to clear the timer*****************************/
	$(".button-clear").click(function(){
		$interval.cancel(reloadtimer);
		$interval.cancel(timer);
	});
	
	/****************Wild Card letter selector *******************************/
	$scope.wildCardletter = function(let){
		$scope.validateHtml = $sce.trustAsHtml(""); 
		var pointArr = $scope.pointsArr;
		var points = pointArr[let];
		var value = let.toUpperCase(); 
		$scope.wildLetter = value;
		$("#"+specId).children( ".letterTileContainer" ).text(value);
		//$("#"+specId).children( ".points" ).text(points);
		var lIndex = $scope.boardTileLetter.indexOf("*");

		for(var c = 0 ; c < placedtiles.length; c++){
			if(placedtiles[c].letter=="*" || placedtiles[c].tileid == specId){
				placedtiles[c].letter = "-"+value;
				$scope.boardTileLetter[lIndex]=value;		
			}
			$scope.placemarker(c);
		}
		
		var validationFlag = $rootScope.gameStatisticsData.extras[1].used
		//var validationFlag = true;
		if(validationFlag == true){
			if($scope.checkadjacentTile($scope.tilePlace)==true)
			{
				$timeout( function(){
					$("#validHtml").html(divHtml);
					//$scope.validateHtml = $sce.trustAsHtml(divHtml); 
				}, 1000);
				$("#validHtml").html(divHtml);
				//$scope.validateHtml = $sce.trustAsHtml(divHtml); 
			}
		}
		$scope.wildCardFlag = false;
		//console.log(placedtiles);
	}
	
	/***************Init game board width height and tilewidth**********************/
	$scope.initgameboard = function(){
		var imageHeight,imageWidth;
		imageWidth = $(".img-thumbnail").width();
		imageHeight = $(".img-thumbnail").height();
		var tilewidth = imageWidth/15;
		return tilewidth;
	}
	
	//Shuffle the letters
	$('.shuffle').click(function(){
		$('.rackContainer').mixItUp();
	})
	

	$( ".tile" ).draggable({
		revert: "invalid",
		start: function(event, ui){
			$scope.originalPosition = ui.originalPosition;			
		}
	}).on('mousedown', function(e) {
		$( this ).addClass("held");
	}).on('mouseup', function(e) {
		$( this ).removeClass("held");
	});
	$(".tileHolder").droppable({
		drop: function(event, ui){
			$("#validHtml").html("");
			var divHTML="";
			var id = ui.draggable.attr("id");
			var index = $("#"+id).children( ".index" ).text();
			fileteredTileplace = tileplaceArr;
			fileteredTileplace = fileteredTileplace.filter(function(e1){
				return e1.tileid !== id;
			})
			tileplaceArr = fileteredTileplace;
			$scope.droppedObjects = fileteredTileplace;
			
			fileteredplacedTile = placedtiles;
			fileteredplacedTile = fileteredplacedTile.filter(function(e1){
				return e1.tileid !== id;
			})
			placedtiles = fileteredplacedTile;			
			
			var tilePlace = $scope.tilesPlaceArr[index];			
			var letterPos;
			fileteredbroadtiles = $scope.boardTiles;			
			fileteredbroadtiles = fileteredbroadtiles.filter(function(e1){
				if(e1 !== tilePlace){ letterPos = fileteredbroadtiles.indexOf(tilePlace);}
				return e1 !== tilePlace;
			})
			$scope.boardTiles = fileteredbroadtiles;			
			$scope.tilesPlaceArr[index]="";
			
			var bLetter = $scope.boardTileLetter;
			if(letterPos != -1){
				bLetter.splice(letterPos, 1);
				$scope.boardTileLetter = bLetter;
			}
			var value = "L"+index;
			$scope.combinedHtml[value] = "";
			letterArray[index]=undefined;
			
			var aw, pTiles="";
			for(var p = 0 ; p< placedtiles.length; p++){
				divHTML +=$scope.placemarker(p);
				aw = $scope.checkadjacentTile(placedtiles[p].tilePosition);
				if(aw == false){
					break;
				}
				if(pTiles == "" || pTiles != true){
					pTiles = $scope.checkwithplayedtiles(placedtiles[p].tilePosition);
				}
			}
			if(index == $scope.wildid){
				$("#"+id).children( ".letterTileContainer" ).text("*");
				$("#"+id).children( ".points" ).text("");
			}
			
			$("#"+id).removeAttr("style");
			$("#"+id).css({"top":"5px", "position":"relative"});
			$("#"+id).children( ".letterTileContainer" ).removeAttr("style");
			$("#"+id).children( ".points" ).removeAttr("style");
			$("#"+id).children( ".points" ).css({"float":"right"});
		
			
			var rflag = false;
			var tileConarray = ["tileContainer0","tileContainer1","tileContainer2","tileContainer3","tileContainer4","tileContainer5","tileContainer6"];
			for(var p = 0; p < tileplaceArr.length; p++){
				for(var k =0 ; k < tileConarray.length; k++){
					if(tileConarray[k] == tileplaceArr[p].tileid){
					  rflag =  true;
					  break;
					}else{ rflag =  false;}
				}
			}
			
			recallflag = rflag;
			var validationFlag = $rootScope.gameStatisticsData.extras[1].used;
			//var validationFlag = true;
			if(validationFlag == true){
				//console.log("pTiles aw");
				//console.log(pTiles+" "+aw);
				if(pTiles == true && aw != false){	
					$timeout( function(){
						for(key in tileplaceArr){
							$("#"+tileplaceArr[key].tileid).css({'border':'none'});					
						}
						$("#validHtml").html(divHtml);
						//$scope.validateHtml = $sce.trustAsHtml(divHtml); 
					}, 1000);
				}else{
					divHtml = "";
					$("#validHtml").html(divHtml);
					//$scope.validateHtml = $sce.trustAsHtml(divHtml);
					for(key in tileplaceArr){
						$("#"+tileplaceArr[key].tileid).css({'border':'2px solid red'});					
					}
				}
			}
			
		}
	});
	
	/****************Function to validate the Words on drop of game board****************************/
	
	/*******************To check the tile position already exist or not************************************/
	$scope.boardTiles=[];
	$scope.boardTileLetter=[];
	var letterArray = [];
	$scope.checkBoard= function(tilePlace, letterindex){
		var tileAlreadyExist;
		var lKey = letterindex;
		var bTiles = $scope.boardTiles;
		var bLetter = $scope.boardTileLetter;
		var divid=parseInt(letterindex)-1;
		var Eletter = $("#tileContainer"+divid).children( ".letterTileContainer" ).text(); 
		var index ="";
		
		if(bTiles.indexOf(tilePlace) == -1 || bTiles.length == 0){
			tileAlreadyExist = false;
			if(letterArray.length == 0 || letterArray[lKey] == undefined ){
				letterArray[lKey] = tilePlace;
			}
			
			bTiles = bTiles.filter(function(e1){
				if(e1 !== letterArray[lKey]){ index = bTiles.indexOf(letterArray[lKey]);}
				return e1 !== letterArray[lKey];
			});
			$scope.boardTiles = bTiles;

			var bindex = $scope.boardTiles.length;
			$scope.boardTiles[bindex] = tilePlace;
			
			if(index != -1){
				bLetter.splice(index, 1);
				$scope.boardTileLetter = bLetter;
			}
			$scope.boardTileLetter[bindex]=Eletter;
			letterArray[lKey] = tilePlace;
			
		}else{
			tileAlreadyExist = true;
		}
		return tileAlreadyExist;
	}
	
	/****************** To get the vertical word tile position ***************************/
	$scope.isvertical = function(pos, op){
		var pushPos = pos+(op*15);
		if($scope.boardTiles.indexOf(pushPos) != -1){
			vervalue.push(pushPos);
			$scope.isvertical(pushPos, op);
		}
		return vervalue;
	}
	/****************** To get the horizontal word tile position ***************************/
	
	$scope.isHorizontal = function(pos, op){
		var pushPos =pos+(op*1);
		if($scope.boardTiles.indexOf(pushPos) != -1){
			horvalue.push(pushPos);
			$scope.isHorizontal(pushPos, op);
		}
		return horvalue;
	}
	/****************** To calculate the top and left ***************************/
	$scope.calculateTopLeft = function(x){
		var xvalue =  x;
		var yvalue = 15;
		var top = Math.floor(xvalue/yvalue);
		var left = Math.floor(xvalue%yvalue);
		top = top * $scope.tilesize;
		left = left * $scope.tilesize;
		return top+":::"+left;
	}
	
	/****************** To check if the adjacent tile present or not ***************************/	
	/******************Start -- Function to check the tiles are in a line ***************************/
	$scope.playedTiles=[];
	$scope.checkwithplayedtiles = function(tileplace){
		var checkTile, tflag;
		dir = [1, -1, 15, -15];
		for(var s = 0; s < dir.length ; s++){
			checkTile = tileplace - dir[s];
			if($scope.playedTiles.indexOf(checkTile)!=-1 || $scope.playedTiles.length == 0){
				tflag = true;
				break;
			}
		}
		return tflag;
	}
	$scope.checkadjacentTile = function(tilePlace){
		//console.log("Hello check adajcent tiles function");
		var dir =[], checkTile, tileflag, len=0, letContain=0;
		var uniqueArr=[];		
		if(placedtiles.length == 1){
			tileflag = $scope.checkwithplayedtiles(placedtiles[0].tilePosition);
		}else{
			var isVer = $scope.callisVerticalWord(tilePlace);
			if(isVer=="Horizontal"){
				uniqueArr = $scope.horizontalWord(tilePlace);
				dir =[1, -1];
			}else if(isVer=="vertical"){
				uniqueArr = $scope.verticalWord(tilePlace);				
				dir =[15, -15];
			}else if(isVer=="notInline"){
				dir =[];
				tileflag = false;
			}
			for (var i=0; i < letterArray.length; i++) {
				if ( letterArray[i] != undefined ) {
					letContain++;
					for (var j=0; j < uniqueArr.length; j++) {
						if ( letterArray[i] == uniqueArr[j] ) {
							len++;
						}
					}
				}
			}
			if(letContain == len){
				for(var s =0; s < dir.length; s++){
					checkTile = tilePlace - dir[s];
					if($scope.boardTiles.indexOf(checkTile)==-1){
						tileflag = false;
					}else{
						tileflag = true;
						break;
					}
				}
			}else{
				tileflag = false;
			}
		}
		return tileflag;
	}	
	
	$scope.checkDirection = function(){
		var checktop=0, checkleft=0;
		if(placedtiles.length > 1){
			var tile1 = $scope.calculateTopLeft(placedtiles[0].tilePosition);
			var tile2 = $scope.calculateTopLeft(placedtiles[1].tilePosition);
			tile1 = tile1.split(':::');
			tile2 = tile2.split(':::');
			if(tile1[0] == tile2[0]){
				checktop = tile1[0];
			}else if(tile1[1] == tile2[1]){
				checkleft = tile1[1];
			}
		}
		return checktop+":::"+checkleft;
	}
	
	$scope.callisVerticalWord = function(value){
		var checkvalue = $scope.checkDirection(), result;
		var tile3 = $scope.calculateTopLeft(value);
		tile3 = tile3.split(':::');
		checkvalue = checkvalue.split(':::');
		if(tile3[0] == checkvalue[0]){
			result = "Horizontal";
		}else if(tile3[1] == checkvalue[1]){
			result = "vertical";
		}else{
			result = "notInline";
		}
		return result;
	}
	/******************End -- Function to check the tiles are in a line ***************************/
	
	/******************Function to find the nearby words for the particular tile ***************************/
	$scope.horizontalWord =function(value){
		var uniquehorizontal=[];
		var horizontalleft = $scope.isHorizontal(value, -1);//left
		var horizontalright = $scope.isHorizontal(value, 1);//right
		
		var thorizontal = horizontalleft.concat(horizontalright); 
		thorizontal.push(value);
		var horizontalSorted = thorizontal.sort(function(a, b) {
			return a- b 
		});
		var j;
		for(j=0; j< horizontalSorted.length; j++){
			if(uniquehorizontal.indexOf(horizontalSorted[j]) === -1) uniquehorizontal.push(horizontalSorted[j]);
		}
		return uniquehorizontal;
	}
	
	$scope.verticalWord =function (value){
		var uniqueVertical=[];
		var Verticaltop = $scope.isvertical(value, -1);//top
		var Verticalbottom = $scope.isvertical(value, 1);//bottom
		
		var tVertical = Verticaltop.concat(Verticalbottom); 
		tVertical.push(value);
		var verticalSorted = tVertical.sort(function(a, b) {
			return a- b 
		});
		var i;
		for(i=0; i< verticalSorted.length; i++){
			if(uniqueVertical.indexOf(verticalSorted[i]) === -1) uniqueVertical.push(verticalSorted[i]);
		}
		return uniqueVertical;
	}
	
	$scope.nearByWordFun = function(value){
		var nearByWord = [];
		var uniqueVertical=[],uniquehorizontal=[];
		
		uniqueVertical = $scope.verticalWord(value);
		uniquehorizontal = $scope.horizontalWord(value);
		var pushArrObj = {
			'vertical' : uniqueVertical,
			'horizontal' : uniquehorizontal
		};
		nearByWord[0] = pushArrObj;
		return nearByWord;
	}
	
	/******************Function to vlaidate the word on place of the tile ***************************/
	$scope.combinedHtml=["","","","","","","",""];
	$scope.placemarker =function(p){
				vervalue=[]; horvalue=[];
				var validateHtml = "";
				var divInd = placedtiles[p].divindex;
				var value = "L"+divInd;
				nearBy[value] = $scope.nearByWordFun(placedtiles[p].tilePosition);
				var n = nearBy[value];	
				var horizontalWord = "", verticalWord="";
				for(var h = 0 ; h < n[0].horizontal.length; h++){
					var tilePos =  n[0].horizontal[h];
					var pindex = $scope.boardTiles.indexOf(tilePos);
					horizontalWord +=$scope.boardTileLetter[pindex];				
				}		
							
				for(var v = 0 ; v < n[0].vertical.length; v++){
					var tilePos =  n[0].vertical[v];
					var pindex =$scope.boardTiles.indexOf(tilePos);
					verticalWord +=$scope.boardTileLetter[pindex];
				}
				
				if(n[0].horizontal.length > 1){
					var dicLanguage = $rootScope.gameStatisticsData.id;
					var data = {"words":horizontalWord};
					$awordedFactory.getReqData('GET', baseUrl+'/dictionaries/'+$rootScope.language, data, $rootScope.getHeaders)
						.then(function (response){

							var topNleftArr=[];
							var topNleft = $scope.calculateTopLeft(n[0].horizontal[0]);
							topNleftArr = topNleft.split(':::');
							validatetop = parseInt(topNleftArr[0]);
							validateleft = parseInt(topNleftArr[1]);
						
							if(response.answer == true ){var color = "green";}else{var color = "red";}
							validateHtml += "<div id = \""+value+"_h\"class=\"\" style=\"top:"+(validatetop+$scope.tilesize*0.1)+"px; left:"+(validateleft+$scope.tilesize*0.05)+"px;\width:"+((n[0].horizontal.length*$scope.tilesize)+4)+"px;height:"+($scope.tilesize+5)+"px; border:3px solid "+color+"; position: absolute; margin:-3px; \"></div>";
						},function(err){
							//console.log('error'+JSON.stringify(err));
						}
					);						
				}
								
				if(n[0].vertical.length > 1){
					var dicLanguage = $rootScope.gameStatisticsData.id;
					var data = {"words":verticalWord};
					$awordedFactory.getReqData('GET', baseUrl+'/dictionaries/'+$rootScope.language, data, $rootScope.getHeaders)
						.then(function (response){
							
							var topNleftArrV=[];
							var topNleftV = $scope.calculateTopLeft(n[0].vertical[0]);
							topNleftArrV = topNleftV.split(':::');
							validatetop1 = parseInt(topNleftArrV[0]);
							validateleft1 = parseInt(topNleftArrV[1]);
							
							if(response.answer == true ){var color = "green";}else{var color = "red";}
							validateHtml += "<div id = \""+value+"_v\"class=\"\" style=\"top:"+(validatetop1+$scope.tilesize*0.1)+"px; left:"+(validateleft1+$scope.tilesize*0.05)+"px;\width:"+(($scope.tilesize)+4)+"px;height:"+((n[0].vertical.length*$scope.tilesize)+5)+"px; border:3px solid "+color+"; position: absolute; margin:-3px; \"></div>";
						},function(err){
						//	console.log('error'+JSON.stringify(err));
						}
					);
				} if(n[0].vertical.length == 1 && n[0].horizontal.length == 1 ){
					var topNleftArrV=[];
					var topNleftV = $scope.calculateTopLeft(n[0].vertical[0]);
					topNleftArrV = topNleftV.split(':::');
					validatetop1 = parseInt(topNleftArrV[0]);
					validateleft1 = parseInt(topNleftArrV[1]);
					
					validateHtml += "<div id = \""+value+"_h\"class=\"\" style=\"top:"+(validatetop1+$scope.tilesize*0.1)+"px; left:"+(validateleft1+$scope.tilesize*0.05)+"px;\width:"+($scope.tilesize+4)+"px;height:"+($scope.tilesize+5)+"px; border:3px solid red; position: absolute; margin:-3px; \"></div>";
				}
				var divHTML="";
				
				$timeout( function(){
					$scope.combinedHtml[value] = validateHtml ;
					for(var key in   $scope.combinedHtml)
					{divHTML = divHTML + $scope.combinedHtml[key];}
					divHtml = divHTML;
					return divHtml;
				}, 1000);
	}

	/************************************************************************************************/
	$scope.tilePlace;
	//$scope.combinedHtml=["","","","","","","",""];
	var validateHtml="";
	var zindex=0;
	$scope.tilesPlaceArr = ["","","","","","","",""];
	$(".img-thumbnail").droppable({
		accept: '.tile',
        drop: function(event, ui){
			$("#validHtml").html("");
			var divHTML="";
			var tilewidth = $scope.initgameboard();
			var id = ui.draggable.attr("id"),j;
			var p = $( "#"+id );
			var position = p.position();
			tileplaceArr = $scope.droppedObjects;
			
			/********** To get the top position.********/
			var top, ptop;
			imageHeight = $(".img-thumbnail").height();		
			var imgheight = -1 * (imageHeight);
			ptop = position.top;
			if(ptop > imgheight){
				offtop = imageHeight + ptop;
			}else{
				offtop = 0;
			}
			top = Math.round(offtop/tilewidth);
			top = 15 - top;
			if(top == 0){
				top = tilewidth;
			}else{
				top = top * tilewidth;
			}
			/*******************************************/
			
			/********** To get the left position.*******/
			var left, rleft, posleft,pleft;
			var tileflag=true;
			posleft = position.left;
			left = ui.position.left;
			posleft = posleft-left;
			pleft = Math.round(posleft/tilewidth);
			pleft = pleft*tilewidth;
			pleft = posleft - pleft;
			rleft = Math.round(left/tilewidth);
			rleft = rleft * tilewidth;
			left = rleft - pleft;
			/*******************************************/
			
			/********** To get the tile position*******/
			var placetileflag =false;
			var imageOffset = $(".img-thumbnail").offset();
			var tiletop = imageHeight - top;
			var tileleft = posleft+left;
			if(tileleft < 0 ){tileleft = 0;}
			tiletop =  Math.round(tiletop/tilewidth);
			tileleft =  Math.round(tileleft/tilewidth);
			var tilePlace = (tiletop * 15)+tileleft;	
			
			$scope.tilePlace = tilePlace;

			letter = $("#"+id).children( ".letterTileContainer" ).text();
			//if(letter == "*"){letter = $scope.wildLetter;}
			var index = $("#"+id).children( ".index" ).text();
			var values ={tileid: id, tilePosition: tilePlace, letter:letter, divindex:index};

			$scope.tilesPlaceArr[index]= tilePlace;// placed tiles tileposition array
			
			//to Check if tile already placed in the position or not
			var originalPosition = $scope.originalPosition
			for(var i=0; i<tileplaceArr.length; i++){
				if(tileplaceArr[i].tilePosition == tilePlace){
					placetileflag = true;
					tileFlag =true;
					break;
				}else{
					tileFlag = false;
				}
			}
			
			var index = $("#"+id).children( ".index" ).text();
			var tilePlacedExist  = $scope.checkBoard(tilePlace, index);
			if(tilePlacedExist == false){
				placetileflag = true;
				$("#"+id).css({ "width": tilewidth+"px","height": tilewidth+"px","top":"-"+top+"px", "left":+left+"px"});
				$("#"+id).children( ".letterTileContainer" ).css({ "font-size": tilewidth*0.73+"px","line-height": tilewidth*0.8284+"px" });
				$("#"+id).children( ".points" ).css({"font-size": tilewidth*0.48+"px","width": tilewidth*0.93+"px", "margin-top":"-"+tilewidth*0.85+"px", "margin-right":"2px" });
			}else{
				placetileflag = false;
				$("#"+id).css({"top":originalPosition.top+"px", "left":+originalPosition.left+"px"});
			}
			
			if(placetileflag == true){
				fileteredTileplace = tileplaceArr;
				fileteredTileplace = fileteredTileplace.filter(function(e1){
					return e1.tileid !== id;
				})
				tileplaceArr = fileteredTileplace;
				
				fileteredplacedTile = placedtiles;
				fileteredplacedTile = fileteredplacedTile.filter(function(e1){
					return e1.tileid !== id;
				})
				placedtiles = fileteredplacedTile;
				tileplaceArr.push(values);
				placedtiles.push(values);
			}
					
			//Recall Functionality 
			var rflag = false;
			var tileConarray = ["tileContainer0","tileContainer1","tileContainer2","tileContainer3","tileContainer4","tileContainer5","tileContainer6"];
			for(var p = 0; p < placedtiles.length; p++){
				for(var k =0 ; k < tileConarray.length; k++){
					if(tileConarray[k] == placedtiles[p].tileid){
					  rflag =  true;
					  break;
					}else{ rflag =  false;}
				}
			}
			recallflag = rflag;
			$scope.droppedObjects = tileplaceArr;
			
			/*******************************************/
			
			/************** To call Validate Function *****************/				
			var validationFlag = $rootScope.gameStatisticsData.extras[1].used
			//var validationFlag = true;
			if(validationFlag == true){
				var aw, pTiles="";
				//console.log('placedtiles');
				//console.log(placedtiles);
				for(var p = 0 ; p < placedtiles.length; p++){
					$scope.placemarker(p);
					if(pTiles == "" || pTiles != true){
						pTiles = $scope.checkwithplayedtiles(placedtiles[p].tilePosition);
					}
				}
				aw = $scope.checkadjacentTile(tilePlace);
				//console.log(pTiles+" "+aw)
				//console.log('$scope.boardTiles');
				//console.log($scope.boardTiles);
				if(pTiles == true && aw == true){	
					//console.log("Hello");
					$timeout( function(){
						for(key in tileplaceArr){
							$("#"+tileplaceArr[key].tileid).css({'border':'none'});					
						}
						$("#validHtml").html(divHtml);
						//$scope.validateHtml = $sce.trustAsHtml(divHtml); 
					}, 1000);
				}else{
					//console.log("bye");
					divHtml = "";
					//$scope.combinedHtml[index] = "";
					$("#validHtml").html(divHtml);
					//$scope.validateHtml = $sce.trustAsHtml(divHtml);
					for(key in tileplaceArr){
						$("#"+tileplaceArr[key].tileid).css({'border':'2px solid red'});					
					}
				}	
			}
			/*********************************************************/
			//var index = $("#"+id).children( ".index" ).text();
			if (letter == "*" || $scope.wildid == index) {
					$scope.wildid = index;
					specId = id;
					$scope.wildCardFlag = true;
			}
		}
	});
	
	// Sort json array object
	$scope.sort_by = function(field, reverse, primer){
	   var key = primer ? 
		   function(x) {return primer(x[field])} : 
		   function(x) {return x[field]};

	   reverse = !reverse ? 1 : -1;

	   return function (a, b) {
		   return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
		 } 
	}
	
	
	// to reload the board
	var MyTurn="bFlag";
	var reloadtimer = $interval( function(){ $scope.reloadboard(); }, 10000);
	$scope.reloadboard = function(){
		
			var gameId = $rootScope.gameStatisticsData.id;
			var data ="";
			$awordedFactory.getReqData('GET', baseUrl+'/users/'+$rootScope.loginUserData.id+'/games/'+gameId, data, $rootScope.getHeaders)
					.then(function (response){
						$rootScope.gameStatisticsData=response;
						if(MyTurn== "bFlag" || MyTurn!=$rootScope.gameStatisticsData.my_turn){
							MyTurn = $rootScope.gameStatisticsData.my_turn;
							$scope.loadboard();
						}					
					},function(err){
						//console.log('error'+JSON.stringify(err));
					}
				);
	}
	
	

	// timer functionality for the display time
	var timeFlag = -1;
	var timer = $interval( function(){ $scope.reTimer(); }, 1000);
	$scope.reTimer = function(){
		
		//console.log($scope.rTime);
		if(timeFlag < $scope.timeSec){
			//console.log("if "+timeFlag +" : "+ $scope.timeSec);
			var minutes = Math.floor($scope.rTime / 60); // 7
			var seconds = Math.round($scope.rTime % 60); // 30
			var mins =  ("0" + minutes).slice(-2);
			var sec = ("0" + seconds).slice(-2);
			$scope.remainingTime = mins +" : "+sec;
			$scope.rTime--;
			timeFlag++;
		}else{
			$interval.cancel(timer);
			//console.log("else "+timeFlag +" : "+ timeSec);
			$scope.reloadboard();
		}
	}
	
	//To load the board
	
	$scope.droppedObjects=[];
	$scope.loadboard = function(){
		gameStatisticsData = $rootScope.gameStatisticsData;
		/**to initialize the shuffle **/
		$('.rackContainer').mixItUp();
		/*****************************/
		if(gameStatisticsData.board_tiles != ""){		
			var boarTil, boardTil=[], boardTileLetter=[],boardTilePosition=[],boardTileDet, boardTile;
			boarTil = $rootScope.gameStatisticsData.board_tiles;
			boardTil = boarTil.split(",");
			for(var p = 0; p< boardTil.length; p++){
				boardTileDet = boardTil[p];
				boardTile = boardTileDet.split("|");
				boardTileLetter.push(boardTile[0]);
				boardTilePosition.push(parseInt(boardTile[1]));
			}
			$scope.playedTiles = boardTilePosition; //previously played tile position
			$scope.boardTiles = boardTilePosition;
			$scope.boardTileLetter = boardTileLetter;
		}
		
		gameStatisticsData = $rootScope.gameStatisticsData;
		$rootScope.type = gameStatisticsData.type;
		$rootScope.language = gameStatisticsData.language;
		
		var resp = $scope.initgameboard();
		$scope.tilesize = resp;
				
		if(gameStatisticsData.game_status == "ENDED"){
			$scope.GameEnded = true;
			$scope.gameExpiry =false;
//new added start		$
			$scope.tileBagPopUp =false;
			$scope.tileBagAlertBox =false;
			$scope.moreScreen = false;
			$scope.SwapPopup=false;
			$scope.validateAlertBox = false;
			$scope.dictionaryAlertBox = false;
			$scope.chatScreen= false;//$
//new added end		$
			
			if(gameStatisticsData.win == true){
				$scope.gameResult = true;
			}else{
				$scope.gameResult = false;
			}
		}else{
			
			$scope.GameEnded = false;
			$scope.my_score= gameStatisticsData.my_score;
			
			if(gameStatisticsData.remaining_time === undefined ){}else{
				if(gameStatisticsData.remaining_time != 0){
					$scope.rTime = $rootScope.gameStatisticsData.remaining_time - 2;
					$scope.timeSec = $scope.rTime;
					$scope.reTimer();
				}else{
					$scope.GameEnded=true;
					$scope.gameExpiry =true;
					$scope.tileBagPopUp =false;//$
					$scope.tileBagAlertBox =false;
					$scope.moreScreen = false;
					$scope.SwapPopup=false;
					$scope.validateAlertBox = false;
					$scope.dictionaryAlertBox = false;//$
				}
			}			
			
			if(gameStatisticsData.opponent.username == ""){
				$scope.opponentUsername = "Random Opponent";
				$scope.opponent_score= "";
			}else{
				$scope.opponent_score= gameStatisticsData.opponent_score;
				if(gameStatisticsData.opponent.facebook_id === undefined){
					$scope.opponentUsername = gameStatisticsData.opponent.username;
				}else{
					if(gameStatisticsData.opponent.fb_show_name!=false){
						$scope.opponentUsername = gameStatisticsData.opponent.facebook_name;
					}else{
						$scope.opponentUsername = gameStatisticsData.opponent.username;
					}
				}
			}
			
			$scope.remaining_tiles= gameStatisticsData.remaining_tiles;
			
			var racktiles = gameStatisticsData.my_rack_tiles;
			racklist = racktiles.split(',');
			var letters = gameStatisticsData.lang_distribution;
			letters = letters.split(',');
			var lettersArr = [];
			for(var i=0;i<letters.length; i++){
				let = letters[i].split(":");
				if(let[0]=="-"){let[0] = "*";}
				lettersArr[let[0]] = let[1];
			}
			$scope.my_turn= gameStatisticsData.my_turn ;
			$scope.pointsArr = lettersArr;
			var points, tile, lett, values,draggable=[];
			for(var i=0;i<racklist.length;i++){
				lett = racklist[i];
				if(racklist[i]=='-'){
					if($scope.wildCardUsed != true){
						lett ='*';
					}else{
						lett = $scope.wildCardNewLetter ;
					}
				}
				tile = lett.toLowerCase();
				points = lettersArr[tile];
				values = {id:i,name: lett, points:points};
				draggable.push(values);
			}
			var tileLen =  7 - draggable.length;
			for(var w =0 ; w < draggable.length ; w++ ){
				$("#tileContainer"+w+" .letterTileContainer").html(draggable[w].name);
				$("#tileContainer"+w+" .points").html(draggable[w].points);
			}
			for(var v =0 ; v < tileLen; v++){
				$("#tileContainer"+w).css({'display': 'none'});
				w++;
			}
			
			var playedTiles = [];
			playedTiles = gameStatisticsData.last_turn.played_tiles;
			if(playedTiles.length != 0){animateArr = playedTiles.split(",");}else{animateArr =[];}
			var b = 0, animateLetter=[],  sortLetter =[];
			var boardtiles = gameStatisticsData.board_tiles;
			if(boardtiles === undefined){}else{
				boardtiles = boardtiles.split(","); 
				var k=7, values, tile,tiledetails;
				if(boardtiles.length != 0){
					for(var s = 0; s < boardtiles.length; s++ ){
						tile = "tileContainer"+k;
						tiledetails = boardtiles[s];
						tiledetails = tiledetails.split("|");
						for(b = 0; b< animateArr.length; b++){
							if(animateArr[b] == tiledetails[1]){
								var val = tiledetails[0].split("");
								if(val[0] == "-" ){
									var aniArrValues = val[1]+"|"+ tiledetails[1];
									animateLetter.push(val[1]);
								}else{
									var aniArrValues = tiledetails[0]+"|"+ tiledetails[1];
									animateLetter.push(tiledetails[0]);
								}
								sortLetter.push(aniArrValues);
							}
						}
						values ={tileid: tile, tilePosition: tiledetails[1], letter: tiledetails[0]};
						k++;
						$scope.droppedObjects.push(values);
					}
				}
			}

			/***************** To animate the Points *************************/
				
			var lastWords = gameStatisticsData.last_turn.words;
			var foundFlag, foundletter, flag;
			lastWords = lastWords.split(",");
			if(animateLetter.length != 0){
				for(var i=0; i < lastWords.length; i++){
					flag = 0;
					for(var j=0; j< animateLetter.length; j++){
						var lWord = lastWords[i].toUpperCase();
						foundFlag = lWord.search(animateLetter[j]);
						if(foundFlag >= 0){
							foundletter = lastWords[i];
							flag++;
						}
					}
					if(animateLetter.length == flag) {break};
				}
				var directionArr = [-1, +1, -15, +15];
				var p,temp, diff;

				if(animateArr.length == 1){
					for(p=0; p< directionArr.length; p++){
						var q = parseInt(animateArr[0]) + parseInt(directionArr[p]);
						var foundanimate = boardTilePosition.indexOf(q);
						if(foundanimate >= 0){
							if(Math.abs(directionArr[p])==1){
								diff = 1; // horizontal 
							}else if(Math.abs(directionArr[p]) == 15){
								diff = -15; //vertical
							}
						}
					}
				}else{
					temp = parseInt(animateArr[1]) - parseInt(animateArr[0]);
					temp = Math.abs(temp) % 15;
					if(temp == 0){diff = -15; }
					else{diff = 1;} 
				}
				
				
				var letterIndex, splitLet;
				for(var z = 0;z<sortLetter.length; z++ ){
					var str = foundletter.toUpperCase();
					splitLet = sortLetter[z].split("|");
					if(str.split(splitLet[0]).length-1 >= 1){
						letterIndex = str.indexOf(splitLet[0]);
						letterPosition = splitLet[1];
						break;
					}
				}
				var firstAnimation;
				if(diff == -15){ 
					firstAnimation = 15 * letterIndex;
					addValue = letterPosition - firstAnimation;				
				}else{ 
					firstAnimation = 1 * letterIndex;
					addValue = letterPosition - firstAnimation;
				}

				if(animateArr.length !=0){
					var animatetopNleftArr=[];
					var animatetopNleft = $scope.calculateTopLeft(addValue);
					animatetopNleftArr = animatetopNleft.split(':::');
					pointtop = animatetopNleftArr[0];
					pointleft = animatetopNleftArr[1];
					
					pointtop1 = parseInt(pointtop)+($scope.tilesize * 0.7);
					pointleft1 = parseInt(pointleft) + ($scope.tilesize * 0.7);
					
					var pointsHtml = "<div class=\"points_view final scoreAnimation\" style=\"top:"+(pointtop1)+"px; left:"+(pointleft1)+"px;\"><div class=\"points\" >"+gameStatisticsData.last_turn.turn_points+"</div></div>";
					
					$scope.pointsHtml = $sce.trustAsHtml(pointsHtml);
					//console.log("isVertical "+diff);
					if(diff == -15){
						//Vertical Word						
						var animateTop = parseInt(pointtop) + ((foundletter.length - 1) * $scope.tilesize) + ($scope.tilesize * 0.7);
						$(".points_view").animate({top: animateTop}, 2000);
					}else{
						//Horizontal Word	
						var animateleft = parseInt(pointleft) +((foundletter.length - 1) * $scope.tilesize) + ($scope.tilesize * 0.7); 
						$(".points_view").animate({left: animateleft}, 2000);
					}
				}
			}
			/*****************************************/
			
			if(gameStatisticsData.turns_played != 0 ){
				opponentPlacedTiles="";
				for(var x=0;x<gameStatisticsData.board_tiles.length;x+=3+l){
					var top=0,left=0,tileplace=0;
					var l=0;
					var temptilePlace=0;
					var temptileplacetext="";
					for(l;l<3;l++){
						if(gameStatisticsData.board_tiles[x] == '-'){
							x++;
						}
						 if(gameStatisticsData.board_tiles[x+2+l] != ',' && (x+2+l) < gameStatisticsData.board_tiles.length){
						   temptileplacetext+=gameStatisticsData.board_tiles[x+2+l];
						 }else if(gameStatisticsData.board_tiles[x+2+l] == ',' && (x+2+l) < gameStatisticsData.board_tiles.length){
							break;
						}

					}

					temptilePlace =parseInt(temptileplacetext);
					$scope.xvalue = temptilePlace;
					
					$scope.yvalue = 15;
					var top_= Math.round($scope.xvalue/$scope.yvalue);
					var left_= $scope.xvalue%$scope.yvalue;
					// console.log("top "+(((top_)*$scope.tilesize)+($scope.tilesize*0.2))+" and left "+(((left_)*$scope.tilesize - ($scope.tilesize*0.1))+ $scope.tilesize));
					var temp_top = $scope.xvalue/$scope.yvalue;
					 if(top_-temp_top > 0){
							 top_=top_-1;
					}
					top = tileplace % 15;
					var lett = gameStatisticsData.board_tiles[x];
					lettlow = lett.toLowerCase();
					var points = lettersArr[lettlow];
					opponentPlacedTiles +="<div class=\"tile position\" style=\"top: "+(((top_)*$scope.tilesize)+$scope.tilesize*0.1)+"px; left: "+(((left_)*$scope.tilesize)+$scope.tilesize*0.05)+"px; display: block; z-index: 0; width:"+$scope.tilesize+"px \"><div class=\"index\" style=\"display:none\"></div><div id=\"letterTileContainer\" style=\"font-size:"+$scope.tilesize*0.75+"px;line-height:"+$scope.tilesize*0.85+"px\" class=\"letter letter_b\">"+lett+"</div><div class=\"points position\" style=\"font-size:"+$scope.tilesize*0.35+"px;width:"+$scope.tilesize*0.85+"px \" >"+points+"</div></div>";
					$scope.opponentPlacedTiles = $sce.trustAsHtml(opponentPlacedTiles);
					//$scope.tilePlacesArray.push(temptilePlace);
			   }
			}
		}		
		
		var lastWord = gameStatisticsData.last_turn.words;
		if(gameStatisticsData.game_status =="ENDED"){
			$scope.lastwords = "";
		}else if(lastWord != ""){
			$scope.lastwords = "Last Moved : '"+lastWord+"'";
		}else if(lastWord == "" && $scope.my_turn==true && gameStatisticsData.last_turn.type == "SWAP"){
			$scope.lastwords = " Last  turn : 'Swapped'";
		}else if(lastWord == "" && $scope.my_turn==false && gameStatisticsData.last_turn.type == "SWAP"){
			$scope.lastwords = " Last  turn : 'Swapped'";
		}else if(lastWord == "" && $scope.my_turn==true && gameStatisticsData.last_turn.type == "PASS"){
			$scope.lastwords = "Last  turn : 'Pass'";
		}else if(lastWord == "" && $scope.my_turn==false && gameStatisticsData.last_turn.type == "PASS"){
			$scope.lastwords = "Last  turn : 'Pass'";
		}else if(lastWord == "" && $scope.my_turn==false){
			$scope.lastwords = "Opponent has to make move.";
		}else{
			$scope.lastwords = "Last Moved : ''";
		}
		
	}

	
	// to play after placing the word
	$scope.play=function(){ 
		//$state.transitionTo($state.current,'',{reload: true});
		var divHtml;
		var turnsPlayed = $rootScope.gameStatisticsData.turns_played;
		$scope.loading_view = true;
		var gameId = $rootScope.gameStatisticsData.id;
		
		var played_tiles="",recentplayedtiles=[];
		recentplayedtiles = placedtiles;
		for(var i=0; i< recentplayedtiles.length; i++)
		{
			played_tiles += recentplayedtiles[i].letter+"|"+recentplayedtiles[i].tilePosition;
			if(i != placedtiles.length-1){ played_tiles +=",";}
		}
		var data = {"type":"PLACE_TILE","played_tiles":""+played_tiles,"turns_played":""+turnsPlayed};
		
		$awordedFactory.getPostReqData('POST', baseUrl+'/users/'+$rootScope.loginUserData.id+'/games/'+gameId+'/turns?country=en', data,$rootScope.getHeaders).then(function (response){
				for(var i =0; i<tileplaceArr.length;i++){
					temp = tileplaceArr[i];
					$("#"+temp.tileid).removeAttr("style");
					$("#"+temp.tileid).css({"top":"5px", "position":"relative"});
					
					$("#"+temp.tileid).addClass("recentlyAddedTileAnimation0");	//$
					
					$("#"+temp.tileid).children( ".letterTileContainer").removeAttr("style");
					$("#"+temp.tileid).children( ".points" ).removeAttr("style");
					$("#"+temp.tileid).children( ".points" ).css({"float":"right"});
				}
				var pointsHtml = "<div class=\"points_view final scoreAnimation\" style=\"top:0px; left:0px;\"><div class=\"points\" >0</div></div>";
				animateArr = placedtiles;
				placedtiles = [];
				$scope.droppedObjects = [];
				divHtml="";
				$("#validHtml").html(divHtml);
				$scope.reloadboard();
				
			},function(err){
				//console.log(err);
				if(err.code==100){
					alert('Error: '+err.message);
				}else{
					alert('Error: '+err.message);
				}
				
				
			}
		);
	}
	
	// to pass the my turn to opponent
	$scope.passMyturn=function(){
		var gameId = $rootScope.gameStatisticsData.id;
		var turnsPlayed = $rootScope.gameStatisticsData.turns_played;
		var data = {"type":"PASS","turns_played":""+turnsPlayed};
		$awordedFactory.getPostReqData('POST', baseUrl+'/users/'+$rootScope.loginUserData.id+'/games/'+gameId+'/turns?country=en', data,$rootScope.getHeaders).then(function (response){
						$scope.my_score = response.my_score;
						if($rootScope.gameStatisticsData.opponent.username != ""){
							$scope.opponentUsername= $rootScope.gameStatisticsData.opponent.username;
							$scope.opponent_score= $rootScope.gameStatisticsData.opponent_score;
						}else{
							$scope.opponentUsername="Random Opponent";
							$scope.opponent_score = "";
						}
						$scope.remaining_tiles= response.remaining_tiles;
						$rootScope.gameStatisticsData.my_turn = false;
						$rootScope.gameStatisticsData.remaining_time = 302 - 2;
						timeFlag = 0;

						
						$scope.reloadboard();
					},function(err){
						//console.log('error'+JSON.stringify(err));
					}
				);
	}
	
	// to swap the letters
	$scope.SwapPopup=false;
	$scope.showSwapPopupfun=function(){
		$scope.SwapPopup = true;
		
		$scope.tileBagPopUp =false;//$
		$scope.tileBagAlertBox =false;
		$scope.moreScreen = false;						
		$scope.gameExpiry = false;//$
		
	}
	$scope.putHideSwapPopup=function(){
		$scope.SwapPopup = false;
		var id, temp;
		for(var i=0;i<$scope.swapObjects.length;i++){
			temp = $scope.swapObjects[i];
			id = temp.id;
			$("#"+id).css({"top":"5px"});
		}
		$scope.swapObjects = [];
		
	}
	$scope.swapObjects = [];
	$scope.addtoSwapArr= function(obj){
		if($scope.SwapPopup == true){
			$("#"+obj).css({"top":"-125px","z-index":"101"});
			var letter = $("#"+obj).children( ".letterTileContainer").text();
			var values = {"id":obj, "name":letter};
			$scope.swapObjects.push(values);
		}
	}
	
	$scope.swap=function(){
		var gameId = $rootScope.gameStatisticsData.id;
		var turnsPlayed = $rootScope.gameStatisticsData.turns_played;
		var swappedLettersCollection="";
		var swappedLetters = $scope.swapObjects;
		for(var i=0;i<swappedLetters.length;i++)
		{
			swappedLettersCollection+=swappedLetters[i].name;
			if(i+1 != swappedLetters.length){
				swappedLettersCollection+=",";
			}
		}
		var data = {"type":"SWAP","played_tiles":swappedLettersCollection,"turns_played":""+turnsPlayed};
		$awordedFactory.getPostReqData('POST', baseUrl+'/users/'+$rootScope.loginUserData.id+'/games/'+gameId+'/turns?country=en', data,$rootScope.getHeaders).then(function (response){
						$scope.my_score= response.my_score;
						if($rootScope.gameStatisticsData.opponent.username != ""){
							$scope.opponentUsername= $rootScope.gameStatisticsData.opponent.username;
							$scope.opponent_score= $rootScope.gameStatisticsData.opponent_score;
						}else{
							$scope.opponentUsername="Random Opponent";
							$scope.opponent_score = "";
						}
						$scope.remaining_tiles= response.remaining_tiles;
						
						$rootScope.gameStatisticsData.my_turn = false;
						$rootScope.gameStatisticsData.remaining_time = 302 - 2;
						timeFlag = 0;
						for(var i=0;i<$scope.swapObjects.length;i++){
							temp = $scope.swapObjects[i];
							id = temp.id;
							$("#"+id).css({"top":"10px"});
						}
						$scope.swapObjects = [];
						$scope.SwapPopup = false;
						
						
						$scope.reloadboard();
					},function(err){
						//console.log('error'+JSON.stringify(err));
					}
				);
	}
	
	// to recall all the letters from the board
	var recallflagtimer = $interval( function(){ $scope.recallflagFun(); }, 100);
	$scope.recallflagFun =function(){
		if(recallflag == true){
			$scope.recallflag = true;
		}else{
			$scope.recallflag = false;
		}
	}
	var recallfiltertile=[];
	$scope.recall=function(){
		var index,divHtml;
		recallflag = false;
		for(var i=0; i<7;i++){
			index = $("#tileContainer"+i).children( ".index").text();
			if(index == $scope.wildid){
				$("#tileContainer"+i).children( ".letterTileContainer").text("*");
				$("#tileContainer"+i).children( ".points").text("");
			}
			$("#tileContainer"+i).removeAttr("style");
			$("#tileContainer"+i).css({"top":"5px", "position":"relative"});
			
			/*$("#tileContainer"+i).addClass("recentlyAddedTileAnimation2");*///$
			
			$("#tileContainer"+i).children( ".letterTileContainer").removeAttr("style");
			$("#tileContainer"+i).children( ".points" ).removeAttr("style");
			$("#tileContainer"+i).children( ".points" ).css({"float":"right"});
			fileteredTileplace = $scope.droppedObjects;
			var tileid = "tileContainer"+i;
			fileteredTileplace = fileteredTileplace.filter(function(e1){
				return e1.tileid !== tileid;
			})
			$scope.droppedObjects = fileteredTileplace;
		}
		tileplaceArr = $scope.droppedObjects;
	
		fileteredTileplace = tileplaceArr;
		var pt;
		for (var key in placedtiles) {
			pt = placedtiles[key];
			fileteredbroadtiles = $scope.boardTiles;
			fileteredbroadtiles = fileteredbroadtiles.filter(function(e1){
				return e1 !== pt.tilePosition;
			})
			$scope.boardTiles = fileteredbroadtiles;
		}
		placedtiles=[];
		$scope.tilesPlaceArr=["","","","","","","",""];
		$scope.combinedHtml=["","","","","","","",""];
		divHtml="";
		letterArray = [];
		$("#validHtml").html(divHtml);
	//	$scope.validateHtml = $sce.trustAsHtml(divHtml);
	}
	
	
	// to display more option (like Resign, see remaining tile and validate the words).
	$scope.moreclose = function(){
		$scope.moreScreen = false;
	}
	
	$scope.chatOption = function(){
		//console.log($rootScope.gameStatisticsData);
		var username;
		if($rootScope.gameStatisticsData.opponent.facebook_name === undefined){
			username = $rootScope.gameStatisticsData.opponent.username;
		}else{
			username = $rootScope.gameStatisticsData.opponent.facebook_name;
		}
		var result = {'oppId' : $rootScope.gameStatisticsData.opponent.id, 'username':username};
		//console.log(result);
		$state.go('menu.chat',{'param1' : $rootScope.gameStatisticsData.opponent.id, 'param2':username});
	}
	
	$scope.moreopen = function(){
		$scope.moreScreen = true;

//new added start		$
		$scope.SwapPopup = false;//$
		var id, temp;
		for(var i=0;i<$scope.swapObjects.length;i++){
			temp = $scope.swapObjects[i];
			id = temp.id;
			$("#"+id).css({"top":"5px"}); //$
		}
		$scope.swapObjects = [];
//new added end
	}
	
	// to resign the current game
	$scope.resign = function() {
		var gameId = $rootScope.gameStatisticsData.id;
		var turnsPlayed = $rootScope.gameStatisticsData.turns_played;
		var data = {"type":"RESIGN", "turns_played":""+turnsPlayed};
		$awordedFactory.getPostReqData('POST', baseUrl+'/users/'+$rootScope.loginUserData.id+'/games/'+gameId+'/turns?country=en', data,$rootScope.getHeaders)
		.then(function (response){
						$scope.reloadboard();
						$rootScope.gameStatisticsData=response;
						$scope.GameEnded = true;
						
						$scope.gameExpiry = false;
						$scope.moreScreen = false;
						$scope.tileBagPopUp =false;//$
						$scope.tileBagAlertBox =false;
						$scope.SwapPopup=false;//$
						
						if($rootScope.gameStatisticsData.win == true){
							$scope.gameResult = true;
						}else{
							$scope.gameResult = false;
						}
						//console.log('gameStatisticsData '+JSON.stringify(response));
						//$state.go('menu.board');
					},function(err){
						//console.log('error'+JSON.stringify(err));
					}
				);
	}
	
	// to play new game with the same opponent
	$scope.playAgain = function(){
		var opponentId = $rootScope.gameStatisticsData.opponent.id;
		var type = $rootScope.type;
		var language = $rootScope.language;
		$scope.loading_view = true;
        $scope.gameEnded = false;
		var data= {"language":language,"opponent":{"id":opponentId},"type": type};
		$awordedFactory.getPostReqData('POST', baseUrl+'/users/'+$rootScope.loginUserData.id+'/games', data,$rootScope.getHeaders)
				.then(function (response){
						$rootScope.gameStatisticsData=response;
						//console.log('gameStatisticsData '+JSON.stringify(response));
						$scope.GameEnded = false;
						$scope.gameResult= false;
						$scope.reloadboard();
					},function(err){
						//console.log('error'+JSON.stringify(err));
					}
				);
		
	}
	$scope.backToList = function() {
		$state.go('menu.dashboard');
	}
	
	// to show the remaining tiles in our tile box
	$scope.ShowTileBagAlertBox=function(){
		$scope.tileBagAlertBox = true;
		$scope.moreScreen = false;
	}
	
	$scope.ShowValidateAlertBox=function(){ //$
		$scope.validateAlertBox = true;
	
		$scope.moreScreen = false;
	}
	$scope.ShowDictionary=function(){ //$
		$scope.dictionaryAlertBox = true;
		$scope.moreScreen = false;
	}
	
	
	$scope.seeRemainingTiles=function(){
		var gameId = $rootScope.gameStatisticsData.id;
		$scope.tileBagAlertBox =false;
		$scope.tilesInTileBag = [];
		var p;
		var points = $scope.pointsArr, available;
		var i, letArr = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
		var data = {"extra":"STOCK_PILE"};
		$awordedFactory.getPostReqData('POST', baseUrl+'/users/'+$rootScope.loginUserData.id+'/games/'+gameId+'/extras', data,$rootScope.getHeaders).then(function (response){
						$scope.tileBagPopUp=true;
						for(i=0; i<letArr.length;i++){
							p = letArr[i].toLowerCase();
							available = response[p];
							$scope.tilesInTileBag.push({"letter" : letArr[i],"points" :points[p] ,"available" : available});
						}	
					},function(err){
						$scope.tileBagPopUp= false;
						alert(err.message);
						//console.log('error'+JSON.stringify(err));
					}
				);
	}
	$scope.HideTileBagAlertBox = function(){
            $scope.tileBagAlertBox = false;
			$scope.moreScreen = true;
    }
	
	$scope.HideValidateAlertBox = function(){ //$
			$scope.validateAlertBox = false;
			$scope.moreScreen = true;
    }
	
	$scope.HideDictionaryAlertBox = function(){ //$
		$scope.dictionaryAlertBox = false; 
		$scope.moreScreen = true;
		
	}
	
	$scope.HideTileBagPopUp = function(){
		$scope.tileBagPopUp= false;
	}
	
	$scope.validateGame=function(){
		$scope.validateAlertBox = false;
		var gameId = $rootScope.gameStatisticsData.id;
		var data = {"extra":"VALIDATOR"};
		$awordedFactory.getPostReqData('POST', baseUrl+'/users/'+$rootScope.loginUserData.id+'/games/'+gameId+'/extras', data,$rootScope.getHeaders).then(function (response){
						$scope.reloadboard();
					},function(err){
						alert(err.message);
						//console.log('error'+JSON.stringify(err));
					}
				);
	}
	
	// to poke the Opponent 
	$scope.poke = function(){	//$scope.postRequest('POST','http://'+path+'/api/users/'+loginUserData.id+'/games/'+scopegameId+'/nudge',null,null,$scope.sessionHeader);
	}
})
.controller('gamechatCtrl', function($state, $scope, $rootScope, $sce, $awordedFactory,$interval,$timeout, $stateParams) {

	var oppId = "";
	var oppUsername = "";
	opId = $stateParams.param1;
	opUser = $stateParams.param2;
	$scope.swapChatScreen = false;
	var chatlistTimer="";
	var chatTimer ="";
	$scope.loadChatList=function(){
		if(opId != ""){
			$scope.swapChatScreen = true;
			$scope.particularChat(opId,opUser);
		}else{
			$scope.swapChatScreen = false;
			$scope.chatListfunction();
		}
	}
	$scope.chatListfunction =function(){
		$awordedFactory.getchatHeaders().then(function (response){
				//console.log(response);
				$scope.chatlist = response
			},function(err){
				//console.log('error'+JSON.stringify(err));
			});
		chatlistTimer = $timeout( function(){ $scope.chatListfunction(); }, 10000);
	}
	$scope.oppusername=""
	$scope.particularChat=function(oppId, oppUsername){
		$timeout.cancel( chatlistTimer );
		$timeout.cancel( chatTimer );
		var heg = $( window ).height()-105;
		$('.chatContainer').css({'height':heg});
		$scope.OppId = oppId;
		if(opId != ""){
			$(".button-clear").css({'display':'block', 'color' : '#FFFFFF'});
		}else{
			$(".button-clear").css({'display':'none', 'color' : '#FFFFFF'});
		}
		var userId = $rootScope.loginUserData.id;
		$scope.swapChatScreen = true;
		$scope.oppusername = oppUsername;
		var data = {};
		$awordedFactory.getReqData('GET', baseUrl+'/users/'+userId+'/users/'+oppId+'/chat', data,$rootScope.getHeaders)
			.then(function (response){
				$scope.chatResponse=[];
				var values, oppTurn, chatDate;
				for(var res in response.list){
					if(response.list[res].message != undefined){
						chatDate = new Date(response.list[res].date);
						var hours = chatDate.getHours();
						var minutes = chatDate.getMinutes();
						if(response.list[res].user_id == oppId){
							oppTurn = 0;
						}else{
							oppTurn = 1;
						}
						values={message:response.list[res].message, date: hours+":"+minutes, opp_turn: oppTurn};
						$scope.chatResponse.push(values);
					}
				}
			},function(err){
				//alert(err.message);
				//console.log('error'+JSON.stringify(err));
			});
			chatTimer = $timeout( function(){ $scope.particularChat(oppId, oppUsername); }, 10000);
	}
	/*********************Back button functionality to clear the timer*****************************/
	$(".button-clear").click(function(){
		$scope.clearTimer();
	});
	$scope.clearTimer = function(){
		console.log("Timeout func called");
		$timeout.cancel(chatTimer);
		$timeout.cancel(chatlistTimer);
	}
	/*********************Back button functionality to clear the timer*****************************/
	$scope.SendChatMess=function(){
		var chatMess = $('#chatinput').val();
		var userId = $rootScope.loginUserData.id;
		var oppId = $scope.OppId;
		var opUsername = $scope.oppusername;
		
		if($.trim(chatMess).length != 0){
			var data = {"message": chatMess};
			var cbody = "";
			$awordedFactory.getPostReqData('POST', baseUrl+'/users/'+userId+'/users/'+oppId+'/chat', data,$rootScope.getHeaders)
			.then(function (response){
				//console.log(response);
				$scope.particularChat(oppId, opUsername);
				
				//console.log(response);
			},function(err){
				//alert(err.message);
				//console.log('error'+JSON.stringify(err));
			});
		}

		$( '#chatForm' ).each(function(){
			this.reset();
		});
		$('#chatinput').val('');
	}
	$scope.showChatList = function(){
		$timeout.cancel( chatTimer );
		$(".button-clear").css({'display':'block'});
		$(".clearContent").html('');
		$scope.swapChatScreen = false;
		$scope.chatListfunction();
	}
})

.controller('menuCtrl', function($scope, $state, $cordovaInAppBrowser) {
	$scope.moveToProfile=function(){
		$state.go('menu.profile');
	};
	$scope.moveToShop=function(){
		$state.go('menu.shop');
	};
	$scope.moveToFacebook=function(){
		var options = {
      			location: 'yes',
      			clearcache: 'yes',
      			toolbar: 'yes'
    			};
		$cordovaInAppBrowser.open('https://www.facebook.com/', '_blank', options)
      			.then(function(event) {
        				// success
     			 })
      			.catch(function(event) {
        			// error
      			});
	};
	$scope.moveToTwitter=function(){
		var options = {
      			location: 'yes',
      			clearcache: 'yes',
      			toolbar: 'yes'
    			};
		$cordovaInAppBrowser.open('http://www.twitter.com/apalabrados', '_blank', options)
      			.then(function(event) {
        				// success
     			 })
      			.catch(function(event) {
        			// error
      			});
	};
	$scope.moveToSettings=function(){
		$state.go('menu.settings');
	};
	$scope.moveToHelp=function(){
		$state.go('menu.help');
	};
	$scope.moveToPremium=function(){
		//$state.go('menu.profile');
	};
	
	})
	.controller('helpCtrl', function($scope, $state) {
		
		$scope.showShopAndExtras=function(){ //$
		$state.go('menu.shopandextras');
		};
		
		$scope.showAccountInformation=function(){ //$
		$state.go('menu.account');
		};
		
		
});