'use strict';
//dependent upon on Bootstrap

app.directive('activityDeviceSelect', function () {
  return {
    restrict: 'E',
    require: 'ngModel',
    replace: true,
    scope: {
      ngModel: '=',
      roomDevices: '=',
      powerInputMode: '=', //default: false (power off), true (power on, input)
      disable: '=' //if true, hides the list 
    },
    templateUrl: 'views/activity-device-select.html',
    link: function(scope, element, attrs) {
      scope.powerInputMode = scope.powerInputMode || false;
    },
    controller: function($scope, $modal) {
      $scope.showPopup = true;

      // input 에 체크가 해제되면 navigation 체크 해제시킴
      $scope.$watch('ngModel', function(newVal, oldVal) {
        var checkedInputs = [];

        _.each(newVal, function(item) {
          if (item.type === 2) {
            checkedInputs.push(item.device_id);

            if (item.navigate) {
              if (angular.element('#navigation' + item.device_id)[0]) {
                angular.element('#navigation' + item.device_id)[0].checked = true;
              }
            }
          }
        });

        angular.element('input.navigation').each(function() {
          var self = this,
            deviceId = +(self.id.split('navigation')[1]);

          if (checkedInputs.indexOf(deviceId) === -1) {
            self.checked = false;
          }
        });
      }, true);

      $scope.checked = function(deviceId) {
        var input = _.find($scope.ngModel, function(item) {
          return item.type === 2 && item.device_id === deviceId;
        });

        if (!input || !input.navigate) {
          return null;
        } else {
          return true;
        }
      };

      // navigation 체크할 때
      $scope.checkNavigation = function(deviceId) {
        var input = _.find($scope.ngModel, function(item) {
          return item.type === 2 && item.device_id === deviceId;
        });

        if (!input) {
          angular.element('#navigation' + deviceId)[0].checked = false;
        }

        if (angular.element('#navigation' + deviceId)[0].checked) {
          input.navigate = 1;

          if ($scope.showPopup) {
            var modal = $modal({
              scope: $scope,
              template: 'views/modal-tpls/navigating-television.html',
              container: 'body',
              show: false
            });
            modal.$promise.then(modal.show);
          }
        } else {
          if (input && input.navigate) {
            delete input.navigate;
          }
        }
      };

      $scope.hidePopup = function() {
        $scope.showPopup = false;
      };
    }
  };
});

'use strict';

app.directive('addDelayStep', function ($modal, $timeout) {
  return {
    restrict: 'A',
    scope: {
      steps: '='
    },
    link: function(scope, element, attrs) {
      var modal = $modal({scope: scope, title: 'Set delay time', template: 'views/modal-tpls/add-delay.html', show: false});
      

      scope.addDelay = function (time) {
        scope.steps = scope.steps || [];
        scope.steps.push({name: 'Delay ' + time + ' seconds', type: 2, value: time*1000});
        // $timeout(function(){
        //   delete scope.delay;
        // }, 500);
      }; 

      element.on('click', function(event) {
        event.preventDefault();
        scope.delay = {};
        modal.$promise.then(modal.show);
      });

    }
  };
});
'use strict';

app.directive('addJumpTo', function ($modal, $timeout) {
  return {
    restrict: 'A',
    scope: {
      steps: '=',
      devices: '='
    },
    controller: function($scope, $element) {
      var modal = $modal({scope: $scope, title: 'Add a jump to a device', template: 'views/modal-tpls/add-jump-to.html', show: false});
      
      $scope.addJumpTo = function (device) {
        $scope.steps = $scope.steps || [];
        $scope.steps.push({'name': 'Jump to ' + device.name, 'type': 3, 'to': {'type': 1, 'value': device.id} });
      }; 

      $element.on('click', function(event) {
        event.preventDefault();
        $scope.jump = {};
        modal.$promise.then(modal.show);
      });
    }
  };
});
'use strict';

app.directive('addPage', function() {
  return {
    require: '^deviceInterface',
    restrict: 'E',
    scope: {
      
    },
    link: function(scope, element, attrs, interfaceCtrl) {
      element.on('click', function() {
        interfaceCtrl.addPage(scope);
      });
      
    },
    template: '<button type="button" class="btn btn-menu">Add a new page</button>'
  };
});
'use strict';

app.directive('addSpecialFunction', function () {
	return {
		restrict: 'A',
		scope: {
			steps: '=',
			sfunc: '='
		},
		controller: function($scope, $element, $modal, toastr) {
			$scope.specialFuncTypes = [{title:'Set Variable: ', value:0}, {title:'If Else: ', value:1}];
			$scope.variableTypes = [{name:'True False', value:0}, {name:'String', value:1}, {name:'Integer', value:2}];
			$scope.opIntTypes = ['=', '>=', '<'];
			$scope.opStrTypes = ['include', '='];
			$scope.sfunc.cond = {type:1};
			$scope.title = '';

			
			var modal;
			if(0 == $scope.sfunc.type)
			{
				modal = $modal({ scope: $scope, placement: 'top', template:'views/modal-tpls/add-variable-function.html', show:false});
			}
			else
			{
				modal = $modal({ scope: $scope, placement: 'top', template:'views/modal-tpls/add-if-function.html', show:false});
			}

			$scope.addStep = function() {

				modal.$promise.then(modal.hide);

				$scope.sfunc.value += '';

				var step = null;

				if(0 == $scope.sfunc.type)///set variable action
				{
					var dispValue = $scope.sfunc.value;
					if($scope.sfunc.variable.type == 0){
						if($scope.sfunc.value == 0){
							dispValue = 'false' ;
						}
						else if($scope.sfunc.value == 1){
							dispValue = 'true' ;
						}
						else if($scope.sfunc.value == 2){
							dispValue = 'invert' ;
						}
					}

					step = {'name': 'VAR ' + $scope.sfunc.variable.name + '= ' + dispValue, 'type': 5, 'id': $scope.sfunc.variable.id, 'value': $scope.sfunc.value };
					$scope.steps.push(step);
				}
				else///if/else action
				{
					$scope.sfunc.cond.id = $scope.sfunc.variable.id;
					$scope.sfunc.cond.value +=  '';
					var name = '';
					if($scope.sfunc.variable.type == 0){
						name = 'If: ' + $scope.sfunc.variable.name + ', ' + ($scope.sfunc.cond.value == 1 ? 'True':'False');
					} else{
						name = 'If: ' + $scope.sfunc.variable.name + ' ' +  $scope.sfunc.cond.operate + ' ' + $scope.sfunc.cond.value;
					} 

					step = {'name': name, 'type': 4, 'cond': $scope.sfunc.cond, 'true': [], 'false': []};

					step.steps = [{name:'True', steps:[]}, {name:'False', steps:[]}];

					$scope.steps.push(step);
				}
				
			};

			$element.on('click', function(event) {
				event.preventDefault();
				$scope.title = $scope.specialFuncTypes[$scope.sfunc.type].title + $scope.variableTypes[$scope.sfunc.variable.type].name;
				$scope.title += ($scope.sfunc.type == 1 ? ' Variable' : '');

				if($scope.sfunc.variable.type == 1) {
					$scope.sfunc.cond.operate = $scope.opStrTypes[0];
				}	else if($scope.sfunc.variable.type == 2) {
					$scope.sfunc.value = parseInt($scope.sfunc.variable.value, 10);
					$scope.sfunc.cond.value = parseInt($scope.sfunc.variable.value, 10);
					$scope.sfunc.cond.operate = $scope.opIntTypes[0];
				}
				
				modal.$promise.then(modal.show);
			});

		}
	};
});

'use strict';

app.directive('deleteVariable', function ($rootScope, $modal, $timeout) {
	return {
		restrict: 'A',
		scope: {
			system: '=',
			steps: '=',
			variable: '='
		},
		controller: function ($rootScope, $scope, $element, Systems, toastr) {
			var modal = $modal({scope: $scope, template: 'views/modal-tpls/delete-variable.html', show: false});
			
			$scope.delete = function () {
				var data = JSON.stringify({ id: $scope.variable.id});

				var roomId = null;
				if ($rootScope.virtualEditor) {
					roomId = Systems.getCurrentRoom();
				}

				Systems.deleteVariable(data, roomId).then(function (data) {
					console.log('data=', data);
          var variable = _.find($scope.system.variables || $scope.system.rooms[0].variables, {'id': $scope.variable.id});

					if(variable){
						///$scope.system.variables에서 삭제한 variable을 제거
            if ($rootScope.virtualEditor) {
              var idx = $scope.system.rooms[0].variables.indexOf(variable);
              $scope.system.rooms[0].variables.splice(idx, 1);
            } else {
              var idx = $scope.system.variables.indexOf(variable);
              $scope.system.variables.splice(idx, 1);
              console.log('variables=', $scope.system.variables);
            }

						///$scope.steps에 삭제한 variable을 참조하고 있다면 제거
						_.forEach($scope.steps, function (step) {
							if(step && (step.type == 4 || step.type == 5)){
								if(step.id == variable.id){
									idx = $scope.steps.indexOf(step);
									$scope.steps.splice(idx, 1);	
								}
							}
						});
					}

				}).catch(function(error) {
					toastr.error(error, 'Error');
				});

				modal.$promise.then(modal.hide);
			}; 

			$element.on('click', function(event) {
				event.preventDefault();
				modal.$promise.then(modal.show);
			});
		}
	};
});
'use strict';

app.directive('deviceBtnDelete', function() {
  // Runs during compile
  return {
    restrict: 'E', // E = Element, A = Attribute, C = Class, M = Comment
    template: '<a title="Delete this button" ng-click="showModal()"><i class="fa fa-fw fa-lg fa-trash-o action-icon"></i></a>',
    scope: {
      selectedBtn: '='
    },
    replace: true,
    controller: function($scope, $modal) {
      var deleteModal = $modal({ scope: $scope, title: 'Delete this button', template:'views/modal-tpls/device-delete-btn.html', show:false});
      
      function showModal() {
        deleteModal.$promise.then(deleteModal.show);
      }
      function hideModal() {
        deleteModal.$promise.then(deleteModal.hide);
      }

      $scope.showModal = showModal;

      $scope.delete = function(obj) {

        var keys = ['id', 'page_btn_idx', 'name', 'device_id', 'room_id', 'repeat_min', 'repeat_macro', 'press_hold', 'repeatSetting'];

        for (var prop in obj) {
          if (keys.indexOf(prop) === -1) {
            delete obj[prop];
          } else {
            if (prop === 'repeatSetting') {
              obj[prop] = 'default';
            }
          }
        }
        $scope.selectedBtn = null;
        hideModal();
      };
    }  
  };
});
'use strict';

app.directive('deviceBtnEdit', function () {
	return {
		restrict: 'EA',
		replace: true,
		scope: {
			selectedBtn: '=',
			deviceData: '=',
			roomId: '='
		},
		template: function(tElement, tAttrs) {
			var template;
			switch (tAttrs.content) {
				case 'add':
					template = '<button class="btn btn-menu" ng-click="showModal()">Add a button</button>';
					break;
				case 'add-from-navi':
					template = '<button class="btn btn-menu" ng-click="showModal()">Add from navigator</button>';
					break;
				case 'add-from-device':
					template = '<button class="btn btn-menu" ng-click="showModal()">Add from a device</button>';
					break;
				case 'edit':
				default:
					template = '<a title="Edit this button" ng-click="showModal()" ><i class="fa fa-fw fa-lg fa-pencil action-icon"></i></a>';
					break;
			}
			return template;
		},
		controller: function($scope, $element, $modal, $attrs, $q, toastr, Database, Systems, Devices) {
			///ip command DB로 setting된 Device라면.. ip command 편집을 위한 준비를 한다.
			$scope.ipCmd = {dispType:'none', dispType_prev:'none', dispString:''};

			var editModal = null;

			if('add-from-navi' == $attrs.content)
			{
				editModal = $modal({ scope: $scope, title: 'Function Navigator', placement: 'top', template:'views/modal-tpls/function-navi.html', show:false});

				$scope.device = {};
				$scope.type = {};

				 var getCategories = function() {
					var d = $q.defer();
					Database.retreiveDeviceTypes().then(
						function(data) {
							d.resolve(data);
						},
						function(error) {
							toastr.error(error, 'Error');
							d.reject(error);
						}
					);
					return d.promise;
				};

				if(null == $scope.types) {
					getCategories().then(	function(data) {
						//console.log('categories=', data);
						$scope.types = data;
						if (!$scope.device.type) {
							$scope.device.type = {id: $scope.types[0].id, name: $scope.types[0].name, device: $scope.types[0].device};  // 기본값 설정
							$scope.device.brand = null;
							$scope.device.model = null;
							$scope.device.func = null;
							$scope.brands = null;
							$scope.models = null;
							$scope.deviceinfo = null;
							$scope.popular_models = null;

							getDeviceBrands();
						}
					}).catch(toastr.error);
				}

				var getDeviceBrands = function() {
					Database.retrieveDeviceBrands($scope.device.type.name).then(function(data) {
						//console.log('brands=', data);
						$scope.brands = Database.getBrands();
					}).catch(toastr.error);
				};

				var getDevicePopularModels = function() {
					
					Database.searchPopularModels($scope.device.type.name, $scope.device.brand.name).then(function(data) {
						console.log('models=', data);
						$scope.popular_models = Database.getDevices();

					}).catch(toastr.error);
				};

				var getDeviceInfo = function() {
					Database.getDeviceInfo($scope.device.type.name, $scope.device.brand.name, $scope.device.model.id, $scope.deviceData.type, $scope.device.model.type).then(function(data) {
						//console.log('deviceinfo=', data);
						$scope.deviceInfo = data;
					}).catch(toastr.error);
				};


				$scope.selectCategory = function(category) {
					$scope.device.type = category;
					$scope.device.brand = null;
					$scope.device.model = null;
					$scope.device.func = null;
					$scope.brands = null;
					$scope.models = null;
					$scope.deviceinfo = null;
					getDeviceBrands();
				}

				$scope.selectBrand = function(brand) {
					$scope.device.brand = brand;
					//getDevicePopularModels();
				}

				$scope.selectModel = function(model) {
					$scope.device.model = model;
					getDeviceInfo();
				}				

				$scope.selectFunction = function(func) {
					$scope.device.func = func;
					//console.log('func=', func);
				}
			
			}
			else if('add-from-device' == $attrs.content)
			{
				editModal = $modal({ scope: $scope, title: 'Device Navigator', placement: 'top', template:'views/modal-tpls/device-navi.html', show:false});

				$scope.alias = {};
				$scope.buttons = [];

				if(!$scope.devices) {
					// room 정보 얻어와서 저장
					Systems.updateRoomDevices($scope.roomId).then(function(data) {
						var roomDevices = Systems.getRoomDevices();
						$scope.devices = roomDevices.devices;

						///dev_type이 twoway(1)인 device를 모두 제거.
						var item = null;
						while(item = _.where($scope.devices, {'dev_type': 1})[0]) {
							var idx = $scope.devices.indexOf(item);
							$scope.devices.splice(idx, 1);
						} 
						console.log('$scope.devices=', $scope.devices);

						console.log('$scope.alias.device=', $scope.alias.device);

						if (!$scope.alias.device) {
							$scope.alias.device = $scope.devices[0];  // 기본값 설정
						}

						$scope.alias.func = $scope.alias.device.funcs[0];
					})
					.catch(toastr.error);
				}


				$scope.selectDevice = function(device) {
					$scope.alias.device = device;
					$scope.alias.func = $scope.alias.device.funcs[0];
				}

				$scope.selectFunction = function(func) {
					$scope.alias.func = func;
					console.log('$scope.alias.func=', $scope.alias.func);
				}

			}
			else	{
				editModal = $modal({ scope: $scope, title: 'Edit this button', placement: 'top', template:'views/modal-tpls/device-edit-btn.html', show:false});
			}

			//Useful Functions
			function checkBin(n){return/^[01]{1,64}$/.test(n)}
			function checkDec(n){return/^[0-9]{1,64}$/.test(n)}
			function checkHex(n){return/^[0-9A-Fa-f]{1,64}$/.test(n)}
			function pad(s,z){s=""+s;return s.length<z?pad("0"+s,z):s}
			function unpad(s){s=""+s;return s.replace(/^0+/,'')}

			//Decimal operations
			function Dec2Bin(n){if(!checkDec(n)||n<0)return 0;return n.toString(2)}
			function Dec2Hex(n){if(!checkDec(n)||n<0)return 0;return n.toString(16)}

			//Binary Operations
			function Bin2Dec(n){if(!checkBin(n))return 0;return parseInt(n,2).toString(10)}
			function Bin2Hex(n){if(!checkBin(n))return 0;return parseInt(n,2).toString(16)}

			//Hexadecimal Operations
			function Hex2Bin(n){if(!checkHex(n))return 0;return parseInt(n,16).toString(2)}
			function Hex2Dec(n){if(!checkHex(n))return 0;return parseInt(n,16).toString(10)}		

			function transferFromAscii(strData)
			{
				var strLen = strData.length;
				var byteData = [];				
				var byteValue;
				var strHex;
				for(var i = 0; i < strLen; i++)
				{
					if(strData.charAt(i) == '\\')
					{
						if(strData.charAt(i+1) ==  'x' && i+3 < strLen)
						{
							strHex = strData.substr(i+2, 2);
							if(checkHex(strHex))
							{
								byteValue = parseInt(strHex, 16);
								//console.log('byteValue=', byteValue);
								byteData.push(byteValue);
							}
							else{
								//console.log('error data=', strHex);
							}

							i+=3;
						}
						else if(strData.charAt(i+1)  == '\\')
						{
							byteValue = '\\';
							//console.log('byteValue=', byteValue);
							byteData.push(byteValue);

							i++;
						}
					}
					else
					{
						byteValue = strData.charCodeAt(i);
						//console.log('byteValue=', byteValue);
						byteData.push(byteValue);
					}					
				}

				//console.log('byteData=', byteData);

				return byteData;
			}

			function transferFromLowHex(strData)
			{
				var byteData = [];				
				var byteValue;
				var strHex;
				//console.log('strData=', strData);
				for(var i = 0; i < strData.length; i+=2)
				{
					strHex = strData.substr(i, 2);

					if(checkHex(strHex))
					{
						byteValue = parseInt(strHex, 16);
						//console.log('byteValue=', byteValue);
						byteData.push(byteValue);
					}
					else{
						//console.log('error data=', strHex);
					}
				}

				//console.log('byteData=', byteData);

				return byteData;
			}

			function transferFromHex(strData)
			{
				var byteData = [];				
				var byteValue;
				var strHex;
				var arrHex = strData.split(',');
				for(var i = 0; i < arrHex.length; i++)
				{
					strHex = arrHex[i];
					strHex = strHex.trim();

					if(checkHex(strHex))
					{
						byteValue = parseInt(strHex, 16);
						//console.log('byteValue=', byteValue);
						byteData.push(byteValue);
					}
					else{
						//console.log('error data=', strHex);
					}
				}

				//console.log('byteData=', byteData);

				return byteData;
			}

			function transferFromDec(strData)
			{
				var byteData = [];				
				var byteValue;
				var strDec;
				var arrDec = strData.split(',');
				for(var i = 0; i < arrDec.length; i++)
				{
					strDec = arrDec[i];

					strDec = strDec.trim();
					if(checkHex(strDec))
					{
						byteValue = parseInt(strDec, 10);
						//console.log('byteValue=', byteValue);
						byteData.push(byteValue);
					}
					else{
						//console.log('error data=', strDec);
					}
				}

				//console.log('byteData=', byteData);

				return byteData;
			}

			function transferToAscii(byteData)
			{
				var dispString = '';
				var charValue;
				var byteValue;
				for(var i=0; i< byteData.length; i++)
				{
					byteValue = byteData[i];
					if( 0 != (charValue = String.fromCharCode(byteValue)) ) 
					{
						//console.log('charValue=', charValue);
						dispString += charValue;
					}
					else
					{
						//console.log('charValue=', charValue);
						dispString += '\\x' + pad(byteValue.toString(16), 2);
					}
				}

				//console.log('dispString=', dispString);

				return dispString;
			}

			function transferToHex(byteData)
			{
				var dispString = '';
				var strHex;
				var byteValue;
				for(var i=0; i< byteData.length; i++)
				{
					byteValue = byteData[i];
					strHex = byteValue.toString(16)

					//console.log('strHex=', strHex);
					dispString += strHex;
					if(i < byteData.length-1)
						dispString += ', ';
				}

				//console.log('dispString=', dispString);

				return dispString;
			}

			function transferToDec(byteData)
			{
				var dispString = '';
				var strDec;
				var byteValue;
				for(var i=0; i< byteData.length; i++)
				{
					byteValue = byteData[i];
					strDec = byteValue.toString(10)

					//console.log('strDec=', strDec);
					dispString += strDec ;
					if(i < byteData.length-1)
						dispString += ', ';
				}

				//console.log('dispString=', dispString);

				return dispString;
			}


			function transferToData(strData, type) {
				switch(type) {
					case 'ascii' :
						return transferFromAscii(strData);
						break;

					case 'hex' :
						return transferFromHex(strData);
						break;

					case 'dec' :
						return transferFromDec(strData);
						break;
				}
			}

			function toHexString(bytes) {
				return bytes.map(function(byte) {
					return pad((byte & 0xFF).toString(16), 2);
				}).join('');
			}			


			$scope.switchDispType = function(type) {
				var byteData ;
				$scope.ipCmd.dispType = type;
				//console.log('dispType_prev=', $scope.ipCmd.dispType_prev, 'dispType=', $scope.ipCmd.dispType);

				if($scope.ipCmd.dispString.length)
					byteData = angular.copy(transferToData($scope.ipCmd.dispString, $scope.ipCmd.dispType_prev));
				else
					byteData = angular.copy(transferFromLowHex($scope.newBtn.func.data));

				switch($scope.ipCmd.dispType) {
					case 'ascii' :
						$scope.ipCmd.dispString = transferToAscii(byteData);
						break;

					case 'hex' :
						$scope.ipCmd.dispString = transferToHex(byteData);
						break;

					case 'dec' :
						$scope.ipCmd.dispString = transferToDec(byteData);
						break;
				}

				$scope.ipCmd.dispType_prev = $scope.ipCmd.dispType;
			};

			$scope.changeFunction = function(func) {
				//console.log('changeFunction - func=', func);
				$scope.newBtn.func = func;

				if($scope.newBtn.func)
				{
					$scope.ipCmd.dispString = '';
					$scope.ipCmd.dispType = 'dec';
					$scope.ipCmd.dispType_prev = $scope.ipCmd.dispType;
					$scope.switchDispType($scope.ipCmd.dispType);
				}
			}



			function findAvailableId() {
				function filterLcdFuncs(id) {
					return id > 2048;
				}
				var db = $scope.deviceData.dbCon;
				var ids = _.pluck(db, 'id').filter(filterLcdFuncs); //ids is an empty array if no id is greater than 2048
				
				if (_.isEmpty(ids)) {
					return 2049;
				}

				ids = _.unique(ids).sort(function(a, b) {
					return a - b;
				});

				var min = _.min(ids) ;
				var counter = min;

				for (var i = 0; i < ids.length; i++) {
					if (ids[i] === counter) {
						counter++;
					} else {
						return counter;
					}
				}
				return counter;
			}

			function saveFromFunction() {
				_.assign($scope.newBtn, {display_text: $scope.device.func.caption});
				//console.log('$scope.newBtn=', $scope.newBtn);
				//console.log('$scope.device.func=', $scope.device.func);

				var func = { 
					id: $scope.newBtn.id < 8192 ? $scope.newBtn.id : findAvailableId(),
					name: $scope.device.func.caption, 
					data: $scope.device.func.cmd,
					type: 0,
					custom: 0,
					press_hold: 1,
					repeat_macro: $scope.deviceData.repeat.macro,
					repeat_min: $scope.deviceData.repeat.min,
					room_id: $scope.newBtn.room_id,
					device_id: $scope.newBtn.device_id
				};

				var device_id = parseInt($scope.deviceData.id, 10);
				var macro = [{type: 1, device_id: device_id}];

				var btn = {
					image_name: '',
					press_hold: func.press_hold ? true:false,
					device_id: func.device_id,
					room_id: func.room_id,
					hidden_option: 0,
					activity: '',
					popup: 0,
					func: func,
					macro: macro
				};

				_.assign($scope.newBtn, btn);

				$scope.deviceData.dbCon.push(func);
				//console.log('btn=', btn);
				//console.log('$scope.newBtn=', $scope.newBtn);
				//console.log('$scope.deviceData=', $scope.deviceData);
			}   

			function saveFromDevice() {
				var macro = [{ 
					type: 6,
					device_id: $scope.alias.device.id,
				}];

				_.assign($scope.newBtn, {display_text: $scope.alias.func.name});
				_.assign($scope.newBtn, {func: $scope.alias.func});
				_.assign($scope.newBtn, {macro: macro});

				//console.log('btn=', btn);
				//console.log('$scope.newBtn=', $scope.newBtn);
			}   


			function showModal() {
				$scope.newBtn = angular.copy($scope.selectedBtn);
				//console.log('showModal - $scope.newBtn=', $scope.newBtn);
				if($scope.newBtn.func)
				{
					$scope.ipCmd.dispString = '';
					$scope.ipCmd.dispType = 'dec';
					$scope.ipCmd.dispType_prev = $scope.ipCmd.dispType;
					$scope.switchDispType($scope.ipCmd.dispType);
				}
				else if('add-from-navi' == $attrs.content)
				{
					$scope.device.brand = null;
					$scope.device.model = null;
					$scope.device.func = null;
					$scope.models = null;
					$scope.deviceinfo = null;
				}

				editModal.$promise.then(editModal.show);
			}
			function hideModal() {
				editModal.$promise.then(editModal.hide);
			}

			$scope.showModal = showModal;

			$scope.edit = function(oldValue, newValue) {
				//console 에 oldValue와 newValue가 동일한 값이 출력됨. 아래의 _.assign(oldValue, newValue);의 영향인 것 같음.
				//console.log('edit - oldValue=',oldValue);
				//console.log('edit - newValue=',newValue);


				
				if('add-from-navi' == $attrs.content)				///function navigator를 통한 add button
				{
					 saveFromFunction();
				}
				else if('add-from-device' == $attrs.content)				///device navigator를 통한 add button
				{
					 saveFromDevice();
				}
				else if ($scope.deviceData.type == 2 && newValue.macro[0].type == 1)				///device data type이 ip type인 경우
				{
					var byteData =  angular.copy(transferToData($scope.ipCmd.dispString, $scope.ipCmd.dispType));
					//console.log('edit - newValue.func.data=', newValue.func.data);
					newValue.func.data = toHexString(byteData);
					//console.log('edit - newValue.func.data=', newValue.func.data);

					var dbCommand = _.find($scope.deviceData.dbCon, {id: newValue.func.id });

					if (dbCommand) {
						//console.log('edit-dbCommand=', dbCommand);
						_.assign(dbCommand, { data: newValue.func.data });
					}
				}
				
				if(newValue.func) {
					if (!newValue.hasOwnProperty('press_hold')) {
						newValue.press_hold = newValue.func.press_hold ? true:false;
					}

					if (!newValue.hasOwnProperty('image_name')) {
						newValue.image_name = '';
					}

					if (!newValue.hasOwnProperty('device_id')) {
						newValue.device_id = newValue.func.device_id;
					}

					if (!newValue.hasOwnProperty('room_id')) {
						newValue.room_id = newValue.func.room_id;
					}

					if (!newValue.hasOwnProperty('hidden_option')) {
						newValue.hidden_option = 0;
						newValue.activity = '';
						newValue.popup = 0;
					}
				}
				
				_.assign(oldValue, newValue);

				hideModal();
			};
			
		}
	};
});
'use strict';

app.directive('deviceBtnMove', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      ngModel: '=',
      selectedBtn: '=',
      exists: '='
    },
    template: '<a title="Move button to another page" ng-click="showModal()"><i class="fa fa-fw fa-lg fa-exchange action-icon"></i></a>',
    controller: function($scope, $element, $modal) {
      var moveModal = $modal({ scope: $scope, title: 'Move button to another page', placement: 'top', template:'views/modal-tpls/device-move-btn.html', show:false});
      
      function showModal() {
        $scope.popupDialog = {};
        moveModal.$promise.then(moveModal.show);
      }
      function hideModal() {
        moveModal.$promise.then(moveModal.hide);
      }

      $scope.showModal = showModal;

      $scope.swapButtons = function(source, dest) {
        var temp1 = _.omit(source, ['id', 'page_btn_idx', 'name', 'device_id', 'room_id']),
            temp2 = _.omit(dest, ['id', 'page_btn_idx', 'name', 'device_id', 'room_id']);

        console.log(temp1);
        console.log(temp2);

        for (var prop1 in temp1) {
          dest[prop1] = temp1[prop1];
        }

        for (var prop2 in temp2) {
          source[prop2] = temp2[prop2];
        }

        hideModal();
      };
      
    }
  };
});
'use strict';
//dependent upon on Bootstrap

app.directive('deviceInterface', function () {
	return {
		restrict: 'E',
		scope: {
			ngModel: '=',
			popup: '=',
			exists: '=',
			hasPageBtn: '=',
			currentState: '='
		},
		templateUrl: 'views/device-interface.html',
		controller: function($scope, $modal, Devices) {
			console.log($scope.ngModel);

			// 2016.06.24 HOMESET-422, MXHOMEPRO-122 안드로이드 버그로 인해 클릭 이벤트 분기 처리
			var isAndroid = /(android)/i.test(navigator.userAgent);
			var dragIndex;

			$scope.ngModel.currentMenuPage = 1;
			$scope.ngModel.currentHardPage = 1;
			$scope.ngModel.selectedBtn = null;
			$scope.ngModel.repeatSetting = 'default';
			$scope.ngModel.activeTab = 'menu';
			//$scope.ngModel.newBtn = {};
			$scope.ngModel.menu = {
					pages: []
			};
			$scope.ngModel.hard = {
				pages: Devices.getHardBtnPages()
			};

			if ($scope.exists) { 
				$scope.ngModel.menu.pages = Devices.getMenuBtnPages();
			} else {
				if ($scope.popup) {
					// if popup copy its current state into the model  
					$scope.ngModel.menu.pages = $scope.currentState.menu.pages; 
				} else {
					// else initialize the device interface push a blank menu page
					$scope.ngModel.menu.pages.push(Devices.makeBlankMenuPage({room_id: $scope.ngModel.room.id, repeat: { min: 3, macro: 3}}));
				}
			}


			$scope.isEmpty = function(val) { return _.isEmpty(val); };
			$scope.sortableOptions = {
				stop: function( event, ui ) {
					var buttonId = _(buttonsArray).pluck('id').min().value();
					console.log(buttonId);
					// 2016.06.24 HOMESET-422, MXHOMEPRO-122 안드로이드 버그로 인해 클릭 이벤트 분기 처리
					if(isAndroid){
						var _item = $(ui.item);
						if(dragIndex == $( 'li.lcd-grid-item' ).index( _item )){
							_item.find('>label').trigger('click');
						}
					}
					for (var i = 0; i < buttonsArray.length; i++) {
						buttonsArray[i].page_btn_idx = i;
						//buttonsArray[i].id = buttonId;
						//buttonId++;
					}
					$scope.$apply();
				},
				start : function(event, ui){
					dragIndex = $( 'li.lcd-grid-item' ).index( $(ui.item) );
				}
			};
			$scope.ngModel.deviceData = Devices.getCurrentData();

			$scope.ngModel.filteredMenuPage = $scope.ngModel.menu.pages[0];
			$scope.ngModel.filteredHardPage = $scope.ngModel.hard.pages[0];
			var buttonsArray = $scope.ngModel.menu.pages[0].btns;

			var menuPages = $scope.ngModel.menu.pages;
			var pageId = _(menuPages).pluck('id').max().value(),
					btnId = _(menuPages[menuPages.length - 1].btns).pluck('id').max().value()+1;

			console.log(pageId);
			console.log(btnId);



			$scope.addPage = function() {
				var btns = [];
				for (var i=0; i < 6; i++) {
					btns.push(Devices.makeBlankMenuButton(btnId, i, $scope.ngModel.deviceData));
					btnId++;
				}
				pageId++;
				console.log('pushing page with id of ' + pageId);
				$scope.ngModel.menu.pages.push({id: pageId, btns: btns});

			};

			$scope.hidePages = function() {
				var modal = $modal({
					scope: $scope,
					title: 'Hide pages',
					template: 'views/modal-tpls/hide-pages.html',
					show: false
				});

				modal.$promise.then(modal.show);
			};

			$scope.hidePagesSave = function() {

			};

			$scope.menuPageChanged = function(page) {
				$scope.ngModel.filteredMenuPage = $scope.ngModel.menu.pages[page - 1];
				buttonsArray = $scope.ngModel.menu.pages[page - 1].btns;
				$scope.ngModel.selectedBtn = null;
				console.log(buttonsArray);
			};

			$scope.hardPageChanged = function(page) {
				$scope.ngModel.filteredHardPage = $scope.ngModel.hard.pages[page - 1];
				buttonsArray = $scope.ngModel.hard.pages[page - 1].btns;
				$scope.ngModel.selectedBtn = null;
				console.log(buttonsArray);
			};

		}
	};
});

'use strict';
/**
 * @ngdoc directive
 * @name download
 * @description
 *  다운로드 메뉴 Start button directive
 */
app.directive('download', function download() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      systemId: '=',
      user: '=',
      text: '@'
    },
    template: '<button class="btn btn-primary" ng-click="start()">{{text}}</button>',
    controller: function ($scope, $interval, $modal, toastr, Systems) {
      $scope.percentage = 0;

      // 다운로드 modal popup
      var dlModal = $modal({ 
        scope: $scope, 
        backdrop: 'static', 
        template: 'views/modal-tpls/dl-popup.html', 
        show: false
      });

      // modal 보이기
      function showModal() {
        dlModal.$promise.then(dlModal.show);
      }

      // 다운로드 시작
      $scope.start = function () {
        showModal();
        $scope.isDone = false;
        $scope.percentage = 0;
        $scope.downloadStatus = 'Generating...';

        // Download Data Generate
        Systems.prepareDownload().then(function(response) {
          if(response.data.result) {

            var systemId = $scope.systemId;
            $scope.downloadStatus = 'Downloading...';

            // 서버와 통신할 때 다른 곳에서는 $http 를 사용하는데 여기서만 $.ajax 를 사용하고 있음
            // XMLHttpRequest 를 확장해서 progress (여기서는 다운로드 진행률) 을 얻음
            $.ajax({
                // 다운로드 progress 를 표시해주기 위해 XMLHttpRequest 를 확장해서 xhr 을 설정
                xhr: function() {
                  var xhr = new window.XMLHttpRequest();
                  xhr.addEventListener("progress", function(evt) {
                    var responseData = evt.currentTarget.response;
                    var lines = responseData.split(";");
                    var progress = 0;
                    if(lines.length) {
                      progress = lines[lines.length-1];
                    }   
                    else {
                      progress = 0;
                    }

                    if(progress.substr(0, 5) === 'ERROR') {
                      $scope.$apply(function() { 
                        $scope.downloadStatus = 'Failed to download.'; 
                        $scope.isDone = true;
                      });
                      return;
                    }

                    if(progress >= 100) {
                      //dlModal.hide();
                      $scope.$apply(function() {
                        $scope.isDone = true;
                        $scope.percentage = 100;
                        $scope.downloadStatus = 'Download finished.';
                      });
                      return;
                    }

                    $scope.$apply(function() { $scope.percentage = progress; });
                  }, false);

                  return xhr;
                },
                type: 'POST',
                url: '/api/download/server_start/' + systemId,    // 다운로드 시작 API
                headers: {
                  Authorization: 'Bearer ' + $scope.user.token
                },
                error: function (xhr, ajaxOptions, thrownError) {
                  $scope.$apply(function() { $scope.downloadStatus = 'Error'; });
                }
              });
          } else {
            $scope.downloadStatus = response.data.error;
          }
        }, function(error) {
          toastr.error('Please try again');
        });
      };

      // 다운로드 정지
      $scope.stop = function() {
        console.log('Fired stop function');

        Systems.stopDownload().then(function(response) {
          console.log(response);
        });
      };
    }
  };
});

'use strict';
/**
 * @ngdoc directive
 * @name eventDelete
 * @description
 *  system-overview ȭ�鿡�� scheduled event ����
 */
app.directive('eventDelete', function ($http, $templateCache, $state, $modal,  toastr, Systems, Rooms) {

  return {
    restrict: 'EA',
    replace: true,
    scope: {
      system: '=',
      room: '=',
      event: '='
    },

    link: function (scope, element, attrs) {
      var modal = $modal({
        scope: scope,
        title: 'Delete this event',
        template: 'delete-event.html',
        container: '#system-overview',
        show: false
      });

      element.on('click', function(event) {
        modal.$promise.then(modal.show);
      });

      scope.deleteEvent = function(id) {
        var jsonData = JSON.stringify({ id: id });

        // scheduled event ����
        Rooms.deleteEvent(scope.system.id, scope.room.id, jsonData)
          .then(function(data) {
            Systems.updateSystem(scope.system.id).then(function () {
              $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
            });
          })
          .catch(toastr.error);
      };
    }
  };
});





















'use strict';
//dependent upon on Bootstrap

app.directive('functionSelect', function() {
	return {
		restrict: 'E',
		replace: true,
		scope: {
			systemId: '=',
			room: '=',
			device: '='
		},
		templateUrl: 'views/function-select.html',
		controller: function($scope, Systems, Devices) {
			$scope.fs = { functions: [] };
			var device = Systems.getDevice($scope.room.id, $scope.device.device_id);
			var funcs = Devices.getFunctions($scope.device.device_id);

			// type:0 - power off
			// type:1 - power on
			// type:2 - input toggle
			function getCommandId(type, device, data) {
				var command;
				switch(type) {
					case 0:               
						command = _.where(data, {'id': device.meta_pwr_off})[0];
						break;
					case 1:
						command = _.where(data, {'id': device.meta_pwr_on})[0];
						break;
					case 2:
						command = _.where(data, {'id': device.meta_in_toggle})[0];
						break;
					default:
						break;
				}

				// type:0 또는 type:1 일때 command 를 찾지 못하면 power toggle 에서 다시 검사
				// jira issue: HCM-513
				if ((type == 0 || type == 1) && !command) {
					command = _.where(data, {'id': device.meta_pwr_toggle})[0];
				}

				return command;
			}


			if(funcs) {
				console.log('func load');
				var f = $scope.device.func;
				var funcData = _.where(funcs, {'id': _.isObject(f) ? f.id: f })[0];

				if (funcData) {
					$scope.device.func = funcData;
				} else {
					console.log('device func not set');    
					$scope.device.func = getCommandId($scope.device.type, device, funcs);
				}

				$scope.fs.functions = funcs;

			} else {
				// 해당 device 의 connected device(즉, command 목록) 얻기
				Devices.fetchFunctions($scope.room.id, $scope.device.device_id).
					then(function(data) {
						
						Devices.setFunctions($scope.device.device_id, data);
						var funcData = _.where(data, {'id': $scope.device.func})[0];

						if (funcData) {
							$scope.device.func = funcData;
						} else {
							console.log('device func not set');    
							$scope.device.func = getCommandId($scope.device.type, device, data);
						}
	
						$scope.fs.functions = data;        
					}).
					catch(function() {
						alert('Unable to retrieve connected data Please try again.');
					});
			}

		}
	};
});

'use strict';
//dependent upon on Bootstrap

app.directive('goBack', function () {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      state: '@',
      stateParams: '@'
    },
    template: '<button class="btn btn-primary" ng-click="goBack()"><i class="fa fa-caret-left"></i> Back</button>',
    controller: function($rootScope, $scope, $state) {
      $scope.goBack = function () {
        //if no state is provided the directive will check the rootScope for the previous state
        if (!$scope.state) {
          $state.go($rootScope.previousState.name, $rootScope.previousState.params);
        } else {
          $state.go($scope.state, $scope.stateParams);
        }
      };

    }
  };
});

'use strict';
//dependent upon on Bootstrap

app.directive('hardwareInfo', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      device: '='
    },
    template: '<a title="{{device.name}} Info" ng-click="showInfoModal()"><i class="fa fa-fw fa-info-circle"></i></a>',
    controller: function($rootScope, $scope, $templateCache, $state, $timeout, $modal, toastr, Systems) {
      
      var infoModal = $modal({ scope: $scope, 
                               title: $scope.device.name + ' Info', 
                               template: 'hardware-info.html', 
                               show: false });
      
      $scope.showInfoModal = function() {
        $scope.isLoading = true;
        $scope.isSuccess = false;
        $scope.isError = false;

        infoModal.$promise.then(infoModal.show);

        //$timeout(function() {
          Systems.searchHardware(false, $scope.device.type, {mac: $scope.device.mac})
          .then(function(data) {
            $scope.isLoading = false;
            $scope.isSuccess = true;
            console.log(data);
            $scope.searchedDevice = _.find(data.searchedDevices, function(item) {
              return item.mac === $scope.device.mac;
            });
          })
          .catch(function(error) {
            $scope.isLoading = false;
            $scope.isError = true;
          });
          
        //}, 4000);
      };


    }
  };
});
'use strict';
/**
 * @ngdoc directive
 * @name hcmDelete
 * @description
 *  system-overview 화면에서 room/base station/remote/device 삭제
 */
app.directive('hcmDelete', function ($rootScope, $http, $templateCache, $state, $modal, toastr, Systems, Rooms) {
  
  return {
    restrict: 'EA',
    replace: true,
    scope: {
      room: '=',
      bstation: '=',  
      remote: '=',
      device: '=',
      type: '@' //string 
    },

    link: function (scope, element, attrs) {
      var modal,
          type = scope.type.toLowerCase();

      switch (scope.type) {
        case 'room':
          modal = $modal({
            scope: scope,
            title: 'Delete this room',
            template: 'delete-room.html',
            container: '#system-overview',
            show: false
          });

          scope.selections = {
            room: angular.copy(scope.room)
          };
          break;
        case 'bstation':
          modal = $modal({
            scope: scope,
            title: 'Delete this controller',
            template: 'delete-bstation.html',
            container: '#system-overview',
            show: false
          });

          scope.selections = {
            room: angular.copy(scope.room),
            bstation: angular.copy(scope.bstation)
          };
          break;

        case 'remote':
          modal = $modal({
            scope: scope,
            title: 'Delete this remote',
            template: 'delete-remote.html',
            container: '#system-overview',
            show: false
          });

          scope.selections = {
            room: angular.copy(scope.room),
            remote: angular.copy(scope.remote)
          };

          break;
        case 'device':
          modal = $modal({
            scope: scope,
            title: 'Delete this device',
            template: 'delete-device.html',
            container: '#system-overview',
            show: false
          });

          scope.selections = {
            room: angular.copy(scope.room),
            device: angular.copy(scope.device)
          };
          break;

        case 'twoway_device':
          modal = $modal({
            scope: scope,
            title: 'Delete this device',
            template: 'delete-twoway-device.html',
            container: '#system-overview',
            show: false
          });

          scope.selections = {
            room: angular.copy(scope.room),
            device: angular.copy(scope.device)
          };
          break;
        
        case 'default':
          throw new Error('There was an error retrieving information. Please try again. If the error continues please log out and then log in again.');
      }


      element.on('click', function(event) {
        if (scope.type === 'bstation') {
          var assignedDevices = scope.room.devices.filter(function(device) {
            return device.target_addr === scope.bstation.mac;
          });

          var len = assignedDevices.length;
          if (len) {     
            for (var str='', i=0; i<len; i++) {
              str += '<li>' + assignedDevices[i].name + '</li>';
            }
            return $modal({
              title: 'Cannot delete this base station', 
              content: 'You cannot delete <strong class="text-primary">' + scope.bstation.name + '</strong> until you unassign the following devices connected to it. <ul class="margin-top-md">'+ str +'</ul>',
              html: true
            });
          }
        } 

        modal.$promise.then(modal.show);
      });



      scope.deleteRoom = function(room) {
        var currentSystem = Systems.getCurrentSystem();

        // room 삭제
        Rooms.delete(room.id)
        .then(function(data) {    
          var roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id });
          currentSystem.rooms.splice(roomIndex, 1);
          console.log(currentSystem);
          Systems.loadSystem(currentSystem);
          if (Systems.currentRoom.id === room.id) {
            Systems.currentRoom.id = null;
          }
          $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
        })
        .catch(toastr.error);
      };
   

      scope.deleteBstation = function(room, bstation) {

        var currentSystem = Systems.getCurrentSystem();

        // base station 을 해당 room 에서 삭제
        Rooms.baseStations('delete',room.id, {mac: bstation.mac})
          .then(function(data) {    
            var roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id });
            var bstationIndex = _.findIndex(currentSystem.rooms[roomIndex].bstations, { 'id': bstation.id });
            currentSystem.rooms[roomIndex].bstations.splice(bstationIndex, 1);
            console.log(currentSystem);
            Systems.loadSystem(currentSystem);
            $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
          })
          .catch(toastr.error);
      };


      scope.deleteRemote = function(room, remote) {

        var currentSystem = Systems.getCurrentSystem();

        // remote 를 해당 room 에서 삭제
        Rooms.delRemote(room.id, {mac: remote.mac})
          .then(function(data) {    
            var roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id });
            var remoteIndex = _.findIndex(currentSystem.rooms[roomIndex].remotes, { 'id': remote.id });
            currentSystem.rooms[roomIndex].remotes.splice(remoteIndex, 1);
            console.log(currentSystem);
            Systems.loadSystem(currentSystem);
            $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
          })
          .catch(toastr.error);
      };


      scope.deleteDevice = function(room, device, twowayDevice) {
        var currentSystem = Systems.getCurrentSystem();

        var url;
        if ($rootScope.virtualEditor) {
          url = '/api/dealer/device/delete/' + room.id + '/' + device.id;
        } else {
          url = '/api/device/delete/' + room.id + '/' + device.id;
        }

        // device 삭제 API 호출
        $http({
          method: 'POST',
          url: url
        }).
          success(function(data) {
            if(data.result) {
              var roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id });
              var deviceIndex = _.findIndex(currentSystem.rooms[roomIndex].devices, { 'id': device.id });
              currentSystem.rooms[roomIndex].devices.splice(deviceIndex, 1);
              console.log(currentSystem);
              Systems.loadSystem(currentSystem);
              $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
            }
            else {
              toastr.error(data.error);
            }
          }).
          error(toastr.error);
      };

      scope.deleteTwowayDevice = function(room, device) {
        var currentSystem = Systems.getCurrentSystem();

        // device 삭제 API 호출
        $http({
          method: 'POST',
          url: '/api/twoway_device/delete/' + room.id + '/' + device.id
        }).
          success(function(data) {
            if(data.result) {
              var roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id });
              var deviceIndex = _.findIndex(currentSystem.rooms[roomIndex].twoway_devices, { 'id': device.id });
              currentSystem.rooms[roomIndex].twoway_devices.splice(deviceIndex, 1);
              console.log(currentSystem);
              Systems.loadSystem(currentSystem);
              $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
            }
            else {
              toastr.error(data.error);
            }
          }).
          error(toastr.error);
      };
    }
  };
});



  
  



  


  


  
  

  



'use strict';
/**
 * @ngdoc directive
 * @name hcmEdit
 * @description
 *  system-overview 화면에서 system/room/base station/device 정보 변경
 */
app.directive('hcmEdit', function ($rootScope, $http, $templateCache, $state, $modal, toastr, Devices, Systems, Rooms) {
	
	return {
		restrict: 'EA',
		replace: true,
		scope: {
			system: '=',
			room: '=',
			bstation: '=',
			device: '=',
			ttype: '=',
			type: '@' //takes in a String for edit type (i.e. system, room, device, bstation)
		},

		link: function (scope, element, attrs) {
			var modal, type = scope.type.toLowerCase();

			scope.lightLevels = [ {'value': 0, 'label': 'Off'}, {'value': 1, 'label': 'Low'}, {'value': 2, 'label': 'Medium'}, {'value': 3, 'label': 'High'}];
			scope.irPortOptions = [{name:'All', value:255}, {name:'1', value:1}, {name:'2', value:2}, {name:'3', value:3}, {name:'4', value:4}];

			scope.ir = {target:0, port:255};

			switch (scope.type) {
				case 'system':
					modal = $modal({
						scope: scope,
						title: 'Edit this system',
						template: 'edit-system.html',
						container: '#system-overview',
						show: false
					});

					scope.selections = {
						system: angular.copy(scope.system)
					};
					break;
				case 'room':
					modal = $modal({
						scope: scope,
						title: 'Edit this room',
						template: 'edit-room.html',
						container: '#system-overview',
						show: false
					});

					scope.selections = {
						room: angular.copy(scope.room)
					};
					break;
				case 'device':
					modal = $modal({
						scope: scope,
						title: 'Edit this device',
						//placement: 'top',
						template: 'edit-device.html',
						container: '#system-overview',
						show: false
					});

					scope.selections = {
						room: angular.copy(scope.room),
						device: angular.copy(scope.device)
					};
					scope.selections.device.ramp_start /= 1000;
					scope.selections.device.ramp_speed /= 1000;

					scope.ir.target = (scope.selections.device.target_port ? 1:2);
					scope.ir.port = (scope.selections.device.target_port  ? scope.selections.device.target_port :255);

					console.log('scope.ir.port = ', scope.ir.port);

          if ($rootScope.virtualEditor) {
            scope.wireless_ir_port = 1;
          } else {
            if (scope.room.bstations[0] && scope.room.bstations[0].type) {
              var bstationType = scope.room.bstations[0].type,
                irInfo = _.find(scope.$parent.types, {name: bstationType});

              scope.wireless_ir_port = irInfo.wireless_ir_port;

              if (irInfo.wired_ir_port_all && irInfo.wired_ir_port == 4) {
                scope.irPortOptions = [{name: 'All', value: 255}, {name: '1', value: 1}, {name: '2', value: 2}, {
                  name: '3',
                  value: 3
                }, {name: '4', value: 4}];
              } else if (irInfo.wired_ir_port_all && irInfo.wired_ir_port == 5) {
                scope.irPortOptions = [{name: 'All', value: 255}, {name: '1', value: 1}, {name: '2', value: 2}, {
                  name: '3',
                  value: 3
                }, {name: '4', value: 4}, {name: '5', value: 5}];
              } else if (!irInfo.wired_ir_port_all && irInfo.wired_ir_port == 4) {
                scope.irPortOptions = [{name: '1', value: 1}, {name: '2', value: 2}, {name: '3', value: 3}, {
                  name: '4',
                  value: 4
                }];
              } else if (!irInfo.wired_ir_port_all && irInfo.wired_ir_port == 5) {
                scope.irPortOptions = [{name: '1', value: 1}, {name: '2', value: 2}, {name: '3', value: 3}, {
                  name: '4',
                  value: 4
                }, {name: '5', value: 5}];
              }
            }
          }

					break;
				case 'twoway_device':
          scope.trfZwLink = $rootScope.env.trfZwLink;
          scope.urcPortalUrl = $rootScope.env.urcPortalUrl;

					modal = $modal({
						scope: scope,
						title: 'Edit this device',
						//placement: 'top',
						template: 'edit-twoway-device.html',
						container: '#system-overview',
						show: false
					});

					scope.selections = {
						room: angular.copy(scope.room),
						device: angular.copy(scope.device)
					};

					scope.getTwowayVersion = function(){

						// fw_version
						var currentSystem = Systems.getCurrentSystem();

            var masterBstation;
            _.each(currentSystem.rooms, function(room) {
              if (!masterBstation) {
                masterBstation = _.where(room.bstations, {
                  master: 1
                })[0];
              }
            });

						Systems.getFirmwareVersion(masterBstation.type, scope.selections.device.model_id, currentSystem.id)
							.then(function(data) {
								scope.selections.device.fw_version = data.version;
								scope.selections.device.fw_run_version = data.run_version;

								scope.selectionsInitial = angular.copy(scope.selections);

							})
							.catch(function(error) {
								//toastr.error(error);
							});
					}

          // MAC
					if (scope.ttype & 0x0001) {
						var targetAddrStr = scope.selections.device.target_addr;
						targetAddrStr = targetAddrStr.toUpperCase();		// MAC address 대문자로 변경
						targetAddrStr = targetAddrStr.replace(/:/g, '');
						targetAddrStr = targetAddrStr.slice(0,10).replace(/(.{2})/g,'$1:') + targetAddrStr.slice(10, 12);		// : 추가

						scope.selections.device.target_addr = targetAddrStr;

						// search
						if (scope.ttype & 0x00010000) {
							scope.selections.device.type = 'discovery';
						}
						// mac
						else {
							scope.selections.device.type = 'mac';
						}
					} else {
						// IP
						if (scope.ttype & 0x0002) {
							scope.selections.device.type = 'ip';

							if (!scope.selections.device.ip) {
								scope.selections.device.ip = angular.copy(scope.selections.device.target_addr).split(':')[0];
							}
							if (!scope.selections.device.port) {
								scope.selections.device.port = +angular.copy(scope.selections.device.target_addr).split(':')[1];
							}
						}
						// service
						else if (scope.ttype & 0x0004) {
							scope.selections.device.type = 'service';
						}
					}

          // TRF-ZW data update
          scope.updateTrfzwData = function() {
            _.each(scope.$parent.system.rooms, function(room) {
              var trfzw = _.find(room.twoway_devices, {model: 'TRF-ZW1'});
              if (trfzw) {
                Devices.updateTwowayDevice(room.id, trfzw.id)
                  .then(function(data) {
                    trfzw.data = data;
                  }, function() {
                    var modal = $modal({
                      container: '.editor-container',
                      template: 'views/modal-tpls/connection-problem.html',
                      show: false
                    });

                    modal.$promise.then(modal.show);
                  })
                  .catch(toastr.error);

                return false;
              }
            });

            var updateModal = $modal({
              container: '.editor-container',
              template: 'views/modal-tpls/update-trfzw-data.html',
              show: false
            });

            updateModal.$promise.then(updateModal.show);
            setTimeout(function() {
              updateModal.$promise.then(updateModal.hide);
            }, 3000);
          };

					break;
				case 'bstation':
					modal = $modal({
						scope: scope,
						title: 'Edit this controller',
						template: 'edit-bstation.html',
						container: '#system-overview',
						show: false
					});

					scope.selections = {
						room: angular.copy(scope.room),
						bstation: angular.copy(scope.bstation)
					};
					break;
				case 'default':
					throw new Error('There was an error retrieving information. Please try again. If the error continues please log out and then log in again.');
			}

			scope.editSystem = function(system) {
				var currentSystem = Systems.getCurrentSystem();

				console.log('editSystem called');
				if (!_.isEqual(currentSystem, system)) {
					var jsonData = JSON.stringify( { name : system.name } );
					console.log(jsonData);
					Systems.editSystem(system.id, jsonData).
						then(function(data) {    
							currentSystem.name = system.name;
							Systems.loadSystem(currentSystem);
							$state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
						}).
						catch(toastr.error);
				}
			};

			scope.editRoom = function(room) {
				var currentSystem = Systems.getCurrentSystem();
				var roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id });
				var currentRoom = currentSystem.rooms[roomIndex];

				if (!_.isEqual(currentRoom, room)) {
					var jsonData = JSON.stringify( { name : room.name } );
					// room 이름 변경
					Rooms.edit(room.id, jsonData).
						then(function(data) {    
							currentRoom.name = room.name;
							Systems.loadSystem(currentSystem);
							$state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
						}).
						catch(toastr.error);
				}
			};


			scope.editBstation = function(room, bstation) {
        if ($rootScope.virtualEditor) {
          toastr.error('This base station cannot be renamed.');
        } else {
          var currentSystem = Systems.getCurrentSystem(),
            roomIndex = _.findIndex(currentSystem.rooms, {'id': room.id}),
            bstationIndex = _.findIndex(currentSystem.rooms[roomIndex].bstations, {'id': bstation.id}),
            currentBstation = currentSystem.rooms[roomIndex].bstations[bstationIndex];

          if (!_.isEqual(currentBstation, bstation)) {
            var jsonData = JSON.stringify({
              name: bstation.name,
              mac: bstation.mac,
              type: bstation.type,
              lightLevel: bstation.light_level
            });
            // base station 의 type, name, lightLevel 을 설정
            Rooms.baseStations('edit', room.id, jsonData).then(function (data) {
              currentBstation.name = bstation.name;
              currentBstation.light_level = bstation.light_level;
              Systems.loadSystem(currentSystem);
              $state.transitionTo($state.current, null, {reload: true, inherit: true, notify: true});
            }).catch(toastr.error);
          }
        }
			};



			scope.editDevice = function(room, device) {
				var currentSystem = Systems.getCurrentSystem(),
								roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id }),
							deviceIndex = _.findIndex(currentSystem.rooms[roomIndex].devices, { 'id': device.id }),
						currentDevice = currentSystem.rooms[roomIndex].devices[deviceIndex],
						clonedDevice = _.clone(device);

				if(clonedDevice.target_type === 1) {  
					console.log('ir.target = ', scope.ir.target);
					if(1 == scope.ir.target  )
						clonedDevice.target_port  = scope.ir.port ;
					else
						clonedDevice.target_port  = 0;
				}
				console.log('editDevice=', clonedDevice.target_port );
						
				clonedDevice.ramp_start *= 1000;
				clonedDevice.ramp_speed *= 1000;

				if (!_.isEqual(currentDevice, clonedDevice)) {
					var jsonData = JSON.stringify( {
						name : clonedDevice.name,
						targetType : clonedDevice.target_type,
						targetAddr : clonedDevice.target_addr,
						targetPort: clonedDevice.target_port,
						repeatMin: clonedDevice.repeat_min,
						repeatMacro: clonedDevice.repeat_macro,
						rampStart: clonedDevice.ramp_start,
						rampSpeed: clonedDevice.ramp_speed,
						autoCr: clonedDevice.auto_cr
					});

					var url;
					if ($rootScope.virtualEditor) {
						url = '/api/dealer/device/edit/' + room.id + '/' + device.id;
					} else {
						url = '/api/device/edit/' + room.id + '/' + device.id;
					}

					// device 정보 변경 API 호출
					$http({
						method: 'POST',
						url: url,
						data : jsonData
					}).
					success(function(data) {
						if(data.result) {
							_.assign(currentDevice, clonedDevice);
							Systems.loadSystem(currentSystem);
							$state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
						}
						else {
							toastr.error(data.error);
						}
					}).
					error(toastr.error);
				}
			};

      scope.$watch('selections.device', function(newVal, oldVal) {
        if (newVal && typeof newVal.variables !== 'undefined' && typeof newVal.variables === 'object' && newVal.variables != null && newVal.variables.length) {
          newVal.hasVariables = true;
          newVal.varData = [];
          newVal.newVarData = {};

          _.each(newVal.variables, function(item) {
            if (item.attr.match('n')) {
              item.required = true;
            } else {
              item.required = false;
            }

            if (item.attr.match('p')) {
              item.type = 'password';
            } else if (item.attr.match('m')) {
              item.type = 'textarea';
            } else {
              item.type = 'text';
            }

            if (item.attr.match('r')) {
              item.readonly = true;
            } else {
              item.readonly = false;
            }

            if (item.name === 'username') {
              newVal.varUsername = item;
            } else if (item.name === 'password') {
              newVal.varPassword = item;
            } else if (item.name !== 'device_port') {
              newVal.varData.push(item);
            }
          });
        }
      });

      scope.showModal = function(mode) {
        // edit parameter 하는 화면에서 값이 미리 입력되어 있게 하기 위해
        if (mode === 'edit-twoway-username') {
          scope.selections.device.varNewUsername = angular.copy(scope.selections.device.varUsername.value);
        } else if (mode === 'edit-twoway-parameters') {
          _.each(scope.selections.device.varData, function(item) {
            if (!item.attr.match('p')) {
              scope.selections.device.newVarData[item.name] = item.value;
            }
          });
        }
        
        var templateUrl = 'views/modal-tpls/system-overview/' + mode + '.html';

        var modal = $modal({
          scope: scope,
          template: templateUrl,
          container: 'body',
          show: false
        });
        modal.$promise.then(modal.show);
      };

      scope.saveUsername = function() {
        scope.selections.device.varUsername.value = angular.copy(scope.selections.device.varNewUsername);
        scope.selections.device.varPassword.value = angular.copy(scope.selections.device.varNewPassword);
      };

      scope.saveParameters = function() {
        _.each(scope.selections.device.varData, function(item) {
          item.value = scope.selections.device.newVarData[item.name];
        });
      };

      scope.editTwowayDevice = function(room, device, targetType) {
				var currentSystem = Systems.getCurrentSystem(),
					roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id }),
					deviceIndex = _.findIndex(currentSystem.rooms[roomIndex].twoway_devices, { 'id': device.id }),
					currentDevice = currentSystem.rooms[roomIndex].twoway_devices[deviceIndex],
					clonedDevice = _.clone(device);

				var d = {
						name: scope.selections.device.name,
						targetType: scope.selections.device.target_type,
						targetAddr: '""'
					};

				// MAC
				if (targetType & 0x0001) {
					// search
					if (targetType & 0x00010000) {
						d.targetAddr = scope.selections.device.target_addr;
					}
					// mac
					else {
						d.targetAddr = scope.selections.device.target_addr;
					}

					d.targetAddr = d.targetAddr.replace(/:/g, '');
          d.targetAddr = d.targetAddr.toUpperCase();
				} else {
					// IP
					if (targetType & 0x0002) {
						d.targetAddr = scope.selections.device.ip + ':' + scope.selections.device.port;
					}
					// service
					else if (targetType & 0x0004) {

					}
				}

        // variables 가 있는 device 인 경우
        if (scope.selections.device.hasVariables) {
          scope.selections.device.variables = [];
          if (scope.selections.device.varUsername) {
            var obj = angular.copy(scope.selections.device.varUsername);
            delete(obj['$$hashKey']);
            delete(obj.required);
            delete(obj.readonly);
            delete(obj.type);

            scope.selections.device.variables.push(obj);
          }
          if (scope.selections.device.varPassword) {
            var obj = angular.copy(scope.selections.device.varPassword);
            delete(obj['$$hashKey']);
            delete(obj.required);
            delete(obj.readonly);
            delete(obj.type);

            scope.selections.device.variables.push(obj);
          }
          _.each(scope.selections.device.varData, function(item) {
            var obj = angular.copy(item);
            delete(obj['$$hashKey']);
            delete(obj.required);
            delete(obj.readonly);
            delete(obj.type);

            scope.selections.device.variables.push(obj);
          });

          d.variables = scope.selections.device.variables;
        } else {
          d.variables = '""';
        }

				var jsonData = JSON.stringify(d);

				// device 정보 변경 API 호출
				$http({
					method: 'POST',
					url: '/api/twoway_device/edit/' + room.id + '/' + device.id,
					data : jsonData
				}).
					success(function(data) {
						if(data.result) {
							_.assign(currentDevice, clonedDevice);
							Systems.loadSystem(currentSystem);
							$state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
						}
						else {
							toastr.error(data.error);
						}
					}).
					error(toastr.error);
			};

			element.on('click', function(event) {
				// HOMESET-392 이슈 처리로 인해 모달창 동작 분기.
				if(scope.type == 'twoway_device'){
					scope.getTwowayVersion();
				}
				modal.$promise.then(modal.show);
			});

			scope.selectionsInitial = angular.copy(scope.selections);

			scope.cancelEdit = function() {
				scope.selections = angular.copy(scope.selectionsInitial);
			};




		}
	};
});



	

	

	



'use strict';

app.directive('homeBtnSetting', function() {
	return {
		restrict: 'EA',
		replace:true,
		scope: {
			system: '='
		},
		template: '<a ng-click="showHomeButtonSettingModal()">Change Home button behavior for remotes</a>',
		controller: function($scope, $modal, toastr, Systems) {
			$scope.homeBtn = {option:0};
			$scope.homeBtn.option = $scope.system.home_btn_option;
			var homeButtonSettingModal = $modal({
				scope: $scope,
				template: 'views/modal-tpls/home-btn-setting.html',
				show: false
			});

			$scope.showHomeButtonSettingModal = function () {
				homeButtonSettingModal.$promise.then(homeButtonSettingModal.show);       
			};

			$scope.setHomeButtonBehavior = function() {
				var data = JSON.stringify({ option: $scope.homeBtn.option});
				Systems.setHomeButton(data).then(function(data) {
					//console.log('data=', data);
					$scope.system.home_btn_option = angular.copy($scope.homeBtn.option);
					Systems.loadSystem($scope.system);
				}).catch(function(error) {
					toastr.error(error, 'Error');
				});
			};

		}
	};
});
'use strict';

app.directive('learnCommand', function () {
	return {
		restrict: 'EA',
		scope: {
			systemId: '=',
			model: '=',
			selectedBtn: '='
		},
		template: '<button type="button" class="btn btn-menu" ng-click="showLearnModal()">Learn!</button>',
		replace: true,
		controller: function($scope, $q, $timeout, $modal, Learning) {
			var learnModal = $modal({scope: $scope, backdrop: 'static', template: 'views/modal-tpls/learn-proc.html', show: false});
			var request;

			$scope.learnedData = null;

			function handleError(error) {
				console.log(error);
				//if (!error) { error='Learning process has been stopped.'}
				$scope.status = error ? '<span class="text-danger">' +  error + '</span>' : 'Learning process has been stopped.';
				$scope.retry = true;
				$scope.stop = false;
			}

			function makingRequest() {
				console.log('Called makingRequest');
				$scope.retry = false;
				$scope.stop = true;
				$scope.next = false;
				$scope.save = false;
				$scope.learnedData = null;
			}

			function learn() {
				console.log('Request being made: ', request);
				$scope.status = 'Attempting to start learning mode...';
							
				if ($scope.selectedBtnCopy.id < 8192 && !$scope.selectedBtnCopy.display_text) {
					$scope.selectedBtnCopy.display_text = angular.copy($scope.selectedBtnCopy.name);
					$scope.selectedBtnCopy.func = {};
					$scope.selectedBtnCopy.func.name = angular.copy($scope.selectedBtnCopy.name);
				}

				request = Learning.start($scope.systemId);
				makingRequest(); 
				
				request.promise.then(function(data) {
					$scope.status = '<span class="text-success">Ready to Learn.</span>';
					return $scope.systemId;
				})
				.then(function(id) {
					$scope.status = '<i class="fa fa-spinner"></i>&nbsp;&nbsp;Learning';
					request = Learning.attempt(id);
					return request.promise;
				})
				.then(function(data) {
					console.log(data);
					$scope.learnedData = data;
					$scope.status = '<span class="text-success">Successfully learned.</span>';
					$scope.next = true;
					$scope.save = true;
					$scope.retry = true;
					$scope.stop = false;
				})
				.catch(handleError);

			}


			function findAvailableId() {
				function filterLcdFuncs(id) {
					return id > 2048;
				}
				var db = $scope.model.deviceData.dbCon;
				var ids = _.pluck(db, 'id').filter(filterLcdFuncs); //ids is an empty array if no id is greater than 2048
				
				if (_.isEmpty(ids)) {
					return 2049;
				}

				ids = _.unique(ids).sort(function(a, b) {
					return a - b;
				});

				var min = _.min(ids) ;
				var counter = min;

				for (var i = 0; i < ids.length; i++) {
					if (ids[i] === counter) {
						counter++;
					} else {
						return counter;
					}
				}
				return counter;
			}

			function save() {
				_.assign($scope.selectedBtn, {display_text: $scope.selectedBtnCopy.display_text });

				var dbCommand = _.find($scope.model.deviceData.dbCon, {id: $scope.selectedBtnCopy.func.id });

				if (dbCommand){
					_.assign(dbCommand, { name: $scope.selectedBtnCopy.func.name, data: $scope.learnedData, type: 1 });
				} else {
					var func = { 
						id: $scope.selectedBtnCopy.id < 8192 ? $scope.selectedBtnCopy.id : findAvailableId(),
						name: $scope.selectedBtnCopy.func.name, 
						data: $scope.learnedData,
						type: 1,
						custom: 0,
						press_hold: 1,
						repeat_macro: $scope.model.deviceData.repeat.macro,
						repeat_min: $scope.model.deviceData.repeat.min,
						room_id: $scope.selectedBtnCopy.room_id,
						device_id: $scope.selectedBtnCopy.device_id
					};

					var btn = {
						image_name: '',
						press_hold: func.press_hold ? true:false,
						device_id: func.device_id,
						room_id: func.room_id,
						hidden_option: 0,
						activity: '',
						popup: 0,
						func: func
					};

					_.assign($scope.selectedBtn, btn);

					$scope.model.deviceData.dbCon.push(func);
				}
			}   

			function next() {
				var activeTab = $scope.model.activeTab;
				var pages = $scope.model[activeTab].pages;
				var btns = _.flatten(pages, 'btns');

				if (activeTab === 'menu') {   
					if ($scope.selectedBtn.page_btn_idx === 5) { 
						if ($scope.model.currentMenuPage !== pages.length) { 
							$scope.model.currentMenuPage++; 
							$scope.model.filteredMenuPage = $scope.model.menu.pages[$scope.model.currentMenuPage - 1];  
						} else { //if last menu page, go to hard btn pages
							$scope.model.activeTab = 'hard'; 
							$scope.model.currentHardPage = 1;             
							return next();
						}
					}
					$scope.selectedBtn =  _.find(btns, { 'id': $scope.selectedBtn.id+1 });
				} else {
					var index = _.findIndex(btns, $scope.selectedBtn);

					// if the currently selected hard btn is CH -, EXIT, or GREEN, it should move to the next page
					if ($scope.selectedBtn.id === 280 || $scope.selectedBtn.id === 307 || $scope.selectedBtn.id === 551 ) { 
						//if ($scope.model.currentPage !== pages.length) { 
						$scope.model.currentHardPage++; 
						$scope.model.filteredHardPage = $scope.model.hard.pages[$scope.model.currentHardPage - 1];         
					}

					$scope.selectedBtn = btns[index+1];
				}

				$scope.selectedBtnCopy = angular.copy($scope.selectedBtn);
			}

			$scope.showLearnModal = function() {
				$scope.stop = true;
				$scope.retry = false;
				$scope.next = false;
				$scope.save = false;

				$scope.selectedBtnCopy = angular.copy($scope.selectedBtn);
				learnModal.$promise.then(learnModal.show);
							
				learn();

			};

			$scope.changedBtnName = function() {
				//console.log($scope.learnCommandForm);
				//if ($scope.learnCommandForm.funcName.$pristine) {
					$scope.selectedBtnCopy.func.name = angular.copy($scope.selectedBtnCopy.display_text);
				//}
			};

			$scope.retryLearn = function() {
				$scope.status = 'Retrying...';
				learn();
			};

			$scope.saveLearn = function() {
				save();
				learnModal.hide();
			};

			$scope.stopLearn = function() {
				request.cancel('Learning process stopped');
				console.log('User cancelled request');
				learnModal.hide();
			};

			$scope.skipLearn = function() {
				request.cancel('Learning process stopped');
				console.log('User cancelled request');

				$timeout(function() {
					console.log('in timeout');
					next();
					learn();
					
				}, 500);
				
			};

			$scope.nextLearn = function() {
				save();
				next();
				learn();
			};
		}
	};
});
'use strict';

app.directive('newVariable', function ($rootScope, $modal, $timeout) {
	return {
		restrict: 'A',
		scope: {
			system: '=',
			newVar: '='
		},
		controller: function ($rootScope, $scope, $element, Systems, toastr) {
			$scope.variableTypes = [{name:'True False', value:0}, {name:'String', value:1}, {name:'Integer', value:2}];

			$scope.title = '';

			var modal = $modal({scope: $scope, template: 'views/modal-tpls/new-variable.html', show: false});

			
			$scope.addVariable = function () {

				var variable = {type: $scope.newVar.type, name:$scope.newVar.name, value: $scope.newVar.value};
				var data  = JSON.stringify(variable);

				var roomId = null;
				if ($rootScope.virtualEditor) {
					roomId = Systems.getCurrentRoom();
				}

				Systems.addVariable(data, roomId).then(function (data) {
					console.log('return variable id=', data);
					variable.id = data;
          if ($rootScope.virtualEditor) {
            $scope.system.rooms[0].variables.push(variable);
          } else {
            $scope.system.variables.push(variable);
          }

					console.log('$scope.system.variables=', $scope.system.variables);
				}).catch(function(error) {
					toastr.error(error, 'Error');
				});
				modal.$promise.then(modal.hide);
			}; 

			$element.on('click', function(event) {
				event.preventDefault();
				$scope.title = 'New Variable: ' + $scope.variableTypes[$scope.newVar.type].name;
				modal.$promise.then(modal.show);
			});
		}
	};
});
'use strict';
app.directive('nextAction', function(){
  return {
    restrict: 'AE',
    replace: true,
    templateUrl: 'views/add-macros/next-action.html',
    scope: {
      continueState: '@',
      backState: '@'
    },
    controller: function($scope, $state) {
      $scope.continue = function() {
        $state.go($scope.continueState);
      };
      $scope.backToRoom = function() {
        $state.go($scope.backState);
      };
      $scope.finish = function() {
        $state.go('menu.advanced.options');
      };
    }
  };
});
'use strict';

app.directive('refreshHardware', function() {
  return {
    restrict: 'EA',
    require: '^ngModel',
    scope: {
      reset: '=',
      ngModel: '=',
      deviceType: '='
    },
    template: '<button  class="btn btn-success" type="button" ng-click="refresh()"><i class="fa fa-refresh"></i>&nbsp;&nbsp;Refresh the list</button>',
    replace: true,
    controller: function($scope, toastr, Systems) {
      $scope.refresh = function() {

        //Reset previously selected choice to null
        $scope.reset = null;
        
        Systems.searchHardware(true, $scope.deviceType).then(
          function(data) {
            console.log('searchedDevices', data);
            $scope.ngModel = data.searchedDevices;
            $scope.$parent.searchKey = data.searchKey;
          },
          function (error) {
            if (error.match('NO DEVICE')) {

            } else {
              toastr.error(error);
            }
          }
        );
        
      };
    }
  };
});
'use strict';
//dependent upon on Bootstrap

app.directive('selectDevice', function (){
	return {
		restrict: 'E',
		require: 'ngModel',
		replace: true,
		scope: {
			ngModel: '=',
			rooms: '=',
			room: '='
		},
		template: '<div class="scrollable-window padding-left-sm">'+
							'<div class="radio" ng-if="room.roomSelectVisible" ng-repeat="room in rooms track by room.id">' +
								'<label>' +
									'<input type="radio" name="room" ng-model="ngModel.roomId" ng-disabled="!room.devices.length" ng-click="ngModel.roomId !== room.id && clearSelection()" ng-value="room.id">' +
									'<strong>{{room.name}}</strong>' +
									'<small class="text-muted" ng-if="!room.devices.length">  This room has no devices yet.</small>' +
								'</label> ' +
								'<div class="fx-fade-down padding-left-md" ng-if="room.devices.length && ngModel.roomId === room.id">' +
									'<div class="radio" ng-repeat="device in room.devices track by device.id">' +
										'<label>' +
											'<input type="radio" name="device" ng-model="ngModel.deviceId"  ng-value="device.id">' +
											'<small class="text-muted">{{device.name}}</small>' +
										'</label>'+
									'</div>'+
								'</div>'+
							'</div></div>',
		controller: function($scope) {

			///dev_type이 twoway(1)인 device를 모두 제거.
			_.forEach($scope.rooms, function (room) {
				var item = null;
				while(item = _.where(room.devices, {'dev_type': 1})[0]) {
					var idx = room.devices.indexOf(item);
					room.devices.splice(idx, 1);
				} 
				//console.log('room.devices=', room.devices);
			});
			
			$scope.clearSelection = function() {
				$scope.ngModel.deviceId = null;
			};  
		},
		link: function(scope, element, attrs, ngModelCtrl) {

      scope.$watch('[ngModel.roomId, ngModel.deviceId]', function(newValue, oldValue) {        
				if (_.every(newValue)) {
					ngModelCtrl.$setValidity('deviceSelected', true);
				} else {
					ngModelCtrl.$setValidity('deviceSelected', false);
				}
			}, true);

      if (scope.room) {
        scope.ngModel.roomId = scope.room.id;

        _.forEach(scope.rooms, function(room) {
          if (room.id === scope.room.id) {
            room.roomSelectVisible = true;
          } else {
            room.roomSelectVisible = false;
          }
        });
      } else {
        _.forEach(scope.rooms, function(room) {
          room.roomSelectVisible = true;
        });
      }
		} 
	};
});

'use strict';
//dependent upon on Bootstrap

app.directive('selectRoom', function () {
  return {
    restrict: 'E',
    require: 'ngModel',
    replace: true,
    scope: {
      ngModel: '=',
      rooms: '=',
      room: '=',
      disable: '='
    },
    template: '<div class="scrollable-window padding-left-sm">' +
              '<div class="radio" ng-if="room.roomSelectVisible" ng-repeat="room in rooms track by room.id">' +
                '<label>' +
                  '<input type="radio" name="room" ng-model="ngModel.room" ng-if="!disable" ng-value="room">' + 
                  '<input type="radio" name="room" ng-model="ngModel.room" ng-if="disable" ng-disabled="room.devices.length === 0" ng-value="room">' +
                  '<strong>{{room.name}}</strong>' +
                  '<p><small class="text-muted" ng-if="room.devices.length === 0">This room has no devices yet.</small></p>' +
                '</label>' +
              '</div></div>',
    link: function (scope, element, attrs, ngModelCtrl) {
      scope.$watch('ngModel.room.id',
        function(newValue, oldValue) {
          if (newValue) {
            ngModelCtrl.$setValidity('roomSelected', true);
          } else {
            ngModelCtrl.$setValidity('roomSelected', false);
          }
        });

      if (scope.room) {
        scope.ngModel.room = scope.room;

        _.forEach(scope.rooms, function(room) {
          if (room === scope.room) {
            room.roomSelectVisible = true;
          } else {
            room.roomSelectVisible = false;
          }
        });
      } else {
        _.forEach(scope.rooms, function(room) {
          room.roomSelectVisible = true;
        });
      }
    }
  };
});
'use strict';

app.directive('selectVariableType', function ($modal, $timeout) {
	return {
		restrict: 'A',
		scope: {
			system: '='
		},
		controller: function($scope, $element) {
			$scope.variableTypes = [{name:'True False', value:0}, {name:'String', value:1}, {name:'Integer', value:2}];
			$scope.newVar = {type:0};
			var modal = $modal({scope: $scope, title: 'New Variable Type', template: 'views/modal-tpls/select-variable-type.html', show: false});
			
			$element.on('click', function(event) {
				event.preventDefault();
				modal.$promise.then(modal.show);
			});
		}
	};
});
'use strict';

app.directive('selectVariable', function ($modal, $timeout) {
	return {
		restrict: 'A',
		scope: {
			system: '=',
			steps: '=',
			sfunc: '='
		},
    controller: function ($rootScope, $scope, $element, Systems, toastr) {
			$scope.specialFuncTypes = [{title:'Variable', value:0}, {title:'If/Else: Variable', value:1}];
			$scope.variables = [];
			$scope.title = '';
			var modal = $modal({scope: $scope, template: 'views/modal-tpls/select-variable.html', show: false});

      var roomId = null;
      if ($rootScope.virtualEditor) {
        roomId = Systems.getCurrentRoom();
      }

      Systems.getVariables(roomId).then(
				function(data){
					$scope.variables = data;

					if($scope.variables.length)
						$scope.sfunc.variable = $scope.variables[0];
					else
						$scope.sfunc.variable = null;
				},
				function(error){
					toastr.error(error);
					console.log('error=', error);
				}
			);

			$element.on('click', function(event) {
				event.preventDefault();
				$scope.title = $scope.specialFuncTypes[$scope.sfunc.type].title;
				modal.$promise.then(modal.show);
			});
		}
	};
});
'use strict';

app.directive('specialFunction', function ($modal, $timeout) {
	return {
		restrict: 'A',
		scope: {
			system: '=',
			steps: '='
		},
		controller: function($scope, $element) {
			$scope.specialFuncTypes = [{name:'Variable', value:0}, {name:'If/Else', value:1}];
			$scope.sfunc = {type:0};
			var modal = $modal({scope: $scope, title: 'Special Functions', template: 'views/modal-tpls/special-function.html', show: false});
			
			$element.on('click', function(event) {
				event.preventDefault();
				modal.$promise.then(modal.show);
			});
		}
	};
});
'use strict';
//dependent upon on Bootstrap

app.directive('testFunction', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      systemId: '=',
      roomId: '=',
      device: '=',
      func: '='
    },
    template: '<button class="btn btn-primary" ng-click="test(systemId, roomId, device, func)">Test it!</button>',
    controller: function($scope, $http, toastr, Systems) {

      $scope.test = function(systemId, roomId, device, func) {
        console.log(systemId);
        console.log(roomId);
        console.log(device);

        var urlData = '/api/cloud/test';

        if (!device.hasOwnProperty('target_type') || !device.hasOwnProperty('target_addr') || !device.hasOwnProperty('target_port')) {
          device = Systems.getDevice(roomId, device.device_id);
          console.log(device);
        }

        

        var testData = {};
        if(device.target_type === 1) {
          testData = { "systemId" : systemId, "type" : device.target_type,
            "addr" : device.target_addr, "port" : device.target_port, "repeat" : device.repeat_macro,
            "ir_type": func.type, "data" : func.data };
        }
        else {
          testData = { "systemId" : systemId, "type" : device.target_type,
            "addr" : device.target_addr, "port" : device.target_port, "repeat" : device.repeat_macro,
            "ramp_start" : device.ramp_start, "ramp_speed" : device.ramp_speed, "auto_cr" : device.auto_cr,
            "data" : func.data };
        }

        var jsonTestData = JSON.stringify(testData);
        console.log(jsonTestData);

        $http({
          method: 'POST',
          url: urlData,
          data: jsonTestData
        }).
        success(function(data) {
          if(data.result === true) {
            toastr.success('Test command sent');
          }
          else {
            toastr.error(data.error);
          }
        }).
        error(function() {
          toastr.error("Please try again");
        });
      };
    }
  };
});

'use strict';
//dependent upon on Bootstrap

app.directive('testMacro', function () {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      systemId: '=',
      devices: '=',
      macro: '='
    },
    template: '<button class="btn btn-primary btn-fw" ng-click="test(systemId, devices, macro)">Test</button>',
    controller: function($scope, $http, $q, $timeout, $modal, toastr) {
      var promise,
          currentStep = 0,
          FUNC_TYPE = 1,
          DELAY_TYPE = 2,
          canceller = $q.defer(),
          modal = $modal({scope: $scope, title: 'Test macro', backdrop: 'static', placement: 'top', template: 'views/modal-tpls/test-macro.html',  show: false});


      $scope.cancel = function () {
        console.log(promise);
        console.log(canceller);

        if ($scope.macro[currentStep].type === FUNC_TYPE) {
          console.log('HTTP req cancelled');
          canceller.resolve('User cancelled');
        } else if ($scope.macro[currentStep].type === DELAY_TYPE) {
          console.log('Timer cancelled');
          $timeout.cancel(promise);
        } else {

        }
      };


      $scope.test = function(systemId, devices, macro) {
        console.log(systemId);
        console.log(devices);
        console.log(macro);


        //Resets
        currentStep = 0;
        canceller = $q.defer();
        $scope.macroCompleted = false;

        _.forEach(macro, function (step) {
          step.isTesting = false;
          step.isError = false;
          step.isCompleted = false;
        });


        function makeRequest (step) {
          switch (step.type) {
            case FUNC_TYPE:
              var jsonTestData,
                  testData = {},
                  urlData = '/api/cloud/test',
                  device = _.where(devices, { 'id': step.device_id })[0],
                  func = _.where(device.funcs, {'id': step.func })[0];

              if(device.target_type === 1) {
                testData = { "systemId" : systemId, "type" : device.target_type,
                  "addr" : device.target_addr, "port" : device.target_port, "repeat" : device.repeat_macro,
                  "data" : func.data, "ir_type": func.type };
              }
              else {
                testData = { "systemId" : systemId, "type" : device.target_type,
                  "addr" : device.target_addr, "port" : device.target_port, "repeat" : device.repeat_macro,
                  "ramp_start" : device.ramp_start, "ramp_speed" : device.ramp_speed, "auto_cr" : device.auto_cr,
                  "data" : func.data };
              }

              jsonTestData = JSON.stringify(testData);
              console.log(jsonTestData);

              return $http({ method: 'POST', url: urlData, data: jsonTestData, timeout: canceller.promise }).success(handleSuccess).error(handleError);

            case DELAY_TYPE:
              promise = $timeout(function () {
                console.log('Timeout callback');
                macro[currentStep].isTesting = false;
                macro[currentStep].isCompleted = true;

                console.log(currentStep);
                makeNextRequest();
              }, step.value);
              return promise;
            default:
              promise = $timeout(function () {
                console.log('Default callback');
                macro[currentStep].isTesting = false;

                console.log(currentStep);
                makeNextRequest();
              }, 0);
              return promise;
          }
        }


        function makeNextRequest() {
          if (currentStep+1 < macro.length) {
            currentStep++;
            macro[currentStep].isTesting = true;
            makeRequest(macro[currentStep]);
          } else {
            $scope.macroCompleted = true;
          }

        }



        function handleSuccess(data) {
          console.log(data);

          if (data.result) {
            toastr.success('Test command sent');

            macro[currentStep].isTesting = false;
            macro[currentStep].isCompleted = true;
          } else {
            macro[currentStep].isTesting = false;
            macro[currentStep].isError = true;
          }

          console.log(currentStep);
          makeNextRequest();
        }


        function handleError(data) {
          console.log(data);
          macro[currentStep].isTesting = false;
          macro[currentStep].isError = true;
          makeNextRequest();
        }

        macro[currentStep].isTesting = true;
        modal.$promise.then(modal.show);

        makeRequest(macro[currentStep]);

      };
    }
  };
});

'use strict';

app.directive('timeSettings', function() {
	return {
		restrict: 'EA',
		replace:true,
		scope: {
			system: '=',
			timeZones: '='
		},
		template: '<a ng-click="showTimeSettingsModal()">Change the time settings for this system </a>',
		//<small>{{system.timezone.data.name}}</small>
		controller: function($scope, $modal, toastr, Systems) {
			var timeSettingsModal = $modal({
				scope: $scope,
				template: 'views/modal-tpls/change-tz.html',
				show: false
			});


			$scope.setTimeZone = function() {
				console.log($scope.time.format);
				var data = JSON.stringify({ id: $scope.time.zone.data.id , dst: $scope.time.zone.dst ? 1:0, time_type: $scope.time.format === 'hh:mm:ss a' ? 0:1 });
				Systems.setTimeZone(data).then(function(data) {
					console.log(data);
					$scope.system.timezone.data = angular.copy($scope.time.zone.data);
					$scope.system.timezone.dst = $scope.time.zone.dst ? 1:0;
					$scope.system.time_type = $scope.time.format === 'hh:mm:ss a' ? 0:1;
					Systems.loadSystem($scope.system);
				}).catch(function(error) {
					toastr.error(error, 'Error');
				});
			};

			$scope.checkDST = function() {
				if ($scope.time.zone.data.s_time === '0.0.0 00:00:00' || !$scope.time.zone.data.d_bias) {
					$scope.time.zone.dst = false;
				} else {
					$scope.time.zone.dst = true;
				}
			};

			$scope.showTimeSettingsModal = function () {
				$scope.time = {};
				$scope.time.zone = { data: angular.copy($scope.system.timezone.data), dst: $scope.system.timezone.dst ? true:false };
				$scope.time.format = $scope.system.time_type === 0 ? 'hh:mm:ss a': 'HH:mm:ss';
				timeSettingsModal.$promise.then(timeSettingsModal.show);       
			};
		}
	};
});
'use strict';

app.directive('userPanel', function() {
  return {
    restrict: 'EA',
    //replace: true,
    scope: {},
    template: '<a class="btn btn-nav pull-right" ng-click="showHelpModal()">' +
                '<i class="fa fa-question-circle fa-lg"></i>&nbsp;&nbsp;<span>Help</span>'+
              '</a>'+
    '<a class="btn btn-nav pull-right" ui-sref="home" ng-if="!currentUser && !dealer && !registerDealer">' +
                '<i class="fa fa-user fa-lg"></i>&nbsp;&nbsp;<span>Login &#47; Register</span>'+
              '</a>'+
    '<button class="btn btn-nav pull-right" ng-if="((currentUser && !currentUser.name && dealer && !menu && (!virtualEditor || !fileExplorer)) || dealerJobsList || virtualEditorState || dealerSettingState) && !registerDealer" data-placement="bottom-right" data-html="1" data-trigger="click" bs-dropdown="dealerUsernameDropdown">' +
    '<i class="fa fa-user fa-lg"></i>&nbsp;&nbsp; {{dealerUsername}} &nbsp;<i class="fa fa-caret-down"></i>' +
    '</button>' +
    '<button class="btn btn-nav pull-right" ng-if="(((currentUser && !currentUser.name && dealer && !menu) && !dealerJobsList && !virtualEditorState) || (virtualEditor && !dealerJobsList && !virtualEditorState)) && !registerDealer && !dealerSettingState" data-placement="bottom-right" data-html="1" data-trigger="click" bs-dropdown="virtualEditorDropdown">' +
    '<i class="fa fa-circle fa-lg"></i>&nbsp;&nbsp;<span>Virtual Editor</span> &nbsp;<i class="fa fa-caret-down"></i>' +
    '</button>' +
    '<button class="btn btn-nav pull-right" ng-if="currentUser && !dealer && !dealerJobsList && !virtualEditorState && !virtualEditor && !dealerSettingState" data-placement="bottom-right" data-html="1" data-trigger="click" bs-dropdown="dropdown">' +
                '<i class="fa fa-user fa-lg"></i>&nbsp;&nbsp; {{currentUser.username}} &nbsp;<i class="fa fa-caret-down"></i>'+
              '</button>',
    controller: function ($rootScope, $scope, $state, $window, $modal, toastr, Auth, User, Systems) {

      $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        if (toState.name.match('menu')) {
          $scope.menu = true;
        } else {
          $scope.menu = false;
        }

        if (toState.name.match('file-explorer')) {
          $scope.fileExplorer = true;
        } else {
          $scope.fileExplorer = false;
        }

        if (toState.name.match('dealer-jobs-list')) {
          $scope.dealerJobsList = true;
        } else {
          $scope.dealerJobsList = false;
        }

        if (toState.name.match('virtual-editor')) {
          $scope.virtualEditorState = true;
        } else {
          $scope.virtualEditorState = false;
        }

        if (toState.name.match('register-dealer')) {
          $scope.registerDealer = true;
        } else {
          $scope.registerDealer = false;
        }

        if (toState.name.match('dealer-account-settings')) {
          $scope.dealerSettingState = true;
        } else {
          $scope.dealerSettingState = false;
        }

        if ($rootScope.virtualEditor) {
          $scope.virtualEditor = true;
        } else {
          $scope.virtualEditor = false;
        }
      });

      Systems.getSystemEnv().then(function(response) {
        $scope.eulaLink = response.eulaLink;
        $scope.downloadsTitle = response.downloadsTitle;
        $scope.remoteOwnersManualLink = response.remoteOwnersManualLink;
        $scope.remoteOwnersManualFile = response.remoteOwnersManualFile;
        $scope.bsOwnersManualLink = response.bsOwnersManualLink;
        $scope.bsOwnersManualFile = response.bsOwnersManualFile;
        $scope.installationGuideLink = response.installationGuideLink;
        $scope.installationGuideFile = response.installationGuideFile;
        $scope.programmingGuideLink = response.programmingGuideLink;
        $scope.programmingGuideFile = response.programmingGuideFile;
        $scope.quickStartGuideLink = response.quickStartGuideLink;
        $scope.quickStartGuideFile = response.quickStartGuideFile;
        $scope.advancedDevicesQuickGuideLink = response.advancedDevicesQuickGuideLink;
        $scope.advancedDevicesQuickGuideFile = response.advancedDevicesQuickGuideFile;
        $scope.zWaveIntegrationLink = response.zWaveIntegrationLink;
        $scope.zWaveIntegrationFile = response.zWaveIntegrationFile;
        $scope.cameraIntegrationLink = response.cameraIntegrationLink;
        $scope.cameraIntegrationFile = response.cameraIntegrationFile;
        $scope.dealerAccessLink = response.dealerAccessLink;
        $scope.dealerAccessFile = response.dealerAccessFile;
        $scope.mobileAppQuickGuideLink = response.mobileAppQuickGuideLink;
        $scope.mobileAppQuickGuideFile = response.mobileAppQuickGuideFile;
        $scope.usingFavoriteChannelsLink = response.usingFavoriteChannelsLink;
        $scope.usingFavoriteChannelsFile = response.usingFavoriteChannelsFile;
      }).catch(function(error) {
        toastr.error(error);
      });

      $scope.viewApplyForDealer = function () {
        window.open('/#/apply-for-dealer', 'Apply for a dealer account', 'scrollbars=no, height=800')
      };

      $scope.currentUser = null;
      $scope.dealer = null;

      $scope.logoutUser = function () {
        User.logout();
        $('.user-panel').css('visibility', 'hidden');
        $window.location.href = '/';
      };

      $scope.$on('user:set', function(event, currentUser) {
        console.log('caught user:set event');

        $scope.dealer = null;

        if (currentUser.username || currentUser.company) {
          $scope.currentUser = currentUser;
        }

        if (currentUser.company) {
          $scope.dealerUsername = currentUser.dealer_username;

          var fileExplorer = _.findWhere($scope.dropdown, {
            href: '/#/file-explorer'
          });

          if (!fileExplorer) {
            $scope.dropdown.push({
              "text": '<i class="fa fa-exclamation-triangle" />&nbsp;&nbsp;File Explorer',
              "href": "/#/file-explorer",
              "target": "_self"
            });

            $scope.dropdown.push({
              "text": '<i class="fa fa-list-alt" />&nbsp;&nbsp;Dealer Jobs List',
              "href": "/#/dealer-jobs-list",
              "target": "_self"
            });
          }

          if (!currentUser.username) {
            $scope.dealer = true;
          }
        }
      });

      $scope.$on('user:unset', function(event) {
        console.log('caught user:unset event');
        $scope.currentUser = null;
      });


      $scope.switch = {};

      var helpModal = $modal({
        scope: $scope,
        placement: 'top',
        template: 'views/modal-tpls/help.html',
        show: false
      });

      $scope.switchUpdate = false;
      $scope.$on('modal.hide',function(){
        if ($scope.switchUpdate) {
          location.reload();
        }
      });

      $scope.showHelpModal = function() {
        if($scope.currentUser) {
          $scope.switch.menu = !!$scope.currentUser.optMenuShow;
          $scope.switch.help = !!$scope.currentUser.optHelpShow;
        }

        helpModal.$promise.then(helpModal.show);
      };

      $scope.$watch('switch.help', function(newValue, oldValue) {
        var optHelpShow,
          user;

        if (newValue != oldValue && typeof oldValue != 'undefined') {
          $scope.switchUpdate = true;

          if (newValue) {
            optHelpShow = 1;
          } else {
            optHelpShow = 0;
          }

          user = JSON.parse($window.localStorage.getItem('hcm_editor'));
          user.optHelpShow = optHelpShow;
          Auth.setCurrentUser(user);

          var jsonData = JSON.stringify({help_show: user.optHelpShow, menu_show: user.optMenuShow});
          User.setOption(jsonData);
        }
      });

      $scope.$watch('switch.menu', function(newValue, oldValue) {
        var optMenuShow,
          user;

        if (newValue != oldValue && typeof oldValue != 'undefined') {
          $scope.switchUpdate = true;

          if (newValue) {
            optMenuShow = 1;
          } else {
            optMenuShow = 0;
          }

          user = JSON.parse($window.localStorage.getItem('hcm_editor'));
          user.optMenuShow = optMenuShow;
          Auth.setCurrentUser(user);

          var jsonData = JSON.stringify({help_show: user.optHelpShow, menu_show: user.optMenuShow});
          User.setOption(jsonData);
        }
      });


      $scope.dropdown = [
        {
          "text": '<i class="fa fa-list" />&nbsp;&nbsp;Overview',
          "href": "/#/menu/system-overview",
          "target": "_self"
        },
        {
          "text": '<i class="fa fa-users" />&nbsp;&nbsp;Account Settings',
          "href": "/#/account-settings",
          "target": "_self"
        },
        {
          "text": '<i class="fa fa-gears" />&nbsp;&nbsp;System Settings',
          "href": "/#/system-settings",
          "target": "_self"

        },
        {
          "text": '<i class="fa fa-sign-out" />&nbsp;&nbsp;Logout',
          "click": "logoutUser()"
        }
      ];

      $scope.virtualEditorDropdown = [
        {
          "text": '<i class="fa fa-list" />&nbsp;&nbsp;Overview',
          "href": "/#/menu/system-overview",
          "target": "_self"
        },
        {
          "text": '<i class="fa fa-sign-out" />&nbsp;&nbsp;Logout',
          "click": "logoutUser()"
        },
        {
          "text": '<i class="fa fa-exclamation-triangle" />&nbsp;&nbsp;File Explorer',
          "href": "/#/file-explorer",
          "target": "_self"
        },
        {
          "text": '<i class="fa fa-list-alt" />&nbsp;&nbsp;Dealer Jobs List',
          "href": "/#/dealer-jobs-list",
          "target": "_self"
        }
      ];

      $scope.dealerUsernameDropdown = [
        {
          "text": '<i class="fa fa-circle" />&nbsp;&nbsp;Virtual Editor',
          "href": "/#/virtual-editor",
          "target": "_self"
        },
        {
          "text": '<i class="fa fa-sign-out" />&nbsp;&nbsp;Logout',
          "click": "logoutUser()"
        }
      ];


    }
  };
});
