/**
 *
 */
'use strict';
define(function() {
  var TabContainerCtrl = function($scope, gaJsUtils) {
    var config;
    var fieldDesc, objectFields, objectId;

    $scope.selectedTabLbl = 'tab_' + $scope.$id + '_' + 0;
    //-- Indicate if it exists a required field with a null value in each tab.
    $scope.tabsRequiredState = [];

    if ($scope.config != null) {
      config = $scope.config;
      objectFields = $scope.objectFields;
      fieldDesc = $scope.fieldDesc;
      objectId = $scope.objectId;
      if (fieldDesc == null) {
        fieldDesc = $scope.__proto__.descField;
      }
    }
    if (config == null && $scope.$parent != null) {
      config = $scope.$parent.config;
      objectFields = $scope.$parent.objectFields;
      fieldDesc = $scope.$parent.fieldDesc;
      objectId = $scope.$parent.objectId;
      if (fieldDesc == null) {
        fieldDesc = $scope.$parent.__proto__.descField;
      }
      if (config == null) {
        if ($scope.$parent.$parent != null) {
          config = $scope.$parent.$parent.config;
          objectFields = $scope.$parent.$parent.objectFields;
          fieldDesc = $scope.$parent.$parent.fieldDesc;
          objectId = $scope.$parent.$parent.objectId;
          if (fieldDesc == null) {
            fieldDesc = $scope.$parent.$parent.__proto__.descField;
          }
        }
      }
    }
    if (config == null) {
      alert('Pas de configuration founie pour le tabContainer !');
      return;
    }
    /*
        		var objectFields={"DATE_CREA":"10/10/2012","DATE_UPDATE":"12/10/2012", "NOM":"Dupond","PRENOM":"Alain",
        						  "ADRESSE1":"1 rue des micocouliers","ADRESSE2":"R�s blouche", "COMMUNE":"14141 Fleurville",
        						  "NAISSANCE_DATE":"21/12/1980", "NAISSANCE_LIEU":"chatville", "SEXE":"1", "NB_ENFANTS":"1",
        						  "PERE_NOM":"Dupond", "PERE_PRENOM":"Gilles",
        						  "PERE_DATE_NAISSANCE":"21/12/1940","PERE_LIEU_NAISSANCE":"Paris"
        			             };

        		var tableMainFields = [{"table":"day_projet_etapes_predefinies","fields":[{"field":"nom_etape"}]}];
*/
    var ind;

    /*yyyyyyyyyyyy
        		var step1 = {  "title":"Personne - naissance",
        				       "panelFields":[ {"field":"NOM"},{"field":"PRENOM"},
        		                    {"group":{"title":"Demandeur","fieldOrder":["DATE_CREA","DATE_UPDATE"]}},
        		                    {"group":{"title":"Naissance","fieldOrder":["NAISSANCE_DATE","NAISSANCE_LIEU","SEXE"]}}
        		                  ],
           		               "fieldOrder":["NOM","PRENOM"],
           		               "objectFields":objectFields,
           		               "fieldDesc":fieldDesc,
           		               "tableMainFields":tableMainFields
        		};
        		var step2 = {   "title":"Personne - adresse",
     						    "panelFields":[ {"field":"ADRESSE1"},{"field":"ADRESSE2"},{"field":"COMMUNE"} ],
     			                "objectFields":objectFields,
           		                "fieldDesc":fieldDesc,
            		               "tableMainFields":tableMainFields
        		};
        		var step3 = {   "title":"Personne - Situation familiale",
        						"panelFields":[ {"field":"NB_ENFANTS"}, {"field":"COMMENTAIRES"} ],
        						"objectFields":objectFields,
        						"fieldDesc":fieldDesc,
        						"specialFields" : {"COMMENTAIRES": {"rows":"5", "type":"comment"},
        										   "CONTRAT_MARIAGE": {"type":"attachment"},
        										   "FACTURES": {"type":"attachment","filtre":"fac_*"}
        										  },
        			            "tableMainFields":tableMainFields
		};
		*/

    if (config.tabs === undefined)
      gaJsUtils.errorMessage(
        "Pas d'onglet défini pour la présentation à onglets !"
      );
    else
      for (ind = 0; ind < config.tabs.length; ind++) {
        config.tabs[ind].fieldDesc = fieldDesc;
        config.tabs[ind].tableMainFields = config.tableMainFields;
        config.tabs[ind].objectFields = objectFields;
        config.tabs[ind].objectId = objectId;
        config.tabs[ind].config = config;
      }

    $scope.thisId = $scope.$id;
    $scope.goLeftPressed = false;
    $scope.goRightPressed = false;
    $scope.tabs = config.tabs;
    /*
                $scope.tabs = [
                               { title:'Personne', contentType:'stepContainer', data: tab1 },
                               { title:'Pere de la personne', contentType:'panelContainer', data: tab2 },
                               { title:'Tout', contentType:'panelContainer', data: tab3 }
                             ];
                */

    $scope.moveRight = function() {
      var elt, pos, reg;
      elt = document.getElementById('tabset_' + $scope.thisId);
      reg = new RegExp('px', 'g');
      if (elt.style.left == '') pos = 0;
      else pos = parseInt(elt.style.left.replace(reg, ''));
      if (pos < 0) {
        pos += 2;
        elt.style.left = '' + pos + 'px';
      }
      if ($scope.goRightPressed) setTimeout($scope.moveRight, 50);
    };

    $scope.stopGoLeft = function(mouseevent) {
      $scope.goLeftPressed = false;
    };
    $scope.stopGoRight = function(mouseevent) {
      $scope.goRightPressed = false;
    };

    $scope.moveLeft = function() {
      var elt, pos, reg;
      elt = document.getElementById('tabset_' + $scope.thisId);
      reg = new RegExp('px', 'g');
      if (elt.style.left == '') pos = 0;
      else pos = parseInt(elt.style.left.replace(reg, ''));
      pos -= 2;
      elt.style.left = '' + pos + 'px';

      if ($scope.goLeftPressed) setTimeout($scope.moveLeft, 50);
    };

    $scope.goLeft = function(mouseevent) {
      $scope.goLeftPressed = true;
      setTimeout($scope.moveLeft, 500);
    };

    $scope.goRight = function(mouseevent) {
      $scope.goRightPressed = true;
      setTimeout($scope.moveRight, 500);
    };

    $scope.showTabContent = function(idContent) {
      var elt;

      elt = document.getElementById(idContent);
      if (elt != undefined) {
        if ($scope.curTab != undefined) $scope.curTab.style.display = 'none';
        elt.style.display = 'block';
        $scope.curTab = elt;
      }
    };

    $scope.showTab = function(event, tabId) {
      var idContent, reg;

      reg = new RegExp('tab_', 'g');
      idContent = event.currentTarget.id.replace(reg, 'tabContent_');
      $scope.showTabContent(idContent);
      $scope.selectedTabLbl = event.currentTarget.id;
    };

    $scope.showFirstTab = function() {
      $scope.showTabContent('tabContent_' + $scope.$id + '_' + 0);
    };

    /**
     *       Called from valueChanged method in order to store the boolean
     * indicating whether there is a required field with null value or not.
     * This boolean is stored for each tab so that we are able to tell the parent
     * if at east one required field is not filled amongast any tab.
     *
     * @param {String} tabScopeId:  scope identifier of the tab which called value changed method.
     */
    $scope.StoreTabRequiredState = function(tabScopeId) {
      var ind, scopeRequired;

      //-- Look for tab identified by scope in the list of booleans.
      for (ind = 0; ind < $scope.tabsRequiredState.length; ind++)
        if ($scope.tabsRequiredState[ind].scopeId == tabScopeId) {
          //-- Tab has been found so store the new boolean value.
          $scope.tabsRequiredState[ind].existsRequiredValueWithNull =
            $scope.$parent.infoFromChildren.existsRequiredValueWithNull;
          break;
        }
      if (ind == $scope.tabsRequiredState.length) {
        //-- Tab has noe been found so add the new boolean value.
        scopeRequired = {};
        scopeRequired.scopeId = tabScopeId;
        scopeRequired.existsRequiredValueWithNull =
          $scope.$parent.infoFromChildren.existsRequiredValueWithNull;
        $scope.tabsRequiredState.push(scopeRequired);
      }
    };

    $scope.valueChangedFunction = true;
    $scope.valueChanged = function(params) {
      //-- If scope id is a parameter store the required field state of the tab.
      if (params != undefined && params.scopeId != undefined)
        $scope.StoreTabRequiredState(params.scopeId);
      if ($scope.$parent.valueChangedFunction === true) {
        if ($scope.$parent.infoFromChildren != undefined) {
          $scope.$parent.infoFromChildren.existsRequiredValueWithNull = false;
          //-- Check if one tab has a required field set to null.
          for (var ind = 0; ind < $scope.tabsRequiredState.length; ind++)
            if ($scope.tabsRequiredState[ind].existsRequiredValueWithNull) {
              $scope.$parent.infoFromChildren.existsRequiredValueWithNull = true;
              break;
            }
        }
        $scope.$parent.valueChanged(params);
      }
    };

    setTimeout($scope.showFirstTab, 300);
  };

  TabContainerCtrl.$inject = ['$scope', 'gaJsUtils'];
  return TabContainerCtrl;
});
