define(['app'], function (app) {
	app.directive('uploadImgFile', 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.prodimage = files[0];
					}
					else {
						$rootScope.$apply(function () {
							$rootScope.modalShown = true;
							$rootScope.message = "Please select Image 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) {
				$('#store_image_' + num)
					.attr('src', e.target.result)
					.width(119)
					.height(112);
			}
			reader.readAsDataURL(input.files[0]);
		}
	}
	app.directive('thumbUploadFile', 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.uploadthumbimage.push(files[0]);
					}
					else {
						$rootScope.$apply(function () {
							$rootScope.modalShown = true;
							$rootScope.message = "Please select image format only"
							angular.element("input[type='file']").val(null);
						})
					}

				})

			}

		}

	}
	)
	app.directive('uploadingFileContent', function ($rootScope) {
		return {
			restrict: 'A',
			scope: true,
			link: function (scope, element, attr) {
				element.on('change', function (event) {
					var files = event.target.files;
					if ($rootScope.filetype_format == 1) {

					}
					if ($rootScope.fileFormat.indexOf(files[0].type) != -1) {
						$rootScope.uploadfile.push(files[0]);
					}
					else {
						$rootScope.$apply(function () {
							$rootScope.modalShown = true;
							$rootScope.message = "Please select Pdf/Video/Doc format only"
							angular.element("input[type='file']").val(null);
						})
					}

				})

			}

		}

	}
	)
	app.service("UploadProdService", 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/products.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.service("UploadContentService", function ($http, $rootScope, $timeout) {

		var service = {}
		service.upload = upload;
		var returnfun;
		function upload(formData, scope) {
			var urllink = "services/content.php"

			//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/content.php") //live
			// xhr.open("POST", $rootScope.static_url + urllink)  //local
			$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('ContentCtrl', function ($scope, $rootScope, AppData, $location, UploadContentService, UploadProdService) {
		//Every module Set Same Variable//

		$rootScope.menucont = true;
		$rootScope.pageLoadComp = false;
		$scope.formLoad = false;
		$scope.listFound = false;
		$scope.pageData = contentData[$rootScope.selLanguage];
		$scope.formAction = "Add";
		$rootScope.sideselect = $scope.pageData.sidemenu[0];

		$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/product/";
		$scope.commonurl = "../senddata/common/";
		$scope.contenturl = "../senddata/content/";
		$rootScope.imageFormat = ["image/jpeg", "image/png"]
		$rootScope.pdfFormat = ["application/pdf"];
		$rootScope.fileFormat = ["video/mp4", "application/pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx"];
		$rootScope.docFormat = ["doc", "docx", "xls", "xlsx", "ppt", "pptx"];
		$rootScope.prodimage = '';
		$rootScope.uploadfile = [];
		$rootScope.uploadthumbimage = [];
		$scope.enableeditbox = false;
		$scope.cat_error = '';
		$scope.topic_error = '';

		//filter data
		$scope.common_filter = [];
		$scope.zonearr = [];
		$scope.regionList = [];
		$scope.dealerList = [];

		$scope.search_box = true;
		$rootScope.modalShown = false;
		$rootScope.cofirmWindow = false;
		//pagination
		$scope.viewby = '10';
		$scope.currentPage = 1;
		$scope.itemsPerPage = $scope.viewby;
		$scope.maxSize = 5; //Number of pager buttons to show
		$scope.choice = {};
		$scope.choice.filelang = '';

		//Check Session//
		$scope.formData = {}
		$rootScope.formData = {}
		$scope.formData.roleList = [];
		$rootScope.formData.roleList = [];

		$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;


		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.listFound = true;
				$scope.statusobj = res.item.status;
				$rootScope.username = res.item.username;

				$scope.functionCall = function(){
					for(let i=0;i<$scope.productList.length;i++){
						if($scope.formData.assettopicid==$scope.productList[i].assettopicid){
							$scope.topicdata=$scope.productList[i].segment;
						}
					}
					console.log('topic'+$scope.topicdata)
				}
				$scope.productsList = function () {
					$scope.searchvalue = ($scope.formData.mymodel != '') ? $scope.formData.mymodel : "";
					$scope.formData.funName = "productlist";
					if ($rootScope.sideselect.id == 1) {
						console.log("outtttt")
						$scope.formData.pn = $scope.currentPage;
						$scope.formData.nr = $scope.itemsPerPage;
					} else {
						console.log("innnnn")
						$scope.formData.pn = '';
						$scope.formData.nr = '';
					}
					$scope.formData.key = $scope.searchvalue;

					AppData.sendData($scope.pageurl, $scope.formData, function (res) {
						if (res.cont) {
							if (res.item != undefined) {

								$scope.productList = res.item.product;
								console.log($scope.productList);
								if ($rootScope.sideselect.id != 2) {
									$scope.totalItems = res.item.total_records;
								}

								// $scope.listFound = true;
							}
						} else {
							$scope.listFound = false;

						}
					})
				}
				$scope.productsList();
				$scope.setPage = function (pageNo) {
					$scope.currentPage = pageNo;
				};

				$scope.pageChanged = function () {
					if ($rootScope.sideselect.id == 1) {
						$scope.productsList();
					} else if ($rootScope.sideselect.id == 2) {
						$scope.contentList();

					}
				};

				$scope.setItemsPerPage = function (num) {
					$scope.itemsPerPage = num;
					$scope.currentPage = 1; //reset to first page
					if ($rootScope.sideselect.id == 1) {
						$scope.productsList();
					} else if ($rootScope.sideselect.id == 2) {
						$scope.contentList();

					}
				}
				$scope.filterData = function () {
					if ($rootScope.sideselect.id == 1) {
						$scope.productsList();
					} else if ($rootScope.sideselect.id == 2) {
						$scope.contentList();

					}
				}

			} else {
				$location.path("/login");
			}
		})
		$scope.categoryList = function () {
			//$scope.formData = {};
			$scope.formData.funName = "category";
			$scope.formData.lang = $rootScope.selLanguage;
			AppData.sendData($scope.commonurl, $scope.formData, function (res) {
				if (res.cont) {
					if (res.item != undefined) {
						$scope.catList = res.item;
					}
				}
			})
		}
		$scope.getLanguage = function () {
			var obj = {};
			obj.funName = "language";
			obj.lang = $rootScope.selLanguage;
			AppData.sendData($scope.commonurl, obj, function (res) {
				if (res.cont) {
					if (res.item != undefined) {
						$scope.langList = res.item;
						$scope.choice.filelang = '1';
						//$scope.isDisabled('1')
					}
				}
			})
		}
		$scope.choices = [
			{ filelang: '1' }
		];

		$scope.addNewChoice = function () {
			var newItemNo = $scope.choices.length + 1;
			$scope.choices.push({});
		};

		$scope.removeChoice = function (item) {
			var lastItem = $scope.choices.length - 1;
			$scope.choices.splice(lastItem);
			$scope.inUse.splice(lastItem);
		};
		$scope.inUse = [];
		$scope.isDisabled = function (name) {
			return $scope.inUse.indexOf(name) !== -1;
		}

		$scope.call = function (val) {
			$scope.inUse = [];
			for (var i = 0; i < $scope.choices.length; i++) {
				var val = $scope.choices[i];
				$scope.inUse.push(val.filelang);
			}
		}
		$scope.getRole = function () {
			var obj = {};
			// obj.funName = "role";
			obj.funName = "contentrole"; 
			obj.lang = $rootScope.selLanguage;
			obj.type = "dse"
			AppData.sendData($scope.commonurl, obj, function (res) {
				if (res.cont) {
					if (res.item != undefined) {
						$scope.role = res.item;
					}
				}
			})
		}
		$scope.getZone = function () {
			var zobj = {};
			zobj.funName = "zone";
			zobj.lang = $rootScope.selLanguage;
			AppData.sendData($scope.commonurl, zobj, function (res) {
				if (res.cont) {
					if (res.item != undefined) {
						$scope.zoneList = res.item;
					}
				}
			})
		}
		// $scope.ischecked = 0;
		// $scope.selectallzone = function (){
		// 	// console.log('zone list:' + $scope.zoneList);
		// 	console.log('Zone length:' + $scope.zoneList.length);
		// 	console.log($scope.zoneList)
		// 	return false
		// 	angular.forEach($scope.zoneList, function (item) {
		// 		console.log(item)
        //         if (zone.indexOf(item.zone) > -1) {
        //             item.checked = true;
		// 		}
        //     });
		// }
		$scope.zoneChanged = function (item, i) {
			console.log(item)
			var obj = {};
			obj.cont = true;
			angular.forEach($scope.regionList, function (cityname, index) {
				if (item.zone == cityname.title) {
					angular.forEach(cityname.child, function (city, ind) {
						for (var k in $scope.formData.regionList) {
							if (city == k) {
								$scope.formData.regionList[k] = false;
							}
						}
					})
					console.log("helloooo", $scope.regionList)
					$scope.regionList.splice(index, 1);
					obj.cont = false;
				}
			})
			var fobj = {};
			fobj.lang = $rootScope.selLanguage;
			fobj.funName = "city";
			var zonename = item.zone;

			fobj.zone = (zonename == undefined) ? "" : zonename;
			if (obj.cont) {
				AppData.sendData($scope.commonurl, fobj, function (res) {
					$rootScope.pageLoadComp = true;
					if (res.cont) {
						if (res.item != undefined) {
							$scope.stateVisible = true;
							var arr = [];
							for (var id = 0; id < res.item.length; id++) {
								arr.push(res.item[id].city);
							}
							console.log(res.item, arr, "helloooo", $scope.regionList)
							$scope.regionList.push({ "title": zonename, "child": arr });
							console.log($scope.regionList)
						} else {
							$scope.regionList = [];
							$scope.dealerList = [];
							$scope.stateVisible = false;
							$scope.dealerVisible = false;
						}
					}
				});
			} else {

				//angular.forEach($scope.dealerList,function(item,index){
				if ($scope.dealerList.length != undefined) {
					for (i = 0; i < $scope.dealerList.length; i++) {
						for (var k in $scope.formData.regionList) {
							if ($scope.dealerList.length != undefined && $scope.dealerList.length > 0) {
								if (k == $scope.dealerList[i].title) {
									if ($scope.formData.regionList[k] == false) {
										angular.forEach($scope.dealerList[i].child, function (dealer, ind) {
											for (var j in $scope.formData.dealerList) {
												if (j == dealer.dealer_code) {
													$scope.formData.dealerList[j] = false;

												}
											}
											$scope.dealerList.splice(i, 1);
										})

									}
								}
							}
						}
					}
				}

			}


		}
		$scope.regionChanged = function (item, i) {
			console.log(item)
			var dobj = {};
			dobj.cont = true;
			if ($scope.dealerList != undefined) {
				angular.forEach($scope.dealerList, function (dealername, index) {
					if (item == dealername.title) {
						angular.forEach(dealername.child, function (dealer, ind) {
							for (var k in $scope.formData.dealerList) {
								if (dealer.dealer_code == k) {
									$scope.formData.dealerList[k] = false;
								}
							}
						})
						console.log("helloooo", $scope.dealerList)
						$scope.dealerList.splice(index, 1);
						dobj.cont = false;
					}
				})
			}

			var fobj = {};
			fobj.lang = $rootScope.selLanguage;
			fobj.funName = "dealer";
			var dealer_name = item;
			// if($scope.is_edit_dealer==false){

			// }else{
			// 	var dealer_name = item.toString();
			// 	$scope.is_edit_dealer= false;
			// }

			fobj.city = (dealer_name == undefined) ? "" : dealer_name;
			if (dobj.cont) {
				AppData.sendData($scope.commonurl, fobj, function (res) {
					$rootScope.pageLoadComp = true;
					if (res.cont) {
						if (res.item != undefined) {
							$scope.dealerVisible = true;
							var arr = [];
							for (var id = 0; id < res.item.length; id++) {
								var obj = {};
								obj.dealer_name = res.item[id].dealer_name;
								obj.dealer_code = res.item[id].dealer_code;
								arr.push(obj);
							}
							$scope.dealerList.push({ "title": dealer_name, "child": arr });
							console.log($scope.dealerList)
						} else {
							$scope.dealerVisible = false;
							$scope.dealerList = [];
						}
					}
				});
			} else {

			}

		}

		$scope.addFun = function () {
			$scope.choices = [{ "filelang": "1" }];
			$scope.call($scope.choices)
			$scope.formLoad = true;
			$scope.listFound = false;
			$scope.formAction = "Add";
			$scope.is_edit_region = false;
			$scope.is_edit_dealer = false;
			//$scope.title = $rootScope.sideselect.title[0];
			$scope.formData = {};
			$scope.zoneList = [];
			$scope.regionList = [];
			$scope.dealerList = [];
			$scope.formData.regionList = {};
			$scope.formData.dealerList = {};
			$rootScope.uploadfile = []
			$rootScope.uploadthumbimage = [];
			$scope.formData.roleList = [];
			$rootScope.formData.roleList = [];
			if ($rootScope.sideselect.id == 1) {
				$scope.formLoad = true;
				$scope.formData.funName = "addproduct";
				$scope.formTitle = "ADD TOPIC";
				angular.element("input[type='file']").val(null);
				$scope.categoryList();
			} else if ($rootScope.sideselect.id == 2) {
				$scope.formLoad = true;
				$scope.formTitle = "ADD CONTENT";
				$scope.formData.funName = "addcontent";
				angular.element("input[type='file']").val(null);
				$scope.getLanguage();
				$scope.getRole();
				$scope.getZone();
				$scope.productsList();
			}
		}
		$rootScope.notifyChange = function () {
			if ($rootScope.formData.notification) {
				$rootScope.roleVisible = true;
				$rootScope.roleGroup = $scope.formData.roleList;
				if ($rootScope.roleGroup.length > 0) {
					angular.forEach($rootScope.roleGroup, function (element) {
						$rootScope.formData.roleList[element.id] = true;
					});
				}
			} else {
				$rootScope.roleVisible = false;
			}
		}
		$scope.deleterow = function (obj, i) {
			$scope.formData = obj;
			$scope.selectedIndex = i;
			$scope.deleteFun();
		}
		$scope.editFun = function () {
			$scope.filerequired = false;
			$scope.thmbrequired = false;
			$scope.formAction = "Edit";
			$scope.is_edit_region = true;
			$scope.is_edit_dealer = true;
			$(".clsbuttoncont .clsbutton").addClass("disable_btn");
			$scope.formLoad = true;
			$scope.listFound = false;
			angular.element("input[type='file']").val(null);
			if ($scope.selectedIndex != null) {
				if ($rootScope.sideselect.id == 1) {
					$scope.formTitle = "EDIT TOPIC";
					$scope.categoryList();
					$scope.image_url = $scope.formData.image_url;
				} else if ($rootScope.sideselect.id == 2) {
					$scope.formTitle = "EDIT CONTENT";
					$scope.getLanguage();
					$scope.getRole();
					$scope.getZone();
					$rootScope.uploadfile = [];
					$rootScope.uploadthumbimage = [];
					$scope.zoneList = [];
					$scope.regionList = [];
					$scope.dealerList = [];
					$scope.formData.zoneList = {};
					$scope.formData.regionList = {};
					$scope.formData.dealerList = {};
					if ($scope.formData.filter_zone.length > 0) {
						angular.forEach($scope.formData.filter_zone, function (element, index) {
							console.log(element, "zoneee")
							$scope.formData.zoneList[element.zone] = true;
							if (element != '') {
								$scope.zoneChanged(element, index);
							}
						});
					} else {
						$scope.stateVisible = false;
						$scope.dealerVisible = false;

					}
					if ($scope.formData.filter_region.length > 0) {
						angular.forEach($scope.formData.filter_region, function (element, index) {
							$scope.formData.regionList[element.city] = true;
							if (element != '') {
								$scope.regionChanged(element['city'], index);
							}
						});
					} else {
						$scope.dealerVisible = false;
					}

					if ($scope.formData.filter_dealer.length > 0) {
						angular.forEach($scope.formData.filter_dealer, function (element) {
							console.log(element)
							$scope.formData.dealerList[element.dealer_code] = true;
						});
						$scope.dealerVisible = true;
					}
					$scope.formData.roleList = $scope.formData.filter_role_name;
					console.log($scope.formData.roleList, "$scope.formData.roleList ", $scope.formData.filter_role_name)
					angular.forEach($scope.formData.file, function (element, i) {
						$scope.filepath_url = element.filepath_url;
						$scope.thumbpath_url = element.thumbpath_url;
						$scope.file_show = i;
						$scope.call(element.language_id)
					});
					$scope.choices = $scope.formData.file;
				}
			} else {
				$rootScope.modalShown = true;
				$rootScope.message = $scope.pageData.errorMsg[0];
			}
		}
		$scope.editrow = function (obj, i,data) {
			if(data == 0){
				$scope.enableeditbox = true;
			}else{
				$scope.enableeditbox = false;
			}
			console.log(obj);
			$scope.formData.assettopicid = obj.assettopicid;
			console.log($scope.formData.assettopicid)
			$scope.productsList();
			$scope.functionCall(function(){
			  },1000); 
			console.log($scope.productList);
			$scope.formData = obj;
			console.log($scope.formData.filetypeid)
			$scope.formData.catename = obj.catename;
			$scope.formData.filetypeid = obj.filetypeid;
			$scope.selectedIndex = i;
			$scope.search_box = false;
			$scope.listFound = false;
			$scope.formLoad = true;
			$scope.formAction = "Edit";
			angular.element("input[type='file']").val(null);
			$rootScope.prodimage = '';
			$scope.editFun();
		}
		$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("confirmDelete", function () {
			if ($rootScope.sideselect.id == 1) {
				$scope.formData.funName = "deleteproduct";
				$scope.url = $scope.pageurl
			} else if ($rootScope.sideselect.id == 2) {
				$scope.formData.funName = "deletecontent";
				$scope.url = $scope.contenturl
			}
			$scope.formData.lang = $rootScope.selLanguage;
			AppData.sendData($scope.url, $scope.formData, function (res) {
				if (res.cont) {
					if ($rootScope.sideselect.id == 1) {
						var index = $scope.productList.indexOf($scope.formData);
						if (index != -1) {
							$scope.productList.splice(index, 1);
						}
					} else if ($rootScope.sideselect.id == 2) {
						var index = $scope.contentdata.indexOf($scope.formData);
						if (index != -1) {
							$scope.contentdata.splice(index, 1);
						}
					}
					$rootScope.modalShown = true;
					$rootScope.cofirmWindow = false;
					$rootScope.message = (res.mess);
				} else {
					$rootScope.modalShown = true;
					$rootScope.message = (res.mess);
				}
			})
		})
		$scope.onSearchChange = function () {
			if ($rootScope.sideselect.id == 1) {
				$scope.productsList();
			} else if ($rootScope.sideselect.id == 2) {
				$scope.contentList();
				// $scope.productsList();
			}
		}
		$scope.contentList = function () {
			$scope.searchvalue = ($scope.formData.mymodel != '') ? $scope.formData.mymodel : "";
			$scope.formData.funName = "contentlist";
			if ($rootScope.sideselect.id == 2) {
				$scope.formData.pn = $scope.currentPage;
				$scope.formData.nr = $scope.itemsPerPage;
			} else {
				$scope.formData.pn = '';
				$scope.formData.nr = '';
			}
			$scope.formData.key = $scope.searchvalue;

			AppData.sendData($scope.contenturl, $scope.formData, function (res) {
				if (res.cont) {
				
					if (res.item != undefined) {
						$scope.contentdata = res.item.content;
						console.log($scope.contentdata)
						$scope.totalItems = res.item.total_records;
						$scope.listFound = true;
					}
				} else {
					$scope.listFound = false;
				}
			})
		}

$scope.onModalHide=function(event){
	console.log(event)
$scope.contentList();
}

		$scope.viewfile=function(obj, id){
			console.log(obj.contentid)
	angular.forEach($scope.contentdata,function(element)  {
				if(element.contentid==obj.contentid){
					$scope.content_view = element;
			
					console.log($scope.content_view.file[0].filepath_url)
				
	$scope.filename=$scope.content_view.file[0].filepath_url
				
				
				}
			});
		}
		$scope.listClick = function (obj) {
			$scope.searchtext = '';
			$scope.formData = {}
			$scope.currentPage = 1;
			$(".clsbuttoncont .clsbutton").removeClass("disable_btn");
			$scope.formLoad = false;
			$rootScope.sideselect = obj;
			$scope.selectedIndex = null;
			$rootScope.sideselect.name = obj.name;
			if (obj.id == 1) {
				$scope.tblheading = obj.headingText;
				$scope.productsList();
			} else if (obj.id == 2) {
				$scope.tblheading = obj.headingText;
				$scope.contentList();
				// $scope.productsList();
			}

		}

		$scope.fieldValidationTopic = function () {
			console.log('prodimage',$rootScope.prodimage)
			$scope.cat_error = ($scope.formData.cateid == undefined || $scope.formData.cateid == '') ? $scope.pageData.errorMsg[0] : '';
			$scope.topic_error = ($scope.formData.topicname == undefined || $scope.formData.topicname == '') ? $scope.pageData.errorMsg[2] : '';
            $scope.segment_error = ($scope.formData.segment == undefined || $scope.formData.segment == '') ? $scope.pageData.errorMsg[0] : '';
			$scope.topic_order_error = ($scope.formData.listorder == undefined || $scope.formData.listorder == '') ? "Choose Order by" : '';
			$scope.topic_image_error = ($rootScope.prodimage == undefined || $rootScope.prodimage == '') ? 'Please Add Image' : '';
			return ($scope.cat_error == '' && $scope.topic_error == '' && $scope.topic_order_error=='' && $scope.topic_image_error=='' && $scope.segment_error=='') ? true : false;
		}
		$scope.clearErrorMsg = function () {
			$scope.cat_error = '';
			$scope.topic_error = '';
			$scope.topic_order_error='';
			$scope.topic_image_error=''; 
            $scope.segment_error ='';

		}
		$scope.topicSubmit = function () {
			if ($scope.fieldValidationTopic()) {
				var formData = new FormData();
				if ($scope.formAction == "Add") {
					formData.append("funName", "addproduct");
				} else if ($scope.formAction == "Edit") {
					formData.append("assettopicid", $scope.formData.assettopicid);
					formData.append("funName", "updateproduct");
				}
				formData.append("lang", $rootScope.selLanguage);
				formData.append("cateid", $scope.formData.cateid);
				formData.append("file", $rootScope.prodimage);
				formData.append("topicname", $scope.formData.topicname);
                formData.append("segment", $scope.formData.segment);
				formData.append("listorder", $scope.formData.listorder);

				UploadProdService.upload(formData, function (data) {
					var response = JSON.parse(data)
					$scope.$apply(function () {
						$scope.formLoad = false;
						$scope.listFound = true;
						$scope.formData = {}
						$scope.productsList();
						$scope.selectedIndex = null;
						$rootScope.loadingCont = false;
						$rootScope.pageLoadComp = true;
						$rootScope.modalShown = true;
						$rootScope.message = response.mess;
					})
				});
			}
		}

		$scope.closeForm = function () {
			console.log('I am closed')
			$scope.formLoad = false;
			$scope.formData = {};
			$scope.selectedIndex = null;
			$scope.search_box = true;
			$scope.listFound = true;
			$scope.choices = [];
			$scope.zoneList = [];
			$scope.regionList = [];
			$scope.dealerList = [];
			$scope.clearErrorMsg();
			// $scope.contentList();

			// $scope.productsList();
		}

		$scope.fieldValidation = function () {
			$scope.ftype_error = ($scope.formData.filetypeid == undefined || $scope.formData.filetypeid == '') ? "Please choose the file" : '';
			$scope.topic_error = ($scope.formData.assettopicid == undefined || $scope.formData.assettopicid == '') ? $scope.pageData.errorMsg[2] : '';
            $scope.segment_error = ($scope.formData.segment == undefined || $scope.formData.segment == '') ? $scope.pageData.errorMsg[0] : '';
			$scope.thumb_error = ($rootScope.uploadthumbimage.length == 0) ? 'Upload the thumb image ' : '';
			$scope.pdf_error = ($rootScope.uploadfile[0] == undefined ||$rootScope.uploadfile[0] == '') ? 'Please upload the pdf' : '';
			return ($scope.ftype_error == '' && $scope.topic_error == '' && $scope.thumb_error == '' && $scope.pdf_error == '' && $scope.segment_error=='') ? true : false;
		}

		$scope.contentSubmit = function () {
			if ($scope.fieldValidation()) {
				var formData = new FormData();
				if ($scope.formAction == "Add") {
					formData.append("funName", "addcontent");
				} else if ($scope.formAction == "Edit") {
					formData.append("contentid", $scope.formData.contentid);
					formData.append("funName", "updatecontent");
				}
				formData.append("lang", $rootScope.selLanguage);
				formData.append("assettopicid", $scope.formData.assettopicid);
                formData.append("segment", $scope.formData.segment);
				formData.append("title", $scope.formData.title);
				formData.append("description", $scope.formData.description);
				formData.append("filetypeid", $scope.formData.filetypeid);
				
				if ($rootScope.uploadfile.length != 0) {
					formData.append("file_en_us", $rootScope.uploadfile[0]);

				}
				if ($rootScope.uploadthumbimage.length != 0) {
					formData.append("thumb_en_us", $rootScope.uploadthumbimage[0]);
				}

				if ($scope.formData.filetypeid == 3) {
					formData.append("url", $scope.formData.url);
				}
				if ($scope.formData.cityList != undefined) {
					var cityarr = [];
					for (k in $scope.formData.cityList) {
						if ($scope.formData.cityList[k] == true) {
							cityarr.push(k)
						}
					}
					if (cityarr.length != 0) {
						formData.append("filter_city", cityarr.toString());
					}
				}
				if ($scope.formData.regionList != undefined) {
					var statearr = [];
					for (k in $scope.formData.regionList) {
						if ($scope.formData.regionList[k] == true) {
							statearr.push(k)
						}
					}
					if (statearr.length != 0) {
						formData.append("filter_region", statearr.toString());
					}
				}
				if ($scope.formData.dealerList != undefined) {
					var dealerarr = [];
					for (k in $scope.formData.dealerList) {
						if ($scope.formData.dealerList[k] == true) {
							dealerarr.push(k)
						}
					}
					if (dealerarr.length != 0) {
						formData.append("filter_dealer", dealerarr.toString());
					}
				}
				if ($scope.formData.zoneList != undefined) {
					var zonearr = [];
					for (k in $scope.formData.zoneList) {
						if ($scope.formData.zoneList[k] == true) {
							zonearr.push(k)
						}
					}
					if (zonearr.length != 0) {
						formData.append("filter_zone", zonearr.toString());
					}
				}
				if ($scope.formData.roleList.length != 0) {
					var rolearr = [];
					for (var id = 0; id < $scope.formData.roleList.length; id++) {
						rolearr.push($scope.formData.roleList[id].id)
					}
					formData.append("filter_role", rolearr.toString());
				}


				UploadContentService.upload(formData, function (data) {
					console.log($scope.formData);
					console.log(data);
					var response = JSON.parse(data);
					if (response.cont) {
						var obj = response.item;
						$scope.$apply(function () {
							if ($rootScope.uploadfile.length > 1) {
								$scope.uploadDataToServer(1, obj[0].contentid, obj[0].assettopicid);
							} else {
								$scope.formData = {};
								$scope.contentList();
							}
							$scope.formData.assettopicid = '';
							$scope.listFound = true;
							$scope.formLoad = false;
							$rootScope.uploadFiletype = null;
							$rootScope.modalShown = true;
							$rootScope.message = response.mess;
							// $scope.contentList();
							$(".clsbuttoncont .clsbutton").removeClass("disable_btn");
						})
					}
				});

			}
			
			$scope.uploadDataToServer = function (id, contentid, topicid) {

				var formData = new FormData();
				formData.append("funName", "uploadcontentfile");
				formData.append("num", id);
				formData.append("lang", $rootScope.selLanguage);
				formData.append("contentid", contentid);
				formData.append("assettopicid", topicid);
				formData.append("filetypeid", $scope.formData.filetypeid);
				if ($rootScope.uploadfile.length != 0) {
					formData.append("file", $rootScope.uploadfile[id]);

				}
				formData.append("language_id", $scope.choices[id].filelang);
				if ($rootScope.uploadthumbimage.length != 0) {
					formData.append("thumb", $rootScope.uploadthumbimage[id]);
				}
				UploadContentService.upload(formData, function (data) {

					$rootScope.$apply(function () {
						var response = JSON.parse(data)
						$rootScope.loadingCont = false;
						$scope.selectedIndex = null;
						if (response.cont) {
							if (id == $rootScope.uploadfile.length - 1) {
								$scope.listFound = true;
								$scope.formLoad = false;
								$rootScope.uploadFiletype = null;
								if ($scope.formAction == "Add") {
									$scope.contentData.push(response.item);
								} else {
									$scope.contentData[$scope.selectedIndex] = response.item;
								}

							} else {
								$scope.listFound = true;
								$scope.formLoad = false;
								$rootScope.modalShown = true;
								$rootScope.message = response.mess;
							}
							if (id < $rootScope.uploadfile.length - 1) {
								id++;
								$scope.uploadDataToServer(id,  contentid, topicid);
							} else {
								$rootScope.modalShown = true;
								$rootScope.message = response.mess;
								$(".clsbuttoncont .clsbutton").removeClass("disable_btn");
								$scope.contentList();
							}

						}

					})
				})
			}
			


			

		}

	});
}); 
