var activeLemmaPanel = 'new_frames';
var selectedColor = 'rgb(176, 196, 222)'; // css backgroud color of selected table elements

$(function(){
  $('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();
}

$(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;
}

///////////////////// 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');
    $form.find('#sem-arguments').remove();
}

// funkcja konwertujaca kody html znakow do znakow
function convertHtml(str) {
  str = str.replace(/&#39;/g, '\'');
  str = str.replace(/&quot;/g, '\"');
  str = str.replace(/&amp;/g, '&');
  str = str.replace(/&gt;/g, '>');
  str = str.replace(/&lt;/g, '<');
  return str;
}

String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}

String.prototype.endsWith = function(suffix) {
	if (this.length < suffix.length) return false;
	return this.lastIndexOf(suffix) === this.length - suffix.length;
}
