(function(){

  var isWikiNameSet = false;
  var isAliasSet = false;
  var lastWikiName;

  
  /**
   * Init the event handlers
   */
  function init() {
    if ($('prettyname')) {
      initStepType();
    } else if ($('owner')) {
      initStepUsers();
    }
  }
  
  function initStepType() {
    var prettyName = $('prettyname');
    prettyName.observe('change', prettyNameChanged);
    prettyName.observe('keyup', prettyNameChanged);
    var wikiName   = $('wikiname');
    wikiName.observe('change', wikiNameChanged);
    wikiName.observe('keyup', wikiNameChanged);
    var alias      = $('wikialias');
    if (alias) {
      alias.observe('change', aliasChanged);
      alias.observe('keyup', aliasChanged);
    }
    if(prettyName.value.blank() || wikiName.value.blank()){
      $('wizard-next').disabled = true;
    }
  }

  function initStepUsers() {
    userScopeChanged();
    $$('input[type=radio][name=userScope]').each(function (item){
      item.observe('click', userScopeChanged);
    });
  }

  /**
   * Pretty name changed
   */
  function prettyNameChanged(event){
    var prettyName = $('prettyname');
    if(prettyName.value.blank()){
      $('wikiprettynamevalidation').innerHTML = "Pretty name must not be empty";
      prettyName.addClassName('xErrorField');
    }else{
      $('wikiprettynamevalidation').innerHTML = '';
      prettyName.removeClassName('xErrorField');
      // If the user has manually changed the wikiname, we don't generate it automaticaly anymore
      if(!isWikiNameSet){
        var wikiName = $('wikiname');
        wikiName.value = prettyName.value.replace(/[^a-zA-Z0-9]/g,'_').toLowerCase();
        validateWikiName();
      }
      if(!isAliasSet){
        var wikiAlias = $('wikialias');
        if (wikiAlias) {
          var alias = filterWikiName(prettyName.value.replace(/[^a-zA-Z0-9]/g,'_').toLowerCase());
          alias += getAliasSuffix();
          wikiAlias.value = alias;
        }
      }
    }
  }
  /**
   * Wiki name changed
   */
  function wikiNameChanged(event){
    isWikiNameSet = true;
    validateWikiName();
  }
  /**
   * Alias changed
   */
  function aliasChanged(event){
    isAliasSet = true;
  }
  /**
   * Validate the wiki name
   */
  function validateWikiName(){
    var wikiNameElement = $('wikiname');
    var wikiname = wikiNameElement.value;
    var filteredWikiName = filterWikiName(wikiname);
    if (wikiname != filteredWikiName) {
      wikiNameElement.value = filteredWikiName;
      wikiname = filteredWikiName;
    }
    if (lastWikiName == wikiname){
      return;
    }
    lastWikiName = wikiname;
    if (wikiname && !wikiname.blank()) {
      var surl = "http://wiki.yibaiqin.com:80/bin/view/WikiManager/IsWikiOrDatabaseOrAvailableService" + "?xpage=plain&outputSyntax=plain&ajax=1&wikiname=" + escape(wikiname);
      surl += "&form_token=5u6JR3fIGsTDoHzYDNMmGQ";
      new Ajax.Request(surl, {
        method: 'get',
        onSuccess: function(transport) {
          if (transport.responseText == "true") {
            $('wikinamevalidation').innerHTML = "";
            wikiNameElement.removeClassName('xErrorField');
              if (!$('prettyname').value.blank()) {
                $('wizard-next').disabled = false;
              }
          }
          else if (transport.responseText == "database"){
            $('wikinamevalidation').innerHTML = "A database with this identifier already exists";
            wikiNameElement.addClassName('xErrorField');
            $('wizard-next').disabled = true;
          }
          else if (transport.responseText == "wiki"){
            $('wikinamevalidation').innerHTML = "This identifier is already used";
            wikiNameElement.addClassName('xErrorField');
            $('wizard-next').disabled = true;
          }
          else{
            $('wikinamevalidation').innerHTML = "This identifier is already used";
            wikiNameElement.addClassName('xErrorField');
            $('wizard-next').disabled = true;
          }
        }
      });
    }
    else{
      $('wikinamevalidation').innerHTML = "Identifier can't be empty";
      $('wizard-next').disabled = true;
    }
  }
  /**
   * Filter wiki name
   */
  function filterWikiName(wikiName){
    var result = noaccent(wikiName);

    // The server-side code strips '_' chars from the database name.
    result = result.replace(/[_]/g, "");

    // Classic requirement for an identifier is to start with a letter.
    while (result.length > 0 && !isNaN(result.charAt(0))) {
      result = result.substring(1);
    }

    // Out of all databases, Oracle seems to be the least permissive, limiting schema names to 30 chars.
    if (result.length > 30) {
      result = result.substring(0, 30);
    }

    // Keep IDs lowercased.
    result = result.toLowerCase();

    return result;
  }
  function getAliasSuffix() {
    var suffix = "";
    if (suffix != "") {
      suffix = "." + suffix;
    } else {
      // try to compute the suffix from the request URL
      var hostname = window.location.hostname;
      if (hostname != "localhost" && !hostname.match(/[0-9]{1,3}(?:\.[0-9]{1,3}){3}/g)) {
        suffix = hostname.substr(hostname.indexOf("."));
      }
    }
    return suffix;
}

  function userScopeChanged(){
    var value = $$('input:checked[type=radio][name=userScope]')[0].value
    if (value=='local_only') {
      // Disable membership type radio button
      $$('input[type=radio][name=membershipType]').each(function (item){
        item.disabled = true;
      });
      // Disable the members
      $('members').disabled = true;
    } else {
      // Enable membership type radio button
      $$('input[type=radio][name=membershipType]').each(function (item){
        item.disabled = false;
      });
      // Enable the members
      $('members').disabled = false;
    }
  };

  /**
   * Call Init
   */
  (XWiki && XWiki.domIsLoaded && init()) || document.observe("xwiki:dom:loaded", init);

})();
var XWiki = (function (XWiki) {
// Start XWiki augmentation.
/**
 * Enhances the behaviour of an extension.
 */
XWiki.WikiCreationStatusBar = Class.create({
  initialize : function () {
    // We run the progress bar only if the <div id="ui-progress"> exists
    if ($('ui-progress')) {
      this._callRefresh.bind(this).delay(1);
    }
  },
  _callRefresh : function () {
    // Document URL
    var document = new XWiki.Document('WikiCreationJobStatusService', 'WikiManager');
    var url = document.getURL('get', 'outputSyntax=plain');
    new Ajax.Request(url, {
      method: 'get',
      parameters : {'wikiId': $('wikiId').value},
      onSuccess : function(response) {
        var result = response.responseText.evalJSON(true);
        this._refresh(result);
      }.bind(this)
   });
  },
  _refresh : function (response) {
    if (response.status == 'FINISHED') {
      $('ui-progress').addClassName('hidden');
      // We need to know if we have error
      if (response.error.length > 0) {
        $('errorMessage').removeClassName('hidden');
        $('cleanUp').removeClassName('hidden');
      } else {
        // Success
        $('successMessage').removeClassName('hidden');
        if (response.hasErrorLog) {
          $('errorlogMessage').removeClassName('hidden');
        }
        $('finalize').removeClassName('hidden');
      }
    }
    else {
      var progress = response.progress;
      if (progress != 'null') {
        if (progress < 0)
          progress = 0;
        else if (progress > 1)
          progress = 1;
        $('wikicreation-progress-bar').setStyle({width: (progress*100)+'%'});
      }
      this._callRefresh.bind(this).delay(1);
    }
    // Display logs
    var creationLogContainer = $('creation-log');
    creationLogContainer.innerHTML = response.logs;
    creationLogContainer.firstDescendant().scrollTop=$$('.log-item-loading')[0].offsetTop;
  }
});

var init = function(event) {
  new XWiki.WikiCreationStatusBar();
  return true;
};
// When the document is loaded, trigger the Extension Manager form enhancements.
(XWiki.domIsLoaded && init()) || document.observe("xwiki:dom:loaded", init);

// End XWiki augmentation.
return XWiki;
}(XWiki || {}));
      

/**************************************************************
 * Code to make the dynamic "flavor/template" tab bar
 **************************************************************/
require(['jquery'], function($) {
  $(window).ready(function(){
    $('.flavor_template  > .xwikitabbar > li > a').click(function(event) {
      var thisTabWidget = $(this).parents('.flavor_template');
      // Change the tab bar
      var activeTab = thisTabWidget.find('.xwikitabbar .active');
      activeTab.removeClass('active');
      var targetTab = $(this).parents('li');
      targetTab.addClass('active');
      // Change the tab content
      var activeTabContent = thisTabWidget.find('.xwiki-createwiki-tab.active');
      var targetTabContent = thisTabWidget.find($(this).attr('href') + '-tab');
      activeTabContent.removeClass('active').fadeOut(400, function() {
        // Display the new tab container when the old one is completly hidden
        targetTabContent.hide().fadeIn().removeClass('hidden').addClass('active');
      });
      // Do not follow the link
      return false;
    });
  });
});
/**************************************************************
 * Code to only have a flavor or a template used, never both
 **************************************************************/
require(['jquery'], function($) {
  $(window).ready(function(){
    /**
     * When a template is selected, unselect the flavor
     */
    $('#'+'template').change(function(event) {
      if (this.value != 'xwikinotemplate') {
        $('.xwiki-flavor-picker-option-selected').removeClass('xwiki-flavor-picker-option-selected');
        $('input[name="flavor"]:radio:checked').prop('checked', false);
      }
    });
    
    /**
     * When a flavor is selected, unselect the template
     */
    var onFlavorChanged = function(event) {
      $('#'+'template').val('xwikinotemplate');
    }
    $('input[name="flavor"]:radio').change(onFlavorChanged);
    $('.xwiki-flavor-picker-option').click(onFlavorChanged);
  });
});

