var VuodenHuiput = {
  isEmpty: function(str) {
    if (!str) {
      return true;
    }
    if (str.clean().length === 0) {
      return true;
    }
    return false;
  },
  
  countWords: function(str){
    var wordCount = 0;
    str = str.replace(/\s/g,' ');
    var words = str.split(' ');
    for (var i=0; i<words.length; i++) {
      if (words[i].length > 0) {
        wordCount++;
      }
    }
    return wordCount;
  },
  
  prettifyFileInput: function(fileInput, wrapperClass) {
    if (!wrapperClass) {
      wrapperClass = 'file-input-container';
    }
    fileInput.style.opacity = '0';
    fileInput.style.filter = 'alpha(opacity=0)';
    var inputContainer = new Element('div', {
      'class': wrapperClass,
      'html': '<div class="button"><span><img src="/common_files/images/icons/buttons/add_file.png" alt=""/>'+fileInput.alt+'</span></div>'
    });
    inputContainer.setStyles({
      'position': 'relative',
      'overflow': 'hidden'
    });
    inputContainer.setStyle('cursor', 'pointer');
    fileInput.setStyles({
      'position': 'absolute',
      'top': '0px',
      'left': '0px',
      'width': 'auto',
      'height': '100%',
      'cursor': 'pointer'
    });
    
    fileInput.addEvent('mousedown', function(fileInputContainer) {
      fileInputContainer.getElement('.button').addClass('active');
    }.bind(this, inputContainer));
  
    fileInput.addEvent('mouseup', function(fileInputContainer) {
      fileInputContainer.getElement('.button').removeClass('active');
    }.bind(this, inputContainer));
    
  /*  inputContainer.addEvent('mouseover', function(fileInputContainer) {
      var fileInput = fileInputContainer.getElement('input[type=file]');
      if (fileInput != null) fileInput.setStyle('display', 'block');
    }.bind(this, inputContainer));
  
    inputContainer.addEvent('mouseout', function(fileInputContainer) {
      var fileInput = fileInputContainer.getElement('input[type=file]');
      if (fileInput != null) fileInput.setStyle('display', 'none');
      fileInputContainer.getElement('.button').removeClass('active');
    }.bind(this, inputContainer));*/
    
    inputContainer.addEvent('mousemove', function(event, fileInputContainer) {
      var fileInput = fileInputContainer.getElement('input[type=file]');
      if (fileInput) {
        var parentPosition = fileInput.getParent().getPosition();
        var fileInputSize = fileInput.getSize();
        var xPos = event.page.x - parentPosition.x - (fileInputSize.x - 30);
        var yPos = event.page.y - parentPosition.y - fileInputSize.y/2;
        fileInput.setStyles({
          'left': xPos+'px',
          'top': yPos+'px'
        });
      }
    }.bindWithEvent(this, inputContainer));
    
    inputContainer.inject(fileInput, 'after');
    inputContainer.grab(fileInput);
    
    return inputContainer;
  }
};

VuodenHuiput.EditableFileList = new Class({
  Implements: [Events],
  inputElement: null,
  container: null,
  fileList: null,
  fileInput: null,
  fileInputContainer: null,
  
  onRemoveExistingFileClick: function(fileIndex) {
    var files = JSON.decode(this.inputElement.get('value'));
    files[fileIndex].remove = true;
    this.inputElement.set('value', JSON.encode(files));
    this.refresh();
  },
  
  onRemoveUploadedFileClick: function(fileIndex) {
    var files = JSON.decode(this.inputElement.get('value'));
    files.splice(fileIndex, 1);
    this.inputElement.set('value', JSON.encode(files));
    this.refresh();
  },
    
  moveFile: function(filename, targetFileList, refresh) {
    var files = JSON.decode(this.inputElement.get('value'));
    var targetFiles = JSON.decode(targetFileList.inputElement.get('value'));
    for (var i=0; i<files.length; i++) {
      if (files[i].name == filename) {
        targetFiles = targetFiles.concat(files.splice(i, 1));
        break;
      }
    }
    this.inputElement.set('value', JSON.encode(files));
    targetFileList.inputElement.set('value', JSON.encode(targetFiles));
    if (refresh) {
      this.refresh();
      targetFileList.refresh();
    }
  },
  
  moveAllFiles: function(targetFileList) {
    var files = JSON.decode(this.inputElement.get('value'));
    var targetFiles = JSON.decode(targetFileList.inputElement.get('value'));
    for (var i=0; i<files.length; i++) {
      if (!files[i].remove) {
        targetFiles = targetFiles.concat(files.splice(i, 1));
        i--;
      }
    }
    this.inputElement.set('value', JSON.encode(files));
    targetFileList.inputElement.set('value', JSON.encode(targetFiles));
    this.refresh();
    targetFileList.refresh();
  },
  
  refresh: function() {
    this.fileList.innerHTML = '';
    var files = JSON.decode(this.inputElement.get('value'));
    for (var i=0; i<files.length; i++) {
      if (!files[i].remove) {
      var fileElement = new Element('li');
  
      if (files[i].uploading) {
        fileElement.innerHTML = 'Lähetetään tiedostoa...';
        fileElement.addClass('sending');
      } else {
        fileElement.innerHTML = files[i].name;
        var removeElement = new Element('div', {
        'class': 'remove',
        'html': '<span>Poista tiedosto</span>'
        });
        
        if (!files[i].tempName) {
          removeElement.addEvent('click', this.onRemoveExistingFileClick.bind(this, i));
        } else {
          removeElement.addEvent('click', this.onRemoveUploadedFileClick.bind(this, i));
        }
        
        removeElement.inject(fileElement);
      }  
      
      fileElement.inject(this.fileList);
      }
    }
  },
  
  fileExists: function(filename) {
    var files = JSON.decode(this.inputElement.get('value'));
    for (var i=0; i<files.length; i++) {
      if (files[i].name == filename) {
      return true;
      }
    }
    return false;
  },
  
  getFileIndex: function(filename) {
    var files = JSON.decode(this.inputElement.get('value'));
    for (var i=0; i<files.length; i++) {
      if (files[i].name == filename) {
      return i;
      }
    }
    return null;
  },
  
  onFileInputChange: function(event) {
    var newFileInput = new Element('input', {
      'name': 'file',
      'type': 'file',
      'alt': 'Liitä tiedosto'
    });
    
    newFileInput.inject(this.container);
    newFileInput.addEvent('change', this.onFileInputChange.bind(this));
    var newFileInputContainer = VuodenHuiput.prettifyFileInput(newFileInput);
  
    var fileUploadForm = new Element('form', {
      'method': 'post',
      'enctype': 'multipart/form-data',
      'encoding': 'multipart/form-data',
      'action': Env.root+'/upload_competition_entry_file',
      'style': 'display: none'
    });
    fileUploadForm.inject($$('body')[0]);
    this.fileInput.inject(fileUploadForm);
    this.fileInputContainer.dispose();
    
    var iframeId = 'file_upload_iframe_'+(new Date().getTime());
  
    var iframe = new Element('iframe', {
      'style': 'display: none',
      'id': iframeId,
      'name': iframeId
    });
  
    iframe.inject($$('body')[0]);
    fileUploadForm.target = iframeId;
    
    var files = JSON.decode(this.inputElement.get('value'));
  
    var filename = this.fileInput.get('value').match(/[^\/\\]+$/)[0];
  
    fileUploadForm.submit();
    
    var file = {
      'name': filename,
      'tempName': null,
      'remove': false,
      'uploading': true,
      'uploadId': new Date().getTime()
    };
    
    iframe.addEvent('load', VuodenHuiput.EditableFileList.onFileUploadComplete.bind(VuodenHuiput.EditableFileList, [iframe, file]));
  
    var fileIndex = this.getFileIndex(file.name);
  
    if (fileIndex === null) {
      files.push(file);
    } else {
      files[fileIndex].uploading = true;
    }
  
    this.inputElement.set('value', JSON.encode(files));
    
    this.fileInput = newFileInput;
    this.fileInputContainer = newFileInputContainer;
  
    this.refresh();
    this.fireEvent('uploadstart');
    },
    
    initialize: function(inputElement) {
    this.inputElement = inputElement;
    this.container = new Element('div', {
      'class': 'editable-file-list'
    });
    this.fileList = new Element('ul', {
      'class': 'file-list'
    });
    
    this.fileInput = new Element('input', {
      'type': 'file',
      'name': 'file',
      'alt': 'Liitä tiedosto'
    });
    this.fileList.inject(this.container);
    this.fileInput.inject(this.container);
    this.fileInput.addEvent('change', this.onFileInputChange.bind(this));
    this.fileInputContainer = VuodenHuiput.prettifyFileInput(this.fileInput);
  
    this.container.inject(this.inputElement, 'after');
    
    this.refresh();
    
    VuodenHuiput.EditableFileList.fileLists.push(this);
  }
});
VuodenHuiput.EditableFileList.fileLists = [];
VuodenHuiput.EditableFileList.getFileListForInput = function(inputElement) {
  for (var i=0; i<VuodenHuiput.EditableFileList.fileLists.length; i++) {
    var fileList = VuodenHuiput.EditableFileList.fileLists[i];
    if (fileList.inputElement == inputElement) {
      return fileList;
    }
  }
};
VuodenHuiput.EditableFileList.onFileUploadComplete = function(iframe, file) {
  var response = JSON.decode($(iframe.contentWindow.document.body).get('text'));
  var fileList = 0;
  var fileIndex = null;
  var files = [];
  for (var i=0; i<VuodenHuiput.EditableFileList.fileLists.length; i++) {
    fileList = VuodenHuiput.EditableFileList.fileLists[i];
    files = JSON.decode(fileList.inputElement.get('value'));
    for (var j=0; j<files.length; j++) {
      if (files[j].uploadId == file.uploadId) {
        fileIndex = j;
        break;
      }
    }
    if (fileIndex !== null) {
      break;
    }
  }
  if (!response) {
    files.splice(fileIndex, 1);
    alert('Tiedoston lähettäminen epäonnistui.');
  }
  if (response.success) {
    files[fileIndex].name = response.name;
    files[fileIndex].tempName = response.tempName;
    files[fileIndex].uploading = false;
  } else {
    files.splice(fileIndex, 1);
    alert('Tiedoston lähettäminen epäonnistui.');
  }
  fileList.inputElement.set('value', JSON.encode(files));
  iframe.dispose();
  fileList.refresh();
  fileList.fireEvent('uploadcomplete');
};




VuodenHuiput.CompetitionEntryTeamControl = new Class({
  roles: [
    'Suunnittelutoimisto / Design Agency',
    'Creative Director',
    'Art Director',
    'Graafinen suunnittelija / Graphic Designer',
    'Kuvittaja / Illustrator',
    'Graafinen viimeistelijä / Graphic Design Assistant',
    'Copywriter',
    'Toimittaja / Editor',
    'Kirjoittaja / Writer',
    'Asiakkaan vastuuhenkilö / Client’s Representative',
    'Projektinjohto / Project Management',
    'Strategiajohtaja / Strategy Manager',
    'Planner',
    'Valokuvat / Photographs',
    'Kuvankäsittely / Image Editing',
    'Ohjaaja / Director',
    'Kuvaaja / Cinematographer',
    'Leikkaaja / Editor',
    'Ääni / Sound',
    'Esiintyjät / Performers',
    'Musiikki / Music',
    'Mediatoimisto / Media Agency',
    'Tuottaja / Producer',
    'Tuotantoyhtiö / Production House',
    'Painotalo / Printing House',
    'Repro / Reproduction',
    'Kustantaja / Publisher',
    'Web Designer',
    '3D-animaatio / 3D Animation',
    'Tekninen suunnittelu / Technical Designer',
    'Designer',
    'Senior Designer',
    'Konseptisuunnittelija / Concept Designer',
    'Lavastus / Set Design',
    'Jälkituotanto / Post Production',
    'Yhteisötuotanto / Community Management',
    'Muut suunnitteluun vaikuttaneet henkilöt / The design was also influenced by'
  ],  
  
  container: null,
  inputElement: null,
  nameInput: null,
  roleSelect: null,
  overText: null,
  
  refresh: function() {
    this.container.innerHTML = '';
    var unsortedPersons = JSON.decode(this.inputElement.get('value'));
    if (!unsortedPersons) {
      unsortedPersons = [];
    }
    
    var persons = [];
    
    for (var i=0; i<this.roles.length; i++) {
      for (var j=0; j<unsortedPersons.length; j++) {
        if (unsortedPersons[j].role == this.roles[i]) {
          persons.push(unsortedPersons[j]);
        }
      }
    }
    
    for (i=0; i<unsortedPersons.length;i++) {
      var found = false;
      for (j=0; j<persons.length;j++) {
        if (persons[j].role == unsortedPersons[i].role && persons[j].name == unsortedPersons[i].name) {
          found = true;
        }
      }
      if (!found) {
        persons.push(unsortedPersons[i]);
      }  
    }
    
    for (i=0; i<persons.length; i++) {
      var element = new Element('div', {
        'class': 'column column-width-3 team-member',
        'html': '<div class="name"><input type="text" value="'+persons[i].name+'"/></div><div class="role">'+persons[i].role+'</div>'
      });
      
      var nameInput = element.getElement('input[type=text]');
      nameInput.addEvent('change', this.onEditTeamMember.bind(this, [persons[i].name, persons[i].role, nameInput]));
      nameInput.addEvent('keypress', function(event, nameInput) {
        if (event.key == 'enter') {
          event.stopPropagation();
          event.stop();
          event.preventDefault();
          nameInput.blur();
          return false;
        }
      }.bind(this, nameInput));
      
      element.addEvent('mouseover', function(element) {
        element.addClass('emphasized-block');
      }.bind(this, element));
      element.addEvent('mouseout', function(element) {
        element.removeClass('emphasized-block');
      }.bind(this, element));
      
      var removeTeamMember = new Element('img', {
        'class': 'remove',
        'alt': 'Poista tekijä',
        'title': 'Poista tekijä',
        'src': '/common_files/images/icons/buttons/delete.png'
      });
      
      //removeTeamMember.addEvent('click', this.onRemoveTeamMemberClick.bind(this, persons[i].name, persons[i].role));
      removeTeamMember.addEvent('click', function( i ) { this.onRemoveTeamMemberClick(persons[i].name, persons[i].role ); }.bind(this, i));
      
      removeTeamMember.inject(element);
      element.inject(this.container);
      
      if ((i%2) === 0) {
        element.addClass('first');
      } else {
        (new Element('div', { 'class': 'clear' })).inject(this.container);
      }
    }
  
    if ((persons.length%2) == 1) {
      (new Element('div', { 'class': 'clear' })).inject(this.container);
    }
  },
  
  onEditTeamMember: function(name, role, newNameInput) {
    var newName = newNameInput.get('value');
    var persons = JSON.decode(this.inputElement.get('value'));
    for( i = 0; i < persons.length; i++ ) {
        if( persons[i].name == name && persons[i].role == role ) {
          persons[i].name = newName;
        }
    }
    this.inputElement.set('value', JSON.encode(persons));
    this.nameInput.set('value', '');
    this.refresh();
  },
  
  onRemoveTeamMemberClick: function(name, role) {
    var persons = JSON.decode(this.inputElement.get('value'));
    var newPersons = []
    for( i = 0; i < persons.length; i++ ) {
        if( persons[i].name == name && persons[i].role == role ) {}
        else newPersons.push( persons[i] );
    }
    //persons.splice(memberNum, 1);
    this.inputElement.set('value', JSON.encode(newPersons));
    this.nameInput.set('value', '');
    this.refresh();
  },
  
  onAddButtonClick: function(event) {
    if (!VuodenHuiput.isEmpty(this.nameInput.get('value'))) {
      var persons = JSON.decode(this.inputElement.get('value'));
      persons.push({ 'name': this.nameInput.get('value'), 'role': this.roleSelect.get('value') });
      this.inputElement.set('value', JSON.encode(persons));
      this.nameInput.set('value', '');
      this.refresh();
      this.overText.show();
    }
  },
  
  initialize: function(inputElement) {
    this.inputElement = inputElement;
    if (this.inputElement.get('value') == '') {
      this.inputElement.set('value', '[]');
    }
    this.inputElement.setStyle('display', 'none');
    this.container = new Element('div');
    this.container.inject(inputElement, 'after');
    
    this.formElement = new Element('div', {
      'class': 'column column-width-3 first add-team-member-form'
    });
    
    var nameLabel = new Element('label', { 'html': 'Tekijän nimi:' });
    nameLabel.inject(this.formElement);
    this.nameInput = new Element('input', {
      'type': 'text',
      'alt': 'Kirjoita tähän tekijän nimi'
    });
    this.nameInput.inject(nameLabel);
    this.nameInput.addEvent('keypress', function(event) {
      if (event.key == 'enter') {
        this.nameInput.blur();
        event.stopPropagation();
        event.stop();
        event.preventDefault();
        this.onAddButtonClick(null);
        return false;
      }
    }.bind(this));

  
    var roleLabel = new Element('label', { 'html': 'Rooli:' });
    roleLabel.inject(this.formElement);
    this.roleSelect = new Element('select');
    for (var i=0; i<this.roles.length; i++) {
      var option = new Element('option', {
      'value': this.roles[i],
      'html': this.roles[i]
      });
      option.inject(this.roleSelect);
    }
    this.roleSelect.inject(roleLabel);
    
    this.addButton = new Element('div', {
      'class': 'button small',
      'html': '<span>Lisää tekijä</span>'
    });
    
    this.addButton.addEvent('click', this.onAddButtonClick.bind(this));
    
    this.addButton.inject(this.formElement);
    
    this.formElement.inject(this.container, 'after');
  
    (new Element('div', {'class': 'clear'})).inject(this.formElement, 'after');
    
    this.overText = new OverText(this.nameInput);
  
    this.refresh();
  }
});

VuodenHuiput.CompetitionCategorySelection = new Class({
  Implements: [Events],
  formElement: null,
  categoryInput: null,
  categorySelect0Container: null,
  categorySelect1Container: null,
  categorySelect2Container: null,
  categorySelect1: null,
  categorySelect2: null,
  categories: null,
  boundOnCategorySelection0Change: null,
  boundOnCategorySelection1Change: null,
  boundOnCategorySelection2Change: null,
  currentCategoryTypeName: null,
  currentCategoryGroupName: null,
  validationMessage: null,
  
  getCategory: function(code) {
    for (var i=0; i<this.categories.length; i++) {
      for (var j=0; j<this.categories[i].categories.length; j++) {
      for (var k=0; k<this.categories[i].categories[j].subcategories.length; k++) {
        if (this.categories[i].categories[j].subcategories[k].code == code) {
        return this.categories[i].categories[j].subcategories[k];
        }
      }
      }
    }
    return null;
  },
  
  getCurrentCategoryCode: function() {
    return this.categoryInput.get('value');
  },

  getCurrentCategory: function() {
    return this.getCategory(this.getCurrentCategoryCode());
  },
  
  getCurrentCategoryGroup: function() {
    var currentCategoryCode = this.getCurrentCategoryCode();
    for (var i=0; i<this.categories.length; i++) {
      for (var j=0; j<this.categories[i].categories.length; j++) {
      for (var k=0; k<this.categories[i].categories[j].subcategories.length; k++) {
        if (this.categories[i].categories[j].subcategories[k].code == currentCategoryCode) {
        return this.categories[i].categories[j];
        }
      }
      }
    }
    return null;
  },
  
  displayCategoryTypes: function() {
    this.categorySelect0Container.innerHTML = '';
    for (var i=0; i<this.categories.length; i++) {
      // Hard coded name check for young creatives category
      if (this.categories[i].name != 'Nuoret Luovat') {
        var radioElement = new Element('input', {
          'type': 'radio',
          'class': 'radio',
          'name': 'category_select_0',
          'value': this.categories[i].name,
          'id': 'category_select_0'+i
        });
      
        if (this.currentCategoryTypeName) {
          if (this.categories[i].name == this.currentCategoryTypeName) {
            radioElement.set('checked', true);
          }
        }
      
        var labelElement = new Element('label', {
          'html': this.categories[i].name,
          'for': 'category_select_0'+i
        });
        
        radioElement.inject(this.categorySelect0Container);
        labelElement.inject(radioElement, 'after');
        radioElement.addEvent('click', this.boundOnCategorySelection0Change);
        (new Element('br')).inject(labelElement, 'after');
      }
    }
  },
  
  displayCategoryGroups: function() {
    this.categorySelect1.innerHTML = '';
    this.categorySelect1Container.setStyle('display', 'none');
  
    this.categorySelect2.innerHTML = '';
    this.categorySelect2Container.setStyle('display', 'none');
    
    var selectedIndex = -1;
    
    if (this.currentCategoryTypeName) {
      this.categorySelect1Container.setStyle('display', 'block');
      for (var i=0; i<this.categories.length; i++) {
        if (this.categories[i].name == this.currentCategoryTypeName) {
          for (var j=0; j<this.categories[i].categories.length; j++) {
            var newOption = new Element('option', {
              'value': this.categories[i].categories[j].name,
              'html': this.categories[i].categories[j].name
            });
            if (this.currentCategoryGroupName) {
              if (this.currentCategoryGroupName == this.categories[i].categories[j].name) {
                selectedIndex = j;
              }
            }
            newOption.inject(this.categorySelect1, 'bottom');
          }
        }
      }
    }
    this.categorySelect1.selectedIndex = selectedIndex;
  },
  
  displayCategories: function() {
    var selectedIndex = -1;
    this.categorySelect2.innerHTML = '';
    if (this.currentCategoryGroupName) {
      for (var i=0; i<this.categories.length; i++) {
        for (var j=0; j<this.categories[i].categories.length; j++) {
          if (this.categories[i].categories[j].name == this.categorySelect1.options[this.categorySelect1.selectedIndex].get('value')) {
            for (var k=0; k<this.categories[i].categories[j].subcategories.length; k++) {
              var newOption = new Element('option', {
                'value': this.categories[i].categories[j].subcategories[k].code,
                'html': this.categories[i].categories[j].subcategories[k].name
              });
              
              if (this.categories[i].categories[j].subcategories[k].code == this.categoryInput.get('value')) {
                selectedIndex = k;
              }
              
              newOption.inject(this.categorySelect2, 'bottom');
              var categorySelection2Container = this.categorySelect2.getParent('.category-selection-2');
              if (categorySelection2Container.getStyle('display') == 'none') {
                categorySelection2Container.setStyle('opacity', '0');
                categorySelection2Container.set('morph', {duration: '90', transition: 'quad:out'});
                categorySelection2Container.morph({ opacity: 1 });
                categorySelection2Container.setStyle('display', 'block');
              }
            }
            break;
          }
        }
      }
    }
    this.categorySelect2.selectedIndex = selectedIndex;
  },
  
  onCategorySelection0Change: function(event) {
    this.categoryInput.set('value', '');
    this.currentCategoryTypeName = this.categorySelect0Container.toQueryString().parseQueryString().category_select_0;
    this.displayCategoryGroups();
  },
  
  onCategorySelection1Change: function(event) {
    this.categoryInput.set('value', '');
    this.currentCategoryGroupName = this.categorySelect1Container.toQueryString().parseQueryString().category_select_1;
    this.displayCategories();
  },
  
  onCategorySelection2Change: function(event) {
    this.categoryInput.set('value', this.categorySelect2.options[this.categorySelect2.selectedIndex].get('value'));
    this.fireEvent('categorychange');
  },
  
  clearValidation: function() {
    this.categorySelect1.removeClass('invalid');
    this.categorySelect2.removeClass('invalid');
  },
  
  validate: function() {
    var isValid = true;
  
  /*  var values0 = this.categorySelect0Container.toQueryString().parseQueryString();
    if (VuodenHuiput.isEmpty(values0.category_select_0)) {
      isValid = false;
    }*/
  
    if (this.categorySelect1.selectedIndex == -1) {
  //    isValid = false;
      this.categorySelect1.addClass('invalid');
      this.categorySelect1.addEvent('change', this.boundValidate);
    } else {
      this.categorySelect1.removeClass('invalid');
      this.categorySelect1.removeEvent('change', this.boundValidate);
    }
  
    if (this.categorySelect2.selectedIndex == -1) {
  //    isValid = false;
      this.categorySelect2.addClass('invalid');
      this.categorySelect2.addEvent('change', this.boundValidate);
    } else {
      this.categorySelect2.removeClass('invalid');
      this.categorySelect2.removeEvent('change', this.boundValidate);
    }
    
    if (VuodenHuiput.isEmpty(this.categoryInput.get('value'))) {
      isValid = false;
    }
    
    this.validationMessage = 'Valitse kilpailukategoria, kilpailusarja ja alasarja.';
    
    return isValid;
  },
  
  refresh: function() {
    this.currentCategoryTypeName = null;
    this.currentCategoryGroupName = null;
    for (var i=0; i<this.categories.length; i++) {
      for (var j=0; j<this.categories[i].categories.length; j++) {
      for (var k=0; k<this.categories[i].categories[j].subcategories.length; k++) {
        if (this.categories[i].categories[j].subcategories[k].code == this.categoryInput.get('value')) {
        this.currentCategoryTypeName = this.categories[i].name;
        this.currentCategoryGroupName = this.categories[i].categories[j].name;
        }
      }
      }
    }
    this.displayCategoryTypes();
    this.displayCategoryGroups();
    this.displayCategories();
    },
    
    setCategory: function(categoryCode) {
    this.categoryInput.set('value', categoryCode);
    this.refresh();
    },
    
    initialize: function(formElement, categories) {
    this.categories = categories;
    this.formElement = formElement;
    this.categoryInput = formElement.getElement('input[name=category]');
    this.categoryInput.setStyle('display', 'none');
    
    this.boundOnCategorySelection0Change = this.onCategorySelection0Change.bind(this);
    this.boundOnCategorySelection1Change = this.onCategorySelection1Change.bind(this);
    this.boundOnCategorySelection2Change = this.onCategorySelection2Change.bind(this);
    
    this.boundValidate = this.validate.bind(this);
  
    this.categorySelect0Container = new Element('div', {
      'class': 'column column-width-2 first category-selection-0'
    });
  
    this.categorySelect1Container = new Element('div', {
      'class': 'column column-width-2 category-selection-1',
      'style': 'display: none',
      'html': '<h4>...sarja</h4>'
    });
  
    this.categorySelect2Container = new Element('div', {
      'class': 'column column-width-2 category-selection-2',
      'style': 'display: none',
      'html': '<h4>...ja alasarja</h4>'
    });
  
    this.categorySelect1 = new Element('select', { 'name': 'category_select_1', size: '6' });
    this.categorySelect1.inject(this.categorySelect1Container);
    this.categorySelect1.addEvent('change', this.boundOnCategorySelection1Change);
  
    this.categorySelect2 = new Element('select', { 'name': 'category_select_2', size: '6' });
    this.categorySelect2.inject(this.categorySelect2Container);
    this.categorySelect2.addEvent('change', this.boundOnCategorySelection2Change);
    
    this.categorySelect0Container.inject(this.categoryInput, 'after');
    this.categorySelect1Container.inject(this.categorySelect0Container, 'after');
    this.categorySelect2Container.inject(this.categorySelect1Container, 'after');
    (new Element('div', { 'class': 'clear' })).inject(this.categorySelect2Container, 'after');
  
    this.refresh();
  }
});