"use strict";

angular.module("ui.TR", [])
  .directive("trwidget", ['$injector', '$location', '$compile', 'dialogsSvc',
    function ($injector, $location, $compile, dialogsSvc) {
      return {
        scope: {
          disabled: "=",
          deact: "=",
          sedname: "@",
          elname: "@"
        },
        require: "ngModel",
        restrict: "E",
        replace: "true",
        template: "<textarea class=\"form-control\" type=\"text\" value=\"\" style=\"resize:vertical;\" type=\"text\" rows=\"5\" cols=\"30\" ng-disabled=\"deact\" ></textarea>",
        link: function (scope, element, attrs, modelCtrl) {
          scope.deact = scope.disabled === true ? true : false;
          scope.locale = LOCALE;

          // append link for translation
          var el = angular.element('<span ng-disabled=\"deact\" ng-click=\"openTranslationWindow()\" style=\"float:right;color:#0088cc;margin:3px 0px 12px 0px;cursor:pointer\"> {{locale[\'Translate\']}} </span>');
          $compile(el)(scope);
          element.parent().append(el);

          // open new window for translation
          scope.openTranslationWindow = function () {
            var id = generateUUID();
            var sedName = scope.sedname;
            var fieldName = scope.elname;
            var language = "en";
            var text = angular.element(element).val();
            
            // get language from user profile
            if ($injector.has('wbUserProfileSvc')) {
              var wbUserProfileSvc = $injector.get('wbUserProfileSvc');
              wbUserProfileSvc.WhenLoaded().then(function (userProfile) {
                language = userProfile.localizationSettings.language;
              }, function (error) {
              });
            }

            // get dependencies
            if ($injector.has('WB_CONSTANTS'))
              var WB_CONSTANTS = $injector.get('WB_CONSTANTS');
            if ($injector.has('wbUtils'))
              var wbUtils = $injector.get('wbUtils');

            //check textarea length
            if (text.length === 0) {
              if (wbUtils) {
                wbUtils.errorToUser(fieldName + ' ' + WB_CONSTANTS.ETRANSLATION.Has_no_value, "", true);
              } else {
            	  //dialogsSvc.OKDialog(fieldName + ' has no value');
            	  var msg;
            	  msg = ERROR_MESSAGES['hasnovalue'];
            	  if(!msg)
            		  msg = 'has no value'
            	  dialogsSvc.OKDialog(fieldName + ' '+msg);
              }
            } else if (text.length <= 255) {
              sessionStorage.setItem(id, text);
              var url = $location.protocol() + "://" + $location.host() + ":" + $location.port() + "/translation?id=" + id + "&sed=" + sedName + "&field=" + fieldName + "&lang=" + language;
              if(($location.absUrl()).indexOf("portal/#") !== -1){
                  url = $location.protocol() + "://" + $location.host() + ":" + $location.port() + "/portal/#/translation?id=" + id + "&sed=" + sedName + "&field=" + fieldName + "&lang=" + language;
              }
              var name = 'eTranslation' + id;
              
              // Local MET form
              if (!$injector.has('wbUtils'))
              {
              	//url = $location.protocol() + "://" + "translation.html" + "/translation?id=" + id + "&sed=" + sedName + "&field=" + fieldName + "&lang=" + language;
                //url = $location.protocol() + "://" + getDirName(window.location.pathname) + "/_forms/trans/" + "translation.html" + "?id=" + id + "&sed=" + sedName + "&field=" + fieldName + "&lang=" + language;
            	url = $location.protocol() + "://";
            	                
            	if ($location.protocol() !== "file") 
            	{
            		url += $location.host() + ":" + $location.port() + "/static";
            	}
            	                
            	url += getDirName(window.location.pathname) + "/_forms/trans/" + "translation.html" + "?id=" + id + "&sed=" + sedName + "&field=" + fieldName + "&lang=" + language;
            	
                // Open a slightly larger window in MET
                window.open(url, name, 'width=900,height=400,top=50,left=100');
                return;
              }
              	
              window.open(url, name, 'width=800,height=400,top=50,left=100');
            } else {
              if (wbUtils) {
                wbUtils.errorToUser(fieldName + ' ' + WB_CONSTANTS.ETRANSLATION.Does_not_comply_with_restriction, "", true);
              } else {
            	  //dialogsSvc.OKDialog(fieldName + ' does not comply with restriction "maxLength:255"');
            	  var msg;
            	  msg = ERROR_MESSAGES['norestriction'];
            	  if(!msg)
            		  msg = 'does not comply with restriction'
            	  dialogsSvc.OKDialog(fieldName + ' ' + msg + ' "maxLength:255"');
              }
            }
          };

          // generate uuid
          function generateUUID() {
            var d = new Date().getTime();
            var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
              var r = (d + Math.random() * 16) % 16 | 0;
              d = Math.floor(d / 16);
              return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
            });
            return uuid;
          }
          
          function getDirName(path)
          {
               if(path === null) return '/';

               if(path.indexOf("/") !== -1)
               {
            	   path = path.split('/')            
                   path.pop()                     
                   path= path.join('/')           
                   if(path === '')
                        return '/';
                   return path;
               }

               return "/";
          }

        }
      };
    }]);
