/*
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() {
  window.selected_real_row_id = -1;
  $('#main-argument').load(ajax_realization_arg_form, "form_data=main_argument")
  $('#create-realization').load(ajax_realization_arg_form, "form_data=")
  
  $('#main-argument .argument-add-form #id_arg_model_name').live('change', main_argument_model_change);
  $('#main-argument .argument-add-form #id_atr_value').live('change', main_atribute_value_change);
  
  $('#create-realization .argument-add-form #id_arg_model_name').live('change', real_argument_model_change);
  $('#create-realization .argument-add-form #id_atr_value').live('change', real_atribute_value_change);
  
  //$('#main-argument .argument-add-form').live('submit', show_realizations);
  
  $('#create-realization .argument-add-form').live('submit', add_realization);
});

function removeRealization(tabId)
{
  ShowProgressAnimation();
  if(tabId != -1)
  {
    realization_id = tabId.replace('realization_', ''); 
    
    main_arg_form = $('#main-argument .argument-add-form');
    main_arg_data = main_arg_form.serializeArray();
    
    main_arg_data = $.map(main_arg_data, function(elem)
    {
      if (elem.name != 'arg_model_name' && elem.name != 'atr_value')
        return elem;
      else {
        if (elem.name == 'arg_model_name')
          type = elem.value.trim();
        else if (elem.name == 'atr_value')
          values.push(elem.value.trim());
      }
    });
  
    main_arg_data.push({name: 'arg_model_name', value: type});
    main_arg_data.push({name: 'atr_values', value: values});
     
    $.ajaxJSON({
      method: 'post',
      url: ajax_remove_realization,
      data: {
        realization_id: realization_id,
        main_arg_data: main_arg_data 
      },

      callback: function(result) { 
       // grid.trigger("reloadGrid");
       window.selected_real_row_id = -1;
       show_realizations();	
       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();
        if (result == 'empty main argument fields') {
          HideProgressAnimation();
          error_alert('Wypełnij wszystkie pola formularza wyboru argumentu głównego.');
          return false;
        }
        else
        {
          HideProgressAnimation();
          return true;
        }
      },
    });
  }	
}

function main_argument_model_change()
{
  arguments_form_change(true, '', true);
  //$('#realizations').empty();
 // show_realizations();
}

function main_atribute_value_change()
{
  arguments_form_change(false, '', true);
  //$('#realizations').empty();
  //show_realizations();
}

function real_argument_model_change()
{
  arguments_form_change(true, '', false)
}

function real_atribute_value_change()
{
  arguments_form_change(false, '', false)
}

function arguments_form_change(arg_model_change, arg_text_rep, main_argument) {
    if(main_argument)
      this_form = $('#main-argument .argument-add-form');
    else
      this_form = $('#create-realization .argument-add-form');
    form_data = this_form.serializeArray();
      
    type = ''
    values = [];
  
  	if(!arg_text_rep)
  	{
      form_data = $.map(form_data, function(elem)
      {
        if (elem.name != 'arg_model_name' && elem.name != 'atr_value') 
          return elem;
        else {
          if (elem.name == 'arg_model_name')
            type = elem.value;
          else if (elem.name == 'atr_value')
            values.push(elem.value);
        }
      });
      
      form_data.push({name: 'arg_model_name', value: type});
      form_data.push({name: 'atr_values', value: values});
      form_data.push({name: 'main_argument', value: main_argument});
    
      if(arg_model_change)
        form_data.push({name: 'arg_model_change', value: 'arg_model_changed'});
      else
        form_data.push({name: 'arg_model_change', value: ''});
      
      form_data.push({name: 'arg_text_rep', value: ''});
    }
    else
      form_data.push({name: 'arg_text_rep', value: arg_text_rep});
    
    data = JSON.stringify(form_data)
    
    if(main_argument)
    {
      $('#main-argument').load(ajax_realization_arg_form, "form_data="+data, function(){
        show_realizations();
      });
    }
    else
      $('#create-realization').load(ajax_realization_arg_form, "form_data="+data);
} 

function show_realizations() {
    window.selected_real_row_id = -1;
    this_form = $('#main-argument .argument-add-form');
    form_data = this_form.serializeArray();
      
    type = ''
    values = [];
    
    form_data = $.map(form_data, function(elem)
    {
      if (elem.name != 'arg_model_name' && elem.name != 'atr_value') 
        return elem;
      else {
        if (elem.name == 'arg_model_name')
          type = elem.value;
        else if (elem.name == 'atr_value')
          values.push(elem.value);
      }
    });
      
    form_data.push({name: 'arg_model_name', value: type});
    form_data.push({name: 'atr_values', value: values});
    form_data.push({name: 'manage', value: true});
    
    data = JSON.stringify(form_data)
    $('#realizations').load(ajax_show_realizations, "form_data="+data, function(){
      $("tr.RealizationTableRow").click(function(){
        selectTr(this.id)});
        
      $("#delete-realization").click(function(e){
        removeRealization(window.selected_real_row_id)});
    });
    
    return false;
}

function add_realization() {
    ShowProgressAnimation()
    realization_form = $(this);
    realization_data = realization_form.serializeArray();
    
    main_arg_form = $('#main-argument .argument-add-form');
    main_arg_data = main_arg_form.serializeArray();
      
    real_type = '';
    real_values = [];
  
    realization_data = $.map(realization_data, function(elem)
    {
      if (elem.name != 'arg_model_name' && elem.name != 'atr_value')
        return elem;
      else {
        if (elem.name == 'arg_model_name')
          real_type = elem.value.trim();
        else if (elem.name == 'atr_value')
          real_values.push(elem.value.trim());
      }
    });
  
    realization_data.push({name: 'arg_model_name', value: real_type});
    realization_data.push({name: 'atr_values', value: real_values});
    
    type = '';
    values = [];
    
    main_arg_data = $.map(main_arg_data, function(elem)
    {
      if (elem.name != 'arg_model_name' && elem.name != 'atr_value')
        return elem;
      else {
        if (elem.name == 'arg_model_name')
          type = elem.value.trim();
        else if (elem.name == 'atr_value')
          values.push(elem.value.trim());
      }
    });
  
    main_arg_data.push({name: 'arg_model_name', value: type});
    main_arg_data.push({name: 'atr_values', value: values});

    $.ajaxJSON({
      method: 'post',
      url: ajax_add_arg_realization,
      data: {
        main_arg_data: main_arg_data,
        realization_data: realization_data
      },

    callback: function(result) { 
      show_realizations();     
      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();
      if (result == 'empty main argument fields') {
        HideProgressAnimation();
        error_alert('Wypełnij wszystkie pola formularza wyboru argumentu głównego.');
        return false;
      }
      else if (result == 'empty realization argument fields') {
        HideProgressAnimation();
        error_alert('Wypełnij wszystkie pola formularza wyboru realizacji.');
        return false;
      }
      else
      {
        HideProgressAnimation();
        return true;
      }
    },
  });
  return false;
}

function selectTr(id)
{  	  
  	if(selected_real_row_id != -1)
  	{
  	  var recent_row = document.getElementById(selected_real_row_id);
  	  var recent_descendants = getDescendantsNodes(recent_row);
  	  for(var i = 0; i<recent_descendants.length; i++)
  	    $(recent_descendants[i]).css("background-color", "");
  	}
  	
  	if(selected_real_row_id == id)
  	  selected_real_row_id = -1;
  	else
  	{
  	  selected_real_row_id = id;
  	  var row = document.getElementById(id);
  	  var descendants = getDescendantsNodes(row);
  	  for(var i = 0; i<descendants.length; i++)
  	    $(descendants[i]).css("background-color", "LightSteelBlue");  
  	}
}

