/*
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.
*/

var activeLemmaPanel = 'new_frames';

$(function(){

  jQuery(window).unload(function() {
    gridPreviewContent(false);
  });

  $('.tabs').tabs().bind('tabsselect', function(event, ui) {
      if(ui.panel.id == 'preview_lemma')
      {
        setTimeout(function () {
          $(window).trigger('resize');
        }, 30);
        window.activeLemmaPanel = ui.panel.id;
        gridPreviewContent(true);
      }
      else if(ui.panel.id == 'new_frames')
      {
        setTimeout(function () {
          $(window).trigger('resize');
        }, 30);
        window.activeLemmaPanel = ui.panel.id;
        
        gridPreviewContent(false);
      }
      else if( ui.panel.id == 'old_frames' || ui.panel.id == 'notes' || ui.panel.id == 'examples' || 
             ui.panel.id == 'change_ctrl' || ui.panel.id == 'status')
      {
        window.activeLemmaPanel = ui.panel.id;
        gridPreviewContent(false);
      }  
  });
  $('')
  $('button').button();
  $('.ui-state-default').live('mouseover', function() {
    $(this).addClass('ui-state-hover');
  });
  $('.ui-state-default').live('mouseout', function() {
    $(this).removeClass('ui-state-hover');
  });
});

$.fn.disable = function() {
  return this.prop('disabled', true);
};

$.fn.enable = function() {
  return this.prop('disabled', false);
};

$.fn.value = function() {
  if (this.is(':checkbox'))
    return this.is(':checked');
  else if (this.is(':radio'))
    return this.is(':checked')? this.val() : null;
  else
    return this.val();
};

$.fn.bind_hover = function(c) {
  var elem = this;
  this.hover(
    function() {elem.addClass(c);},
    function() {elem.removeClass(c);}
  );
};

function multiselect_toggle(select, option_value, enable) {
  select = $(select);
  widget = select.multiselect("widget");
  option = widget.find('[value="' + option_value + '"]');
  if (enable)
    option.enable();
  else
    option.disable();
  option.parent().toggleClass('ui-state-disabled', !enable);
  option.parent().parent().toggleClass('ui-multiselect-disabled', !enable);
};

function multiselect_enable(select, option_value) {
  select = $(select);
  widget = select.multiselect("widget");
  option = widget.find('[value="' + option_value + '"]');
  option.enable();
  option.parent().removeClass('ui-state-disabled');
  option.parent().parent().removeClass('ui-multiselect-disabled');
};

function _(text) {
  return text;
};

function error_alert(text) {
  alert(text);
};

// parametry: method, url, data | description, dest, callback, callback_args
$.ajaxJSON = function(params) {
  var encoded_data = {};
  if (params.save && !before_save())
    return false;
  $.each(params.data, function(key, value) {
    encoded_data[key] = $.toJSON(value);
  });
  $.ajax({
    type: params.method,
    url: params.url,
    dataType: 'json',
    data: encoded_data,
    success: parse_result(params),
    error: params.error_callback
  });
};

function blank(str) {
  re = /^[\t\n ]*$/;
  return re.test(str);
}

// parametry: description, dest, callback, callback_args
function parse_result(params) {
  return function(data, status) {
    if(data.result != 'ok' || status == 'error') {
      if(data.result=='logout')
        error_alert(_("Sesja wygasła - zaloguj się i spróbuj ponownie."));
      else
        if (!params.bad_data_callback || params.bad_data_callback(data.result))
          error_alert(params.description+' '+_("nie powiodło się."));
    }
    else { // OK
      if (params.dest) {
        params.dest.html(data.html);
      }
      if (data.js) {
        eval(data.js); // nie używane
      }
      if (params.callback) {
        if (!params.callback_args)
          params.callback_args = [];
        args = [data].concat(params.callback_args);
        params.callback.apply({}, args);
      }
    }
  }
};

function debug(content) {
  var doc = $('#debug').contents().get(0);
  doc.open();
  doc.writeln(content);
  doc.close();
};

$(function() {
  $('#show-debug').click(function() {
    $('#debug').toggle();
  });
  $('#debug').height($(window).height() - $('#main_menu').height());
  $('#debug').css('top', $('#main_menu').height())
});

function parse_error(event, request, settings) {
  debug(request.responseText);
  $('#show-debug').show();
}

//$.ajaxSetup({global: true, error: parse_error});

$(function() {$('#debug').ajaxError(parse_error);});

$('html').ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

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

function getDescendantsNodes(parent)
{
    var childElements = new Array();
    if(parent.childNodes)
    {
      for(var i=0; i<parent.childNodes.length;i++)
      {
        childElements.push(parent.childNodes[i]);
      }

      for(var i=0; i<parent.childNodes.length; i++)
      {
        var descendants = getDescendantsNodes(parent.childNodes[i]);
        for(var j=0; j<descendants.length; j++)
        {
          childElements.push(descendants[j]);
        }
      }
    }
    return childElements;
}

function gridPreviewContent(isPreview) {
  	      $.ajaxJSON({
            method: 'post',
            url: ajax_preview_select,
            async: false,
            data: {
              isPreview: isPreview, 
              //lemma_id: lemma_id    // obecnie ustawione haslo
            },

            callback: function(result) {
              
              if(result['reload'])
              {
                if(isPreview)
                {
                  window.lastPrevSelectedId = window.prev_lemma_id;
                  grid.trigger("reloadGrid");

                  data = grid.jqGrid('getGridParam', 'postData');
                  data['mask'] = '';
                  data['id'] = window.prev_lemma_id;

                  $.get(ajax_location, data, function(resp) {
                    var selectedRow = resp['selected_id'] + "";
                    var rowIndex = resp['rowIndex'];
                    var recordsCount = resp['records'];
                    if (recordsCount > 0){
                      grid.jqGrid('scrollToRow', rowIndex, recordsCount);
                    }
                  });
                  
                }
                else
                {
               //  alert('nprev')
                  window.lastSelectedId = window.lemma_id;
                  grid.trigger("reloadGrid");

                  data = grid.jqGrid('getGridParam', 'postData');
                  data['mask'] = '';
                  data['id'] = window.lemma_id;

                  $.get(ajax_location, data, function(resp) {
                    var selectedRow = resp['selected_id'] + "";
                    var rowIndex = resp['rowIndex'];
                    var recordsCount = resp['records'];
                    if (recordsCount > 0){
                      grid.jqGrid('scrollToRow', rowIndex, recordsCount);
                    }
                  });
                }
                refresh_column_headers();
              }
            },
    
            error_callback: function(xhr, status, error) {
              error_alert(status + ': ' + error);
      //if (ctrl)
      //  ctrl.remove();
            },
          });
      return false;
}

///////////////////// funkcje ogolnego uzycia /////////////////////////////////

// czyszczenie formularza
function resetForm($form) {
    $form.find('input:text, input:password, input:file, select, textarea').val('');
    $form.find('input:radio, input:checkbox')
         .removeAttr('checked').removeAttr('selected');
}


