/*
Copyright (c) 2012, Bartłomiej Nitoń
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

$(function() {

///////////////////////////
$('form.voc-download-form').live('submit', download_form_submit);
//////////////////////////
   
  //$("button#get-vocabulary-file").click(function(){
    //vocabulary_name = $('#vocabulary-select').val();
    //format = $('#vocabulary-format-select').val();
  //  get_vocabulary_file(vocabulary_name, format)});
    
  $("button#remove-lemma").click(function(){
    vocabulary_name = $('#vocabulary-select').val();
    delete_lemma(vocabulary_name, '.lemma-add-form')});
    
  $('#vocabulary-select').live('change', show_vocabulary_info);
  $('form.vocab-perm-manage-form').live('submit', vocab_perm_manage_form_submit);
  $('form.lemma-add-form').live('submit', lemma_add_form_submit);
  
//attach autocomplete  
  $('input#id_base_lemma').autocomplete({  
    //define callback to format results  
    source: function(req, add){  
    //pass request to server  
      $.getJSON(ajax_lemma_lookup, req, function(data) {  
    //create array for response objects  
        var suggestions = [];  
        $.each(data['result'], function(i, val){  
          suggestions.push(val[0]);  
        });  
  
        //pass array to callback  
        add(suggestions);  
      });  
    },  
  });  
// end attach autocomplete
  show_vocabulary_info(); 
});

function delete_lemma(vocabulary_name, form_selector) {
    ShowProgressAnimation();
    if(!vocabulary_name)
    {
      HideProgressAnimation();
      error_alert('Aby usunąć hasło musisz wybrać słownik, z którego ono pochodzi.')
      return false;
    }
    
    HideProgressAnimation();
    if(confirm("Czy jesteś pewien, że chcesz usunąć wybrane hasło?"))
      ShowProgressAnimation();
    else
      return false;
	
	this_form = $(form_selector);	
    form_data = this_form.serializeArray();
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'entry' && elem.name != 'base_lemma')
        return elem;
      else {
        if (elem.name == 'entry')
          entry = elem.value;
        else if (elem.name == 'base_lemma')
          base_lemma = elem.value;
      }
    });

	form_data.push({name: 'entry', value: entry});
    form_data.push({name: 'base_lemma', value: base_lemma});
    form_data.push({name: 'vocabulary_name', value: vocabulary_name});

    $.ajaxJSON({
      method: 'post',
      url: ajax_delete_lemma,
      data: {
        form_data: form_data
      },

    callback: function(result) { 
      resetForm(this_form);  
      HideProgressAnimation();
      alert('Hasło usunięto pomyślnie.') 
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
      if (result == 'entry not selected') {
        HideProgressAnimation();
        error_alert('Wybierz nazwę hasła.');
        return false;
      }
      else if (result == 'whitespace in entry') {
        HideProgressAnimation();
        error_alert('Nazwa hasła zawiera białe znaki.');
        return false;
      }
      else if (result == 'lemma not exist') {
        HideProgressAnimation();
        error_alert('Nie można usunąć hasła, które nie istnieje.');
        return false;
      }
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
}

function lemma_add_form_submit() {

    if(confirm("Czy jesteś pewien, że chcesz dodać nowe hasło?"));
    else
      return false;
    
    ShowProgressAnimation();
    
    vocabulary_name = $('#vocabulary-select').val();
    if(!vocabulary_name)
    {
      HideProgressAnimation();
      error_alert('Aby zapisać hasło musisz wybrać słownik.')
      return false;
    }
	
	this_form = $(this);	
    form_data = this_form.serializeArray();
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'entry' && elem.name != 'base_lemma')
        return elem;
      else {
        if (elem.name == 'entry')
          entry = elem.value;
        else if (elem.name == 'base_lemma')
          base_lemma = elem.value;
      }
    });

	form_data.push({name: 'entry', value: entry});
    form_data.push({name: 'base_lemma', value: base_lemma});
    form_data.push({name: 'vocabulary_name', value: vocabulary_name});

    $.ajaxJSON({
      method: 'post',
      url: ajax_lemma_add_form_submit,
      data: {
        form_data: form_data
      },

    callback: function(result) { 
      resetForm(this_form);  
      HideProgressAnimation();
      alert('Hasło dodano pomyślnie.') 
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
      if (result == 'entry not selected') {
        HideProgressAnimation();
        error_alert('Wybierz nazwę hasła.');
        return false;
      }
      else if (result == 'whitespace in entry') {
        HideProgressAnimation();
        error_alert('Nazwa hasła zawiera białe znaki.');
        return false;
      }
      else if (result == 'lemma exist') {
        HideProgressAnimation();
        error_alert('Hasło istnieje już w wybranym słowniku.');
        return false;
      }
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
}

function vocab_perm_manage_form_submit() {
    ShowProgressAnimation();
	this_form = $(this);	
    form_data = this_form.serializeArray();
    var managers = new Array();
    var editors = new Array();
    var viewers = new Array();
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'managers' && elem.name != 'editors' &&
         elem.name != 'viewers')
        return elem;
      else {
        if (elem.name == 'managers')
          managers.push(elem.value);
        else if (elem.name == 'editors')
          editors.push(elem.value);
        else if (elem.name == 'viewers')
          viewers.push(elem.value);
      }
    });

	form_data.push({name: 'managers', value: managers});
    form_data.push({name: 'editors', value: editors});
    form_data.push({name: 'viewers', value: viewers});
    form_data.push({name: 'vocabulary_name', value: $('#vocabulary-select').val()});

    $.ajaxJSON({
      method: 'post',
      url: ajax_vocab_perm_manage_form_submit,
      data: {
        form_data: form_data
      },

    callback: function(result) {      
      HideProgressAnimation();
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
      HideProgressAnimation();
      return true;
    },
  });
  return false;
}


function show_vocabulary_info()
{ 
  vocabulary_name = $('#vocabulary-select').val();
  if(vocabulary_name)
  {
    $('#vocabulary-perm-management').load(ajax_vocab_perm_manage_form, "vocabulary_name="+vocabulary_name);
    $('#vocabulary-statistisc').load(ajax_get_vocabulary_stats, "vocabulary_name="+vocabulary_name);
  }
  else
  {
    $('#vocabulary-perm-management').empty();
    $('#vocabulary-statistisc').load(ajax_get_vocabulary_stats, "vocabulary_name=");
  }
}

//////////////////////////////////////////////

function download_form_submit() {
    ShowProgressAnimation();
	this_form = $(this);
    form_data = this_form.serializeArray();
    
    var vocabularies = new Array();
    var frame_opinions = new Array();
    var lemma_statuses = new Array();
    var realizations = new Array();
    var owners = new Array();
  
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'vocabulary' && elem.name != 'format'
         && elem.name != 'frame_opinion' && elem.name != 'lemma_status' &&
         elem.name != 'realization' && elem.name != 'owner')
        return elem;
      else {
        if (elem.name == 'vocabulary')
          vocabularies.push(elem.value);
        else if (elem.name == 'format')
          format = elem.value;
        else if (elem.name == 'frame_opinion')
          frame_opinions.push(elem.value);
        else if (elem.name == 'lemma_status')
          lemma_statuses.push(elem.value);
        else if (elem.name == 'owner')
          owners.push(elem.value);
        else if (elem.name == 'realization')  
          realizations.push(elem.value);
      }
    });

	form_data.push({name: 'vocabularies', value: vocabularies});
	form_data.push({name: 'format', value: format});
    form_data.push({name: 'frame_opinions', value: frame_opinions});
    form_data.push({name: 'lemma_statuses', value: lemma_statuses});
    form_data.push({name: 'owners', value: owners});
    form_data.push({name: 'realizations', value: realizations});

    $.ajaxJSON({
      method: 'post',
      url: ajax_create_vocabulary,
      data: {
        form_data: form_data
      },

    callback: function(result) {    
	    HideProgressAnimation();
      lemma_view_location = window.location.toString();
    // trzeba by to moze z czasem poprawic na cos madrzejszego
      //alert(result['file_name'])
      var url = lemma_view_location.replace('/slowniki/', '/slowniki/'+result['file_name']);
      window.open(url,'Download');
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
      error_alert(status + ': ' + error);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      //if (ctrl)
      //  ctrl.remove();
      if (result == 'format not selected') {
        HideProgressAnimation();
        error_alert('Wybierz format pliku wyjściowego.');
        return false;
      }
      else if (result == 'creating vocabulary error') {
        HideProgressAnimation();
        error_alert('Nie udało się utworzyć słownika.');
        return false;
      }
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
}
////////////////////////////////////////////

function get_vocabulary_file(vocabulary_name, format) {
    ShowProgressAnimation();
    if(!vocabulary_name || !format)
    {
      HideProgressAnimation();
      error_alert('Wybierz słownik i format pliku wyjściowego.');
      return false;
    }

    $.ajaxJSON({
      method: 'post', 
      url: ajax_create_vocabulary,
      data: {
        vocabulary_name: vocabulary_name,
        format: format
    },

    callback: function(result) {      
      HideProgressAnimation();
      lemma_view_location = window.location.toString();
    // trzeba by to moze z czasem poprawic na cos madrzejszego
      var url = lemma_view_location.replace('/slowniki/', '/slowniki/'+vocabulary_name);
      window.open(url,'Download');
    },
    error_callback: function(xhr, status, error) {
      HideProgressAnimation();
    //  error_alert(status + ': ' + error);
      //if (ctrl)
      //  ctrl.remove();
    },
    bad_data_callback: function(result) {
      if (result == 'creating vocabulary error') {
        HideProgressAnimation();
        error_alert('Wystąpił błąd podczas tworzenia pliku słownikowego.');
        return false;
      }
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;

}
