define(['app'], function (app) {
	app.directive('addButtonClick',function($rootScope,$timeout){
		return{
			restrict:'A',
			rootScope:true,
			link:function(rootScope,element,attr){
				rootScope.onclick=function(evt){
					var ele = (evt.target);
					console.log(ele);
					$(ele).off("click",rootScope.onclick)
					$timeout(function (e) {
						//$rootScope.informationimage = []
						//$(element).children("input[type=file]").click()
						$('#imgclick').click()
						$(ele).on("click",rootScope.onclick)
					},100)
				}
				element.on("click",rootScope.onclick)
			}
			
		}
		
	})
	app.directive('imgUploadFile',function($rootScope){
		return{
			restrict:'A',
			scope:true,
			link:function(scope,element,attr){
				element.on('change',function(event){
					var files = event.target.files;
					
					if($rootScope.imageFormat.indexOf(files[0].type) !=-1)
					{
						$rootScope.qimage = files[0];
					}
					else
					{
						$rootScope.$apply(function(){
							$rootScope.modalShown =true;
							$rootScope.message="Please select Image/Video format only"
							angular.element("input[type='file']").val(null);
						})
					}	
						
				})
				
			}
			
			}
		
		}
	)
	
		
		function readURL(input) {

			var num = current_imageObject.attr('data-id');
			if (input.files && input.files[0]) {
					var reader = new FileReader();
					
					reader.onload = function (e) {
					//console.log(num);
					$('#store_image_'+num)
					.attr('src', e.target.result)
					.width(119)
					.height(112);
				}
				reader.readAsDataURL(input.files[0]);
			}
		 }
		 app.service("UploadQuesService",function($http,$rootScope,$timeout){
			
			var service = {}
			service.upload = upload;
			var returnfun;
		function upload(formData,scope){
			
			
			//console.log("File : ",formData);
			returnfun = scope
			 $rootScope.loadingCont = true;
			
			var xhr;
			if (window.XMLHttpRequest)
			  {// code for IE7+, Firefox, Chrome, Opera, Safari
			  xhr=new XMLHttpRequest();
			  }
			else
			  {// code for IE6, IE5
			  xhr=new ActiveXObject("Microsoft.XMLHTTP");
			  }
			  //this._scope['formLoad'] = false;
			xhr.upload.addEventListener("progress", uploadProgress, false)
		   xhr.addEventListener("load", function(evt){
				returnfun(evt.target.responseText);
			}, false)
			
			xhr.addEventListener("error", uploadFailed, false)
			xhr.addEventListener("abort", uploadCanceled, false)
			
			xhr.open("POST", "../services/question.php")
			$rootScope.progressVisible = true
			xhr.send(formData);
			
		}
		
		function uploadProgress(evt) {
			   $rootScope.$apply(function(){
				if (evt.lengthComputable) {
					//$rootScope.progress = Math.round((evt.loaded * 100 )/ evt.total)
				} else {
	
					//$rootScope.progress = 'unable to compute'
				}
			})
	  
		}
	
		function uploadComplete(evt) {
			
			
				//scope.showAlert();
				
		}
	
		function uploadFailed(evt) {
			$rootScope.$apply(function(){
				 $rootScope.loadingCont = false;
			})
			
		}
	
		function uploadCanceled(evt) {
			$rootScope.$apply(function(){
				 $rootScope.loadingCont = false;
			})
		}
		
		
		return service;
		
		})
    app.controller('QuestionCtrl', function ($scope,$rootScope,AppData,$location,UploadQuesService) {
		//Every module Set Same Variable//
	
		$rootScope.menucont = true;
		$rootScope.pageLoadComp = false;
		$scope.formLoad = false;
		$scope.listFound = false;
		$scope.pageData = questionData[$rootScope.selLanguage];
		$scope.formAction = "Add";
		$rootScope.sideselect = $scope.pageData.sidemenu[0];
		console.log($rootScope.sideselect)
		$scope.itemdetail = [];
		$scope.selectedIndex = null;
		$rootScope.cofirmWindow = false;
		$scope.submenu = $scope.pageData.sidemenu;
		$scope.tblheading = $rootScope.sideselect.headingText;
		$scope.url = "../senddata/log/";
		$scope.pageurl = "../senddata/question/";
		$scope.commonurl = "../senddata/common/";
		$rootScope.imageFormat = ["image/jpeg","image/png","video/mp4"];
		$rootScope.qimage = '';
		$scope.search_box = true;

        //pagination
		$scope.viewby = '10';
		$scope.currentPage = 1;
		$scope.itemsPerPage = $scope.viewby;
		$scope.maxSize = 5; //Number of pager buttons to show
		
		//Check Session//
		$scope.formData = {}
		$scope.formData.ismenuload = "Yes";
		if($rootScope.items == undefined || $rootScope.items == null){
			$scope.formData.ismenuload = "No";
		}
		$scope.formData.funName = "checksession";
		$scope.formData.lang = $rootScope.selLanguage;
		$scope.formData.start = 0;
		$scope.formData.limit = 2;
		
		//this page Variable//
		$scope.catearray = [];
		$scope.typearray = [];
		$scope.optdetail = []; 
		AppData.sendData($scope.url,$scope.formData,function(res){
			if(res.cont){
				if($rootScope.items == undefined || $rootScope.items == null){
					$rootScope.items = res.item.control;
				}
				for(var i = 0; i < $rootScope.items.length; i++){
					if($location.path() == $rootScope.items[i].modulepath){
						$rootScope.modulename = $rootScope.items[i].modulename;
						$scope.usercontrol = String($rootScope.items[i].permission).split("|");
					}
				}
				$scope.statusobj = res.item.status;
				$rootScope.username = res.item.username;
				$scope.questionList = function(){
					var fobj = {};
					fobj.funName = "questionlist";
					fobj.lang = $rootScope.selLanguage;
					fobj.pn = $scope.currentPage;
					fobj.nr = $scope.itemsPerPage;
					fobj.lang = $rootScope.selLanguage;
					fobj.key = $scope.searchtext;
					fobj.cateid = 0;
					
					$rootScope.pageLoadComp = true;
					AppData.sendData($scope.pageurl,fobj,function(res){
						$rootScope.pageLoadComp = true;
						if(res.cont){
							if(res.item != undefined){
								$scope.question_data = res.item.questions;
								$scope.totalItems = res.item.total_records;
								$scope.listFound = true;
								$scope.search_box = true;
							}
							$scope.formData = {}
						}else{
							$scope.listFound = false;
							$scope.errorMsg = res.mess;
						}
					})
				}
				$scope.questionList();
				$scope.setPage = function (pageNo) {
					$scope.currentPage = pageNo;
				  };
				
				  $scope.pageChanged = function() {
					console.log('Page changed to: ' + $scope.currentPage);
					$scope.questionList();
				  };
				
				$scope.setItemsPerPage = function(num) {
				  $scope.itemsPerPage = num;
				  $scope.currentPage = 1; //reset to first page
				  $scope.questionList();
				}
				$scope.filterData = function() {
					console.log($scope.searchtext)
					$scope.questionList();
				}
				
			}else{
				$location.path("/login");
			}
		})
		$scope.cartiQuesList = function(){
			var fobj = {};
			fobj.funName = "questionlist";
			fobj.lang = $rootScope.selLanguage;
			fobj.pn = $scope.currentPage;
			fobj.nr = $scope.itemsPerPage;
			fobj.lang = $rootScope.selLanguage;
			fobj.key = $scope.searchtext;
			fobj.certified = 1;
			$rootScope.pageLoadComp = true;
			AppData.sendData($scope.pageurl,fobj,function(res){
				$rootScope.pageLoadComp = true;
				if(res.cont){
					if(res.item != undefined){
						$scope.cert_ques_data = res.item.questions;
						$scope.totalItems = res.item.total_records;
						$scope.listFound = true;
						$scope.search_box = true;
					}
					$scope.formData = {}
				}else{
					$scope.listFound = false;
					$scope.errorMsg = res.mess;
				}
			})
		}
		
		$scope.listClick = function(obj){
			$(".clsbuttoncont .clsbutton").removeClass("disable_btn");
			$scope.formLoad = false;
			$rootScope.sideselect = obj;
			$scope.itemdetail = [];
			$scope.selectedIndex = null;
			var fobj = {};
			fobj.lang = $rootScope.selLanguage;
			fobj.funName = "questionlist";
			
			if(obj.id == 1){
				$scope.tblheading = obj.headingText;
				$scope.questionList();
			}else if(obj.id == 2){
				$scope.tblheading = obj.headingText;
				$scope.cartiQuesList();
			}
			
		}
		
		$scope.changeRemarks =  function(){
			if($scope.formData.rtype==2 || $scope.formData.rtype==3){
				$scope.optdetail=[];
				$scope.optdetail.push({optid:1,iscorrect:0,opttext:"",score:""});
				$scope.optdetail.push({optid:2,iscorrect:0,opttext:"",score:""});
				console.log($scope.optdetail)

			}
			

		}
		/*$scope.curRowClick = function(obj,e){
			$scope.formData = obj
			$scope.selectedIndex = e;
		}*/
		$scope.deleterow = function(obj, i){
			$scope.formData = obj;
			$scope.selectedIndex = i;
			$scope.deleteFun();
		}
		$scope.editrow = function(obj, i){
			console.log(obj)
			$scope.formData = obj;
			$scope.selectedIndex = i;
			console.log($scope.formData);
			$scope.search_box = false;
			$scope.formLoad = true;
			$scope.listFound = false;
			angular.element("input[type='file']").val(null);
			$rootScope.qimage='';
			if($scope.formData.qtype==3){
				$scope.formData.rtype = $scope.formData.surveyqtype;
				$scope.category = $scope.surveycatearray;

			}else{
				$scope.category = $scope.catearray;
				$scope.formData.cattype = $scope.formData.cattype;
			}
			$scope.editFun();
		}
		$scope.viewTiprow = function(obj, i){
			$scope.formData = obj;
			$scope.selectedIndex = i;
			$scope.viewTipFun();
		}
		$scope.viewrow = function(obj, i){
			$scope.formData = obj;
			$scope.selectedIndex = i;
			$scope.viewFun();
		}
		$scope.editFun = function(){
			$scope.questypeList();
			$(".supplieredit").prop('disabled', true);
			if($scope.optdetail!=undefined && $scope.optdetail!=''){
				if($scope.optdetail.length<0){
					$scope.formData.child=[];
				}
			}else{
				$scope.formData.child=[];
			}
			console.log($scope.optdetail)
			$scope.formtitle = "Edit Question";
			$scope.formData.funName = "editquestion";
			$(".clsbuttoncont .clsbutton").addClass("disable_btn");
			if($scope.selectedIndex != null){
					if($scope.formData.questiontypeid=='1'|| $scope.formData.questiontypeid=='2' || $scope.formData.questiontypeid=='5' || $scope.formData.questiontypeid=='6'){
						console.log($scope.formData.qtype)
						var obj = {};
						obj.id = $scope.formData.id;
						obj.funName = "questionoptionlist";
						AppData.sendData($scope.pageurl,obj,function(res){
							if(res.cont){
								$scope.formData.child = res.item;
								console.log($scope.formData.child)
								$scope.optdetail = res.item;
								
							}
						})
					}
					$scope.formLoad = true;
					$scope.formAction = "Edit";
					$scope.title = $rootScope.sideselect.title[1];
				
			}else{
				$rootScope.modalShown =true;
				$rootScope.message=$scope.pageData.errorMsg[0];
			}
		}
		$scope.deleteFun = function(){
			if($scope.selectedIndex != null){
				$rootScope.cofirmWindow = true;
				$rootScope.modalShown =true;
				$rootScope.message=$scope.pageData.errorMsg[1];
			}else{
				$rootScope.modalShown =true;
				$rootScope.message=$scope.pageData.errorMsg[0];
			}
		}
		
		$scope.$on("cofirmDelete",function(){
				
				$scope.formData.funName = "deletequestion";
				
				AppData.sendData($scope.pageurl,$scope.formData,function(res){
					if(res.cont){
						var index = $scope.question_data.indexOf($scope.formData);
						if(index != -1){
							$scope.question_data.splice(index,1);
						}
						$rootScope.modalShown =true;
						$rootScope.cofirmWindow = false;
						$rootScope.message=(res.mess);
					}else{
						$rootScope.modalShown =true;
						$rootScope.message=(res.mess);
					}
				})
		})
		$scope.supplierList = function(){
			var obj = {};
			obj.funName = "supplierlist";
			obj.lang = $rootScope.selLanguage;
			AppData.sendData($scope.supplierurl,obj,function(res){
				if(res.cont){
					$scope.supplierlist = res.item.users;
				}else{
					$rootScope.modalShown =true;
					$rootScope.message=(res.mess);
				}
			})
		}
		//$scope.optionshow = false;
		$scope.changeQuestype = function(){
			if($scope.formData.questiontypeid==1 || $scope.formData.questiontypeid==2 || $scope.formData.questiontypeid==5 || $scope.formData.questiontypeid==6){
				//$scope.optionshow = true;
				$scope.optdetail=[];
				$scope.optdetail.push({optid:1,iscorrect:0,opttext:"",score:""});
				$scope.optdetail.push({optid:2,iscorrect:0,opttext:"",score:""});

				console.log($scope.optdetail)
			}else{
				//$scope.optionshow = false;
				$scope.optdetail=[];
			}
		}
		$scope.questypeList = function(){
			var qobj = {};
			qobj.funName = "questiontype";
			qobj.lang = $rootScope.selLanguage;
			AppData.sendData($scope.commonurl,qobj,function(res){
				if(res.cont){
					$scope.questype= res.item;
				}else{
					$rootScope.modalShown =true;
					$rootScope.message=(res.mess);
				}
			})
		}
		$scope.addFun = function(){
			$scope.formLoad = true;
			$scope.listFound = false;
			$scope.search_box = false;
			$scope.formAction = "Add";
			$scope.formtitle = "Add Question";
			$scope.title = $rootScope.sideselect.title[0];
			$scope.selectedIndex = null;
			$(".supplieredit").prop('disabled', false);
			$scope.questypeList();
			$(".clsbuttoncont .clsbutton").addClass("disable_btn");
			$scope.formData = {};
			
			$scope.formData.funName = "addquestion";
			$scope.formData.child=[];
			$scope.optdetail = []
			$scope.category=[];
			$scope.optdetail.push({optid:1,iscorrect:0,opttext:"",score:""});
			$scope.optdetail.push({optid:2,iscorrect:0,opttext:"",score:""});
			console.log($scope.optdetail)
		}
		$scope.addChoice = function(){
			var len = getMaxID($scope.optdetail);
			$scope.optdetail.push({optid:len,iscorrect:0,opttext:"",score:""});
			console.log($scope.optdetail)
		}
		$scope.deleteChioce = function(index,item){
			console.log(index,item)
			if($scope.optdetail.length > 2){
				if($scope.optdetail!=undefined){
					var num = $scope.optdetail.indexOf(index);
					
					if(num != -1){
						$scope.optdetail.splice(num,1);
						console.log($scope.optdetail);
					}

				}
				
				if($scope.formAction == "Add"){
					if($scope.formData.child!=undefined){
					var num2 = $scope.formData.child.indexOf(item);
					if(num2 != -1){
						$scope.formData.child.splice(num2,1);
					}
				}
				}
				console.log($scope.optdetail,$scope.formData.child);
			}
		}
		$scope.closeForm = function(){
			$scope.formLoad = false;
			$scope.formData = {};
			$scope.selectedIndex = null;
			$scope.search_box = true;
			$scope.listFound = true;
			$(".clsbuttoncont .clsbutton").removeClass("disable_btn");
		}
		
		$scope.questionSubmit = function(){
			console.log($scope.formData.child)
			
			var formData = new FormData();
				formData.append("funName",$scope.formData.funName);
				console.log("here")
				if($scope.formAction == "Edit")
				{
					formData.append("id",$scope.formData.id);
				}
				formData.append("lang",$rootScope.selLanguage);
				formData.append("questiontypeid",$scope.formData.questiontypeid);
				formData.append("questiontext",$scope.formData.questiontext);
				console.log("here11")
				var obj = selectcheckboxStatus($scope.pageData.errorMsg,$scope.formData.qtype);
				
					var arr = checkboxStatus();
					console.log(arr)
					for(id=0;id < arr.length;id++){
						$scope.formData.child[arr[id]].iscorrect = 0;
					}
					console.log($scope.formData.child)
					var str = JSON.stringify($scope.formData.child);
					console.log("here222"+str)
					$scope.formData.child = str;
					formData.append("child",$scope.formData.child);
					console.log(str)
				    // formData.append("file",$rootScope.qimage);
					UploadQuesService.upload(formData,function(res){
					console.log(res)
					var response = JSON.parse(res)
					$scope.$apply(function(){
						$scope.questionList();
						$scope.selectedIndex = null;
						$rootScope.loadingCont = false;
						$rootScope.pageLoadComp = true;
						$rootScope.modalShown =true;
						$rootScope.message=response.mess;
						$scope.formLoad = false;
						$scope.listFound = true;
						$(".clsbuttoncont .clsbutton").removeClass("disable_btn");
				})
		      })
				// AppData.sendData($scope.pageurl,$scope.formData,function(res){
				// 	if(res.cont){
				// 		$rootScope.modalShown =true;
				// 		$rootScope.message=(res.mess);
				// 		if($scope.formAction == "Add"){
				// 			$scope.itemdetail.push(res.item);
				// 		}else{
				// 			$scope.itemdetail[$scope.selectedIndex] = res.item
				// 		}
				// 		$scope.selectedIndex = null;
				// 		$scope.formLoad = false;
				// 		$scope.listFound = true;
				// 	}else{
				// 		$rootScope.modalShown =true;
				// 		$rootScope.message=(res.mess);
				// 	}
				// })
			
		}
		
		$scope.RemoveImage = function (obj){
			current_imageObject= $(obj).parent().parent().find('img');
			current_imageObject.attr('src',"");
			$rootScope.image='';
		}
		
		
      	
    });
}); 
function getMaxID(arr){
	var m =[];
	for(var id = 0; id <arr.length;id++){
		m.push(arr[id].optid);
	}
	var MaxNum = Math.max.apply(null,m);
	return (MaxNum+1);
}
function checkboxStatus(){
	var arr = [];
	var obj = document.getElementsByClassName("clsiscorrectbox");
	for(var id = 0;id < obj.length; id++){
		var ms = obj[id];
		if(!ms.checked){
			var index = String(ms.id).split("checkbox_")[1]
			arr.push(index);
		}
	}
	return arr;
}
function selectcheckboxStatus(arr,mid){
	var marr = []
	var obj = document.getElementsByClassName("clsiscorrectbox");
	for(var id = 0;id < obj.length; id++){
		var ms = obj[id];
		if(ms.checked){
			marr.push(id);
		}
	}
	var obj = {};
	obj.cont = false;
	if(marr.length != 0){
		if(mid == 1){
			if(marr.length == 1){
				obj.cont = true;
			}else{
				obj.cont = false;
				obj.mess = arr[2];
			}
		}else if(mid == 2){
			obj.cont = true;
		}
	}else {
		obj.cont = false;
		obj.mess = arr[3];
	}
	return obj;
}
function onRemoveImage(obj){
	current_imageObject= $(obj).parent().parent().find('img');
	// var iEl = angular.element( document.querySelector( '#store_image_1' ) );
	// iEl.remove();
	
	current_imageObject.attr('src',"");
}
function onclickimg(num){
	console.log(num);
		console.log('#imgclick'+num);
	//$('#imgclick'+num).click();
}
function onAddImage(obj){
	//current_imageObject= $(obj).parent().parent().find('img');
	//var num = current_imageObject.attr('data-id');
	console.log('#imgclick'+obj);
	//var element_string="<div><input type='file' id='informationimage"+num+"' data-id='"+num+"' name='informationimage'   accept='image/*' onchange='readURL(this);' hidden /></div>";
	
	//$('body').append(element_string);
	//$('#imgclick'+obj).click();
}
function readURL(input) {
	var num = current_imageObject.attr('data-id');
	if (input.files && input.files[0]) {
			var reader = new FileReader();
			
			reader.onload = function (e) {
			console.log(num);
			$('#store_image_'+num)
			.attr('src', e.target.result)
			.width(119)
			.height(112);
		}
		reader.readAsDataURL(input.files[0]);
	}
}