diff --git a/accounts/ajax.py b/accounts/ajax.py
index 791fedc..21ef722 100644
--- a/accounts/ajax.py
+++ b/accounts/ajax.py
@@ -4,19 +4,21 @@ from django.contrib.auth.models import User, Group
 from common.decorators import ajax
 from dictionary.models import Vocabulary
 
+
 @ajax(method='post')
 def set_group(request, user_id, group_id, set):
-  user = User.objects.get(pk=user_id)
-  group = Group.objects.get(pk=group_id)
-  if set:
-    user.groups.add(group)
-  else:
-    user.groups.remove(group)
-  return {}
+    user = User.objects.get(pk=user_id)
+    group = Group.objects.get(pk=group_id)
+    if set:
+        user.groups.add(group)
+    else:
+        user.groups.remove(group)
+    return {}
+
 
 @ajax(method='post')
 def save_default_owner(request, vocab_id):
-  us = request.user.usersettings
-  us.default_owner = Vocabulary.objects.get(pk=vocab_id)
-  us.save()
-  return {}
+    us = request.user.usersettings
+    us.default_owner = Vocabulary.objects.get(pk=vocab_id)
+    us.save()
+    return {}
diff --git a/accounts/forms.py b/accounts/forms.py
index 087f4de..e4f5f8b 100644
--- a/accounts/forms.py
+++ b/accounts/forms.py
@@ -3,35 +3,38 @@
 import random
 import string
 from django.forms import *
-from django.utils.translation import ugettext_lazy as _
 from django.contrib.auth.forms import PasswordResetForm
 from django.contrib.auth.models import User
 from accounts.models import UserSettings
 
+
 class AddUserForm(ModelForm):
-  def save(self, commit=True, request=None):
-    user = super(AddUserForm, self).save(commit=False)
-    password = ''.join(random.choice(string.printable) for i in range(32))
-    user.set_password(password)
-    if commit:
-      user.save()
-    fakeform = PasswordResetForm(data={'email': user.email})
-    if fakeform.is_valid(): # oczywiście, że jest
-      fakeform.save(request=request)
-    UserSettings.objects.create(user=user)
-    user.groups.add(*self.cleaned_data['groups'])
-    return user
-  class Meta:
-    model = User
-    fields = ['username', 'first_name', 'last_name', 'email', 'groups']
+    def save(self, commit=True, request=None):
+        user = super(AddUserForm, self).save(commit=False)
+        password = ''.join(random.choice(string.printable) for i in range(32))
+        user.set_password(password)
+        if commit:
+            user.save()
+        fakeform = PasswordResetForm(data={'email': user.email})
+        if fakeform.is_valid(): # oczywiście, że jest
+            fakeform.save(request=request)
+        UserSettings.objects.create(user=user)
+        user.groups.add(*self.cleaned_data['groups'])
+        return user
+
+    class Meta:
+        model = User
+        fields = ['username', 'first_name', 'last_name', 'email', 'groups']
+
 
 class SettingsForm(ModelForm):
-  def __init__(self, vocabularies=None, **kwargs):
-    super(SettingsForm, self).__init__(**kwargs)
-    if vocabularies:
-      self.fields['default_owner'].queryset = vocabularies
-    else:
-      self.fields['default_owner'].widget = HiddenInput()
-  class Meta:
-    model = UserSettings
-    fields = ['incremental_search', 'filter_search', 'default_owner']
+    def __init__(self, vocabularies=None, **kwargs):
+        super(SettingsForm, self).__init__(**kwargs)
+        if vocabularies:
+            self.fields['default_owner'].queryset = vocabularies
+        else:
+            self.fields['default_owner'].widget = HiddenInput()
+
+    class Meta:
+        model = UserSettings
+        fields = ['incremental_search', 'filter_search', 'default_owner']
diff --git a/accounts/management/commands/create_groups.py b/accounts/management/commands/create_groups.py
index 021d4c2..113f7ac 100644
--- a/accounts/management/commands/create_groups.py
+++ b/accounts/management/commands/create_groups.py
@@ -1,54 +1,56 @@
 #-*- coding:utf-8 -*-
 
 from django.contrib.auth.models import Permission, Group
-from django.core.management.base import BaseCommand, CommandError
+from django.core.management.base import BaseCommand
+
 
 class Command(BaseCommand):
-  args = 'none'
-  help = 'Creates default groups'
+    args = 'none'
+    help = 'Creates default groups'
 
-  def handle(self, **options):
-    create_groups()
+    def handle(self, **options):
+        create_groups()
 
 
 def get_permission(codename):
-  return Permission.objects.get(codename=codename)
+    return Permission.objects.get(codename=codename)
+
 
 def create_groups():
-  Group.objects.all().delete()
-  observers = Group.objects.create(name=u'Obserwator')
-  lexicographers = Group.objects.create(name=u'Leksykograf')
-  superlexicographers = Group.objects.create(name=u'Superleksykograf')
-  patternmakers = Group.objects.create(name=u'Wzorzysta')
-  managers = Group.objects.create(name=u'Wydawca')
-  admins = Group.objects.create(name=u'Administrator')
-
-  observers.permissions.add(get_permission('view_lexeme'))
-  #observers.permissions.add(get_permission('add_comment'))
-  observers.permissions.add(get_permission('view_pattern'))
-  lexicographers.permissions.add(get_permission('view_lexeme'))
-  lexicographers.permissions.add(get_permission('change_lexeme'))
-  lexicographers.permissions.add(get_permission('export_lexemes'))
-  lexicographers.permissions.add(get_permission('view_pattern'))
-  superlexicographers.permissions.add(get_permission('view_lexeme'))
-  superlexicographers.permissions.add(get_permission('change_lexeme'))
-  superlexicographers.permissions.add(get_permission('export_lexemes'))
-  superlexicographers.permissions.add(get_permission('lexeme_priority'))
-  superlexicographers.permissions.add(get_permission('view_pattern'))
-  # może dokonywać zmian w Banku błędów
-  # może dokonywać zmian w zakładce Etykiety
-  patternmakers.permissions.add(get_permission('view_pattern'))
-  patternmakers.permissions.add(get_permission('change_pattern'))
-  managers.permissions.add(get_permission('manage_vocabulary'))
-  managers.permissions.add(get_permission('view_lexeme'))
-  managers.permissions.add(get_permission('view_all_lexemes'))
-  managers.permissions.add(get_permission('view_pattern'))
-  managers.permissions.add(get_permission('add_user'))
-  managers.permissions.add(get_permission('export_lexemes'))
-  # zarządzanie rolami użytkowników:
-  managers.permissions.add(get_permission('change_group'))
-  admins.permissions.add(get_permission('add_user'))
-  admins.permissions.add(get_permission('change_group'))
-  admins.permissions.add(get_permission('create_admin'))
-  admins.permissions.add(get_permission('manage_vocabulary'))
-  admins.permissions.add(get_permission('manage_all_vocabularies'))
+    Group.objects.all().delete()
+    observers = Group.objects.create(name=u'Obserwator')
+    lexicographers = Group.objects.create(name=u'Leksykograf')
+    superlexicographers = Group.objects.create(name=u'Superleksykograf')
+    patternmakers = Group.objects.create(name=u'Wzorzysta')
+    managers = Group.objects.create(name=u'Wydawca')
+    admins = Group.objects.create(name=u'Administrator')
+
+    observers.permissions.add(get_permission('view_lexeme'))
+    #observers.permissions.add(get_permission('add_comment'))
+    observers.permissions.add(get_permission('view_pattern'))
+    lexicographers.permissions.add(get_permission('view_lexeme'))
+    lexicographers.permissions.add(get_permission('change_lexeme'))
+    lexicographers.permissions.add(get_permission('export_lexemes'))
+    lexicographers.permissions.add(get_permission('view_pattern'))
+    superlexicographers.permissions.add(get_permission('view_lexeme'))
+    superlexicographers.permissions.add(get_permission('change_lexeme'))
+    superlexicographers.permissions.add(get_permission('export_lexemes'))
+    superlexicographers.permissions.add(get_permission('lexeme_priority'))
+    superlexicographers.permissions.add(get_permission('view_pattern'))
+    # może dokonywać zmian w Banku błędów
+    # może dokonywać zmian w zakładce Etykiety
+    patternmakers.permissions.add(get_permission('view_pattern'))
+    patternmakers.permissions.add(get_permission('change_pattern'))
+    managers.permissions.add(get_permission('manage_vocabulary'))
+    managers.permissions.add(get_permission('view_lexeme'))
+    managers.permissions.add(get_permission('view_all_lexemes'))
+    managers.permissions.add(get_permission('view_pattern'))
+    managers.permissions.add(get_permission('add_user'))
+    managers.permissions.add(get_permission('export_lexemes'))
+    # zarządzanie rolami użytkowników:
+    managers.permissions.add(get_permission('change_group'))
+    admins.permissions.add(get_permission('add_user'))
+    admins.permissions.add(get_permission('change_group'))
+    admins.permissions.add(get_permission('create_admin'))
+    admins.permissions.add(get_permission('manage_vocabulary'))
+    admins.permissions.add(get_permission('manage_all_vocabularies'))
diff --git a/accounts/management/commands/create_users.py b/accounts/management/commands/create_users.py
index 441f845..ff51aca 100644
--- a/accounts/management/commands/create_users.py
+++ b/accounts/management/commands/create_users.py
@@ -5,92 +5,97 @@ from django.core.management.base import BaseCommand, CommandError
 from dictionary.models import Vocabulary
 from accounts.models import UserSettings
 
+
 class Command(BaseCommand):
-  args = 'none'
-  help = 'Creates default users'
+    args = 'none'
+    help = 'Creates default users'
 
-  def handle(self, **options):
-    create_users()
+    def handle(self, **options):
+        create_users()
 
 
 def create_users():
-  observers = Group.objects.get(name=u'Obserwator')
-  lexicographers = Group.objects.get(name=u'Leksykograf')
-  superlexicographers = Group.objects.get(name=u'Superleksykograf')
-  patternmakers = Group.objects.get(name=u'Wzorzysta')
-  managers = Group.objects.get(name=u'Wydawca')
-  admins = Group.objects.get(name=u'Administrator')
-
-  SGJP = Vocabulary.objects.get(id='SGJP')
-  SJPDor = Vocabulary.objects.get(id='SJPDor')
-  zmiotki = Vocabulary.objects.get(id='zmiotki')
-  try:
-    WSJP = Vocabulary.objects.get(id='WSJP')
-  except Vocabulary.DoesNotExist:
-    WSJP = None
-  Morfologik, created = Vocabulary.objects.get_or_create(id='Morfologik')
-  PoliMorf, created = Vocabulary.objects.get_or_create(id='PoliMorf')
-
-  User.objects.all().delete()
-  sgjp = User.objects.create_user('sgjp', 'sgjp@example.com', 'sgjp')
-  nzm = User.objects.create_user('nzm', 'nzm@example.com', 'nzm')
-  redsgjp = User.objects.create_user('redsgjp', 'redsgjp@example.com', 'redsgjp')
-  rednzm = User.objects.create_user('rednzm', 'rednzm@example.com', 'rednzm')
-  supersgjp = User.objects.create_user('supersgjp', 'supersgjp@example.com', 'supersgjp')
-  supernzm = User.objects.create_user('supernzm', 'supernzm@example.com', 'supernzm')
-  wzornik = User.objects.create_user('wzornik', 'wzornik@example.com', 'wzornik')
-  admin = User.objects.create_user('admin', 'admin@example.com', 'admin')
-
-  users = (sgjp, nzm, redsgjp, rednzm, supersgjp, supernzm, wzornik, admin)
-  for user in users:
-    UserSettings.objects.create(user=user)
-
-  admin.groups.add(admins)
-
-  sgjp_vocabs = (SGJP, SJPDor, zmiotki)
-  if WSJP: sgjp_vocabs += (WSJP,)
-  nzm_vocabs = (zmiotki, Morfologik, PoliMorf)
-
-  sgjp.groups.add(managers)
-  for vocab in sgjp_vocabs:
-    sgjp.managed_vocabularies.add(vocab)
-  nzm.groups.add(managers)
-  for vocab in nzm_vocabs:
-    nzm.managed_vocabularies.add(vocab)
-
-  redsgjp.groups.add(lexicographers)
-  for vocab in sgjp_vocabs:
-    redsgjp.visible_vocabularies.add(vocab)
-    redsgjp.editable_vocabularies.add(vocab)
-  redsgjp.visible_vocabularies.add(PoliMorf)
-
-  rednzm.groups.add(lexicographers)
-  for vocab in nzm_vocabs:
-    rednzm.visible_vocabularies.add(vocab)
-    rednzm.editable_vocabularies.add(vocab)
-  rednzm.visible_vocabularies.add(SGJP)
-  if WSJP:
-    rednzm.visible_vocabularies.add(WSJP)
-  rednzm.visible_vocabularies.add(SJPDor)
-
-  supersgjp.groups.add(superlexicographers)
-  for vocab in sgjp_vocabs:
-    supersgjp.visible_vocabularies.add(vocab)
-    supersgjp.editable_vocabularies.add(vocab)
-  supersgjp.visible_vocabularies.add(PoliMorf)
-
-  supernzm.groups.add(superlexicographers)
-  for vocab in nzm_vocabs:
-    supernzm.visible_vocabularies.add(vocab)
-    supernzm.editable_vocabularies.add(vocab)
-  supernzm.visible_vocabularies.add(SGJP)
-  if WSJP:
-    supernzm.visible_vocabularies.add(WSJP)
-  supernzm.visible_vocabularies.add(SJPDor)
-
-  wzornik.groups.add(superlexicographers)
-  for vocab in sgjp_vocabs:
-    wzornik.visible_vocabularies.add(vocab)
-    wzornik.editable_vocabularies.add(vocab)
-  wzornik.visible_vocabularies.add(PoliMorf)
-  wzornik.groups.add(patternmakers)
+    observers = Group.objects.get(name=u'Obserwator')
+    lexicographers = Group.objects.get(name=u'Leksykograf')
+    superlexicographers = Group.objects.get(name=u'Superleksykograf')
+    patternmakers = Group.objects.get(name=u'Wzorzysta')
+    managers = Group.objects.get(name=u'Wydawca')
+    admins = Group.objects.get(name=u'Administrator')
+
+    SGJP = Vocabulary.objects.get(id='SGJP')
+    SJPDor = Vocabulary.objects.get(id='SJPDor')
+    zmiotki = Vocabulary.objects.get(id='zmiotki')
+    try:
+        WSJP = Vocabulary.objects.get(id='WSJP')
+    except Vocabulary.DoesNotExist:
+        WSJP = None
+    Morfologik, created = Vocabulary.objects.get_or_create(id='Morfologik')
+    PoliMorf, created = Vocabulary.objects.get_or_create(id='PoliMorf')
+
+    User.objects.all().delete()
+    sgjp = User.objects.create_user('sgjp', 'sgjp@example.com', 'sgjp')
+    nzm = User.objects.create_user('nzm', 'nzm@example.com', 'nzm')
+    redsgjp = User.objects.create_user('redsgjp', 'redsgjp@example.com',
+                                       'redsgjp')
+    rednzm = User.objects.create_user('rednzm', 'rednzm@example.com', 'rednzm')
+    supersgjp = User.objects.create_user('supersgjp', 'supersgjp@example.com',
+                                         'supersgjp')
+    supernzm = User.objects.create_user('supernzm', 'supernzm@example.com',
+                                        'supernzm')
+    wzornik = User.objects.create_user('wzornik', 'wzornik@example.com',
+                                       'wzornik')
+    admin = User.objects.create_user('admin', 'admin@example.com', 'admin')
+
+    users = (sgjp, nzm, redsgjp, rednzm, supersgjp, supernzm, wzornik, admin)
+    for user in users:
+        UserSettings.objects.create(user=user)
+
+    admin.groups.add(admins)
+
+    sgjp_vocabs = (SGJP, SJPDor, zmiotki)
+    if WSJP: sgjp_vocabs += (WSJP,)
+    nzm_vocabs = (zmiotki, Morfologik, PoliMorf)
+
+    sgjp.groups.add(managers)
+    for vocab in sgjp_vocabs:
+        sgjp.managed_vocabularies.add(vocab)
+    nzm.groups.add(managers)
+    for vocab in nzm_vocabs:
+        nzm.managed_vocabularies.add(vocab)
+
+    redsgjp.groups.add(lexicographers)
+    for vocab in sgjp_vocabs:
+        redsgjp.visible_vocabularies.add(vocab)
+        redsgjp.editable_vocabularies.add(vocab)
+    redsgjp.visible_vocabularies.add(PoliMorf)
+
+    rednzm.groups.add(lexicographers)
+    for vocab in nzm_vocabs:
+        rednzm.visible_vocabularies.add(vocab)
+        rednzm.editable_vocabularies.add(vocab)
+    rednzm.visible_vocabularies.add(SGJP)
+    if WSJP:
+        rednzm.visible_vocabularies.add(WSJP)
+    rednzm.visible_vocabularies.add(SJPDor)
+
+    supersgjp.groups.add(superlexicographers)
+    for vocab in sgjp_vocabs:
+        supersgjp.visible_vocabularies.add(vocab)
+        supersgjp.editable_vocabularies.add(vocab)
+    supersgjp.visible_vocabularies.add(PoliMorf)
+
+    supernzm.groups.add(superlexicographers)
+    for vocab in nzm_vocabs:
+        supernzm.visible_vocabularies.add(vocab)
+        supernzm.editable_vocabularies.add(vocab)
+    supernzm.visible_vocabularies.add(SGJP)
+    if WSJP:
+        supernzm.visible_vocabularies.add(WSJP)
+    supernzm.visible_vocabularies.add(SJPDor)
+
+    wzornik.groups.add(superlexicographers)
+    for vocab in sgjp_vocabs:
+        wzornik.visible_vocabularies.add(vocab)
+        wzornik.editable_vocabularies.add(vocab)
+    wzornik.visible_vocabularies.add(PoliMorf)
+    wzornik.groups.add(patternmakers)
diff --git a/accounts/management/commands/dummy_passwords.py b/accounts/management/commands/dummy_passwords.py
index 1a4963e..fa922d4 100644
--- a/accounts/management/commands/dummy_passwords.py
+++ b/accounts/management/commands/dummy_passwords.py
@@ -3,15 +3,16 @@
 from django.contrib.auth.models import User
 from django.core.management.base import BaseCommand
 
+
 class Command(BaseCommand):
-  args = 'none'
-  help = 'Sets dummy passwords'
+    args = 'none'
+    help = 'Sets dummy passwords'
 
-  def handle(self, **options):
-    dummy_passwords()
+    def handle(self, **options):
+        dummy_passwords()
 
 
 def dummy_passwords():
-  for user in User.objects.all():
-    user.set_password(user.username)
-    user.save()
\ No newline at end of file
+    for user in User.objects.all():
+        user.set_password(user.username)
+        user.save()
\ No newline at end of file
diff --git a/accounts/models.py b/accounts/models.py
index e8878ba..7dc2806 100644
--- a/accounts/models.py
+++ b/accounts/models.py
@@ -6,45 +6,48 @@ from dictionary.models import Vocabulary
 
 MANAGER_GROUPS = ('Obserwator', 'Leksykograf', 'Superleksykograf')
 
+
 def manager_groups():
-  return Group.objects.filter(name__in=MANAGER_GROUPS)
+    return Group.objects.filter(name__in=MANAGER_GROUPS)
+
 
 class UserSettings(Model):
-  user = OneToOneField(User)
-  incremental_search = BooleanField(
-    default=True,
-    verbose_name=u'wyszukiwanie przyrostowe',
-    help_text=u'Wyszukiwanie odbywa się automatycznie w miarę wpisywania '
-              u'szukanego hasła. Sugerujemy wyłączenie w wypadku wolnego '
-              u'połączenia internetowego.')
-  filter_search = BooleanField(
-    default=False,
-    verbose_name=u'wyszukiwanie przez filtrowanie',
-    help_text=u'Wyszukiwanie powoduje zawężenie listy haseł do pasujących '
-              u'do zapytania.')
-  default_owner = ForeignKey(
-    Vocabulary, blank=True, null=True,
-    verbose_name=u'domyślny słownik właściciel dodawanych leksemów')
-
-  def views_lexeme(self):
-    return self.user.has_perm('dictionary.view_lexeme')
-
-  def views_all_lexemes(self):
-    return self.user.has_perm('dictionary.view_all_lexemes')
-
-  def changes_lexeme(self):
-    return self.user.has_perm('dictionary.change_lexeme')
-
-  def manages_vocabulary(self):
-    return self.user.has_perm('dictionary.manage_vocabulary')
-
-  def manages_all_vocabs(self):
-    return self.user.has_perm('dictionary.manage_all_vocabularies')
-
-  class Meta:
-    permissions = (
-      ('create_admin', u'Może nadawać dowolne role'),
-    )
+    user = OneToOneField(User)
+    incremental_search = BooleanField(
+        default=True,
+        verbose_name=u'wyszukiwanie przyrostowe',
+        help_text=u'Wyszukiwanie odbywa się automatycznie w miarę wpisywania '
+                  u'szukanego hasła. Sugerujemy wyłączenie w wypadku wolnego '
+                  u'połączenia internetowego.')
+    filter_search = BooleanField(
+        default=False,
+        verbose_name=u'wyszukiwanie przez filtrowanie',
+        help_text=u'Wyszukiwanie powoduje zawężenie listy haseł do pasujących '
+                  u'do zapytania.')
+    default_owner = ForeignKey(
+        Vocabulary, blank=True, null=True,
+        verbose_name=u'domyślny słownik właściciel dodawanych leksemów')
+
+    def views_lexeme(self):
+        return self.user.has_perm('dictionary.view_lexeme')
+
+    def views_all_lexemes(self):
+        return self.user.has_perm('dictionary.view_all_lexemes')
+
+    def changes_lexeme(self):
+        return self.user.has_perm('dictionary.change_lexeme')
+
+    def manages_vocabulary(self):
+        return self.user.has_perm('dictionary.manage_vocabulary')
+
+    def manages_all_vocabs(self):
+        return self.user.has_perm('dictionary.manage_all_vocabularies')
+
+    class Meta:
+        permissions = (
+            ('create_admin', u'Może nadawać dowolne role'),
+        )
+
 
 def filtering_mode(user):
-  return user.usersettings.filter_search
+    return user.usersettings.filter_search
diff --git a/accounts/templates/manage_groups.html b/accounts/templates/manage_groups.html
index ab94af3..19827c2 100644
--- a/accounts/templates/manage_groups.html
+++ b/accounts/templates/manage_groups.html
@@ -2,32 +2,33 @@
 {% load ingroup %}
 
 {% block extrahead %}
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/manage-groups.js"></script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/manage-groups.js"></script>
 {% endblock %}
 
 {% block title %}Role użytkowników{% endblock %}
 
 {% block content %}
-  <h3>Role użytkowników</h3>
-  <table id="user-groups">
-    <tr>
-      <th>nazwa</th>
-      {% for group in groups %}
-        <th>{{ group.name }}</th>
-      {% endfor %}
-    </tr>
-    {% for u in users %}
-      <tr>
-        <td>{{ u.username }}</td>
-        {% for group in groups %}
-          <td>
-            <input
-              type="checkbox"
-              id="group-{{ group.pk }}-{{ u.pk }}"
-              {% if u|ingroup:group %}checked="checked"{% endif %}/>
-          </td>
+    <h3>Role użytkowników</h3>
+    <table id="user-groups">
+        <tr>
+            <th>nazwa</th>
+            {% for group in groups %}
+                <th>{{ group.name }}</th>
+            {% endfor %}
+        </tr>
+        {% for u in users %}
+            <tr>
+                <td>{{ u.username }}</td>
+                {% for group in groups %}
+                    <td>
+                        <input
+                                type="checkbox"
+                                id="group-{{ group.pk }}-{{ u.pk }}"
+                                {% if u|ingroup:group %}checked="checked"{% endif %}/>
+                    </td>
+                {% endfor %}
+            </tr>
         {% endfor %}
-      </tr>
-    {% endfor %}
-  </table>
+    </table>
 {% endblock %}
diff --git a/accounts/templates/registration/activate.html b/accounts/templates/registration/activate.html
index 568b72d..155e119 100644
--- a/accounts/templates/registration/activate.html
+++ b/accounts/templates/registration/activate.html
@@ -4,10 +4,11 @@
 
 {% block content %}
 
-{% blocktrans %}
-<h1>Activation</h1>
-<p>Your account is now activated. Go <a href="{% url 'main' %}">here</a> to continue.</p>
+    {% blocktrans %}
+        <h1>Activation</h1>
+        <p>Your account is now activated. Go <a href="{% url 'main' %}">here</a>
+            to continue.</p>
 
-{% endblocktrans %}
+    {% endblocktrans %}
 
 {% endblock %}
diff --git a/accounts/templates/registration/login.html b/accounts/templates/registration/login.html
index b0f9632..d4ffc9d 100644
--- a/accounts/templates/registration/login.html
+++ b/accounts/templates/registration/login.html
@@ -3,32 +3,35 @@
 {% load url from future %}
 
 {% block content %}
-{% if form.errors and not form.non_field_errors and not form.this_is_the_login_form.errors %}
-<p class="errornote">
-{% blocktrans count form.errors.items|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
-</p>
-{% endif %}
+    {% if form.errors and not form.non_field_errors and not form.this_is_the_login_form.errors %}
+        <p class="errornote">
+            {% blocktrans count form.errors.items|length as counter %}Please
+                correct the error below.{% plural %}Please correct the errors
+                below.{% endblocktrans %}
+        </p>
+    {% endif %}
 
-{% if form.non_field_errors or form.this_is_the_login_form.errors %}
-{% for error in form.non_field_errors|add:form.this_is_the_login_form.errors %}
-<p class="errornote">
-    {{ error }}
-</p>
-{% endfor %}
-{% endif %}
+    {% if form.non_field_errors or form.this_is_the_login_form.errors %}
+        {% for error in form.non_field_errors|add:form.this_is_the_login_form.errors %}
+            <p class="errornote">
+                {{ error }}
+            </p>
+        {% endfor %}
+    {% endif %}
 
-<div id="content-main">
-<form action="" method="post" id="login-form">{% csrf_token %}
-  {{ form.as_p }}
-  <div class="submit-row">
-    <label>&nbsp;</label><input type="submit" value="{% trans 'Log in' %}" />
-  </div>
-</form>
+    <div id="content-main">
+        <form action="" method="post" id="login-form">{% csrf_token %}
+            {{ form.as_p }}
+            <div class="submit-row">
+                <label>&nbsp;</label><input type="submit"
+                                            value="{% trans 'Log in' %}"/>
+            </div>
+        </form>
 
-<a href="{% url 'auth_password_reset' %}">Nie pamiętam hasła</a>
+        <a href="{% url 'auth_password_reset' %}">Nie pamiętam hasła</a>
 
-<script type="text/javascript">
-document.getElementById('id_username').focus()
-</script>
-</div>
+        <script type="text/javascript">
+            document.getElementById('id_username').focus()
+        </script>
+    </div>
 {% endblock %}
diff --git a/accounts/templates/registration/logout.html b/accounts/templates/registration/logout.html
index 0166b4c..ae611f5 100644
--- a/accounts/templates/registration/logout.html
+++ b/accounts/templates/registration/logout.html
@@ -4,8 +4,8 @@
 
 {% block content %}
 
-<p>{% trans "Thanks for spending some quality time with the Web site today." %}</p>
+    <p>{% trans "Thanks for spending some quality time with the Web site today." %}</p>
 
-<p><a href="{% url 'auth_login' %}">{% trans 'Log in again' %}</a></p>
+    <p><a href="{% url 'auth_login' %}">{% trans 'Log in again' %}</a></p>
 
 {% endblock %}
diff --git a/accounts/templates/registration/password_change_done.html b/accounts/templates/registration/password_change_done.html
index bc57f4e..6c9011e 100644
--- a/accounts/templates/registration/password_change_done.html
+++ b/accounts/templates/registration/password_change_done.html
@@ -2,14 +2,15 @@
 {% load i18n %}
 {% load url from future %}
 
-{% block userlinks %}{% trans 'Change password' %} / <a href="{{ url 'auth_logout' }}">{% trans 'Log out' %}</a>{% endblock %}
+{% block userlinks %}{% trans 'Change password' %} /
+    <a href="{{ url 'auth_logout' }}">{% trans 'Log out' %}</a>{% endblock %}
 
 {% block title %}{% trans 'Password change successful' %}{% endblock %}
 
 {% block content %}
 
-<h1>{% trans 'Password change successful' %}</h1>
+    <h1>{% trans 'Password change successful' %}</h1>
 
-<p>{% trans 'Your password was changed.' %}</p>
+    <p>{% trans 'Your password was changed.' %}</p>
 
 {% endblock %}
diff --git a/accounts/templates/registration/password_change_form.html b/accounts/templates/registration/password_change_form.html
index 9a1908f..8341251 100644
--- a/accounts/templates/registration/password_change_form.html
+++ b/accounts/templates/registration/password_change_form.html
@@ -1,49 +1,57 @@
 {% extends "base.html" %}
 {% load i18n %}
 {% load url from future %}
-{% block userlinks %}{% trans 'Change password' %} / <a href="{% url 'auth_logout' %}">{% trans 'Log out' %}</a>{% endblock %}
+{% block userlinks %}{% trans 'Change password' %} /
+    <a href="{% url 'auth_logout' %}">{% trans 'Log out' %}</a>{% endblock %}
 
 {% block title %}{% trans 'Password change' %}{% endblock %}
 
-{% block content %}<div id="content-main">
-
-<form action="" method="post">{% csrf_token %}
-<div>
-{% if form.errors %}
-    <p class="errornote">
-    {% blocktrans count form.errors.items|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
-    </p>
-{% endif %}
-
-<h1>{% trans 'Password change' %}</h1>
-
-<p>{% trans "Please enter your old password, for security's sake, and then enter your new password twice so we can verify you typed it in correctly." %}</p>
-
-<fieldset class="module aligned wide">
-
-<div class="form-row">
-    {{ form.old_password.errors }}
-    <label for="id_old_password" class="required">{% trans 'Old password' %}:</label>{{ form.old_password }}
-</div>
-
-<div class="form-row">
-    {{ form.new_password1.errors }}
-    <label for="id_new_password1" class="required">{% trans 'New password' %}:</label>{{ form.new_password1 }}
-</div>
-
-<div class="form-row">
-{{ form.new_password2.errors }}
-    <label for="id_new_password2" class="required">{% trans 'Password (again)' %}:</label>{{ form.new_password2 }}
-</div>
-
-</fieldset>
-
-<div class="submit-row">
-    <input type="submit" value="{% trans 'Change my password' %}" class="default" />
-</div>
-
-<script type="text/javascript">document.getElementById("id_old_password").focus();</script>
-</div>
-</form></div>
+{% block content %}
+    <div id="content-main">
+
+    <form action="" method="post">{% csrf_token %}
+        <div>
+            {% if form.errors %}
+                <p class="errornote">
+                    {% blocktrans count form.errors.items|length as counter %}
+                        Please correct the error below.{% plural %}Please
+                        correct the errors below.{% endblocktrans %}
+                </p>
+            {% endif %}
+
+            <h1>{% trans 'Password change' %}</h1>
+
+            <p>{% trans "Please enter your old password, for security's sake, and then enter your new password twice so we can verify you typed it in correctly." %}</p>
+
+            <fieldset class="module aligned wide">
+
+                <div class="form-row">
+                    {{ form.old_password.errors }}
+                    <label for="id_old_password"
+                           class="required">{% trans 'Old password' %}:</label>{{ form.old_password }}
+                </div>
+
+                <div class="form-row">
+                    {{ form.new_password1.errors }}
+                    <label for="id_new_password1"
+                           class="required">{% trans 'New password' %}:</label>{{ form.new_password1 }}
+                </div>
+
+                <div class="form-row">
+                    {{ form.new_password2.errors }}
+                    <label for="id_new_password2"
+                           class="required">{% trans 'Password (again)' %}:</label>{{ form.new_password2 }}
+                </div>
+
+            </fieldset>
+
+            <div class="submit-row">
+                <input type="submit" value="{% trans 'Change my password' %}"
+                       class="default"/>
+            </div>
+
+            <script type="text/javascript">document.getElementById("id_old_password").focus();</script>
+        </div>
+    </form></div>
 
 {% endblock %}
diff --git a/accounts/templates/registration/password_reset_complete.html b/accounts/templates/registration/password_reset_complete.html
index 6315839..63565a3 100644
--- a/accounts/templates/registration/password_reset_complete.html
+++ b/accounts/templates/registration/password_reset_complete.html
@@ -5,10 +5,10 @@
 
 {% block content %}
 
-<h1>{% trans 'Password reset complete' %}</h1>
+    <h1>{% trans 'Password reset complete' %}</h1>
 
-<p>{% trans "Your password has been set.  You may go ahead and log in now." %}</p>
+    <p>{% trans "Your password has been set.  You may go ahead and log in now." %}</p>
 
-<p><a href="{{ login_url }}">{% trans 'Log in' %}</a></p>
+    <p><a href="{{ login_url }}">{% trans 'Log in' %}</a></p>
 
 {% endblock %}
diff --git a/accounts/templates/registration/password_reset_confirm.html b/accounts/templates/registration/password_reset_confirm.html
index 51f2677..41d22ee 100644
--- a/accounts/templates/registration/password_reset_confirm.html
+++ b/accounts/templates/registration/password_reset_confirm.html
@@ -5,26 +5,32 @@
 
 {% block content %}
 
-{% if validlink %}
+    {% if validlink %}
 
-<h1>{% trans 'Enter new password' %}</h1>
+        <h1>{% trans 'Enter new password' %}</h1>
 
-<p>{% trans "Please enter your new password twice so we can verify you typed it in correctly." %}</p>
+        <p>{% trans "Please enter your new password twice so we can verify you typed it in correctly." %}</p>
 
-<form action="" method="post">{% csrf_token %}
-{{ form.new_password1.errors }}
-<p class="aligned wide"><label for="id_new_password1">{% trans 'New password:' %}</label>{{ form.new_password1 }}</p>
-{{ form.new_password2.errors }}
-<p class="aligned wide"><label for="id_new_password2">{% trans 'Confirm password:' %}</label>{{ form.new_password2 }}</p>
-<p><input type="submit" value="{% trans 'Change my password' %}" /></p>
-</form>
+        <form action="" method="post">{% csrf_token %}
+            {{ form.new_password1.errors }}
+            <p class="aligned wide"><label
+                    for="id_new_password1">{% trans 'New password:' %}</label>{{ form.new_password1 }}
+            </p>
+            {{ form.new_password2.errors }}
+            <p class="aligned wide"><label
+                    for="id_new_password2">{% trans 'Confirm password:' %}</label>{{ form.new_password2 }}
+            </p>
 
-{% else %}
+            <p><input type="submit" value="{% trans 'Change my password' %}"/>
+            </p>
+        </form>
 
-<h1>{% trans 'Password reset unsuccessful' %}</h1>
+    {% else %}
 
-<p>{% trans "The password reset link was invalid, possibly because it has already been used.  Please request a new password reset." %}</p>
+        <h1>{% trans 'Password reset unsuccessful' %}</h1>
 
-{% endif %}
+        <p>{% trans "The password reset link was invalid, possibly because it has already been used.  Please request a new password reset." %}</p>
+
+    {% endif %}
 
 {% endblock %}
diff --git a/accounts/templates/registration/password_reset_done.html b/accounts/templates/registration/password_reset_done.html
index fe63794..bd14f94 100644
--- a/accounts/templates/registration/password_reset_done.html
+++ b/accounts/templates/registration/password_reset_done.html
@@ -5,8 +5,8 @@
 
 {% block content %}
 
-<h1>{% trans 'Password reset successful' %}</h1>
+    <h1>{% trans 'Password reset successful' %}</h1>
 
-<p>{% trans "We've e-mailed you instructions for setting your password to the e-mail address you submitted. You should be receiving it shortly." %}</p>
+    <p>{% trans "We've e-mailed you instructions for setting your password to the e-mail address you submitted. You should be receiving it shortly." %}</p>
 
 {% endblock %}
diff --git a/accounts/templates/registration/password_reset_email.html b/accounts/templates/registration/password_reset_email.html
index edfcc81..f93ad72 100644
--- a/accounts/templates/registration/password_reset_email.html
+++ b/accounts/templates/registration/password_reset_email.html
@@ -1,19 +1,21 @@
 {% load i18n %}{% load url from future %}{% autoescape off %}
 
-Szanowny Użytkowniku!
+    Szanowny Użytkowniku!
 
-Ten list jest częścią procedury ustanawiania lub zmiany hasła w systemie Kuźnia.
-Jeżeli fakt, że masz konto w systemie Kuźnia jest dla Ciebie
-zaskoczeniem, zechciej ten list uznać za doniesienie, że właśnie
-założyliśmy Ci konto.
+    Ten list jest częścią procedury ustanawiania lub zmiany hasła w systemie
+    Kuźnia.
+    Jeżeli fakt, że masz konto w systemie Kuźnia jest dla Ciebie
+    zaskoczeniem, zechciej ten list uznać za doniesienie, że właśnie
+    założyliśmy Ci konto.
 
-Aby wprowadzić nowe hasło, przejdź na następującą stronę:
-{% block reset_link %}
-{{ protocol }}://{{ domain }}{% url 'django.contrib.auth.views.password_reset_confirm' uidb36=uid token=token %}
-{% endblock %}
+    Aby wprowadzić nowe hasło, przejdź na następującą stronę:
+    {% block reset_link %}
+        {{ protocol }}://
+        {{ domain }}{% url 'django.contrib.auth.views.password_reset_confirm' uidb36=uid token=token %}
+    {% endblock %}
 
-Twoja nazwa użytkownika: {{ user.username }}
+    Twoja nazwa użytkownika: {{ user.username }}
 
-Z wyrazami szacunku
-Zespół Kuźni
+    Z wyrazami szacunku
+    Zespół Kuźni
 {% endautoescape %}
diff --git a/accounts/templates/registration/password_reset_form.html b/accounts/templates/registration/password_reset_form.html
index 941fef4..bdf9f1b 100644
--- a/accounts/templates/registration/password_reset_form.html
+++ b/accounts/templates/registration/password_reset_form.html
@@ -5,13 +5,15 @@
 
 {% block content %}
 
-<h1>{% trans "Password reset" %}</h1>
+    <h1>{% trans "Password reset" %}</h1>
 
-<p>{% trans "Forgotten your password? Enter your e-mail address below, and we'll e-mail instructions for setting a new one." %}</p>
+    <p>{% trans "Forgotten your password? Enter your e-mail address below, and we'll e-mail instructions for setting a new one." %}</p>
 
-<form action="" method="post">{% csrf_token %}
-{{ form.email.errors }}
-<p><label for="id_email">{% trans 'E-mail address:' %}</label> {{ form.email }} <input type="submit" value="{% trans 'Reset my password' %}" /></p>
-</form>
+    <form action="" method="post">{% csrf_token %}
+        {{ form.email.errors }}
+        <p><label
+                for="id_email">{% trans 'E-mail address:' %}</label> {{ form.email }}
+            <input type="submit" value="{% trans 'Reset my password' %}"/></p>
+    </form>
 
 {% endblock %}
diff --git a/accounts/templates/registration/registration_complete.html b/accounts/templates/registration/registration_complete.html
index 6877aa1..fd88f66 100644
--- a/accounts/templates/registration/registration_complete.html
+++ b/accounts/templates/registration/registration_complete.html
@@ -3,9 +3,10 @@
 
 {% block content %}
 
-{% blocktrans %}
-<h1>Thank you</h1>
-<p>An email has been sent to you. You need to click link in it to activate your account.</p>
-{% endblocktrans %}
+    {% blocktrans %}
+        <h1>Thank you</h1>
+        <p>An email has been sent to you. You need to click link in it to
+            activate your account.</p>
+    {% endblocktrans %}
 
 {% endblock %}
diff --git a/accounts/templates/registration/registration_form.html b/accounts/templates/registration/registration_form.html
index 5fb5d08..d1d837d 100644
--- a/accounts/templates/registration/registration_form.html
+++ b/accounts/templates/registration/registration_form.html
@@ -3,36 +3,40 @@
 {% load url from future %}
 
 {% block extrahead %}
-  <style>
-    label {
-      vertical-align: top;
-      width: 100px;
-      display: inline-block;
-    }
-  </style>
+    <style>
+        label {
+            vertical-align: top;
+            width: 100px;
+            display: inline-block;
+        }
+    </style>
 {% endblock %}
 
 {% block title %}{% trans 'Registration' %}{% endblock %}
 
-{% block content %}<div id="content-main">
+{% block content %}
+    <div id="content-main">
 
-<form action="" method="post">{% csrf_token %}
-<div>
-{% if form.errors %}
-    <p class="errornote">
-    {% blocktrans count form.errors.items|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
-    </p>
-{% endif %}
+    <form action="" method="post">{% csrf_token %}
+        <div>
+            {% if form.errors %}
+                <p class="errornote">
+                    {% blocktrans count form.errors.items|length as counter %}
+                        Please correct the error below.{% plural %}Please
+                        correct the errors below.{% endblocktrans %}
+                </p>
+            {% endif %}
 
-<h1>{% trans 'Registration' %}</h1>
+            <h1>{% trans 'Registration' %}</h1>
 
-{{ form.as_p }}
+            {{ form.as_p }}
 
-<div class="submit-row">
-    <input type="submit" value="{% trans 'Add user' %}" class="default" />
-</div>
+            <div class="submit-row">
+                <input type="submit" value="{% trans 'Add user' %}"
+                       class="default"/>
+            </div>
 
-</div>
-</form></div>
+        </div>
+    </form></div>
 
 {% endblock %}
diff --git a/accounts/templates/settings.html b/accounts/templates/settings.html
index 189812d..db5f7a5 100644
--- a/accounts/templates/settings.html
+++ b/accounts/templates/settings.html
@@ -4,16 +4,16 @@
 {% block title %}Ustawienia{% endblock %}
 
 {% block content %}
-<h1>Ustawienia użytkownika</h1>
-<form method="post" action="">
-  {{ form.as_p }}
-  {% csrf_token %}
-  <input type="hidden" name="next" value="{{ next }}"/>
-  <button type="submit">
-    Zapisz
-  </button>
-</form>
-<p>
-  <a href="{% url 'auth_password_change' %}">Zmiana hasła</a>
-</p>
+    <h1>Ustawienia użytkownika</h1>
+    <form method="post" action="">
+        {{ form.as_p }}
+        {% csrf_token %}
+        <input type="hidden" name="next" value="{{ next }}"/>
+        <button type="submit">
+            Zapisz
+        </button>
+    </form>
+    <p>
+        <a href="{% url 'auth_password_change' %}">Zmiana hasła</a>
+    </p>
 {% endblock %}
diff --git a/accounts/util.py b/accounts/util.py
index ce639ab..dabae0d 100644
--- a/accounts/util.py
+++ b/accounts/util.py
@@ -6,13 +6,15 @@ from django.contrib.auth.models import User
 
 
 def set_history(user):
-  cursor = connection.cursor()
-  cursor.execute("SELECT set_config('var.user_id', %s, true)", [str(user.id)])
+    cursor = connection.cursor()
+    cursor.execute("SELECT set_config('var.user_id', %s, true)", [str(user.id)])
+
 
 def bot_history():
-  set_history(User.objects.get(username=u'Kuźniobot'))
+    set_history(User.objects.get(username=u'Kuźniobot'))
+
 
 def users_with_perm(perm):
-  return User.objects.filter(
-    Q(groups__permissions=perm) | Q(user_permissions=perm) |
-    Q(is_superuser=True)).distinct()
\ No newline at end of file
+    return User.objects.filter(
+        Q(groups__permissions=perm) | Q(user_permissions=perm) |
+        Q(is_superuser=True)).distinct()
\ No newline at end of file
diff --git a/accounts/views.py b/accounts/views.py
index e499c3c..ba4ab15 100644
--- a/accounts/views.py
+++ b/accounts/views.py
@@ -9,43 +9,47 @@ from accounts.forms import AddUserForm, SettingsForm
 from accounts.models import UserSettings, manager_groups
 from dictionary.models import editable_vocabularies
 
+
 @permission_required('auth.add_user')
 @render('registration/registration_form.html')
 def register(request):
-  if request.method == 'POST':
-    form = AddUserForm(data=request.POST)
-    if form.is_valid():
-      form.save(request=request)
-      return HttpResponseRedirect(reverse('registration_complete'))
-  else:
-    form = AddUserForm()
-    if not request.user.has_perm('accounts.create_admin'):
-      choices = ((g.pk, g.name) for g in manager_groups())
-      form.fields['groups'].choices = choices
-  return {'form': form}
+    if request.method == 'POST':
+        form = AddUserForm(data=request.POST)
+        if form.is_valid():
+            form.save(request=request)
+            return HttpResponseRedirect(reverse('registration_complete'))
+    else:
+        form = AddUserForm()
+        if not request.user.has_perm('accounts.create_admin'):
+            choices = ((g.pk, g.name) for g in manager_groups())
+            form.fields['groups'].choices = choices
+    return {'form': form}
+
 
 @login_required
 @render()
 def settings(request):
-  user_settings, created = UserSettings.objects.get_or_create(user=request.user)
-  if request.method == 'POST':
-    form = SettingsForm(data=request.POST, instance=user_settings)
-    if form.is_valid():
-      form.save()
-      return HttpResponseRedirect(request.POST['next'])
-  else:
-    form = SettingsForm(
-      instance=user_settings,
-      vocabularies=editable_vocabularies(request.user))
-  return {'form': form, 'next': request.META.get('HTTP_REFERER', '')}
+    user_settings, created = UserSettings.objects.get_or_create(
+        user=request.user)
+    if request.method == 'POST':
+        form = SettingsForm(data=request.POST, instance=user_settings)
+        if form.is_valid():
+            form.save()
+            return HttpResponseRedirect(request.POST['next'])
+    else:
+        form = SettingsForm(
+            instance=user_settings,
+            vocabularies=editable_vocabularies(request.user))
+    return {'form': form, 'next': request.META.get('HTTP_REFERER', '')}
+
 
 @permission_required('auth.add_user')
 @render()
 def manage_groups(request):
-  users = User.objects.filter(is_superuser=False)
-  if request.user.has_perm('accounts.create_admin'):
-    groups = Group.objects.all()
-  else:
-    groups = manager_groups()
-  js_vars = {'ajax_set_group': reverse('set_group')}
-  return {'users': users, 'groups': groups, 'js_vars': js_vars}
+    users = User.objects.filter(is_superuser=False)
+    if request.user.has_perm('accounts.create_admin'):
+        groups = Group.objects.all()
+    else:
+        groups = manager_groups()
+    js_vars = {'ajax_set_group': reverse('set_group')}
+    return {'users': users, 'groups': groups, 'js_vars': js_vars}
diff --git a/common/context_processors.py b/common/context_processors.py
index cc35555..eef995c 100644
--- a/common/context_processors.py
+++ b/common/context_processors.py
@@ -1,15 +1,16 @@
 # -*- coding: utf-8 -*-
 
 def error_proc(request):
-  if request.session.get('error', ''):
-    error = request.session.pop('error')
-    return {'error': error}
-  else:
-    return {}
+    if request.session.get('error', ''):
+        error = request.session.pop('error')
+        return {'error': error}
+    else:
+        return {}
+
 
 def message_proc(request):
-  if request.session.get('message', ''):
-    message = request.session.pop('message')
-    return {'alert_message': message}
-  else:
-    return {}
+    if request.session.get('message', ''):
+        message = request.session.pop('message')
+        return {'alert_message': message}
+    else:
+        return {}
diff --git a/common/decorators.py b/common/decorators.py
index 3b8dbbc..c62b103 100644
--- a/common/decorators.py
+++ b/common/decorators.py
@@ -15,70 +15,84 @@ from common.util import stringify_keys
 
 
 class AjaxError(Exception):
-  pass
+    pass
+
 
 def json_decode_fallback(value):
-  try:
-    return json_decode(value)
-  except ValueError:
-    return value
+    try:
+        return json_decode(value)
+    except ValueError:
+        return value
+
 
 def ajax(login_required=True, method=None, encode_result=True, template=None):
-  def decorator(fun):
-    @wraps(fun)
-    def ajax_view(request):
-      kwargs = {}
-      request_params = None
-      if method == 'post':
-        request_params = request.POST
-      elif method == 'get':
-        request_params = request.GET
-      fun_params, xx, fun_kwargs, xxxx = getargspec(fun)
-      if request_params:
-        request_params = dict((key, json_decode_fallback(value))
-          for key, value in request_params.iteritems()
-          if fun_kwargs or key in fun_params)
-        kwargs.update(stringify_keys(request_params))
-      res = None
-      if login_required and not request.user.is_authenticated():
-        res = {'result': 'logout'}
-      if not res:
-        try:
-          res = fun(request, **kwargs)
-        except AjaxError as e:
-          transaction.rollback()
-          res = {'result': e.args[0]}
-      if template:
-        res = {'html': render_to_string(template, res, RequestContext(request))}
-      if encode_result:
-        if 'result' not in res:
-          res['result'] = 'ok'
-        return HttpResponse(json_encode(res), mimetype='application/json')
-      else:
-        return res
-    return ajax_view
-  return decorator
+    def decorator(fun):
+        @wraps(fun)
+        def ajax_view(request):
+            kwargs = {}
+            request_params = None
+            if method == 'post':
+                request_params = request.POST
+            elif method == 'get':
+                request_params = request.GET
+            fun_params, xx, fun_kwargs, xxxx = getargspec(fun)
+            if request_params:
+                request_params = dict((key, json_decode_fallback(value))
+                                      for key, value in
+                                      request_params.iteritems()
+                                      if fun_kwargs or key in fun_params)
+                kwargs.update(stringify_keys(request_params))
+            res = None
+            if login_required and not request.user.is_authenticated():
+                res = {'result': 'logout'}
+            if not res:
+                try:
+                    res = fun(request, **kwargs)
+                except AjaxError as e:
+                    transaction.rollback()
+                    res = {'result': e.args[0]}
+            if template:
+                res = {'html': render_to_string(template, res,
+                                                RequestContext(request))}
+            if encode_result:
+                if 'result' not in res:
+                    res['result'] = 'ok'
+                return HttpResponse(json_encode(res),
+                                    mimetype='application/json')
+            else:
+                return res
+
+        return ajax_view
+
+    return decorator
+
 
 def render(template=None, mimetype=None):
-  mimetype = mimetype or settings.DEFAULT_CONTENT_TYPE
-  template1 = template
-  def decorator(func):
-    template = template1 # no cóż...
-    if not template:
-      template = func.__name__ + '.html'
-    @wraps(func)
-    def renderer(request, *args, **kw):
-      output = func(request, *args, **kw)
-      if isinstance(output, (list, tuple)):
-        return render_to_response(
-          output[1], output[0], RequestContext(request), mimetype=mimetype)
-      elif isinstance(output, dict):
-        return render_to_response(
-          template, output, RequestContext(request), mimetype=mimetype)
-      return output
-    return renderer
-  return decorator
+    mimetype = mimetype or settings.DEFAULT_CONTENT_TYPE
+    template1 = template
+
+    def decorator(func):
+        template = template1 # no cóż...
+        if not template:
+            template = func.__name__ + '.html'
+
+        @wraps(func)
+        def renderer(request, *args, **kw):
+            output = func(request, *args, **kw)
+            if isinstance(output, (list, tuple)):
+                return render_to_response(
+                    output[1], output[0], RequestContext(request),
+                    mimetype=mimetype)
+            elif isinstance(output, dict):
+                return render_to_response(
+                    template, output, RequestContext(request),
+                    mimetype=mimetype)
+            return output
+
+        return renderer
+
+    return decorator
 
 # żeby były linki do szablonów w PyCharm przy ajaxach
 def render_template(t):
-  return lambda x: x
\ No newline at end of file
+    return lambda x: x
\ No newline at end of file
diff --git a/common/forms.py b/common/forms.py
index 3a950fa..4c8d1e6 100644
--- a/common/forms.py
+++ b/common/forms.py
@@ -3,12 +3,14 @@
 from django import forms
 from django.utils.encoding import force_unicode
 
+
 def hidden_id(id):
-  return forms.CharField(initial=id, widget=forms.HiddenInput())
+    return forms.CharField(initial=id, widget=forms.HiddenInput())
 
 # http://www.djangosnippets.org/snippets/863/ z moimi zmianami
 class ChoiceWithOtherRenderer(forms.RadioSelect.renderer):
     """RadioFieldRenderer that renders its last choice with a placeholder."""
+
     def __init__(self, *args, **kwargs):
         super(ChoiceWithOtherRenderer, self).__init__(*args, **kwargs)
         self.choices, self.other = self.choices[:-1], self.choices[-1]
@@ -16,17 +18,22 @@ class ChoiceWithOtherRenderer(forms.RadioSelect.renderer):
     def __iter__(self):
         for input in super(ChoiceWithOtherRenderer, self).__iter__():
             yield input
-        id = '%s_%s' % (self.attrs['id'], self.other[0]) if 'id' in self.attrs else ''
+        id = '%s_%s' % (
+        self.attrs['id'], self.other[0]) if 'id' in self.attrs else ''
         label_for = ' for="%s"' % id if id else ''
-        checked = '' if not force_unicode(self.other[0]) == self.value else 'checked="true" '
+        checked = '' if not force_unicode(
+            self.other[0]) == self.value else 'checked="true" '
         yield '<label%s><input type="radio" id="%s" value="%s" name="%s" %s/> %s</label> %%s' % (
             label_for, id, self.other[0], self.name, checked, self.other[1])
 
+
 class ChoiceWithOtherWidget(forms.MultiWidget):
     """MultiWidget for use with ChoiceWithOtherField."""
+
     def __init__(self, choices):
         widgets = [
-            forms.RadioSelect(choices=choices, renderer=ChoiceWithOtherRenderer),
+            forms.RadioSelect(choices=choices,
+                              renderer=ChoiceWithOtherRenderer),
             forms.TextInput
         ]
         super(ChoiceWithOtherWidget, self).__init__(widgets)
@@ -40,20 +47,25 @@ class ChoiceWithOtherWidget(forms.MultiWidget):
         """Format the output by substituting the "other" choice into the first widget."""
         return rendered_widgets[0] % rendered_widgets[1]
 
+
 class ChoiceWithOtherField(forms.MultiValueField):
     """
     ChoiceField with an option for a user-submitted "other" value.
     """
+
     def __init__(self, *args, **kwargs):
         fields = [
-            forms.ChoiceField(widget=forms.RadioSelect(renderer=ChoiceWithOtherRenderer), *args, **kwargs),
+            forms.ChoiceField(
+                widget=forms.RadioSelect(renderer=ChoiceWithOtherRenderer),
+                *args, **kwargs),
             forms.CharField(required=False)
         ]
         widget = ChoiceWithOtherWidget(choices=kwargs['choices'])
         kwargs.pop('choices')
         self._was_required = kwargs.pop('required', True)
         kwargs['required'] = False
-        super(ChoiceWithOtherField, self).__init__(widget=widget, fields=fields, *args, **kwargs)
+        super(ChoiceWithOtherField, self).__init__(widget=widget, fields=fields,
+                                                   *args, **kwargs)
 
     def compress(self, value):
         if self._was_required and (not value or value[0] in (None, '')):
@@ -61,5 +73,6 @@ class ChoiceWithOtherField(forms.MultiValueField):
         if not value:
             return [None, u'']
         return (value[0], value[1]
-          if force_unicode(value[0]) == force_unicode(self.fields[0].choices[-1][0])
-          else self.fields[0].choices[int(value[0]) - 1][1])
\ No newline at end of file
+        if force_unicode(value[0]) == force_unicode(
+            self.fields[0].choices[-1][0])
+        else self.fields[0].choices[int(value[0]) - 1][1])
\ No newline at end of file
diff --git a/common/middleware.py b/common/middleware.py
index 5e06ab1..a75f195 100644
--- a/common/middleware.py
+++ b/common/middleware.py
@@ -1,23 +1,25 @@
 #-*- coding:utf-8 -*-
 
-from django.db import connection
 from decimal import Decimal
 
+from django.db import connection
+
 from accounts.util import set_history
 
+
 class MyMiddleware(object):
-  def process_request(self, request):
-    if request.user.is_authenticated():
-      set_history(request.user)
+    def process_request(self, request):
+        if request.user.is_authenticated():
+            set_history(request.user)
 
-  def process_response(self, request, response):
-    if False:
-      if len(connection.queries) > 0:
-        print 'Queries for %s:' % request.path_info
-        for query in connection.queries:
-          print query['time'], query['sql']
-        print 'Total of %s queries for %s.' % (
-          len(connection.queries), request.path)
-        print 'Total time: %s' % sum(Decimal(q['time'])
-                                     for q in connection.queries)
-    return response
\ No newline at end of file
+    def process_response(self, request, response):
+        if False:
+            if len(connection.queries) > 0:
+                print 'Queries for %s:' % request.path_info
+                for query in connection.queries:
+                    print query['time'], query['sql']
+                print 'Total of %s queries for %s.' % (
+                    len(connection.queries), request.path)
+                print 'Total time: %s' % sum(Decimal(q['time'])
+                                             for q in connection.queries)
+        return response
\ No newline at end of file
diff --git a/common/templates/error.html b/common/templates/error.html
index ce9f88f..96a9f2c 100644
--- a/common/templates/error.html
+++ b/common/templates/error.html
@@ -1,3 +1,3 @@
-<p id="erroralert" style="display:{{ error|yesno:",none"}}">
-{{ error }}
+<p id="erroralert" style="display:{{ error|yesno:",none" }}">
+    {{ error }}
 </p>
diff --git a/common/templates/message.html b/common/templates/message.html
index b09870b..99480d8 100644
--- a/common/templates/message.html
+++ b/common/templates/message.html
@@ -1,3 +1,3 @@
-<p id="messagealert" style="display:{{ alert_message|yesno:",none"}}">
-{{ alert_message }}
+<p id="messagealert" style="display:{{ alert_message|yesno:",none" }}">
+    {{ alert_message }}
 </p>
diff --git a/common/templates/navigation.html b/common/templates/navigation.html
index abf2176..40758c1 100644
--- a/common/templates/navigation.html
+++ b/common/templates/navigation.html
@@ -1,7 +1,7 @@
 {% for menu_item in menu %}
-  <li>
-    <a href="{{ menu_item.url }}">
-      {{ menu_item.name }}
-    </a>
-  </li>
+    <li>
+        <a href="{{ menu_item.url }}">
+            {{ menu_item.name }}
+        </a>
+    </li>
 {% endfor %}
\ No newline at end of file
diff --git a/common/templatetags/format_date.py b/common/templatetags/format_date.py
index e98065f..4ca82e8 100644
--- a/common/templatetags/format_date.py
+++ b/common/templatetags/format_date.py
@@ -4,10 +4,12 @@ from django.template import Library
 
 register = Library()
 
+
 @register.filter
 def format_date(date):
-  return date.strftime('%d.%m.%Y %H:%M')
+    return date.strftime('%d.%m.%Y %H:%M')
+
 
 @register.filter
 def format_date_exact(date):
-  return date.strftime('%d.%m.%Y %H:%M:%S.%f')
+    return date.strftime('%d.%m.%Y %H:%M:%S.%f')
diff --git a/common/templatetags/get.py b/common/templatetags/get.py
index 1bd57ab..3e83c45 100644
--- a/common/templatetags/get.py
+++ b/common/templatetags/get.py
@@ -4,6 +4,7 @@ from django.template import Library
 
 register = Library()
 
+
 @register.filter
 def get(dict, arg):
-  return dict[arg]
\ No newline at end of file
+    return dict[arg]
\ No newline at end of file
diff --git a/common/templatetags/ingroup.py b/common/templatetags/ingroup.py
index 265b3b8..1ef8b83 100644
--- a/common/templatetags/ingroup.py
+++ b/common/templatetags/ingroup.py
@@ -4,6 +4,7 @@ from django.template import Library
 
 register = Library()
 
+
 @register.filter
 def ingroup(user, group):
-  return group in user.groups.all()
+    return group in user.groups.all()
diff --git a/common/templatetags/jsonify.py b/common/templatetags/jsonify.py
index cb6b19b..64a421f 100644
--- a/common/templatetags/jsonify.py
+++ b/common/templatetags/jsonify.py
@@ -9,6 +9,7 @@ from django.template import Library
 
 register = Library()
 
+
 @register.filter
 def jsonify(object):
     if isinstance(object, QuerySet):
diff --git a/common/templatetags/script.py b/common/templatetags/script.py
index 5b59c04..f5ac904 100644
--- a/common/templatetags/script.py
+++ b/common/templatetags/script.py
@@ -3,10 +3,12 @@ from django import template
 
 register = template.Library()
 
+
 @register.simple_tag
 def script():
-  return '<script type="text/javascript"> /* <![CDATA[ */'
+    return '<script type="text/javascript"> /* <![CDATA[ */'
+
 
 @register.simple_tag
 def endscript():
-  return '/* ]]> */ </script>'
+    return '/* ]]> */ </script>'
diff --git a/common/util.py b/common/util.py
index b201a6c..f480420 100644
--- a/common/util.py
+++ b/common/util.py
@@ -7,96 +7,116 @@ from django.http import HttpResponseRedirect, Http404
 
 
 def debug(entry, text):
-  print>>sys.stderr, (u'%s: %s' % (entry, text)).encode('utf-8')
+    print>> sys.stderr, (u'%s: %s' % (entry, text)).encode('utf-8')
+
 
 def error_redirect(request, error, url='/'):
-  request.session['error'] = error
-  return HttpResponseRedirect(url)
+    request.session['error'] = error
+    return HttpResponseRedirect(url)
+
 
 def message_redirect(request, message, url='/'):
-  request.session['message'] = message
-  return HttpResponseRedirect(url)
+    request.session['message'] = message
+    return HttpResponseRedirect(url)
+
 
 def make_form(request, form_class, **kwargs):
-  if request.POST.get('det', '') == form_class.base_fields['det'].initial:
-    return form_class(data=request.POST, files=request.FILES, **kwargs)
-  else:
-    return form_class(**kwargs)
+    if request.POST.get('det', '') == form_class.base_fields['det'].initial:
+        return form_class(data=request.POST, files=request.FILES, **kwargs)
+    else:
+        return form_class(**kwargs)
+
 
 def invert(l):
-  return dict((e,nr) for (nr,e) in enumerate(l))
+    return dict((e, nr) for (nr, e) in enumerate(l))
+
 
 def generator_slice(generator, count):
-  res = []
-  try:
-    for i in range(count):
-      res.append(generator.next())
-  except StopIteration:
-    pass
-  return res
+    res = []
+    try:
+        for i in range(count):
+            res.append(generator.next())
+    except StopIteration:
+        pass
+    return res
+
 
 def url(regex, view, **kwargs):
-  if 'name' not in kwargs:
-    kwargs['name'] = view.rsplit('.', 1)[-1]
-  return urls.url(regex, view, **kwargs)
+    if 'name' not in kwargs:
+        kwargs['name'] = view.rsplit('.', 1)[-1]
+    return urls.url(regex, view, **kwargs)
+
 
 def stringify_keys(dictionary):
-  return dict((keyword.encode('ascii'), value)
-    for keyword, value in dictionary.iteritems())
+    return dict((keyword.encode('ascii'), value)
+                for keyword, value in dictionary.iteritems())
 
 # copypasta ze standardowego modułu bisect
 def bisect_left(a, x, lo=0, hi=None, cmp=None):
-  if cmp is None:
-    cmp = __builtins__.cmp
-  if lo < 0:
-    raise ValueError('lo must be non-negative')
-  if hi is None:
-    hi = len(a)
-  while lo < hi:
-    mid = (lo+hi)//2
-    if cmp(a[mid], x) < 0: lo = mid+1
-    else: hi = mid
-  return lo
+    if cmp is None:
+        cmp = __builtins__.cmp
+    if lo < 0:
+        raise ValueError('lo must be non-negative')
+    if hi is None:
+        hi = len(a)
+    while lo < hi:
+        mid = (lo + hi) // 2
+        if cmp(a[mid], x) < 0:
+            lo = mid + 1
+        else:
+            hi = mid
+    return lo
+
 
 def no_history():
-  from django.db import connection
-  cursor = connection.cursor()
-  cursor.execute("SELECT set_config('var.user_id', '0', false)")
+    from django.db import connection
+
+    cursor = connection.cursor()
+    cursor.execute("SELECT set_config('var.user_id', '0', false)")
+
 
 def reverse(seq):
-  return seq[::-1]
+    return seq[::-1]
+
 
 def flatten(seq):
-  return [item for subseq in seq for item in subseq]
+    return [item for subseq in seq for item in subseq]
+
 
 def suffix(string, length):
-  return string[-length:] if length > 0 else ''
+    return string[-length:] if length > 0 else ''
+
 
 def suffixes(s):
-  return [s[i:] for i in range(len(s)+1)]
+    return [s[i:] for i in range(len(s) + 1)]
+
 
 def cut_end(s, end):
-  assert s.endswith(end)
-  n = len(end)
-  if n == 0:
-    return s
-  else:
-    return s[:-n]
+    assert s.endswith(end)
+    n = len(end)
+    if n == 0:
+        return s
+    else:
+        return s[:-n]
+
 
 def error_messages(form):
-  return '\n'.join(
-    '%s: %s' % (form.fields[k].label, ' '.join(v)) if k != '__all__'
-    else ' '.join(v)
-    for k, v in form.errors.iteritems())
+    return '\n'.join(
+        '%s: %s' % (form.fields[k].label, ' '.join(v)) if k != '__all__'
+        else ' '.join(v)
+        for k, v in form.errors.iteritems())
+
 
 class GroupDict(dict):
-  def add(self, key, value):
-    if key not in self:
-      self[key] = []
-    self[key].append(value)
+    def add(self, key, value):
+        if key not in self:
+            self[key] = []
+        self[key].append(value)
+
 
 def json_encode(obj):
-  return json.dumps(obj, sort_keys=True)
+    return json.dumps(obj, sort_keys=True)
+
 
 def json_decode(obj):
-  return json.loads(obj)
\ No newline at end of file
+    return json.loads(obj)
\ No newline at end of file
diff --git a/dictionary/ajax_export.py b/dictionary/ajax_export.py
index f3d298d..9f67b7f 100644
--- a/dictionary/ajax_export.py
+++ b/dictionary/ajax_export.py
@@ -4,42 +4,46 @@ from common.decorators import render, ajax, AjaxError
 from dictionary.forms import MagicQualifierForm
 from dictionary.models import SavedExportData
 
+
 @render()
 @ajax(method='get', encode_result=False)
 def magic_qualifier_row(request):
-  return {'form': MagicQualifierForm(prefix='magic_NUM')}
+    return {'form': MagicQualifierForm(prefix='magic_NUM')}
+
 
 @ajax(method='post')
 def save_export_data(request, name, serialized_data, force=False):
-  existing_data = SavedExportData.objects.filter(name=name)
-  if force or not existing_data:
-    if existing_data:
-      data = existing_data[0]
+    existing_data = SavedExportData.objects.filter(name=name)
+    if force or not existing_data:
+        if existing_data:
+            data = existing_data[0]
+        else:
+            data = SavedExportData()
+            data.name = name
+        data.serialized_data = serialized_data
+        try:
+            data.save()
+        except ValueError as e:
+            raise AjaxError(e.data)
     else:
-      data = SavedExportData()
-      data.name = name
-    data.serialized_data = serialized_data
-    try:
-      data.save()
-    except ValueError as e:
-      raise AjaxError(e.data)
-  else:
-    return {'exists': True}
-  return {}
+        return {'exists': True}
+    return {}
+
 
 @ajax(method='get')
 def get_export_data(request):
-  data_list = [{
-    'id': 'export%s' % data.pk,
-    'name': data.name,
-    'json': data.serialized_data,
-    }
-    for data in SavedExportData.objects.all()]
-  return {'data_list': data_list}
+    data_list = [{
+                     'id': 'export%s' % data.pk,
+                     'name': data.name,
+                     'json': data.serialized_data,
+                 }
+                 for data in SavedExportData.objects.all()]
+    return {'data_list': data_list}
+
 
 @ajax(method='post')
 def delete_export_data(request, data_id):
-  export_data_id = data_id[len('export'):]
-  data = SavedExportData.objects.get(pk=export_data_id)
-  data.delete()
-  return {}
+    export_data_id = data_id[len('export'):]
+    data = SavedExportData.objects.get(pk=export_data_id)
+    data.delete()
+    return {}
diff --git a/dictionary/ajax_filters.py b/dictionary/ajax_filters.py
index 9412519..2f58508 100644
--- a/dictionary/ajax_filters.py
+++ b/dictionary/ajax_filters.py
@@ -3,41 +3,44 @@
 from common.decorators import ajax, AjaxError
 from dictionary.models import SavedFilter
 
+
 @ajax(method='post')
 def save_filter(request, name, serialized_filter, super=False, force=False):
-  existing_filter = SavedFilter.objects.filter(user=request.user, name=name)
-  if force or not existing_filter:
-    if existing_filter:
-      filter = existing_filter[0]
+    existing_filter = SavedFilter.objects.filter(user=request.user, name=name)
+    if force or not existing_filter:
+        if existing_filter:
+            filter = existing_filter[0]
+        else:
+            filter = SavedFilter()
+            filter.name = name
+            filter.user = request.user
+        filter.serialized_filter = serialized_filter
+        filter.super = super
+        try:
+            filter.save()
+        except ValueError as e:
+            raise AjaxError(e.data)
     else:
-      filter = SavedFilter()
-      filter.name = name
-      filter.user = request.user
-    filter.serialized_filter = serialized_filter
-    filter.super = super
-    try:
-      filter.save()
-    except ValueError as e:
-      raise AjaxError(e.data)
-  else:
-    return {'exists': True}
-  return {}
+        return {'exists': True}
+    return {}
+
 
 @ajax(method='get')
 def get_filters(request):
-  filters = [{
-               'id': 'filter%s' % filter.pk,
-               'name': filter.name,
-               'json': filter.serialized_filter,
-             }
-             for filter in SavedFilter.objects.filter(user=request.user)]
-  return {'filters': filters}
+    filters = [{
+                   'id': 'filter%s' % filter.pk,
+                   'name': filter.name,
+                   'json': filter.serialized_filter,
+               }
+               for filter in SavedFilter.objects.filter(user=request.user)]
+    return {'filters': filters}
+
 
 @ajax(method='post')
 def delete_filter(request, id):
-  filter_id = id[len('filter'):]
-  filter = SavedFilter.objects.get(pk=filter_id)
-  if filter.user != request.user:
-    raise AjaxError('access denied')
-  filter.delete()
-  return {}
+    filter_id = id[len('filter'):]
+    filter = SavedFilter.objects.get(pk=filter_id)
+    if filter.user != request.user:
+        raise AjaxError('access denied')
+    filter.delete()
+    return {}
diff --git a/dictionary/ajax_history.py b/dictionary/ajax_history.py
index ef2edc5..c31cb31 100644
--- a/dictionary/ajax_history.py
+++ b/dictionary/ajax_history.py
@@ -4,10 +4,11 @@ from common.decorators import ajax, render_template
 from dictionary.models import History
 from dictionary.history import lexeme_tables
 
+
 @render_template('history_table.html')
 @ajax(method='get', template='history_table.html')
 def history_table(request, lexeme_id):
-  history_items = History.objects.filter(
-    lexeme__pk=lexeme_id).order_by('-transaction_began')
-  transaction_tables = lexeme_tables(history_items)
-  return {'transaction_tables': transaction_tables}
+    history_items = History.objects.filter(
+        lexeme__pk=lexeme_id).order_by('-transaction_began')
+    transaction_tables = lexeme_tables(history_items)
+    return {'transaction_tables': transaction_tables}
diff --git a/dictionary/ajax_jqgrid.py b/dictionary/ajax_jqgrid.py
index 6cbdb23..560a796 100644
--- a/dictionary/ajax_jqgrid.py
+++ b/dictionary/ajax_jqgrid.py
@@ -4,267 +4,270 @@ import math
 from accounts.models import filtering_mode
 from common.decorators import render, ajax
 
+
 class JqGridQuery(object):
-  def __init__(self, filters, sort_rules, mask, user):
-    self.filters = filters
-    self.sort_rules = sort_rules
-    self.mask = mask
-    self.user = user
+    def __init__(self, filters, sort_rules, mask, user):
+        self.filters = filters
+        self.sort_rules = sort_rules
+        self.mask = mask
+        self.user = user
+
+    def filtering_mode(self):
+        return filtering_mode(self.user)
 
-  def filtering_mode(self):
-    return filtering_mode(self.user)
 
 class JqGridAjax(object):
-  model = None
-  search_field = None
-  field_translation = {}
+    model = None
+    search_field = None
+    field_translation = {}
 
-  @classmethod
-  def translate_field(cls, field):
-    if field in cls.field_translation:
-      return cls.field_translation[field]
-    else:
-      return field
+    @classmethod
+    def translate_field(cls, field):
+        if field in cls.field_translation:
+            return cls.field_translation[field]
+        else:
+            return field
 
-  @staticmethod
-  def sort_field_special_case(rule):
-    return rule['field']
+    @staticmethod
+    def sort_field_special_case(rule):
+        return rule['field']
 
-  @classmethod
-  def get_sort_field(cls, rule):
-    field = cls.sort_field_special_case(rule)
-    field = cls.translate_field(field)
-    if rule['order'] == 'desc':
-      field = '-' + field
-    return field
+    @classmethod
+    def get_sort_field(cls, rule):
+        field = cls.sort_field_special_case(rule)
+        field = cls.translate_field(field)
+        if rule['order'] == 'desc':
+            field = '-' + field
+        return field
 
-  @staticmethod
-  def sort_queryset_special_case(queryset, field):
-    return queryset
+    @staticmethod
+    def sort_queryset_special_case(queryset, field):
+        return queryset
 
-  @classmethod
-  def sort_queryset(cls, queryset, sort_rules):
-    order_list = []
-    for rule in sort_rules:
-      queryset = cls.sort_queryset_special_case(queryset, rule)
-      order_list.append(cls.get_sort_field(rule))
-    return queryset.extra(order_by=order_list)
+    @classmethod
+    def sort_queryset(cls, queryset, sort_rules):
+        order_list = []
+        for rule in sort_rules:
+            queryset = cls.sort_queryset_special_case(queryset, rule)
+            order_list.append(cls.get_sort_field(rule))
+        return queryset.extra(order_by=order_list)
 
-  lookup_translation = {
-    'eq': 'exact',
-    'ne': '-exact',
-    'bw': 'startswith',
-    'bn': '-startswith',
-    'ew': 'endswith',
-    'en': '-endswith',
-    'cn': 'contains',
-    'nc': '-contains',
-    're': 'regex',
-    'nr': '-regex',
-    #'se': 'surely',
-    #'sd': '-maybe',
-    #'me': 'maybe',
-    #'md': '-surely',
-    'le': 'lte',
-    'ge': 'gte',
-  }
+    lookup_translation = {
+        'eq': 'exact',
+        'ne': '-exact',
+        'bw': 'startswith',
+        'bn': '-startswith',
+        'ew': 'endswith',
+        'en': '-endswith',
+        'cn': 'contains',
+        'nc': '-contains',
+        're': 'regex',
+        'nr': '-regex',
+        #'se': 'surely',
+        #'sd': '-maybe',
+        #'me': 'maybe',
+        #'md': '-surely',
+        'le': 'lte',
+        'ge': 'gte',
+    }
 
-  @staticmethod
-  def filter_special_case(filter, lookup, negated, queryset):
-    return False, filter['field'], queryset
+    @staticmethod
+    def filter_special_case(filter, lookup, negated, queryset):
+        return False, filter['field'], queryset
 
-  @classmethod
-  def apply_filter(cls, queryset, filter):
-    lookup = cls.lookup_translation[filter['op']]
-    negated = (lookup[0] == '-')
-    lookup = lookup.lstrip('-')
-    data = filter['data']
-    special, field, queryset = cls.filter_special_case(
-      filter, lookup, negated, queryset)
-    if not special:
-      arg = {(field + '__' + lookup): data}
-      if negated:
-        queryset = queryset.exclude(**arg)
-      else:
-        queryset = queryset.filter(**arg).distinct()
-    return queryset
+    @classmethod
+    def apply_filter(cls, queryset, filter):
+        lookup = cls.lookup_translation[filter['op']]
+        negated = (lookup[0] == '-')
+        lookup = lookup.lstrip('-')
+        data = filter['data']
+        special, field, queryset = cls.filter_special_case(
+            filter, lookup, negated, queryset)
+        if not special:
+            arg = {(field + '__' + lookup): data}
+            if negated:
+                queryset = queryset.exclude(**arg)
+            else:
+                queryset = queryset.filter(**arg).distinct()
+        return queryset
 
-  @classmethod
-  def get_queryset(cls, query):
-    return cls.model.objects.all()
+    @classmethod
+    def get_queryset(cls, query):
+        return cls.model.objects.all()
 
-  @classmethod
-  def get_empty_queryset(cls):
-    return cls.model.objects.none()
+    @classmethod
+    def get_empty_queryset(cls):
+        return cls.model.objects.none()
 
-  @classmethod
-  def apply_filters(cls, query):
-    filters = query.filters
-    queryset = cls.get_queryset(query)
-    if filters:
-      if filters['groupOp'] == 'AND':
-        for filter in filters['rules']:
-          queryset = cls.apply_filter(queryset, filter)
-      elif filters['groupOp'] == 'OR':
-        new_queryset = cls.get_empty_queryset()
-        for filter in filters['rules']:
-          new_queryset |= cls.apply_filter(queryset, filter)
-        queryset = new_queryset
-    return queryset
+    @classmethod
+    def apply_filters(cls, query):
+        filters = query.filters
+        queryset = cls.get_queryset(query)
+        if filters:
+            if filters['groupOp'] == 'AND':
+                for filter in filters['rules']:
+                    queryset = cls.apply_filter(queryset, filter)
+            elif filters['groupOp'] == 'OR':
+                new_queryset = cls.get_empty_queryset()
+                for filter in filters['rules']:
+                    new_queryset |= cls.apply_filter(queryset, filter)
+                queryset = new_queryset
+        return queryset
 
-  @staticmethod
-  def apply_mask(queryset, mask, sort_rules):
-    pass # abstract
+    @staticmethod
+    def apply_mask(queryset, mask, sort_rules):
+        pass # abstract
 
-  @staticmethod
-  def filter_value_special_case(queryset, rule, from_value, upward):
-    return False, queryset
+    @staticmethod
+    def filter_value_special_case(queryset, rule, from_value, upward):
+        return False, queryset
 
-  # filtruje queryset według pola z reguły rule od wartości from,
-  # wartości dalsze w porządku jeśli upward, w przeciwnym razie bliższe
-  @classmethod
-  def filter_value(cls, queryset, rule, from_value, upward):
-    greater = (rule['order'] == 'asc') == upward
-    special, queryset = cls.filter_value_special_case(
-      queryset, rule, from_value, upward)
-    if special:
-      return queryset
-    if greater:
-      lookup = '__gte'
-    else:
-      lookup = '__lte'
-    field = cls.translate_field(rule['field'])
-    return queryset.filter(**{field + lookup: from_value})
+    # filtruje queryset według pola z reguły rule od wartości from,
+    # wartości dalsze w porządku jeśli upward, w przeciwnym razie bliższe
+    @classmethod
+    def filter_value(cls, queryset, rule, from_value, upward):
+        greater = (rule['order'] == 'asc') == upward
+        special, queryset = cls.filter_value_special_case(
+            queryset, rule, from_value, upward)
+        if special:
+            return queryset
+        if greater:
+            lookup = '__gte'
+        else:
+            lookup = '__lte'
+        field = cls.translate_field(rule['field'])
+        return queryset.filter(**{field + lookup: from_value})
 
-  # id instancji z search_field rownym mask badz takiej, ktora bylaby nastepna
-  # po instancji z search_field równym mask w danym sortowaniu.
-  # Jezeli nie ma 'wiekszej' instancji badz reguly sortowania nie uwzgledniaja
-  # search_field, metoda zwroci pierwsza instancje w danym sortowaniu
-  #
-  # beznadziejna nazwa metody...
-  @classmethod
-  def get_pk(cls, query):
-    whole_queryset = cls.apply_filters(query)
-    queryset = whole_queryset
-    matching = cls.apply_mask(queryset, query.mask, query.sort_rules)
-    if matching.count() > 0:
-      matching = cls.sort_queryset(matching, query.sort_rules)
-      return matching[0].pk
-    else:
-      #gdy nie ma pasującego
-      rule = query.sort_rules[0]
-      if rule['field'] == cls.search_field:
-        queryset = cls.filter_value(
-          queryset, rule, from_value=query.mask, upward=True)
-        if queryset.count() == 0:
-          queryset = whole_queryset
-      queryset = cls.sort_queryset(queryset, query.sort_rules)
-      return queryset[0].pk
+    # id instancji z search_field rownym mask badz takiej, ktora bylaby nastepna
+    # po instancji z search_field równym mask w danym sortowaniu.
+    # Jezeli nie ma 'wiekszej' instancji badz reguly sortowania nie uwzgledniaja
+    # search_field, metoda zwroci pierwsza instancje w danym sortowaniu
+    #
+    # beznadziejna nazwa metody...
+    @classmethod
+    def get_pk(cls, query):
+        whole_queryset = cls.apply_filters(query)
+        queryset = whole_queryset
+        matching = cls.apply_mask(queryset, query.mask, query.sort_rules)
+        if matching.count() > 0:
+            matching = cls.sort_queryset(matching, query.sort_rules)
+            return matching[0].pk
+        else:
+            #gdy nie ma pasującego
+            rule = query.sort_rules[0]
+            if rule['field'] == cls.search_field:
+                queryset = cls.filter_value(
+                    queryset, rule, from_value=query.mask, upward=True)
+                if queryset.count() == 0:
+                    queryset = whole_queryset
+            queryset = cls.sort_queryset(queryset, query.sort_rules)
+            return queryset[0].pk
 
-  @staticmethod
-  def get_field_special_case(field, instance):
-    return False, None
+    @staticmethod
+    def get_field_special_case(field, instance):
+        return False, None
 
-  @classmethod
-  def get_field(cls, field, instance):
-    special, value = cls.get_field_special_case(field, instance)
-    if not special:
-      value = getattr(instance, field)
-    return cls.translate_field(field), value
+    @classmethod
+    def get_field(cls, field, instance):
+        special, value = cls.get_field_special_case(field, instance)
+        if not special:
+            value = getattr(instance, field)
+        return cls.translate_field(field), value
 
-  # indeks wiersza w danym sortowaniu, w którym
-  # znajdzie się instancja o danym id
-  @classmethod
-  def row_index(cls, pk, query):
-    selected = cls.model.objects.get(pk=pk)
-    queryset = cls.apply_filters(query)
-    if query.filtering_mode():
-      queryset = cls.apply_mask(queryset, query.mask, query.sort_rules)
-    count = queryset.count()
-    if count == 0:
-      return 0, 0
-    preceding = None
-    assert len(query.sort_rules) > 0
-    for rule in query.sort_rules:
-      field = rule['field']
-      field, data = cls.get_field(field, selected)
-      preceding = cls.filter_value(
-        queryset, rule, from_value=data, upward=False)
-    return preceding.count(), count
+    # indeks wiersza w danym sortowaniu, w którym
+    # znajdzie się instancja o danym id
+    @classmethod
+    def row_index(cls, pk, query):
+        selected = cls.model.objects.get(pk=pk)
+        queryset = cls.apply_filters(query)
+        if query.filtering_mode():
+            queryset = cls.apply_mask(queryset, query.mask, query.sort_rules)
+        count = queryset.count()
+        if count == 0:
+            return 0, 0
+        preceding = None
+        assert len(query.sort_rules) > 0
+        for rule in query.sort_rules:
+            field = rule['field']
+            field, data = cls.get_field(field, selected)
+            preceding = cls.filter_value(
+                queryset, rule, from_value=data, upward=False)
+        return preceding.count(), count
 
-  # też beznadziejna nazwa
-  @classmethod
-  def find_id(cls, selected_pk, query):
-    index, count = cls.row_index(selected_pk, query)
-    return {
-      'rowIndex': index,
-      'records': count,
-    }
+    # też beznadziejna nazwa
+    @classmethod
+    def find_id(cls, selected_pk, query):
+        index, count = cls.row_index(selected_pk, query)
+        return {
+            'rowIndex': index,
+            'records': count,
+        }
 
-  @classmethod
-  def get_location(cls, query):
-    queryset = cls.apply_filters(query)
-    count = queryset.count()
-    # nie wiem, czy ma sens - wzorów i tak jest mało, a leksemy są keszowane
-    if count > 0 and query.mask == '':
-      return {
-        'rowIndex': 0,
-        'selected_id': queryset[0].pk,
-        'records': count,
-      }
-    if query.filtering_mode():
-      queryset = cls.apply_mask(queryset, query.mask, query.sort_rules)
-    if queryset.count() > 0:
-      selected_pk = cls.get_pk(query)
-      index, _count = cls.row_index(selected_pk, query)
-    else:
-      index = None
-      selected_pk = None
-    return {
-      'rowIndex': index,
-      'selected_id': selected_pk,
-      'records': count,
-    }
+    @classmethod
+    def get_location(cls, query):
+        queryset = cls.apply_filters(query)
+        count = queryset.count()
+        # nie wiem, czy ma sens - wzorów i tak jest mało, a leksemy są keszowane
+        if count > 0 and query.mask == '':
+            return {
+                'rowIndex': 0,
+                'selected_id': queryset[0].pk,
+                'records': count,
+            }
+        if query.filtering_mode():
+            queryset = cls.apply_mask(queryset, query.mask, query.sort_rules)
+        if queryset.count() > 0:
+            selected_pk = cls.get_pk(query)
+            index, _count = cls.row_index(selected_pk, query)
+        else:
+            index = None
+            selected_pk = None
+        return {
+            'rowIndex': index,
+            'selected_id': selected_pk,
+            'records': count,
+        }
 
-  @classmethod
-  def get_sorted_queryset(cls, query):
-    queryset = cls.apply_filters(query)
-    if query.filtering_mode():
-      queryset = cls.apply_mask(queryset, query.mask, query.sort_rules)
-    return cls.sort_queryset(queryset, query.sort_rules)
+    @classmethod
+    def get_sorted_queryset(cls, query):
+        queryset = cls.apply_filters(query)
+        if query.filtering_mode():
+            queryset = cls.apply_mask(queryset, query.mask, query.sort_rules)
+        return cls.sort_queryset(queryset, query.sort_rules)
 
-  @staticmethod
-  def count_pages(count, page, limit):
-    total_pages = int(math.ceil(float(count) / limit))
-    if limit < 0:
-      limit = 0
-    page = min(page, total_pages)
-    start = limit * (page - 1)
-    start = max(start, 0)
-    response_rowcount = min(limit, count - start)
-    return total_pages, start, response_rowcount
+    @staticmethod
+    def count_pages(count, page, limit):
+        total_pages = int(math.ceil(float(count) / limit))
+        if limit < 0:
+            limit = 0
+        page = min(page, total_pages)
+        start = limit * (page - 1)
+        start = max(start, 0)
+        response_rowcount = min(limit, count - start)
+        return total_pages, start, response_rowcount
 
-  @staticmethod
-  def response_row(instance):
-    pass # abstract
+    @staticmethod
+    def response_row(instance):
+        pass # abstract
 
-  @classmethod
-  def make_response(cls, response_qs, count, page, total_pages):
-    rows = [{
-              'id': instance.pk,
-              'cell': cls.response_row(instance),
-            } for instance in response_qs]
-    return {
-      'page': page,
-      'total': total_pages,
-      'records': count,
-      'rows': rows,
-    }
+    @classmethod
+    def make_response(cls, response_qs, count, page, total_pages):
+        rows = [{
+                    'id': instance.pk,
+                    'cell': cls.response_row(instance),
+                } for instance in response_qs]
+        return {
+            'page': page,
+            'total': total_pages,
+            'records': count,
+            'rows': rows,
+        }
 
-  @classmethod
-  def get_page(cls, page, limit, query):
-    queryset = cls.get_sorted_queryset(query)
-    count = queryset.count()
-    total_pages, start, response_rowcount = cls.count_pages(count, page, limit)
-    response_qs = queryset[start:start + response_rowcount]
-    return cls.make_response(response_qs, count, page, total_pages)
\ No newline at end of file
+    @classmethod
+    def get_page(cls, page, limit, query):
+        queryset = cls.get_sorted_queryset(query)
+        count = queryset.count()
+        total_pages, start, response_rowcount = cls.count_pages(count, page,
+                                                                limit)
+        response_qs = queryset[start:start + response_rowcount]
+        return cls.make_response(response_qs, count, page, total_pages)
\ No newline at end of file
diff --git a/dictionary/ajax_lexeme_jqgrid.py b/dictionary/ajax_lexeme_jqgrid.py
index 319243f..e678a09 100644
--- a/dictionary/ajax_lexeme_jqgrid.py
+++ b/dictionary/ajax_lexeme_jqgrid.py
@@ -2,60 +2,62 @@
 from hashlib import md5
 
 from django.db.models import Count
+from django.core.cache import cache
+
 from dictionary.models import Lexeme, filter_visible, visible_vocabularies, LexemeInflectionPattern, LexemeAssociation
 from dictionary.ajax_jqgrid import JqGridAjax, JqGridQuery
 from common.decorators import ajax
 from common.util import bisect_left, reverse, GroupDict, json_encode
-from django.core.cache import cache
-
-class LexemeGrid(JqGridAjax):
-  model = Lexeme
-  search_field = 'entry'
-  field_translation = {
-    'part_of_speech': 'part_of_speech__symbol',
-  }
-
-  @staticmethod
-  def sort_field_special_case(rule):
-    if rule['field'] == 'entry' and rule['a_tergo']:
-      return 'rev'
-    else:
-      return rule['field']
 
-  @staticmethod
-  def sort_queryset_special_case(queryset, rule):
-    if rule['field'] == 'entry' and rule['a_tergo']:
-      return queryset.extra(select={'rev': "reverse(haslo)"})
-    else:
-      return queryset
 
-  @staticmethod
-  def filter_special_case(filter, lookup, negated, queryset):
-    field, data = filter['field'], filter['data']
-    special = False
+class LexemeGrid(JqGridAjax):
+    model = Lexeme
+    search_field = 'entry'
     field_translation = {
-      'form': 'lexemeform__form',
-      'lexeme_qualifier': 'qualifiers__pk',
-      'lip_qualifier': 'lexemeinflectionpattern__qualifiers__pk',
-      'classification_value': 'classificationvalue__pk',
-      'pattern_name': 'lexemeinflectionpattern__pattern__name',
-      'inflection_characteristic':
-        'lexemeinflectionpattern__inflection_characteristic__symbol',
-      'containing_vocabulary': 'vocabularies__pk',
-      'owner_vocabulary': 'owner_vocabulary__pk',
-      'pattern_count': 'pc',
-      'ic_count': 'icc',
-      'cr_type': 'refs_to__type__pk',
+        'part_of_speech': 'part_of_speech__symbol',
     }
-    if field == 'pattern_count':
-      queryset = queryset.annotate(
-        pc=Count('lexemeinflectionpattern__pattern', distinct=True))
-    elif field == 'ic_count':
-      queryset = queryset.annotate(
-        icc=Count('lexemeinflectionpattern__inflection_characteristic',
-          distinct=True))
-    elif field == 'qualifier':
-      where = '''(
+
+    @staticmethod
+    def sort_field_special_case(rule):
+        if rule['field'] == 'entry' and rule['a_tergo']:
+            return 'rev'
+        else:
+            return rule['field']
+
+    @staticmethod
+    def sort_queryset_special_case(queryset, rule):
+        if rule['field'] == 'entry' and rule['a_tergo']:
+            return queryset.extra(select={'rev': "reverse(haslo)"})
+        else:
+            return queryset
+
+    @staticmethod
+    def filter_special_case(filter, lookup, negated, queryset):
+        field, data = filter['field'], filter['data']
+        special = False
+        field_translation = {
+            'form': 'lexemeform__form',
+            'lexeme_qualifier': 'qualifiers__pk',
+            'lip_qualifier': 'lexemeinflectionpattern__qualifiers__pk',
+            'classification_value': 'classificationvalue__pk',
+            'pattern_name': 'lexemeinflectionpattern__pattern__name',
+            'inflection_characteristic':
+                'lexemeinflectionpattern__inflection_characteristic__symbol',
+            'containing_vocabulary': 'vocabularies__pk',
+            'owner_vocabulary': 'owner_vocabulary__pk',
+            'pattern_count': 'pc',
+            'ic_count': 'icc',
+            'cr_type': 'refs_to__type__pk',
+        }
+        if field == 'pattern_count':
+            queryset = queryset.annotate(
+                pc=Count('lexemeinflectionpattern__pattern', distinct=True))
+        elif field == 'ic_count':
+            queryset = queryset.annotate(
+                icc=Count('lexemeinflectionpattern__inflection_characteristic',
+                          distinct=True))
+        elif field == 'qualifier':
+            where = '''(
         exists (
           select * from kwalifikatory_leksemow where lexeme_id = leksemy.id and
             qualifier_id = %s) or
@@ -75,200 +77,209 @@ class LexemeGrid(JqGridAjax):
           where o.l_id = leksemy.id and s.wariant = '1' and
             kz.qualifier_id = %s)
       )'''
-      if negated:
-        where = 'not ' + where
-      queryset = queryset.extra(where=[where], params=[data] * 3)
-      special = True
-    return special, field_translation.get(field, field), queryset
-
-  @classmethod
-  def get_queryset(cls, query):
-    lexemes = super(LexemeGrid, cls).get_queryset(query)
-    return filter_visible(lexemes, query.user)
-
-  @staticmethod
-  def apply_mask(lexemes, mask, sort_rules):
-    if mask == '':
-      return lexemes
-    for rule in sort_rules:
-      if rule['field'] == 'entry':
-        if not rule['a_tergo']:
-          matching_lexemes = lexemes.filter(entry__istartswith=mask)
+            if negated:
+                where = 'not ' + where
+            queryset = queryset.extra(where=[where], params=[data] * 3)
+            special = True
+        return special, field_translation.get(field, field), queryset
+
+    @classmethod
+    def get_queryset(cls, query):
+        lexemes = super(LexemeGrid, cls).get_queryset(query)
+        return filter_visible(lexemes, query.user)
+
+    @staticmethod
+    def apply_mask(lexemes, mask, sort_rules):
+        if mask == '':
+            return lexemes
+        for rule in sort_rules:
+            if rule['field'] == 'entry':
+                if not rule['a_tergo']:
+                    matching_lexemes = lexemes.filter(entry__istartswith=mask)
+                else:
+                    matching_lexemes = lexemes.filter(entry__iendswith=mask)
+                break
         else:
-          matching_lexemes = lexemes.filter(entry__iendswith=mask)
-        break
-    else:
-      matching_lexemes = lexemes.filter(entry__istartswith=mask)
-    return matching_lexemes
-
-  @staticmethod
-  def filter_value_special_case(queryset, rule, from_value, greater):
-    if rule['field'] == 'entry' and rule['a_tergo']:
-      if greater:
-        comp = '>='
-      else:
-        comp = '<='
-      queryset = queryset.extra(where=["reverse(haslo) " + comp + " %s"],
-                                params=[reverse(from_value)])
-      return True, queryset
-    else:
-      return False, queryset
+            matching_lexemes = lexemes.filter(entry__istartswith=mask)
+        return matching_lexemes
+
+    @staticmethod
+    def filter_value_special_case(queryset, rule, from_value, greater):
+        if rule['field'] == 'entry' and rule['a_tergo']:
+            if greater:
+                comp = '>='
+            else:
+                comp = '<='
+            queryset = queryset.extra(where=["reverse(haslo) " + comp + " %s"],
+                                      params=[reverse(from_value)])
+            return True, queryset
+        else:
+            return False, queryset
+
+    @staticmethod
+    def get_field_special_case(field, lexeme):
+        if field == 'part_of_speech':
+            return True, lexeme.part_of_speech.symbol
+        else:
+            return False, None
+
+    @staticmethod
+    def response_row(lexeme):
+        lip_data = lexeme.lip_data()
+        cont_vocabs = '/'.join(v.id for v in lexeme.vocabularies.all())
+        return [
+            lexeme.id,
+            lexeme.entry,
+            lexeme.part_of_speech.symbol,
+            lip_data['patterns'],
+            '', # brak liczby wzorów
+            lip_data['inflection_characteristics'],
+            '', # brak liczby charfli
+            '', # brak formy
+            cont_vocabs,
+            lexeme.owner_vocabulary.id,
+            dict(Lexeme.STATUS_CHOICES).get(lexeme.status),
+            '', # brak komentarza
+        ]
+
+    # indeks wiersza w danym sortowaniu, w którym
+    # znajdzie się instancja o danym id
+    @classmethod
+    def row_index(cls, pk, query):
+        pk_list = get_pk_list(query)
+        count = len(pk_list)
+        if count == 0:
+            return 0, 0
+        return pk_list.index(pk), count
+
+    # id instancji z search_field rownym mask badz takiej, ktora bylaby nastepna
+    # po instancji z search_field równym mask w danym sortowaniu.
+    # Jezeli nie ma 'wiekszej' instancji badz reguly sortowania nie uwzgledniaja
+    # search_field, metoda zwroci pierwsza instancje w danym sortowaniu
+    @classmethod
+    def get_pk(cls, query):
+        pk_list = get_pk_list(query)
+        count = len(pk_list)
+        if count == 0:
+            return None, None, 0
+            # nie podoba mi się w ogóle cała ta idea
+        sort_rules = query.sort_rules
+        assert len(sort_rules) >= 0
+        if sort_rules[0]['field'] != cls.search_field:
+            selected_pk = super(cls, LexemeGrid).get_pk(query)
+            index, count = cls.row_index(selected_pk, query)
+            return selected_pk, index, count
+
+        index = bisect_left(pk_list, query.mask,
+                            cmp=make_lexeme_cmp(sort_rules[0]))
+        if index == count:
+            index -= 1
+        return pk_list[index], index, count
+
+    @classmethod
+    def get_location(cls, query):
+        selected_pk, index, count = cls.get_pk(query)
+        return {
+            'rowIndex': index,
+            'selected_id': selected_pk,
+            'records': count,
+        }
 
-  @staticmethod
-  def get_field_special_case(field, lexeme):
-    if field == 'part_of_speech':
-      return True, lexeme.part_of_speech.symbol
-    else:
-      return False, None
-
-  @staticmethod
-  def response_row(lexeme):
-    lip_data = lexeme.lip_data()
-    cont_vocabs = '/'.join(v.id for v in lexeme.vocabularies.all())
-    return [
-      lexeme.id,
-      lexeme.entry,
-      lexeme.part_of_speech.symbol,
-      lip_data['patterns'],
-      '', # brak liczby wzorów
-      lip_data['inflection_characteristics'],
-      '', # brak liczby charfli
-      '', # brak formy
-      cont_vocabs,
-      lexeme.owner_vocabulary.id,
-      dict(Lexeme.STATUS_CHOICES).get(lexeme.status),
-      '', # brak komentarza
-    ]
-
-  # indeks wiersza w danym sortowaniu, w którym
-  # znajdzie się instancja o danym id
-  @classmethod
-  def row_index(cls, pk, query):
-    pk_list = get_pk_list(query)
-    count = len(pk_list)
-    if count == 0:
-      return 0, 0
-    return pk_list.index(pk), count
-
-  # id instancji z search_field rownym mask badz takiej, ktora bylaby nastepna
-  # po instancji z search_field równym mask w danym sortowaniu.
-  # Jezeli nie ma 'wiekszej' instancji badz reguly sortowania nie uwzgledniaja
-  # search_field, metoda zwroci pierwsza instancje w danym sortowaniu
-  @classmethod
-  def get_pk(cls, query):
-    pk_list = get_pk_list(query)
-    count = len(pk_list)
-    if count == 0:
-      return None, None, 0
-    # nie podoba mi się w ogóle cała ta idea
-    sort_rules = query.sort_rules
-    assert len(sort_rules) >= 0
-    if sort_rules[0]['field'] != cls.search_field:
-      selected_pk = super(cls, LexemeGrid).get_pk(query)
-      index, count = cls.row_index(selected_pk, query)
-      return selected_pk, index, count
-
-    index = bisect_left(pk_list, query.mask, cmp=make_lexeme_cmp(sort_rules[0]))
-    if index == count:
-      index -= 1
-    return pk_list[index], index, count
-
-  @classmethod
-  def get_location(cls, query):
-    selected_pk, index, count = cls.get_pk(query)
-    return {
-      'rowIndex': index,
-      'selected_id': selected_pk,
-      'records': count,
-    }
 
 import locale
+
 locale.setlocale(locale.LC_ALL, 'pl_PL.UTF-8')
 
+
 def make_lexeme_cmp(rule):
-  def lexeme_cmp(pk, mask):
-    e1 = Lexeme.objects.get(pk=pk).entry
-    e2 = mask
-    if rule['a_tergo']:
-      e1 = reverse(e1)
-      e2 = reverse(e2)
-    result = locale.strcoll(e1, e2)
-    if rule['order'] == 'desc' and e2 != '':
-      result = -result
-    return result
-  return lexeme_cmp
+    def lexeme_cmp(pk, mask):
+        e1 = Lexeme.objects.get(pk=pk).entry
+        e2 = mask
+        if rule['a_tergo']:
+            e1 = reverse(e1)
+            e2 = reverse(e2)
+        result = locale.strcoll(e1, e2)
+        if rule['order'] == 'desc' and e2 != '':
+            result = -result
+        return result
+
+    return lexeme_cmp
 
 # Zapytanie o indeks wiersza o pewnym id przy danym sortowaniu
 @ajax(method='get')
 def find_id(request, id, sort_rules, mask, filters=None):
-  query = JqGridQuery(
-    filters=filters, sort_rules=sort_rules, mask=mask, user=request.user)
-  return LexemeGrid.find_id(id, query)
+    query = JqGridQuery(
+        filters=filters, sort_rules=sort_rules, mask=mask, user=request.user)
+    return LexemeGrid.find_id(id, query)
 
 # Zapytanie o id oraz indeks pierwszego wiersza przy danym sortowaniu,
 # którego hasło rozpoczyna się od mask.
 # 'selected_id' == None, jeśli takiego nie ma
 @ajax(method='get')
 def get_location(request, sort_rules, mask='', filters=None):
-  query = JqGridQuery(
-    filters=filters, sort_rules=sort_rules, mask=mask, user=request.user)
-  return LexemeGrid.get_location(query)
+    query = JqGridQuery(
+        filters=filters, sort_rules=sort_rules, mask=mask, user=request.user)
+    return LexemeGrid.get_location(query)
 
 # twór Miłosza - trzeba kiedyś poprawić
 def cache_key(query):
-  key = json_encode(query.sort_rules) + json_encode(query.filters)
-  for vocabulary in visible_vocabularies(query.user):
-    key += vocabulary.id
-  if query.filtering_mode():
-    key += query.mask
-  return md5(key).hexdigest()
+    key = json_encode(query.sort_rules) + json_encode(query.filters)
+    for vocabulary in visible_vocabularies(query.user):
+        key += vocabulary.id
+    if query.filtering_mode():
+        key += query.mask
+    return md5(key).hexdigest()
+
 
 def get_cached_lexemes(query):
-  key = cache_key(query)
-  return cache.get(key)
+    key = cache_key(query)
+    return cache.get(key)
+
 
 def cache_lexemes(pk_list, query):
-  key = cache_key(query)
-  cache.set(key, pk_list)
-  key_list = cache.get('key_list', [])
-  if key not in key_list:
-    key_list.append(key)
-  cache.set('key_list', key_list)
+    key = cache_key(query)
+    cache.set(key, pk_list)
+    key_list = cache.get('key_list', [])
+    if key not in key_list:
+        key_list.append(key)
+    cache.set('key_list', key_list)
+
 
 def get_pk_list(query, force_reload=False):
-  if not force_reload:
-    pk_list = get_cached_lexemes(query)
-  else:
-    pk_list = None
-  if pk_list is None:
-    lexemes = LexemeGrid.get_sorted_queryset(query)
-    if 'rev' in lexemes.query.extra_select:
-      pk_list = list(row[0] for row in lexemes.values_list('pk', 'rev'))
+    if not force_reload:
+        pk_list = get_cached_lexemes(query)
     else:
-      #print lexemes.values_list('pk', flat=True).query
-      pk_list = list(lexemes.values_list('pk', flat=True))
-    cache_lexemes(pk_list, query)
-  return pk_list
+        pk_list = None
+    if pk_list is None:
+        lexemes = LexemeGrid.get_sorted_queryset(query)
+        if 'rev' in lexemes.query.extra_select:
+            pk_list = list(row[0] for row in lexemes.values_list('pk', 'rev'))
+        else:
+            #print lexemes.values_list('pk', flat=True).query
+            pk_list = list(lexemes.values_list('pk', flat=True))
+        cache_lexemes(pk_list, query)
+    return pk_list
+
 
 @ajax(method='get')
 def get_lexemes(request, page, rows, sort_rules, filters=None, mask='',
                 target_page=0, totalrows=0, force_reload=False):
-  request.session['sort_rules'] = json_encode(sort_rules)
-  request.session['filters'] = json_encode(filters)
-  page = target_page or page
-  limit = totalrows or rows
-  query = JqGridQuery(
-    filters=filters, sort_rules=sort_rules, mask=mask, user=request.user)
-  pk_list = get_pk_list(query, force_reload)
-  count = len(pk_list)
-  total_pages, start, response_rowcount = LexemeGrid.count_pages(
-    count, page, limit)
-  sublist = pk_list[start:start + response_rowcount]
-  lexemes_qs = Lexeme.objects.filter(pk__in=sublist).select_related(
-    'owner_vocabulary', 'part_of_speech').prefetch_related(
-    'lexemeinflectionpattern_set__pattern',
-    'lexemeinflectionpattern_set__inflection_characteristic',
-    'vocabularies')
-  lexemes_dict = dict((l.pk, l) for l in lexemes_qs)
-  lexemes = [lexemes_dict[pk] for pk in sublist]
-  return LexemeGrid.make_response(lexemes, count, page, total_pages)
+    request.session['sort_rules'] = json_encode(sort_rules)
+    request.session['filters'] = json_encode(filters)
+    page = target_page or page
+    limit = totalrows or rows
+    query = JqGridQuery(
+        filters=filters, sort_rules=sort_rules, mask=mask, user=request.user)
+    pk_list = get_pk_list(query, force_reload)
+    count = len(pk_list)
+    total_pages, start, response_rowcount = LexemeGrid.count_pages(
+        count, page, limit)
+    sublist = pk_list[start:start + response_rowcount]
+    lexemes_qs = Lexeme.objects.filter(pk__in=sublist).select_related(
+        'owner_vocabulary', 'part_of_speech').prefetch_related(
+        'lexemeinflectionpattern_set__pattern',
+        'lexemeinflectionpattern_set__inflection_characteristic',
+        'vocabularies')
+    lexemes_dict = dict((l.pk, l) for l in lexemes_qs)
+    lexemes = [lexemes_dict[pk] for pk in sublist]
+    return LexemeGrid.make_response(lexemes, count, page, total_pages)
diff --git a/dictionary/ajax_lexeme_view.py b/dictionary/ajax_lexeme_view.py
index 2f665a9..eff8bc2 100644
--- a/dictionary/ajax_lexeme_view.py
+++ b/dictionary/ajax_lexeme_view.py
@@ -7,552 +7,584 @@ from django.db.models import Max
 from dictionary.ajax_jqgrid import JqGridQuery
 from dictionary.ajax_lexeme_jqgrid import cache_key, get_pk_list
 from dictionary.models import Lexeme, LexemeInflectionPattern, PartOfSpeech, \
-  Pattern, InflectionCharacteristic, Vocabulary, Qualifier, \
-  prepare_table, ClassificationValue, CrossReference, TableTemplate, get_root, \
-  InputLexeme, CrossReferenceType, filter_visible, \
-  editable_vocabularies, visible_qualifiers, LexemeAttributeValue
+    Pattern, InflectionCharacteristic, Vocabulary, Qualifier, \
+    prepare_table, ClassificationValue, CrossReference, TableTemplate, get_root, \
+    InputLexeme, CrossReferenceType, filter_visible, \
+    editable_vocabularies, visible_qualifiers, LexemeAttributeValue
 from dictionary.forms import LexemeEditForm, LIPEditForm, ClassificationForm, \
-  CrossReferenceForm, ActionFieldForm, ACTION_FIELDS, LexemeOpenAttributeForm, \
-  LexemeClosedAttributeForm, LexemeMultipleAttributeForm
+    CrossReferenceForm, ActionFieldForm, ACTION_FIELDS, LexemeOpenAttributeForm, \
+    LexemeClosedAttributeForm, LexemeMultipleAttributeForm
 from common.decorators import render, ajax, AjaxError, render_template
 from common.util import error_messages
 
+
 @ajax(method='get', template='inflection_tables.html')
 def get_inflection_tables(request, variant, lexeme_id):
-  lexeme = Lexeme.all_objects.get(pk=lexeme_id) # może być nowy
-  if not lexeme.perm(request.user, 'view'):
-    raise AjaxError('access denied')
-  qualifiers = visible_qualifiers(request.user)
-  tables = lexeme.inflection_tables(variant, qualifiers=qualifiers)
-  return {
-    'tables': tables,
-    'lexeme': lexeme,
-    'cross_references': lexeme.refs_to.order_by('type__index'),
-    'info': lexeme.sgjp_info(),
-  }
+    lexeme = Lexeme.all_objects.get(pk=lexeme_id) # może być nowy
+    if not lexeme.perm(request.user, 'view'):
+        raise AjaxError('access denied')
+    qualifiers = visible_qualifiers(request.user)
+    tables = lexeme.inflection_tables(variant, qualifiers=qualifiers)
+    return {
+        'tables': tables,
+        'lexeme': lexeme,
+        'cross_references': lexeme.refs_to.order_by('type__index'),
+        'info': lexeme.sgjp_info(),
+    }
+
 
 @ajax(method='get', template='inflection_table.html')
 def table_preview(request, lexeme_id, pattern, inflection_characteristic,
                   lip_id, entry=None, pos=None):
-  lexeme = Lexeme.all_objects.get(pk=lexeme_id)
-  if not lexeme.perm(request.user, 'view'):
-    raise AjaxError('access denied')
-  if entry is None:
-    entry = lexeme.entry
-  if pos is None:
-    pos = lexeme.part_of_speech.symbol
-  try:
-    pattern = Pattern.objects.get(name=pattern)
-    inflection_characteristic = InflectionCharacteristic.objects.get(
-      pk=inflection_characteristic)
-    if lip_id.startswith('lip_add'):
-      lip = LexemeInflectionPattern(lexeme=lexeme, index=0)
-    else:
-      lip = LexemeInflectionPattern.objects.get(pk=int(lip_id[3:]))
-    lip.pattern = pattern
-    lip.inflection_characteristic = inflection_characteristic
-    lip.root = get_root(entry, pos, pattern, inflection_characteristic)
-    qualifiers = visible_qualifiers(request.user)
-    table = lip.inflection_table('0', separated=True, qualifiers=qualifiers,
-                                 edit_view=True)
-    prepare_table(table)
-  except Pattern.DoesNotExist:
-    table = None
-  except TableTemplate.DoesNotExist:
-    table = None
-  return {'table': table}
+    lexeme = Lexeme.all_objects.get(pk=lexeme_id)
+    if not lexeme.perm(request.user, 'view'):
+        raise AjaxError('access denied')
+    if entry is None:
+        entry = lexeme.entry
+    if pos is None:
+        pos = lexeme.part_of_speech.symbol
+    try:
+        pattern = Pattern.objects.get(name=pattern)
+        inflection_characteristic = InflectionCharacteristic.objects.get(
+            pk=inflection_characteristic)
+        if lip_id.startswith('lip_add'):
+            lip = LexemeInflectionPattern(lexeme=lexeme, index=0)
+        else:
+            lip = LexemeInflectionPattern.objects.get(pk=int(lip_id[3:]))
+        lip.pattern = pattern
+        lip.inflection_characteristic = inflection_characteristic
+        lip.root = get_root(entry, pos, pattern, inflection_characteristic)
+        qualifiers = visible_qualifiers(request.user)
+        table = lip.inflection_table('0', separated=True, qualifiers=qualifiers,
+                                     edit_view=True)
+        prepare_table(table)
+    except Pattern.DoesNotExist:
+        table = None
+    except TableTemplate.DoesNotExist:
+        table = None
+    return {'table': table}
+
 
 @ajax(method='get', template="odm_forms.html")
 def odm_forms(request, lexeme_id):
-  to_return = {}
-  l = Lexeme.all_objects.get(pk=lexeme_id)
-  if not l.perm(request.user, 'view'):
-    raise AjaxError('access denied')
-  odm_lexemes = []
-  for l in InputLexeme.objects.filter(entry=l.entry):
-    odm_lexemes.append(list(l.inputform_set.values_list('form', flat=True)))
-  to_return['odm_lexemes'] = odm_lexemes
-  return to_return
+    to_return = {}
+    l = Lexeme.all_objects.get(pk=lexeme_id)
+    if not l.perm(request.user, 'view'):
+        raise AjaxError('access denied')
+    odm_lexemes = []
+    for l in InputLexeme.objects.filter(entry=l.entry):
+        odm_lexemes.append(list(l.inputform_set.values_list('form', flat=True)))
+    to_return['odm_lexemes'] = odm_lexemes
+    return to_return
+
 
 def attribute_forms(l, part_of_speech=None, ics=None):
-  for attr, v in l.attributes_values(part_of_speech, ics):
-    if not attr.closed:
-      form_class = LexemeOpenAttributeForm
-    elif not attr.multiple:
-      form_class = LexemeClosedAttributeForm
-    else:
-      form_class = LexemeMultipleAttributeForm
-    prefix = 'attr%s' % attr.pk
-    yield form_class(attribute=attr, initial_value=v, prefix=prefix)
+    for attr, v in l.attributes_values(part_of_speech, ics):
+        if not attr.closed:
+            form_class = LexemeOpenAttributeForm
+        elif not attr.multiple:
+            form_class = LexemeClosedAttributeForm
+        else:
+            form_class = LexemeMultipleAttributeForm
+        prefix = 'attr%s' % attr.pk
+        yield form_class(attribute=attr, initial_value=v, prefix=prefix)
+
 
 @render_template('extra_attributes.html')
 @ajax(method='get', template='extra_attributes.html')
 def extra_attributes(request, lexeme_id, pos, ics):
-  l = Lexeme.all_objects.get(pk=lexeme_id)
-  part_of_speech = PartOfSpeech.objects.get(symbol=pos)
-  ics = InflectionCharacteristic.objects.filter(pk__in=ics)
-  return {
-    'forms': attribute_forms(
-      l, part_of_speech=part_of_speech, ics=ics),
-  }
+    l = Lexeme.all_objects.get(pk=lexeme_id)
+    part_of_speech = PartOfSpeech.objects.get(symbol=pos)
+    ics = InflectionCharacteristic.objects.filter(pk__in=ics)
+    return {
+        'forms': attribute_forms(
+            l, part_of_speech=part_of_speech, ics=ics),
+    }
+
 
 @ajax(method='get')
 def check_attributes(request, lexeme_id, pos, ics):
-  l = Lexeme.all_objects.get(pk=lexeme_id)
-  part_of_speech = PartOfSpeech.objects.get(symbol=pos)
-  ics = InflectionCharacteristic.objects.filter(
-    part_of_speech=part_of_speech, symbol__in=ics)
-  attrs = list(l.attributes(part_of_speech, ics).values_list('pk', flat=True))
-  return {'attrs': attrs}
+    l = Lexeme.all_objects.get(pk=lexeme_id)
+    part_of_speech = PartOfSpeech.objects.get(symbol=pos)
+    ics = InflectionCharacteristic.objects.filter(
+        part_of_speech=part_of_speech, symbol__in=ics)
+    attrs = list(l.attributes(part_of_speech, ics).values_list('pk', flat=True))
+    return {'attrs': attrs}
+
 
 @render_template('lexeme_edit_form.html')
 @ajax(method='get', template='lexeme_edit_form.html')
 def lexeme_edit_form(request, id):
-  to_return = {}
-  l = Lexeme.all_objects.get(pk=id) # bo może być świeżo utworzony
-  if not l.perm(request.user, 'view'):
-    raise AjaxError('access denied')
-  editable = l.perm(request.user, 'change')
-  to_return['editable'] = editable
-  owner = l.owner_vocabulary
-
-  to_return['attribute_forms'] = attribute_forms(l)
-
-  editable_vocabs = editable_vocabularies(request.user)
-  ro_owner = owner not in editable_vocabs
-  to_return['multiple_editable'] = editable and editable_vocabs.count() > 1
-  if ro_owner:
-    # nie pokazujemy wszystkich, tylko te z właściciela
-    ro_qualifiers = l.qualifiers.filter(vocabulary=owner)
-  else:
-    ro_qualifiers = []
-  to_return['owner'] = owner
-  ro_vocabularies = l.visible_vocabularies(request.user).exclude(
-    pk=owner.pk).exclude(pk__in=editable_vocabs)
-  to_return['ro_vocabularies'] = ro_vocabularies
-  to_return['ro_qualifiers'] = ro_qualifiers
-
-  to_return['form'] = LexemeEditForm(
-    instance=l, editable=editable, user=request.user)
-  to_return['id'] = l.pk
-  to_return['part_of_speech'] = l.part_of_speech.symbol
-  to_return['classification_forms'] = make_classification_forms(
-    l, editable=editable)
-
-  lips = l.lexemeinflectionpattern_set.all()
-  to_return['lip_forms'] = [
-    (LIPEditForm(
-      lexeme=l, part_of_speech=l.part_of_speech, instance=lip,
-      prefix='lip' + str(lip.pk), user=request.user, editable=editable),
-     lip.qualifiers.filter(vocabulary=owner) if ro_owner else [])
-    for lip in lips]
-  crs = l.refs_to.order_by('type__index')
-  to_return['cross_references'] = crs
-  return to_return
+    to_return = {}
+    l = Lexeme.all_objects.get(pk=id) # bo może być świeżo utworzony
+    if not l.perm(request.user, 'view'):
+        raise AjaxError('access denied')
+    editable = l.perm(request.user, 'change')
+    to_return['editable'] = editable
+    owner = l.owner_vocabulary
+
+    to_return['attribute_forms'] = attribute_forms(l)
+
+    editable_vocabs = editable_vocabularies(request.user)
+    ro_owner = owner not in editable_vocabs
+    to_return['multiple_editable'] = editable and editable_vocabs.count() > 1
+    if ro_owner:
+        # nie pokazujemy wszystkich, tylko te z właściciela
+        ro_qualifiers = l.qualifiers.filter(vocabulary=owner)
+    else:
+        ro_qualifiers = []
+    to_return['owner'] = owner
+    ro_vocabularies = l.visible_vocabularies(request.user).exclude(
+        pk=owner.pk).exclude(pk__in=editable_vocabs)
+    to_return['ro_vocabularies'] = ro_vocabularies
+    to_return['ro_qualifiers'] = ro_qualifiers
+
+    to_return['form'] = LexemeEditForm(
+        instance=l, editable=editable, user=request.user)
+    to_return['id'] = l.pk
+    to_return['part_of_speech'] = l.part_of_speech.symbol
+    to_return['classification_forms'] = make_classification_forms(
+        l, editable=editable)
+
+    lips = l.lexemeinflectionpattern_set.all()
+    to_return['lip_forms'] = [
+        (LIPEditForm(
+            lexeme=l, part_of_speech=l.part_of_speech, instance=lip,
+            prefix='lip' + str(lip.pk), user=request.user, editable=editable),
+         lip.qualifiers.filter(vocabulary=owner) if ro_owner else [])
+        for lip in lips]
+    crs = l.refs_to.order_by('type__index')
+    to_return['cross_references'] = crs
+    return to_return
+
 
 @ajax(method='get')
 def check_classifications(request, owner_id, pos):
-  part_of_speech = PartOfSpeech.objects.get(symbol=pos)
-  owner = Vocabulary.objects.get(pk=owner_id)
-  classifications = owner.classifications.filter(
-    parts_of_speech=part_of_speech)
-  return {'classifications': list(classifications.values_list('pk', flat=True))}
+    part_of_speech = PartOfSpeech.objects.get(symbol=pos)
+    owner = Vocabulary.objects.get(pk=owner_id)
+    classifications = owner.classifications.filter(
+        parts_of_speech=part_of_speech)
+    return {
+    'classifications': list(classifications.values_list('pk', flat=True))}
+
 
 def make_classification_forms(lexeme, vocabulary=None, part_of_speech=None,
                               editable=True):
-  if not vocabulary:
-    vocabulary = lexeme.owner_vocabulary
-  if not part_of_speech:
-    part_of_speech = lexeme.part_of_speech
-  classifications = vocabulary.classifications.filter(
-    parts_of_speech=part_of_speech)
-  classification_forms = []
-  for c in classifications:
-    values = lexeme.classification_values(c)
-    classification_forms.append(
-      ClassificationForm(
-        classification=c, values=values, prefix='cl' + str(c.pk),
-        editable=editable))
-  return classification_forms
+    if not vocabulary:
+        vocabulary = lexeme.owner_vocabulary
+    if not part_of_speech:
+        part_of_speech = lexeme.part_of_speech
+    classifications = vocabulary.classifications.filter(
+        parts_of_speech=part_of_speech)
+    classification_forms = []
+    for c in classifications:
+        values = lexeme.classification_values(c)
+        classification_forms.append(
+            ClassificationForm(
+                classification=c, values=values, prefix='cl' + str(c.pk),
+                editable=editable))
+    return classification_forms
+
 
 @render_template('classification_forms.html')
 @ajax(method='get', template='classification_forms.html')
 def classification_forms(request, lexeme_id, vocab_id, pos):
-  l = Lexeme.objects.get(pk=lexeme_id)
-  part_of_speech = PartOfSpeech.objects.get(symbol=pos)
-  if vocab_id:
-    vocab = Vocabulary.objects.get(pk=vocab_id)
-  else:
-    vocab = None
-  forms = make_classification_forms(l, vocab, part_of_speech)
-  return {'forms': forms}
+    l = Lexeme.objects.get(pk=lexeme_id)
+    part_of_speech = PartOfSpeech.objects.get(symbol=pos)
+    if vocab_id:
+        vocab = Vocabulary.objects.get(pk=vocab_id)
+    else:
+        vocab = None
+    forms = make_classification_forms(l, vocab, part_of_speech)
+    return {'forms': forms}
+
 
 @render_template('lexeme_edit_form_row.html')
 @ajax(method='get', template='lexeme_edit_form_row.html')
 def new_lip_edit_row(request, lexeme_id, pos_id, num):
-  l = Lexeme.all_objects.get(pk=lexeme_id)
-  if not l.perm(request.user, 'change'):
-    raise AjaxError('access denied')
-  if not pos_id:
-    raise AjaxError(u'Nieokreślona część mowy.')
-  pos = PartOfSpeech.objects.get(pk=pos_id)
-  lip_form = LIPEditForm(
-    lexeme=l, part_of_speech=pos, prefix='lip_add_%s' % num, user=request.user)
-  return {'lip_form': lip_form, 'editable': True}
+    l = Lexeme.all_objects.get(pk=lexeme_id)
+    if not l.perm(request.user, 'change'):
+        raise AjaxError('access denied')
+    if not pos_id:
+        raise AjaxError(u'Nieokreślona część mowy.')
+    pos = PartOfSpeech.objects.get(pk=pos_id)
+    lip_form = LIPEditForm(
+        lexeme=l, part_of_speech=pos, prefix='lip_add_%s' % num,
+        user=request.user)
+    return {'lip_form': lip_form, 'editable': True}
+
 
 @render('cross_reference_row.html')
 @ajax(method='get', encode_result=False)
 def new_cross_reference_row(request, id, pos_id):
-  l = Lexeme.objects.get(pk=id)
-  if not l.perm(request.user, 'change'):
-    raise AjaxError('access denied')
-  pos = PartOfSpeech.objects.get(pk=pos_id)
-  cr_form = CrossReferenceForm(lexeme=l, pos=pos, prefix='cr_add_NUM')
-  return {'cr_form': cr_form, 'editable': True}
+    l = Lexeme.objects.get(pk=id)
+    if not l.perm(request.user, 'change'):
+        raise AjaxError('access denied')
+    pos = PartOfSpeech.objects.get(pk=pos_id)
+    cr_form = CrossReferenceForm(lexeme=l, pos=pos, prefix='cr_add_NUM')
+    return {'cr_form': cr_form, 'editable': True}
+
 
 @ajax(method='post')
 def update_lexeme(request, form_data, mask=''):
-  form_dict = dict((x['name'], x['value']) for x in form_data)
-  l = Lexeme.all_objects.get(pk=form_dict['id'])
-  if not l.perm(request.user, 'view'):
-    raise AjaxError('access denied')
-  owner = l.owner_vocabulary
-  created = l.entry == ''
-  if not l.perm(request.user, 'change'):
-    return update_lexeme_qualifiers(
-      l, request.user, form_dict, form_data)
-  form = LexemeEditForm(data=form_dict, instance=l, user=request.user)
-  if form.is_valid():
-    l = form.save()
-    l.responsible = request.user
-    l.deleted = False
-    l.fix_homonym_number()
-    l.save()
-  else:
-    raise AjaxError(error_messages(form))
-
-  for vocab in editable_vocabularies(request.user):
-    if vocab != owner:
-      vocab.set_lexeme(l, vocab in form.cleaned_data['vocabularies'])
-  new_owner = form.cleaned_data.get('new_owner')
-  if new_owner and new_owner != owner:
-    l.change_owner(new_owner)
-    l.save()
-  for qualifier in form.fields['qualifiers'].queryset:
-    qualifier.set_for(l, qualifier in form.cleaned_data['qualifiers'])
-
-  classifications = l.owner_vocabulary.classifications.filter(
-    parts_of_speech=l.part_of_speech)
-  for c in classifications:
-    classification_form = ClassificationForm(
-      data=form_dict, classification=c, prefix='cl' + str(c.pk))
-    if classification_form.is_valid():
-      cvs = ClassificationValue.objects.filter(
-        pk__in=classification_form.cleaned_data['values'])
-      l_cvs = l.classification_values(c)
-      for cv in l_cvs:
-        if cv.pk not in classification_form.cleaned_data['values']:
-          cv.remove_lexeme(l)
-      for cv in cvs:
-        if cv not in l_cvs:
-          cv.add_lexeme(l)
+    form_dict = dict((x['name'], x['value']) for x in form_data)
+    l = Lexeme.all_objects.get(pk=form_dict['id'])
+    if not l.perm(request.user, 'view'):
+        raise AjaxError('access denied')
+    owner = l.owner_vocabulary
+    created = l.entry == ''
+    if not l.perm(request.user, 'change'):
+        return update_lexeme_qualifiers(
+            l, request.user, form_dict, form_data)
+    form = LexemeEditForm(data=form_dict, instance=l, user=request.user)
+    if form.is_valid():
+        l = form.save()
+        l.responsible = request.user
+        l.deleted = False
+        l.fix_homonym_number()
+        l.save()
     else:
-      raise AjaxError(error_messages(classification_form))
-  for cv in l.classificationvalue_set.all():
-    if cv.classification not in classifications:
-      cv.remove_lexeme(l)
-
-  extra_attributes = l.attributes()
-  for attr in extra_attributes:
-    prefix = 'attr' + str(attr.pk)
-    attr_values = attr.values.filter(lexemes=l)
-    if not attr.multiple:
-      assert len(attr_values) <= 1
-      if not attr.closed:
-        attr_form = LexemeOpenAttributeForm(
-          attribute=attr, data=form_dict, prefix=prefix)
-      else:
-        attr_form = LexemeClosedAttributeForm(
-          attribute=attr, data=form_dict, prefix=prefix)
-      if attr_form.is_valid():
-        if not attr.closed:
-          value = attr_form.cleaned_data['value']
-          av = LexemeAttributeValue.objects.get_or_create(
-            attribute=attr, value=value)
+        raise AjaxError(error_messages(form))
+
+    for vocab in editable_vocabularies(request.user):
+        if vocab != owner:
+            vocab.set_lexeme(l, vocab in form.cleaned_data['vocabularies'])
+    new_owner = form.cleaned_data.get('new_owner')
+    if new_owner and new_owner != owner:
+        l.change_owner(new_owner)
+        l.save()
+    for qualifier in form.fields['qualifiers'].queryset:
+        qualifier.set_for(l, qualifier in form.cleaned_data['qualifiers'])
+
+    classifications = l.owner_vocabulary.classifications.filter(
+        parts_of_speech=l.part_of_speech)
+    for c in classifications:
+        classification_form = ClassificationForm(
+            data=form_dict, classification=c, prefix='cl' + str(c.pk))
+        if classification_form.is_valid():
+            cvs = ClassificationValue.objects.filter(
+                pk__in=classification_form.cleaned_data['values'])
+            l_cvs = l.classification_values(c)
+            for cv in l_cvs:
+                if cv.pk not in classification_form.cleaned_data['values']:
+                    cv.remove_lexeme(l)
+            for cv in cvs:
+                if cv not in l_cvs:
+                    cv.add_lexeme(l)
         else:
-          av = attr_form.cleaned_data['value']
-        if not attr_values or attr_values.get() != av:
-          for av1 in attr_values:
-            av1.remove_lexeme(l)
-          av.add_lexeme(l)
-    else:
-      attr_form = LexemeMultipleAttributeForm(
-        attribute=attr, data=form_dict, prefix=prefix)
-      if attr_form.is_valid():
-        new_values = attr_form.cleaned_data['value']
-        for av in set(attr_values) - set(new_values):
-          av.remove_lexeme(l)
-        for av in set(new_values) - set(attr_values):
-          av.add_lexeme(l)
-  for av in l.lexemeattributevalue_set.all():
-    if av.attribute not in extra_attributes:
-      av.remove_lexeme(l)
-
-  for prefix in form_dict['deleted']:
-    pk = int(prefix[3:])
-    LexemeInflectionPattern.objects.get(pk=pk).delete()
-  for cr_pk in form_dict['deleted_cr']:
-    CrossReference.objects.get(pk=cr_pk).delete()
-  submitted_lips = []
-  submitted_crs = []
-  for pair in form_data:
-    # może (?) się psuć, jeśli jest zły charfl
-    name = pair['name']
-    prefix = name.split('-')[0]
-    if name.startswith('lip') and prefix not in submitted_lips:
-      submitted_lips.append(prefix)
-      if prefix.startswith('lip_add'):
-        lip = LexemeInflectionPattern()
-        lip.lexeme = l
-      else:
+            raise AjaxError(error_messages(classification_form))
+    for cv in l.classificationvalue_set.all():
+        if cv.classification not in classifications:
+            cv.remove_lexeme(l)
+
+    extra_attributes = l.attributes()
+    for attr in extra_attributes:
+        prefix = 'attr' + str(attr.pk)
+        attr_values = attr.values.filter(lexemes=l)
+        if not attr.multiple:
+            assert len(attr_values) <= 1
+            if not attr.closed:
+                attr_form = LexemeOpenAttributeForm(
+                    attribute=attr, data=form_dict, prefix=prefix)
+            else:
+                attr_form = LexemeClosedAttributeForm(
+                    attribute=attr, data=form_dict, prefix=prefix)
+            if attr_form.is_valid():
+                if not attr.closed:
+                    value = attr_form.cleaned_data['value']
+                    av = LexemeAttributeValue.objects.get_or_create(
+                        attribute=attr, value=value)
+                else:
+                    av = attr_form.cleaned_data['value']
+                if not attr_values or attr_values.get() != av:
+                    for av1 in attr_values:
+                        av1.remove_lexeme(l)
+                    av.add_lexeme(l)
+        else:
+            attr_form = LexemeMultipleAttributeForm(
+                attribute=attr, data=form_dict, prefix=prefix)
+            if attr_form.is_valid():
+                new_values = attr_form.cleaned_data['value']
+                for av in set(attr_values) - set(new_values):
+                    av.remove_lexeme(l)
+                for av in set(new_values) - set(attr_values):
+                    av.add_lexeme(l)
+    for av in l.lexemeattributevalue_set.all():
+        if av.attribute not in extra_attributes:
+            av.remove_lexeme(l)
+
+    for prefix in form_dict['deleted']:
         pk = int(prefix[3:])
-        lip = LexemeInflectionPattern.objects.get(pk=pk)
-      form_dict[prefix + '-qualifiers'] = get_list(
-        form_data, prefix + '-qualifiers')
-      lip_form = LIPEditForm(
-        lexeme=l, part_of_speech=l.part_of_speech, data=form_dict, prefix=prefix,
-        instance=lip, user=request.user, index=len(submitted_lips))
-      if lip_form.is_valid():
-        lip = lip_form.save()
-        lip.root = l.get_root(lip.pattern, lip.inflection_characteristic)
-        if lip.root is None:
-          raise AjaxError(u'Niepasujące zakończenie formy podstawowej.')
-        for qualifier in lip_form.fields['qualifiers'].queryset:
-          qualifier.set_for(
-            lip, qualifier in lip_form.cleaned_data['qualifiers'])
-        lip.save()
-      else:
-        raise AjaxError(error_messages(lip_form))
-    if name.startswith('cr_add') and prefix not in submitted_crs:
-      submitted_crs.append(prefix)
-      cr_form = CrossReferenceForm(data=form_dict, prefix=prefix)
-      if cr_form.is_valid():
-        cr_form.save()
-      else:
-        raise AjaxError(error_messages(cr_form))
-  if len(submitted_lips) == 0 and l.status != 'cand':
-    raise AjaxError(u'Wybierz odmianę lub ustaw status "kandydat".')
-  l.refresh_forms()
-  if created:
-    sort_rules = json.loads(request.session['sort_rules'])
-    filters = json.loads(request.session['filters'])
-    query = JqGridQuery(
-      filters=filters, sort_rules=sort_rules, mask=mask, user=request.user)
-    key = cache_key(query)
-    pk_list = cache.get(key)
-    if pk_list:
-      pk_list = [l.pk] + pk_list
-      cache.set(key, pk_list)
-  return {}
+        LexemeInflectionPattern.objects.get(pk=pk).delete()
+    for cr_pk in form_dict['deleted_cr']:
+        CrossReference.objects.get(pk=cr_pk).delete()
+    submitted_lips = []
+    submitted_crs = []
+    for pair in form_data:
+        # może (?) się psuć, jeśli jest zły charfl
+        name = pair['name']
+        prefix = name.split('-')[0]
+        if name.startswith('lip') and prefix not in submitted_lips:
+            submitted_lips.append(prefix)
+            if prefix.startswith('lip_add'):
+                lip = LexemeInflectionPattern()
+                lip.lexeme = l
+            else:
+                pk = int(prefix[3:])
+                lip = LexemeInflectionPattern.objects.get(pk=pk)
+            form_dict[prefix + '-qualifiers'] = get_list(
+                form_data, prefix + '-qualifiers')
+            lip_form = LIPEditForm(
+                lexeme=l, part_of_speech=l.part_of_speech, data=form_dict,
+                prefix=prefix,
+                instance=lip, user=request.user, index=len(submitted_lips))
+            if lip_form.is_valid():
+                lip = lip_form.save()
+                lip.root = l.get_root(lip.pattern,
+                                      lip.inflection_characteristic)
+                if lip.root is None:
+                    raise AjaxError(
+                        u'Niepasujące zakończenie formy podstawowej.')
+                for qualifier in lip_form.fields['qualifiers'].queryset:
+                    qualifier.set_for(
+                        lip, qualifier in lip_form.cleaned_data['qualifiers'])
+                lip.save()
+            else:
+                raise AjaxError(error_messages(lip_form))
+        if name.startswith('cr_add') and prefix not in submitted_crs:
+            submitted_crs.append(prefix)
+            cr_form = CrossReferenceForm(data=form_dict, prefix=prefix)
+            if cr_form.is_valid():
+                cr_form.save()
+            else:
+                raise AjaxError(error_messages(cr_form))
+    if len(submitted_lips) == 0 and l.status != 'cand':
+        raise AjaxError(u'Wybierz odmianę lub ustaw status "kandydat".')
+    l.refresh_forms()
+    if created:
+        sort_rules = json.loads(request.session['sort_rules'])
+        filters = json.loads(request.session['filters'])
+        query = JqGridQuery(
+            filters=filters, sort_rules=sort_rules, mask=mask,
+            user=request.user)
+        key = cache_key(query)
+        pk_list = cache.get(key)
+        if pk_list:
+            pk_list = [l.pk] + pk_list
+            cache.set(key, pk_list)
+    return {}
+
 
 def update_lexeme_qualifiers(lexeme, user, form_dict, form_data):
-  owner = lexeme.owner_vocabulary
-  editable_vocabs = editable_vocabularies(user).exclude(pk=owner.pk)
-  l_editable_vocabs = lexeme.editable_vocabularies(user)
-  qualifiers = Qualifier.objects.filter(vocabulary__in=l_editable_vocabs)
-  for qualifier in qualifiers:
-    qualifier.set_for(
-      lexeme, unicode(qualifier.pk) in form_dict['qualifiers'])
-  for vocab in editable_vocabs:
-    vocab.set_lexeme(lexeme, vocab.pk in form_dict['vocabularies'])
-  submitted_lips = []
-  for pair in form_data:
-    name = pair['name']
-    prefix = name.split('-')[0]
-    if name.startswith('lip') and prefix not in submitted_lips:
-      submitted_lips.append(prefix)
-      pk = int(prefix[3:])
-      lip = LexemeInflectionPattern.objects.get(pk=pk)
-      lip_qualifiers = get_list(form_data, prefix + '-qualifiers')
-      for qualifier in qualifiers:
-        qualifier.set_for(lip, unicode(qualifier.pk) in lip_qualifiers)
-  return {}
+    owner = lexeme.owner_vocabulary
+    editable_vocabs = editable_vocabularies(user).exclude(pk=owner.pk)
+    l_editable_vocabs = lexeme.editable_vocabularies(user)
+    qualifiers = Qualifier.objects.filter(vocabulary__in=l_editable_vocabs)
+    for qualifier in qualifiers:
+        qualifier.set_for(
+            lexeme, unicode(qualifier.pk) in form_dict['qualifiers'])
+    for vocab in editable_vocabs:
+        vocab.set_lexeme(lexeme, vocab.pk in form_dict['vocabularies'])
+    submitted_lips = []
+    for pair in form_data:
+        name = pair['name']
+        prefix = name.split('-')[0]
+        if name.startswith('lip') and prefix not in submitted_lips:
+            submitted_lips.append(prefix)
+            pk = int(prefix[3:])
+            lip = LexemeInflectionPattern.objects.get(pk=pk)
+            lip_qualifiers = get_list(form_data, prefix + '-qualifiers')
+            for qualifier in qualifiers:
+                qualifier.set_for(lip, unicode(qualifier.pk) in lip_qualifiers)
+    return {}
+
 
 def get_list(form_data, name):
-  return [pair['value'] for pair in form_data if pair['name'] == name]
+    return [pair['value'] for pair in form_data if pair['name'] == name]
+
 
 @ajax(method='post')
 def delete_lexeme(request, lexeme_id):
-  lexeme_id = int(lexeme_id)
-  l = Lexeme.objects.get(pk=lexeme_id)
-  if not l.perm(request.user, 'change'):
-    raise AjaxError('access denied')
-  l.deleted = True
-  l.save()
-  key_list = cache.get('key_list', [])
-  for key in key_list:
-    pk_list = cache.get(key)
-    if pk_list and lexeme_id in pk_list:
-      pk_list.remove(lexeme_id)
-      cache.set(key, pk_list)
-  return {}
+    lexeme_id = int(lexeme_id)
+    l = Lexeme.objects.get(pk=lexeme_id)
+    if not l.perm(request.user, 'change'):
+        raise AjaxError('access denied')
+    l.deleted = True
+    l.save()
+    key_list = cache.get('key_list', [])
+    for key in key_list:
+        pk_list = cache.get(key)
+        if pk_list and lexeme_id in pk_list:
+            pk_list.remove(lexeme_id)
+            cache.set(key, pk_list)
+    return {}
+
 
 @ajax(method='get')
 def check_pos(request, pos_id, ic_id):
-  ic = InflectionCharacteristic.objects.get(pk=ic_id)
-  if InflectionCharacteristic.objects.filter(
-       symbol=ic.symbol, part_of_speech__pk=pos_id):
-    return {'answer': 'yes'}
-  else:
-    return {'answer': 'no'}
+    ic = InflectionCharacteristic.objects.get(pk=ic_id)
+    if InflectionCharacteristic.objects.filter(
+            symbol=ic.symbol, part_of_speech__pk=pos_id):
+        return {'answer': 'yes'}
+    else:
+        return {'answer': 'no'}
+
 
 @ajax(method='get')
 def check_pattern(request, pattern_name, ic_id):
-  lips = LexemeInflectionPattern.objects.filter(
-    inflection_characteristic__pk=ic_id, pattern__name=pattern_name)
-  lips = lips.exclude(lexeme__status='cand')
-  if lips.exists():
-    return {'answer': 'yes'}
-  else:
-    return {'answer': 'no'}
+    lips = LexemeInflectionPattern.objects.filter(
+        inflection_characteristic__pk=ic_id, pattern__name=pattern_name)
+    lips = lips.exclude(lexeme__status='cand')
+    if lips.exists():
+        return {'answer': 'yes'}
+    else:
+        return {'answer': 'no'}
+
 
 @ajax(method='get')
 def get_ics(request, pos_id):
-  return {'ics': list(InflectionCharacteristic.objects.filter(
-                        part_of_speech__pk=pos_id).values_list('pk', 'symbol'))}
+    return {'ics': list(InflectionCharacteristic.objects.filter(
+        part_of_speech__pk=pos_id).values_list('pk', 'symbol'))}
+
 
 START_ID = 1000000
 
+
 @ajax(method='post')
 def create_lexeme(request, vocab_id):
-  owner = Vocabulary.objects.get(pk=vocab_id)
-  if request.user not in owner.all_editors():
-    raise AjaxError('access denied')
-  next_id = Lexeme.all_objects.filter(
-    pk__gte=START_ID).aggregate(Max('id'))['id__max']
-  next_id = next_id + 1 if next_id else START_ID
-  l = Lexeme()
-  l.id = next_id
-  l.homonym_number = 1 # zanim zostanie faktycznie stworzony
-  l.part_of_speech = PartOfSpeech.objects.get(symbol='subst')
-  l.owner_vocabulary = owner
-  l.status = 'cand'
-  l.responsible = request.user
-  l.deleted = True # proste i genialne!
-  l.save()
-  owner.add_lexeme(l)
-  return {'id': l.id}
+    owner = Vocabulary.objects.get(pk=vocab_id)
+    if request.user not in owner.all_editors():
+        raise AjaxError('access denied')
+    next_id = Lexeme.all_objects.filter(
+        pk__gte=START_ID).aggregate(Max('id'))['id__max']
+    next_id = next_id + 1 if next_id else START_ID
+    l = Lexeme()
+    l.id = next_id
+    l.homonym_number = 1 # zanim zostanie faktycznie stworzony
+    l.part_of_speech = PartOfSpeech.objects.get(symbol='subst')
+    l.owner_vocabulary = owner
+    l.status = 'cand'
+    l.responsible = request.user
+    l.deleted = True # proste i genialne!
+    l.save()
+    owner.add_lexeme(l)
+    return {'id': l.id}
+
 
 @ajax(method='get', login_required=True)
 def homonym_count(request, entry, lexeme_id):
-  lexemes = Lexeme.objects.filter(entry=entry).exclude(pk=lexeme_id)
-  lexemes = filter_visible(lexemes, request.user)
-  return {'count': lexemes.count()}
+    lexemes = Lexeme.objects.filter(entry=entry).exclude(pk=lexeme_id)
+    lexemes = filter_visible(lexemes, request.user)
+    return {'count': lexemes.count()}
+
 
 @ajax(method='get', login_required=True)
 def cr_homonyms(request, entry, cr_type):
-  cr_type = CrossReferenceType.objects.get(pk=cr_type)
-  lexemes = Lexeme.objects.filter(entry=entry, part_of_speech=cr_type.to_pos)
-  lexemes_data = [
-    {
-      'homonym_number': l.homonym_number,
-      'lip_data': l.lip_data(),
-    } for l in lexemes.order_by('homonym_number')
-  ]
-  return {'lexemes': lexemes_data}
+    cr_type = CrossReferenceType.objects.get(pk=cr_type)
+    lexemes = Lexeme.objects.filter(entry=entry, part_of_speech=cr_type.to_pos)
+    lexemes_data = [
+        {
+            'homonym_number': l.homonym_number,
+            'lip_data': l.lip_data(),
+        } for l in lexemes.order_by('homonym_number')
+    ]
+    return {'lexemes': lexemes_data}
 
 
 @render('new_action_row.html')
 @ajax(method='get', login_required=True, encode_result=False)
 def new_action_row(request):
-  form = ActionFieldForm(prefix='action_NUM')
-  return {'form': form}
+    form = ActionFieldForm(prefix='action_NUM')
+    return {'form': form}
+
 
 @ajax(method='get', login_required=True)
 def dynamic_action_fields(request, field_name):
-  action_form, value_form = dict(ACTION_FIELDS)[field_name][1:3]
-  return {
-    'action': action_form()['action'].as_widget(),
-    'value': value_form(request)['value'].as_widget(),
-  }
+    action_form, value_form = dict(ACTION_FIELDS)[field_name][1:3]
+    return {
+        'action': action_form()['action'].as_widget(),
+        'value': value_form(request)['value'].as_widget(),
+    }
+
 
 @ajax(method='post', login_required=True)
 def execute_group_actions(request, actions, filters):
-  if not request.user.has_perm('dictionary.change_lexeme'):
-    raise AjaxError('access denied')
-  if isinstance(filters, basestring):
-    filters = json.loads(filters)
-  query = JqGridQuery(
-    filters=filters, sort_rules=[], mask='', user=request.user)
-  pk_list = get_pk_list(query)
-  lexemes = Lexeme.objects.filter(pk__in=pk_list)
-  for l in lexemes:
-    for action in actions:
-      field = action['field']
-      if field == 'status':
-        # action['type'] == 'set'
-        l.status = action['value']
-      elif field == 'using_vocabulary':
-        vocab = Vocabulary.objects.get(pk=action['value'])
-        if action['type'] == 'add':
-          vocab.add_lexeme(l)
-        else: # 'remove'
-          if vocab != l.owner_vocabulary:
-            vocab.remove_lexeme(l)
-      else: # field == 'lexeme_qualifier'
-        qual = Qualifier.objects.get(pk=action['value'])
-        # a co jeśli koliduje z innym?
-        if action['type'] == 'add':
-          l.qualifiers.add(qual) #add
-        else:
-          l.qualifiers.remove(qual) #add
-    l.save()
-  #print repr(actions), repr(filters)
-  return {}
+    if not request.user.has_perm('dictionary.change_lexeme'):
+        raise AjaxError('access denied')
+    if isinstance(filters, basestring):
+        filters = json.loads(filters)
+    query = JqGridQuery(
+        filters=filters, sort_rules=[], mask='', user=request.user)
+    pk_list = get_pk_list(query)
+    lexemes = Lexeme.objects.filter(pk__in=pk_list)
+    for l in lexemes:
+        for action in actions:
+            field = action['field']
+            if field == 'status':
+                # action['type'] == 'set'
+                l.status = action['value']
+            elif field == 'using_vocabulary':
+                vocab = Vocabulary.objects.get(pk=action['value'])
+                if action['type'] == 'add':
+                    vocab.add_lexeme(l)
+                else: # 'remove'
+                    if vocab != l.owner_vocabulary:
+                        vocab.remove_lexeme(l)
+            else: # field == 'lexeme_qualifier'
+                qual = Qualifier.objects.get(pk=action['value'])
+                # a co jeśli koliduje z innym?
+                if action['type'] == 'add':
+                    l.qualifiers.add(qual) #add
+                else:
+                    l.qualifiers.remove(qual) #add
+        l.save()
+        #print repr(actions), repr(filters)
+    return {}
 
 
 @ajax(method='post')
 def save_columns(request, col_model, col_names, remap):
-  request.session['colModel'] = col_model
-  request.session['colNames'] = col_names
-  request.session['remap'] = remap
-  return {}
+    request.session['colModel'] = col_model
+    request.session['colNames'] = col_names
+    request.session['remap'] = remap
+    return {}
 
 
 @ajax(method='post')
 def add_vocabulary(request, name):
-  if not request.user.has_perm('dictionary.manage_vocabulary'):
-    raise AjaxError('access denied')
-  vocab = Vocabulary.objects.create(id=name)
-  vocab.managers.add(request.user) #add
-  return {}
+    if not request.user.has_perm('dictionary.manage_vocabulary'):
+        raise AjaxError('access denied')
+    vocab = Vocabulary.objects.create(id=name)
+    vocab.managers.add(request.user) #add
+    return {}
 
 # nieużywane
 @ajax(method='get')
 def vocabulary_permissions(request, vocab_id):
-  if not request.user.has_perm('dictionary.manage_vocabulary'):
-    raise AjaxError('access denied')
-  vocab = Vocabulary.objects.get(id=vocab_id)
-  return {
-    'managers': list(vocab.all_managers().values_list('pk', flat=True)),
-    'viewers': list(vocab.all_viewers().values_list('pk', flat=True)),
-    'editors': list(vocab.editors.values_list('pk', flat=True)),
-  }
+    if not request.user.has_perm('dictionary.manage_vocabulary'):
+        raise AjaxError('access denied')
+    vocab = Vocabulary.objects.get(id=vocab_id)
+    return {
+        'managers': list(vocab.all_managers().values_list('pk', flat=True)),
+        'viewers': list(vocab.all_viewers().values_list('pk', flat=True)),
+        'editors': list(vocab.editors.values_list('pk', flat=True)),
+    }
+
 
 @ajax(method='post')
 def set_vocabulary_permission(request, name, vocab_id, perm, on):
-  if not request.user.has_perm('dictionary.manage_vocabulary'):
-    raise AjaxError('access denied')
-  vocab = Vocabulary.objects.get(id=name)
-  user = User.objects.get(pk=vocab_id)
-  if perm == 'view':
-    related_manager = vocab.viewers
-  elif perm == 'change':
-    related_manager = vocab.editors
-  else: # type == 'manage'
-    related_manager = vocab.managers
-  if on:
-    related_manager.add(user) #add
-  else:
-    related_manager.remove(user) #add
-  return {}
\ No newline at end of file
+    if not request.user.has_perm('dictionary.manage_vocabulary'):
+        raise AjaxError('access denied')
+    vocab = Vocabulary.objects.get(id=name)
+    user = User.objects.get(pk=vocab_id)
+    if perm == 'view':
+        related_manager = vocab.viewers
+    elif perm == 'change':
+        related_manager = vocab.editors
+    else: # type == 'manage'
+        related_manager = vocab.managers
+    if on:
+        related_manager.add(user) #add
+    else:
+        related_manager.remove(user) #add
+    return {}
\ No newline at end of file
diff --git a/dictionary/ajax_pattern_view.py b/dictionary/ajax_pattern_view.py
index fc4739e..b058575 100644
--- a/dictionary/ajax_pattern_view.py
+++ b/dictionary/ajax_pattern_view.py
@@ -2,44 +2,44 @@
 
 from common.util import json_encode
 from dictionary.models import Pattern, Ending, BaseFormLabel, PatternType, \
-  editable_qualifiers, readonly_vocabularies
+    editable_qualifiers, readonly_vocabularies
 from dictionary.forms import PatternEditForm, PatternTypeForm, QualifierForm
 from dictionary.ajax_jqgrid import JqGridAjax, JqGridQuery
 from common.decorators import render, ajax, AjaxError, render_template
 
 
 class PatternGrid(JqGridAjax):
-  model = Pattern
-  search_field = 'name'
-
-  @staticmethod
-  def filter_special_case(filter, lookup, negated, queryset):
-    field = filter['field']
-    if field == 'part_of_speech':
-      field = 'type__lexical_class__symbol'
-    elif field == 'type':
-      field = 'type__symbol'
-    return False, field, queryset
-
-  @staticmethod
-  def apply_mask(patterns, mask, sort_rules):
-    return patterns.filter(name__istartswith=mask)
-
-  @staticmethod
-  def response_row(pattern):
-    return [
-      pattern.name,
-      pattern.type.symbol,
-      pattern.type.lexical_class.symbol,
-    ]
+    model = Pattern
+    search_field = 'name'
+
+    @staticmethod
+    def filter_special_case(filter, lookup, negated, queryset):
+        field = filter['field']
+        if field == 'part_of_speech':
+            field = 'type__lexical_class__symbol'
+        elif field == 'type':
+            field = 'type__symbol'
+        return False, field, queryset
+
+    @staticmethod
+    def apply_mask(patterns, mask, sort_rules):
+        return patterns.filter(name__istartswith=mask)
+
+    @staticmethod
+    def response_row(pattern):
+        return [
+            pattern.name,
+            pattern.type.symbol,
+            pattern.type.lexical_class.symbol,
+        ]
 
 
 # Zapytanie o indeks wiersza o pewnym id przy danym sortowaniu
 @ajax(method='get')
 def find_id(request, id, sort_rules, mask, filters=None):
-  query = JqGridQuery(
-    filters=filters, sort_rules=sort_rules, mask=mask, user=request.user)
-  return PatternGrid.find_id(id, query)
+    query = JqGridQuery(
+        filters=filters, sort_rules=sort_rules, mask=mask, user=request.user)
+    return PatternGrid.find_id(id, query)
 
 
 # Zapytanie o id oraz indeks wiersza przy danym sortowaniu
@@ -47,104 +47,109 @@ def find_id(request, id, sort_rules, mask, filters=None):
 # 'selected_id' < 0, jeśli takiego nie ma
 @ajax(method='get')
 def get_location(request, sort_rules, filters=None, mask=''):
-  query = JqGridQuery(
-    filters=filters, sort_rules=sort_rules, mask=mask, user=request.user)
-  return PatternGrid.get_location(query)
+    query = JqGridQuery(
+        filters=filters, sort_rules=sort_rules, mask=mask, user=request.user)
+    return PatternGrid.get_location(query)
 
 
 @ajax(method='get')
 def get_patterns(request, page, rows, sort_rules, filters=None, mask='',
                  target_page=0, totalrows=0):
-  request.session['pattern-sort_rules'] = json_encode(sort_rules)
-  request.session['pattern-filters'] = json_encode(filters)
-  page = target_page or page
-  limit = totalrows or rows
-  query = JqGridQuery(
-    filters=filters, sort_rules=sort_rules, mask=mask, user=request.user)
-  return PatternGrid.get_page(page, limit, query)
+    request.session['pattern-sort_rules'] = json_encode(sort_rules)
+    request.session['pattern-filters'] = json_encode(filters)
+    page = target_page or page
+    limit = totalrows or rows
+    query = JqGridQuery(
+        filters=filters, sort_rules=sort_rules, mask=mask, user=request.user)
+    return PatternGrid.get_page(page, limit, query)
 
 
 @render_template('pattern_edit_form.html')
 @ajax(method='get', template='pattern_edit_form.html')
 def pattern_edit_form(request, id):
-  if not request.user.has_perm('dictionary.view_pattern'):
-    raise AjaxError('access denied')
-  to_return = {}
-  p = Pattern.objects.get(pk=id)
-  editable = request.user.has_perm('dictionary.change_pattern')
-  to_return['form'] = PatternEditForm(instance=p, editable=editable)
-  to_return['type_form'] = PatternTypeForm(instance=p.type, editable=editable)
-  to_return['id'] = p.pk
-  to_return['editable'] = editable
-  bfls = p.type.base_form_labels()
-  ending_groups = dict((bfl, []) for bfl in bfls)
-  endings = p.endings.order_by('base_form_label', 'index')
-  for e in endings:
-    ro_qualifers = e.qualifiers.filter(
-      vocabulary__in=readonly_vocabularies(request.user))
-    q_form = QualifierForm(
-      qualified=e, user=request.user, editable=editable, prefix='end%s' % e.pk)
-    ending_groups[e.base_form_label].append((e, ro_qualifers, q_form))
-  to_return['ending_groups'] = ending_groups
-  return to_return
+    if not request.user.has_perm('dictionary.view_pattern'):
+        raise AjaxError('access denied')
+    to_return = {}
+    p = Pattern.objects.get(pk=id)
+    editable = request.user.has_perm('dictionary.change_pattern')
+    to_return['pattern'] = p
+    to_return['form'] = PatternEditForm(instance=p, editable=editable)
+    to_return['type_form'] = PatternTypeForm(instance=p.type, editable=editable)
+    to_return['editable'] = editable
+    bfls = p.type.base_form_labels()
+    ending_groups = dict((bfl, []) for bfl in bfls)
+    endings = p.endings.order_by('base_form_label', 'index')
+    for e in endings:
+        ro_qualifers = e.qualifiers.filter(
+            vocabulary__in=readonly_vocabularies(request.user))
+        q_form = QualifierForm(
+            qualified=e, user=request.user, editable=editable,
+            prefix='end%s' % e.pk)
+        ending_groups[e.base_form_label].append((e, ro_qualifers, q_form))
+    to_return['ending_groups'] = ending_groups
+    return to_return
 
 
 # mogłoby iść przez js_vars...
 @render('ending_row.html')
 @ajax(method='get', encode_result=False)
-def new_ending_row(request):
-  ending = {'string': '', 'id': 'add-NUM'}
-  form = QualifierForm(user=request.user, prefix='add-NUM')
-  return {'ending': ending, 'editable': True, 'form': form}
+def new_ending_row(request, pattern_id):
+    p = Pattern.objects.get(id=pattern_id)
+    ending = {'string': '', 'id': 'add-NUM'}
+    form = QualifierForm(user=request.user, prefix='add-NUM')
+    return {'ending': ending, 'editable': True, 'form': form, 'pattern': p}
 
 
 @ajax(method='post')
 def update_pattern(request, form_data):
-  if not request.user.has_perm('dictionary.change_pattern'):
-    raise AjaxError('access denied')
-  form_dict = dict((x['name'], x['value']) for x in form_data)
-  p = Pattern.objects.get(pk=form_dict['id'])
-  form = PatternEditForm(data=form_dict, instance=p)
-  type_form = PatternTypeForm(data=form_dict)
-  if type_form.is_valid():
-    type_qs = PatternType.objects.filter(
-      symbol=type_form.cleaned_data['symbol'],
-      lexical_class=type_form.cleaned_data['lexical_class'])
-  else:
-    raise AjaxError('invalid data')
-  if form.is_valid() and len(type_qs) == 1:
-    form.save()
-    p.type = type_qs[0]
-    p.save()
-    for ending_pk in form_dict['deleted']:
-      Ending.objects.get(pk=int(ending_pk)).delete()
-    qualifiers = editable_qualifiers(request.user)
-    for bfl_endings in form_dict['ending_list']:
-      endings_data = bfl_endings['endings']
-      bfl = BaseFormLabel.objects.get(symbol=bfl_endings['base_form_label'])
-      endings = []
-      for index, ending_data in zip(range(1, len(endings_data) + 1), endings_data):
-        quals = set(int(q) for q in ending_data['qualifiers'])
-        if ending_data['id'] == 'add':
-          ending = Ending.objects.create(
-            pattern=p, base_form_label=bfl, string=ending_data['string'],
-            index=index)
-        else:
-          ending = Ending.objects.get(pk=int(ending_data['id']))
-          ending.index = index
-          ending.string = ending_data['string']
-          ending.save()
-        for qualifier in qualifiers:
-          qualifier.set_for(ending, qualifier.pk in quals)
-        endings.append(ending)
-  else:
-    raise AjaxError('invalid data')
-  return {}
+    if not request.user.has_perm('dictionary.change_pattern'):
+        raise AjaxError('access denied')
+    form_dict = dict((x['name'], x['value']) for x in form_data)
+    p = Pattern.objects.get(pk=form_dict['id'])
+    form = PatternEditForm(data=form_dict, instance=p)
+    type_form = PatternTypeForm(data=form_dict)
+    if type_form.is_valid():
+        type_qs = PatternType.objects.filter(
+            symbol=type_form.cleaned_data['symbol'],
+            lexical_class=type_form.cleaned_data['lexical_class'])
+    else:
+        raise AjaxError('invalid data')
+    if form.is_valid() and len(type_qs) == 1:
+        form.save()
+        p.type = type_qs[0]
+        p.save()
+        for ending_pk in form_dict['deleted']:
+            Ending.objects.get(pk=int(ending_pk)).delete()
+        qualifiers = editable_qualifiers(request.user)
+        for bfl_endings in form_dict['ending_list']:
+            endings_data = bfl_endings['endings']
+            bfl = BaseFormLabel.objects.get(
+                symbol=bfl_endings['base_form_label'])
+            endings = []
+            for index, ending_data in zip(range(1, len(endings_data) + 1),
+                                          endings_data):
+                quals = set(int(q) for q in ending_data['qualifiers'])
+                if ending_data['id'] == 'add':
+                    ending = Ending.objects.create(
+                        pattern=p, base_form_label=bfl,
+                        string=ending_data['string'],
+                        index=index)
+                else:
+                    ending = Ending.objects.get(pk=int(ending_data['id']))
+                    ending.index = index
+                    ending.string = ending_data['string']
+                    ending.save()
+                for qualifier in qualifiers:
+                    qualifier.set_for(ending, qualifier.pk in quals)
+                endings.append(ending)
+    else:
+        raise AjaxError('invalid data')
+    return {}
 
 
 @ajax(method='post')
 def save_columns(request, col_model, col_names, remap):
-  request.session['pattern-colModel'] = col_model
-  request.session['pattern-colNames'] = col_names
-  request.session['pattern-remap'] = remap
-  return {}
+    request.session['pattern-colModel'] = col_model
+    request.session['pattern-colNames'] = col_names
+    request.session['pattern-remap'] = remap
+    return {}
diff --git a/dictionary/ajax_prompter.py b/dictionary/ajax_prompter.py
index 3cba2a5..4151407 100644
--- a/dictionary/ajax_prompter.py
+++ b/dictionary/ajax_prompter.py
@@ -3,82 +3,84 @@
 from common.decorators import render, ajax, AjaxError
 from common.util import suffix, cut_end
 from dictionary.models import Lexeme, LexemeInflectionPattern, Pattern, \
-  InflectionCharacteristic, prepare_table, visible_vocabularies, get_root, \
-  ClassificationValue, Classification, filter_visible_lips
+    InflectionCharacteristic, prepare_table, visible_vocabularies, get_root, \
+    ClassificationValue, Classification, filter_visible_lips
 from dictionary.pattern_blacklist import blacklist
 
 commonness = Classification.objects.get(name=u'pospolitość')
 
 LIP_ROWS = 10
 
+
 def make_list(user, entry, pos, ic, cvs, bl_check):
-  lips = LexemeInflectionPattern.objects.distinct()
-  lips = filter_visible_lips(lips, user)
-  lips = lips.filter(
-    lexeme__part_of_speech__symbol=pos).exclude(lexeme__status='cand')
-  if ic:
-    lips = lips.filter(inflection_characteristic=ic)
-  if cvs:
-    lips = lips.filter(lexeme__classificationvalue__in=cvs)
-  else:
-    lips = lips.exclude(lexeme__classificationvalue=None)
-  lips = lips.order_by('lexeme__entry')
-  feature_sets = set()
-  bad_inflections = set()
-  chosen_lips = []
-  for suf_len in xrange(len(entry), 0, -1):
-    suf = suffix(entry, suf_len)
-    suf_lips = lips.filter(lexeme__entry__endswith=suf)
-    if suf_len < len(entry):
-      suf1 = suffix(entry, suf_len + 1)
-      suf_lips = suf_lips.exclude(lexeme__entry__endswith=suf1)
-    for p0, ic0 in bad_inflections:
-      suf_lips.exclude(pattern=p0, inflection_characteristic=ic0)
-    for p0, ic0 in feature_sets:
-      suf_lips = suf_lips.exclude(
-        pattern=p0, inflection_characteristic=ic0)
-    for lip in suf_lips:
-      #lip = suf_lips[0]
-      p = lip.pattern
-      #suf_lips = suf_lips.exclude(pattern=p)
-      if p.name in blacklist and bl_check: continue
-      if ic:
-        l_ic = ic
-      else:
-        l_ic = lip.inflection_characteristic
-      if (p, l_ic) in bad_inflections: continue
-      if (p, l_ic) in feature_sets: continue
-      if cvs:
-        l_cvs = lip.lexeme.classification_values(commonness) & cvs
-      else:
-        l_cvs = lip.lexeme.classification_values(commonness)
-      if get_root(entry, pos, p, l_ic) is not None:
-        l_root = lip.lexeme.get_root(p, l_ic)
-        l_end = lip.lexeme.entry[len(l_root):]
-        l_entry = u'%s·%s' % (l_root, l_end)
-        if len(l_end) < len(suf):
-          suf = suffix(l_entry, suf_len + 1)
-        chosen_lips.append((lip, l_cvs, cut_end(l_entry, suf), suf))
-        feature_sets.add((p, l_ic))
+    lips = LexemeInflectionPattern.objects.distinct()
+    lips = filter_visible_lips(lips, user)
+    lips = lips.filter(
+        lexeme__part_of_speech__symbol=pos).exclude(lexeme__status='cand')
+    if ic:
+        lips = lips.filter(inflection_characteristic=ic)
+    if cvs:
+        lips = lips.filter(lexeme__classificationvalue__in=cvs)
+    else:
+        lips = lips.exclude(lexeme__classificationvalue=None)
+    lips = lips.order_by('lexeme__entry')
+    feature_sets = set()
+    bad_inflections = set()
+    chosen_lips = []
+    for suf_len in xrange(len(entry), 0, -1):
+        suf = suffix(entry, suf_len)
+        suf_lips = lips.filter(lexeme__entry__endswith=suf)
+        if suf_len < len(entry):
+            suf1 = suffix(entry, suf_len + 1)
+            suf_lips = suf_lips.exclude(lexeme__entry__endswith=suf1)
+        for p0, ic0 in bad_inflections:
+            suf_lips.exclude(pattern=p0, inflection_characteristic=ic0)
+        for p0, ic0 in feature_sets:
+            suf_lips = suf_lips.exclude(
+                pattern=p0, inflection_characteristic=ic0)
+        for lip in suf_lips:
+            #lip = suf_lips[0]
+            p = lip.pattern
+            #suf_lips = suf_lips.exclude(pattern=p)
+            if p.name in blacklist and bl_check: continue
+            if ic:
+                l_ic = ic
+            else:
+                l_ic = lip.inflection_characteristic
+            if (p, l_ic) in bad_inflections: continue
+            if (p, l_ic) in feature_sets: continue
+            if cvs:
+                l_cvs = lip.lexeme.classification_values(commonness) & cvs
+            else:
+                l_cvs = lip.lexeme.classification_values(commonness)
+            if get_root(entry, pos, p, l_ic) is not None:
+                l_root = lip.lexeme.get_root(p, l_ic)
+                l_end = lip.lexeme.entry[len(l_root):]
+                l_entry = u'%s·%s' % (l_root, l_end)
+                if len(l_end) < len(suf):
+                    suf = suffix(l_entry, suf_len + 1)
+                chosen_lips.append((lip, l_cvs, cut_end(l_entry, suf), suf))
+                feature_sets.add((p, l_ic))
+                if len(chosen_lips) == LIP_ROWS:
+                    break
+            else:
+                bad_inflections.add((p, l_ic))
         if len(chosen_lips) == LIP_ROWS:
-          break
-      else:
-        bad_inflections.add((p, l_ic))
-    if len(chosen_lips) == LIP_ROWS:
-      break
-  return chosen_lips
+            break
+    return chosen_lips
+
 
 @ajax(method='get', template='prompter_list.html')
 def prompter_list(request, entry, pos_id, ic_id, commonness_ids,
                   ic_check, cv_check, bl_check):
-  if ic_check:
-    ic = InflectionCharacteristic.objects.get(pk=ic_id)
-  else:
-    ic = None
-  if cv_check: # and commonness not in ('undefined', 'None'):
-    cvs = ClassificationValue.objects.filter(pk__in=commonness_ids)
-  else:
-    cvs = None
-  lips = make_list(request.user, entry, pos_id, ic, cvs, bl_check)
-  # zakładamy, że symbol == pk
-  return {'lips': lips}
+    if ic_check:
+        ic = InflectionCharacteristic.objects.get(pk=ic_id)
+    else:
+        ic = None
+    if cv_check: # and commonness not in ('undefined', 'None'):
+        cvs = ClassificationValue.objects.filter(pk__in=commonness_ids)
+    else:
+        cvs = None
+    lips = make_list(request.user, entry, pos_id, ic, cvs, bl_check)
+    # zakładamy, że symbol == pk
+    return {'lips': lips}
diff --git a/dictionary/export.py b/dictionary/export.py
index 3f82819..a496f5f 100644
--- a/dictionary/export.py
+++ b/dictionary/export.py
@@ -7,32 +7,33 @@ from common.util import debug, flatten
 from dictionary.models import CrossReferenceType, ClassificationValue, LexemeAttributeValue
 
 ADJPREDYKATYWNE = [
-  u'ciekaw',
-  u'godzien',
-  u'gotów',
-  u'łaskaw',
-  u'świadom',
-  u'winien',
-  u'zdrów',
-# wątpliwe:
-  u'dłużen',
-  u'miłościw',
-  u'praw',
-  u'wesół',
-  u'żyw',
+    u'ciekaw',
+    u'godzien',
+    u'gotów',
+    u'łaskaw',
+    u'świadom',
+    u'winien',
+    u'zdrów',
+    # wątpliwe:
+    u'dłużen',
+    u'miłościw',
+    u'praw',
+    u'wesół',
+    u'żyw',
 ]
 
 REFL_TRANSLATION = {
-  u'—': 'nonrefl',
-  u'się': 'refl',
-  u'sobie': 'refl',
-  u'się/sobie': 'refl',
-  u'(się)': 'refl.nonrefl',
-  u'(sobie)': 'refl.nonrefl',
+    u'—': 'nonrefl',
+    u'się': 'refl',
+    u'sobie': 'refl',
+    u'się/sobie': 'refl',
+    u'(się)': 'refl.nonrefl',
+    u'(sobie)': 'refl.nonrefl',
 }
 
+
 def qualifier_clause(q_id):
-  return '''not exists (
+    return '''not exists (
     select * from kwalifikatory_leksemow where lexeme_id = l.id and
       qualifier_id = %(q)d) and not exists (
     select * from kwalifikatory_odmieniasiow where qualifier_id = %(q)d and
@@ -40,8 +41,9 @@ def qualifier_clause(q_id):
     select * from kwalifikatory_zakonczen where qualifier_id = %(q)d and
       ending_id = z.id) and ''' % {'q': q_id}
 
+
 def magic_qualifier_clause():
-  return '''and not (tag like %s and exists (
+    return '''and not (tag like %s and exists (
     select kw.id
     from kwalifikatory kw
       join kwalifikatory_leksemow kwl on kw.id = kwl.qualifier_id
@@ -49,45 +51,45 @@ def magic_qualifier_clause():
 
 
 def export_lexemes(data=None, output_file=None):
-  if not data:
-    data = {
-      'vocabs': ['PoliMorf'],
-      'antivocabs': [],
-      'variant': 'Morfeusz',
-      'excluding_qualifiers': [],
-      'magic_qualifiers': [],
-      'refl': False,
-      'commonness': False,
-    }
-  if output_file is None:
-    output_file = sys.stdout
-  vocabs_placeholders = ', '.join('%s' for v in data['vocabs'])
+    if not data:
+        data = {
+            'vocabs': ['PoliMorf'],
+            'antivocabs': [],
+            'variant': 'Morfeusz',
+            'excluding_qualifiers': [],
+            'magic_qualifiers': [],
+            'refl': False,
+            'commonness': False,
+        }
+    if output_file is None:
+        output_file = sys.stdout
+    vocabs_placeholders = ', '.join('%s' for v in data['vocabs'])
 
-  if data['antivocabs']:
-    antivocabs_placeholders = ', '.join('%s' for v in data['antivocabs'])
-    antivocabs_clause = '''not exists (
+    if data['antivocabs']:
+        antivocabs_placeholders = ', '.join('%s' for v in data['antivocabs'])
+        antivocabs_clause = '''not exists (
       select * from leksemy_w_slownikach ls2 where ls2.l_id = l.id
       and ls2.slownik in (%s)) and''' % antivocabs_placeholders
-  else:
-    antivocabs_clause = ''
+    else:
+        antivocabs_clause = ''
 
-  qualifier_clauses = ''.join(
-    qualifier_clause(q_id) for q_id in data['excluding_qualifiers'])
-  magic_qualifier_clauses = ''.join(
-    magic_qualifier_clause() for pattern, q_id in data['magic_qualifiers'])
+    qualifier_clauses = ''.join(
+        qualifier_clause(q_id) for q_id in data['excluding_qualifiers'])
+    magic_qualifier_clauses = ''.join(
+        magic_qualifier_clause() for pattern, q_id in data['magic_qualifiers'])
 
-  crtypes = ['comadv', 'comadj', 'gerver', 'pactver', 'ppasver']
-  crtype_ids = CrossReferenceType.objects.filter(
-    symbol__in=crtypes).values_list('pk', flat=True)
+    crtypes = ['comadv', 'comadj', 'gerver', 'pactver', 'ppasver']
+    crtype_ids = CrossReferenceType.objects.filter(
+        symbol__in=crtypes).values_list('pk', flat=True)
 
-  cv_ids = ClassificationValue.objects.filter(
-    classification__name=u'pospolitość').values_list('pk', flat=True)
+    cv_ids = ClassificationValue.objects.filter(
+        classification__name=u'pospolitość').values_list('pk', flat=True)
 
-  refls = dict(LexemeAttributeValue.objects.filter(
-    attribute__name=u'zwrotność').values_list('pk', 'value'))
+    refls = dict(LexemeAttributeValue.objects.filter(
+        attribute__name=u'zwrotność').values_list('pk', 'value'))
 
-  cursor = connection.cursor()
-  query = """
+    cursor = connection.cursor()
+    query = """
     select distinct haslo, prefiks||rdzen||zak||sufiks, l.pos, ch.charfl, tag,
       l.id as leksem_id, refl.attribute_value_id %(clas_field)s
     from leksemy l
@@ -133,46 +135,46 @@ def export_lexemes(data=None, output_file=None):
       --and g.haslo < 'b'
     order by haslo, leksem_id
     """ % {
-      'vocabs': vocabs_placeholders,
-      'antivocabs': antivocabs_clause,
-      'x_qual': qualifier_clauses,
-      'magic': magic_qualifier_clauses,
-      'crtype_ids': ', '.join(str(pk) for pk in crtype_ids), # brzydko, oj tam
-      'clas_field': ', classification_value_id' if data['commonness'] else '',
-      'clas_join':
-        'left outer join dictionary_lexemecv wkl '
-        'on (wkl.lexeme_id=l.id and wkl.classification_value_id in (%s))'
-        % ', '.join(str(pk) for pk in cv_ids) if data['commonness'] else '',
-      'refl':
-        'refl.attribute_value_id in (%s)'
-        % ', '.join(str(pk) for pk in refls),
+        'vocabs': vocabs_placeholders,
+        'antivocabs': antivocabs_clause,
+        'x_qual': qualifier_clauses,
+        'magic': magic_qualifier_clauses,
+        'crtype_ids': ', '.join(str(pk) for pk in crtype_ids), # brzydko, oj tam
+        'clas_field': ', classification_value_id' if data['commonness'] else '',
+        'clas_join':
+            'left outer join dictionary_lexemecv wkl '
+            'on (wkl.lexeme_id=l.id and wkl.classification_value_id in (%s))'
+            % ', '.join(str(pk) for pk in cv_ids) if data['commonness'] else '',
+        'refl':
+            'refl.attribute_value_id in (%s)'
+            % ', '.join(str(pk) for pk in refls),
     }
-  params_part = (list(data['vocabs']) + list(data['antivocabs']) +
-                 [data['variant']])
-  params = params_part + flatten(data['magic_qualifiers']) + params_part
-  cursor.execute(query, params)
-  refl = data['refl']
-  cv_table = dict(ClassificationValue.objects.values_list('id', 'label'))
-  for row in cursor:
-    if data['commonness']:
-      entry, form, pos, _ic, tag, _id, refl_id, cv_id = row
-    else:
-      entry, form, pos, _ic, tag, _id, refl_id = row
-    form = form.lstrip('+') # odmienne postfiksy
-    if tag == 'adja':
-      form = form.rstrip('+')
-    if tag == 'adjc':
-      if form not in ADJPREDYKATYWNE:
-        tag = "adj:sg:nom:m1.m2.m3:pos|adj:sg:acc:m3:pos"
-    if refl and pos in ('v', 'pact', 'ger'):
-      if refl_id in refls:
-        tag += ':' + REFL_TRANSLATION[refls[refl_id]]
-      else:
-        debug(entry, u'Nieznana zwrotność: %s' % refl_id)
-    if data['commonness']:
-      cv = cv_table[cv_id] if cv_id else ''
-      output_file.write((u'%s\t%s\t%s\t%s\n' %
-                         (form, entry, tag, cv)).encode('utf-8'))
-    else:
-      output_file.write((u'%s\t%s\t%s\n' %
-                         (form, entry, tag)).encode('utf-8'))
+    params_part = (list(data['vocabs']) + list(data['antivocabs']) +
+                   [data['variant']])
+    params = params_part + flatten(data['magic_qualifiers']) + params_part
+    cursor.execute(query, params)
+    refl = data['refl']
+    cv_table = dict(ClassificationValue.objects.values_list('id', 'label'))
+    for row in cursor:
+        if data['commonness']:
+            entry, form, pos, _ic, tag, _id, refl_id, cv_id = row
+        else:
+            entry, form, pos, _ic, tag, _id, refl_id = row
+        form = form.lstrip('+') # odmienne postfiksy
+        if tag == 'adja':
+            form = form.rstrip('+')
+        if tag == 'adjc':
+            if form not in ADJPREDYKATYWNE:
+                tag = "adj:sg:nom:m1.m2.m3:pos|adj:sg:acc:m3:pos"
+        if refl and pos in ('v', 'pact', 'ger'):
+            if refl_id in refls:
+                tag += ':' + REFL_TRANSLATION[refls[refl_id]]
+            else:
+                debug(entry, u'Nieznana zwrotność: %s' % refl_id)
+        if data['commonness']:
+            cv = cv_table[cv_id] if cv_id else ''
+            output_file.write((u'%s\t%s\t%s\t%s\n' %
+                               (form, entry, tag, cv)).encode('utf-8'))
+        else:
+            output_file.write((u'%s\t%s\t%s\n' %
+                               (form, entry, tag)).encode('utf-8'))
diff --git a/dictionary/forms.py b/dictionary/forms.py
index 0ee8661..393171d 100644
--- a/dictionary/forms.py
+++ b/dictionary/forms.py
@@ -3,512 +3,548 @@
 from django.forms import *
 from common.forms import hidden_id
 from dictionary.models import Lexeme, LexemeInflectionPattern, Ending, \
-  InflectionCharacteristic, Pattern, PatternType, Classification, \
-  ClassificationValue, Vocabulary, CrossReference, Qualifier, \
-  QualifierExclusionClass, Variant, editable_vocabularies, editable_qualifiers, LexemeAttribute, LexemeAttributeValue
+    InflectionCharacteristic, Pattern, PatternType, Classification, \
+    ClassificationValue, Vocabulary, CrossReference, Qualifier, \
+    QualifierExclusionClass, Variant, editable_vocabularies, editable_qualifiers, LexemeAttribute, LexemeAttributeValue
 
 
 def disable_field(field):
-  if type(field.widget) in (Textarea, TextInput):
-    field.widget.attrs['readonly'] = 'readonly'
-  else:
-    field.widget.attrs['disabled'] = 'disabled'
+    if type(field.widget) in (Textarea, TextInput):
+        field.widget.attrs['readonly'] = 'readonly'
+    else:
+        field.widget.attrs['disabled'] = 'disabled'
 
 # ze StackOverflow, http://stackoverflow.com/questions/3737116/
 class QualifiersField(ModelMultipleChoiceField):
-  def __init__(self, **kwargs):
-    super(QualifiersField, self).__init__(Qualifier.objects.none(), **kwargs)
-    self.to_field_name = None #?
-
-  def set_qualifiers(self, user, qualified=None, lexeme=None):
-    if qualified and qualified.id:
-      if lexeme:
-        vocabularies = lexeme.editable_vocabularies(user)
-      else:
-        vocabularies = qualified.editable_vocabularies(user)
-      qualifiers = Qualifier.objects.filter(vocabulary__in=vocabularies)
-    else:
-      qualifiers = editable_qualifiers(user)
-    if not qualifiers:
-      disable_field(self)
-      return
-    self.queryset = queryset = qualifiers.order_by('vocabulary', 'label')
-    if qualified and qualified.pk:
-      initial_qualifiers = qualified.qualifiers.all() & qualifiers
-      self.initial = initial_qualifiers
-
-    queryset = queryset.select_related()
-    vocabulary = None
-    self.choices = []
-    q_list = []
-    for qualifier in queryset:
-      if not vocabulary:
-        vocabulary = qualifier.vocabulary
-      if vocabulary != qualifier.vocabulary:
-        self.choices.append((vocabulary.id, q_list))
-        vocabulary = qualifier.vocabulary
+    def __init__(self, **kwargs):
+        super(QualifiersField, self).__init__(Qualifier.objects.none(),
+                                              **kwargs)
+        self.to_field_name = None #?
+
+    def set_qualifiers(self, user, qualified=None, lexeme=None):
+        if qualified and qualified.id:
+            if lexeme:
+                vocabularies = lexeme.editable_vocabularies(user)
+            else:
+                vocabularies = qualified.editable_vocabularies(user)
+            qualifiers = Qualifier.objects.filter(vocabulary__in=vocabularies)
+        else:
+            qualifiers = editable_qualifiers(user)
+        if not qualifiers:
+            disable_field(self)
+            return
+        self.queryset = queryset = qualifiers.order_by('vocabulary', 'label')
+        if qualified and qualified.pk:
+            initial_qualifiers = qualified.qualifiers.all() & qualifiers
+            self.initial = initial_qualifiers
+
+        queryset = queryset.select_related()
+        vocabulary = None
+        self.choices = []
         q_list = []
-      q_list.append((qualifier.pk, qualifier.label))
-    self.choices.append((vocabulary.id, q_list))
+        for qualifier in queryset:
+            if not vocabulary:
+                vocabulary = qualifier.vocabulary
+            if vocabulary != qualifier.vocabulary:
+                self.choices.append((vocabulary.id, q_list))
+                vocabulary = qualifier.vocabulary
+                q_list = []
+            q_list.append((qualifier.pk, qualifier.label))
+        self.choices.append((vocabulary.id, q_list))
+
 
 class QualifierField(ModelChoiceField):
-  def __init__(self, **kwargs):
-    qualifiers = Qualifier.objects.all()
-    super(QualifierField, self).__init__(qualifiers, **kwargs)
-    self.set_qualifiers(qualifiers)
-
-  def set_qualifiers(self, qualifiers):
-    if not qualifiers:
-      disable_field(self)
-      return
-    qualifiers = qualifiers.select_related().order_by('vocabulary', 'label')
-    vocabulary = None
-    self.choices = []
-    q_list = []
-    for qualifier in qualifiers:
-      if not vocabulary:
-        vocabulary = qualifier.vocabulary
-      if vocabulary != qualifier.vocabulary:
-        self.choices.append((vocabulary.id, q_list))
-        vocabulary = qualifier.vocabulary
+    def __init__(self, **kwargs):
+        qualifiers = Qualifier.objects.all()
+        super(QualifierField, self).__init__(qualifiers, **kwargs)
+        self.set_qualifiers(qualifiers)
+
+    def set_qualifiers(self, qualifiers):
+        if not qualifiers:
+            disable_field(self)
+            return
+        qualifiers = qualifiers.select_related().order_by('vocabulary', 'label')
+        vocabulary = None
+        self.choices = []
         q_list = []
-      q_list.append((qualifier.pk, qualifier.label))
-    self.choices.append((vocabulary.id, q_list))
+        for qualifier in qualifiers:
+            if not vocabulary:
+                vocabulary = qualifier.vocabulary
+            if vocabulary != qualifier.vocabulary:
+                self.choices.append((vocabulary.id, q_list))
+                vocabulary = qualifier.vocabulary
+                q_list = []
+            q_list.append((qualifier.pk, qualifier.label))
+        self.choices.append((vocabulary.id, q_list))
+
 
 class LexemeEditForm(ModelForm):
-  vocabularies = ModelMultipleChoiceField(
-    queryset=Vocabulary.objects.none(), required=False)
-  qualifiers = QualifiersField(required=False)
-  new_owner = ModelChoiceField(
-    queryset=Vocabulary.objects.none(), required=False)
-
-  def __init__(self,  user, editable=True, **kwargs):
-    super(LexemeEditForm, self).__init__(**kwargs)
-    editable_vocabs = editable_vocabularies(user)
-    instance = getattr(self, 'instance', None)
-    other_editable_vocabs = editable_vocabs.exclude(pk=instance.owner_vocabulary.pk)
-    self.fields['entry'].required = True
-    self.fields['new_owner'].queryset = editable_vocabs
-    self.fields['vocabularies'].queryset = other_editable_vocabs
-    self.fields['vocabularies'].initial = instance.visible_vocabularies(user)
-    owner_choices = editable_vocabs.values_list('pk', 'id')
-    self.fields['new_owner'].choices = owner_choices
-    if instance and instance.id:
-      self.fields['new_owner'].initial = instance.owner_vocabulary
-    if other_editable_vocabs.count() == 0:
-      disable_field(self.fields['vocabularies'])
-    self.fields['qualifiers'].set_qualifiers(user, instance)
-    if not editable:
-      if instance and instance.id:
-        for name, field in self.fields.iteritems():
-          if name not in ('qualifiers', 'vocabularies'):
-            disable_field(field)
-
-  def clean_comment(self):
-    data = self.cleaned_data['comment']
-    return data.replace('\r', '')
-
-  class Meta:
-    model = Lexeme
-    fields = (
-      'part_of_speech',
-      'entry',
-      'pronunciation',
-      'valence',
-      'status',
-      'gloss',
-      'note',
-      'comment',
-    )
-    widgets = {
-      'comment': Textarea(attrs={'cols': 40, 'rows': 5}),
-      'gloss': TextInput(attrs={'size': 40}),
-      'note': TextInput(attrs={'size': 40}),
-      'pronunciation': TextInput(attrs={'size': 40}),
-      'valence': TextInput(attrs={'size': 40}),
-    }
+    vocabularies = ModelMultipleChoiceField(
+        queryset=Vocabulary.objects.none(), required=False)
+    qualifiers = QualifiersField(required=False)
+    new_owner = ModelChoiceField(
+        queryset=Vocabulary.objects.none(), required=False)
+
+    def __init__(self, user, editable=True, **kwargs):
+        super(LexemeEditForm, self).__init__(**kwargs)
+        editable_vocabs = editable_vocabularies(user)
+        instance = getattr(self, 'instance', None)
+        other_editable_vocabs = editable_vocabs.exclude(
+            pk=instance.owner_vocabulary.pk)
+        self.fields['entry'].required = True
+        self.fields['new_owner'].queryset = editable_vocabs
+        self.fields['vocabularies'].queryset = other_editable_vocabs
+        self.fields['vocabularies'].initial = instance.visible_vocabularies(
+            user)
+        owner_choices = editable_vocabs.values_list('pk', 'id')
+        self.fields['new_owner'].choices = owner_choices
+        if instance and instance.id:
+            self.fields['new_owner'].initial = instance.owner_vocabulary
+        if other_editable_vocabs.count() == 0:
+            disable_field(self.fields['vocabularies'])
+        self.fields['qualifiers'].set_qualifiers(user, instance)
+        if not editable:
+            if instance and instance.id:
+                for name, field in self.fields.iteritems():
+                    if name not in ('qualifiers', 'vocabularies'):
+                        disable_field(field)
+
+    def clean_comment(self):
+        data = self.cleaned_data['comment']
+        return data.replace('\r', '')
+
+    class Meta:
+        model = Lexeme
+        fields = (
+            'part_of_speech',
+            'entry',
+            'pronunciation',
+            'valence',
+            'status',
+            'gloss',
+            'note',
+            'comment',
+        )
+        widgets = {
+            'comment': Textarea(attrs={'cols': 40, 'rows': 5}),
+            'gloss': TextInput(attrs={'size': 40}),
+            'note': TextInput(attrs={'size': 40}),
+            'pronunciation': TextInput(attrs={'size': 40}),
+            'valence': TextInput(attrs={'size': 40}),
+        }
 
 # abstract
 class LexemeAttributeForm(Form):
+    def __init__(self, attribute, **kwargs):
+        super(LexemeAttributeForm, self).__init__(**kwargs)
+        self.fields['value'].label = attribute.name
+        self.fields['value'].required = attribute.required
 
-  def __init__(self, attribute, **kwargs):
-    super(LexemeAttributeForm, self).__init__(**kwargs)
-    self.fields['value'].label = attribute.name
-    self.fields['value'].required = attribute.required
 
 class LexemeOpenAttributeForm(LexemeAttributeForm):
-  value = CharField(widget=TextInput(attrs={'class': 'pattern', 'size': '10'}))
+    value = CharField(
+        widget=TextInput(attrs={'class': 'pattern', 'size': '10'}))
+
+    def __init__(self, attribute, initial_value=None, **kwargs):
+        assert not attribute.closed and not attribute.multiple
+        super(LexemeOpenAttributeForm, self).__init__(attribute, **kwargs)
+        if initial_value is not None:
+            self.fields['value'].initial = initial_value.value
 
-  def __init__(self, attribute, initial_value=None, **kwargs):
-    assert not attribute.closed and not attribute.multiple
-    super(LexemeOpenAttributeForm, self).__init__(attribute, **kwargs)
-    if initial_value is not None:
-      self.fields['value'].initial = initial_value.value
 
 class LexemeClosedAttributeForm(LexemeAttributeForm):
-  value = ModelChoiceField(queryset=LexemeAttributeValue.objects.none())
+    value = ModelChoiceField(queryset=LexemeAttributeValue.objects.none())
+
+    def __init__(self, attribute, initial_value=None, **kwargs):
+        assert attribute.closed and not attribute.multiple
+        super(LexemeClosedAttributeForm, self).__init__(attribute, **kwargs)
+        self.fields['value'].queryset = attribute.values
+        self.fields['value'].initial = initial_value
 
-  def __init__(self, attribute, initial_value=None, **kwargs):
-    assert attribute.closed and not attribute.multiple
-    super(LexemeClosedAttributeForm, self).__init__(attribute, **kwargs)
-    self.fields['value'].queryset = attribute.values
-    self.fields['value'].initial = initial_value
 
 class LexemeMultipleAttributeForm(LexemeAttributeForm):
-  value = ModelMultipleChoiceField(queryset=LexemeAttributeValue.objects.none())
+    value = ModelMultipleChoiceField(
+        queryset=LexemeAttributeValue.objects.none())
+
+    def __init__(self, attribute, initial_value=None, **kwargs):
+        assert attribute.closed and attribute.multiple
+        super(LexemeMultipleAttributeForm, self).__init__(attribute, **kwargs)
+        self.fields['value'].queryset = attribute.values
+        self.fields['value'].initial = initial_value
 
-  def __init__(self, attribute, initial_value=None, **kwargs):
-    assert attribute.closed and attribute.multiple
-    super(LexemeMultipleAttributeForm, self).__init__(attribute, **kwargs)
-    self.fields['value'].queryset = attribute.values
-    self.fields['value'].initial = initial_value
 
 class LIPEditForm(ModelForm):
-  pattern_name = CharField(widget=TextInput(
-    attrs={'class': 'pattern', 'size': '10'}), label=u'Wzór')
-  qualifiers = QualifiersField(
-    required=False, label=u'Kwal.',
-    widget = SelectMultiple(attrs={'class':'lip-qualifiers'}))
-
-  def __init__(self, part_of_speech, lexeme, user, editable=True, index=None,
-               **kwargs):
-    super(LIPEditForm, self).__init__(**kwargs)
-    ic_choices = InflectionCharacteristic.objects.filter(
-      part_of_speech=part_of_speech).values_list('pk', 'symbol')
-    self.fields['inflection_characteristic'].choices = ic_choices
-    instance = getattr(self, 'instance', None)
-    self.fields['qualifiers'].set_qualifiers(user, instance, lexeme)
-    if instance and instance.id:
-      self.fields['pattern_name'].initial = instance.pattern.name
-      if not editable:
-        for name, field in self.fields.iteritems():
-          if name != 'qualifiers':
-            disable_field(field)
-    self.index = index
-
-  def clean_pattern_name(self):
-    cleaned_data = self.cleaned_data
-    try:
-      pattern = Pattern.objects.get(name=cleaned_data['pattern_name'])
-    except Pattern.DoesNotExist:
-      raise ValidationError(u'Niepoprawna nazwa wzoru.')
-    ic = cleaned_data['inflection_characteristic']
-    if pattern.type.lexical_class != ic.part_of_speech.lexical_class:
-      raise ValidationError(u'Wzór nie pasuje do części mowy.')
-    cleaned_data['pattern'] = pattern
-    return cleaned_data['pattern_name']
-
-  def save(self, *args, **kwargs):
-    lip = self.instance
-    lip.pattern = self.cleaned_data['pattern']
-    if self.index:
-      lip.index = self.index
-    super(LIPEditForm, self).save(*args, **kwargs)
-    lip.save()
-    return lip
-
-  class Meta:
-    model = LexemeInflectionPattern
-    fields = ['inflection_characteristic']
-    widgets = {
-      'inflection_characteristic': Select(
-        attrs={'class': 'inflection-characteristic'}),
-    }
+    pattern_name = CharField(widget=TextInput(
+        attrs={'class': 'pattern', 'size': '10'}), label=u'Wzór')
+    qualifiers = QualifiersField(
+        required=False, label=u'Kwal.',
+        widget=SelectMultiple(attrs={'class': 'lip-qualifiers'}))
+
+    def __init__(self, part_of_speech, lexeme, user, editable=True, index=None,
+                 **kwargs):
+        super(LIPEditForm, self).__init__(**kwargs)
+        ic_choices = InflectionCharacteristic.objects.filter(
+            part_of_speech=part_of_speech).values_list('pk', 'symbol')
+        self.fields['inflection_characteristic'].choices = ic_choices
+        instance = getattr(self, 'instance', None)
+        self.fields['qualifiers'].set_qualifiers(user, instance, lexeme)
+        if instance and instance.id:
+            self.fields['pattern_name'].initial = instance.pattern.name
+            if not editable:
+                for name, field in self.fields.iteritems():
+                    if name != 'qualifiers':
+                        disable_field(field)
+        self.index = index
+
+    def clean_pattern_name(self):
+        cleaned_data = self.cleaned_data
+        try:
+            pattern = Pattern.objects.get(name=cleaned_data['pattern_name'])
+        except Pattern.DoesNotExist:
+            raise ValidationError(u'Niepoprawna nazwa wzoru.')
+        ic = cleaned_data['inflection_characteristic']
+        if pattern.type.lexical_class != ic.part_of_speech.lexical_class:
+            raise ValidationError(u'Wzór nie pasuje do części mowy.')
+        cleaned_data['pattern'] = pattern
+        return cleaned_data['pattern_name']
+
+    def save(self, *args, **kwargs):
+        lip = self.instance
+        lip.pattern = self.cleaned_data['pattern']
+        if self.index:
+            lip.index = self.index
+        super(LIPEditForm, self).save(*args, **kwargs)
+        lip.save()
+        return lip
+
+    class Meta:
+        model = LexemeInflectionPattern
+        fields = ['inflection_characteristic']
+        widgets = {
+            'inflection_characteristic': Select(
+                attrs={'class': 'inflection-characteristic'}),
+        }
+
 
 class ClassificationForm(Form):
-  values = TypedMultipleChoiceField(
-    choices=[], empty_value=None, coerce=int,
-    widget = SelectMultiple(attrs={'class': 'classification-values'}))
-
-  def __init__(self, classification, editable=True, values=None,
-               **kwargs):
-    super(ClassificationForm, self).__init__(**kwargs)
-    self.fields['values'].label = classification.name
-    self.fields['values'].choices = classification.make_choices()
-    if values:
-      self.fields['values'].initial = [value.pk for value in values]
-    if not editable:
-      for _name, field in self.fields.iteritems():
-        disable_field(field)
+    values = TypedMultipleChoiceField(
+        choices=[], empty_value=None, coerce=int,
+        widget=SelectMultiple(attrs={'class': 'classification-values'}))
+
+    def __init__(self, classification, editable=True, values=None,
+                 **kwargs):
+        super(ClassificationForm, self).__init__(**kwargs)
+        self.fields['values'].label = classification.name
+        self.fields['values'].choices = classification.make_choices()
+        if values:
+            self.fields['values'].initial = [value.pk for value in values]
+        if not editable:
+            for _name, field in self.fields.iteritems():
+                disable_field(field)
+
 
 class AddClassificationForm(ModelForm):
-  det = hidden_id('classification_form')
+    det = hidden_id('classification_form')
+
+    class Meta:
+        model = Classification
 
-  class Meta:
-    model = Classification
 
 class AddClassificationValueForm(ModelForm):
-  det = hidden_id('value_form')
-
-  def __init__(self, classification=None, **kwargs):
-    super(AddClassificationValueForm, self).__init__(**kwargs)
-    if classification is not None:
-      parent_choices = [('', u'<brak>')] + classification.make_choices()
-      self.fields['parent_node'].choices = parent_choices
-      self.fields['classification'].initial = classification.pk
-
-  class Meta:
-    model = ClassificationValue
-    fields = ['label', 'parent_node', 'classification']
-    widgets = {
-      'classification': HiddenInput(),
-    }
+    det = hidden_id('value_form')
+
+    def __init__(self, classification=None, **kwargs):
+        super(AddClassificationValueForm, self).__init__(**kwargs)
+        if classification is not None:
+            parent_choices = [('', u'<brak>')] + classification.make_choices()
+            self.fields['parent_node'].choices = parent_choices
+            self.fields['classification'].initial = classification.pk
+
+    class Meta:
+        model = ClassificationValue
+        fields = ['label', 'parent_node', 'classification']
+        widgets = {
+            'classification': HiddenInput(),
+        }
+
 
 class AddExclusionClassForm(ModelForm):
-  det = hidden_id('add_exclusion_class')
+    det = hidden_id('add_exclusion_class')
 
-  def __init__(self, vocabulary=None, **kwargs):
-    super(AddExclusionClassForm, self).__init__(**kwargs)
-    self.fields['vocabulary'].initial = vocabulary
+    def __init__(self, vocabulary=None, **kwargs):
+        super(AddExclusionClassForm, self).__init__(**kwargs)
+        self.fields['vocabulary'].initial = vocabulary
+
+    class Meta:
+        model = QualifierExclusionClass
+        widgets = {
+            'vocabulary': HiddenInput(),
+        }
 
-  class Meta:
-    model = QualifierExclusionClass
-    widgets = {
-      'vocabulary': HiddenInput(),
-    }
 
 class ExclusionClassForm(Form):
-  det = hidden_id('remove_exclusion_class')
-  ec = ModelChoiceField(
-    queryset=QualifierExclusionClass.objects.all(), label=u'') # dziura
+    det = hidden_id('remove_exclusion_class')
+    ec = ModelChoiceField(
+        queryset=QualifierExclusionClass.objects.all(), label=u'') # dziura
+
+    def __init__(self, queryset=None, **kwargs):
+        super(ExclusionClassForm, self).__init__(**kwargs)
+        if queryset:
+            self.fields['ec'].queryset = queryset
 
-  def __init__(self, queryset=None, **kwargs):
-    super(ExclusionClassForm, self).__init__(**kwargs)
-    if queryset:
-      self.fields['ec'].queryset = queryset
 
 class AddQualifierForm(ModelForm):
-  det = hidden_id('add_qualifier')
-
-  def __init__(self, vocabulary=None, **kwargs):
-    super(AddQualifierForm, self).__init__(**kwargs)
-    self.fields['vocabulary'].initial = vocabulary
-    if vocabulary:
-      self.fields['exclusion_class'].queryset = (QualifierExclusionClass.objects
-        .filter(vocabulary=vocabulary).distinct())
-
-  def clean(self):
-    cleaned_data = self.cleaned_data
-    ec = cleaned_data['exclusion_class']
-    if ec:
-      ec_vocab = ec.vocabulary
-      if ec_vocab and ec_vocab != cleaned_data['vocabulary']:
-        raise ValidationError(u'Klasa wykluczania niezgodna ze słownikiem.')
-    return cleaned_data
-
-  class Meta:
-    model = Qualifier
-    fields = ['label', 'exclusion_class', 'vocabulary']
-    widgets = {
-      'vocabulary': HiddenInput(),
-    }
+    det = hidden_id('add_qualifier')
+
+    def __init__(self, vocabulary=None, **kwargs):
+        super(AddQualifierForm, self).__init__(**kwargs)
+        self.fields['vocabulary'].initial = vocabulary
+        if vocabulary:
+            self.fields['exclusion_class'].queryset = (
+            QualifierExclusionClass.objects
+            .filter(vocabulary=vocabulary).distinct())
+
+    def clean(self):
+        cleaned_data = self.cleaned_data
+        ec = cleaned_data['exclusion_class']
+        if ec:
+            ec_vocab = ec.vocabulary
+            if ec_vocab and ec_vocab != cleaned_data['vocabulary']:
+                raise ValidationError(
+                    u'Klasa wykluczania niezgodna ze słownikiem.')
+        return cleaned_data
+
+    class Meta:
+        model = Qualifier
+        fields = ['label', 'exclusion_class', 'vocabulary']
+        widgets = {
+            'vocabulary': HiddenInput(),
+        }
+
 
 class ChangeClassForm(ModelForm):
-  def __init__(self, **kwargs):
-    super(ChangeClassForm, self).__init__(**kwargs)
-    exclusion_classes = (
-      self.instance.vocabulary.qualifierexclusionclass_set.all())
-    self.fields['exclusion_class'].queryset = exclusion_classes
-
-  def clean(self):
-    ec = self.cleaned_data['exclusion_class']
-    q = self.instance
-    if ec:
-      ec_qualifiers = ec.qualifier_set.all()
-      if Lexeme.objects.filter(qualifiers=q).filter(
-           qualifiers__in=ec_qualifiers):
-        raise ValidationError(u'Kolizja w klasie wykluczania')
-      if LexemeInflectionPattern.objects.filter(
-           qualifiers=q).filter(qualifiers__in=ec_qualifiers):
-        raise ValidationError(u'Kolizja w klasie wykluczania')
-      if Ending.objects.filter(qualifiers=q).filter(
-           qualifiers__in=ec_qualifiers):
-        raise ValidationError(u'Kolizja w klasie wykluczania')
-    return self.cleaned_data
-
-  class Meta:
-    model = Qualifier
-    fields = ['exclusion_class']
+    def __init__(self, **kwargs):
+        super(ChangeClassForm, self).__init__(**kwargs)
+        exclusion_classes = (
+            self.instance.vocabulary.qualifierexclusionclass_set.all())
+        self.fields['exclusion_class'].queryset = exclusion_classes
+
+    def clean(self):
+        ec = self.cleaned_data['exclusion_class']
+        q = self.instance
+        if ec:
+            ec_qualifiers = ec.qualifier_set.all()
+            if Lexeme.objects.filter(qualifiers=q).filter(
+                    qualifiers__in=ec_qualifiers):
+                raise ValidationError(u'Kolizja w klasie wykluczania')
+            if LexemeInflectionPattern.objects.filter(
+                    qualifiers=q).filter(qualifiers__in=ec_qualifiers):
+                raise ValidationError(u'Kolizja w klasie wykluczania')
+            if Ending.objects.filter(qualifiers=q).filter(
+                    qualifiers__in=ec_qualifiers):
+                raise ValidationError(u'Kolizja w klasie wykluczania')
+        return self.cleaned_data
+
+    class Meta:
+        model = Qualifier
+        fields = ['exclusion_class']
+
 
 class CrossReferenceForm(ModelForm):
-  entry = CharField(label=u'hasło', widget=TextInput(attrs={
-    'class': 'entry',
-    'size': 12,
-  }))
-  homonym_number = IntegerField(label=u'hom.',
-    widget=TextInput(attrs={
-      'class': 'homonym-number',
-      'readonly': 'readonly',
-      'size': 1,
+    entry = CharField(label=u'hasło', widget=TextInput(attrs={
+        'class': 'entry',
+        'size': 12,
     }))
+    homonym_number = IntegerField(label=u'hom.',
+                                  widget=TextInput(attrs={
+                                      'class': 'homonym-number',
+                                      'readonly': 'readonly',
+                                      'size': 1,
+                                  }))
+
+    def __init__(self, lexeme=None, pos=None, **kwargs):
+        super(CrossReferenceForm, self).__init__(**kwargs)
+        if lexeme is not None:
+            if pos is None:
+                pos = lexeme.part_of_speech
+            crtypes = pos.crtype_to.all()
+            type_choices = crtypes.values_list('pk', 'desc')
+            self.fields['type'].widget.choices = type_choices
+            self.fields['from_lexeme'].initial = lexeme.pk
+
+    def clean(self):
+        cleaned_data = self.cleaned_data
+        from_lexeme = cleaned_data.get('from_lexeme')
+        entry = cleaned_data.get('entry')
+        hom = cleaned_data.get('homonym_number')
+        cr_type = cleaned_data.get('type')
+        try:
+            to_lexeme = Lexeme.objects.get(
+                entry=entry, homonym_number=hom, part_of_speech=cr_type.to_pos)
+        except Lexeme.DoesNotExist:
+            raise ValidationError(u'Wybrany leksem nie istnieje.')
+        except Lexeme.MultipleObjectsReturned:
+            # jeśli się zdarzy, to jest niespójność w danych
+            raise ValidationError(u'Niejednoznaczny numer homonimu!')
+        if from_lexeme and to_lexeme and cr_type:
+            if cr_type.from_pos != from_lexeme.part_of_speech:
+                raise ValidationError(u'Nieprawidłowa część mowy w odsyłaczu.')
+        cleaned_data['to_lexeme'] = to_lexeme
+        return cleaned_data
+
+    def save(self, commit=True):
+        cr = super(CrossReferenceForm, self).save(False)
+        cr.to_lexeme = self.cleaned_data['to_lexeme']
+        if commit:
+            cr.save()
+        return cr
+
+    class Meta:
+        model = CrossReference
+        fields = ['type', 'from_lexeme']
+        widgets = {
+            'type': Select(attrs={'class': 'type'}),
+            'from_lexeme': HiddenInput(),
+        }
 
-  def __init__(self, lexeme=None, pos=None, **kwargs):
-    super(CrossReferenceForm, self).__init__(**kwargs)
-    if lexeme is not None:
-      if pos is None:
-        pos = lexeme.part_of_speech
-      crtypes = pos.crtype_to.all()
-      type_choices = crtypes.values_list('pk', 'desc')
-      self.fields['type'].widget.choices = type_choices
-      self.fields['from_lexeme'].initial = lexeme.pk
-
-  def clean(self):
-    cleaned_data = self.cleaned_data
-    from_lexeme = cleaned_data.get('from_lexeme')
-    entry = cleaned_data.get('entry')
-    hom = cleaned_data.get('homonym_number')
-    cr_type = cleaned_data.get('type')
-    try:
-      to_lexeme = Lexeme.objects.get(
-        entry=entry, homonym_number=hom, part_of_speech=cr_type.to_pos)
-    except Lexeme.DoesNotExist:
-      raise ValidationError(u'Wybrany leksem nie istnieje.')
-    except Lexeme.MultipleObjectsReturned:
-      # jeśli się zdarzy, to jest niespójność w danych
-      raise ValidationError(u'Niejednoznaczny numer homonimu!')
-    if from_lexeme and to_lexeme and cr_type:
-      if cr_type.from_pos != from_lexeme.part_of_speech:
-        raise ValidationError(u'Nieprawidłowa część mowy w odsyłaczu.')
-    cleaned_data['to_lexeme'] = to_lexeme
-    return cleaned_data
-
-  def save(self, commit=True):
-    cr = super(CrossReferenceForm, self).save(False)
-    cr.to_lexeme = self.cleaned_data['to_lexeme']
-    if commit:
-      cr.save()
-    return cr
-
-  class Meta:
-    model = CrossReference
-    fields = ['type', 'from_lexeme']
-    widgets = {
-      'type': Select(attrs={'class': 'type'}),
-      'from_lexeme': HiddenInput(),
-    }
 
 class VocabularyForm(Form):
-  det = hidden_id('vocabulary_form')
-  vocabulary = ModelChoiceField(
-    label=u"dodaj słownik", queryset=Vocabulary.objects.none())
-  classification = ModelChoiceField(
-    widget=HiddenInput(), queryset=Classification.objects.all())
-
-  def __init__(self, queryset, classification=None, **kwargs):
-    super(VocabularyForm, self).__init__(**kwargs)
-    self.fields['vocabulary'].queryset = queryset
-    if classification:
-      self.fields['classification'].initial = classification
+    det = hidden_id('vocabulary_form')
+    vocabulary = ModelChoiceField(
+        label=u"dodaj słownik", queryset=Vocabulary.objects.none())
+    classification = ModelChoiceField(
+        widget=HiddenInput(), queryset=Classification.objects.all())
+
+    def __init__(self, queryset, classification=None, **kwargs):
+        super(VocabularyForm, self).__init__(**kwargs)
+        self.fields['vocabulary'].queryset = queryset
+        if classification:
+            self.fields['classification'].initial = classification
+
 
 class PatternEditForm(ModelForm):
-  def __init__(self, editable=True, **kwargs):
-    super(PatternEditForm, self).__init__(**kwargs)
-    if not editable:
-      instance = getattr(self, 'instance', None)
-      if instance and instance.id:
-        for _name, field in self.fields.iteritems():
-          disable_field(field)
-
-  class Meta:
-    model = Pattern
-    fields = ('name', 'example', 'basic_form_ending', 'status', 'comment')
+    def __init__(self, editable=True, **kwargs):
+        super(PatternEditForm, self).__init__(**kwargs)
+        if not editable:
+            instance = getattr(self, 'instance', None)
+            if instance and instance.id:
+                for _name, field in self.fields.iteritems():
+                    disable_field(field)
+
+    class Meta:
+        model = Pattern
+        fields = ('name', 'example', 'basic_form_ending', 'status', 'comment')
+
 
 class PatternTypeForm(ModelForm):
-  def __init__(self, editable=True, **kwargs):
-    super(PatternTypeForm, self).__init__(**kwargs)
-    if not editable:
-      instance = getattr(self, 'instance', None)
-      if instance and instance.id:
-        for _name, field in self.fields.iteritems():
-          disable_field(field)
-
-  class Meta:
-    model = PatternType
-    fields = ('lexical_class', 'symbol')
+    def __init__(self, editable=True, **kwargs):
+        super(PatternTypeForm, self).__init__(**kwargs)
+        if not editable:
+            instance = getattr(self, 'instance', None)
+            if instance and instance.id:
+                for _name, field in self.fields.iteritems():
+                    disable_field(field)
+
+    class Meta:
+        model = PatternType
+        fields = ('lexical_class', 'symbol')
+
 
 class QualifierForm(Form):
-  qualifiers = QualifiersField(
-    required=False, label=u'',
-    widget = SelectMultiple(attrs={'class':'qualifiers'}))
+    qualifiers = QualifiersField(
+        required=False, label=u'',
+        widget=SelectMultiple(attrs={'class': 'qualifiers'}))
+
+    def __init__(self, user, qualified=None, editable=True,
+                 **kwargs):
+        super(QualifierForm, self).__init__(**kwargs)
+        self.fields['qualifiers'].set_qualifiers(user, qualified)
+        if not editable:
+            disable_field(self.fields['qualifiers'])
 
-  def __init__(self, user, qualified=None, editable=True,
-               **kwargs):
-    super(QualifierForm, self).__init__(**kwargs)
-    self.fields['qualifiers'].set_qualifiers(user, qualified)
-    if not editable:
-      disable_field(self.fields['qualifiers'])
 
 class ExportForm(Form):
-  vocabs = ModelMultipleChoiceField(
-    queryset=Vocabulary.objects.all(), label=u'słowniki')
-  antivocabs = ModelMultipleChoiceField(
-    queryset=Vocabulary.objects.all(), label=u'antysłowniki', required=False)
-  variant = ModelChoiceField(queryset=Variant.objects.all(), label=u'wariant')
-  refl = BooleanField(label=u'tagi z "refl"', required=False)
-  commonness = BooleanField(label=u'etykiety pospolitości', required=False)
-  #excluding_qualifiers = QualifiersField(
-  #  required=False, label=u'kwal. wykluczające')
+    vocabs = ModelMultipleChoiceField(
+        queryset=Vocabulary.objects.all(), label=u'słowniki')
+    antivocabs = ModelMultipleChoiceField(
+        queryset=Vocabulary.objects.all(), label=u'antysłowniki',
+        required=False)
+    variant = ModelChoiceField(queryset=Variant.objects.all(), label=u'wariant')
+    refl = BooleanField(label=u'tagi z "refl"', required=False)
+    commonness = BooleanField(label=u'etykiety pospolitości', required=False)
+    #excluding_qualifiers = QualifiersField(
+    #  required=False, label=u'kwal. wykluczające')
+
 
 class MagicQualifierForm(Form):
-  qualifier = QualifierField(label=u'kwal. leksemu')
-  regex = CharField(label=u'wzorzec tagu', required=False)
+    qualifier = QualifierField(label=u'kwal. leksemu')
+    regex = CharField(label=u'wzorzec tagu', required=False)
+
 
 ADD_REMOVE_CHOICES = (
-  ('add', u'Dodaj'),
-  ('remove', u'Usuń'),
+    ('add', u'Dodaj'),
+    ('remove', u'Usuń'),
 )
 
+
 class StatusActionForm(Form):
-  action = ChoiceField(
-    choices=[('set', u'ustaw')], label=u'',
-    widget=Select(attrs={'class': 'action-choice'}))
+    action = ChoiceField(
+        choices=[('set', u'ustaw')], label=u'',
+        widget=Select(attrs={'class': 'action-choice'}))
+
 
 class StatusValueForm(Form):
-  value = ChoiceField(
-    choices=Lexeme.STATUS_CHOICES, label=u'',
-    widget=Select(attrs={'class': 'value-choice'}))
+    value = ChoiceField(
+        choices=Lexeme.STATUS_CHOICES, label=u'',
+        widget=Select(attrs={'class': 'value-choice'}))
+
+    def __init__(self, request, **kwargs):
+        super(StatusValueForm, self).__init__(**kwargs)
 
-  def __init__(self, request, **kwargs):
-    super(StatusValueForm, self).__init__(**kwargs)
 
 class UsingVocabularyActionForm(Form):
-  action = ChoiceField(
-    choices=ADD_REMOVE_CHOICES, label=u'',
-    widget=Select(attrs={'class': 'action-choice'}))
+    action = ChoiceField(
+        choices=ADD_REMOVE_CHOICES, label=u'',
+        widget=Select(attrs={'class': 'action-choice'}))
+
 
 class VocabularyValueForm(Form):
-  value = ModelChoiceField(
-    queryset=Vocabulary.objects.none(), label=u'',
-    widget=Select(attrs={'class': 'value-choice'}))
+    value = ModelChoiceField(
+        queryset=Vocabulary.objects.none(), label=u'',
+        widget=Select(attrs={'class': 'value-choice'}))
+
+    def __init__(self, request, **kwargs):
+        super(VocabularyValueForm, self).__init__(**kwargs)
+        self.fields['value'].queryset = editable_vocabularies(request.user)
 
-  def __init__(self, request, **kwargs):
-    super(VocabularyValueForm, self).__init__(**kwargs)
-    self.fields['value'].queryset = editable_vocabularies(request.user)
 
 class LexemeQualifierActionForm(Form):
-  action = ChoiceField(
-    choices=ADD_REMOVE_CHOICES, label=u'',
-    widget=Select(attrs={'class': 'action-choice'}))
+    action = ChoiceField(
+        choices=ADD_REMOVE_CHOICES, label=u'',
+        widget=Select(attrs={'class': 'action-choice'}))
+
 
 class LexemeQualifierValueForm(Form):
-  value = QualifierField(label=u'',
-    widget=Select(attrs={'class': 'value-choice'}))
+    value = QualifierField(label=u'',
+                           widget=Select(attrs={'class': 'value-choice'}))
+
+    def __init__(self, request, **kwargs):
+        super(LexemeQualifierValueForm, self).__init__(**kwargs)
+        self.fields['value'].set_qualifiers(editable_qualifiers(request.user))
 
-  def __init__(self, request, **kwargs):
-    super(LexemeQualifierValueForm, self).__init__(**kwargs)
-    self.fields['value'].set_qualifiers(editable_qualifiers(request.user))
 
 ACTION_FIELDS = (
-  ('status',
-   (u'Status', StatusActionForm, StatusValueForm)),
-  ('using_vocabulary',
-   (u'Słownik używający', UsingVocabularyActionForm, VocabularyValueForm)),
-  ('lexeme_qualifier',
-   (u'Kwalifikator leksemu',
-    LexemeQualifierActionForm, LexemeQualifierValueForm)),
+    ('status',
+     (u'Status', StatusActionForm, StatusValueForm)),
+    ('using_vocabulary',
+     (u'Słownik używający', UsingVocabularyActionForm, VocabularyValueForm)),
+    ('lexeme_qualifier',
+     (u'Kwalifikator leksemu',
+      LexemeQualifierActionForm, LexemeQualifierValueForm)),
 )
 
+
 class ActionFieldForm(Form):
-  field = ChoiceField(
-    choices=[(id, data[0]) for id, data in ACTION_FIELDS], label=u'',
-    widget=Select(attrs={'class': 'field-choice'}))
\ No newline at end of file
+    field = ChoiceField(
+        choices=[(id, data[0]) for id, data in ACTION_FIELDS], label=u'',
+        widget=Select(attrs={'class': 'field-choice'}))
\ No newline at end of file
diff --git a/dictionary/history.py b/dictionary/history.py
index 4bc12d4..aadb070 100644
--- a/dictionary/history.py
+++ b/dictionary/history.py
@@ -3,316 +3,331 @@
 from django.core.exceptions import ObjectDoesNotExist
 from common.util import GroupDict
 from dictionary.models import Lexeme, LexemeInflectionPattern, \
-  Pattern, InflectionCharacteristic, ClassificationValue, Qualifier, History, \
-  CrossReferenceType, LexemeAttributeValue
+    Pattern, InflectionCharacteristic, ClassificationValue, Qualifier, History, \
+    CrossReferenceType, LexemeAttributeValue
 
 attribute_translation = {
-  # Leksem
-  ('leksemy', 'haslo'): u'hasło',
-  ('leksemy', 'haslosuf'): u'sufiks hasła',
-  ('leksemy', 'glosa'): u'glosa',
-  ('leksemy', 'nota'): u'nota',
-  ('leksemy', 'wymowa'): u'wymowa',
-  ('leksemy', 'valence'): u'łączliwość',
-  ('leksemy', 'pos'): u'część mowy',
-  ('leksemy', 'slownik'): u'słownik właściciel',
-  ('leksemy', 'status'): u'status',
-  ('leksemy', 'komentarz'): u'komentarz',
-  # Odmiana
-  ('odmieniasie', 'oind'): u'kolejność',
-  ('odmieniasie', 'charfl'): u'charakterystyka fleksyjna',
-  ('odmieniasie', 'w_id'): u'wzór',
+    # Leksem
+    ('leksemy', 'haslo'): u'hasło',
+    ('leksemy', 'haslosuf'): u'sufiks hasła',
+    ('leksemy', 'glosa'): u'glosa',
+    ('leksemy', 'nota'): u'nota',
+    ('leksemy', 'wymowa'): u'wymowa',
+    ('leksemy', 'valence'): u'łączliwość',
+    ('leksemy', 'pos'): u'część mowy',
+    ('leksemy', 'slownik'): u'słownik właściciel',
+    ('leksemy', 'status'): u'status',
+    ('leksemy', 'komentarz'): u'komentarz',
+    # Odmiana
+    ('odmieniasie', 'oind'): u'kolejność',
+    ('odmieniasie', 'charfl'): u'charakterystyka fleksyjna',
+    ('odmieniasie', 'w_id'): u'wzór',
 }
 
 # brzydkie - do pokazywania usuniętych leksemów
 attribute_translation_list = [
-  # Leksem
-  ('leksemy', 'haslo', u'hasło'),
-  ('leksemy', 'haslosuf', u'sufiks hasła'),
-  ('leksemy', 'glosa', u'glosa'),
-  ('leksemy', 'nota', u'nota'),
-  ('leksemy', 'wymowa', u'wymowa'),
-  ('leksemy', 'valence', u'łączliwość'),
-  ('leksemy', 'pos', u'część mowy'),
-  ('leksemy', 'slownik', u'słownik właściciel'),
-  ('leksemy', 'status', u'status'),
-  ('leksemy', 'komentarz', u'komentarz'),
-  # Odmiana
-  ('odmieniasie', 'oind', u'kolejność'),
-  ('odmieniasie', 'charfl', u'charakterystyka fleksyjna'),
-  ('odmieniasie', 'w_id', u'wzór'),
+    # Leksem
+    ('leksemy', 'haslo', u'hasło'),
+    ('leksemy', 'haslosuf', u'sufiks hasła'),
+    ('leksemy', 'glosa', u'glosa'),
+    ('leksemy', 'nota', u'nota'),
+    ('leksemy', 'wymowa', u'wymowa'),
+    ('leksemy', 'valence', u'łączliwość'),
+    ('leksemy', 'pos', u'część mowy'),
+    ('leksemy', 'slownik', u'słownik właściciel'),
+    ('leksemy', 'status', u'status'),
+    ('leksemy', 'komentarz', u'komentarz'),
+    # Odmiana
+    ('odmieniasie', 'oind', u'kolejność'),
+    ('odmieniasie', 'charfl', u'charakterystyka fleksyjna'),
+    ('odmieniasie', 'w_id', u'wzór'),
 ]
 
 lexeme_attribute_order = [
-  u'hasło',
-  u'sufiks hasła',
-  u'glosa',
-  u'nota',
-  u'wymowa',
-  u'łączliwość',
-  u'część mowy',
-  u'słownik właściciel',
-  u'status',
-  u'komentarz',
-  #u'kwalifikator',
-  #u'klasyfikacja',
-  #u'slownik',
-  #u'odsyłacz',
+    u'hasło',
+    u'sufiks hasła',
+    u'glosa',
+    u'nota',
+    u'wymowa',
+    u'łączliwość',
+    u'część mowy',
+    u'słownik właściciel',
+    u'status',
+    u'komentarz',
+    #u'kwalifikator',
+    #u'klasyfikacja',
+    #u'slownik',
+    #u'odsyłacz',
 ]
 
+
 def get_lexeme_attr(attr, lexeme):
-  if attr == 'haslo':
-    return lexeme.entry
-  elif attr == 'haslosuf':
-    return lexeme.entry_suffix
-  elif attr == 'glosa':
-    return lexeme.gloss
-  elif attr == 'wymowa':
-    return lexeme.pronunciation
-  elif attr == 'nota':
-    return lexeme.note
-  elif attr == 'valence':
-    return lexeme.valence
-  elif attr == 'pos':
-    return lexeme.part_of_speech.symbol
-  elif attr == 'slownik':
-    return lexeme.owner_vocabulary.id
-  elif attr == 'status':
-    return lexeme.status
-  elif attr == 'komentarz':
-    return lexeme.comment
+    if attr == 'haslo':
+        return lexeme.entry
+    elif attr == 'haslosuf':
+        return lexeme.entry_suffix
+    elif attr == 'glosa':
+        return lexeme.gloss
+    elif attr == 'wymowa':
+        return lexeme.pronunciation
+    elif attr == 'nota':
+        return lexeme.note
+    elif attr == 'valence':
+        return lexeme.valence
+    elif attr == 'pos':
+        return lexeme.part_of_speech.symbol
+    elif attr == 'slownik':
+        return lexeme.owner_vocabulary.id
+    elif attr == 'status':
+        return lexeme.status
+    elif attr == 'komentarz':
+        return lexeme.comment
+
 
 def get_lip_attr(attr, lip):
-  if attr == 'oind':
-    return lip.index
-  elif attr == 'charfl':
-    return lip.inflection_characteristic.symbol
-  elif attr == 'w_id':
-    return lip.pattern.name
+    if attr == 'oind':
+        return lip.index
+    elif attr == 'charfl':
+        return lip.inflection_characteristic.symbol
+    elif attr == 'w_id':
+        return lip.pattern.name
+
 
 lip_attribute_order = [
-  u'kolejność',
-  u'charakterystyka fleksyjna',
-  u'wzór',
-  #u'kwalifikator',
+    u'kolejność',
+    u'charakterystyka fleksyjna',
+    u'wzór',
+    #u'kwalifikator',
 ]
 
+
 def prepare_value(table, column, value):
-  try:
-    if column == 'qualifier_id':
-      prepared = Qualifier.all_objects.get(pk=int(value)).label
-    elif column == 'status':
-      prepared = dict(Lexeme.STATUS_CHOICES).get(value)
-    elif column == 'charfl':
-      prepared = InflectionCharacteristic.objects.get(pk=int(value)).symbol
-    elif column == 'w_id':
-      prepared = Pattern.objects.get(pk=int(value)).name
-    elif column in ('classification_value_id', 'classificationvalue_id'):
-      cv = ClassificationValue.all_objects.get(pk=int(value))
-      prepared = (cv.label, cv.classification.name)
-    elif column == 'attribute_value_id':
-      av = LexemeAttributeValue.objects.get(pk=int(value))
-      prepared = (av.value, av.attribute.name)
-    else:
-      prepared = value
-  except ObjectDoesNotExist:
-    prepared = None
-  except ValueError:
-    prepared = None
-  return prepared
+    try:
+        if column == 'qualifier_id':
+            prepared = Qualifier.all_objects.get(pk=int(value)).label
+        elif column == 'status':
+            prepared = dict(Lexeme.STATUS_CHOICES).get(value)
+        elif column == 'charfl':
+            prepared = InflectionCharacteristic.objects.get(
+                pk=int(value)).symbol
+        elif column == 'w_id':
+            prepared = Pattern.objects.get(pk=int(value)).name
+        elif column in ('classification_value_id', 'classificationvalue_id'):
+            cv = ClassificationValue.all_objects.get(pk=int(value))
+            prepared = (cv.label, cv.classification.name)
+        elif column == 'attribute_value_id':
+            av = LexemeAttributeValue.objects.get(pk=int(value))
+            prepared = (av.value, av.attribute.name)
+        else:
+            prepared = value
+    except ObjectDoesNotExist:
+        prepared = None
+    except ValueError:
+        prepared = None
+    return prepared
+
 
 def transaction_table(transaction_data):
-  transaction_dict = {}
-  lips = GroupDict()
-  extra_attributes = {}
-  classifications = {}
-  qualifiers = []
-  vocabs = []
-  crs = {}
-  lip_qualifiers = {}
-  deleted = False
-  for item1 in transaction_data:
-    table = item1.table_name
-    column = item1.column_name
-    if (table == 'leksemy' and column == 'usuniety' and
-        item1.new_value == 'true' and item1.old_value == 'false'):
-      deleted = True
-    attr = None
-    if (table, column) in attribute_translation:
-      attr = attribute_translation[(table, column)]
-    before, after = tuple(
-      prepare_value(table, column, v)
-      for v in (item1.old_value, item1.new_value))
-    before_after = (
-      before if item1.operation != 'INSERT' else None,
-      after if item1.operation != 'DELETE' else None)
-    if attr:
-      if table not in ('odmieniasie', 'kwalifikatory_odmieniasiow'):
-        transaction_dict[attr] = before_after
-      elif table == 'odmieniasie':
-        if item1.row_id not in lips:
-          lips[item1.row_id] = {}
-        lips[item1.row_id][attr] = before_after
-    if column == 'attribute_value_id':
-      if before:
-        value, attr = before
-        which = 0
-      else: # after
-        value, attr = after
-        which = 1
-      if attr not in extra_attributes:
-        extra_attributes[attr] = ([], [])
-      extra_attributes[attr][which].append(value)
-    if column in ('classification_value_id', 'classificationvalue_id'):
-      if before:
-        value, classification_name = before
-        which = 0
-      else: # after
-        value, classification_name = after
-        which = 1
-      if classification_name not in classifications:
-        classifications[classification_name] = ([], [])
-      classifications[classification_name][which].append(value)
-    if table == 'kwalifikatory_leksemow' and column == 'qualifier_id':
-      qualifiers.append(before_after)
-    if table == 'leksemy_w_slownikach' and column == 'slownik':
-      vocabs.append(before_after)
-    if table == 'odsylacze':
-      if item1.row_id not in crs:
-        crs[item1.row_id] = {}
-      crs[item1.row_id][column] = before_after
-    if table == 'kwalifikatory_odmieniasiow':
-      if item1.row_id not in lip_qualifiers:
-        lip_qualifiers[item1.row_id] = {}
-      if column: # stare DELETE nie będą widoczne
-        lip_qualifiers[item1.row_id][column] = before_after
-  if deleted:
-    return deleted_lexeme_table(transaction_data[0].lexeme)
-  rows = []
-  for attr in lexeme_attribute_order:
-    if attr in transaction_dict:
-      rows.append((attr, transaction_dict[attr]))
-  for attr, (before, after) in extra_attributes.iteritems():
-    rows.append((attr, (', '.join(before) or None, ', '.join(after) or None)))
-  for before_after in qualifiers:
-    rows.append((u'kwalifikator', before_after))
-  for name, (before, after) in classifications.iteritems():
-    attr = u'klasyfikacja: %s' % name
-    rows.append((attr, (', '.join(before) or None, ', '.join(after) or None)))
-  for before_after in vocabs:
-    rows.append((u'słownik', before_after))
-  for cr_data in crs.itervalues():
-    attr = u'odsyłacz'
-    before_after = []
-    for i in (0, 1):
-      try:
-        if cr_data['l_id_do'][i] is not None:
-          l = Lexeme.all_objects.get(pk=int(cr_data['l_id_do'][i]))
-          ic = l.lip_data()['inflection_characteristics']
-          cr_type = CrossReferenceType.objects.get(pk=cr_data['typods_id'][i])
-          prepared = ' '.join((cr_type.symbol, unicode(l), ic))
+    transaction_dict = {}
+    lips = GroupDict()
+    extra_attributes = {}
+    classifications = {}
+    qualifiers = []
+    vocabs = []
+    crs = {}
+    lip_qualifiers = {}
+    deleted = False
+    for item1 in transaction_data:
+        table = item1.table_name
+        column = item1.column_name
+        if (table == 'leksemy' and column == 'usuniety' and
+                    item1.new_value == 'true' and item1.old_value == 'false'):
+            deleted = True
+        attr = None
+        if (table, column) in attribute_translation:
+            attr = attribute_translation[(table, column)]
+        before, after = tuple(
+            prepare_value(table, column, v)
+            for v in (item1.old_value, item1.new_value))
+        before_after = (
+            before if item1.operation != 'INSERT' else None,
+            after if item1.operation != 'DELETE' else None)
+        if attr:
+            if table not in ('odmieniasie', 'kwalifikatory_odmieniasiow'):
+                transaction_dict[attr] = before_after
+            elif table == 'odmieniasie':
+                if item1.row_id not in lips:
+                    lips[item1.row_id] = {}
+                lips[item1.row_id][attr] = before_after
+        if column == 'attribute_value_id':
+            if before:
+                value, attr = before
+                which = 0
+            else: # after
+                value, attr = after
+                which = 1
+            if attr not in extra_attributes:
+                extra_attributes[attr] = ([], [])
+            extra_attributes[attr][which].append(value)
+        if column in ('classification_value_id', 'classificationvalue_id'):
+            if before:
+                value, classification_name = before
+                which = 0
+            else: # after
+                value, classification_name = after
+                which = 1
+            if classification_name not in classifications:
+                classifications[classification_name] = ([], [])
+            classifications[classification_name][which].append(value)
+        if table == 'kwalifikatory_leksemow' and column == 'qualifier_id':
+            qualifiers.append(before_after)
+        if table == 'leksemy_w_slownikach' and column == 'slownik':
+            vocabs.append(before_after)
+        if table == 'odsylacze':
+            if item1.row_id not in crs:
+                crs[item1.row_id] = {}
+            crs[item1.row_id][column] = before_after
+        if table == 'kwalifikatory_odmieniasiow':
+            if item1.row_id not in lip_qualifiers:
+                lip_qualifiers[item1.row_id] = {}
+            if column: # stare DELETE nie będą widoczne
+                lip_qualifiers[item1.row_id][column] = before_after
+    if deleted:
+        return deleted_lexeme_table(transaction_data[0].lexeme)
+    rows = []
+    for attr in lexeme_attribute_order:
+        if attr in transaction_dict:
+            rows.append((attr, transaction_dict[attr]))
+    for attr, (before, after) in extra_attributes.iteritems():
+        rows.append(
+            (attr, (', '.join(before) or None, ', '.join(after) or None)))
+    for before_after in qualifiers:
+        rows.append((u'kwalifikator', before_after))
+    for name, (before, after) in classifications.iteritems():
+        attr = u'klasyfikacja: %s' % name
+        rows.append(
+            (attr, (', '.join(before) or None, ', '.join(after) or None)))
+    for before_after in vocabs:
+        rows.append((u'słownik', before_after))
+    for cr_data in crs.itervalues():
+        attr = u'odsyłacz'
+        before_after = []
+        for i in (0, 1):
+            try:
+                if cr_data['l_id_do'][i] is not None:
+                    l = Lexeme.all_objects.get(pk=int(cr_data['l_id_do'][i]))
+                    ic = l.lip_data()['inflection_characteristics']
+                    cr_type = CrossReferenceType.objects.get(
+                        pk=cr_data['typods_id'][i])
+                    prepared = ' '.join((cr_type.symbol, unicode(l), ic))
+                else:
+                    prepared = None
+            except Lexeme.DoesNotExist:
+                prepared = None
+            before_after.append(prepared)
+        rows.append((attr, tuple(before_after)))
+    lip_dict = GroupDict()
+    for lip_id, lip_data in lips.iteritems():
+        for attr in lip_attribute_order:
+            if attr in lip_data:
+                lip_dict.add(lip_id, (attr, lip_data[attr]))
+    for q_data in lip_qualifiers.itervalues():
+        if q_data: # stare DELETE...
+            attr = u'kwalifikator'
+            lip_data = q_data['lexemeinflectionpattern_id']
+            lip_id = int(lip_data[0] or lip_data[1])
+            lip_dict.add(lip_id, (attr, q_data['qualifier_id']))
+    lip_tables = []
+    for lip_id, lip_data in lip_dict.iteritems():
+        lip = LexemeInflectionPattern.all_objects.filter(pk=lip_id)
+        if lip:
+            lip = lip[0]
+            header = '%s/%s' % (
+                lip.inflection_characteristic.symbol, lip.pattern.name)
         else:
-          prepared = None
-      except Lexeme.DoesNotExist:
-        prepared = None
-      before_after.append(prepared)
-    rows.append((attr, tuple(before_after)))
-  lip_dict = GroupDict()
-  for lip_id, lip_data in lips.iteritems():
-    for attr in lip_attribute_order:
-      if attr in lip_data:
-        lip_dict.add(lip_id, (attr, lip_data[attr]))
-  for q_data in lip_qualifiers.itervalues():
-    if q_data: # stare DELETE...
-      attr = u'kwalifikator'
-      lip_data = q_data['lexemeinflectionpattern_id']
-      lip_id = int(lip_data[0] or lip_data[1])
-      lip_dict.add(lip_id, (attr, q_data['qualifier_id']))
-  lip_tables = []
-  for lip_id, lip_data in lip_dict.iteritems():
-    lip = LexemeInflectionPattern.all_objects.filter(pk=lip_id)
-    if lip:
-      lip = lip[0]
-      header = '%s/%s' % (
-        lip.inflection_characteristic.symbol, lip.pattern.name)
-    else:
-      records = History.objects.filter(
-        operation='DELETE', table_name='odmieniasie', row_id=lip_id)
-      try:
-        ic_id = records.get(column_name='charfl').old_value
-        pattern_id = records.get(column_name='w_id').old_value
-        ic = InflectionCharacteristic.objects.get(pk=ic_id)
-        pattern = Pattern.objects.get(pk=pattern_id)
-        header = u'%s/%s ' % (ic.symbol, pattern.name)
-      except ObjectDoesNotExist: # stare DELETE...
-        header = ''
-      header += u'(usunięta)'
-    lip_tables.append((header, lip_data))
-  return rows, lip_tables
+            records = History.objects.filter(
+                operation='DELETE', table_name='odmieniasie', row_id=lip_id)
+            try:
+                ic_id = records.get(column_name='charfl').old_value
+                pattern_id = records.get(column_name='w_id').old_value
+                ic = InflectionCharacteristic.objects.get(pk=ic_id)
+                pattern = Pattern.objects.get(pk=pattern_id)
+                header = u'%s/%s ' % (ic.symbol, pattern.name)
+            except ObjectDoesNotExist: # stare DELETE...
+                header = ''
+            header += u'(usunięta)'
+        lip_tables.append((header, lip_data))
+    return rows, lip_tables
+
 
 def deleted_lexeme_table(lexeme):
-  rows = []
-  for table, column, attr in attribute_translation_list:
-    if table == 'leksemy':
-      rows.append(
-        (attr,
-         (prepare_value(table, column, get_lexeme_attr(column, lexeme)),
-          None)))
-  for q in lexeme.qualifiers.all():
-    rows.append((u'kwalifikator', (q.label, None)))
-  for classification in lexeme.owner_vocabulary.classifications.all():
-    attr = u'klasyfikacja: %s' % classification.name
-    cvs = lexeme.classification_values(classification)
-    for cv in cvs:
-      rows.append((attr, (cv.label, None)))
-  for vocab in lexeme.vocabularies.all():
-    rows.append((u'słownik', (vocab.id, None)))
-  for cr in lexeme.refs_to.all():
-    attr = u'odsyłacz'
-    rows.append((attr, (
-      ' '.join([cr.type.symbol, cr.to_lexeme.entry,
-                cr.to_lexeme.lip_data()['inflection_characteristics']]), None)))
-  lip_tables = []
-  for lip in lexeme.lexemeinflectionpattern_set.all():
-    lip_data = []
+    rows = []
     for table, column, attr in attribute_translation_list:
-      if table == 'odmieniasie':
-        lip_data.append((attr, (get_lip_attr(column, lip), None)))
-    for q in lip.qualifiers.all():
-      attr = u'kwalifikator'
-      lip_data.append((attr, (q.label, None)))
-    header = '%s/%s' % (lip.inflection_characteristic.symbol, lip.pattern.name)
-    lip_tables.append((header, lip_data))
-  return rows, lip_tables
+        if table == 'leksemy':
+            rows.append(
+                (attr,
+                 (prepare_value(table, column, get_lexeme_attr(column, lexeme)),
+                  None)))
+    for q in lexeme.qualifiers.all():
+        rows.append((u'kwalifikator', (q.label, None)))
+    for classification in lexeme.owner_vocabulary.classifications.all():
+        attr = u'klasyfikacja: %s' % classification.name
+        cvs = lexeme.classification_values(classification)
+        for cv in cvs:
+            rows.append((attr, (cv.label, None)))
+    for vocab in lexeme.vocabularies.all():
+        rows.append((u'słownik', (vocab.id, None)))
+    for cr in lexeme.refs_to.all():
+        attr = u'odsyłacz'
+        rows.append((attr, (
+            ' '.join([cr.type.symbol, cr.to_lexeme.entry,
+                      cr.to_lexeme.lip_data()['inflection_characteristics']]),
+            None)))
+    lip_tables = []
+    for lip in lexeme.lexemeinflectionpattern_set.all():
+        lip_data = []
+        for table, column, attr in attribute_translation_list:
+            if table == 'odmieniasie':
+                lip_data.append((attr, (get_lip_attr(column, lip), None)))
+        for q in lip.qualifiers.all():
+            attr = u'kwalifikator'
+            lip_data.append((attr, (q.label, None)))
+        header = '%s/%s' % (
+        lip.inflection_characteristic.symbol, lip.pattern.name)
+        lip_tables.append((header, lip_data))
+    return rows, lip_tables
+
 
 def lexeme_table(transaction_data, last_tb):
-  rows, lip_tables = transaction_table(transaction_data)
-  try:
-    lexeme = transaction_data[0].lexeme
-  except Lexeme.DoesNotExist:
-    lexeme = u'(usunięty)' # aktualnie niemożliwe
-  return {
-    'rows': rows,
-    'lip_tables': lip_tables,
-    'user': transaction_data[0].user,
-    'date': last_tb,
-    'lexeme': lexeme,
-  }
+    rows, lip_tables = transaction_table(transaction_data)
+    try:
+        lexeme = transaction_data[0].lexeme
+    except Lexeme.DoesNotExist:
+        lexeme = u'(usunięty)' # aktualnie niemożliwe
+    return {
+        'rows': rows,
+        'lip_tables': lip_tables,
+        'user': transaction_data[0].user,
+        'date': last_tb,
+        'lexeme': lexeme,
+    }
+
 
 def lexeme_table_from_row(row):
-  transaction_data = History.objects.filter(
-    lexeme__pk=row['lexeme'], user__pk=row['user'],
-    transaction_began=row['transaction_began'])
-  return lexeme_table(transaction_data, row['transaction_began'])
+    transaction_data = History.objects.filter(
+        lexeme__pk=row['lexeme'], user__pk=row['user'],
+        transaction_began=row['transaction_began'])
+    return lexeme_table(transaction_data, row['transaction_began'])
+
 
 def lexeme_tables(history_items):
-  transaction_data = []
-  last_tb = None
-  for item in history_items:
-    if last_tb and item.transaction_began != last_tb:
-      yield lexeme_table(transaction_data, last_tb)
-      transaction_data = []
-    last_tb = item.transaction_began
-    transaction_data.append(item)
-  if transaction_data:
-    yield lexeme_table(transaction_data, last_tb)
+    transaction_data = []
+    last_tb = None
+    for item in history_items:
+        if last_tb and item.transaction_began != last_tb:
+            yield lexeme_table(transaction_data, last_tb)
+            transaction_data = []
+        last_tb = item.transaction_began
+        transaction_data.append(item)
+    if transaction_data:
+        yield lexeme_table(transaction_data, last_tb)
diff --git a/dictionary/management/commands/check_ispell.py b/dictionary/management/commands/check_ispell.py
index eb8fb0f..1251a9b 100644
--- a/dictionary/management/commands/check_ispell.py
+++ b/dictionary/management/commands/check_ispell.py
@@ -3,32 +3,36 @@
 from django.core.management.base import BaseCommand
 from dictionary.models import Lexeme
 
+
 class Command(BaseCommand):
-  args = '<input file>'
-  help = ''
+    args = '<input file>'
+    help = ''
+
+    def handle(self, input_file, **options):
+        check_ispell(input_file)
 
-  def handle(self, input_file, **options):
-    check_ispell(input_file)
 
 def inc_count(d, key):
-  d[key] = 1 + d.get(key, 0)
+    d[key] = 1 + d.get(key, 0)
+
 
 def dict_repr(d):
-  return '|'.join('%s:%s' % (key, value) for key, value in d.iteritems())
+    return '|'.join('%s:%s' % (key, value) for key, value in d.iteritems())
+
 
 def check_ispell(input_file):
-  results = {}
-  for line in open(input_file):
-    line = line.decode('utf-8').strip()
-    entry, flags = line.split('/', 1)
-    lexemes = Lexeme.objects.filter(entry=entry).exclude(status='cand')
-    if flags not in results:
-      results[flags] = {'pos': {}, 'ics': {}}
-    for l in lexemes:
-      ics = l.lip_data()['inflection_characteristics']
-      inc_count(results[flags]['pos'], l.part_of_speech.symbol)
-      inc_count(results[flags]['ics'], ics)
-  for flags, res in results.iteritems():
-    print ('%s=%s,%s' %
-           ((flags, dict_repr(res['pos']),
-             dict_repr(res['ic'])))).encode('utf-8')
\ No newline at end of file
+    results = {}
+    for line in open(input_file):
+        line = line.decode('utf-8').strip()
+        entry, flags = line.split('/', 1)
+        lexemes = Lexeme.objects.filter(entry=entry).exclude(status='cand')
+        if flags not in results:
+            results[flags] = {'pos': {}, 'ics': {}}
+        for l in lexemes:
+            ics = l.lip_data()['inflection_characteristics']
+            inc_count(results[flags]['pos'], l.part_of_speech.symbol)
+            inc_count(results[flags]['ics'], ics)
+    for flags, res in results.iteritems():
+        print ('%s=%s,%s' %
+               ((flags, dict_repr(res['pos']),
+                 dict_repr(res['ic'])))).encode('utf-8')
\ No newline at end of file
diff --git a/dictionary/management/commands/check_morfologik.py b/dictionary/management/commands/check_morfologik.py
index 51e6827..9b75905 100644
--- a/dictionary/management/commands/check_morfologik.py
+++ b/dictionary/management/commands/check_morfologik.py
@@ -5,129 +5,135 @@ from django.core.management.base import BaseCommand, CommandError
 from common.util import debug
 from dictionary.models import Lexeme
 
+
 class Command(BaseCommand):
-  args = '<symbol części mowy> <nazwa pliku wejściowego>'
-  help = 'Check Morfologik import'
+    args = '<symbol części mowy> <nazwa pliku wejściowego>'
+    help = 'Check Morfologik import'
 
-  def handle(self, lc_sym, input_file, **options):
-    check_morfologik(lc_sym, input_file)
+    def handle(self, lc_sym, input_file, **options):
+        check_morfologik(lc_sym, input_file)
 
 # i tak nie ma żadnych q* aktualnie...
 v_forms = {
-  ('1', 'allq'): u'',
-  ('1', 'all'): u'cie|my|sz',
-  ('2', 'all'): u'',
-  ('3', 'all'): u'',
-  ('3', 'ndk'): u'c',
-  ('3', 'pact'): u'ca|cą|ce|cego|cej|cemu|cy|cych|cym|cymi',
-  ('4', 'all'): u'|że|my|myż|cie|cież',
-  ('5', 'allq'): u'',
-  ('6', 'all'): u'|by|byś|bym',
-  ("6'", 'dk'): u'szy',
-  ('7', 'all'): u'em|eś',
-  ('8', 'allq'): u'o|oby',
-  ('8', 'all'): u'a|aby|abyś|abym|am|aś|obym|obyś|om|oś|'
-                u'y|yby|ybyście|ybyśmy|yście|yśmy',
-  ('9', 'all'): u'i|iby|ibyście|ibyśmy|iście|iśmy',
-  ('10', 'all'): u'o',
-  ('10', 'ppas'): u'a|ą|e|ego|ej|emu|y|ych|ym|ymi',
-  ('11', 'ger'): u'ie|ia|iach|iami|iem|iom|iu',
-  ('11pg', 'ger'): u'',
-  ('12', 'ppas'): u'',
+    ('1', 'allq'): u'',
+    ('1', 'all'): u'cie|my|sz',
+    ('2', 'all'): u'',
+    ('3', 'all'): u'',
+    ('3', 'ndk'): u'c',
+    ('3', 'pact'): u'ca|cą|ce|cego|cej|cemu|cy|cych|cym|cymi',
+    ('4', 'all'): u'|że|my|myż|cie|cież',
+    ('5', 'allq'): u'',
+    ('6', 'all'): u'|by|byś|bym',
+    ("6'", 'dk'): u'szy',
+    ('7', 'all'): u'em|eś',
+    ('8', 'allq'): u'o|oby',
+    ('8', 'all'): u'a|aby|abyś|abym|am|aś|obym|obyś|om|oś|'
+                  u'y|yby|ybyście|ybyśmy|yście|yśmy',
+    ('9', 'all'): u'i|iby|ibyście|ibyśmy|iście|iśmy',
+    ('10', 'all'): u'o',
+    ('10', 'ppas'): u'a|ą|e|ego|ej|emu|y|ych|ym|ymi',
+    ('11', 'ger'): u'ie|ia|iach|iami|iem|iom|iu',
+    ('11pg', 'ger'): u'',
+    ('12', 'ppas'): u'',
 }
 
+
 def get_forms(l, lc_sym):
-  if lc_sym != 'v':
-    l_forms = set(l.lexemeform_set.values_list('form', flat=True))
-    if lc_sym == 'adj':
-      neg = l.refs_to.filter(type__symbol='adjnie')
-      if neg:
-        l_neg = neg[0].to_lexeme
-        neg_forms = l_neg.lexemeform_set.values_list('form', flat=True)
-        added_forms = l_neg.all_forms(label_filter='^0|3\+$')
-        l_forms |= set(form for form in neg_forms if form not in added_forms)
-  else:
-    tags = ['allq']
-    if l.refs_to.filter(type__symbol='verpact'):
-      tags.append('pact')
-    if l.refs_to.filter(type__symbol='verppas'):
-      tags.append('ppas')
-    if l.refs_to.filter(type__symbol='verger'):
-      tags.append('ger')
-    lips = l.lexemeinflectionpattern_set.all()
-    if not lips:
-      return set()
-    ic = lips[0].inflection_characteristic.symbol
-    q = ic.startswith('q')
-    if not q:
-      tags.append('all')
-      if 'ndk' in ic:
-        tags.append('ndk')
-      if 'dk' in ic.replace('ndk', ''):
-        tags.append('dk')
-    base_forms = {}
-    for lip in l.lexemeinflectionpattern_set.all():
-      for ending in lip.pattern.endings.all():
-        bfl = ending.base_form_label.symbol
-        if bfl not in base_forms:
-          base_forms[bfl] = set()
-        base_forms[bfl].add(lip.root + ending.string)
-    l_forms = set()
-    for (label, tag), suffixes in v_forms.iteritems():
-      if tag in tags and label in base_forms:
-        new_forms = set()
-        for base_form in base_forms[label]:
-          new_forms |= set(base_form + suffix for suffix in suffixes.split('|'))
-        l_forms |= new_forms
-        if tag in ('pact', 'ppas', 'ger'):
-          l_forms |= set('nie' + form for form in new_forms)
-  return l_forms
+    if lc_sym != 'v':
+        l_forms = set(l.lexemeform_set.values_list('form', flat=True))
+        if lc_sym == 'adj':
+            neg = l.refs_to.filter(type__symbol='adjnie')
+            if neg:
+                l_neg = neg[0].to_lexeme
+                neg_forms = l_neg.lexemeform_set.values_list('form', flat=True)
+                added_forms = l_neg.all_forms(label_filter='^0|3\+$')
+                l_forms |= set(
+                    form for form in neg_forms if form not in added_forms)
+    else:
+        tags = ['allq']
+        if l.refs_to.filter(type__symbol='verpact'):
+            tags.append('pact')
+        if l.refs_to.filter(type__symbol='verppas'):
+            tags.append('ppas')
+        if l.refs_to.filter(type__symbol='verger'):
+            tags.append('ger')
+        lips = l.lexemeinflectionpattern_set.all()
+        if not lips:
+            return set()
+        ic = lips[0].inflection_characteristic.symbol
+        q = ic.startswith('q')
+        if not q:
+            tags.append('all')
+            if 'ndk' in ic:
+                tags.append('ndk')
+            if 'dk' in ic.replace('ndk', ''):
+                tags.append('dk')
+        base_forms = {}
+        for lip in l.lexemeinflectionpattern_set.all():
+            for ending in lip.pattern.endings.all():
+                bfl = ending.base_form_label.symbol
+                if bfl not in base_forms:
+                    base_forms[bfl] = set()
+                base_forms[bfl].add(lip.root + ending.string)
+        l_forms = set()
+        for (label, tag), suffixes in v_forms.iteritems():
+            if tag in tags and label in base_forms:
+                new_forms = set()
+                for base_form in base_forms[label]:
+                    new_forms |= set(
+                        base_form + suffix for suffix in suffixes.split('|'))
+                l_forms |= new_forms
+                if tag in ('pact', 'ppas', 'ger'):
+                    l_forms |= set('nie' + form for form in new_forms)
+    return l_forms
+
 
 def check_forms(lc_sym, forms):
-  entry = forms[0]
-  forms = set(forms)
-  morf_lexemes = Lexeme.objects.filter(
-    lexemeassociation__vocabulary__id='Morfologik', entry=entry,
-    part_of_speech__lexical_class__symbol=lc_sym)
-  for l in morf_lexemes:
-    if l.part_of_speech.lexical_class.symbol != lc_sym:
-      continue
-    l_forms = get_forms(l, lc_sym)
-    if l_forms == set():
-      break # brak dopasowania nas tu nie interesuje
-    if forms == l_forms:
-      break
-    if lc_sym == 'subst':
-      m1_lips = l.lexemeinflectionpattern_set.filter(
-        inflection_characteristic__symbol='m1')
-      if m1_lips and u'formę depr' in l.comment:
-        if forms | l.all_forms(label_filter='^pl:nom$') == l_forms:
-          break
-      if (u'rozszerzone singulare' in l.comment
-          or u'rozszerzyć sgtant' in l.comment
-          or l.owner_vocabulary.id != 'Morfologik'):
-        if forms == l.all_forms(label_filter='^sg:'):
-          break
-    elif lc_sym == 'adj':
-      #if u' -o' in l.comment:
-        if forms | l.all_forms(label_filter='^0$') == l_forms:
-          break
-  else: # żaden nie pasował
-    print entry.encode('utf-8')
+    entry = forms[0]
+    forms = set(forms)
+    morf_lexemes = Lexeme.objects.filter(
+        lexemeassociation__vocabulary__id='Morfologik', entry=entry,
+        part_of_speech__lexical_class__symbol=lc_sym)
     for l in morf_lexemes:
-      l_forms = get_forms(l, lc_sym)
-      missing = ', '.join(forms - l_forms)
-      extra = ', '.join(l_forms - forms)
-      print ('%s|%s' % (missing, extra)).encode('utf-8')
+        if l.part_of_speech.lexical_class.symbol != lc_sym:
+            continue
+        l_forms = get_forms(l, lc_sym)
+        if l_forms == set():
+            break # brak dopasowania nas tu nie interesuje
+        if forms == l_forms:
+            break
+        if lc_sym == 'subst':
+            m1_lips = l.lexemeinflectionpattern_set.filter(
+                inflection_characteristic__symbol='m1')
+            if m1_lips and u'formę depr' in l.comment:
+                if forms | l.all_forms(label_filter='^pl:nom$') == l_forms:
+                    break
+            if (u'rozszerzone singulare' in l.comment
+                or u'rozszerzyć sgtant' in l.comment
+                or l.owner_vocabulary.id != 'Morfologik'):
+                if forms == l.all_forms(label_filter='^sg:'):
+                    break
+        elif lc_sym == 'adj':
+        #if u' -o' in l.comment:
+            if forms | l.all_forms(label_filter='^0$') == l_forms:
+                break
+    else: # żaden nie pasował
+        print entry.encode('utf-8')
+        for l in morf_lexemes:
+            l_forms = get_forms(l, lc_sym)
+            missing = ', '.join(forms - l_forms)
+            extra = ', '.join(l_forms - forms)
+            print ('%s|%s' % (missing, extra)).encode('utf-8')
+
 
 def check_morfologik(lc_sym, input_file):
-  with open(input_file) as file:
-    forms = []
-    for line in file:
-      line = line.decode('utf-8').rstrip('\n')
-      if line == '':
-        check_forms(lc_sym, forms)
+    with open(input_file) as file:
         forms = []
-      else:
-        form, tag = line.split('\t')
-        forms.append(form)
+        for line in file:
+            line = line.decode('utf-8').rstrip('\n')
+            if line == '':
+                check_forms(lc_sym, forms)
+                forms = []
+            else:
+                form, tag = line.split('\t')
+                forms.append(form)
diff --git a/dictionary/management/commands/create_classifications.py b/dictionary/management/commands/create_classifications.py
index 4b9959c..c746fda 100644
--- a/dictionary/management/commands/create_classifications.py
+++ b/dictionary/management/commands/create_classifications.py
@@ -1,41 +1,45 @@
 #-*- coding:utf-8 -*-
 
-from django.core.management.base import BaseCommand, CommandError
+from django.core.management.base import BaseCommand
 from dictionary.models import Classification, ClassificationValue
 
+
 class Command(BaseCommand):
-  args = 'none'
-  help = 'Creates default classifications'
+    args = 'none'
+    help = 'Creates default classifications'
 
-  def handle(self, **options):
-    create_classifications()
+    def handle(self, **options):
+        create_classifications()
 
 
 def get_permission(codename):
-  return Permission.objects.get(codename=codename)
+    return Permission.objects.get(codename=codename)
+
 
 def create_classifications():
-  Classification.objects.all().delete()
-  ClassificationValue.objects.all().delete()
-  commonness = Classification.objects.create(name=u'pospolitość')
-
-  common_name = ClassificationValue.objects.create(
-    label=u'pospolita', parent_node=None, classification=commonness)
-  proper_name = ClassificationValue.objects.create(
-    label=u'własna', parent_node=None, classification=commonness)
-  person = ClassificationValue.objects.create(
-    label=u'osoba', parent_node=proper_name, classification=commonness)
-  ClassificationValue.objects.create(
-    label=u'imię', parent_node=person, classification=commonness)
-  ClassificationValue.objects.create(
-    label=u'nazwisko', parent_node=person, classification=commonness)
-  ClassificationValue.objects.create(
-    label=u'patronimicum', parent_node=person, classification=commonness)
-  ClassificationValue.objects.create(
-    label=u'przydomek', parent_node=person, classification=commonness)
-  ClassificationValue.objects.create(
-    label=u'pseudonim', parent_node=person, classification=commonness)
-  ClassificationValue.objects.create(
-    label=u'geograficzna', parent_node=proper_name, classification=commonness)
-  ClassificationValue.objects.create(
-    label=u'organizacja', parent_node=proper_name, classification=commonness)
+    Classification.objects.all().delete()
+    ClassificationValue.objects.all().delete()
+    commonness = Classification.objects.create(name=u'pospolitość')
+
+    common_name = ClassificationValue.objects.create(
+        label=u'pospolita', parent_node=None, classification=commonness)
+    proper_name = ClassificationValue.objects.create(
+        label=u'własna', parent_node=None, classification=commonness)
+    person = ClassificationValue.objects.create(
+        label=u'osoba', parent_node=proper_name, classification=commonness)
+    ClassificationValue.objects.create(
+        label=u'imię', parent_node=person, classification=commonness)
+    ClassificationValue.objects.create(
+        label=u'nazwisko', parent_node=person, classification=commonness)
+    ClassificationValue.objects.create(
+        label=u'patronimicum', parent_node=person, classification=commonness)
+    ClassificationValue.objects.create(
+        label=u'przydomek', parent_node=person, classification=commonness)
+    ClassificationValue.objects.create(
+        label=u'pseudonim', parent_node=person, classification=commonness)
+    ClassificationValue.objects.create(
+        label=u'geograficzna', parent_node=proper_name,
+        classification=commonness)
+    ClassificationValue.objects.create(
+        label=u'organizacja', parent_node=proper_name,
+        classification=commonness)
diff --git a/dictionary/management/commands/create_forms.py b/dictionary/management/commands/create_forms.py
index 16d7a49..2cfcf39 100644
--- a/dictionary/management/commands/create_forms.py
+++ b/dictionary/management/commands/create_forms.py
@@ -1,29 +1,27 @@
 #-*- coding:utf-8 -*-
 
-import sys
 from django.db import connection, transaction
-from django.core.management.base import BaseCommand, CommandError
-from common.util import debug
-from dictionary.models import Lexeme
+from django.core.management.base import BaseCommand
+
 
 class Command(BaseCommand):
-  args = 'none'
-  help = 'Creates forms for filtering'
+    args = 'none'
+    help = 'Creates forms for filtering'
 
-  def handle(self, **options):
-    create_forms()
+    def handle(self, **options):
+        create_forms()
 
 
 def create_forms():
-  cursor = connection.cursor()
+    cursor = connection.cursor()
 
-  transaction.commit_unless_managed()
-  transaction.enter_transaction_management()
-  transaction.managed(True)
+    transaction.commit_unless_managed()
+    transaction.enter_transaction_management()
+    transaction.managed(True)
 
-  cursor.execute('''delete from dictionary_lexemeform''')
-  # ew. można odfiltrować te z wygenerowanymi?
-  select_query = '''select l.id as lexeme_id, prefiks||rdzen||zak||sufiks as form
+    cursor.execute('''delete from dictionary_lexemeform''')
+    # ew. można odfiltrować te z wygenerowanymi?
+    select_query = '''select l.id as lexeme_id, prefiks||rdzen||zak||sufiks as form
         from leksemy l
         join odmieniasie o on l.id = o.l_id
         join charfle ch on ch.id = o.charfl
@@ -34,8 +32,8 @@ def create_forms():
         join klatki k on k.st_id = s.id
         join zakonczenia z on (o.w_id=z.w_id and k.efobaz=z.efobaz)
         where wariant='1' ''' # jaki wariant?
-  cursor.execute('''insert into dictionary_lexemeform (lexeme_id, form)
+    cursor.execute('''insert into dictionary_lexemeform (lexeme_id, form)
         (%s)''' % select_query)
 
-  transaction.commit()
-  transaction.leave_transaction_management()
+    transaction.commit()
+    transaction.leave_transaction_management()
diff --git a/dictionary/management/commands/delete_unique.py b/dictionary/management/commands/delete_unique.py
index 8b03c19..635dc81 100644
--- a/dictionary/management/commands/delete_unique.py
+++ b/dictionary/management/commands/delete_unique.py
@@ -2,14 +2,16 @@
 from south.db import db
 from django.core.management.base import BaseCommand
 
+
 class Command(BaseCommand):
-  args = 'none'
-  help = 'Aktualnie nie dziala z powodu bledu w south.'
+    args = 'none'
+    help = 'Aktualnie nie dziala z powodu bledu w south.'
+
+    def handle(self, **options):
+        delete_unique()
 
-  def handle(self, **options):
-    delete_unique()
 
 def delete_unique():
-  db.delete_unique('odmieniasie', ['l_id', 'oind'])
-  db.delete_unique('zakonczenia', ['w_id', 'efobaz', 'zind'])
+    db.delete_unique('odmieniasie', ['l_id', 'oind'])
+    db.delete_unique('zakonczenia', ['w_id', 'efobaz', 'zind'])
 
diff --git a/dictionary/management/commands/disamb.py b/dictionary/management/commands/disamb.py
index a467c3f..fc3a883 100755
--- a/dictionary/management/commands/disamb.py
+++ b/dictionary/management/commands/disamb.py
@@ -7,179 +7,197 @@ from django.core.management.base import BaseCommand, CommandError
 from common.util import debug
 from dictionary.util import expand_tag
 
+
 class Command(BaseCommand):
-  args = '<nazwa pliku wejściowego>'
-  help = 'Dezambiguacja tagów z Morfologika'
+    args = '<nazwa pliku wejściowego>'
+    help = 'Dezambiguacja tagów z Morfologika'
 
-  def handle(self, input_file, **options):
-    parse_file(input_file)
+    def handle(self, input_file, **options):
+        parse_file(input_file)
 
 
 base_tag = {}
 
 form_categories = {
-  'adj': ['adj'],
-  'verb': ['subst:ger', 'verb', 'pact', 'ppas', 'pant', 'pcon'],
-  'subst': ['subst'],
-  'adv': ['adv'],
+    'adj': ['adj'],
+    'verb': ['subst:ger', 'verb', 'pact', 'ppas', 'pant', 'pcon'],
+    'subst': ['subst'],
+    'adv': ['adv'],
 }
 
+
 def all_tags(form, filter_base=False):
-  tags = []
-  for tag, base in zip(form['tags'], form['base']):
-    if not filter_base or base:
-      tags += expand_tag(tag)
-  return tags
+    tags = []
+    for tag, base in zip(form['tags'], form['base']):
+        if not filter_base or base:
+            tags += expand_tag(tag)
+    return tags
+
 
 def base_tag(tag):
-  pos = tag.split(':')[0]
-  if tag.startswith('subst:ger'):
-    return False
-  if pos in ('num', 'subst', 'adj'):
-    return 'nom' in tag
-  if pos == 'verb':
-    return 'inf' in tag or 'winien' in tag
-  if pos in ('refl', 'pact', 'ppas'):
-    return False
-  return True
+    pos = tag.split(':')[0]
+    if tag.startswith('subst:ger'):
+        return False
+    if pos in ('num', 'subst', 'adj'):
+        return 'nom' in tag
+    if pos == 'verb':
+        return 'inf' in tag or 'winien' in tag
+    if pos in ('refl', 'pact', 'ppas'):
+        return False
+    return True
 
 # forms: lista {form: forma, tags: lista możliwych tagów)?
 def disamb_lexeme(forms):
-  base_form_tags = (tag for tag, base
-                     in zip(forms[0]['tags'], forms[0]['base'])
-                     if base and base_tag(tag))
-  possible_pos = set(tag.split(':')[0] for tag in base_form_tags)
-  entry = forms[0]['form']
-  if forms[0]['tags'][0] == '-':
-    print >>sys.stderr, (u'%s: nierozpoznana forma podstawowa' %
-                         entry).encode('utf-8')
-    return None, None
-  if len(possible_pos) == 1:
-    pos = list(possible_pos)[0]
-  else:
-    print >>sys.stderr, (u'%s: niejednoznaczna część mowy' %
-                         entry).encode('utf-8')
-    return None, None
-  cats = form_categories.get(pos, [pos])
-  new_forms = []
-  other_lexemes = []
-  for form in forms:
-    new_tags = []
-    for tag, base in zip(form['tags'], form['base']):
-      for cat in cats:
-        if tag.startswith(cat) and base:
-          new_tags.append(tag)
-          break
-      else: # nie pasowało
-        if pos == 'verb':
-          tags = tag.split('+')
-          fixed = None
-          if tags[0].startswith('subst'):
-            fixed = ['subst:ger' + tag[len('subst'):] for tag in tags]
-          elif tags[0].startswith('adj'):
-            start = None
-            if any(form['form'].endswith(end) for end in [u'cy', u'ca', u'ce',
-                   u'cą', u'cego', u'cej', u'cemu', u'cym', u'cych', u'cymi']):
-              start = 'pact'
-            else:
-              start = 'ppas'
-            if start:
-              fixed = [start + tag[len('adj'):] for tag in tags]
-          if fixed:
-            new_tags.append('+'.join(fixed))
-    if new_tags:
-      form['tags'] = new_tags
-      new_forms.append(form)
-    else:
-      if pos == 'adj' and 'adv' in (tag.split(':')[0] for tag in form['tags']):
-        form['tags'] = [tag for tag in form['tags'] if tag.startswith('adv')]
-        other_lexemes.append([form])
-        nie_prefix = ''
-        while forms[0]['form'].startswith(nie_prefix):
-          nie_prefix += 'nie'
-        if not form['form'].startswith(nie_prefix):
-          print >>sys.stderr, (u'advadj: %s %s' % (form['form'], forms[0]['form'])).encode('utf-8')
-      else:
-        form['tags'] = [pos + ':irreg']
-        new_forms.append(form)
-      #print >>sys.stderr, (u'odrzucona forma: %s %s [%s]' %
-      #                     (form['form'], ', '.join(form['tags']), pos)).encode('utf-8')
-
-#  if len(new_forms[0]['tags']) == 1:
-#    if pos not in base_tag:
-#      base_tag[pos] = set()
-#    base_tag[pos].add(new_forms[0]['tags'][0])
-
-  if pos == 'subst':
-    # ujednoznacznić rodzaj... niezguła, sezamek
-    genders = set(tag[-1][0] for tag in all_tags(new_forms[0]))
-    if len(genders) == 1:
-      gender = list(genders)[0]
+    base_form_tags = (tag for tag, base
+                      in zip(forms[0]['tags'], forms[0]['base'])
+                      if base and base_tag(tag))
+    possible_pos = set(tag.split(':')[0] for tag in base_form_tags)
+    entry = forms[0]['form']
+    if forms[0]['tags'][0] == '-':
+        print >> sys.stderr, (u'%s: nierozpoznana forma podstawowa' %
+                              entry).encode('utf-8')
+        return None, None
+    if len(possible_pos) == 1:
+        pos = list(possible_pos)[0]
     else:
-      genders = set(tag[-1][0] for tag in all_tags(new_forms[0], filter_base=True))
-      if len(genders) == 1:
-        gender = list(genders)[0]
-      else:
-        good_genders = []
-        for gender in genders:
-          for form in new_forms:
+        print >> sys.stderr, (u'%s: niejednoznaczna część mowy' %
+                              entry).encode('utf-8')
+        return None, None
+    cats = form_categories.get(pos, [pos])
+    new_forms = []
+    other_lexemes = []
+    for form in forms:
+        new_tags = []
+        for tag, base in zip(form['tags'], form['base']):
+            for cat in cats:
+                if tag.startswith(cat) and base:
+                    new_tags.append(tag)
+                    break
+            else: # nie pasowało
+                if pos == 'verb':
+                    tags = tag.split('+')
+                    fixed = None
+                    if tags[0].startswith('subst'):
+                        fixed = ['subst:ger' + tag[len('subst'):] for tag in
+                                 tags]
+                    elif tags[0].startswith('adj'):
+                        start = None
+                        if any(form['form'].endswith(end) for end in
+                               [u'cy', u'ca', u'ce',
+                                u'cą', u'cego', u'cej', u'cemu', u'cym',
+                                u'cych', u'cymi']):
+                            start = 'pact'
+                        else:
+                            start = 'ppas'
+                        if start:
+                            fixed = [start + tag[len('adj'):] for tag in tags]
+                    if fixed:
+                        new_tags.append('+'.join(fixed))
+        if new_tags:
+            form['tags'] = new_tags
+            new_forms.append(form)
+        else:
+            if pos == 'adj' and 'adv' in (tag.split(':')[0] for tag in
+                                          form['tags']):
+                form['tags'] = [tag for tag in form['tags'] if
+                                tag.startswith('adv')]
+                other_lexemes.append([form])
+                nie_prefix = ''
+                while forms[0]['form'].startswith(nie_prefix):
+                    nie_prefix += 'nie'
+                if not form['form'].startswith(nie_prefix):
+                    print >> sys.stderr, (
+                    u'advadj: %s %s' % (form['form'], forms[0]['form'])).encode(
+                        'utf-8')
+            else:
+                form['tags'] = [pos + ':irreg']
+                new_forms.append(form)
+                #print >>sys.stderr, (u'odrzucona forma: %s %s [%s]' %
+                #                     (form['form'], ', '.join(form['tags']), pos)).encode('utf-8')
+
+            #  if len(new_forms[0]['tags']) == 1:
+            #    if pos not in base_tag:
+            #      base_tag[pos] = set()
+            #    base_tag[pos].add(new_forms[0]['tags'][0])
+
+    if pos == 'subst':
+        # ujednoznacznić rodzaj... niezguła, sezamek
+        genders = set(tag[-1][0] for tag in all_tags(new_forms[0]))
+        if len(genders) == 1:
+            gender = list(genders)[0]
+        else:
+            genders = set(
+                tag[-1][0] for tag in all_tags(new_forms[0], filter_base=True))
+            if len(genders) == 1:
+                gender = list(genders)[0]
+            else:
+                good_genders = []
+                for gender in genders:
+                    for form in new_forms:
+                        for tag in all_tags(form):
+                            if tag[-1][0] in (gender, 'i'):
+                                break # jest
+                        else: # nie ma
+                            break
+                    else: # ok
+                        good_genders.append(gender)
+                if len(good_genders) != 1:
+                    print >> sys.stderr, (
+                    u'%s: nie da się ujednoznacznić rodzaju' %
+                    entry).encode('utf-8')
+                    return None, None
+                gender = good_genders[0]
+            # znamy rodzaj, przesiewamy
+        for form in new_forms:
+            good_tags = []
             for tag in all_tags(form):
-              if tag[-1][0] in (gender, 'i'):
-                break # jest
-            else: # nie ma
-              break
-          else: # ok
-            good_genders.append(gender)
-        if len(good_genders) != 1:
-          print >> sys.stderr, (u'%s: nie da się ujednoznacznić rodzaju' %
-                                entry).encode('utf-8')
-          return None, None
-        gender = good_genders[0]
-    # znamy rodzaj, przesiewamy
-    for form in new_forms:
-      good_tags = []
-      for tag in all_tags(form):
-        if tag[-1][0] in (gender, 'i') or (tag[-1] == 'depr' and gender == 'm'):
-          good_tags.append(':'.join(tag))
-      if good_tags:
-        form['tags'] = good_tags
-      else:
-        form['tags'] = [pos + ':irreg']
-  return new_forms, other_lexemes
+                if tag[-1][0] in (gender, 'i') or (
+                        tag[-1] == 'depr' and gender == 'm'):
+                    good_tags.append(':'.join(tag))
+            if good_tags:
+                form['tags'] = good_tags
+            else:
+                form['tags'] = [pos + ':irreg']
+    return new_forms, other_lexemes
+
 
 def print_forms(forms):
-  for form in forms:
-    for tag in form['tags']:
-      print ('%s\t%s' % (form['form'], tag)).encode('utf-8')
-  print
+    for form in forms:
+        for tag in form['tags']:
+            print ('%s\t%s' % (form['form'], tag)).encode('utf-8')
+    print
+
 
 def parse_file(path):
-  with open(path) as file:
-    forms = []
-    for line in file:
-      line = line.decode('utf-8').rstrip('\n')
-      if line.startswith('Processed '):
-        break
-      if line == '':
-        disambiguated, other_lexemes = disamb_lexeme(forms)
-        if disambiguated:
-          print_forms(disambiguated)
-          for l in other_lexemes:
-            print_forms(l)
+    with open(path) as file:
         forms = []
-      else:
-        form, base, tag = line.split('\t')
-        if not forms:
-          entry = form
-        if not forms or form != forms[-1]['form']:
-          forms.append({'form': form, 'base': [], 'tags': []})
-        forms[-1]['tags'].append(tag)
-        forms[-1]['base'].append(
-          base == entry or tag == 'adv:comp'
-          or (tag.startswith('subst:pl') and 'nom' in tag)) # brzydko...
+        for line in file:
+            line = line.decode('utf-8').rstrip('\n')
+            if line.startswith('Processed '):
+                break
+            if line == '':
+                disambiguated, other_lexemes = disamb_lexeme(forms)
+                if disambiguated:
+                    print_forms(disambiguated)
+                    for l in other_lexemes:
+                        print_forms(l)
+                forms = []
+            else:
+                form, base, tag = line.split('\t')
+                if not forms:
+                    entry = form
+                if not forms or form != forms[-1]['form']:
+                    forms.append({'form': form, 'base': [], 'tags': []})
+                forms[-1]['tags'].append(tag)
+                forms[-1]['base'].append(
+                    base == entry or tag == 'adv:comp'
+                    or (
+                    tag.startswith('subst:pl') and 'nom' in tag)) # brzydko...
+
 #  for pos, tags in base_tag.iteritems():
 #    print ('base %s: %s' % (pos, ', '.join(tags))).encode('utf-8')
 
 if __name__ == '__main__':
-  import sys
-  parse_file(sys.argv[1])
+    import sys
+
+    parse_file(sys.argv[1])
diff --git a/dictionary/management/commands/edit_words.py b/dictionary/management/commands/edit_words.py
index a671d8d..2d381ce 100644
--- a/dictionary/management/commands/edit_words.py
+++ b/dictionary/management/commands/edit_words.py
@@ -1,24 +1,24 @@
 #-*- coding:utf-8 -*-
 
-import sys
-from django.core.management.base import BaseCommand, CommandError
-from common.util import debug
+from django.core.management.base import BaseCommand
 from accounts.util import bot_history
 from dictionary.models import Lexeme, Vocabulary
 
+
 class Command(BaseCommand):
-  args = '<input file name>'
-  help = 'Does something with a list of words'
+    args = '<input file name>'
+    help = 'Does something with a list of words'
+
+    def handle(self, filename, **options):
+        edit_words(open(filename))
 
-  def handle(self, filename, **options):
-    edit_words(open(filename))
 
 def edit_words(input_file):
-  bot_history()
-  anty = Vocabulary.objects.get(id='antyMorfeusz')
-  for line in input_file:
-    word = line.decode('utf-8').strip()
-    lexemes = Lexeme.objects.filter(entry=word)
-    for lexeme in lexemes:
-      anty.add_lexeme(lexeme)
-      # lexeme.save()
+    bot_history()
+    anty = Vocabulary.objects.get(id='antyMorfeusz')
+    for line in input_file:
+        word = line.decode('utf-8').strip()
+        lexemes = Lexeme.objects.filter(entry=word)
+        for lexeme in lexemes:
+            anty.add_lexeme(lexeme)
+            # lexeme.save()
diff --git a/dictionary/management/commands/export_lexemes.py b/dictionary/management/commands/export_lexemes.py
index 932a1c8..37c8849 100644
--- a/dictionary/management/commands/export_lexemes.py
+++ b/dictionary/management/commands/export_lexemes.py
@@ -2,9 +2,10 @@
 
 from dictionary.export import export_lexemes
 
+
 class Command(BaseCommand):
-  args = 'none'
-  help = 'Temporary export script'
+    args = 'none'
+    help = 'Temporary export script'
 
-  def handle(self, **options):
-    export_lexemes()
+    def handle(self, **options):
+        export_lexemes()
diff --git a/dictionary/management/commands/extra_crs.py b/dictionary/management/commands/extra_crs.py
index dc7940c..bcf2452 100644
--- a/dictionary/management/commands/extra_crs.py
+++ b/dictionary/management/commands/extra_crs.py
@@ -9,174 +9,187 @@ from dictionary.models import Lexeme, Vocabulary, CrossReference
 # Nie wiem, czy warto to poprawiać...
 
 class Command(BaseCommand):
-  args = '<type> <input file>'
-  help = 'Adds extra cross-references'
+    args = '<type> <input file>'
+    help = 'Adds extra cross-references'
+
+    def handle(self, type, input_file, **options):
+        return
+        add_crs(type, input_file)
 
-  def handle(self, type, input_file, **options):
-    return
-    add_crs(type, input_file)
 
 def debug(entry, text):
-  print>>sys.stderr, (u'%s: %s' % (entry, text)).encode('utf-8')
+    print>> sys.stderr, (u'%s: %s' % (entry, text)).encode('utf-8')
+
 
 def connect_real(from_l, to_l, cr_type):
-  created1 = created2 = False
-  if from_l.source == 'Morfologik':
-    cr1, created1 = CrossReference.objects.get_or_create(
-      from_lexeme=from_l, to_lexeme=to_l, type=cr_type[0])
-  if to_l.source == 'Morfologik':
-    cr2, created2 = CrossReference.objects.get_or_create(
-      from_lexeme=to_l, to_lexeme=from_l, type=cr_type[1])
-  if created1 or created2:
-    debug(from_l.entry, u'Powiązano z %s' % to_l.entry)
+    created1 = created2 = False
+    if from_l.source == 'Morfologik':
+        cr1, created1 = CrossReference.objects.get_or_create(
+            from_lexeme=from_l, to_lexeme=to_l, type=cr_type[0])
+    if to_l.source == 'Morfologik':
+        cr2, created2 = CrossReference.objects.get_or_create(
+            from_lexeme=to_l, to_lexeme=from_l, type=cr_type[1])
+    if created1 or created2:
+        debug(from_l.entry, u'Powiązano z %s' % to_l.entry)
+
 
 def connect_dummy(from_l, to_l, cr_type):
-  created1 = not CrossReference.objects.filter(
-    from_lexeme=from_l, to_lexeme=to_l, type=cr_type[0])
-  created2 = not CrossReference.objects.filter(
-    from_lexeme=to_l, to_lexeme=from_l, type=cr_type[1])
-  if created1 or created2:
-    debug(from_l.entry, u'Powiązanoby z %s' % to_l.entry)
-    if 'Morfologik' not in (from_l.source, to_l.source):
-      debug(from_l.entry, u'Powiązanoby leksemy spoza Morfologika!')
+    created1 = not CrossReference.objects.filter(
+        from_lexeme=from_l, to_lexeme=to_l, type=cr_type[0])
+    created2 = not CrossReference.objects.filter(
+        from_lexeme=to_l, to_lexeme=from_l, type=cr_type[1])
+    if created1 or created2:
+        debug(from_l.entry, u'Powiązanoby z %s' % to_l.entry)
+        if 'Morfologik' not in (from_l.source, to_l.source):
+            debug(from_l.entry, u'Powiązanoby leksemy spoza Morfologika!')
+
 
 connect = connect_dummy
 
+
 def make_detail(qs, desc, morf, details):
-  if qs.count() > 1:
-    morf_count = qs.filter(pk__in=morf).count()
-    details.append(
-      u'%s: %s, w tym z Morfologika: %s' % (desc, qs.count(), morf_count))
+    if qs.count() > 1:
+        morf_count = qs.filter(pk__in=morf).count()
+        details.append(
+            u'%s: %s, w tym z Morfologika: %s' % (desc, qs.count(), morf_count))
+
 
 def which_lacks(qs1, desc1, qs2, desc2):
-  if qs2.count() > 0:
-    return desc2
-  elif qs1.count() > 0:
-    return desc1
-  else:
-    return u'obu'
+    if qs2.count() > 0:
+        return desc2
+    elif qs1.count() > 0:
+        return desc1
+    else:
+        return u'obu'
 
 
 # dużo copypasty, ale chyba nie warto refaktoryzować
 def add_crs(type, path):
-  no_history()
-  morfologik = Vocabulary.objects.get(id='Morfologik')
-  morf = morfologik.owned_lexemes_pk()
-  lexemes = Lexeme.objects.filter(
-    lexemeassociation__vocabulary__id='Morfologik')
-  adv = lexemes.filter(part_of_speech__symbol__in=('adv', 'advndm'))
-  adj = lexemes.filter(part_of_speech__symbol='adj')
-  advcom = lexemes.filter(part_of_speech__symbol='advcom')
-  with open(path) as file:
-    if type == 'advnie':
-      cr_type = ('nieadj', 'adjnie')
-      for line in file:
-        advneg_e, base_e = line.strip().decode('utf-8').split()
-        advnegs = adv.filter(entry=advneg_e)
-        if adv.filter(entry=base_e):
-          advs = adv.filter(entry=base_e)
-          if advnegs.count() > 1 or advs.count() > 1:
-            details = []
-            make_detail(advnegs, u'zanegowane', morf, details)
-            make_detail(advs, u'niezanegowane', morf, details)
-            debug(advneg_e, u'Niejednoznaczność: %s' % '; '.join(details))
-          elif advnegs.count() == 0 or advs.count() == 0:
-            lack = which_lacks(
-              advnegs, u'zanegowanego', advs, u'niezanegowanego')
-            debug(advneg_e, u'Brak %s' % lack)
-          else:
-            connect(advnegs[0], advs[0], cr_type)
-        elif adj.filter(entry=base_e):
-          # najpierw trzeba odpalić advadj!
-          adjs = adj.filter(
-            entry=base_e, refs_to__type='adjadv',
-            refs_to__to_lexeme__deleted=False)
-          adjs = adjs | adj.filter(
-            entry=base_e, refs_from__type='advadj',
-            refs_from__from_lexeme__deleted=False)
-          adjs = adjs.distinct()
-          if advnegs.count() > 1 or adjs.count() > 1:
-            details = []
-            make_detail(advnegs, u'zanegowane', morf, details)
-            make_detail(adjs, u'przymiotniki', morf, details)
-            debug(advneg_e, u'Niejednoznaczność: %s' % '; '.join(details))
-          elif advnegs.count() == 0 or adjs.count() == 0:
-            lack = which_lacks(
-              advnegs, u'zanegowanego', adjs, u'przymiotnika')
-            debug(advneg_e, u'Brak %s' % lack)
-          else:
-            advs = [cr.to_lexeme.pk for cr
-                    in adjs[0].refs_to.filter(type='adjadv')]
-            advs += [cr.from_lexeme.pk for cr
-                     in adjs[0].refs_from.filter(type='advadj')]
-            advs = adv.filter(pk__in=advs).distinct()
-            if len(advs) > 1:
-              details = []
-              make_detail(advs, u'niezanegowane', morf, details)
-              debug(advneg_e, u'Niejednoznaczność: %s' % '; '.join(details))
-            elif len(advs) == 0:
-              debug(advneg_e, u'Brak niezanegowanego')
-            else:
-              connect(advnegs[0], advs[0], cr_type)
-        else:
-          debug(advneg_e, u'Brak drugiego leksemu [przymiotnik lub przysłówek]')
-    elif type == 'advadj':
-      cr_type = ('advadj', 'adjadv')
-      for line in file:
-        adv_e, adj_e = line.strip().decode('utf-8').split()
-        advs = adv.filter(entry=adv_e, part_of_speech__symbol='adv')
-        adjs = adj.filter(entry=adj_e, patterns__name__contains='').distinct()
-        if advs.count() > 1 or adjs.count() > 1:
-          details = []
-          make_detail(advs, u'przysłówki', morf, details)
-          make_detail(adjs, u'przymiotniki', morf, details)
-          debug(adv_e, u'Niejednoznaczność: %s' % '; '.join(details))
-        elif advs.count() == 0 or adjs.count() == 0:
-          lack = which_lacks(advs, u'przysłówka', adjs, u'przymiotnika')
-          debug(adv_e, u'Brak %s' % lack)
-        else:
-          connect(advs[0], adjs[0], cr_type)
-    elif type == 'advcom':
-      cr_type = ('advcom', 'comadv')
-      for line in file:
-        com_e, adv_e = line.strip().decode('utf-8').split()
-        advs = adv.filter(entry=adv_e)
-        coms = advcom.filter(entry=com_e)
-        if advs.count() > 1 or coms.count() > 1:
-          details = []
-          make_detail(advs, u'równe', morf, details)
-          make_detail(coms, u'wyższe', morf, details)
-          debug(adv_e, u'Niejednoznaczność: %s' % '; '.join(details))
-        elif advs.count() == 0 or coms.count() == 0:
-          lack = which_lacks(advs, u'równego', coms, u'wyższego')
-          debug(adv_e, u'Brak %s' % lack)
-        else:
-          connect(advs[0], coms[0], cr_type)
-    elif type == 'adjadvc': # do puszczenia na koniec
-      cr_type = ('adjadvc', 'advcadj')
-      # uch!
-      advs = Lexeme.objects.filter(
-        refs_to__type='advadj', refs_to__to_lexeme__deleted=False)
-      advs = advs | Lexeme.objects.filter(
-        refs_from__type='adjadv', refs_from__from_lexeme__deleted=False)
-      advs_with_com = advs.filter(
-        refs_to__type='advcom', refs_to__to_lexeme__deleted=False)
-      advs_with_com = advs_with_com | advs.filter(
-        refs_from__type='comadv', refs_from__from_lexeme__deleted=False)
-      advs = advs_with_com.distinct()
-      for adv in advs:
-        adjs = Lexeme.objects.filter(
-          refs_to__type='adjadv', refs_to__to_lexeme=adv,
-          refs_to__to_lexeme__deleted=False)
-        adjs = adjs | Lexeme.objects.filter(
-          refs_from__type='advadj', refs_from__from_lexeme=adv)
-        adjs = adjs.distinct()
-        advcoms = Lexeme.objects.filter(
-          refs_to__type='comadv', refs_to__to_lexeme=adv,
-          refs_to__to_lexeme__deleted=False)
-        advcoms = advcoms | Lexeme.objects.filter(
-          refs_from__type='advcom', refs_from__from_lexeme=adv)
-        for adj in adjs:
-          for advcom in advcoms:
-            if not adj.refs_to.filter(to_lexeme=advcom, type='adjadvc'):
-              connect(adj, advcom, cr_type)
+    no_history()
+    morfologik = Vocabulary.objects.get(id='Morfologik')
+    morf = morfologik.owned_lexemes_pk()
+    lexemes = Lexeme.objects.filter(
+        lexemeassociation__vocabulary__id='Morfologik')
+    adv = lexemes.filter(part_of_speech__symbol__in=('adv', 'advndm'))
+    adj = lexemes.filter(part_of_speech__symbol='adj')
+    advcom = lexemes.filter(part_of_speech__symbol='advcom')
+    with open(path) as file:
+        if type == 'advnie':
+            cr_type = ('nieadj', 'adjnie')
+            for line in file:
+                advneg_e, base_e = line.strip().decode('utf-8').split()
+                advnegs = adv.filter(entry=advneg_e)
+                if adv.filter(entry=base_e):
+                    advs = adv.filter(entry=base_e)
+                    if advnegs.count() > 1 or advs.count() > 1:
+                        details = []
+                        make_detail(advnegs, u'zanegowane', morf, details)
+                        make_detail(advs, u'niezanegowane', morf, details)
+                        debug(advneg_e,
+                              u'Niejednoznaczność: %s' % '; '.join(details))
+                    elif advnegs.count() == 0 or advs.count() == 0:
+                        lack = which_lacks(
+                            advnegs, u'zanegowanego', advs, u'niezanegowanego')
+                        debug(advneg_e, u'Brak %s' % lack)
+                    else:
+                        connect(advnegs[0], advs[0], cr_type)
+                elif adj.filter(entry=base_e):
+                    # najpierw trzeba odpalić advadj!
+                    adjs = adj.filter(
+                        entry=base_e, refs_to__type='adjadv',
+                        refs_to__to_lexeme__deleted=False)
+                    adjs = adjs | adj.filter(
+                        entry=base_e, refs_from__type='advadj',
+                        refs_from__from_lexeme__deleted=False)
+                    adjs = adjs.distinct()
+                    if advnegs.count() > 1 or adjs.count() > 1:
+                        details = []
+                        make_detail(advnegs, u'zanegowane', morf, details)
+                        make_detail(adjs, u'przymiotniki', morf, details)
+                        debug(advneg_e,
+                              u'Niejednoznaczność: %s' % '; '.join(details))
+                    elif advnegs.count() == 0 or adjs.count() == 0:
+                        lack = which_lacks(
+                            advnegs, u'zanegowanego', adjs, u'przymiotnika')
+                        debug(advneg_e, u'Brak %s' % lack)
+                    else:
+                        advs = [cr.to_lexeme.pk for cr
+                                in adjs[0].refs_to.filter(type='adjadv')]
+                        advs += [cr.from_lexeme.pk for cr
+                                 in adjs[0].refs_from.filter(type='advadj')]
+                        advs = adv.filter(pk__in=advs).distinct()
+                        if len(advs) > 1:
+                            details = []
+                            make_detail(advs, u'niezanegowane', morf, details)
+                            debug(advneg_e,
+                                  u'Niejednoznaczność: %s' % '; '.join(details))
+                        elif len(advs) == 0:
+                            debug(advneg_e, u'Brak niezanegowanego')
+                        else:
+                            connect(advnegs[0], advs[0], cr_type)
+                else:
+                    debug(advneg_e,
+                          u'Brak drugiego leksemu [przymiotnik lub przysłówek]')
+        elif type == 'advadj':
+            cr_type = ('advadj', 'adjadv')
+            for line in file:
+                adv_e, adj_e = line.strip().decode('utf-8').split()
+                advs = adv.filter(entry=adv_e, part_of_speech__symbol='adv')
+                adjs = adj.filter(entry=adj_e,
+                                  patterns__name__contains='').distinct()
+                if advs.count() > 1 or adjs.count() > 1:
+                    details = []
+                    make_detail(advs, u'przysłówki', morf, details)
+                    make_detail(adjs, u'przymiotniki', morf, details)
+                    debug(adv_e, u'Niejednoznaczność: %s' % '; '.join(details))
+                elif advs.count() == 0 or adjs.count() == 0:
+                    lack = which_lacks(advs, u'przysłówka', adjs,
+                                       u'przymiotnika')
+                    debug(adv_e, u'Brak %s' % lack)
+                else:
+                    connect(advs[0], adjs[0], cr_type)
+        elif type == 'advcom':
+            cr_type = ('advcom', 'comadv')
+            for line in file:
+                com_e, adv_e = line.strip().decode('utf-8').split()
+                advs = adv.filter(entry=adv_e)
+                coms = advcom.filter(entry=com_e)
+                if advs.count() > 1 or coms.count() > 1:
+                    details = []
+                    make_detail(advs, u'równe', morf, details)
+                    make_detail(coms, u'wyższe', morf, details)
+                    debug(adv_e, u'Niejednoznaczność: %s' % '; '.join(details))
+                elif advs.count() == 0 or coms.count() == 0:
+                    lack = which_lacks(advs, u'równego', coms, u'wyższego')
+                    debug(adv_e, u'Brak %s' % lack)
+                else:
+                    connect(advs[0], coms[0], cr_type)
+        elif type == 'adjadvc': # do puszczenia na koniec
+            cr_type = ('adjadvc', 'advcadj')
+            # uch!
+            advs = Lexeme.objects.filter(
+                refs_to__type='advadj', refs_to__to_lexeme__deleted=False)
+            advs = advs | Lexeme.objects.filter(
+                refs_from__type='adjadv', refs_from__from_lexeme__deleted=False)
+            advs_with_com = advs.filter(
+                refs_to__type='advcom', refs_to__to_lexeme__deleted=False)
+            advs_with_com = advs_with_com | advs.filter(
+                refs_from__type='comadv', refs_from__from_lexeme__deleted=False)
+            advs = advs_with_com.distinct()
+            for adv in advs:
+                adjs = Lexeme.objects.filter(
+                    refs_to__type='adjadv', refs_to__to_lexeme=adv,
+                    refs_to__to_lexeme__deleted=False)
+                adjs = adjs | Lexeme.objects.filter(
+                    refs_from__type='advadj', refs_from__from_lexeme=adv)
+                adjs = adjs.distinct()
+                advcoms = Lexeme.objects.filter(
+                    refs_to__type='comadv', refs_to__to_lexeme=adv,
+                    refs_to__to_lexeme__deleted=False)
+                advcoms = advcoms | Lexeme.objects.filter(
+                    refs_from__type='advcom', refs_from__from_lexeme=adv)
+                for adj in adjs:
+                    for advcom in advcoms:
+                        if not adj.refs_to.filter(to_lexeme=advcom,
+                                                  type='adjadvc'):
+                            connect(adj, advcom, cr_type)
diff --git a/dictionary/management/commands/filter_new.py b/dictionary/management/commands/filter_new.py
index 372c000..81e2020 100644
--- a/dictionary/management/commands/filter_new.py
+++ b/dictionary/management/commands/filter_new.py
@@ -3,69 +3,72 @@
 from django.core.management.base import BaseCommand
 from dictionary.models import Vocabulary, Lexeme
 
+
 class Command(BaseCommand):
-  args = '<input file>'
-  help = 'blah'
+    args = '<input file>'
+    help = 'blah'
+
+    def handle(self, input_file, **options):
+        filter_new(open(input_file))
 
-  def handle(self, input_file, **options):
-    filter_new(open(input_file))
 
 def output(text):
-  print text.encode('utf-8')
+    print text.encode('utf-8')
+
 
 def filter_new(input_file):
-  for line in input_file:
-    line = line.decode('utf-8').strip()
-    entry = line.split(':')[0]
-    not_found = (line.split(':')[1] == 'notfound')
-    if not not_found:
-      pos, ic, forms = line.split(':')[1].split(';')
-      lexemes = Lexeme.objects.distinct().filter(
-        vocabularies__id__in=('Morfologik', 'zbytkiM'), entry=entry)
-      if pos == 'subst':
-        lexemes = lexemes.filter(part_of_speech__symbol__in=(
-          'subst', 'osc', 'skrs'))
-      else:
-        lexemes = lexemes.filter(part_of_speech__symbol=pos)
-      if ic == 'm':
-        lexemes = lexemes.filter(
-          lexemeinflectionpattern__inflection_characteristic__symbol__in=(
-            'm1', 'm2', 'm3')
-        )
-      elif ic == 'ndk/dk':
-        lexemes = lexemes.filter(
-          lexemeinflectionpattern__inflection_characteristic__symbol__in=(
-            'ndk/dk', 'dk/ndk', 'ndk/(dk)', 'dk/(ndk)')
-        )
-      elif ic == 'qndk': # jakoś nie ma qdk
-        lexemes = lexemes.filter(
-          lexemeinflectionpattern__inflection_characteristic__symbol__in=(
-            'qndk', 'qdk', 'qndk/(dk)', 'qndk/dk')
-        )
-      else:
-        lexemes = lexemes.filter(
-          lexemeinflectionpattern__inflection_characteristic__symbol=ic)
-      if len(lexemes) == 0:
-        not_found = True
-      elif len(lexemes) == 1:
-        output('FOUND: %s' % line)
-      else:
-        output('AMBIGUITY: %s' % line)
-    if not_found:
-      lexemes = Lexeme.objects.filter(
-        vocabularies__id__in=('Morfologik', 'zbytkiM'), entry=entry)
-      if len(lexemes) == 0:
-        output('NOT FOUND: %s' % line)
-      elif len(lexemes) == 1:
-        output('FOUND: %s (%s;%s)' % (
-          line, lexemes.get().part_of_speech.symbol,
-          lexemes.get().lip_data()['inflection_characteristics']
-        ))
-      else:
-        pos_set = set()
-        ic_set = set()
-        for l in lexemes:
-          pos_set.add(l.part_of_speech.symbol)
-          ic_set.add(l.lip_data()['inflection_characteristics'])
-        output('AMBIGUITY: %s (%s;%s)' % (
-          line, '|'.join(pos_set), '|'.join(ic_set)))
\ No newline at end of file
+    for line in input_file:
+        line = line.decode('utf-8').strip()
+        entry = line.split(':')[0]
+        not_found = (line.split(':')[1] == 'notfound')
+        if not not_found:
+            pos, ic, forms = line.split(':')[1].split(';')
+            lexemes = Lexeme.objects.distinct().filter(
+                vocabularies__id__in=('Morfologik', 'zbytkiM'), entry=entry)
+            if pos == 'subst':
+                lexemes = lexemes.filter(part_of_speech__symbol__in=(
+                    'subst', 'osc', 'skrs'))
+            else:
+                lexemes = lexemes.filter(part_of_speech__symbol=pos)
+            if ic == 'm':
+                lexemes = lexemes.filter(
+                    lexemeinflectionpattern__inflection_characteristic__symbol__in=(
+                        'm1', 'm2', 'm3')
+                )
+            elif ic == 'ndk/dk':
+                lexemes = lexemes.filter(
+                    lexemeinflectionpattern__inflection_characteristic__symbol__in=(
+                        'ndk/dk', 'dk/ndk', 'ndk/(dk)', 'dk/(ndk)')
+                )
+            elif ic == 'qndk': # jakoś nie ma qdk
+                lexemes = lexemes.filter(
+                    lexemeinflectionpattern__inflection_characteristic__symbol__in=(
+                        'qndk', 'qdk', 'qndk/(dk)', 'qndk/dk')
+                )
+            else:
+                lexemes = lexemes.filter(
+                    lexemeinflectionpattern__inflection_characteristic__symbol=ic)
+            if len(lexemes) == 0:
+                not_found = True
+            elif len(lexemes) == 1:
+                output('FOUND: %s' % line)
+            else:
+                output('AMBIGUITY: %s' % line)
+        if not_found:
+            lexemes = Lexeme.objects.filter(
+                vocabularies__id__in=('Morfologik', 'zbytkiM'), entry=entry)
+            if len(lexemes) == 0:
+                output('NOT FOUND: %s' % line)
+            elif len(lexemes) == 1:
+                output('FOUND: %s (%s;%s)' % (
+                    line, lexemes.get().part_of_speech.symbol,
+                    lexemes.get().lip_data()['inflection_characteristics']
+                ))
+            else:
+                pos_set = set()
+                ic_set = set()
+                for l in lexemes:
+                    pos_set.add(l.part_of_speech.symbol)
+                    ic_set.add(l.lip_data()['inflection_characteristics'])
+                output('AMBIGUITY: %s (%s;%s)' % (
+                    line, '|'.join(pos_set), '|'.join(ic_set)))
\ No newline at end of file
diff --git a/dictionary/management/commands/fix_homonym.py b/dictionary/management/commands/fix_homonym.py
index 00fd299..4393c6f 100644
--- a/dictionary/management/commands/fix_homonym.py
+++ b/dictionary/management/commands/fix_homonym.py
@@ -1,27 +1,28 @@
 #-*- coding:utf-8 -*-
 
-import sys
-from django.core.management.base import BaseCommand, CommandError
+from django.core.management.base import BaseCommand
 from django.db.models import Count
 from common.util import no_history
 from dictionary.models import Lexeme
 
+
 class Command(BaseCommand):
-  args = 'none'
-  help = 'fixes homonym numbers'
+    args = 'none'
+    help = 'fixes homonym numbers'
+
+    def handle(self, **options):
+        fix_homonym()
 
-  def handle(self, **options):
-    fix_homonym()
 
 def fix_homonym():
-  no_history()
-  homonyms = (
-    Lexeme.objects.values('entry', 'part_of_speech')
-    .annotate(count=Count('pk')).filter(count__gt=1))
-  for homonym in homonyms:
-    lexemes = Lexeme.objects.filter(
-      entry=homonym['entry'],
-      part_of_speech=homonym['part_of_speech']).order_by('pk')
-    for i, lexeme in enumerate(lexemes, 1):
-      lexeme.homonym_number = i
-      lexeme.save()
\ No newline at end of file
+    no_history()
+    homonyms = (
+        Lexeme.objects.values('entry', 'part_of_speech')
+        .annotate(count=Count('pk')).filter(count__gt=1))
+    for homonym in homonyms:
+        lexemes = Lexeme.objects.filter(
+            entry=homonym['entry'],
+            part_of_speech=homonym['part_of_speech']).order_by('pk')
+        for i, lexeme in enumerate(lexemes, 1):
+            lexeme.homonym_number = i
+            lexeme.save()
\ No newline at end of file
diff --git a/dictionary/management/commands/fix_morfologik.py b/dictionary/management/commands/fix_morfologik.py
index a1b5980..191858f 100644
--- a/dictionary/management/commands/fix_morfologik.py
+++ b/dictionary/management/commands/fix_morfologik.py
@@ -4,71 +4,77 @@ import sys
 from django.core.management.base import BaseCommand, CommandError
 from common.util import no_history, debug
 from dictionary.models import Lexeme, Pattern, Vocabulary, \
-  Qualifier, InflectionCharacteristic
+    Qualifier, InflectionCharacteristic
+
 
 class Command(BaseCommand):
-  args = 'none'
-  help = 'Fixes various issues with Morfologik import'
+    args = 'none'
+    help = 'Fixes various issues with Morfologik import'
+
+    def handle(self, **options):
+        fix_morfologik()
 
-  def handle(self, **options):
-    fix_morfologik()
 
 morfologik = Vocabulary.objects.get(id='Morfologik')
 morf = morfologik.owned_lexemes_pk()
 existing = Lexeme.objects # usunięte są odsiewane automatycznie
 
+
 def sgtant_qualifiers():
-  sgtant = existing.filter(comment__contains='singulare tantum')
-  q, created = Qualifier.objects.get_or_create(
-    label='zwykle lp', vocabulary=morfologik)
-  for l in sgtant:
-    l.qualifiers.add(q) #add
+    sgtant = existing.filter(comment__contains='singulare tantum')
+    q, created = Qualifier.objects.get_or_create(
+        label='zwykle lp', vocabulary=morfologik)
+    for l in sgtant:
+        l.qualifiers.add(q) #add
+
 
 def cand_ndm():
-  for l in existing.filter(
-      status='desc', lexemeinflectionpattern__pattern__name='0000'):
-    l.status = 'cand'
-    l.save()
-  for l in existing.filter(
-      status='desc', lexemeinflectionpattern__pattern__name='P00'):
-    l.status = 'cand'
-    l.save()
-  for l in (existing.filter(
-      status='desc', lexemeinflectionpattern__pattern__name='ndm')
-            .exclude(part_of_speech__symbol='adv')):
-    l.status = 'cand'
-    l.save()
+    for l in existing.filter(
+            status='desc', lexemeinflectionpattern__pattern__name='0000'):
+        l.status = 'cand'
+        l.save()
+    for l in existing.filter(
+            status='desc', lexemeinflectionpattern__pattern__name='P00'):
+        l.status = 'cand'
+        l.save()
+    for l in (existing.filter(
+            status='desc', lexemeinflectionpattern__pattern__name='ndm')
+              .exclude(part_of_speech__symbol='adv')):
+        l.status = 'cand'
+        l.save()
+
 
 def fix_ow():
-  owy = existing.filter(
-    source='Morfologik', part_of_speech__symbol='subst',
-    entry__regex='^[A-ZĄĆĘŁŃÓŚŻŹ].*ów$')
-  m3 = InflectionCharacteristic.objects.get(
-    symbol='m3', part_of_speech__symbol='subst')
-  for l in owy:
-    for lip in l.lexemeinflectionpattern_set.all():
-      lip.inflection_characteristic = m3
-      lip.save()
-  debug(u'ów', u'%s poprawionych' % owy.count())
+    owy = existing.filter(
+        source='Morfologik', part_of_speech__symbol='subst',
+        entry__regex='^[A-ZĄĆĘŁŃÓŚŻŹ].*ów$')
+    m3 = InflectionCharacteristic.objects.get(
+        symbol='m3', part_of_speech__symbol='subst')
+    for l in owy:
+        for lip in l.lexemeinflectionpattern_set.all():
+            lip.inflection_characteristic = m3
+            lip.save()
+    debug(u'ów', u'%s poprawionych' % owy.count())
 
 # uwaga: nie sprawdza, czy po zmianie leksem nie jest identyczny z SGJP
 def fix_stwo():
-  stwo = existing.filter(
-    entry__endswith='stwo', source='Morfologik',
-    lexemeinflectionpattern__pattern__name='0173o')
-  p1 = InflectionCharacteristic.objects.get(
-    symbol='p1', part_of_speech__symbol='subst')
-  p0205 = Pattern.objects.get(name='0205')
-  for l in stwo:
-    for lip in l.lexemeinflectionpattern_set.all():
-      lip.inflection_characteristic = p1
-      lip.pattern = p0205
-      lip.save()
-  debug(u'stwo', u'%s poprawionych' % stwo.count())
+    stwo = existing.filter(
+        entry__endswith='stwo', source='Morfologik',
+        lexemeinflectionpattern__pattern__name='0173o')
+    p1 = InflectionCharacteristic.objects.get(
+        symbol='p1', part_of_speech__symbol='subst')
+    p0205 = Pattern.objects.get(name='0205')
+    for l in stwo:
+        for lip in l.lexemeinflectionpattern_set.all():
+            lip.inflection_characteristic = p1
+            lip.pattern = p0205
+            lip.save()
+    debug(u'stwo', u'%s poprawionych' % stwo.count())
+
 
 def fix_morfologik():
-  no_history()
-  sgtant_qualifiers()
-  cand_ndm()
-  fix_ow()
-  fix_stwo()
+    no_history()
+    sgtant_qualifiers()
+    cand_ndm()
+    fix_ow()
+    fix_stwo()
diff --git a/dictionary/management/commands/fix_osc.py b/dictionary/management/commands/fix_osc.py
index 16576c7..5c687d6 100644
--- a/dictionary/management/commands/fix_osc.py
+++ b/dictionary/management/commands/fix_osc.py
@@ -5,63 +5,68 @@ from django.core.management.base import BaseCommand, CommandError
 from common.util import no_history, debug
 from dictionary.models import Lexeme, Vocabulary, PartOfSpeech, CrossReference
 
+
 class Command(BaseCommand):
-  args = 'none'
-  help = 'Fixes osc'
+    args = 'none'
+    help = 'Fixes osc'
 
-  def handle(self, **options):
-    fix_osc()
+    def handle(self, **options):
+        fix_osc()
 
 # aktualnie łączymy tylko jeśli razem z -ością przyszedł odpowiedni przymiotnik
 # lub wersja niezanegowana (dla zanegowanych)
 
 def fix_osc():
-  no_history()
-  morfologik = Vocabulary.objects.get(id='Morfologik')
-  morf = morfologik.owned_lexemes_pk()
-  existing = Lexeme.objects
-  morf_osc = existing.filter(
-    pk__in=morf, part_of_speech__symbol='subst', entry__endswith=u'ość')
-  for lexeme in morf_osc:
-    if lexeme.entry.endswith(u'jość'):
-      base = lexeme.entry[:-4]
-    else:
-      base = lexeme.entry[:-3]
-    options = (base + 'i', base + 'y', base)
-    adjs = existing.filter(
-      pk__in=morf, part_of_speech__lexical_class__symbol='adj',
-      entry__in=options)
-    if adjs.count() > 1:
-      debug(lexeme.entry, u'Niejednoznaczny przymiotnik źródłowy')
-    if adjs:
-      lexeme.part_of_speech = PartOfSpeech.objects.get(symbol='osc')
-      lexeme.save()
-      negs = CrossReference.objects.filter(
-        from_lexeme__in=adjs, type__symbol='nieadj')
-      if negs:
-        # wszystkie przymiotniki z Morfologika mają negację nie+, nie nie-+
-        # wygląda na to, że w M nie ma nie-...-ości...
-        assert lexeme.entry.startswith('nie')
-        nonnegs = existing.filter(pk__in=morf, entry=lexeme.entry[4:])
-        if nonnegs.count() > 1:
-          debug(lexeme.entry, u'Niejednoznaczna wersja niezanegowana')
-        if not nonnegs:
-          debug(lexeme.entry, u'Nie znaleziono wersji niezanegowanej')
+    no_history()
+    morfologik = Vocabulary.objects.get(id='Morfologik')
+    morf = morfologik.owned_lexemes_pk()
+    existing = Lexeme.objects
+    morf_osc = existing.filter(
+        pk__in=morf, part_of_speech__symbol='subst', entry__endswith=u'ość')
+    for lexeme in morf_osc:
+        if lexeme.entry.endswith(u'jość'):
+            base = lexeme.entry[:-4]
         else:
-          for l in nonnegs:
-            cr = CrossReference(
-              from_lexeme=lexeme, to_lexeme=l, type__symbol='nieadj')
-            cr.save()
-            cr = CrossReference(
-              from_lexeme=l, to_lexeme=lexeme, type__symbol='adjnie')
-            cr.save()
-          debug(lexeme.entry, u'Dopisano jako negację osc')
-      else:
-        for adj in adjs:
-          cr = CrossReference(
-            from_lexeme=lexeme, to_lexeme=adj, type__symbol='oscadj')
-          cr.save()
-          cr = CrossReference(
-            from_lexeme=adj, to_lexeme=lexeme, type__symbol='adjosc')
-          cr.save()
-        debug(lexeme.entry, u'Dopisano jako osc')
+            base = lexeme.entry[:-3]
+        options = (base + 'i', base + 'y', base)
+        adjs = existing.filter(
+            pk__in=morf, part_of_speech__lexical_class__symbol='adj',
+            entry__in=options)
+        if adjs.count() > 1:
+            debug(lexeme.entry, u'Niejednoznaczny przymiotnik źródłowy')
+        if adjs:
+            lexeme.part_of_speech = PartOfSpeech.objects.get(symbol='osc')
+            lexeme.save()
+            negs = CrossReference.objects.filter(
+                from_lexeme__in=adjs, type__symbol='nieadj')
+            if negs:
+                # wszystkie przymiotniki z Morfologika mają negację nie+, nie nie-+
+                # wygląda na to, że w M nie ma nie-...-ości...
+                assert lexeme.entry.startswith('nie')
+                nonnegs = existing.filter(pk__in=morf, entry=lexeme.entry[4:])
+                if nonnegs.count() > 1:
+                    debug(lexeme.entry, u'Niejednoznaczna wersja niezanegowana')
+                if not nonnegs:
+                    debug(lexeme.entry, u'Nie znaleziono wersji niezanegowanej')
+                else:
+                    for l in nonnegs:
+                        cr = CrossReference(
+                            from_lexeme=lexeme, to_lexeme=l,
+                            type__symbol='nieadj')
+                        cr.save()
+                        cr = CrossReference(
+                            from_lexeme=l, to_lexeme=lexeme,
+                            type__symbol='adjnie')
+                        cr.save()
+                    debug(lexeme.entry, u'Dopisano jako negację osc')
+            else:
+                for adj in adjs:
+                    cr = CrossReference(
+                        from_lexeme=lexeme, to_lexeme=adj,
+                        type__symbol='oscadj')
+                    cr.save()
+                    cr = CrossReference(
+                        from_lexeme=adj, to_lexeme=lexeme,
+                        type__symbol='adjosc')
+                    cr.save()
+                debug(lexeme.entry, u'Dopisano jako osc')
diff --git a/dictionary/management/commands/fix_surnames.py b/dictionary/management/commands/fix_surnames.py
index 9199bb4..e783a1c 100644
--- a/dictionary/management/commands/fix_surnames.py
+++ b/dictionary/management/commands/fix_surnames.py
@@ -5,54 +5,57 @@ from django.core.management.base import BaseCommand, CommandError
 from common.util import no_history, debug
 from dictionary.models import Lexeme, Vocabulary
 
+
 class Command(BaseCommand):
-  args = 'none'
-  help = 'Fixes SGJP surnames which come from Morfologik as adjectives'
+    args = 'none'
+    help = 'Fixes SGJP surnames which come from Morfologik as adjectives'
+
+    def handle(self, **options):
+        fix_surnames()
 
-  def handle(self, **options):
-    fix_surnames()
 
 def fix_surnames():
-  no_history()
-  morfologik = Vocabulary.objects.get(id='Morfologik')
-  SGJP = Vocabulary.objects.get(id='SGJP')
-  morf = morfologik.owned_lexemes_pk()
-  sgjp = SGJP.owned_lexemes_pk()
-  existing = Lexeme.objects
-  sgjp_subst = existing.filter( # jak odsiewam po SGJP, to nic nie zostaje...
-    part_of_speech__symbol='subst',
-    entry__regex=u'^[A-ZĄĆĘŁŃÓŚŻŹ]')
-  morf_surnames = existing.filter(
-    pk__in=morf, part_of_speech__symbol='adj', entry__regex=u'^[A-ZĄĆĘŁŃÓŚŻŹ]')
-  subst_entries = set(sgjp_subst.values_list('entry', flat=True))
-  surnames_entries = set(morf_surnames.values_list('entry', flat=True))
-  entries = subst_entries & surnames_entries
-  lexemes = morf_surnames.filter(entry__in=entries)
-  for lexeme in lexemes:
-    if lexeme.entry[-1] not in 'iy':
-      debug(lexeme.entry, u'Nie jest nazwiskiem rodzaju męskiego')
-      continue
-    m = existing.filter(
-      pk__in=sgjp, entry=lexeme.entry, part_of_speech__symbol='subst',
-      lexemeinflectionpattern__inflection_characteristic__symbol='m1')
-    female = lexeme.entry[:-1] + 'a'
-    f = existing.filter(
-      pk__in=sgjp, entry=female, part_of_speech__symbol='subst',
-      lexemeinflectionpattern__inflection_characteristic__symbol='f')
-    if m.count() == 0 or f.count() == 0:
-      debug(lexeme.entry, u'Brak homonimu w SGJP')
-    elif m.count() > 1 or f.count() > 1:
-      debug(lexeme.entry, u'Niejednoznaczne homonimy w SGJP')
-    else:
-      m = m[0]
-      f = f[0]
-      if morfologik not in m.vocabularies.all():
-        morfologik.add_lexeme(m)
-      else:
-        debug(lexeme.entry, u'Już jest dopisany do Morfologika [m]')
-      if morfologik not in f.vocabularies.all():
-        morfologik.add_lexeme(f)
-      else:
-        debug(lexeme.entry, u'Już jest dopisany do Morfologika [f]')
-      lexeme.delete()
-      debug(lexeme.entry, u'Wykonano')
+    no_history()
+    morfologik = Vocabulary.objects.get(id='Morfologik')
+    SGJP = Vocabulary.objects.get(id='SGJP')
+    morf = morfologik.owned_lexemes_pk()
+    sgjp = SGJP.owned_lexemes_pk()
+    existing = Lexeme.objects
+    sgjp_subst = existing.filter(# jak odsiewam po SGJP, to nic nie zostaje...
+                                 part_of_speech__symbol='subst',
+                                 entry__regex=u'^[A-ZĄĆĘŁŃÓŚŻŹ]')
+    morf_surnames = existing.filter(
+        pk__in=morf, part_of_speech__symbol='adj',
+        entry__regex=u'^[A-ZĄĆĘŁŃÓŚŻŹ]')
+    subst_entries = set(sgjp_subst.values_list('entry', flat=True))
+    surnames_entries = set(morf_surnames.values_list('entry', flat=True))
+    entries = subst_entries & surnames_entries
+    lexemes = morf_surnames.filter(entry__in=entries)
+    for lexeme in lexemes:
+        if lexeme.entry[-1] not in 'iy':
+            debug(lexeme.entry, u'Nie jest nazwiskiem rodzaju męskiego')
+            continue
+        m = existing.filter(
+            pk__in=sgjp, entry=lexeme.entry, part_of_speech__symbol='subst',
+            lexemeinflectionpattern__inflection_characteristic__symbol='m1')
+        female = lexeme.entry[:-1] + 'a'
+        f = existing.filter(
+            pk__in=sgjp, entry=female, part_of_speech__symbol='subst',
+            lexemeinflectionpattern__inflection_characteristic__symbol='f')
+        if m.count() == 0 or f.count() == 0:
+            debug(lexeme.entry, u'Brak homonimu w SGJP')
+        elif m.count() > 1 or f.count() > 1:
+            debug(lexeme.entry, u'Niejednoznaczne homonimy w SGJP')
+        else:
+            m = m[0]
+            f = f[0]
+            if morfologik not in m.vocabularies.all():
+                morfologik.add_lexeme(m)
+            else:
+                debug(lexeme.entry, u'Już jest dopisany do Morfologika [m]')
+            if morfologik not in f.vocabularies.all():
+                morfologik.add_lexeme(f)
+            else:
+                debug(lexeme.entry, u'Już jest dopisany do Morfologika [f]')
+            lexeme.delete()
+            debug(lexeme.entry, u'Wykonano')
diff --git a/dictionary/management/commands/import_data.py b/dictionary/management/commands/import_data.py
index 26e041a..40ff699 100644
--- a/dictionary/management/commands/import_data.py
+++ b/dictionary/management/commands/import_data.py
@@ -22,681 +22,713 @@ OTHER = 'inne'
 DEFAULT_VOCAB = 'SGJP'
 
 ATTRS = {
-  u'zwrotność': (
-    (('v', 'ger', 'pact'), None),
-    (
-      (u'—', u''),
-      (u'się', u'się'),
-      (u'(się)', u'(się)'),
-      (u'sobie', u'sobie'),
-      (u'(sobie)', u'(sobie)'),
-      (u'się/sobie', u'się/sobie'),
+    u'zwrotność': (
+        (('v', 'ger', 'pact'), None),
+        (
+            (u'—', u''),
+            (u'się', u'się'),
+            (u'(się)', u'(się)'),
+            (u'sobie', u'sobie'),
+            (u'(sobie)', u'(sobie)'),
+            (u'się/sobie', u'się/sobie'),
+        ),
+        ('haslosuf', lambda suf: suf.strip(' ?') or u'—'),
     ),
-    ('haslosuf', lambda suf: suf.strip(' ?') or u'—'),
-  ),
-  u'przechodniość': (
-    (('v', 'pred'), None),
-    (
-      ('iT', u'nieprzechodni'),
-      ('qT', u'quasi-przechodni'),
-      ('T', u'przechodni'),
+    u'przechodniość': (
+        (('v', 'pred'), None),
+        (
+            ('iT', u'nieprzechodni'),
+            ('qT', u'quasi-przechodni'),
+            ('T', u'przechodni'),
+        ),
+        ('przechodniosc', lambda x: x),
     ),
-    ('przechodniosc', lambda x: x),
-  ),
-  u'aspekt': (
-    (('v', 'pred', 'ger', 'pact', 'ppas', 'appas'), None),
-    (
-      ('dk', u'dk'),
-      ('ndk', u'ndk'),
-      ('ndk/dk', u'ndk/dk'),
-      ('dk/ndk', u'dk/ndk'),
-      ('ndk/(dk)', u'ndk/(dk)'),
-      ('dk/(ndk)', u'dk/(ndk)'),
+    u'aspekt': (
+        (('v', 'pred', 'ger', 'pact', 'ppas', 'appas'), None),
+        (
+            ('dk', u'dk'),
+            ('ndk', u'ndk'),
+            ('ndk/dk', u'ndk/dk'),
+            ('dk/ndk', u'dk/ndk'),
+            ('ndk/(dk)', u'ndk/(dk)'),
+            ('dk/(ndk)', u'dk/(ndk)'),
+        ),
+        ('aspekt', lambda x: x),
     ),
-    ('aspekt', lambda x: x),
-  ),
-  u'właściwy': (
-    (('v', 'pred'), None),
-    (
-      ('Q', u'niewłaściwy'),
-      ('(Q)', u'właściwy/niewłaściwy'),
-      ('', u'właściwy'),
+    u'właściwy': (
+        (('v', 'pred'), None),
+        (
+            ('Q', u'niewłaściwy'),
+            ('(Q)', u'właściwy/niewłaściwy'),
+            ('', u'właściwy'),
+        ),
+        ('właściwy', lambda x: x),
     ),
-    ('właściwy', lambda x: x),
-  ),
-  u'depr': (
-    (('subst', 'skrs'), 'm1'),
-    (
-      ('n', u''),
-      ('d', u''),
-      ('nd', u''),
-    ),
-    ('depr', lambda x: x),
-  )
+    u'depr': (
+        (('subst', 'skrs'), 'm1'),
+        (
+            ('n', u''),
+            ('d', u''),
+            ('nd', u''),
+        ),
+        ('depr', lambda x: x),
+    )
 }
 
 # tymczasowa tabelka
 BASIC_FORM_LABELS = {
-  '0-': '1',
-  '3+': '1',
-  'f':  'sg:nom',
-  'm1': 'sg:nom',
-  'm2': 'sg:nom',
-  'm3': 'sg:nom',
-  'n1': 'sg:nom',
-  'n2': 'sg:nom',
-  'p1': 'pl:nom:mo',
-  'p2': 'pl:nom',
-  'p3': 'pl:nom',
-  'pri': 'sg:nom', # albo pl. teraz już naprawdę się nie da.
-  'sec': 'sg:nom',
+    '0-': '1',
+    '3+': '1',
+    'f': 'sg:nom',
+    'm1': 'sg:nom',
+    'm2': 'sg:nom',
+    'm3': 'sg:nom',
+    'n1': 'sg:nom',
+    'n2': 'sg:nom',
+    'p1': 'pl:nom:mo',
+    'p2': 'pl:nom',
+    'p3': 'pl:nom',
+    'pri': 'sg:nom', # albo pl. teraz już naprawdę się nie da.
+    'sec': 'sg:nom',
 }
 
 # to chyba nie jest najlepsze rozwiązanie...
 BASIC_FORM_LABELS_POS = {
-  'v': '5',
-  'ger': '11',
-  'pact': '3',
-  'ppas': '10',
-  'appas': '10',
-  'pred': '5',
+    'v': '5',
+    'ger': '11',
+    'pact': '3',
+    'ppas': '10',
+    'appas': '10',
+    'pred': '5',
 }
 
 TRANSLATE_CLASS = {
-  'h': 'header',
-  'c': 'header-c',
-  'b': 'blank',
-  'd': 'data',
+    'h': 'header',
+    'c': 'header-c',
+    'b': 'blank',
+    'd': 'data',
 }
 
+
 class Command(BaseCommand):
-  args = '<input db filename>'
-  help = 'Imports initial data'
+    args = '<input db filename>'
+    help = 'Imports initial data'
+
+    def handle(self, db_name=DEFAULT_DATABASE, **options):
+        ImportData(db_name).delete_and_import()
 
-  def handle(self, db_name=DEFAULT_DATABASE, **options):
-    ImportData(db_name).delete_and_import()
 
 def get_cursor(db):
-  conn = sqlite3.connect(db)
-  conn.row_factory = sqlite3.Row
-  return conn.cursor()
+    conn = sqlite3.connect(db)
+    conn.row_factory = sqlite3.Row
+    return conn.cursor()
+
 
 def bulk_create(model, objects):
-  model.objects.bulk_create(objects, batch_size=BATCH_SIZE)
+    model.objects.bulk_create(objects, batch_size=BATCH_SIZE)
+
 
 METHOD_NAMES = {
-  CrossReference: 'import_cross_references',
-  Ending: 'import_endings',
-  LexemeInflectionPattern: 'import_lexeme_inflection_patterns',
-  Lexeme: 'import_lexemes',
-  PatternType: 'import_pattern_types',
-  TableTemplate: 'import_tables',
-  BaseFormLabel: 'new_base_form_labels',
-  CrossReferenceType: 'new_cross_reference_types',
-  InflectionCharacteristic: 'new_inflection_characteristics',
-  LexemeAssociation: 'new_lexeme_associations',
-  LexicalClass: 'new_lexical_classes',
-  PartOfSpeech: 'new_parts_of_speech',
-  Pattern: 'new_patterns',
-  Qualifier: 'new_qualifiers',
-  TableHeader: 'new_table_headers',
-  Vocabulary: 'new_vocabularies',
+    CrossReference: 'import_cross_references',
+    Ending: 'import_endings',
+    LexemeInflectionPattern: 'import_lexeme_inflection_patterns',
+    Lexeme: 'import_lexemes',
+    PatternType: 'import_pattern_types',
+    TableTemplate: 'import_tables',
+    BaseFormLabel: 'new_base_form_labels',
+    CrossReferenceType: 'new_cross_reference_types',
+    InflectionCharacteristic: 'new_inflection_characteristics',
+    LexemeAssociation: 'new_lexeme_associations',
+    LexicalClass: 'new_lexical_classes',
+    PartOfSpeech: 'new_parts_of_speech',
+    Pattern: 'new_patterns',
+    Qualifier: 'new_qualifiers',
+    TableHeader: 'new_table_headers',
+    Vocabulary: 'new_vocabularies',
 }
 
+
 class ImportData(object):
-  def __init__(self, db):
-    transaction.commit_unless_managed()
-    transaction.enter_transaction_management()
-    transaction.managed()
-    self.cursor = connection.cursor()
-    self.sqlite_cursor = get_cursor(db)
-    no_history()
-
-  def close(self):
-    self.cursor.close()
-    self.sqlite_cursor.close()
-    transaction.commit()
-    transaction.leave_transaction_management()
-
-
-  def new_lexical_classes(self):
-    if not LexicalClass.objects.filter(symbol=OTHER).exists():
-      yield LexicalClass(symbol=OTHER)
-    for row in self.sqlite_cursor.execute('select distinct pos from wzory'):
-      if not LexicalClass.objects.filter(symbol=row['pos']).exists():
-        yield LexicalClass(symbol=row['pos'])
-
-  def cache_lc(self):
-    if 'lc' not in self.__dict__:
-      self.lc = dict((lc.symbol, lc) for lc in LexicalClass.objects.all())
-
-  def new_parts_of_speech(self):
-    lcs = {}
-    for row in self.sqlite_cursor.execute(
-        'select distinct wzory.pos, leksemy.pos from wzory '
-        'natural join odmieniasie join leksemy on leksemy.nr = odmieniasie.nr'):
-      lcs[row[1]] = row[0]
-
-    for row in self.sqlite_cursor.execute('SELECT * FROM klasygramatyczne'):
-      if not PartOfSpeech.objects.filter(symbol=row['pos']).exists():
-        lc = lcs.get(row['pos'], OTHER)
-        yield PartOfSpeech(
-          symbol=row['pos'],
-          full_name=row['nazwakl'],
-          index=row['klporz'],
-          color_scheme=row['posind'],
-          lexical_class = LexicalClass.objects.get(symbol=lc))
-
-  def cache_pos(self):
-    if 'pos' not in self.__dict__:
-      self.pos = dict((pos.symbol, pos) for pos in PartOfSpeech.objects.all())
-
-  def cache_lc_pos(self):
-    if 'lc_pos' not in self.__dict__:
-      self.lc_pos = dict(
-        (pos.symbol, pos.lexical_class) for pos in PartOfSpeech.objects.all()
-      )
-
-  def new_base_form_labels(self):
-    query_result = self.sqlite_cursor.execute("""
+    def __init__(self, db):
+        transaction.commit_unless_managed()
+        transaction.enter_transaction_management()
+        transaction.managed()
+        self.cursor = connection.cursor()
+        self.sqlite_cursor = get_cursor(db)
+        no_history()
+
+    def close(self):
+        self.cursor.close()
+        self.sqlite_cursor.close()
+        transaction.commit()
+        transaction.leave_transaction_management()
+
+
+    def new_lexical_classes(self):
+        if not LexicalClass.objects.filter(symbol=OTHER).exists():
+            yield LexicalClass(symbol=OTHER)
+        for row in self.sqlite_cursor.execute('select distinct pos from wzory'):
+            if not LexicalClass.objects.filter(symbol=row['pos']).exists():
+                yield LexicalClass(symbol=row['pos'])
+
+    def cache_lc(self):
+        if 'lc' not in self.__dict__:
+            self.lc = dict((lc.symbol, lc) for lc in LexicalClass.objects.all())
+
+    def new_parts_of_speech(self):
+        lcs = {}
+        for row in self.sqlite_cursor.execute(
+                'select distinct wzory.pos, leksemy.pos from wzory '
+                'natural join odmieniasie join leksemy on leksemy.nr = odmieniasie.nr'):
+            lcs[row[1]] = row[0]
+
+        for row in self.sqlite_cursor.execute('SELECT * FROM klasygramatyczne'):
+            if not PartOfSpeech.objects.filter(symbol=row['pos']).exists():
+                lc = lcs.get(row['pos'], OTHER)
+                yield PartOfSpeech(
+                    symbol=row['pos'],
+                    full_name=row['nazwakl'],
+                    index=row['klporz'],
+                    color_scheme=row['posind'],
+                    lexical_class=LexicalClass.objects.get(symbol=lc))
+
+    def cache_pos(self):
+        if 'pos' not in self.__dict__:
+            self.pos = dict(
+                (pos.symbol, pos) for pos in PartOfSpeech.objects.all())
+
+    def cache_lc_pos(self):
+        if 'lc_pos' not in self.__dict__:
+            self.lc_pos = dict(
+                (pos.symbol, pos.lexical_class) for pos in
+                PartOfSpeech.objects.all()
+            )
+
+    def new_base_form_labels(self):
+        query_result = self.sqlite_cursor.execute("""
       SELECT efobaz FROM paradygmaty
       UNION
       SELECT efobaz FROM zakonczenia
       """)
-    for row in query_result:
-      yield BaseFormLabel(symbol=row[0])
-
-  def cache_bfl(self):
-    if 'bfls' not in self.__dict__:
-      self.bfls = dict((bfl.symbol, bfl) for bfl in BaseFormLabel.objects.all())
-
-  def new_inflection_characteristics(self):
-    for row in self.sqlite_cursor.execute(
-            'SELECT DISTINCT charfl, pos FROM paradygmaty'):
-      if row['charfl'] == '':
-        bfl_symbol = '1' if row['pos'] in ('adj', 'adjcom') else ''
-      else:
-        bfl_symbol = BASIC_FORM_LABELS.get(row['charfl'], '')
-      if row['pos'] in BASIC_FORM_LABELS_POS:
-        bfl_symbol = BASIC_FORM_LABELS_POS[row['pos']]
-      bfl = BaseFormLabel.objects.get(symbol=bfl_symbol)
-      yield InflectionCharacteristic(
-        symbol=row['charfl'], basic_form_label=bfl,
-        part_of_speech=PartOfSpeech.objects.get(pk=row['pos']))
-
-  def cache_ics(self):
-    if 'ics' not in self.__dict__:
-      self.ics = dict(
-        ((ic.symbol, ic.part_of_speech.symbol), ic)
-        for ic in InflectionCharacteristic.objects.all()
-      )
-
-  def new_vocabularies(self):
-    result = self.sqlite_cursor.execute("""
+        for row in query_result:
+            yield BaseFormLabel(symbol=row[0])
+
+    def cache_bfl(self):
+        if 'bfls' not in self.__dict__:
+            self.bfls = dict(
+                (bfl.symbol, bfl) for bfl in BaseFormLabel.objects.all())
+
+    def new_inflection_characteristics(self):
+        for row in self.sqlite_cursor.execute(
+                'SELECT DISTINCT charfl, pos FROM paradygmaty'):
+            if row['charfl'] == '':
+                bfl_symbol = '1' if row['pos'] in ('adj', 'adjcom') else ''
+            else:
+                bfl_symbol = BASIC_FORM_LABELS.get(row['charfl'], '')
+            if row['pos'] in BASIC_FORM_LABELS_POS:
+                bfl_symbol = BASIC_FORM_LABELS_POS[row['pos']]
+            bfl = BaseFormLabel.objects.get(symbol=bfl_symbol)
+            yield InflectionCharacteristic(
+                symbol=row['charfl'], basic_form_label=bfl,
+                part_of_speech=PartOfSpeech.objects.get(pk=row['pos']))
+
+    def cache_ics(self):
+        if 'ics' not in self.__dict__:
+            self.ics = dict(
+                ((ic.symbol, ic.part_of_speech.symbol), ic)
+                for ic in InflectionCharacteristic.objects.all()
+            )
+
+    def new_vocabularies(self):
+        result = self.sqlite_cursor.execute("""
       SELECT slownik FROM leksemy
       UNION
       SELECT slownik_uz FROM slowniki_uzywajace
     """)
-    for row in result:
-      yield Vocabulary(id = row[0])
+        for row in result:
+            yield Vocabulary(id=row[0])
 
-  def cache_vocabs(self):
-    if 'vocabs' not in self.__dict__:
-      self.vocabs = dict((v.id, v) for v in Vocabulary.objects.all())
+    def cache_vocabs(self):
+        if 'vocabs' not in self.__dict__:
+            self.vocabs = dict((v.id, v) for v in Vocabulary.objects.all())
 
-  def new_qualifiers(self):
-    default = Vocabulary.objects.get(id=DEFAULT_VOCAB)
-    query_result = self.sqlite_cursor.execute("""
+    def new_qualifiers(self):
+        default = Vocabulary.objects.get(id=DEFAULT_VOCAB)
+        query_result = self.sqlite_cursor.execute("""
       SELECT okwal FROM odmieniasie
       UNION
       SELECT zkwal FROM zakonczenia
       UNION
       SELECT lkwal FROM leksemy
       """)
-    added = set()
-    for row in query_result:
-      if row[0]:
-        for qualifier_label in row[0].split('|'):
-          if qualifier_label not in added:
-            added.add(qualifier_label)
-            yield Qualifier(label=qualifier_label, vocabulary=default)
-
-  def cache_qualifiers(self):
-    if 'qual' not in self.__dict__:
-      self.qual = dict((q.label, q) for q in Qualifier.objects.all())
-
-  def create_attributes(self):
-    attr_values = {}
-    for attr_name, ((poses, ic), values, import_info) in ATTRS.iteritems():
-      la, created = LexemeAttribute.objects.get_or_create(
-        name=attr_name, closed=True, required=True, takes_ic=bool(ic))
-      for pos in PartOfSpeech.objects.filter(symbol__in=poses):
-        la.parts_of_speech.add(pos) #add
-        pos_ics = InflectionCharacteristic.objects.filter(
-          part_of_speech=pos, symbol=ic)
-        for ic0 in pos_ics:
-          la.inflection_characteristics.add(ic0) #add
-      values_cache = {}
-      for val, display_val in values:
-        values_cache[val], created = LexemeAttributeValue.objects.get_or_create(
-          value=val, display_value=display_val, attribute=la)
-      attr_values[attr_name] = values_cache
-    return attr_values
-
-  def new_lexemes(self):
-    self.cache_qualifiers()
-    if MINI_MODE:
-      result = self.sqlite_cursor.execute(
-        MINI_LEXEME_QUERY % '*',(MINI_LEXEME_COUNT,))
-    else:
-      result = self.sqlite_cursor.execute('SELECT * FROM leksemy')
-    attr_values = self.create_attributes()
-    date = datetime.datetime.now()
-    cv_table = dict(
-      (cv.label, cv) for cv in ClassificationValue.objects.all())
-    lexemes = []
-    lexeme_associations = []
-    lexeme_qualifiers = []
-    lexeme_cvs = []
-    lexeme_attrs = []
-    for row in result:
-      slownik = row['slownik']
-      status = 'conf' if slownik != 'zmiotki' else 'cand'
-      cv = cv_table[row['pospolitosc']]
-      lexemes.append(Lexeme(
-        id=row['nr'],
-        entry=row['haslo'],
-        entry_suffix=row['haslosuf'] or '', # pozostałość historyczna
-        gloss=row['glosa'] or '',
-        note=row['nota'] or '',
-        pronunciation=row['wymowa'] or '',
-        valence=row['łączliwość'] or '',
-        part_of_speech_id=row['pos'],
-        source='SGJP',
-        status=status,
-        comment=row['komentarz'] or '',
-        last_modified=date,
-        owner_vocabulary_id=slownik,
-      ))
-      lexeme_associations.append(LexemeAssociation(
-        lexeme_id=row['nr'], vocabulary_id=slownik))
-      lexeme_cvs.append(LexemeCV(lexeme_id=row['nr'], classification_value=cv))
-      if row['lkwal']:
-        for qual in row['lkwal'].split('|'):
-          lexeme_qualifiers.append((row['nr'], self.qual[qual]))
-      for attr_name, ((poses, ic), values, (column, f)) in ATTRS.iteritems():
-        if row['pos'] in poses:
-          attr_value = attr_values[attr_name].get(f(row[column]))
-          if attr_value:
-            lexeme_attrs.append(
-              LexemeAV(lexeme_id=row['nr'], attribute_value=attr_value))
-          elif row[column]:
-            print 'unknown value of %s: %s' % (attr_name, row[column])
-    return (lexemes, lexeme_associations, lexeme_cvs, lexeme_qualifiers,
-      lexeme_attrs)
-
-  def new_lexeme_associations(self):
-    self.cache_vocabs()
-    if MINI_MODE:
-      result = self.sqlite_cursor.execute(
-        'SELECT * FROM slowniki_uzywajace WHERE nr in (%s)'
-        % (MINI_LEXEME_QUERY % 'nr'), [MINI_LEXEME_COUNT])
-    else:
-      result = self.sqlite_cursor.execute('SELECT * FROM slowniki_uzywajace')
-    for row in result:
-      yield LexemeAssociation(
-        vocabulary=self.vocabs[row['slownik_uz']], lexeme_id=row['nr'])
-
-  CR_DESC = {
-    ('verppas', 'appas'): u'quasi-imiesłów bierny',
-    ('adjnie', 'appas'): u'„zanegowany” quasi-imiesłów bierny',
-    ('adjnie', 'adv'): u'przysłówek „zanegowany”',
-    ('adjnie', 'osc'): u'„zanegowana” nazwa cechy',
-    ('nieadj', 'appas'): u'quasi-imiesłów bierny bez „nie-”',
-    ('nieadj', 'adv'): u'przysłówek bez „nie-”',
-    ('nieadj', 'osc'): u'nazwa cechy bez „nie-”',
-  }
-
-  def new_cross_reference_types(self):
-    result = self.sqlite_cursor.execute(
-      'select distinct l1.pos pos1, l2.pos pos2, t.* '
-      'from odsylacze o join leksemy l1 on nrod=l1.nr '
-      'join leksemy l2 on nrdo=l2.nr '
-      'join typyodsylaczy t on t.typods=o.typods')
-    for row in result:
-      desc = self.CR_DESC.get((row['typods'], row['pos2']), row['naglowek'])
-      yield CrossReferenceType(
-        symbol=row['typods'],
-        desc=desc,
-        index=row['kolejnosc'],
-        from_pos=PartOfSpeech.objects.get(symbol=row['pos1']),
-        to_pos=PartOfSpeech.objects.get(symbol=row['pos2']),
-      )
-
-  def new_cross_references(self):
-    if MINI_MODE:
-      result = self.sqlite_cursor.execute(
-        'SELECT o.*, l1.pos pos1, l2.pos pos2 FROM odsylacze o '
-        'JOIN leksemy l1 on nrod=l1.nr '
-        'JOIN leksemy l2 on nrdo=l2.nr '
-        'WHERE nrod in (%(subq)s) and nrdo in (%(subq)s)'
-        % {'subq': MINI_LEXEME_QUERY % 'nr'},
-        [MINI_LEXEME_COUNT, MINI_LEXEME_COUNT])
-    else:
-      result = self.sqlite_cursor.execute(
-        'SELECT o.*, l1.pos pos1, l2.pos pos2 FROM odsylacze o '
-        'JOIN leksemy l1 on nrod=l1.nr '
-        'JOIN leksemy l2 on nrdo=l2.nr'
-      )
-    cr_type_table = dict(
-      ((crt.symbol, crt.from_pos.symbol, crt.to_pos.symbol), crt)
-      for crt in CrossReferenceType.objects.all()
-    )
-    for row in result:
-      # niekompletne odsyłacze zdarzają się dla 'asp'
-      if row['nrod'] and row['nrdo']:
-        cr_type = cr_type_table[(row['typods'], row['pos1'], row['pos2'])]
-        yield CrossReference(
-            from_lexeme_id=row['nrod'], to_lexeme_id=row['nrdo'],
-            type=cr_type)
-
-  def copy_aspects(self):
-    aspect_vals = dict(LexemeAttributeValue.objects.filter(
-      attribute__name='aspekt').values_list('value', 'pk'))
-    if MINI_MODE:
-      result = self.sqlite_cursor.execute(
-        "select distinct nrdo, aspekt "
-        "from odsylacze o "
-        "join leksemy l on o.nrod = l.nr "
-        "where typods in ('verger', 'verppas', 'verpact') "
-        "and nrod in (%(subq)s) and nrdo in (%(subq)s)"
-        % {'subq': MINI_LEXEME_QUERY % 'nr'},
-        [MINI_LEXEME_COUNT, MINI_LEXEME_COUNT])
-    else:
-      result = self.sqlite_cursor.execute(
-        "select distinct nrdo, aspekt "
-        "from odsylacze o "
-        "join leksemy l on o.nrod = l.nr "
-        "where typods in ('verger', 'verppas', 'verpact')")
-    for row in result:
-      yield LexemeAV(
-        lexeme_id=row['nrdo'], attribute_value_id=aspect_vals[row['aspekt']])
-
-  def import_pattern_types(self):
-    self.cache_lc_pos()
-    result = self.sqlite_cursor.execute(
-      'SELECT DISTINCT typr, pos FROM paradygmaty')
-    for row in result:
-      lc = self.lc_pos[row['pos']]
-      PatternType.objects.get_or_create(lexical_class=lc, symbol=row['typr'])
-    # prowizorka z powodu pustej klasy 'skr'
-    self.cache_lc()
-    result = self.sqlite_cursor.execute('SELECT DISTINCT typr, pos FROM wzory')
-    for row in result:
-      lc = self.lc[row['pos']]
-      PatternType.objects.get_or_create(lexical_class=lc, symbol=row['typr'])
-
-  def cache_ptypes(self):
-    if 'ptypes' not in self.__dict__:
-      self.ptypes = dict(
-        ((pt.lexical_class.symbol, pt.symbol), pt)
-        for pt in PatternType.objects.all()
-      )
-
-  def new_patterns(self):
-    self.cache_ptypes()
-    for row in self.sqlite_cursor.execute('SELECT * FROM wzory'):
-      yield Pattern(
-        name=row['wzor'],
-        type=self.ptypes[(row['pos'], row['typr'])],
-        basic_form_ending=row['zakp'],
-        example=row['przyklad'] or '',
-        comment=row['wkomentarz'] or '',
-        status = 'temp',
-      )
-
-  def cache_patterns(self):
-    if 'paterns' not in self.__dict__:
-      self.patterns = dict((p.name, p) for p in Pattern.objects.all())
-
-  def new_endings(self):
-    self.cache_qualifiers()
-    self.cache_patterns()
-    self.cache_bfl()
-    endings = []
-    ending_quals = []
-    for row in self.sqlite_cursor.execute('SELECT * FROM zakonczenia'):
-      if row['zak'] is not None:
-        endings.append(Ending(
-          pattern=self.patterns[row['wzor']],
-          base_form_label = self.bfls[row['efobaz']],
-          string = row['zak'],
-          index = row['nrskl'],
-        ))
-        if row['zkwal']:
-          for qual in row['zkwal'].split('|'):
-            ending_quals.append((
-              self.patterns[row['wzor']],
-              self.bfls[row['efobaz']],
-              row['nrskl'],
-              self.qual[qual]))
-    return endings, ending_quals
-
-  def new_lexeme_inflection_patterns(self):
-    self.cache_ics()
-    self.cache_qualifiers()
-    self.cache_patterns()
-    if MINI_MODE:
-      result = self.sqlite_cursor.execute(
-        'SELECT o.*, l.pos FROM odmieniasie o '
-        'JOIN leksemy l ON o.nr = l.nr '
-        'WHERE l.nr IN (%s)' % (MINI_LEXEME_QUERY % 'nr'),
-        (MINI_LEXEME_COUNT,))
-    else:
-      result = self.sqlite_cursor.execute(
-        'SELECT * FROM odmieniasie o JOIN leksemy l ON o.nr = l.nr')
-    lips = []
-    lip_quals = []
-    for row in result:
-      lexeme_id = row['nr']
-      lips.append(LexemeInflectionPattern(
-        lexeme_id=lexeme_id,
-        index=row['oskl'],
-        pattern=self.patterns[row['wzor']],
-        inflection_characteristic=self.ics[
-          (row['charfl'], row['pos'])],
-        root=row['rdzen'],
-      ))
-      if row['okwal']:
-        for qual in row['okwal'].split('|'):
-          lip_quals.append((lexeme_id, row['oskl'], self.qual[qual]))
-    return lips, lip_quals
-
-  def new_variants(self):
-    result = self.sqlite_cursor.execute(
-      'SELECT DISTINCT wariant FROM paradygmaty')
-    for row in result:
-      yield Variant(id=row['wariant'])
-
-  def new_table_templates(self):
-    self.cache_ics()
-    self.cache_ptypes()
-    self.cache_lc_pos()
-    result = self.sqlite_cursor.execute(
-      'SELECT DISTINCT wariant, pos, typr, charfl FROM paradygmaty')
-    for row in result:
-      yield TableTemplate(
-        variant_id=row['wariant'],
-        pattern_type=self.ptypes[(self.lc_pos[row['pos']].symbol, row['typr'])],
-        inflection_characteristic=self.ics[(row['charfl'], row['pos'])])
-
-  # to zostaje, bo tabelki i tak się pozmieniają
-  def import_tables(self):
-    self.cache_bfl()
-    tt_table = dict(
-      ((
-         tt.variant.id,
-         tt.pattern_type.symbol,
-         tt.inflection_characteristic.symbol,
-         tt.inflection_characteristic.part_of_speech.symbol,
-       ), tt) for tt in TableTemplate.objects.all()
-    )
-    for row in self.sqlite_cursor.execute('SELECT * FROM paradygmaty'):
-      tt = tt_table[
-        (unicode(row['wariant']), row['typr'], row['charfl'], row['pos'])]
-      if not SQL_MODE:
-        c = Cell(
-          table_template=tt,
-          base_form_label=BaseFormLabel.objects.get(symbol=row['efobaz']),
-          tag=row['morf'],
-          prefix=row['pref'],
-          suffix=row['suf'],
-          index=row['kskl'],
+        added = set()
+        for row in query_result:
+            if row[0]:
+                for qualifier_label in row[0].split('|'):
+                    if qualifier_label not in added:
+                        added.add(qualifier_label)
+                        yield Qualifier(label=qualifier_label,
+                                        vocabulary=default)
+
+    def cache_qualifiers(self):
+        if 'qual' not in self.__dict__:
+            self.qual = dict((q.label, q) for q in Qualifier.objects.all())
+
+    def create_attributes(self):
+        attr_values = {}
+        for attr_name, ((poses, ic), values, import_info) in ATTRS.iteritems():
+            la, created = LexemeAttribute.objects.get_or_create(
+                name=attr_name, closed=True, required=True, takes_ic=bool(ic))
+            for pos in PartOfSpeech.objects.filter(symbol__in=poses):
+                la.parts_of_speech.add(pos) #add
+                pos_ics = InflectionCharacteristic.objects.filter(
+                    part_of_speech=pos, symbol=ic)
+                for ic0 in pos_ics:
+                    la.inflection_characteristics.add(ic0) #add
+            values_cache = {}
+            for val, display_val in values:
+                values_cache[
+                    val], created = LexemeAttributeValue.objects.get_or_create(
+                    value=val, display_value=display_val, attribute=la)
+            attr_values[attr_name] = values_cache
+        return attr_values
+
+    def new_lexemes(self):
+        self.cache_qualifiers()
+        if MINI_MODE:
+            result = self.sqlite_cursor.execute(
+                MINI_LEXEME_QUERY % '*', (MINI_LEXEME_COUNT,))
+        else:
+            result = self.sqlite_cursor.execute('SELECT * FROM leksemy')
+        attr_values = self.create_attributes()
+        date = datetime.datetime.now()
+        cv_table = dict(
+            (cv.label, cv) for cv in ClassificationValue.objects.all())
+        lexemes = []
+        lexeme_associations = []
+        lexeme_qualifiers = []
+        lexeme_cvs = []
+        lexeme_attrs = []
+        for row in result:
+            slownik = row['slownik']
+            status = 'conf' if slownik != 'zmiotki' else 'cand'
+            cv = cv_table[row['pospolitosc']]
+            lexemes.append(Lexeme(
+                id=row['nr'],
+                entry=row['haslo'],
+                entry_suffix=row['haslosuf'] or '', # pozostałość historyczna
+                gloss=row['glosa'] or '',
+                note=row['nota'] or '',
+                pronunciation=row['wymowa'] or '',
+                valence=row['łączliwość'] or '',
+                part_of_speech_id=row['pos'],
+                source='SGJP',
+                status=status,
+                comment=row['komentarz'] or '',
+                last_modified=date,
+                owner_vocabulary_id=slownik,
+            ))
+            lexeme_associations.append(LexemeAssociation(
+                lexeme_id=row['nr'], vocabulary_id=slownik))
+            lexeme_cvs.append(
+                LexemeCV(lexeme_id=row['nr'], classification_value=cv))
+            if row['lkwal']:
+                for qual in row['lkwal'].split('|'):
+                    lexeme_qualifiers.append((row['nr'], self.qual[qual]))
+            for attr_name, (
+            (poses, ic), values, (column, f)) in ATTRS.iteritems():
+                if row['pos'] in poses:
+                    attr_value = attr_values[attr_name].get(f(row[column]))
+                    if attr_value:
+                        lexeme_attrs.append(
+                            LexemeAV(lexeme_id=row['nr'],
+                                     attribute_value=attr_value))
+                    elif row[column]:
+                        print 'unknown value of %s: %s' % (
+                        attr_name, row[column])
+        return (lexemes, lexeme_associations, lexeme_cvs, lexeme_qualifiers,
+                lexeme_attrs)
+
+    def new_lexeme_associations(self):
+        self.cache_vocabs()
+        if MINI_MODE:
+            result = self.sqlite_cursor.execute(
+                'SELECT * FROM slowniki_uzywajace WHERE nr in (%s)'
+                % (MINI_LEXEME_QUERY % 'nr'), [MINI_LEXEME_COUNT])
+        else:
+            result = self.sqlite_cursor.execute(
+                'SELECT * FROM slowniki_uzywajace')
+        for row in result:
+            yield LexemeAssociation(
+                vocabulary=self.vocabs[row['slownik_uz']], lexeme_id=row['nr'])
+
+    CR_DESC = {
+        ('verppas', 'appas'): u'quasi-imiesłów bierny',
+        ('adjnie', 'appas'): u'„zanegowany” quasi-imiesłów bierny',
+        ('adjnie', 'adv'): u'przysłówek „zanegowany”',
+        ('adjnie', 'osc'): u'„zanegowana” nazwa cechy',
+        ('nieadj', 'appas'): u'quasi-imiesłów bierny bez „nie-”',
+        ('nieadj', 'adv'): u'przysłówek bez „nie-”',
+        ('nieadj', 'osc'): u'nazwa cechy bez „nie-”',
+    }
+
+    def new_cross_reference_types(self):
+        result = self.sqlite_cursor.execute(
+            'select distinct l1.pos pos1, l2.pos pos2, t.* '
+            'from odsylacze o join leksemy l1 on nrod=l1.nr '
+            'join leksemy l2 on nrdo=l2.nr '
+            'join typyodsylaczy t on t.typods=o.typods')
+        for row in result:
+            desc = self.CR_DESC.get((row['typods'], row['pos2']),
+                                    row['naglowek'])
+            yield CrossReferenceType(
+                symbol=row['typods'],
+                desc=desc,
+                index=row['kolejnosc'],
+                from_pos=PartOfSpeech.objects.get(symbol=row['pos1']),
+                to_pos=PartOfSpeech.objects.get(symbol=row['pos2']),
+            )
+
+    def new_cross_references(self):
+        if MINI_MODE:
+            result = self.sqlite_cursor.execute(
+                'SELECT o.*, l1.pos pos1, l2.pos pos2 FROM odsylacze o '
+                'JOIN leksemy l1 on nrod=l1.nr '
+                'JOIN leksemy l2 on nrdo=l2.nr '
+                'WHERE nrod in (%(subq)s) and nrdo in (%(subq)s)'
+                % {'subq': MINI_LEXEME_QUERY % 'nr'},
+                [MINI_LEXEME_COUNT, MINI_LEXEME_COUNT])
+        else:
+            result = self.sqlite_cursor.execute(
+                'SELECT o.*, l1.pos pos1, l2.pos pos2 FROM odsylacze o '
+                'JOIN leksemy l1 on nrod=l1.nr '
+                'JOIN leksemy l2 on nrdo=l2.nr'
+            )
+        cr_type_table = dict(
+            ((crt.symbol, crt.from_pos.symbol, crt.to_pos.symbol), crt)
+            for crt in CrossReferenceType.objects.all()
         )
-        c.save()
-        if row['row']:
-          tc = TableCell(
-            cell=c,
-            row=row['row'],
-            col=row['col'],
-            rowspan=row['rowspan'],
-            colspan=row['colspan'],
-          )
-          tc.save()
-      else:
-        efobaz_id = self.bfls[row['efobaz']].id
-        self.cursor.execute(
-          "INSERT INTO klatki (st_id, efobaz, tag, prefiks, sufiks, kind) "
-          "VALUES (%s, %s, %s, %s, %s, %s)", [tt.pk, efobaz_id, row['morf'],
-          row['pref'], row['suf'], row['kskl']])
-        if row['row']:
-          self.cursor.execute("select currval('klatki_id_seq')")
-          last_id = self.cursor.fetchone()[0]
-          self.cursor.execute(
-            "INSERT INTO komorki_tabel (k_id, row, col, rowspan, colspan) "
-            "VALUES (%s, %s, %s, %s, %s)", [last_id, row['row'],
-            row['col'], row['rowspan'], row['colspan']])
-
-  def new_table_headers(self):
-    for row in self.sqlite_cursor.execute('SELECT * FROM naglowkiwierszy'):
-      tts = TableTemplate.objects.filter(
-        variant__id=row['wariant'], pattern_type__symbol=row['typr'],
-        inflection_characteristic__symbol=row['charfl'],
-        inflection_characteristic__part_of_speech__symbol=row['pos'])
-      if tts:
-        tt = tts.get()
-        yield TableHeader(
-          table_template=tt,
-          row=row['row'],
-          col=row['col'],
-          rowspan=row['rowspan'],
-          colspan=row['colspan'],
-          label=row['nagl'],
-          css_class=TRANSLATE_CLASS[row['styl']],
+        for row in result:
+            # niekompletne odsyłacze zdarzają się dla 'asp'
+            if row['nrod'] and row['nrdo']:
+                cr_type = cr_type_table[
+                    (row['typods'], row['pos1'], row['pos2'])]
+                yield CrossReference(
+                    from_lexeme_id=row['nrod'], to_lexeme_id=row['nrdo'],
+                    type=cr_type)
+
+    def copy_aspects(self):
+        aspect_vals = dict(LexemeAttributeValue.objects.filter(
+            attribute__name='aspekt').values_list('value', 'pk'))
+        if MINI_MODE:
+            result = self.sqlite_cursor.execute(
+                "select distinct nrdo, aspekt "
+                "from odsylacze o "
+                "join leksemy l on o.nrod = l.nr "
+                "where typods in ('verger', 'verppas', 'verpact') "
+                "and nrod in (%(subq)s) and nrdo in (%(subq)s)"
+                % {'subq': MINI_LEXEME_QUERY % 'nr'},
+                [MINI_LEXEME_COUNT, MINI_LEXEME_COUNT])
+        else:
+            result = self.sqlite_cursor.execute(
+                "select distinct nrdo, aspekt "
+                "from odsylacze o "
+                "join leksemy l on o.nrod = l.nr "
+                "where typods in ('verger', 'verppas', 'verpact')")
+        for row in result:
+            yield LexemeAV(
+                lexeme_id=row['nrdo'],
+                attribute_value_id=aspect_vals[row['aspekt']])
+
+    def import_pattern_types(self):
+        self.cache_lc_pos()
+        result = self.sqlite_cursor.execute(
+            'SELECT DISTINCT typr, pos FROM paradygmaty')
+        for row in result:
+            lc = self.lc_pos[row['pos']]
+            PatternType.objects.get_or_create(lexical_class=lc,
+                                              symbol=row['typr'])
+            # prowizorka z powodu pustej klasy 'skr'
+        self.cache_lc()
+        result = self.sqlite_cursor.execute(
+            'SELECT DISTINCT typr, pos FROM wzory')
+        for row in result:
+            lc = self.lc[row['pos']]
+            PatternType.objects.get_or_create(lexical_class=lc,
+                                              symbol=row['typr'])
+
+    def cache_ptypes(self):
+        if 'ptypes' not in self.__dict__:
+            self.ptypes = dict(
+                ((pt.lexical_class.symbol, pt.symbol), pt)
+                for pt in PatternType.objects.all()
+            )
+
+    def new_patterns(self):
+        self.cache_ptypes()
+        for row in self.sqlite_cursor.execute('SELECT * FROM wzory'):
+            yield Pattern(
+                name=row['wzor'],
+                type=self.ptypes[(row['pos'], row['typr'])],
+                basic_form_ending=row['zakp'],
+                example=row['przyklad'] or '',
+                comment=row['wkomentarz'] or '',
+                status='temp',
+            )
+
+    def cache_patterns(self):
+        if 'paterns' not in self.__dict__:
+            self.patterns = dict((p.name, p) for p in Pattern.objects.all())
+
+    def new_endings(self):
+        self.cache_qualifiers()
+        self.cache_patterns()
+        self.cache_bfl()
+        endings = []
+        ending_quals = []
+        for row in self.sqlite_cursor.execute('SELECT * FROM zakonczenia'):
+            if row['zak'] is not None:
+                endings.append(Ending(
+                    pattern=self.patterns[row['wzor']],
+                    base_form_label=self.bfls[row['efobaz']],
+                    string=row['zak'],
+                    index=row['nrskl'],
+                ))
+                if row['zkwal']:
+                    for qual in row['zkwal'].split('|'):
+                        ending_quals.append((
+                            self.patterns[row['wzor']],
+                            self.bfls[row['efobaz']],
+                            row['nrskl'],
+                            self.qual[qual]))
+        return endings, ending_quals
+
+    def new_lexeme_inflection_patterns(self):
+        self.cache_ics()
+        self.cache_qualifiers()
+        self.cache_patterns()
+        if MINI_MODE:
+            result = self.sqlite_cursor.execute(
+                'SELECT o.*, l.pos FROM odmieniasie o '
+                'JOIN leksemy l ON o.nr = l.nr '
+                'WHERE l.nr IN (%s)' % (MINI_LEXEME_QUERY % 'nr'),
+                (MINI_LEXEME_COUNT,))
+        else:
+            result = self.sqlite_cursor.execute(
+                'SELECT * FROM odmieniasie o JOIN leksemy l ON o.nr = l.nr')
+        lips = []
+        lip_quals = []
+        for row in result:
+            lexeme_id = row['nr']
+            lips.append(LexemeInflectionPattern(
+                lexeme_id=lexeme_id,
+                index=row['oskl'],
+                pattern=self.patterns[row['wzor']],
+                inflection_characteristic=self.ics[
+                    (row['charfl'], row['pos'])],
+                root=row['rdzen'],
+            ))
+            if row['okwal']:
+                for qual in row['okwal'].split('|'):
+                    lip_quals.append((lexeme_id, row['oskl'], self.qual[qual]))
+        return lips, lip_quals
+
+    def new_variants(self):
+        result = self.sqlite_cursor.execute(
+            'SELECT DISTINCT wariant FROM paradygmaty')
+        for row in result:
+            yield Variant(id=row['wariant'])
+
+    def new_table_templates(self):
+        self.cache_ics()
+        self.cache_ptypes()
+        self.cache_lc_pos()
+        result = self.sqlite_cursor.execute(
+            'SELECT DISTINCT wariant, pos, typr, charfl FROM paradygmaty')
+        for row in result:
+            yield TableTemplate(
+                variant_id=row['wariant'],
+                pattern_type=self.ptypes[
+                    (self.lc_pos[row['pos']].symbol, row['typr'])],
+                inflection_characteristic=self.ics[(row['charfl'], row['pos'])])
+
+    # to zostaje, bo tabelki i tak się pozmieniają
+    def import_tables(self):
+        self.cache_bfl()
+        tt_table = dict(
+            ((
+                 tt.variant.id,
+                 tt.pattern_type.symbol,
+                 tt.inflection_characteristic.symbol,
+                 tt.inflection_characteristic.part_of_speech.symbol,
+             ), tt) for tt in TableTemplate.objects.all()
         )
-      else:
-        raise Exception('Brak szablonu dla nagłówka: %s', dict(row))
-
-  def delete_and_import(self):
-    models = (
-      TableCell,
-      Cell,
-      TableTemplate,
-      Variant,
-      CrossReference,
-      CrossReferenceType,
-      LexemeAssociation,
-      LexemeInflectionPattern,
-      Lexeme,
-      Ending,
-      Pattern,
-      PatternType,
-      Qualifier,
-      #Vocabulary,
-      InflectionCharacteristic,
-      BaseFormLabel,
-      #PartOfSpeech,
-      #LexicalClass,
-      LexemeAttribute,
-    )
-    print 'deleting old data...'
-    for model in models:
-      model.objects.all().delete()
-
-    print 'importing lexical classes...'
-    bulk_create(LexicalClass, self.new_lexical_classes())
-    print 'importing parts of speech...'
-    bulk_create(PartOfSpeech, self.new_parts_of_speech())
-    print 'importing base form labels...'
-    bulk_create(BaseFormLabel, self.new_base_form_labels())
-    print 'importing inflection characteristics...'
-    bulk_create(InflectionCharacteristic,
-      self.new_inflection_characteristics())
-    print 'importing vocabularies...'
-    for v in self.new_vocabularies():
-      v.save()
-    print 'importing qualifiers...'
-    bulk_create(Qualifier, self.new_qualifiers())
-    print 'importing pattern types...'
-    self.import_pattern_types()
-    print 'importing patterns...'
-    bulk_create(Pattern, self.new_patterns())
-    print 'importing endings...'
-    endings, ending_quals = self.new_endings()
-    bulk_create(Ending, endings)
-    for pattern, bfl, index, q in ending_quals:
-      Ending.objects.get(
-        pattern=pattern, base_form_label=bfl, index=index).qualifiers.add(q)
-    def import_lexemes():
-      print 'importing lexemes...'
-      (lexemes, lexeme_assoc, lexeme_cvs, lexeme_quals,
-       lexeme_attrs) = self.new_lexemes()
-      print 'creating...'
-      bulk_create(Lexeme, lexemes)
-      print 'associations...'
-      bulk_create(LexemeAssociation, lexeme_assoc)
-      print 'classifications...'
-      bulk_create(LexemeCV, lexeme_cvs)
-      print 'qualifiers...'
-      for lexeme_id, q in lexeme_quals:
-        q.lexeme_set.add(lexeme_id) #add
-      print 'attributes...'
-      bulk_create(LexemeAV, lexeme_attrs)
-    import_lexemes()
-    def import_lips():
-      print 'importing lexeme inflection patterns...'
-      lips, lip_quals = self.new_lexeme_inflection_patterns()
-      print 'creating...'
-      bulk_create(LexemeInflectionPattern, lips)
-      print 'qualifiers...'
-      for lexeme_id, index, q in lip_quals:
-        LexemeInflectionPattern.objects.get(
-          lexeme_id=lexeme_id, index=index).qualifiers.add(q)
-    import_lips()
-    print 'importing lexeme associations...'
-    bulk_create(LexemeAssociation, self.new_lexeme_associations())
-    print 'importing cross-reference types...'
-    bulk_create(CrossReferenceType,
-      self.new_cross_reference_types())
-    print 'importing cross-references...'
-    bulk_create(CrossReference, self.new_cross_references())
-    print 'copying aspect values to derived lexemes...'
-    bulk_create(LexemeAV, self.copy_aspects())
-    print 'importing variants...'
-    bulk_create(Variant, self.new_variants())
-    print 'importing table templates...'
-    bulk_create(TableTemplate, self.new_table_templates())
-    print 'importing tables...'
-    self.import_tables()
-    print 'importing table headers...'
-    bulk_create(TableHeader, self.new_table_headers())
-    print 'committing to database...'
-    self.close()
-
-  def single_import(self, model):
-    method_name = METHOD_NAMES[model]
-    if method_name.startswith('new'):
-      bulk_create(model, self.__getattribute__(method_name)())
-    elif method_name.startswith('import'):
-      self.__getattribute__(method_name)()
-    self.close()
+        for row in self.sqlite_cursor.execute('SELECT * FROM paradygmaty'):
+            tt = tt_table[
+                (unicode(row['wariant']), row['typr'], row['charfl'],
+                 row['pos'])]
+            if not SQL_MODE:
+                c = Cell(
+                    table_template=tt,
+                    base_form_label=BaseFormLabel.objects.get(
+                        symbol=row['efobaz']),
+                    tag=row['morf'],
+                    prefix=row['pref'],
+                    suffix=row['suf'],
+                    index=row['kskl'],
+                )
+                c.save()
+                if row['row']:
+                    tc = TableCell(
+                        cell=c,
+                        row=row['row'],
+                        col=row['col'],
+                        rowspan=row['rowspan'],
+                        colspan=row['colspan'],
+                    )
+                    tc.save()
+            else:
+                efobaz_id = self.bfls[row['efobaz']].id
+                self.cursor.execute(
+                    "INSERT INTO klatki (st_id, efobaz, tag, prefiks, sufiks, kind) "
+                    "VALUES (%s, %s, %s, %s, %s, %s)",
+                    [tt.pk, efobaz_id, row['morf'],
+                     row['pref'], row['suf'], row['kskl']])
+                if row['row']:
+                    self.cursor.execute("select currval('klatki_id_seq')")
+                    last_id = self.cursor.fetchone()[0]
+                    self.cursor.execute(
+                        "INSERT INTO komorki_tabel (k_id, row, col, rowspan, colspan) "
+                        "VALUES (%s, %s, %s, %s, %s)", [last_id, row['row'],
+                                                        row['col'],
+                                                        row['rowspan'],
+                                                        row['colspan']])
+
+    def new_table_headers(self):
+        for row in self.sqlite_cursor.execute('SELECT * FROM naglowkiwierszy'):
+            tts = TableTemplate.objects.filter(
+                variant__id=row['wariant'], pattern_type__symbol=row['typr'],
+                inflection_characteristic__symbol=row['charfl'],
+                inflection_characteristic__part_of_speech__symbol=row['pos'])
+            if tts:
+                tt = tts.get()
+                yield TableHeader(
+                    table_template=tt,
+                    row=row['row'],
+                    col=row['col'],
+                    rowspan=row['rowspan'],
+                    colspan=row['colspan'],
+                    label=row['nagl'],
+                    css_class=TRANSLATE_CLASS[row['styl']],
+                )
+            else:
+                raise Exception('Brak szablonu dla nagłówka: %s', dict(row))
+
+    def delete_and_import(self):
+        models = (
+            TableCell,
+            Cell,
+            TableTemplate,
+            Variant,
+            CrossReference,
+            CrossReferenceType,
+            LexemeAssociation,
+            LexemeInflectionPattern,
+            Lexeme,
+            Ending,
+            Pattern,
+            PatternType,
+            Qualifier,
+            #Vocabulary,
+            InflectionCharacteristic,
+            BaseFormLabel,
+            #PartOfSpeech,
+            #LexicalClass,
+            LexemeAttribute,
+        )
+        print 'deleting old data...'
+        for model in models:
+            model.objects.all().delete()
+
+        print 'importing lexical classes...'
+        bulk_create(LexicalClass, self.new_lexical_classes())
+        print 'importing parts of speech...'
+        bulk_create(PartOfSpeech, self.new_parts_of_speech())
+        print 'importing base form labels...'
+        bulk_create(BaseFormLabel, self.new_base_form_labels())
+        print 'importing inflection characteristics...'
+        bulk_create(InflectionCharacteristic,
+                    self.new_inflection_characteristics())
+        print 'importing vocabularies...'
+        for v in self.new_vocabularies():
+            v.save()
+        print 'importing qualifiers...'
+        bulk_create(Qualifier, self.new_qualifiers())
+        print 'importing pattern types...'
+        self.import_pattern_types()
+        print 'importing patterns...'
+        bulk_create(Pattern, self.new_patterns())
+        print 'importing endings...'
+        endings, ending_quals = self.new_endings()
+        bulk_create(Ending, endings)
+        for pattern, bfl, index, q in ending_quals:
+            Ending.objects.get(
+                pattern=pattern, base_form_label=bfl,
+                index=index).qualifiers.add(q)
+
+        def import_lexemes():
+            print 'importing lexemes...'
+            (lexemes, lexeme_assoc, lexeme_cvs, lexeme_quals,
+             lexeme_attrs) = self.new_lexemes()
+            print 'creating...'
+            bulk_create(Lexeme, lexemes)
+            print 'associations...'
+            bulk_create(LexemeAssociation, lexeme_assoc)
+            print 'classifications...'
+            bulk_create(LexemeCV, lexeme_cvs)
+            print 'qualifiers...'
+            for lexeme_id, q in lexeme_quals:
+                q.lexeme_set.add(lexeme_id) #add
+            print 'attributes...'
+            bulk_create(LexemeAV, lexeme_attrs)
+
+        import_lexemes()
+
+        def import_lips():
+            print 'importing lexeme inflection patterns...'
+            lips, lip_quals = self.new_lexeme_inflection_patterns()
+            print 'creating...'
+            bulk_create(LexemeInflectionPattern, lips)
+            print 'qualifiers...'
+            for lexeme_id, index, q in lip_quals:
+                LexemeInflectionPattern.objects.get(
+                    lexeme_id=lexeme_id, index=index).qualifiers.add(q)
+
+        import_lips()
+        print 'importing lexeme associations...'
+        bulk_create(LexemeAssociation, self.new_lexeme_associations())
+        print 'importing cross-reference types...'
+        bulk_create(CrossReferenceType,
+                    self.new_cross_reference_types())
+        print 'importing cross-references...'
+        bulk_create(CrossReference, self.new_cross_references())
+        print 'copying aspect values to derived lexemes...'
+        bulk_create(LexemeAV, self.copy_aspects())
+        print 'importing variants...'
+        bulk_create(Variant, self.new_variants())
+        print 'importing table templates...'
+        bulk_create(TableTemplate, self.new_table_templates())
+        print 'importing tables...'
+        self.import_tables()
+        print 'importing table headers...'
+        bulk_create(TableHeader, self.new_table_headers())
+        print 'committing to database...'
+        self.close()
+
+    def single_import(self, model):
+        method_name = METHOD_NAMES[model]
+        if method_name.startswith('new'):
+            bulk_create(model, self.__getattribute__(method_name)())
+        elif method_name.startswith('import'):
+            self.__getattribute__(method_name)()
+        self.close()
diff --git a/dictionary/management/commands/import_kipi.py b/dictionary/management/commands/import_kipi.py
index fd8c319..943349f 100644
--- a/dictionary/management/commands/import_kipi.py
+++ b/dictionary/management/commands/import_kipi.py
@@ -2,355 +2,386 @@
 
 from django.core.management.base import BaseCommand
 from common.util import debug, suffixes, cut_end
-from dictionary.models import Lexeme, Pattern, InflectionCharacteristic,\
-  Ending, BaseFormLabel
+from dictionary.models import Lexeme, Pattern, InflectionCharacteristic, \
+    Ending, BaseFormLabel
 from dictionary.management.commands.import_morfologik import create_lexeme, \
-  create_lip, print_data, find_minimal_sets, blacklist_filter, join_many, \
-  join, print_forms
+    create_lip, print_data, find_minimal_sets, blacklist_filter, join_many, \
+    join, print_forms
+
 
 class Command(BaseCommand):
-  args = '<input file name>'
-  help = 'importuje leksemy z KIPI 1.0'
+    args = '<input file name>'
+    help = 'importuje leksemy z KIPI 1.0'
+
+    def handle(self, filename, **options):
+        import_kipi(open(filename))
 
-  def handle(self, filename, **options):
-    import_kipi(open(filename))
 
 DEBUG = False
 
 COMMONNESS = {
-  'geog': u'geograficzna',
-  'imie': u'imię',
-  'inna': u'własna',
-  'nazw': u'nazwisko',
-  'orga': u'organizacja',
-  'posp': u'pospolita',
+    'geog': u'geograficzna',
+    'imie': u'imię',
+    'inna': u'własna',
+    'nazw': u'nazwisko',
+    'orga': u'organizacja',
+    'posp': u'pospolita',
 }
 
+
 def inflection_characteristic(forms, pos):
-  # w KIPI jest tylko subst i adj
-  tag = forms[0][1]
-  if pos == 'subst':
-    if 'depr' in tag or tag.endswith('m1'):
-      ic = 'm1'
-    else:
-      ic = tag.rsplit(':', 1)[1]
-  elif pos == 'adj':
-    # formy 3+ tu nie występują
-    if any(tag == 'adja' for form, tag in forms):
-      ic = ''
-    else:
-      ic = '0-'
-  return ic
+    # w KIPI jest tylko subst i adj
+    tag = forms[0][1]
+    if pos == 'subst':
+        if 'depr' in tag or tag.endswith('m1'):
+            ic = 'm1'
+        else:
+            ic = tag.rsplit(':', 1)[1]
+    elif pos == 'adj':
+        # formy 3+ tu nie występują
+        if any(tag == 'adja' for form, tag in forms):
+            ic = ''
+        else:
+            ic = '0-'
+    return ic
 
 # COPYPASTA HEAVEN
 def get_basic_endings(lexical_class, ic):
-  return Ending.objects.filter(
-    base_form_label=ic.basic_form_label,
-    pattern__type__lexical_class__symbol=lexical_class)
+    return Ending.objects.filter(
+        base_form_label=ic.basic_form_label,
+        pattern__type__lexical_class__symbol=lexical_class)
+
 
 basic_form_endings_dict = {}
 for pos in ('adj', 'subst'):
-  for ic in InflectionCharacteristic.objects.filter(part_of_speech__symbol=pos):
-    basic_form_endings_dict[(pos, ic.symbol)] = get_basic_endings(pos, ic)
+    for ic in InflectionCharacteristic.objects.filter(
+            part_of_speech__symbol=pos):
+        basic_form_endings_dict[(pos, ic.symbol)] = get_basic_endings(pos, ic)
 
 sure_bfls_sg = tuple(
-  BaseFormLabel.objects.filter(
-    symbol__in=['sg:dat', 'sg:gen', 'sg:inst']).values_list('pk', flat=True))
+    BaseFormLabel.objects.filter(
+        symbol__in=['sg:dat', 'sg:gen', 'sg:inst']).values_list('pk',
+                                                                flat=True))
 sure_bfls_pl = tuple(
-  BaseFormLabel.objects.filter(
-    symbol__in=['pl:dat', 'pl:inst', 'pl:loc']).values_list('pk', flat=True))
+    BaseFormLabel.objects.filter(
+        symbol__in=['pl:dat', 'pl:inst', 'pl:loc']).values_list('pk',
+                                                                flat=True))
+
 
 def basic_form_endings(lexical_class, ic, basic_form, form_set):
-  if lexical_class != 'subst':
-    return basic_form_endings_dict[(lexical_class, ic)].filter(
-      string__in=suffixes(basic_form))
-  else:
-    # karkołomne, ale trochę przyśpiesza
-    endings = basic_form_endings_dict[(lexical_class, ic)]
-    new_endings = Ending.objects.none()
-    for suf in suffixes(basic_form):
-      root = cut_end(basic_form, suf)
-      n = len(root)
-      ending_strings = tuple(
-        form[n:] for form in form_set if form.startswith(root))
-      endings_part = endings.filter(string=suf)
-      pattern_ids = endings_part.values_list('pattern', flat=True)
-      patterns = Pattern.objects.filter(pk__in=pattern_ids).extra(
-        where=["(id = '0000' or not exists "
-               "(select id from zakonczenia where w_id = wzory.id "
-               "and zak not in %s and efobaz in %s) or not exists "
-               "(select id from zakonczenia where w_id = wzory.id "
-               "and zak not in %s and efobaz in %s))"],
-        params=[ending_strings, sure_bfls_sg, ending_strings, sure_bfls_pl])
-      new_endings = new_endings | endings_part.filter(pattern__in=patterns)
-    return new_endings
+    if lexical_class != 'subst':
+        return basic_form_endings_dict[(lexical_class, ic)].filter(
+            string__in=suffixes(basic_form))
+    else:
+        # karkołomne, ale trochę przyśpiesza
+        endings = basic_form_endings_dict[(lexical_class, ic)]
+        new_endings = Ending.objects.none()
+        for suf in suffixes(basic_form):
+            root = cut_end(basic_form, suf)
+            n = len(root)
+            ending_strings = tuple(
+                form[n:] for form in form_set if form.startswith(root))
+            endings_part = endings.filter(string=suf)
+            pattern_ids = endings_part.values_list('pattern', flat=True)
+            patterns = Pattern.objects.filter(pk__in=pattern_ids).extra(
+                where=["(id = '0000' or not exists "
+                       "(select id from zakonczenia where w_id = wzory.id "
+                       "and zak not in %s and efobaz in %s) or not exists "
+                       "(select id from zakonczenia where w_id = wzory.id "
+                       "and zak not in %s and efobaz in %s))"],
+                params=[ending_strings, sure_bfls_sg, ending_strings,
+                        sure_bfls_pl])
+            new_endings = new_endings | endings_part.filter(
+                pattern__in=patterns)
+        return new_endings
+
 
 memoized_pattern_ics = {}
 
+
 def bad_pattern_subst(pattern, ic):
-  if (pattern, ic) in memoized_pattern_ics:
-    return memoized_pattern_ics[(pattern, ic)]
-  if not pattern.lexemeinflectionpattern_set.filter(
-       inflection_characteristic__symbol=ic).exclude(lexeme__status='cand'):
-    ret = True
-  elif pattern.type.symbol in 'mn' and ic == 'f':
-    ret = True
-  elif pattern.type.symbol in 'fm' and ic[0] == 'n':
-    ret = True
-  else:
-    ret = False
-  memoized_pattern_ics[(pattern, ic)] = ret
-  return ret
+    if (pattern, ic) in memoized_pattern_ics:
+        return memoized_pattern_ics[(pattern, ic)]
+    if not pattern.lexemeinflectionpattern_set.filter(
+            inflection_characteristic__symbol=ic).exclude(
+            lexeme__status='cand'):
+        ret = True
+    elif pattern.type.symbol in 'mn' and ic == 'f':
+        ret = True
+    elif pattern.type.symbol in 'fm' and ic[0] == 'n':
+        ret = True
+    else:
+        ret = False
+    memoized_pattern_ics[(pattern, ic)] = ret
+    return ret
+
 
 memoized_good_endings = {}
 
+
 def good_ending_set_subst(pattern, ic, root):
-  if (pattern, ic) in memoized_good_endings:
-    good_endings = memoized_good_endings[(pattern, ic)]
+    if (pattern, ic) in memoized_good_endings:
+        good_endings = memoized_good_endings[(pattern, ic)]
+        return set(root + e for e in good_endings)
+    endings = pattern.endings
+    if ic not in ('m1', 'p1'):
+        endings = endings.exclude(base_form_label__symbol='pl:nom:mo')
+    if ic[0] == 'p':
+        endings = endings.filter(base_form_label__symbol__startswith='pl')
+    else:
+        for g in list(set('mfn') - set(ic[0])):
+            endings = endings.exclude(
+                base_form_label__symbol__startswith='pl:gen:' + g)
+    if ic == 'p3':
+        if pattern.type.symbol == 'f':
+            endings = endings.exclude(base_form_label__symbol='pl:gen:m')
+        elif pattern.type.symbol == 'n':
+            endings = endings.exclude(base_form_label__symbol='pl:gen:n')
+    good_endings = list(endings.values_list('string', flat=True))
+    memoized_good_endings[(pattern, ic)] = good_endings
     return set(root + e for e in good_endings)
-  endings = pattern.endings
-  if ic not in ('m1', 'p1'):
-    endings = endings.exclude(base_form_label__symbol='pl:nom:mo')
-  if ic[0] == 'p':
-    endings = endings.filter(base_form_label__symbol__startswith='pl')
-  else:
-    for g in list(set('mfn') - set(ic[0])):
-      endings = endings.exclude(
-        base_form_label__symbol__startswith='pl:gen:' + g)
-  if ic == 'p3':
-    if pattern.type.symbol == 'f':
-      endings = endings.exclude(base_form_label__symbol='pl:gen:m')
-    elif pattern.type.symbol == 'n':
-      endings = endings.exclude(base_form_label__symbol='pl:gen:n')
-  good_endings = list(endings.values_list('string', flat=True))
-  memoized_good_endings[(pattern, ic)] = good_endings
-  return set(root + e for e in good_endings)
+
 
 def good_ending_set(lexical_class, ic, pattern, root=''):
-  if lexical_class != 'subst':
-    return pattern.ending_set(root)
-  else:
-    return good_ending_set_subst(pattern, ic, root)
+    if lexical_class != 'subst':
+        return pattern.ending_set(root)
+    else:
+        return good_ending_set_subst(pattern, ic, root)
+
 
 def relevant_subst(ending, ic):
-  bfl = ending.base_form_label.symbol
-  tag = bfl.split(':')
-  pattern_type = ending.pattern.type.symbol
-  return (not (ic in ('m1', 'p1') and bfl == 'pl:nom') and
-          not (len(tag) >= 3 and ic[0] != 'p' and
-               tag[2][0] != ic[0]) and
-          not (ic[0] == 'p' and tag[0] != 'pl') and
-          not (ic == 'p3' and bfl.startswith('pl:gen:') and (
+    bfl = ending.base_form_label.symbol
+    tag = bfl.split(':')
+    pattern_type = ending.pattern.type.symbol
+    return (not (ic in ('m1', 'p1') and bfl == 'pl:nom') and
+            not (len(tag) >= 3 and ic[0] != 'p' and
+                 tag[2][0] != ic[0]) and
+            not (ic[0] == 'p' and tag[0] != 'pl') and
+            not (ic == 'p3' and bfl.startswith('pl:gen:') and (
                 (pattern_type == 'n' and tag[2] == 'n') or
                 (pattern_type == 'f' and tag[2] == 'm')
-              )) and
-          not (ic not in ('m1', 'p1') and bfl == 'pl:nom:mo'))
+            )) and
+            not (ic not in ('m1', 'p1') and bfl == 'pl:nom:mo'))
+
 
 def relevant_adj(ending):
-  tag = ending.base_form_label.symbol
-  return tag not in ('0', '3+')
+    tag = ending.base_form_label.symbol
+    return tag not in ('0', '3+')
+
 
 def relevant(lexical_class, ending, ic):
-  if lexical_class == 'subst':
-    return relevant_subst(ending, ic)
-  elif lexical_class == 'adj':
-    return relevant_adj(ending)
+    if lexical_class == 'subst':
+        return relevant_subst(ending, ic)
+    elif lexical_class == 'adj':
+        return relevant_adj(ending)
+
 
 def find_patterns(basic_form, pos, ic, forms):
-  patterns = Pattern.objects.filter(type__lexical_class__symbol=pos)
-  # znaleźć wszystkie zawarte i zawierające wzory
-  form_set = set(form for form, tag in forms)
-  ending_sets = {}
-  included_patterns = set()
-  including_patterns = set()
-  matching_patterns = set()
-  for basic_ending in basic_form_endings(pos, ic, basic_form, form_set):
-    pattern = basic_ending.pattern
-    if pos == 'subst' and bad_pattern_subst(pattern, ic):
-      #print 'odpadł:', pattern
-      continue # olewamy komentarze że formy odrzucone przez charfle?
-    root = basic_form[:len(basic_form) - len(basic_ending.string)]
-    ending_sets[pattern] = good_ending_set(pos, ic, pattern, root)
-    including = form_set.issubset(ending_sets[pattern])
-    bad_forms = set()
-    for ending in pattern.endings.all():
-      if relevant(pos, ending, ic):
-        if root + ending.string not in form_set:
-          bfl = ending.base_form_label.symbol
-          #print pattern.name, root, ending.string, bfl
-          bad_forms.add(root + ending.string)
-    if not bad_forms:
-      included_patterns.add((pattern, root))
-      if including:
-        matching_patterns.add((pattern, root))
-    elif including:
-      including_patterns.add(((pattern, root), tuple(bad_forms)))
-
-  # nie wiem, czy to potrzebne, ale na wszelki wypadek
-  included_patterns = list(included_patterns)
-  including_patterns = list(including_patterns)
-  matching_patterns = list(matching_patterns)
-  if len(matching_patterns) > 0:
-    if DEBUG:
-      print u'dokładne wzory: %s' % join(matching_patterns)
-    return 'match', matching_patterns, included_patterns, including_patterns
-  # nic nie pasuje albo trzeba wybrać wiele wzorów
-  if DEBUG and len(including_patterns) > 0:
-    print u'zawierające: %s' % join(p for p, b_f in including_patterns)
-  if DEBUG and len(included_patterns) > 0:
-    print u'zawarte: %s' % join(included_patterns)
-  return find_many_patterns(
-    pos, ic, form_set, basic_form, included_patterns, ending_sets) + (
-    included_patterns, including_patterns)
+    patterns = Pattern.objects.filter(type__lexical_class__symbol=pos)
+    # znaleźć wszystkie zawarte i zawierające wzory
+    form_set = set(form for form, tag in forms)
+    ending_sets = {}
+    included_patterns = set()
+    including_patterns = set()
+    matching_patterns = set()
+    for basic_ending in basic_form_endings(pos, ic, basic_form, form_set):
+        pattern = basic_ending.pattern
+        if pos == 'subst' and bad_pattern_subst(pattern, ic):
+            #print 'odpadł:', pattern
+            continue # olewamy komentarze że formy odrzucone przez charfle?
+        root = basic_form[:len(basic_form) - len(basic_ending.string)]
+        ending_sets[pattern] = good_ending_set(pos, ic, pattern, root)
+        including = form_set.issubset(ending_sets[pattern])
+        bad_forms = set()
+        for ending in pattern.endings.all():
+            if relevant(pos, ending, ic):
+                if root + ending.string not in form_set:
+                    bfl = ending.base_form_label.symbol
+                    #print pattern.name, root, ending.string, bfl
+                    bad_forms.add(root + ending.string)
+        if not bad_forms:
+            included_patterns.add((pattern, root))
+            if including:
+                matching_patterns.add((pattern, root))
+        elif including:
+            including_patterns.add(((pattern, root), tuple(bad_forms)))
+
+    # nie wiem, czy to potrzebne, ale na wszelki wypadek
+    included_patterns = list(included_patterns)
+    including_patterns = list(including_patterns)
+    matching_patterns = list(matching_patterns)
+    if len(matching_patterns) > 0:
+        if DEBUG:
+            print u'dokładne wzory: %s' % join(matching_patterns)
+        return 'match', matching_patterns, included_patterns, including_patterns
+        # nic nie pasuje albo trzeba wybrać wiele wzorów
+    if DEBUG and len(including_patterns) > 0:
+        print u'zawierające: %s' % join(p for p, b_f in including_patterns)
+    if DEBUG and len(included_patterns) > 0:
+        print u'zawarte: %s' % join(included_patterns)
+    return find_many_patterns(
+        pos, ic, form_set, basic_form, included_patterns, ending_sets) + (
+               included_patterns, including_patterns)
+
 
 def find_many_patterns(pos, ic, form_set, basic_form, included_patterns,
                        ending_sets):
-  necessary_patterns = set()
-  missing_form = None
-  for form in form_set:
-    having = []
-    for pattern, root in included_patterns:
-      if form in ending_sets[pattern]:
-        having.append((pattern, root))
-    if len(having) == 1:
-      necessary_patterns.add(having[0])
-    if having == []:
-      missing_form = form
-      break
-  if missing_form:
-    if DEBUG:
-      print u"brak formy: %s" % missing_form
-    return 'none', []
-  covered_forms = set()
-  for pattern, root in necessary_patterns:
-    covered_forms |= ending_sets[pattern]
-  if form_set.issubset(covered_forms):
-    if DEBUG:
-      print u"pokryte koniecznymi wzorami: %s" % join(necessary_patterns)
-    return 'many', [list(necessary_patterns)]
-  else:
-    #for pattern, root in included_patterns:
-    #  print pattern, ending_sets[pattern]
-    minimal_sets = find_minimal_sets(
-      form_set, covered_forms, necessary_patterns, included_patterns,
-      ending_sets)
-    return 'many', minimal_sets
+    necessary_patterns = set()
+    missing_form = None
+    for form in form_set:
+        having = []
+        for pattern, root in included_patterns:
+            if form in ending_sets[pattern]:
+                having.append((pattern, root))
+        if len(having) == 1:
+            necessary_patterns.add(having[0])
+        if having == []:
+            missing_form = form
+            break
+    if missing_form:
+        if DEBUG:
+            print u"brak formy: %s" % missing_form
+        return 'none', []
+    covered_forms = set()
+    for pattern, root in necessary_patterns:
+        covered_forms |= ending_sets[pattern]
+    if form_set.issubset(covered_forms):
+        if DEBUG:
+            print u"pokryte koniecznymi wzorami: %s" % join(necessary_patterns)
+        return 'many', [list(necessary_patterns)]
+    else:
+        #for pattern, root in included_patterns:
+        #  print pattern, ending_sets[pattern]
+        minimal_sets = find_minimal_sets(
+            form_set, covered_forms, necessary_patterns, included_patterns,
+            ending_sets)
+        return 'many', minimal_sets
+
 
 def filter_patterns(filter, action_name, type, patterns, included, including,
                     lexical_class, form_set, entry, ic):
-  old_patterns = patterns
-  old_included = included
-  bad_patterns = False
-  if type == 'many':
-    if any(pattern_set != filter(pattern_set) for pattern_set in patterns):
-      included = filter(included)
-      ending_sets = {}
-      for pattern, root in included:
-        ending_sets[pattern] = good_ending_set(lexical_class, ic, pattern, root)
-      type, patterns = find_many_patterns(
-        lexical_class, ic, form_set, entry, included, ending_sets)
-      if type != 'many':
-        debug(entry, u'mnogie dopasowanie zepsute przez %s (%s)' %
-                     (action_name, join_many(old_patterns)))
-        type = 'many'
-        patterns, included = old_patterns, old_included
-        bad_patterns = True
-  elif type == 'none':
-    including_dict = dict(including)
-    including = [(key, including_dict[key]) for key in filter(including_dict)]
-  else: # type == 'match'
-    patterns = filter(patterns)
-    including_dict = dict(including)
-    including = [(key, including_dict[key]) for key in filter(including_dict)]
-    included = filter(included)
-    if old_patterns and not patterns:
-      ending_sets = {}
-      for pattern, root in included:
-        ending_sets[pattern] = good_ending_set(lexical_class, ic, pattern, root)
-      type, patterns = find_many_patterns(
-        lexical_class, ic, form_set, entry, included, ending_sets)
-      if type == 'none':
-        debug(entry, u'znikły wzory przez %s (%s)' %
-                     (action_name, join(old_patterns)))
-        type = 'match'
-        patterns = old_patterns
-        bad_patterns = True
-  return type, patterns, included, including, bad_patterns
+    old_patterns = patterns
+    old_included = included
+    bad_patterns = False
+    if type == 'many':
+        if any(pattern_set != filter(pattern_set) for pattern_set in patterns):
+            included = filter(included)
+            ending_sets = {}
+            for pattern, root in included:
+                ending_sets[pattern] = good_ending_set(lexical_class, ic,
+                                                       pattern, root)
+            type, patterns = find_many_patterns(
+                lexical_class, ic, form_set, entry, included, ending_sets)
+            if type != 'many':
+                debug(entry, u'mnogie dopasowanie zepsute przez %s (%s)' %
+                             (action_name, join_many(old_patterns)))
+                type = 'many'
+                patterns, included = old_patterns, old_included
+                bad_patterns = True
+    elif type == 'none':
+        including_dict = dict(including)
+        including = [(key, including_dict[key]) for key in
+                     filter(including_dict)]
+    else: # type == 'match'
+        patterns = filter(patterns)
+        including_dict = dict(including)
+        including = [(key, including_dict[key]) for key in
+                     filter(including_dict)]
+        included = filter(included)
+        if old_patterns and not patterns:
+            ending_sets = {}
+            for pattern, root in included:
+                ending_sets[pattern] = good_ending_set(lexical_class, ic,
+                                                       pattern, root)
+            type, patterns = find_many_patterns(
+                lexical_class, ic, form_set, entry, included, ending_sets)
+            if type == 'none':
+                debug(entry, u'znikły wzory przez %s (%s)' %
+                             (action_name, join(old_patterns)))
+                type = 'match'
+                patterns = old_patterns
+                bad_patterns = True
+    return type, patterns, included, including, bad_patterns
+
 
 def process_forms(forms, base, pos, commonness):
-  if Lexeme.objects.filter(entry=base):
-    return
-  ic = inflection_characteristic(forms, pos)
-  form_set = set(form for form, tag in forms)
-  type, patterns, included, including = find_patterns(base, pos, ic, forms)
-  type, patterns, included, including, bad_patterns = filter_patterns(
-    blacklist_filter, u'czarną listę', type, patterns, included, including,
-    pos, form_set, base, ic)
-  # wzory się już nie zmienią od tego miejsca
-  if type == 'many':
-    all_patterns = [p for pattern_set in patterns for p in pattern_set]
-  else:
-    all_patterns = patterns
-
-  if type == 'none':
-    debug(base, u'zawiera się w %s' % join(p for p, b_f in including))
-    chosen = []
-    fitting = including
-    if pos == 'adj' and including:
-      print_forms(forms, 'rzeczownik#')
-      return
-  elif type == 'match':
-    patterns.sort(key=lambda p: p[0].name)
-    fitting = patterns
-    chosen = patterns[:1]
-  elif type == 'many':
-    chosen = patterns[0]
-    if DEBUG:
-      print u'zestawy wielu wzorów: %s' % join_many(patterns)
-    fitting = patterns
-
-  if not DEBUG:
-    comments = [u'z Korpusu IPI 1.0']
-    if commonness == u'własna' or type != 'match' or len(fitting) > 1:
-      status = 'cand'
+    if Lexeme.objects.filter(entry=base):
+        return
+    ic = inflection_characteristic(forms, pos)
+    form_set = set(form for form, tag in forms)
+    type, patterns, included, including = find_patterns(base, pos, ic, forms)
+    type, patterns, included, including, bad_patterns = filter_patterns(
+        blacklist_filter, u'czarną listę', type, patterns, included, including,
+        pos, form_set, base, ic)
+    # wzory się już nie zmienią od tego miejsca
+    if type == 'many':
+        all_patterns = [p for pattern_set in patterns for p in pattern_set]
     else:
-      status = 'desc'
-    if bad_patterns:
-      comments.append(u'Wzory z czarnej listy!')
-      status = 'cand'
-    if len(fitting) > 1 or (type == 'none' and fitting):
-      if type == 'none':
-        comments.append(u'Zawierające wzory:')
-        for (pattern, root), bad_forms in fitting:
-          comments.append(u'%s: %s' % (pattern.name, ', '.join(bad_forms)))
-      elif type != 'many':
-        comments.append(u'Pasujące wzory: %s' % join(fitting))
-      else:
-        comments.append(u'Pasujące zestawy wzorów: %s' % join_many(fitting))
-    comment = '\n'.join(comments)
-    lips = []
-    for i, pattern in enumerate(chosen):
-      lips.append(create_lip(pattern[0], pattern[1], i + 1, ic, pos))
-    lexeme_data = create_lexeme(base, 1, pos, status, comment)
-    lexeme_data['commonness'] = commonness
-    data = {
-      'lexeme': lexeme_data,
-      'lips': lips,
-    }
-    print_data(data)
+        all_patterns = patterns
+
+    if type == 'none':
+        debug(base, u'zawiera się w %s' % join(p for p, b_f in including))
+        chosen = []
+        fitting = including
+        if pos == 'adj' and including:
+            print_forms(forms, 'rzeczownik#')
+            return
+    elif type == 'match':
+        patterns.sort(key=lambda p: p[0].name)
+        fitting = patterns
+        chosen = patterns[:1]
+    elif type == 'many':
+        chosen = patterns[0]
+        if DEBUG:
+            print u'zestawy wielu wzorów: %s' % join_many(patterns)
+        fitting = patterns
+
+    if not DEBUG:
+        comments = [u'z Korpusu IPI 1.0']
+        if commonness == u'własna' or type != 'match' or len(fitting) > 1:
+            status = 'cand'
+        else:
+            status = 'desc'
+        if bad_patterns:
+            comments.append(u'Wzory z czarnej listy!')
+            status = 'cand'
+        if len(fitting) > 1 or (type == 'none' and fitting):
+            if type == 'none':
+                comments.append(u'Zawierające wzory:')
+                for (pattern, root), bad_forms in fitting:
+                    comments.append(
+                        u'%s: %s' % (pattern.name, ', '.join(bad_forms)))
+            elif type != 'many':
+                comments.append(u'Pasujące wzory: %s' % join(fitting))
+            else:
+                comments.append(
+                    u'Pasujące zestawy wzorów: %s' % join_many(fitting))
+        comment = '\n'.join(comments)
+        lips = []
+        for i, pattern in enumerate(chosen):
+            lips.append(create_lip(pattern[0], pattern[1], i + 1, ic, pos))
+        lexeme_data = create_lexeme(base, 1, pos, status, comment)
+        lexeme_data['commonness'] = commonness
+        data = {
+            'lexeme': lexeme_data,
+            'lips': lips,
+        }
+        print_data(data)
+
 
 def import_kipi(input_file):
-  last_key = None
-  forms = None
-  for line in input_file:
-    data = line.strip().decode('utf-8').split('\t')
-    form, base, comm, tag = data
-    pos = 'subst' if tag.startswith('subst') else 'adj' # bez split, bo adja
-    key = (base, pos, comm)
-    if key != last_key:
-      if last_key is not None:
-        process_forms(forms, last_key[0], last_key[1], COMMONNESS[last_key[2]])
-      last_key = key
-      forms = []
-    forms.append((form, tag))
-  process_forms(forms, last_key[0], last_key[1], COMMONNESS[last_key[2]])
+    last_key = None
+    forms = None
+    for line in input_file:
+        data = line.strip().decode('utf-8').split('\t')
+        form, base, comm, tag = data
+        pos = 'subst' if tag.startswith('subst') else 'adj' # bez split, bo adja
+        key = (base, pos, comm)
+        if key != last_key:
+            if last_key is not None:
+                process_forms(forms, last_key[0], last_key[1],
+                              COMMONNESS[last_key[2]])
+            last_key = key
+            forms = []
+        forms.append((form, tag))
+    process_forms(forms, last_key[0], last_key[1], COMMONNESS[last_key[2]])
diff --git a/dictionary/management/commands/import_morfologik.py b/dictionary/management/commands/import_morfologik.py
index 835aa48..e36b1e6 100644
--- a/dictionary/management/commands/import_morfologik.py
+++ b/dictionary/management/commands/import_morfologik.py
@@ -1,20 +1,24 @@
 #-*- coding:utf-8 -*-
 
-from django.core.management.base import BaseCommand
 import sys
 import json
+
+from django.core.management.base import BaseCommand
+
 from common.util import suffixes, cut_end, debug, GroupDict
 from dictionary.models import Pattern, Lexeme, InflectionCharacteristic, \
-  Ending, LexicalClass, CrossReference, BaseFormLabel, Vocabulary
+    Ending, LexicalClass, CrossReference, BaseFormLabel, Vocabulary
 from dictionary.util import expand_tag, compare_patterns
 from dictionary.pattern_blacklist import blacklist
 
+
 class Command(BaseCommand):
-  args = '<symbol części mowy> <nazwa pliku wejściowego>'
-  help = 'Creates scripts for importing data from Morfologik'
+    args = '<symbol części mowy> <nazwa pliku wejściowego>'
+    help = 'Creates scripts for importing data from Morfologik'
+
+    def handle(self, lc_sym, input_file, **options):
+        parse_file(lc_sym, input_file)
 
-  def handle(self, lc_sym, input_file, **options):
-    parse_file(lc_sym, input_file)
 
 DEBUG = False
 
@@ -24,1207 +28,1295 @@ sgjp = Lexeme.objects.filter(source='SGJP')
 
 # może być nierozpoznane pltant
 ending_genders = {
-  'm1': ['m1', 'p1'],
-  'm': ['m2', 'm3', 'p2', 'p3'],
-  'f': ['f', 'p2', 'p3'],
-  'n': ['n1', 'n2', 'p2', 'p3'],
-  'p1': ['p1'],
-  'p3': ['p2', 'p3'],
-  'i': [], # wszystkie
+    'm1': ['m1', 'p1'],
+    'm': ['m2', 'm3', 'p2', 'p3'],
+    'f': ['f', 'p2', 'p3'],
+    'n': ['n1', 'n2', 'p2', 'p3'],
+    'p1': ['p1'],
+    'p3': ['p2', 'p3'],
+    'i': [], # wszystkie
 }
 
 genders = {
-  'm1': ['m1'],
-  'm': ['m2', 'm3'], #, 'p1', 'p2', 'p3'],
-  'f': ['f'], #, 'p2', 'p3'],
-  'n': ['n1', 'n2'], #, 'p2', 'p3'],
-  'p1': ['p1'],
-  'p3': ['p2', 'p3'],
-  'i': [], # wszystkie
+    'm1': ['m1'],
+    'm': ['m2', 'm3'], #, 'p1', 'p2', 'p3'],
+    'f': ['f'], #, 'p2', 'p3'],
+    'n': ['n1', 'n2'], #, 'p2', 'p3'],
+    'p1': ['p1'],
+    'p3': ['p2', 'p3'],
+    'i': [], # wszystkie
 }
 
 # piękne nazwy...
 genders2 = {
-  'm1': ['m1', 'p1'],
-  'm': ['m2', 'm3', 'p2', 'p3'],
-  'f': ['f', 'p2', 'p3'],
-  'n': ['n1', 'n2', 'p2', 'p3'],
-  'p1': ['p1', 'm1'],
-  'p3': ['p2', 'p3', 'f', 'm2', 'm3', 'n1', 'n2'],
-  'i': [], # wszystkie
+    'm1': ['m1', 'p1'],
+    'm': ['m2', 'm3', 'p2', 'p3'],
+    'f': ['f', 'p2', 'p3'],
+    'n': ['n1', 'n2', 'p2', 'p3'],
+    'p1': ['p1', 'm1'],
+    'p3': ['p2', 'p3', 'f', 'm2', 'm3', 'n1', 'n2'],
+    'i': [], # wszystkie
 }
 
+
 def get_basic_endings(lexical_class, parts_of_speech, gender=None):
-  if lexical_class.symbol == 'v':
-    return Ending.objects.filter(
-      base_form_label__symbol='5', pattern__type__lexical_class=lexical_class)
-  ics = InflectionCharacteristic.objects.filter(
-    part_of_speech__in=parts_of_speech)
-  if gender and ending_genders[gender]:
-    ics = ics.filter(symbol__in=ending_genders[gender])
-  basic_form_labels = ics.values_list('basic_form_label', flat=True).distinct()
-  return Ending.objects.filter(base_form_label__pk__in=basic_form_labels,
-                               pattern__type__lexical_class=lexical_class)
+    if lexical_class.symbol == 'v':
+        return Ending.objects.filter(
+            base_form_label__symbol='5',
+            pattern__type__lexical_class=lexical_class)
+    ics = InflectionCharacteristic.objects.filter(
+        part_of_speech__in=parts_of_speech)
+    if gender and ending_genders[gender]:
+        ics = ics.filter(symbol__in=ending_genders[gender])
+    basic_form_labels = ics.values_list('basic_form_label',
+                                        flat=True).distinct()
+    return Ending.objects.filter(base_form_label__pk__in=basic_form_labels,
+                                 pattern__type__lexical_class=lexical_class)
+
 
 basic_form_endings_dict = {}
 for lexical_class in LexicalClass.objects.all():
-  parts_of_speech = lexical_class.partofspeech_set.all()
-  if lexical_class.symbol == 'subst':
-    for gender in ending_genders:
-      basic_form_endings_dict[(lexical_class, gender)] = get_basic_endings(
-        lexical_class, parts_of_speech, gender)
-  else:
-    basic_form_endings_dict[lexical_class] = get_basic_endings(
-      lexical_class, parts_of_speech)
+    parts_of_speech = lexical_class.partofspeech_set.all()
+    if lexical_class.symbol == 'subst':
+        for gender in ending_genders:
+            basic_form_endings_dict[
+                (lexical_class, gender)] = get_basic_endings(
+                lexical_class, parts_of_speech, gender)
+    else:
+        basic_form_endings_dict[lexical_class] = get_basic_endings(
+            lexical_class, parts_of_speech)
+
 
 def join(patterns):
-  return ', '.join(sorted(p[0].name for p in patterns))
+    return ', '.join(sorted(p[0].name for p in patterns))
+
 
 def join_many(patterns):
-  return ', '.join('[%s]' % join(set) for set in patterns)
+    return ', '.join('[%s]' % join(set) for set in patterns)
+
 
 def prepare_endings(forms):
-  root = forms[0][0]
-  for form in forms[1:]:
-    new_root = ''
-    for char1, char2 in zip(root, form[0]):
-      if char1 == char2:
-        new_root += char1
-      else:
-        break
-    root = new_root
-  endings = set()
-  for form in forms:
-    endings.add((form[0][len(root):], form[1]))
-  return endings, root
+    root = forms[0][0]
+    for form in forms[1:]:
+        new_root = ''
+        for char1, char2 in zip(root, form[0]):
+            if char1 == char2:
+                new_root += char1
+            else:
+                break
+        root = new_root
+    endings = set()
+    for form in forms:
+        endings.add((form[0][len(root):], form[1]))
+    return endings, root
+
 
 def get_form_set(forms):
-  form_set = set(form[0] for form in forms)
-  return form_set - set('nie' + form for form in form_set)
+    form_set = set(form[0] for form in forms)
+    return form_set - set('nie' + form for form in form_set)
+
 
 def expand_forms(forms):
-  expanded = []
-  for form in forms:
-    tags = expand_tag(form[1])
-    expanded += [(form[0], tag) for tag in tags]
-  return expanded
+    expanded = []
+    for form in forms:
+        tags = expand_tag(form[1])
+        expanded += [(form[0], tag) for tag in tags]
+    return expanded
+
 
 def get_tantum(forms):
-  sg = set()
-  pl = set()
-  for form in forms:
-    if form[1][1].startswith('pl'):
-      pl.add(form[0])
-    elif form[1][1].startswith('sg'): # ignorujemy irreg
-      sg.add(form[0])
-  if sg == pl:
-    return
-  # za dużo fałszywych pozytywów
-  #elif pl.issubset(sg):
-  #  return 'sg'
-  elif sg.issubset(pl): # or len(sg) == 1: -- czasem psuje
-    return 'pl'
-  else:
-    return
+    sg = set()
+    pl = set()
+    for form in forms:
+        if form[1][1].startswith('pl'):
+            pl.add(form[0])
+        elif form[1][1].startswith('sg'): # ignorujemy irreg
+            sg.add(form[0])
+    if sg == pl:
+        return
+    # za dużo fałszywych pozytywów
+    #elif pl.issubset(sg):
+    #  return 'sg'
+    elif sg.issubset(pl): # or len(sg) == 1: -- czasem psuje
+        return 'pl'
+    else:
+        return
+
 
 def tantum_a_posteriori(form_set, patterns):
-  tantum = None
-  for pattern, root in patterns:
-    tantum_forms = {
-      'sg': set(root + e for e in
-                pattern.endings.filter(base_form_label__symbol__startswith='sg')
-                .values_list('string', flat=True)),
-      'pl': set(root + e for e in
-                pattern.endings.filter(base_form_label__symbol__startswith='pl')
-                .values_list('string', flat=True)),
-    }
-    for num in ('sg', 'pl'):
-      if form_set.issubset(tantum_forms[num]):
-        tantum = num
-    if tantum:
-      return tantum
-  if not patterns:
-    return 'sg'
-  return None
+    tantum = None
+    for pattern, root in patterns:
+        tantum_forms = {
+            'sg': set(root + e for e in
+                      pattern.endings.filter(
+                          base_form_label__symbol__startswith='sg')
+                      .values_list('string', flat=True)),
+            'pl': set(root + e for e in
+                      pattern.endings.filter(
+                          base_form_label__symbol__startswith='pl')
+                      .values_list('string', flat=True)),
+        }
+        for num in ('sg', 'pl'):
+            if form_set.issubset(tantum_forms[num]):
+                tantum = num
+        if tantum:
+            return tantum
+    if not patterns:
+        return 'sg'
+    return None
+
 
 v_base_forms = [
-  ('1', 'verb:fin:sg:ter:', u''),
-  ('2', 'verb:fin:sg:pri:', u''),
-  ('3', 'verb:fin:pl:ter:', u''),
-  ('4', 'verb:impt:sg:sec:', u''),
-  ('5', 'verb:inf:', u''),
-  ('6', 'verb:praet:sg:ter:m:', u''),
-  ("6'", 'pant:perf', u'szy'),
-  ('7', 'verb:praet:sg:pri:m:', u'em'),
-  ('8', 'verb:praet:sg:pri:f:', u'am'),
-  ('9', 'verb:praet:pl:ter:m1:', u'i'),
-  ('10', 'verb:imps', u'o'),
-  ('11', 'subst:ger:sg:nom:n', u'ie'), # [bez przeczenia]
-  ('11pg', 'subst:ger:pl:gen:n', u''),
-  ('12', 'ppas:pl:nom:m1', u''),
+    ('1', 'verb:fin:sg:ter:', u''),
+    ('2', 'verb:fin:sg:pri:', u''),
+    ('3', 'verb:fin:pl:ter:', u''),
+    ('4', 'verb:impt:sg:sec:', u''),
+    ('5', 'verb:inf:', u''),
+    ('6', 'verb:praet:sg:ter:m:', u''),
+    ("6'", 'pant:perf', u'szy'),
+    ('7', 'verb:praet:sg:pri:m:', u'em'),
+    ('8', 'verb:praet:sg:pri:f:', u'am'),
+    ('9', 'verb:praet:pl:ter:m1:', u'i'),
+    ('10', 'verb:imps', u'o'),
+    ('11', 'subst:ger:sg:nom:n', u'ie'), # [bez przeczenia]
+    ('11pg', 'subst:ger:pl:gen:n', u''),
+    ('12', 'ppas:pl:nom:m1', u''),
 ]
 
+
 def get_extra(lexical_class, forms, **extra):
-  if lexical_class.symbol == 'subst':
-    if 'tantum' in extra:
-      tantum = extra['tantum']
+    if lexical_class.symbol == 'subst':
+        if 'tantum' in extra:
+            tantum = extra['tantum']
+        else:
+            tantum = get_tantum(forms)
+        tag = forms[0][1]
+        gender = tag[-1][0]
+        # powinienem częściej tak pisać zamiast for...else jeśli się da
+        if all(form[1][-1] in ('m1', 'depr') for form in forms):
+            gender = 'm1'
+        if tantum == 'pl' or tag[1] == 'pltant':
+            gender = 'p'
+            tantum = 'pl'
+        return {'gender': gender, 'tantum': tantum}
+    elif lexical_class.symbol == 'adj':
+        all_forms = [form[0] for form in forms]
+        negated = [(form, tag) for (form, tag) in forms
+                   if form == 'nie' + all_forms[0]]
+        negated += [(form, tag) for (form, tag) in forms
+                    if form.startswith('nie') and form[4:] in all_forms
+            and form != 'nie' + all_forms[0]]
+        return {'negated': negated}
+    elif lexical_class.symbol == 'v':
+        all_forms = [form[0] for form in forms]
+        base_forms = []
+        for label, tag_prefix, end in v_base_forms:
+            for form, tag in forms:
+                negated_form = (form.startswith(u'nie') and
+                                form[len('nie'):] in all_forms)
+                if (':'.join(tag).startswith(tag_prefix) and
+                        not (form.endswith(u'że') and tag[1] == 'impt')
+                    and not negated_form):
+                    if form.endswith(end): # ech...
+                        base_form = cut_end(form, end)
+                        if label == '10':
+                            bf10 = base_form
+                        base_forms.append((base_form, label))
+        derived = set()
+        labels = set(label for (form, label) in base_forms)
+        if '10' in labels and bf10 + 'y' in all_forms:
+            derived.add('ppas')
+        for form, tag in forms:
+            plain_tag = ':'.join(tag)
+            if plain_tag.startswith('subst:ger') and '11' in labels:
+                derived.add('ger')
+            if plain_tag.startswith('pact') and '3' in labels:
+                derived.add('pact')
+        old_base_forms = base_forms
+        if 'ppas' not in derived:
+            base_forms = []
+            for base_form, label in old_base_forms:
+                if label != '12':
+                    base_forms.append((base_form, label))
+        if DEBUG:
+            for f, l in base_forms:
+                print f, l
+        return {'base_forms': base_forms, 'derived': derived}
     else:
-      tantum = get_tantum(forms)
-    tag = forms[0][1]
-    gender = tag[-1][0]
-    # powinienem częściej tak pisać zamiast for...else jeśli się da
-    if all(form[1][-1] in ('m1', 'depr') for form in forms):
-      gender = 'm1'
-    if tantum == 'pl' or tag[1] == 'pltant':
-      gender = 'p'
-      tantum = 'pl'
-    return {'gender': gender, 'tantum': tantum}
-  elif lexical_class.symbol == 'adj':
-    all_forms = [form[0] for form in forms]
-    negated = [(form, tag) for (form, tag) in forms
-               if form == 'nie' + all_forms[0]]
-    negated += [(form, tag) for (form, tag) in forms
-                if form.startswith('nie') and form[4:] in all_forms
-                and form != 'nie' + all_forms[0]]
-    return {'negated': negated}
-  elif lexical_class.symbol == 'v':
-    all_forms = [form[0] for form in forms]
-    base_forms = []
-    for label, tag_prefix, end in v_base_forms:
-      for form, tag in forms:
-        negated_form = (form.startswith(u'nie') and
-                        form[len('nie'):] in all_forms)
-        if (':'.join(tag).startswith(tag_prefix) and
-            not (form.endswith(u'że') and tag[1] == 'impt')
-            and not negated_form):
-          if form.endswith(end): # ech...
-            base_form = cut_end(form, end)
-            if label == '10':
-              bf10 = base_form
-            base_forms.append((base_form, label))
-    derived = set()
-    labels = set(label for (form, label) in base_forms)
-    if '10' in labels and bf10 + 'y' in all_forms:
-      derived.add('ppas')
-    for form, tag in forms:
-      plain_tag = ':'.join(tag)
-      if plain_tag.startswith('subst:ger') and '11' in labels:
-        derived.add('ger')
-      if plain_tag.startswith('pact') and '3' in labels:
-        derived.add('pact')
-    old_base_forms = base_forms
-    if 'ppas' not in derived:
-      base_forms = []
-      for base_form, label in old_base_forms:
-        if label != '12':
-          base_forms.append((base_form, label))
-    if DEBUG:
-      for f, l in base_forms:
-        print f, l
-    return {'base_forms': base_forms, 'derived': derived}
-  else:
-    return {}
+        return {}
 
 
 def relevant_subst(ending, gender, tantum):
-  bfl = ending.base_form_label.symbol
-  tag = bfl.split(':')
-  pattern_type = ending.pattern.type.symbol
-  return (not (gender in ('m1', 'p1') and bfl == 'pl:nom') and
-          not (len(tag) >= 3 and gender[0] != 'p' and
-               tag[2][0] != gender[0]) and
-          not (tantum and tag[0] != tantum) and
-          not (gender == 'p3' and bfl.startswith('pl:gen:') and (
+    bfl = ending.base_form_label.symbol
+    tag = bfl.split(':')
+    pattern_type = ending.pattern.type.symbol
+    return (not (gender in ('m1', 'p1') and bfl == 'pl:nom') and
+            not (len(tag) >= 3 and gender[0] != 'p' and
+                 tag[2][0] != gender[0]) and
+            not (tantum and tag[0] != tantum) and
+            not (gender == 'p3' and bfl.startswith('pl:gen:') and (
                 (pattern_type == 'n' and tag[2] == 'n') or
                 (pattern_type == 'f' and tag[2] == 'm')
-              )) and
-          not (gender not in ('m1', 'p1') and bfl == 'pl:nom:mo'))
+            )) and
+            not (gender not in ('m1', 'p1') and bfl == 'pl:nom:mo'))
+
 
 def relevant_adj(ending):
-  tag = ending.base_form_label.symbol
-  return tag not in ('0', '3+')
+    tag = ending.base_form_label.symbol
+    return tag not in ('0', '3+')
+
 
 def relevant_v(ending, base_forms, derived):
-  tag = ending.base_form_label.symbol
-  if 'ppas' not in derived and tag == '12':
-    return False
-  if 'ger' not in derived and tag in ('11', '11pg'):
-    return False
-  return tag not in ("6'",)
+    tag = ending.base_form_label.symbol
+    if 'ppas' not in derived and tag == '12':
+        return False
+    if 'ger' not in derived and tag in ('11', '11pg'):
+        return False
+    return tag not in ("6'",)
+
 
 def relevant(lexical_class, ending, **extra):
-  if lexical_class.symbol == 'subst':
-    return relevant_subst(ending, **extra)
-  elif lexical_class.symbol == 'adj':
-    return relevant_adj(ending)
-  elif lexical_class.symbol == 'v':
-    return relevant_v(ending, **extra)
+    if lexical_class.symbol == 'subst':
+        return relevant_subst(ending, **extra)
+    elif lexical_class.symbol == 'adj':
+        return relevant_adj(ending)
+    elif lexical_class.symbol == 'v':
+        return relevant_v(ending, **extra)
+
 
 from itertools import chain, combinations
+
+
 def powerset(iterable):
-  """powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"""
-  s = list(iterable)
-  return chain.from_iterable(
-    combinations(s, r) for r in range(min(len(s)+1, 5)))
+    """powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"""
+    s = list(iterable)
+    return chain.from_iterable(
+        combinations(s, r) for r in range(min(len(s) + 1, 5)))
+
 
 def find_minimal_sets(form_set, covered_forms, necessary_patterns,
                       included_patterns, ending_sets):
-  unnecessary_patterns = list(set(included_patterns) - set(necessary_patterns))
-  found = []
-  for subset in powerset(unnecessary_patterns):
-    for found_set in found:
-      if set(tuple(necessary_patterns) + subset).issuperset(found_set):
-        break
-    else:
-      new_covered = set(covered_forms)
-      for pattern, root in subset:
-        new_covered |= ending_sets[pattern]
-      if form_set.issubset(new_covered):
-        found.append(tuple(necessary_patterns) + subset)
-  return found
+    unnecessary_patterns = list(
+        set(included_patterns) - set(necessary_patterns))
+    found = []
+    for subset in powerset(unnecessary_patterns):
+        for found_set in found:
+            if set(tuple(necessary_patterns) + subset).issuperset(found_set):
+                break
+        else:
+            new_covered = set(covered_forms)
+            for pattern, root in subset:
+                new_covered |= ending_sets[pattern]
+            if form_set.issubset(new_covered):
+                found.append(tuple(necessary_patterns) + subset)
+    return found
+
 
 sure_bfls_sg = tuple(
-  BaseFormLabel.objects.filter(
-    symbol__in=['sg:dat', 'sg:gen', 'sg:inst']).values_list('pk', flat=True))
+    BaseFormLabel.objects.filter(
+        symbol__in=['sg:dat', 'sg:gen', 'sg:inst']).values_list('pk',
+                                                                flat=True))
 sure_bfls_pl = tuple(
-  BaseFormLabel.objects.filter(
-    symbol__in=['pl:dat', 'pl:inst', 'pl:loc']).values_list('pk', flat=True))
+    BaseFormLabel.objects.filter(
+        symbol__in=['pl:dat', 'pl:inst', 'pl:loc']).values_list('pk',
+                                                                flat=True))
+
 
 def basic_form_endings(lexical_class, basic_form, form_set, **extra):
-  if 'gender' in extra:
-    key = (lexical_class, extra['gender'])
-  else:
-    key = lexical_class
-  if lexical_class.symbol != 'subst':
-    return basic_form_endings_dict[key].filter(string__in=suffixes(basic_form))
-  else:
-    # karkołomne, ale trochę przyśpiesza
-    endings = basic_form_endings_dict[key]
-    new_endings = Ending.objects.none()
-    for suf in suffixes(basic_form):
-      root = cut_end(basic_form, suf)
-      n = len(root)
-      ending_strings = tuple(
-        form[n:] for form in form_set if form.startswith(root))
-      endings_part = endings.filter(string=suf)
-      pattern_pks = endings_part.values_list('pattern', flat=True)
-      patterns = Pattern.objects.filter(pk__in=pattern_pks).extra(
-        where=["(w_id = '0000' or not exists "
-               "(select id from zakonczenia where w_id = wzory.id "
-               "and zak not in %s and efobaz in %s) or not exists "
-               "(select id from zakonczenia where w_id = wzory.id "
-               "and zak not in %s and efobaz in %s))"],
-        params=[ending_strings, sure_bfls_sg, ending_strings, sure_bfls_pl])
-      new_endings = new_endings | endings_part.filter(pattern__in=patterns)
-    return new_endings
+    if 'gender' in extra:
+        key = (lexical_class, extra['gender'])
+    else:
+        key = lexical_class
+    if lexical_class.symbol != 'subst':
+        return basic_form_endings_dict[key].filter(
+            string__in=suffixes(basic_form))
+    else:
+        # karkołomne, ale trochę przyśpiesza
+        endings = basic_form_endings_dict[key]
+        new_endings = Ending.objects.none()
+        for suf in suffixes(basic_form):
+            root = cut_end(basic_form, suf)
+            n = len(root)
+            ending_strings = tuple(
+                form[n:] for form in form_set if form.startswith(root))
+            endings_part = endings.filter(string=suf)
+            pattern_pks = endings_part.values_list('pattern', flat=True)
+            patterns = Pattern.objects.filter(pk__in=pattern_pks).extra(
+                where=["(w_id = '0000' or not exists "
+                       "(select id from zakonczenia where w_id = wzory.id "
+                       "and zak not in %s and efobaz in %s) or not exists "
+                       "(select id from zakonczenia where w_id = wzory.id "
+                       "and zak not in %s and efobaz in %s))"],
+                params=[ending_strings, sure_bfls_sg, ending_strings,
+                        sure_bfls_pl])
+            new_endings = new_endings | endings_part.filter(
+                pattern__in=patterns)
+        return new_endings
+
 
 memoized_good_endings = {}
 
+
 def good_ending_set_subst(pattern, root, tantum, gender):
-  if (pattern, tantum, gender) in memoized_good_endings:
-    good_endings = memoized_good_endings[(pattern, tantum, gender)]
+    if (pattern, tantum, gender) in memoized_good_endings:
+        good_endings = memoized_good_endings[(pattern, tantum, gender)]
+        return set(root + e for e in good_endings)
+    endings = pattern.endings
+    if tantum:
+        endings = endings.filter(base_form_label__symbol__startswith=tantum)
+    if gender not in ('m1', 'p1'):
+        endings = endings.exclude(base_form_label__symbol='pl:nom:mo')
+    if gender[0] != 'p':
+        for g in list(set('mfn') - set(gender[0])):
+            endings = endings.exclude(
+                base_form_label__symbol__startswith='pl:gen:' + g)
+    if gender == 'p3':
+        if pattern.type.symbol == 'f':
+            endings = endings.exclude(base_form_label__symbol='pl:gen:m')
+        if pattern.type.symbol == 'n':
+            endings = endings.exclude(base_form_label__symbol='pl:gen:n')
+    good_endings = list(endings.values_list('string', flat=True))
+    memoized_good_endings[(pattern, tantum, gender)] = good_endings
     return set(root + e for e in good_endings)
-  endings = pattern.endings
-  if tantum:
-    endings = endings.filter(base_form_label__symbol__startswith=tantum)
-  if gender not in ('m1', 'p1'):
-    endings = endings.exclude(base_form_label__symbol='pl:nom:mo')
-  if gender[0] != 'p':
-    for g in list(set('mfn') - set(gender[0])):
-      endings = endings.exclude(
-        base_form_label__symbol__startswith='pl:gen:' + g)
-  if gender == 'p3':
-    if pattern.type.symbol == 'f':
-      endings = endings.exclude(base_form_label__symbol='pl:gen:m')
-    if pattern.type.symbol == 'n':
-      endings = endings.exclude(base_form_label__symbol='pl:gen:n')
-  good_endings = list(endings.values_list('string', flat=True))
-  memoized_good_endings[(pattern, tantum, gender)] = good_endings
-  return set(root + e for e in good_endings)
+
 
 def good_ending_set(lexical_class, pattern, root='', **extra):
-  if lexical_class.symbol != 'subst':
-    return pattern.ending_set(root)
-  else:
-    return good_ending_set_subst(pattern, root, **extra)
+    if lexical_class.symbol != 'subst':
+        return pattern.ending_set(root)
+    else:
+        return good_ending_set_subst(pattern, root, **extra)
+
 
 memoized_pattern_ics = {}
 
+
 def bad_pattern_subst(pattern, gender, tantum):
-  if (pattern, gender) in memoized_pattern_ics:
-    return memoized_pattern_ics[(pattern, gender)]
-  ics = genders2[gender]
-  if not pattern.lexemeinflectionpattern_set.filter(
-       inflection_characteristic__symbol__in=ics).filter(lexeme__pk__in=sgjp):
-    ret = True
-  elif pattern.type.symbol in 'mn' and gender == 'f':
-    ret = True
-  elif pattern.type.symbol in 'fm' and gender == 'n':
-    ret = True
-  else:
-    ret = False
-  memoized_pattern_ics[(pattern, gender)] = ret
-  return ret
+    if (pattern, gender) in memoized_pattern_ics:
+        return memoized_pattern_ics[(pattern, gender)]
+    ics = genders2[gender]
+    if not pattern.lexemeinflectionpattern_set.filter(
+            inflection_characteristic__symbol__in=ics).filter(
+            lexeme__pk__in=sgjp):
+        ret = True
+    elif pattern.type.symbol in 'mn' and gender == 'f':
+        ret = True
+    elif pattern.type.symbol in 'fm' and gender == 'n':
+        ret = True
+    else:
+        ret = False
+    memoized_pattern_ics[(pattern, gender)] = ret
+    return ret
 
 
 def find_patterns(lexical_class, forms, **extra):
-  basic_form = forms[0][0]
-  patterns = Pattern.objects.filter(type__lexical_class=lexical_class)
-  # znaleźć wszystkie zawarte i zawierające wzory
-  form_set = get_form_set(forms)
-  if lexical_class.symbol == 'v':
-    form_set = set(form for form, label in extra['base_forms'])
-    all_forms = set(form for form, tag in forms)
-  ending_sets = {}
-  included_patterns = set()
-  including_patterns = set()
-  matching_patterns = set()
-  base_forms_changed = False
-  for basic_ending in basic_form_endings(lexical_class, basic_form, form_set, **extra):
-    pattern = basic_ending.pattern
-    if lexical_class.symbol == 'subst' and bad_pattern_subst(pattern, **extra):
-      #print 'odpadł:', pattern
-      continue # olewamy komentarze że formy odrzucone przez charfle?
-    root = basic_form[:len(basic_form) - len(basic_ending.string)]
-    ending_sets[pattern] = good_ending_set(
-      lexical_class, pattern, root, **extra)
-    including = form_set.issubset(ending_sets[pattern])
-    extra_base_forms = []
-    bad_forms = set()
-    for ending in pattern.endings.all():
-      if relevant(lexical_class, ending, **extra):
-        if root + ending.string not in form_set:
-          bfl = ending.base_form_label.symbol
-          #print pattern.name, root, ending.string, bfl
-          if lexical_class.symbol == 'v':
-            for label, tag, end in v_base_forms:
-              if label == bfl:
-                if root + ending.string + end in all_forms:
-                  for form, tag in forms:
-                    if form == root + ending.string + end:
-                      this_tag = tag
-                      break
-                  # ech... uwielbiam zgadywać błędy
-                  if (bfl in ('4', '5', "6'", '10', '11', '11pg', '12') and
-                      (this_tag == ('verb', 'irreg') or this_tag[1] == 'ger')):
-                    extra_base_forms.append(
-                      (root + ending.string, label))
-                    break
-            else: # jeśli to nie była niewykryta forma bazowa
-              for label, tag, end in v_base_forms:
-                if label == bfl:
-                  bad_forms.add(root + ending.string + end)
-                  break
-          else: # inne części mowy nie mają istotnych sufiksów?
-            bad_forms.add(root + ending.string)
-    if not bad_forms:
-      if extra_base_forms:
-        extra['base_forms'] += extra_base_forms
-        base_forms_changed = True
-      included_patterns.add((pattern, root))
-      if including:
-        matching_patterns.add((pattern, root))
-    elif including:
-      including_patterns.add(((pattern, root), tuple(bad_forms)))
-
-  if base_forms_changed:
-    #print extra['base_forms']
-    return find_patterns(lexical_class, forms, **extra)
-  # nie wiem, czy to potrzebne, ale na wszelki wypadek
-  included_patterns = list(included_patterns)
-  including_patterns = list(including_patterns)
-  matching_patterns = list(matching_patterns)
-  if len(matching_patterns) > 0:
-    if DEBUG:
-      print u'dokładne wzory: %s' % join(matching_patterns)
-    return 'match', matching_patterns, included_patterns, including_patterns
-  # nic nie pasuje albo trzeba wybrać wiele wzorów
-  if DEBUG and len(including_patterns) > 0:
-    print u'zawierające: %s' % join(p for p, b_f in including_patterns)
-  if DEBUG and len(included_patterns) > 0:
-    print u'zawarte: %s' % join(included_patterns)
-  return find_many_patterns(
-    lexical_class, form_set, basic_form, included_patterns, ending_sets,
-    **extra) + (included_patterns, including_patterns)
+    basic_form = forms[0][0]
+    patterns = Pattern.objects.filter(type__lexical_class=lexical_class)
+    # znaleźć wszystkie zawarte i zawierające wzory
+    form_set = get_form_set(forms)
+    if lexical_class.symbol == 'v':
+        form_set = set(form for form, label in extra['base_forms'])
+        all_forms = set(form for form, tag in forms)
+    ending_sets = {}
+    included_patterns = set()
+    including_patterns = set()
+    matching_patterns = set()
+    base_forms_changed = False
+    for basic_ending in basic_form_endings(lexical_class, basic_form, form_set,
+                                           **extra):
+        pattern = basic_ending.pattern
+        if lexical_class.symbol == 'subst' and bad_pattern_subst(pattern,
+                                                                 **extra):
+            #print 'odpadł:', pattern
+            continue # olewamy komentarze że formy odrzucone przez charfle?
+        root = basic_form[:len(basic_form) - len(basic_ending.string)]
+        ending_sets[pattern] = good_ending_set(
+            lexical_class, pattern, root, **extra)
+        including = form_set.issubset(ending_sets[pattern])
+        extra_base_forms = []
+        bad_forms = set()
+        for ending in pattern.endings.all():
+            if relevant(lexical_class, ending, **extra):
+                if root + ending.string not in form_set:
+                    bfl = ending.base_form_label.symbol
+                    #print pattern.name, root, ending.string, bfl
+                    if lexical_class.symbol == 'v':
+                        for label, tag, end in v_base_forms:
+                            if label == bfl:
+                                if root + ending.string + end in all_forms:
+                                    for form, tag in forms:
+                                        if form == root + ending.string + end:
+                                            this_tag = tag
+                                            break
+                                        # ech... uwielbiam zgadywać błędy
+                                    if (bfl in (
+                                    '4', '5', "6'", '10', '11', '11pg',
+                                    '12') and
+                                            (this_tag == ('verb', 'irreg') or
+                                                     this_tag[1] == 'ger')):
+                                        extra_base_forms.append(
+                                            (root + ending.string, label))
+                                        break
+                        else: # jeśli to nie była niewykryta forma bazowa
+                            for label, tag, end in v_base_forms:
+                                if label == bfl:
+                                    bad_forms.add(root + ending.string + end)
+                                    break
+                    else: # inne części mowy nie mają istotnych sufiksów?
+                        bad_forms.add(root + ending.string)
+        if not bad_forms:
+            if extra_base_forms:
+                extra['base_forms'] += extra_base_forms
+                base_forms_changed = True
+            included_patterns.add((pattern, root))
+            if including:
+                matching_patterns.add((pattern, root))
+        elif including:
+            including_patterns.add(((pattern, root), tuple(bad_forms)))
+
+    if base_forms_changed:
+        #print extra['base_forms']
+        return find_patterns(lexical_class, forms, **extra)
+        # nie wiem, czy to potrzebne, ale na wszelki wypadek
+    included_patterns = list(included_patterns)
+    including_patterns = list(including_patterns)
+    matching_patterns = list(matching_patterns)
+    if len(matching_patterns) > 0:
+        if DEBUG:
+            print u'dokładne wzory: %s' % join(matching_patterns)
+        return 'match', matching_patterns, included_patterns, including_patterns
+        # nic nie pasuje albo trzeba wybrać wiele wzorów
+    if DEBUG and len(including_patterns) > 0:
+        print u'zawierające: %s' % join(p for p, b_f in including_patterns)
+    if DEBUG and len(included_patterns) > 0:
+        print u'zawarte: %s' % join(included_patterns)
+    return find_many_patterns(
+        lexical_class, form_set, basic_form, included_patterns, ending_sets,
+        **extra) + (included_patterns, including_patterns)
+
 
 def find_many_patterns(lexical_class, form_set, basic_form, included_patterns,
                        ending_sets, **extra):
-  necessary_patterns = set()
-  missing_form = None
-  for form in form_set:
-    having = []
-    for pattern, root in included_patterns:
-      if form in ending_sets[pattern]:
-        having.append((pattern, root))
-    if len(having) == 1:
-      necessary_patterns.add(having[0])
-    if not having:
-      missing_form = form
-      break
-  if missing_form:
-    if DEBUG:
-      print u"brak formy: %s" % missing_form
-    return 'none', []
-  covered_forms = set()
-  for pattern, root in necessary_patterns:
-    covered_forms |= ending_sets[pattern]
-  if form_set.issubset(covered_forms):
-    if DEBUG:
-      print u"pokryte koniecznymi wzorami: %s" % join(necessary_patterns)
-    return 'many', [list(necessary_patterns)]
-  else:
-    #for pattern, root in included_patterns:
-    #  print pattern, ending_sets[pattern]
-    minimal_sets = find_minimal_sets(
-      form_set, covered_forms, necessary_patterns, included_patterns,
-      ending_sets)
-    return 'many', minimal_sets
+    necessary_patterns = set()
+    missing_form = None
+    for form in form_set:
+        having = []
+        for pattern, root in included_patterns:
+            if form in ending_sets[pattern]:
+                having.append((pattern, root))
+        if len(having) == 1:
+            necessary_patterns.add(having[0])
+        if not having:
+            missing_form = form
+            break
+    if missing_form:
+        if DEBUG:
+            print u"brak formy: %s" % missing_form
+        return 'none', []
+    covered_forms = set()
+    for pattern, root in necessary_patterns:
+        covered_forms |= ending_sets[pattern]
+    if form_set.issubset(covered_forms):
+        if DEBUG:
+            print u"pokryte koniecznymi wzorami: %s" % join(necessary_patterns)
+        return 'many', [list(necessary_patterns)]
+    else:
+        #for pattern, root in included_patterns:
+        #  print pattern, ending_sets[pattern]
+        minimal_sets = find_minimal_sets(
+            form_set, covered_forms, necessary_patterns, included_patterns,
+            ending_sets)
+        return 'many', minimal_sets
 
 
 def check_sgjp_v(entry, ic, patterns, base_forms, derived):
-  lexemes = Lexeme.objects.distinct().filter(
-    entry=entry, part_of_speech__symbol='v')
-  lexemes = lexemes.filter(pk__in=sgjp)
-  for lexeme in lexemes:
-    sgjp_patterns = set()
-    for lip in lexeme.lexemeinflectionpattern_set.all():
-      sgjp_ic = lip.inflection_characteristic.symbol
-      # TODO co z q*?
-      if sgjp_ic != ic and ic in ('dk', 'ndk'):
-        break
-      if sgjp_ic in ('dk', 'ndk') and ic not in ('dk', 'ndk'):
-        break
-      sgjp_patterns.add((lip.pattern, lip.root))
-    else:
-      if set(patterns) == sgjp_patterns:
-        sgjp_derived = {}
-        for pos in ('ger', 'pact', 'ppas'):
-          derived_part = lexeme.refs_to.filter(type='ver' + pos)
-          if pos == 'ppas':
-            derived_part = derived_part
-          if derived_part:
-            sgjp_derived[pos] = [der.to_lexeme for der in derived_part]
-        if derived == set(sgjp_derived):
-          return lexeme, sgjp_derived
-  return False, None
+    lexemes = Lexeme.objects.distinct().filter(
+        entry=entry, part_of_speech__symbol='v')
+    lexemes = lexemes.filter(pk__in=sgjp)
+    for lexeme in lexemes:
+        sgjp_patterns = set()
+        for lip in lexeme.lexemeinflectionpattern_set.all():
+            sgjp_ic = lip.inflection_characteristic.symbol
+            # TODO co z q*?
+            if sgjp_ic != ic and ic in ('dk', 'ndk'):
+                break
+            if sgjp_ic in ('dk', 'ndk') and ic not in ('dk', 'ndk'):
+                break
+            sgjp_patterns.add((lip.pattern, lip.root))
+        else:
+            if set(patterns) == sgjp_patterns:
+                sgjp_derived = {}
+                for pos in ('ger', 'pact', 'ppas'):
+                    derived_part = lexeme.refs_to.filter(type='ver' + pos)
+                    if pos == 'ppas':
+                        derived_part = derived_part
+                    if derived_part:
+                        sgjp_derived[pos] = [der.to_lexeme for der in
+                                             derived_part]
+                if derived == set(sgjp_derived):
+                    return lexeme, sgjp_derived
+    return False, None
+
 
 def check_sgjp(lc_sym, entry, form_set, forms, **extra):
-  if lc_sym == 'v':
-    return False
-  if lc_sym != 'adj':
-    lexemes = Lexeme.objects.distinct().filter(
-      entry=entry, part_of_speech__lexical_class__symbol=lc_sym)
-  else:
-    if forms[0][1][-1] == 'comp':
-      parts_of_speech = ['adjcom']
+    if lc_sym == 'v':
+        return False
+    if lc_sym != 'adj':
+        lexemes = Lexeme.objects.distinct().filter(
+            entry=entry, part_of_speech__lexical_class__symbol=lc_sym)
     else:
-      parts_of_speech = ['adj', 'appas']
-    lexemes = Lexeme.objects.distinct().filter(
-      entry=entry, part_of_speech__symbol__in=parts_of_speech)
-  lexemes = lexemes.filter(pk__in=sgjp)
-  matched_lexemes = []
-  for lexeme in lexemes:
-    if lc_sym == 'adj' and lexeme.refs_to.filter(type='nieadj'):
-      continue
-    if lc_sym == 'subst' and extra['tantum'] == 'sg':
-      sgjp_forms = lexeme.all_forms(affixes=False, label_filter=r'sg:')
-    elif lexeme.part_of_speech.symbol == 'appas':
-      sgjp_forms = lexeme.all_forms(affixes=True)
-    else:
-      sgjp_forms = lexeme.all_forms(affixes=False)
-    if sgjp_forms == form_set:
-      matched_lexemes.append(lexeme)
-      continue
-    diff = sgjp_forms - form_set
-    exceptions = []
-    if lc_sym == 'subst':
-      if lexeme.lexemeinflectionpattern_set.filter(
-          inflection_characteristic__symbol__in=('m1', 'p1')).exists():
-        # depr
-        exceptions = lexeme.all_forms(affixes=False, label_filter=r'^pl:nom$')
-    elif lc_sym == 'adj':
-      # -o
-      exceptions = lexeme.all_forms(affixes=False, label_filter=r'^0$')
-    if form_set.issubset(sgjp_forms) and diff.issubset(exceptions):
-      matched_lexemes.append(lexeme)
-  if len(matched_lexemes) > 1:
-    if lc_sym == 'subst' and entry.endswith(u'ość'):
-      matched_lexemes_subst = [
-        l for l in matched_lexemes if l.part_of_speech.symbol == 'subst']
-      if matched_lexemes_subst:
-        matched_lexemes = matched_lexemes_subst
+        if forms[0][1][-1] == 'comp':
+            parts_of_speech = ['adjcom']
+        else:
+            parts_of_speech = ['adj', 'appas']
+        lexemes = Lexeme.objects.distinct().filter(
+            entry=entry, part_of_speech__symbol__in=parts_of_speech)
+    lexemes = lexemes.filter(pk__in=sgjp)
+    matched_lexemes = []
+    for lexeme in lexemes:
+        if lc_sym == 'adj' and lexeme.refs_to.filter(type='nieadj'):
+            continue
+        if lc_sym == 'subst' and extra['tantum'] == 'sg':
+            sgjp_forms = lexeme.all_forms(affixes=False, label_filter=r'sg:')
+        elif lexeme.part_of_speech.symbol == 'appas':
+            sgjp_forms = lexeme.all_forms(affixes=True)
+        else:
+            sgjp_forms = lexeme.all_forms(affixes=False)
+        if sgjp_forms == form_set:
+            matched_lexemes.append(lexeme)
+            continue
+        diff = sgjp_forms - form_set
+        exceptions = []
+        if lc_sym == 'subst':
+            if lexeme.lexemeinflectionpattern_set.filter(
+                    inflection_characteristic__symbol__in=(
+                    'm1', 'p1')).exists():
+                # depr
+                exceptions = lexeme.all_forms(affixes=False,
+                                              label_filter=r'^pl:nom$')
+        elif lc_sym == 'adj':
+            # -o
+            exceptions = lexeme.all_forms(affixes=False, label_filter=r'^0$')
+        if form_set.issubset(sgjp_forms) and diff.issubset(exceptions):
+            matched_lexemes.append(lexeme)
     if len(matched_lexemes) > 1:
-      debug(entry, u'niejednoznaczność dopasowanych leksemów')
-  if len(matched_lexemes) > 0:
-    return matched_lexemes[0]
-  return False
+        if lc_sym == 'subst' and entry.endswith(u'ość'):
+            matched_lexemes_subst = [
+                l for l in matched_lexemes if
+                l.part_of_speech.symbol == 'subst']
+            if matched_lexemes_subst:
+                matched_lexemes = matched_lexemes_subst
+        if len(matched_lexemes) > 1:
+            debug(entry, u'niejednoznaczność dopasowanych leksemów')
+    if len(matched_lexemes) > 0:
+        return matched_lexemes[0]
+    return False
 
 # dla przymiotników
 def get_negation(lc_sym, lexeme):
-  negations = [cf.to_lexeme for cf in CrossReference.objects.filter(
-               from_lexeme=lexeme, type='adjnie')]
-  good_negation = None
-  for n in negations:
-    if n.entry == u'nie' + lexeme.entry:
-      if all(lip.inflection_characteristic.symbol == '0-'
-             for lip in n.lexemeinflectionpattern_set.all()):
-        good_negation = n
-  return good_negation
+    negations = [cf.to_lexeme for cf in CrossReference.objects.filter(
+        from_lexeme=lexeme, type='adjnie')]
+    good_negation = None
+    for n in negations:
+        if n.entry == u'nie' + lexeme.entry:
+            if all(lip.inflection_characteristic.symbol == '0-'
+                   for lip in n.lexemeinflectionpattern_set.all()):
+                good_negation = n
+    return good_negation
+
 
 def closest_lexeme_subst(entry, gender, patterns, included=None):
-  lexemes = Lexeme.objects.filter(
-    part_of_speech__lexical_class__symbol='subst')
-  lexemes = lexemes.distinct()
-  # ten sam rodzaj
-  gender = gender[0] if gender != 'm1' else 'm1'
-  if genders[gender]:
-    lexemes = lexemes.filter(
-      lexemeinflectionpattern__inflection_characteristic__symbol__in=
-      genders[gender])
-  if not included:
-    # posiada wzór zawierający się w pasujących
-    lexemes = lexemes.filter(lexemeinflectionpattern__pattern__in=patterns)
-  else:
-    #print patterns, included
-    new_lexemes = Lexeme.objects.none()
-    # posiada wszystkie wzory z któregoś zestawu
-    for pattern_set in patterns:
-      part = lexemes
-      for pattern, root in pattern_set:
-        part = part.filter(lexemeinflectionpattern__pattern=pattern)
-      new_lexemes = new_lexemes | part
-    lexemes = new_lexemes.distinct()
-  # nie posiada wzorów niezawierających się w pasujących, dobra wielkość
-  uppercase = entry[0].isupper()
-  good_lexemes = []
-  for lexeme in lexemes:
-    if lexeme.entry[0].isupper():
-      for lip in lexeme.lexemeinflectionpattern_set.all():
-        if not included:
-          if lip.pattern not in patterns:
-            break
-        else:
-          if lip.pattern not in included:
-            break
-      else:
-        good_lexemes.append(lexeme)
-  # najdłuższe wspólne zakończenie
-  best = (-1, None)
-  for lexeme in good_lexemes:
-    common_suffix = 0
-    for char1, char2 in zip(entry[::-1], lexeme.entry[::-1]):
-      if char1 == char2:
-        common_suffix += 1
-      else:
-        break
-    if common_suffix > best[0]:
-      best = (common_suffix, lexeme)
-  return best[1]
+    lexemes = Lexeme.objects.filter(
+        part_of_speech__lexical_class__symbol='subst')
+    lexemes = lexemes.distinct()
+    # ten sam rodzaj
+    gender = gender[0] if gender != 'm1' else 'm1'
+    if genders[gender]:
+        lexemes = lexemes.filter(
+            lexemeinflectionpattern__inflection_characteristic__symbol__in=
+            genders[gender])
+    if not included:
+        # posiada wzór zawierający się w pasujących
+        lexemes = lexemes.filter(lexemeinflectionpattern__pattern__in=patterns)
+    else:
+        #print patterns, included
+        new_lexemes = Lexeme.objects.none()
+        # posiada wszystkie wzory z któregoś zestawu
+        for pattern_set in patterns:
+            part = lexemes
+            for pattern, root in pattern_set:
+                part = part.filter(lexemeinflectionpattern__pattern=pattern)
+            new_lexemes = new_lexemes | part
+        lexemes = new_lexemes.distinct()
+        # nie posiada wzorów niezawierających się w pasujących, dobra wielkość
+    uppercase = entry[0].isupper()
+    good_lexemes = []
+    for lexeme in lexemes:
+        if lexeme.entry[0].isupper():
+            for lip in lexeme.lexemeinflectionpattern_set.all():
+                if not included:
+                    if lip.pattern not in patterns:
+                        break
+                else:
+                    if lip.pattern not in included:
+                        break
+            else:
+                good_lexemes.append(lexeme)
+        # najdłuższe wspólne zakończenie
+    best = (-1, None)
+    for lexeme in good_lexemes:
+        common_suffix = 0
+        for char1, char2 in zip(entry[::-1], lexeme.entry[::-1]):
+            if char1 == char2:
+                common_suffix += 1
+            else:
+                break
+        if common_suffix > best[0]:
+            best = (common_suffix, lexeme)
+    return best[1]
+
 
 def get_inflection_characteristic_subst(forms, patterns, gender, ic, tantum):
-  if tantum == 'sg' and ic == 'm':
-    ic = 'm3'
-  elif ic in ('n', 'i'): # ech, to 'i' - nadal możliwe?
-    ic = 'n2'
-  elif ic == 'm':
-    ic = 'm3'
-    sg_acc = []
-    for form in forms:
-      if len(form[1]) >= 3 and form[1][1:3] == ('sg', 'acc'):
-        sg_acc.append(form[0])
-    if len(sg_acc) == 1:
-      if sg_acc[0] != forms[0][0]:
-        ic = 'm2'
-  return ic
+    if tantum == 'sg' and ic == 'm':
+        ic = 'm3'
+    elif ic in ('n', 'i'): # ech, to 'i' - nadal możliwe?
+        ic = 'n2'
+    elif ic == 'm':
+        ic = 'm3'
+        sg_acc = []
+        for form in forms:
+            if len(form[1]) >= 3 and form[1][1:3] == ('sg', 'acc'):
+                sg_acc.append(form[0])
+        if len(sg_acc) == 1:
+            if sg_acc[0] != forms[0][0]:
+                ic = 'm2'
+    return ic
+
 
 def get_inflection_characteristic_adj(forms, patterns, **extra):
-  # charfl: 3+ jeśli jest adjp
-  ic = '0-'
-  for form in forms:
-    if form[1][0] == 'adjp':
-      ic = '3+'
-  if patterns[0][0].endings.filter(base_form_label__symbol='0') and ic != '3+':
-    ic = ''
-  return ic
+    # charfl: 3+ jeśli jest adjp
+    ic = '0-'
+    for form in forms:
+        if form[1][0] == 'adjp':
+            ic = '3+'
+    if patterns[0][0].endings.filter(
+            base_form_label__symbol='0') and ic != '3+':
+        ic = ''
+    return ic
+
 
 def get_inflection_characteristic_v(forms, base_forms, **extra):
-  # dk, ndk, ndk/dk
-  # na podstawie istnienia -ąc (ndk), -szy (dk)
-  ndk = dk = nonq = False
-  for form in forms:
-    if form[0].endswith(u'ąc') and not ':'.join(form[1]).startswith('verb:inf'):
-      ndk = True
-    elif form[0].endswith(u'wszy') or form[0].endswith(u'łszy'):
-      dk = True
-    elif ':'.join(form[1]).startswith('verb:praet:sg:pri'):
-      nonq = True
-  if not dk and not ndk: # mniej wiarygodne - czy mdlić może być dk?
+    # dk, ndk, ndk/dk
+    # na podstawie istnienia -ąc (ndk), -szy (dk)
+    ndk = dk = nonq = False
     for form in forms:
-      if form[1][1] == 'inf':
-        if form[1][-1] == 'imperf':
-          ndk = True
-        elif form[1][-1] == 'perf':
-          dk = True
-        break
-  if ndk and not dk:
-    ic = 'ndk'
-  elif dk and not ndk:
-    ic = 'dk'
-  elif ndk and dk:
-    ic = 'ndk/dk'
-  else:
-    debug(forms[0][0], u'nie udało się ustalić aspektu')
-    ic = None
-  if ic and not nonq:
-    ic = 'q' + ic
-  return ic
+        if form[0].endswith(u'ąc') and not ':'.join(form[1]).startswith(
+                'verb:inf'):
+            ndk = True
+        elif form[0].endswith(u'wszy') or form[0].endswith(u'łszy'):
+            dk = True
+        elif ':'.join(form[1]).startswith('verb:praet:sg:pri'):
+            nonq = True
+    if not dk and not ndk: # mniej wiarygodne - czy mdlić może być dk?
+        for form in forms:
+            if form[1][1] == 'inf':
+                if form[1][-1] == 'imperf':
+                    ndk = True
+                elif form[1][-1] == 'perf':
+                    dk = True
+                break
+    if ndk and not dk:
+        ic = 'ndk'
+    elif dk and not ndk:
+        ic = 'dk'
+    elif ndk and dk:
+        ic = 'ndk/dk'
+    else:
+        debug(forms[0][0], u'nie udało się ustalić aspektu')
+        ic = None
+    if ic and not nonq:
+        ic = 'q' + ic
+    return ic
+
 
 def get_inflection_characteristic(lc_sym, forms, patterns, **extra):
-  if lc_sym == 'subst':
-    return get_inflection_characteristic_subst(forms, patterns, **extra)
-  elif lc_sym == 'adj':
-    return get_inflection_characteristic_adj(forms, patterns, **extra)
-  elif lc_sym == 'v':
-    return get_inflection_characteristic_v(forms, **extra)
+    if lc_sym == 'subst':
+        return get_inflection_characteristic_subst(forms, patterns, **extra)
+    elif lc_sym == 'adj':
+        return get_inflection_characteristic_adj(forms, patterns, **extra)
+    elif lc_sym == 'v':
+        return get_inflection_characteristic_v(forms, **extra)
+
 
 def blacklist_filter(patterns):
-  return [(pattern, root) for (pattern, root) in patterns
-          if pattern.name not in blacklist]
+    return [(pattern, root) for (pattern, root) in patterns
+            if pattern.name not in blacklist]
+
 
 def filter_patterns(filter, action_name, type, patterns, included, including,
                     lexical_class, form_set, entry, **extra):
-  old_patterns = patterns
-  old_included = included
-  bad_patterns = False
-  if type == 'many':
-    if any(pattern_set != filter(pattern_set) for pattern_set in patterns):
-      included = filter(included)
-      ending_sets = {}
-      for pattern, root in included:
-        ending_sets[pattern] = good_ending_set(
-          lexical_class, pattern, root, **extra)
-      type, patterns = find_many_patterns(
-        lexical_class, form_set, entry, included, ending_sets, **extra)
-      if type != 'many':
-        debug(entry, u'mnogie dopasowanie zepsute przez %s (%s)' %
-                     (action_name, join_many(old_patterns)))
-        type = 'many'
-        patterns, included = old_patterns, old_included
-        bad_patterns = True
-  elif type == 'none':
-    including_dict = dict(including)
-    including = [(key, including_dict[key]) for key in filter(including_dict)]
-  else: # type == 'match'
-    patterns = filter(patterns)
-    including_dict = dict(including)
-    including = [(key, including_dict[key]) for key in filter(including_dict)]
-    included = filter(included)
-    if old_patterns and not patterns:
-      ending_sets = {}
-      for pattern, root in included:
-        ending_sets[pattern] = good_ending_set(
-          lexical_class, pattern, root, **extra)
-      type, patterns = find_many_patterns(
-        lexical_class, form_set, entry, included, ending_sets, **extra)
-      if type == 'none':
-        debug(entry, u'znikły wzory przez %s (%s)' %
-                     (action_name, join(old_patterns)))
-        type = 'match'
-        patterns = old_patterns
-        bad_patterns = True
-  return type, patterns, included, including, bad_patterns
+    old_patterns = patterns
+    old_included = included
+    bad_patterns = False
+    if type == 'many':
+        if any(pattern_set != filter(pattern_set) for pattern_set in patterns):
+            included = filter(included)
+            ending_sets = {}
+            for pattern, root in included:
+                ending_sets[pattern] = good_ending_set(
+                    lexical_class, pattern, root, **extra)
+            type, patterns = find_many_patterns(
+                lexical_class, form_set, entry, included, ending_sets, **extra)
+            if type != 'many':
+                debug(entry, u'mnogie dopasowanie zepsute przez %s (%s)' %
+                             (action_name, join_many(old_patterns)))
+                type = 'many'
+                patterns, included = old_patterns, old_included
+                bad_patterns = True
+    elif type == 'none':
+        including_dict = dict(including)
+        including = [(key, including_dict[key]) for key in
+                     filter(including_dict)]
+    else: # type == 'match'
+        patterns = filter(patterns)
+        including_dict = dict(including)
+        including = [(key, including_dict[key]) for key in
+                     filter(including_dict)]
+        included = filter(included)
+        if old_patterns and not patterns:
+            ending_sets = {}
+            for pattern, root in included:
+                ending_sets[pattern] = good_ending_set(
+                    lexical_class, pattern, root, **extra)
+            type, patterns = find_many_patterns(
+                lexical_class, form_set, entry, included, ending_sets, **extra)
+            if type == 'none':
+                debug(entry, u'znikły wzory przez %s (%s)' %
+                             (action_name, join(old_patterns)))
+                type = 'match'
+                patterns = old_patterns
+                bad_patterns = True
+    return type, patterns, included, including, bad_patterns
+
 
 def create_derived(pos, base_forms, forms, patterns):
-  tab = {'ger': ('11', u'ie'), 'pact': ('3', u'cy'), 'ppas': ('10', u'y')}
-  entries = GroupDict()
-  for pattern, root in patterns:
-    bfl = tab[pos][0]
-    ending = pattern.endings.get(base_form_label__symbol=bfl)
-    entry = root + ending.string + tab[pos][1]
-    entries.add(entry, pattern.name)
-  output = []
-  for entry, patterns in entries.iteritems():
-    if entry in (form[0] for form in forms):
-      output.append((pos, entry, patterns))
-  return output
+    tab = {'ger': ('11', u'ie'), 'pact': ('3', u'cy'), 'ppas': ('10', u'y')}
+    entries = GroupDict()
+    for pattern, root in patterns:
+        bfl = tab[pos][0]
+        ending = pattern.endings.get(base_form_label__symbol=bfl)
+        entry = root + ending.string + tab[pos][1]
+        entries.add(entry, pattern.name)
+    output = []
+    for entry, patterns in entries.iteritems():
+        if entry in (form[0] for form in forms):
+            output.append((pos, entry, patterns))
+    return output
+
 
 def get_sgjp(lexeme):
-  return {'source': 'sgjp', 'id': lexeme.pk, 'entry': lexeme.entry}
+    return {'source': 'sgjp', 'id': lexeme.pk, 'entry': lexeme.entry}
+
 
 def create_lexeme(entry, part_of_speech, status, comment):
-  return {
-    'source': 'morfologik',
-    'entry': entry,
-    'part_of_speech': part_of_speech,
-    'status': status,
-    'comment': comment,
-  }
+    return {
+        'source': 'morfologik',
+        'entry': entry,
+        'part_of_speech': part_of_speech,
+        'status': status,
+        'comment': comment,
+    }
+
 
 def create_lip(pattern, root, i, ic, part_of_speech):
-  output = {
-    'pattern': pattern if isinstance(pattern, basestring) else pattern.name,
-    'ind': i,
-    'ic': (ic, part_of_speech),
-  }
-  if root:
-    output['root'] = {'type': 'string', 'root': root}
-  else:
-    output['root'] = {'type': 'compute'}
-  return output
+    output = {
+        'pattern': pattern if isinstance(pattern, basestring) else pattern.name,
+        'ind': i,
+        'ic': (ic, part_of_speech),
+    }
+    if root:
+        output['root'] = {'type': 'string', 'root': root}
+    else:
+        output['root'] = {'type': 'compute'}
+    return output
+
 
 alternative_gender = {
-  'p1': 'p3',
-  'p3': 'p1',
-  'm1': 'm2/m3',
-  'm': 'm1',
+    'p1': 'p3',
+    'p3': 'p1',
+    'm1': 'm2/m3',
+    'm': 'm1',
 }
 
 alternative_gender2 = {
-  'p1': 'p3',
-  'p3': 'p1',
-  'm1': 'm',
-  'm': 'm1',
+    'p1': 'p3',
+    'p3': 'p1',
+    'm1': 'm',
+    'm': 'm1',
 }
 
+
 def lexeme_creation(lc_sym, entry, ic, forms, type, patterns, fitting,
                     bad_patterns, included, other_result, tantum=None,
                     gender=None, negated=None, base_forms=None, derived=None):
-  status = 'desc' if type != 'none' else 'cand'
-  comments = []
-  copy_lips = False
-  if lc_sym == 'subst':
-    part_of_speech = 'subst' # co z osc i skrs?
-    if ic in ('m2', 'm3'):
-      sure = False
-      if type != 'none' and len(fitting) == 1:
-        for pattern, root in patterns:
-          for e in patterns[0][0].endings.filter(base_form_label__symbol='sg:gen'):
-            if not e.string.endswith('u'):
-              break
-          else:
-            continue
-          break
-        else: # wszystkie sg:gen kończą się na 'u'
-          ic = 'm3'
-          sure = True
-        for pattern, root in patterns:
-          if pattern.type.symbol == 'f':
-            ic = 'm2'
-            sure = True
-            break
-      if not sure:
-        status = 'cand'
-    if tantum is None and ic == 'm1':
-      for pattern, root in patterns:
-        nmo_endings = pattern.endings.filter(base_form_label__symbol='pl:nom')
-        for e in nmo_endings:
-          nmo_form = root + e.string
-          if nmo_form not in (form[0] for form in forms):
-            comments.append(u'Dodano formę depr')
-            break
+    status = 'desc' if type != 'none' else 'cand'
+    comments = []
+    copy_lips = False
+    if lc_sym == 'subst':
+        part_of_speech = 'subst' # co z osc i skrs?
+        if ic in ('m2', 'm3'):
+            sure = False
+            if type != 'none' and len(fitting) == 1:
+                for pattern, root in patterns:
+                    for e in patterns[0][0].endings.filter(
+                            base_form_label__symbol='sg:gen'):
+                        if not e.string.endswith('u'):
+                            break
+                    else:
+                        continue
+                    break
+                else: # wszystkie sg:gen kończą się na 'u'
+                    ic = 'm3'
+                    sure = True
+                for pattern, root in patterns:
+                    if pattern.type.symbol == 'f':
+                        ic = 'm2'
+                        sure = True
+                        break
+            if not sure:
+                status = 'cand'
+        if tantum is None and ic == 'm1':
+            for pattern, root in patterns:
+                nmo_endings = pattern.endings.filter(
+                    base_form_label__symbol='pl:nom')
+                for e in nmo_endings:
+                    nmo_form = root + e.string
+                    if nmo_form not in (form[0] for form in forms):
+                        comments.append(u'Dodano formę depr')
+                        break
+                else:
+                    continue
+                break
+        if ic == 'p1':
+            for pattern, root in patterns:
+                nmo_endings = pattern.endings.filter(
+                    base_form_label__symbol='pl:nom')
+                other_endings = pattern.endings.exclude(
+                    base_form_label__symbol='pl:nom')
+                other_strings = other_endings.values_list('string', flat=True)
+                nmo_strings = [e.string for e in nmo_endings if
+                               e.string not in other_strings]
+                nmo_forms = set(root + s for s in nmo_strings)
+                if nmo_forms & set(form[0] for form in forms):
+                    comments.append(
+                        u'Usunięto formę depr: %s' % ', '.join(list(nmo_forms)))
+                    break
+        if tantum == 'sg' and type != 'none':
+            if type == 'match':
+                search_patterns = [pattern for pattern, root in fitting]
+                l = closest_lexeme_subst(entry, gender, search_patterns)
+            else:
+                included_patterns = [pattern for pattern, root in included]
+                l = closest_lexeme_subst(entry, gender, fitting,
+                                         included_patterns)
+            if l:
+                copy_lips = l.lexemeinflectionpattern_set.all()
+                #print l
+                comments.append(u'Automatycznie rozszerzone singulare tantum')
+            else:
+                if type == 'match':
+                    p = join(fitting)
+                else:
+                    p = join_many(fitting)
+                debug(entry,
+                      u'nie ma pasujących leksemów dla rozszerzenia sgtant '
+                      u'dla wzorów %s' % p)
+                comments.append(u'Nie udało się rozszerzyć singulare tantum')
+                #status = 'cand'
+                # dodać kwalifikator [po imporcie jednak]
+    elif lc_sym == 'adj':
+        if forms[0][1][-1] == 'comp':
+            part_of_speech = 'adjcom'
+            ic = ''
         else:
-          continue
-        break
-    if ic == 'p1':
-      for pattern, root in patterns:
-        nmo_endings = pattern.endings.filter(base_form_label__symbol='pl:nom')
-        other_endings = pattern.endings.exclude(base_form_label__symbol='pl:nom')
-        other_strings = other_endings.values_list('string', flat=True)
-        nmo_strings = [e.string for e in nmo_endings if e.string not in other_strings]
-        nmo_forms = set(root + s for s in nmo_strings)
-        if nmo_forms & set(form[0] for form in forms):
-          comments.append(
-            u'Usunięto formę depr: %s' % ', '.join(list(nmo_forms)))
-          break
-    if tantum == 'sg' and type != 'none':
-      if type == 'match':
-        search_patterns = [pattern for pattern, root in fitting]
-        l = closest_lexeme_subst(entry, gender, search_patterns)
-      else:
-        included_patterns = [pattern for pattern, root in included]
-        l = closest_lexeme_subst(entry, gender, fitting, included_patterns)
-      if l:
-        copy_lips = l.lexemeinflectionpattern_set.all()
-        #print l
-        comments.append(u'Automatycznie rozszerzone singulare tantum')
-      else:
-        if type == 'match':
-          p = join(fitting)
+            part_of_speech = 'adj'
+            if ic != '0-' and type != 'none':
+                comments.append(u'Dodano formę -o')
+    else: # lc_sym == 'v':
+        part_of_speech = 'v'
+        if type != 'none':
+            if ic is None:
+                comments.append(u'Nie udało się ustalić aspektu')
+                ic = 'ndk'
+                status = 'cand'
+            elif ic.startswith('q') and derived != set():
+                comments.append(u'Derywaty muszą mieć charfle bez q')
+    if bad_patterns:
+        comments.append(u'Wzory z czarnej listy!')
+        status = 'cand'
+    if len(fitting) > 1 or (type == 'none' and fitting):
+        status = 'cand'
+        if type == 'none':
+            comments.append(u'Zawierające wzory:')
+            for (pattern, root), bad_forms in fitting:
+                comments.append('%s: %s' % (pattern.name, ', '.join(bad_forms)))
+        elif type != 'many':
+            comments.append(u'Pasujące wzory: %s' % join(fitting))
         else:
-          p = join_many(fitting)
-        debug(entry, u'nie ma pasujących leksemów dla rozszerzenia sgtant '
-                     u'dla wzorów %s' % p)
-        comments.append(u'Nie udało się rozszerzyć singulare tantum')
-        #status = 'cand'
-      # dodać kwalifikator [po imporcie jednak]
-  elif lc_sym == 'adj':
-    if forms[0][1][-1] == 'comp':
-      part_of_speech = 'adjcom'
-      ic = ''
-    else:
-      part_of_speech = 'adj'
-      if ic != '0-' and type != 'none':
-        comments.append(u'Dodano formę -o')
-  else: # lc_sym == 'v':
-    part_of_speech = 'v'
-    if type != 'none':
-      if ic is None:
-        comments.append(u'Nie udało się ustalić aspektu')
-        ic = 'ndk'
+            comments.append(u'Pasujące zestawy wzorów: %s' % join_many(fitting))
+    if other_result:
         status = 'cand'
-      elif ic.startswith('q') and derived != set():
-        comments.append(u'Derywaty muszą mieć charfle bez q')
-  if bad_patterns:
-    comments.append(u'Wzory z czarnej listy!')
-    status = 'cand'
-  if len(fitting) > 1 or (type == 'none' and fitting):
-    status = 'cand'
-    if type == 'none':
-      comments.append(u'Zawierające wzory:')
-      for (pattern, root), bad_forms in fitting:
-        comments.append('%s: %s' % (pattern.name, ', '.join(bad_forms)))
-    elif type != 'many':
-      comments.append(u'Pasujące wzory: %s' % join(fitting))
-    else:
-      comments.append(u'Pasujące zestawy wzorów: %s' % join_many(fitting))
-  if other_result:
-    status = 'cand'
-    type2, patterns2, included2, including2 = other_result
-    comments.append(u'Alternatywny rodzaj: %s' % alternative_gender[gender])
-    if type2 == 'match':
-      comments.append(u'Pasujące wzory: %s' % join(patterns2))
-    elif type2 == 'many':
-      comments.append(u'Pasujące zestawy wzorów: %s' % join_many(patterns2))
-  # hm?
-  if ic is None and type != 'none':
-    comments.append(u'Dopasowane wzory: %s' % join(patterns))
-  # zbieramy wzory do porównania [fuj, copypasta!]
-  if len(fitting) > 1:
-    if type == 'none':
-      all_patterns = set(p for p, b_f in fitting)
-    elif type != 'many':
-      all_patterns = set(fitting)
-    else:
-      all_patterns = set()
-      for pattern_set in fitting:
-        all_patterns |= set(pattern_set)
-    diff = compare_patterns(list(all_patterns))
-    comments.append(u'Porównanie wzorów:')
-    for p, diff_forms in diff.iteritems():
-      comments.append(
-        '%s: %s' % (p.name, ', '.join('%s: %s' % pair for pair in diff_forms)))
-  if other_result and len(patterns2) > 1:
-    if type2 != 'many':
-      other_patterns = set(patterns2)
-    else:
-      other_patterns = set()
-      for pattern_set in patterns2:
-        other_patterns |= set(pattern_set)
-    diff = compare_patterns(list(other_patterns))
-    comments.append(u'Porównanie alternatywnych wzorów:')
-    for p, diff_forms in diff.iteritems():
-      comments.append(
-        '%s: %s' % (p.name, ', '.join('%s: %s' % pair for pair in diff_forms)))
-  comment = '\n'.join(comments)
-  output = {
-    'lexeme': create_lexeme(entry, part_of_speech, status, comment)
-  }
-  lips = []
-  if ic is not None:
-    if not copy_lips:
-      for i, (pattern, root) in enumerate(patterns):
-        lips.append(create_lip(pattern, root, i + 1, ic, part_of_speech))
-    else:
-      for lip in copy_lips:
-        ic = lip.inflection_characteristic.symbol
-        lips.append(
-          create_lip(lip.pattern, None, lip.index, ic, part_of_speech))
-  output['lips'] = lips
-  if lc_sym == 'adj' and negated:
-    output['negated'] = True
-  if lc_sym == 'v':
-    derived_data = []
-    for pos in derived:
-      # wypadałoby informować, jeśli wyszło puste... (?)
-      derived_data += create_derived(pos, base_forms, forms, patterns)
-    output['derived'] = derived_data
-  return output
+        type2, patterns2, included2, including2 = other_result
+        comments.append(u'Alternatywny rodzaj: %s' % alternative_gender[gender])
+        if type2 == 'match':
+            comments.append(u'Pasujące wzory: %s' % join(patterns2))
+        elif type2 == 'many':
+            comments.append(
+                u'Pasujące zestawy wzorów: %s' % join_many(patterns2))
+        # hm?
+    if ic is None and type != 'none':
+        comments.append(u'Dopasowane wzory: %s' % join(patterns))
+        # zbieramy wzory do porównania [fuj, copypasta!]
+    if len(fitting) > 1:
+        if type == 'none':
+            all_patterns = set(p for p, b_f in fitting)
+        elif type != 'many':
+            all_patterns = set(fitting)
+        else:
+            all_patterns = set()
+            for pattern_set in fitting:
+                all_patterns |= set(pattern_set)
+        diff = compare_patterns(list(all_patterns))
+        comments.append(u'Porównanie wzorów:')
+        for p, diff_forms in diff.iteritems():
+            comments.append(
+                '%s: %s' % (
+                p.name, ', '.join('%s: %s' % pair for pair in diff_forms)))
+    if other_result and len(patterns2) > 1:
+        if type2 != 'many':
+            other_patterns = set(patterns2)
+        else:
+            other_patterns = set()
+            for pattern_set in patterns2:
+                other_patterns |= set(pattern_set)
+        diff = compare_patterns(list(other_patterns))
+        comments.append(u'Porównanie alternatywnych wzorów:')
+        for p, diff_forms in diff.iteritems():
+            comments.append(
+                '%s: %s' % (
+                p.name, ', '.join('%s: %s' % pair for pair in diff_forms)))
+    comment = '\n'.join(comments)
+    output = {
+        'lexeme': create_lexeme(entry, part_of_speech, status, comment)
+    }
+    lips = []
+    if ic is not None:
+        if not copy_lips:
+            for i, (pattern, root) in enumerate(patterns):
+                lips.append(
+                    create_lip(pattern, root, i + 1, ic, part_of_speech))
+        else:
+            for lip in copy_lips:
+                ic = lip.inflection_characteristic.symbol
+                lips.append(
+                    create_lip(lip.pattern, None, lip.index, ic,
+                               part_of_speech))
+    output['lips'] = lips
+    if lc_sym == 'adj' and negated:
+        output['negated'] = True
+    if lc_sym == 'v':
+        derived_data = []
+        for pos in derived:
+            # wypadałoby informować, jeśli wyszło puste... (?)
+            derived_data += create_derived(pos, base_forms, forms, patterns)
+        output['derived'] = derived_data
+    return output
+
 
 def process_forms(lexical_class, forms, **extra):
-  lc_sym = lexical_class.symbol
-  other_result = None
-  entry = forms[0][0]
-  form_set = get_form_set(forms)
-  check = check_sgjp(lc_sym, entry, form_set, forms, **extra)
-  if check and not DEBUG:
-    # dopisz leksem do słownika
-    data = {'lexeme': get_sgjp(check)}
-    if (lc_sym == 'adj' and extra['negated']):
-      neg = get_negation(lc_sym, check)
-      if neg:
-        print_data({'lexeme': get_sgjp(neg)})
-      else:
-        data['negated'] = True
-    print_data(data)
-  else:
-    if lexical_class.symbol == 'subst':
-      ic = extra['gender']
-    extra2 = dict(extra)
-    # jeśli rzeczownik męski lub pltant, to puszczamy więcej razy
-    if lexical_class.symbol == 'subst' and extra['gender'] in 'pm':
-      if extra['gender'] == 'm':
-        type2, patterns2, included2, including2 = find_patterns(
-          lexical_class, forms, **extra)
-        extra2['gender'] = 'm1'
-        type1, patterns1, included1, including1 = find_patterns(
-          lexical_class, forms, **extra2)
-      elif extra['gender'] == 'p':
-        extra2['gender'] = 'p1'
-        type1, patterns1, included1, including1 = find_patterns(
-          lexical_class, forms, **extra2)
-        extra2['gender'] = 'p3'
-        type2, patterns2, included2, including2 = find_patterns(
-          lexical_class, forms, **extra2)
-      if type1 != 'none' and type2 == 'none':
-        type, patterns, included, including = type1, patterns1, included1, including1
-        if extra['gender'] == 'm':
-          ic = 'm1'
-        else:
-          ic = 'p1'
-      elif type1 == 'none' and type2 != 'none':
-        type, patterns, included, including = type2, patterns2, included2, including2
-        if extra['gender'] == 'm':
-          ic = 'm'
+    lc_sym = lexical_class.symbol
+    other_result = None
+    entry = forms[0][0]
+    form_set = get_form_set(forms)
+    check = check_sgjp(lc_sym, entry, form_set, forms, **extra)
+    if check and not DEBUG:
+        # dopisz leksem do słownika
+        data = {'lexeme': get_sgjp(check)}
+        if (lc_sym == 'adj' and extra['negated']):
+            neg = get_negation(lc_sym, check)
+            if neg:
+                print_data({'lexeme': get_sgjp(neg)})
+            else:
+                data['negated'] = True
+        print_data(data)
+    else:
+        if lexical_class.symbol == 'subst':
+            ic = extra['gender']
+        extra2 = dict(extra)
+        # jeśli rzeczownik męski lub pltant, to puszczamy więcej razy
+        if lexical_class.symbol == 'subst' and extra['gender'] in 'pm':
+            if extra['gender'] == 'm':
+                type2, patterns2, included2, including2 = find_patterns(
+                    lexical_class, forms, **extra)
+                extra2['gender'] = 'm1'
+                type1, patterns1, included1, including1 = find_patterns(
+                    lexical_class, forms, **extra2)
+            elif extra['gender'] == 'p':
+                extra2['gender'] = 'p1'
+                type1, patterns1, included1, including1 = find_patterns(
+                    lexical_class, forms, **extra2)
+                extra2['gender'] = 'p3'
+                type2, patterns2, included2, including2 = find_patterns(
+                    lexical_class, forms, **extra2)
+            if type1 != 'none' and type2 == 'none':
+                type, patterns, included, including = type1, patterns1, included1, including1
+                if extra['gender'] == 'm':
+                    ic = 'm1'
+                else:
+                    ic = 'p1'
+            elif type1 == 'none' and type2 != 'none':
+                type, patterns, included, including = type2, patterns2, included2, including2
+                if extra['gender'] == 'm':
+                    ic = 'm'
+                else:
+                    ic = 'p3'
+            elif type1 == type2 == 'none':
+                type = 'none'
+                patterns = []
+                included = list(set(included1) | set(included2))
+                including = list(set(including1) | set(including2))
+                # chyba warto coś ustawić
+                if extra['gender'] == 'm':
+                    ic = 'm'
+                else:
+                    ic = 'p3'
+            else: # z obu coś wyszło
+                type, patterns, included, including = type1, patterns1, included1, including1
+                if extra['gender'] == 'm':
+                    ic = 'm1'
+                else:
+                    ic = 'p1'
+                other_result = (type2, patterns2, included2, including2)
+                if DEBUG:
+                    print u"dwie możliwości na rodzaj"
         else:
-          ic = 'p3'
-      elif type1 == type2 == 'none':
-        type = 'none'
-        patterns = []
-        included = list(set(included1) | set(included2))
-        including = list(set(including1) | set(including2))
-        # chyba warto coś ustawić
-        if extra['gender'] == 'm':
-          ic = 'm'
+            type, patterns, included, including = find_patterns(
+                lexical_class, forms, **extra)
+        if type == 'none':
+            if lexical_class.symbol == 'subst' and not extra['tantum']:
+                extra['tantum'] = tantum_a_posteriori(
+                    form_set, [p for p, b_f in including])
+                if extra['tantum']:
+                    if extra['tantum'] == 'pl':
+                        extra['gender'] = 'p'
+                        #if ic == 'm1':
+                        #  extra['gender'] = 'p1'
+                        #else:
+                        #  extra['gender'] = 'p3'
+                    return process_forms(lexical_class, forms, **extra)
+
+        if lexical_class.symbol == 'subst':
+            extra2['gender'] = ic
+        type, patterns, included, including, bad_patterns = filter_patterns(
+            blacklist_filter, u'czarną listę', type, patterns, included,
+            including,
+            lexical_class, form_set, entry, **extra2)
+        if bad_patterns and other_result:
+            type, patterns, included, including = other_result
+            ic = extra2['gender'] = alternative_gender2[ic]
+            type, patterns, included, including, bad_patterns = filter_patterns(
+                blacklist_filter, u'czarną listę', type, patterns, included,
+                including,
+                lexical_class, form_set, entry, **extra2)
+            other_result = None
+        elif other_result:
+            type2, patterns2, included2, including2 = other_result
+            new_other_result = filter_patterns(
+                blacklist_filter, u'czarną listę', type2, patterns2, included2,
+                including2, lexical_class, form_set, entry, **extra2)
+            if not new_other_result[4]:
+                other_result = new_other_result[:4]
+            else:
+                other_result = None
+
+        # wzory się już nie zmienią od tego miejsca
+        if type == 'many':
+            # albo patterns[0]...
+            all_patterns = [p for pattern_set in patterns for p in pattern_set]
         else:
-          ic = 'p3'
-      else: # z obu coś wyszło
-        type, patterns, included, including = type1, patterns1, included1, including1
-        if extra['gender'] == 'm':
-          ic = 'm1'
+            all_patterns = patterns
+        if type != 'none':
+            # brzydko...
+            if lexical_class.symbol == 'subst':
+                extra['ic'] = ic
+            ic = get_inflection_characteristic(lc_sym, forms, all_patterns,
+                                               **extra)
+            if lexical_class.symbol == 'subst':
+                del extra['ic']
         else:
-          ic = 'p1'
-        other_result = (type2, patterns2, included2, including2)
-        if DEBUG:
-          print u"dwie możliwości na rodzaj"
-    else:
-      type, patterns, included, including = find_patterns(
-        lexical_class, forms, **extra)
-    if type == 'none':
-      if lexical_class.symbol == 'subst' and not extra['tantum']:
-        extra['tantum'] = tantum_a_posteriori(
-          form_set, [p for p, b_f in including])
-        if extra['tantum']:
-          if extra['tantum'] == 'pl':
-            extra['gender'] = 'p'
-            #if ic == 'm1':
-            #  extra['gender'] = 'p1'
-            #else:
-            #  extra['gender'] = 'p3'
-          return process_forms(lexical_class, forms, **extra)
+            ic = None
+        if lc_sym == 'subst':
+            # poprawka dla m2/m3
+            if ic in ('m2', 'm3') and patterns and not bad_patterns:
+                new_ic = ''
+                for pattern, root in all_patterns:
+                    for ic2 in ('m2', 'm3'):
+                        # jeśli wszystkie użycia tego wzoru są przy ic2
+                        if not pattern.lexemeinflectionpattern_set.exclude(
+                                inflection_characteristic__symbol=ic2).filter(
+                                lexeme__pk__in=sgjp).exists():
+                            if new_ic == '':
+                                new_ic = ic2
+                            elif new_ic != ic2:
+                                new_ic = None
+                if new_ic:
+                    ic = new_ic
+
+        if type == 'none':
+            debug(entry, u'zawiera się w %s' % join(p for p, b_f in including))
+            chosen = []
+            fitting = including
+            if lexical_class.symbol == 'adj' and including:
+                print_forms(forms, 'rzeczownik#')
+                return
+        elif type == 'match':
+            patterns.sort(key=lambda p: p[0].name)
+            fitting = patterns
+            chosen = patterns[:1]
+        elif type == 'many':
+            chosen = patterns[0]
+            if DEBUG:
+                print u'zestawy wielu wzorów: %s' % join_many(patterns)
+            fitting = patterns
+        if not DEBUG and lc_sym == 'v':
+            check, sgjp_derived = check_sgjp_v(entry, ic, chosen, **extra)
+            if check:
+                print_data({'lexeme': get_sgjp(check)})
+                for derived_lexemes in sgjp_derived.values():
+                    for derived_lexeme in derived_lexemes:
+                        print_data({'lexeme': get_sgjp(derived_lexeme)})
+                return
+        if not DEBUG:
+            data = lexeme_creation(
+                lc_sym, entry, ic, forms, type, chosen, fitting, bad_patterns,
+                included,
+                other_result, **extra2)
+            print_data(data)
 
-    if lexical_class.symbol == 'subst':
-      extra2['gender'] = ic
-    type, patterns, included, including, bad_patterns = filter_patterns(
-      blacklist_filter, u'czarną listę', type, patterns, included, including,
-      lexical_class, form_set, entry, **extra2)
-    if bad_patterns and other_result:
-      type, patterns, included, including = other_result
-      ic = extra2['gender'] = alternative_gender2[ic]
-      type, patterns, included, including, bad_patterns = filter_patterns(
-        blacklist_filter, u'czarną listę', type, patterns, included, including,
-        lexical_class, form_set, entry, **extra2)
-      other_result = None
-    elif other_result:
-      type2, patterns2, included2, including2 = other_result
-      new_other_result = filter_patterns(
-        blacklist_filter, u'czarną listę', type2, patterns2, included2,
-        including2, lexical_class, form_set, entry, **extra2)
-      if not new_other_result[4]:
-        other_result = new_other_result[:4]
-      else:
-        other_result = None
-
-    # wzory się już nie zmienią od tego miejsca
-    if type == 'many':
-      # albo patterns[0]...
-      all_patterns = [p for pattern_set in patterns for p in pattern_set]
-    else:
-      all_patterns = patterns
-    if type != 'none':
-      # brzydko...
-      if lexical_class.symbol == 'subst':
-        extra['ic'] = ic
-      ic = get_inflection_characteristic(lc_sym, forms, all_patterns, **extra)
-      if lexical_class.symbol == 'subst':
-        del extra['ic']
-    else:
-      ic = None
-    if lc_sym == 'subst':
-      # poprawka dla m2/m3
-      if ic in ('m2', 'm3') and patterns and not bad_patterns:
-        new_ic = ''
-        for pattern, root in all_patterns:
-          for ic2 in ('m2', 'm3'):
-            # jeśli wszystkie użycia tego wzoru są przy ic2
-            if not pattern.lexemeinflectionpattern_set.exclude(
-                 inflection_characteristic__symbol=ic2).filter(
-                   lexeme__pk__in=sgjp).exists():
-              if new_ic == '':
-                new_ic = ic2
-              elif new_ic != ic2:
-                new_ic = None
-        if new_ic:
-          ic = new_ic
-
-    if type == 'none':
-      debug(entry, u'zawiera się w %s' % join(p for p, b_f in including))
-      chosen = []
-      fitting = including
-      if lexical_class.symbol == 'adj' and including:
-        print_forms(forms, 'rzeczownik#')
-        return
-    elif type == 'match':
-      patterns.sort(key=lambda p: p[0].name)
-      fitting = patterns
-      chosen = patterns[:1]
-    elif type == 'many':
-      chosen = patterns[0]
-      if DEBUG:
-        print u'zestawy wielu wzorów: %s' % join_many(patterns)
-      fitting = patterns
-    if not DEBUG and lc_sym == 'v':
-      check, sgjp_derived = check_sgjp_v(entry, ic, chosen, **extra)
-      if check:
-        print_data({'lexeme': get_sgjp(check)})
-        for derived_lexemes in sgjp_derived.values():
-          for derived_lexeme in derived_lexemes:
-            print_data({'lexeme': get_sgjp(derived_lexeme)})
-        return
-    if not DEBUG:
-      data = lexeme_creation(
-        lc_sym, entry, ic, forms, type, chosen, fitting, bad_patterns, included,
-        other_result, **extra2)
-      print_data(data)
 
 def get_pos_ndm(tag):
-  if tag[0] == 'adv':
-    return 'adv' if tag[-1] != 'comp' else 'advcom'
-  elif tag[0] == 'xxx':
-    return 'burk'
-  else:
-    return tag[0]
+    if tag[0] == 'adv':
+        return 'adv' if tag[-1] != 'comp' else 'advcom'
+    elif tag[0] == 'xxx':
+        return 'burk'
+    else:
+        return tag[0]
+
 
 def process_ndm(forms):
-  entry = forms[0][0]
-  form_set = get_form_set(forms)
-  pattern_name = 'ndm'
-  ics = ['']
-  tag = forms[0][1].split(':')
-  pos = get_pos_ndm(tag)
-  status = 'desc'
-  comments = []
-  if len(form_set) > 2:
-    debug(entry, u'nieodmienne z ponad dwiema formami')
-    comments.append(u'nieodmienne z ponad dwiema formami')
-    status = 'cand'
-    ics = []
-  elif pos == 'prep':
-    if len(tag) == 1:
-      debug(entry, u'przyimek bez przypadku')
-      comments.append(u'przyimek bez przypadku')
-      status = 'cand'
-      ics = []
-    else:
-      ics = tag[1].split('.')
-    if len(form_set) == 2:
-      if entry + u'e' == forms[1][0]:
-        pattern_name = 'ndm e'
-      else:
-        debug(entry, u'nierozpoznana odmiana przyimka')
-        comments.append(u'nierozpoznana odmiana przyimka')
+    entry = forms[0][0]
+    form_set = get_form_set(forms)
+    pattern_name = 'ndm'
+    ics = ['']
+    tag = forms[0][1].split(':')
+    pos = get_pos_ndm(tag)
+    status = 'desc'
+    comments = []
+    if len(form_set) > 2:
+        debug(entry, u'nieodmienne z ponad dwiema formami')
+        comments.append(u'nieodmienne z ponad dwiema formami')
         status = 'cand'
-  elif len(form_set) == 2:
-    if pos == 'adv' and forms[1][0] == u'nie' + entry:
-      process_ndm(forms[:1])
-      process_ndm(forms[1:])
-      return
+        ics = []
+    elif pos == 'prep':
+        if len(tag) == 1:
+            debug(entry, u'przyimek bez przypadku')
+            comments.append(u'przyimek bez przypadku')
+            status = 'cand'
+            ics = []
+        else:
+            ics = tag[1].split('.')
+        if len(form_set) == 2:
+            if entry + u'e' == forms[1][0]:
+                pattern_name = 'ndm e'
+            else:
+                debug(entry, u'nierozpoznana odmiana przyimka')
+                comments.append(u'nierozpoznana odmiana przyimka')
+                status = 'cand'
+    elif len(form_set) == 2:
+        if pos == 'adv' and forms[1][0] == u'nie' + entry:
+            process_ndm(forms[:1])
+            process_ndm(forms[1:])
+            return
+        else:
+            debug(entry, u'nierozpoznane nieodmienne z dwiema formami')
+            comments.append(u'nierozpoznane nieodmienne z dwiema formami')
+            status = 'cand'
+        # sprawdzić czy to co wyszło jest już w sgjp
+    lexemes = Lexeme.objects.distinct().filter(entry=entry)
+    lexemes = lexemes.filter(pk__in=sgjp)
+    if pos == 'adv':
+        lexemes = lexemes.filter(part_of_speech__symbol__in=('adv', 'advndm'))
+    elif pos == 'conj':
+        lexemes = lexemes.filter(part_of_speech__symbol__in=('conj', 'comp'))
     else:
-      debug(entry, u'nierozpoznane nieodmienne z dwiema formami')
-      comments.append(u'nierozpoznane nieodmienne z dwiema formami')
-      status = 'cand'
-  # sprawdzić czy to co wyszło jest już w sgjp
-  lexemes = Lexeme.objects.distinct().filter(entry=entry)
-  lexemes = lexemes.filter(pk__in=sgjp)
-  if pos == 'adv':
-    lexemes = lexemes.filter(part_of_speech__symbol__in=('adv', 'advndm'))
-  elif pos == 'conj':
-    lexemes = lexemes.filter(part_of_speech__symbol__in=('conj', 'comp'))
-  else:
-    lexemes = lexemes.filter(part_of_speech__symbol=pos)
-  in_sgjp = bool(lexemes)
-  for lexeme in lexemes:
-    sgjp_ics = set()
-    for lip in lexeme.lexemeinflectionpattern_set.all():
-      if lip.pattern.name != pattern_name:
-        in_sgjp = False
-        break
-      sgjp_ics.add(lip.inflection_characteristic.symbol)
-    if set(ics) != sgjp_ics:
-      in_sgjp = False
+        lexemes = lexemes.filter(part_of_speech__symbol=pos)
+    in_sgjp = bool(lexemes)
+    for lexeme in lexemes:
+        sgjp_ics = set()
+        for lip in lexeme.lexemeinflectionpattern_set.all():
+            if lip.pattern.name != pattern_name:
+                in_sgjp = False
+                break
+            sgjp_ics.add(lip.inflection_characteristic.symbol)
+        if set(ics) != sgjp_ics:
+            in_sgjp = False
+        if in_sgjp:
+            break
     if in_sgjp:
-      break
-  if in_sgjp:
-    print_data({'lexeme': get_sgjp(lexeme)})
-  else:
-    data = {
-      'lexeme': create_lexeme(
-        entry, pos, status, '\n'.join(comments))
-    }
-    lips = []
-    for i, ic in enumerate(ics):
-      lips.append(create_lip(pattern_name, entry, i + 1, ic, pos))
-    data['lips'] = lips
-    print_data(data)
+        print_data({'lexeme': get_sgjp(lexeme)})
+    else:
+        data = {
+            'lexeme': create_lexeme(
+                entry, pos, status, '\n'.join(comments))
+        }
+        lips = []
+        for i, ic in enumerate(ics):
+            lips.append(create_lip(pattern_name, entry, i + 1, ic, pos))
+        data['lips'] = lips
+        print_data(data)
+
 
 def print_data(data):
-  print json.dumps(data)
+    print json.dumps(data)
+
 
 def print_forms(forms, prefix):
-  for form, tag in forms:
-    try:
-      end = tag.index('pos')
-    except ValueError:
-      end = tag.index('comp')
-    new_tag = ':'.join(tag[:end]).replace('adj', 'subst')
-    print>>sys.stderr, ('%s%s\t%s' % (prefix, form, new_tag)).encode('utf-8')
-  print>>sys.stderr, prefix
+    for form, tag in forms:
+        try:
+            end = tag.index('pos')
+        except ValueError:
+            end = tag.index('comp')
+        new_tag = ':'.join(tag[:end]).replace('adj', 'subst')
+        print>> sys.stderr, ('%s%s\t%s' % (prefix, form, new_tag)).encode(
+            'utf-8')
+    print>> sys.stderr, prefix
+
 
 def parse_file(lc_sym, path):
-  with open(path) as file:
-    lexical_class = LexicalClass.objects.get(symbol=lc_sym)
-    forms = []
-    for line in file:
-      line = line.decode('utf-8').rstrip('\n')
-      if line == '':
-        if lc_sym == 'ndm':
-          process_ndm(forms)
-        else:
-          forms = expand_forms(forms)
-          extra = get_extra(lexical_class, forms)
-          process_forms(lexical_class, forms, **extra)
+    with open(path) as file:
+        lexical_class = LexicalClass.objects.get(symbol=lc_sym)
         forms = []
-      else:
-        form, tag = line.split('\t')
-        if DEBUG and forms == []:
-          print form
-        forms.append((form, tag))
+        for line in file:
+            line = line.decode('utf-8').rstrip('\n')
+            if line == '':
+                if lc_sym == 'ndm':
+                    process_ndm(forms)
+                else:
+                    forms = expand_forms(forms)
+                    extra = get_extra(lexical_class, forms)
+                    process_forms(lexical_class, forms, **extra)
+                forms = []
+            else:
+                form, tag = line.split('\t')
+                if DEBUG and forms == []:
+                    print form
+                forms.append((form, tag))
diff --git a/dictionary/management/commands/import_odm.py b/dictionary/management/commands/import_odm.py
index c77b4c2..1b67063 100644
--- a/dictionary/management/commands/import_odm.py
+++ b/dictionary/management/commands/import_odm.py
@@ -1,35 +1,35 @@
 #-*- coding:utf-8 -*-
 
-import sys
 from django.db import connection, transaction
-from django.core.management.base import BaseCommand, CommandError
-from common.util import debug
-from dictionary.models import Lexeme
+from django.core.management.base import BaseCommand
+
 
 class Command(BaseCommand):
-  args = '<nazwa pliku wejściowego>'
-  help = 'Imports forms from odm.txt used for import'
+    args = '<nazwa pliku wejściowego>'
+    help = 'Imports forms from odm.txt used for import'
 
-  def handle(self, input_file, **options):
-    import_odm(input_file)
+    def handle(self, input_file, **options):
+        import_odm(input_file)
 
 
 def import_odm(filename):
-  cursor = connection.cursor()
-
-  transaction.commit_unless_managed()
-  transaction.enter_transaction_management()
-  transaction.managed(True)
-
-  for line in open(filename):
-    forms = line.strip().decode('utf-8').split(', ')
-    cursor.execute("INSERT INTO dictionary_inputlexeme (entry) "
-                   "VALUES (%s)", [forms[0]])
-    cursor.execute("select currval('dictionary_inputlexeme_id_seq'::regclass)")
-    il_id = cursor.fetchone()[0]
-    for form in forms:
-      cursor.execute("INSERT INTO dictionary_inputform (form, input_lexeme_id) "
-                     "VALUES (%s, %s)", [form, il_id])
-
-  transaction.commit()
-  transaction.leave_transaction_management()
+    cursor = connection.cursor()
+
+    transaction.commit_unless_managed()
+    transaction.enter_transaction_management()
+    transaction.managed(True)
+
+    for line in open(filename):
+        forms = line.strip().decode('utf-8').split(', ')
+        cursor.execute("INSERT INTO dictionary_inputlexeme (entry) "
+                       "VALUES (%s)", [forms[0]])
+        cursor.execute(
+            "select currval('dictionary_inputlexeme_id_seq'::regclass)")
+        il_id = cursor.fetchone()[0]
+        for form in forms:
+            cursor.execute(
+                "INSERT INTO dictionary_inputform (form, input_lexeme_id) "
+                "VALUES (%s, %s)", [form, il_id])
+
+    transaction.commit()
+    transaction.leave_transaction_management()
diff --git a/dictionary/management/commands/import_resztki.py b/dictionary/management/commands/import_resztki.py
index c2c88f7..eff95d4 100644
--- a/dictionary/management/commands/import_resztki.py
+++ b/dictionary/management/commands/import_resztki.py
@@ -1,19 +1,23 @@
 #-*- coding:utf-8 -*-
 
-from django.core.management.base import BaseCommand
 import json
+
+from django.core.management.base import BaseCommand
+
 from common.util import suffixes, cut_end, debug, GroupDict
-from dictionary.models import Pattern, Lexeme, InflectionCharacteristic,\
-  Ending, LexicalClass, BaseFormLabel, Vocabulary
+from dictionary.models import Pattern, Lexeme, InflectionCharacteristic, \
+    Ending, LexicalClass, BaseFormLabel, Vocabulary
 from dictionary.pattern_blacklist import blacklist
 from dictionary.management.commands.import_morfologik import join, join_many, \
-  relevant_subst, relevant_adj, find_minimal_sets
+    relevant_subst, relevant_adj, find_minimal_sets
+
 
 class Command(BaseCommand):
-  args = '<nazwa pliku wejściowego>'
+    args = '<nazwa pliku wejściowego>'
+
+    def handle(self, input_file, **options):
+        import_resztki(open(input_file))
 
-  def handle(self, input_file, **options):
-    import_resztki(open(input_file))
 
 DEBUG = False
 
@@ -22,748 +26,808 @@ GENDERS = ('m1', 'm2', 'm3', 'm', 'f', 'n1', 'n2', 'p1', 'p2', 'p3')
 #morf = Vocabulary.objects.get(id='Morfologik').owned_lexemes.all()
 sgjp = Lexeme.objects.exclude(source='Morfologik')
 
+
 def get_basic_endings(parts_of_speech, genders=None):
-  ics = InflectionCharacteristic.objects.filter(
-    part_of_speech__in=parts_of_speech)
-  if genders:
-    ics = ics.filter(symbol__in=genders)
-  basic_form_labels = ics.values_list('basic_form_label', flat=True).distinct()
-  return Ending.objects.filter(base_form_label__pk__in=basic_form_labels,
-    pattern__type__lexical_class=lexical_class)
+    ics = InflectionCharacteristic.objects.filter(
+        part_of_speech__in=parts_of_speech)
+    if genders:
+        ics = ics.filter(symbol__in=genders)
+    basic_form_labels = ics.values_list('basic_form_label',
+                                        flat=True).distinct()
+    return Ending.objects.filter(base_form_label__pk__in=basic_form_labels,
+                                 pattern__type__lexical_class=lexical_class)
+
 
 def expand_gender(gender):
-  if gender == 'm':
-    return ['m1', 'm2', 'm3']
-  else:
-    return [gender]
+    if gender == 'm':
+        return ['m1', 'm2', 'm3']
+    else:
+        return [gender]
+
 
 basic_form_endings_dict = {}
 for lexical_class in LexicalClass.objects.all():
-  parts_of_speech = lexical_class.partofspeech_set.all()
-  if lexical_class.symbol == 'subst':
-    for gender in GENDERS:
-      basic_form_endings_dict[(lexical_class, gender)] = get_basic_endings(
-        parts_of_speech, expand_gender(gender))
-  else:
-    basic_form_endings_dict[lexical_class] = get_basic_endings(
-      parts_of_speech)
+    parts_of_speech = lexical_class.partofspeech_set.all()
+    if lexical_class.symbol == 'subst':
+        for gender in GENDERS:
+            basic_form_endings_dict[
+                (lexical_class, gender)] = get_basic_endings(
+                parts_of_speech, expand_gender(gender))
+    else:
+        basic_form_endings_dict[lexical_class] = get_basic_endings(
+            parts_of_speech)
+
 
 def tantum_a_posteriori(form_set, patterns):
-  tantum = None
-  for pattern, root in patterns:
-    tantum_forms = {
-      'sg': set(root + e for e in
-        pattern.endings.filter(base_form_label__symbol__startswith='sg')
-        .values_list('string', flat=True)),
-      'pl': set(root + e for e in
-        pattern.endings.filter(base_form_label__symbol__startswith='pl')
-        .values_list('string', flat=True)),
-      }
-    for num in ('sg', 'pl'):
-      if form_set.issubset(tantum_forms[num]):
-        tantum = num
-    if tantum:
-      return tantum
-  if not patterns:
-    return 'sg'
-  return None
+    tantum = None
+    for pattern, root in patterns:
+        tantum_forms = {
+            'sg': set(root + e for e in
+                      pattern.endings.filter(
+                          base_form_label__symbol__startswith='sg')
+                      .values_list('string', flat=True)),
+            'pl': set(root + e for e in
+                      pattern.endings.filter(
+                          base_form_label__symbol__startswith='pl')
+                      .values_list('string', flat=True)),
+        }
+        for num in ('sg', 'pl'):
+            if form_set.issubset(tantum_forms[num]):
+                tantum = num
+        if tantum:
+            return tantum
+    if not patterns:
+        return 'sg'
+    return None
+
 
 def relevant(lexical_class, ending, **extra):
-  if lexical_class.symbol == 'subst':
-    return relevant_subst(ending, **extra)
-  elif lexical_class.symbol == 'adj':
-    return relevant_adj(ending)
+    if lexical_class.symbol == 'subst':
+        return relevant_subst(ending, **extra)
+    elif lexical_class.symbol == 'adj':
+        return relevant_adj(ending)
+
 
 from itertools import chain, combinations
+
+
 def powerset(iterable):
-  """powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"""
-  s = list(iterable)
-  return chain.from_iterable(
-    combinations(s, r) for r in xrange(min(len(s)+1, 5)))
+    """powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"""
+    s = list(iterable)
+    return chain.from_iterable(
+        combinations(s, r) for r in xrange(min(len(s) + 1, 5)))
+
 
 sure_bfls_sg = tuple(
-  BaseFormLabel.objects.filter(
-    symbol__in=['sg:dat', 'sg:gen', 'sg:inst']).values_list('pk', flat=True))
+    BaseFormLabel.objects.filter(
+        symbol__in=['sg:dat', 'sg:gen', 'sg:inst']).values_list('pk',
+                                                                flat=True))
 sure_bfls_pl = tuple(
-  BaseFormLabel.objects.filter(
-    symbol__in=['pl:dat', 'pl:inst', 'pl:loc']).values_list('pk', flat=True))
+    BaseFormLabel.objects.filter(
+        symbol__in=['pl:dat', 'pl:inst', 'pl:loc']).values_list('pk',
+                                                                flat=True))
+
 
 def basic_form_endings(lexical_class, basic_form, form_set, **extra):
-  if 'gender' in extra:
-    key = (lexical_class, extra['gender'])
-  else:
-    key = lexical_class
-  if lexical_class.symbol != 'subst':
-    return basic_form_endings_dict[key].filter(string__in=suffixes(basic_form))
-  else:
-    # karkołomne, ale trochę przyśpiesza
-    endings = basic_form_endings_dict[key]
-    new_endings = Ending.objects.none()
-    for suf in suffixes(basic_form):
-      root = cut_end(basic_form, suf)
-      n = len(root)
-      ending_strings = tuple(
-        form[n:] for form in form_set if form.startswith(root))
-      endings_part = endings.filter(string=suf)
-      pattern_pks = endings_part.values_list('pattern', flat=True)
-      patterns = Pattern.objects.filter(pk__in=pattern_pks).extra(
-        where=["(w_id = '0000' or not exists "
-               "(select id from zakonczenia where w_id = wzory.id "
-               "and zak not in %s and efobaz in %s) or not exists "
-               "(select id from zakonczenia where w_id = wzory.id "
-               "and zak not in %s and efobaz in %s))"],
-        params=[ending_strings, sure_bfls_sg, ending_strings, sure_bfls_pl])
-      new_endings = new_endings | endings_part.filter(pattern__in=patterns)
-    return new_endings
+    if 'gender' in extra:
+        key = (lexical_class, extra['gender'])
+    else:
+        key = lexical_class
+    if lexical_class.symbol != 'subst':
+        return basic_form_endings_dict[key].filter(
+            string__in=suffixes(basic_form))
+    else:
+        # karkołomne, ale trochę przyśpiesza
+        endings = basic_form_endings_dict[key]
+        new_endings = Ending.objects.none()
+        for suf in suffixes(basic_form):
+            root = cut_end(basic_form, suf)
+            n = len(root)
+            ending_strings = tuple(
+                form[n:] for form in form_set if form.startswith(root))
+            endings_part = endings.filter(string=suf)
+            pattern_pks = endings_part.values_list('pattern', flat=True)
+            patterns = Pattern.objects.filter(pk__in=pattern_pks).extra(
+                where=["(w_id = '0000' or not exists "
+                       "(select id from zakonczenia where w_id = wzory.id "
+                       "and zak not in %s and efobaz in %s) or not exists "
+                       "(select id from zakonczenia where w_id = wzory.id "
+                       "and zak not in %s and efobaz in %s))"],
+                params=[ending_strings, sure_bfls_sg, ending_strings,
+                        sure_bfls_pl])
+            new_endings = new_endings | endings_part.filter(
+                pattern__in=patterns)
+        return new_endings
+
 
 memoized_good_endings = {}
 
+
 def good_ending_set_subst(pattern, root, tantum, gender):
-  if (pattern, tantum, gender) in memoized_good_endings:
-    good_endings = memoized_good_endings[(pattern, tantum, gender)]
+    if (pattern, tantum, gender) in memoized_good_endings:
+        good_endings = memoized_good_endings[(pattern, tantum, gender)]
+        return set(root + e for e in good_endings)
+    endings = pattern.endings
+    if tantum:
+        endings = endings.filter(base_form_label__symbol__startswith=tantum)
+    if gender not in ('m1', 'p1'):
+        endings = endings.exclude(base_form_label__symbol='pl:nom:mo')
+    if gender[0] != 'p':
+        for g in list(set('mfn') - set(gender[0])):
+            endings = endings.exclude(
+                base_form_label__symbol__startswith='pl:gen:' + g)
+    if gender == 'p3':
+        if pattern.type.symbol == 'f':
+            endings = endings.exclude(base_form_label__symbol='pl:gen:m')
+        if pattern.type.symbol == 'n':
+            endings = endings.exclude(base_form_label__symbol='pl:gen:n')
+    good_endings = list(endings.values_list('string', flat=True))
+    memoized_good_endings[(pattern, tantum, gender)] = good_endings
     return set(root + e for e in good_endings)
-  endings = pattern.endings
-  if tantum:
-    endings = endings.filter(base_form_label__symbol__startswith=tantum)
-  if gender not in ('m1', 'p1'):
-    endings = endings.exclude(base_form_label__symbol='pl:nom:mo')
-  if gender[0] != 'p':
-    for g in list(set('mfn') - set(gender[0])):
-      endings = endings.exclude(
-        base_form_label__symbol__startswith='pl:gen:' + g)
-  if gender == 'p3':
-    if pattern.type.symbol == 'f':
-      endings = endings.exclude(base_form_label__symbol='pl:gen:m')
-    if pattern.type.symbol == 'n':
-      endings = endings.exclude(base_form_label__symbol='pl:gen:n')
-  good_endings = list(endings.values_list('string', flat=True))
-  memoized_good_endings[(pattern, tantum, gender)] = good_endings
-  return set(root + e for e in good_endings)
+
 
 def good_ending_set(lexical_class, pattern, root='', **extra):
-  if lexical_class.symbol != 'subst':
-    return pattern.ending_set(root)
-  else:
-    return good_ending_set_subst(pattern, root, **extra)
+    if lexical_class.symbol != 'subst':
+        return pattern.ending_set(root)
+    else:
+        return good_ending_set_subst(pattern, root, **extra)
+
 
 memoized_pattern_ics = {}
 
+
 def bad_pattern_subst(pattern, gender, tantum):
-  if (pattern, gender) in memoized_pattern_ics:
-    return memoized_pattern_ics[(pattern, gender)]
-  ics = expand_gender(gender)
-  if gender == 'p1':
-    ics.append('m1')
-  if gender in ('p2', 'p3'):
-    ics += ['m2', 'm3', 'f', 'n1', 'n2']
-  if not pattern.lexemeinflectionpattern_set.filter(
-    inflection_characteristic__symbol__in=ics).filter(lexeme__pk__in=sgjp):
-    ret = True
-  elif pattern.type.symbol in 'mn' and gender == 'f':
-    ret = True
-  elif pattern.type.symbol in 'fm' and gender[0] == 'n':
-    ret = True
-  else:
-    ret = False
-  memoized_pattern_ics[(pattern, gender)] = ret
-  return ret
+    if (pattern, gender) in memoized_pattern_ics:
+        return memoized_pattern_ics[(pattern, gender)]
+    ics = expand_gender(gender)
+    if gender == 'p1':
+        ics.append('m1')
+    if gender in ('p2', 'p3'):
+        ics += ['m2', 'm3', 'f', 'n1', 'n2']
+    if not pattern.lexemeinflectionpattern_set.filter(
+            inflection_characteristic__symbol__in=ics).filter(
+            lexeme__pk__in=sgjp):
+        ret = True
+    elif pattern.type.symbol in 'mn' and gender == 'f':
+        ret = True
+    elif pattern.type.symbol in 'fm' and gender[0] == 'n':
+        ret = True
+    else:
+        ret = False
+    memoized_pattern_ics[(pattern, gender)] = ret
+    return ret
+
 
 def find_patterns(lexical_class, basic_form, forms, **extra):
-  #patterns = Pattern.objects.filter(type__lexical_class=lexical_class)
-  # znaleźć wszystkie zawarte i zawierające wzory
-  form_set = set(forms)
-  ending_sets = {}
-  included_patterns = set()
-  including_patterns = set()
-  matching_patterns = set()
-  base_forms_changed = False
-  for basic_ending in basic_form_endings(
-      lexical_class, basic_form, form_set, **extra):
-    pattern = basic_ending.pattern
-    if lexical_class.symbol == 'subst' and bad_pattern_subst(pattern, **extra):
-      #print 'odpadł:', pattern
-      continue # olewamy komentarze że formy odrzucone przez charfle?
-    root = basic_form[:len(basic_form) - len(basic_ending.string)]
-    ending_sets[pattern] = good_ending_set(
-      lexical_class, pattern, root, **extra)
-    including = form_set.issubset(ending_sets[pattern])
-    extra_base_forms = []
-    bad_forms = set()
-    for ending in pattern.endings.all():
-      if relevant(lexical_class, ending, **extra):
-        if root + ending.string not in form_set:
-          if DEBUG:
-            bfl = ending.base_form_label.symbol
-            #print pattern.name, root, ending.string, bfl
-          bad_forms.add(root + ending.string)
-    if not bad_forms:
-      if extra_base_forms:
-        extra['base_forms'] += extra_base_forms
-        base_forms_changed = True
-      included_patterns.add((pattern, root))
-      if including:
-        matching_patterns.add((pattern, root))
-    elif including:
-      including_patterns.add(((pattern, root), tuple(bad_forms)))
-
-  if base_forms_changed:
-    #print extra['base_forms']
-    return find_patterns(lexical_class, basic_form, forms, **extra)
-    # nie wiem, czy to potrzebne, ale na wszelki wypadek
-  included_patterns = list(included_patterns)
-  including_patterns = list(including_patterns)
-  matching_patterns = list(matching_patterns)
-  if len(matching_patterns) > 0:
-    if DEBUG:
-      print u'dokładne wzory: %s' % join(matching_patterns)
-    return 'match', matching_patterns, included_patterns, including_patterns
-    # nic nie pasuje albo trzeba wybrać wiele wzorów
-  if DEBUG and len(including_patterns) > 0:
-    print u'zawierające: %s' % join(p for p, b_f in including_patterns)
-  if DEBUG and len(included_patterns) > 0:
-    print u'zawarte: %s' % join(included_patterns)
-  return find_many_patterns(
-    lexical_class, form_set, basic_form, included_patterns, ending_sets,
-    **extra) + (included_patterns, including_patterns)
+    #patterns = Pattern.objects.filter(type__lexical_class=lexical_class)
+    # znaleźć wszystkie zawarte i zawierające wzory
+    form_set = set(forms)
+    ending_sets = {}
+    included_patterns = set()
+    including_patterns = set()
+    matching_patterns = set()
+    base_forms_changed = False
+    for basic_ending in basic_form_endings(
+            lexical_class, basic_form, form_set, **extra):
+        pattern = basic_ending.pattern
+        if lexical_class.symbol == 'subst' and bad_pattern_subst(pattern,
+                                                                 **extra):
+            #print 'odpadł:', pattern
+            continue # olewamy komentarze że formy odrzucone przez charfle?
+        root = basic_form[:len(basic_form) - len(basic_ending.string)]
+        ending_sets[pattern] = good_ending_set(
+            lexical_class, pattern, root, **extra)
+        including = form_set.issubset(ending_sets[pattern])
+        extra_base_forms = []
+        bad_forms = set()
+        for ending in pattern.endings.all():
+            if relevant(lexical_class, ending, **extra):
+                if root + ending.string not in form_set:
+                    if DEBUG:
+                        bfl = ending.base_form_label.symbol
+                        #print pattern.name, root, ending.string, bfl
+                    bad_forms.add(root + ending.string)
+        if not bad_forms:
+            if extra_base_forms:
+                extra['base_forms'] += extra_base_forms
+                base_forms_changed = True
+            included_patterns.add((pattern, root))
+            if including:
+                matching_patterns.add((pattern, root))
+        elif including:
+            including_patterns.add(((pattern, root), tuple(bad_forms)))
+
+    if base_forms_changed:
+        #print extra['base_forms']
+        return find_patterns(lexical_class, basic_form, forms, **extra)
+        # nie wiem, czy to potrzebne, ale na wszelki wypadek
+    included_patterns = list(included_patterns)
+    including_patterns = list(including_patterns)
+    matching_patterns = list(matching_patterns)
+    if len(matching_patterns) > 0:
+        if DEBUG:
+            print u'dokładne wzory: %s' % join(matching_patterns)
+        return 'match', matching_patterns, included_patterns, including_patterns
+        # nic nie pasuje albo trzeba wybrać wiele wzorów
+    if DEBUG and len(including_patterns) > 0:
+        print u'zawierające: %s' % join(p for p, b_f in including_patterns)
+    if DEBUG and len(included_patterns) > 0:
+        print u'zawarte: %s' % join(included_patterns)
+    return find_many_patterns(
+        lexical_class, form_set, basic_form, included_patterns, ending_sets,
+        **extra) + (included_patterns, including_patterns)
+
 
 def find_many_patterns(lexical_class, form_set, basic_form, included_patterns,
                        ending_sets, **extra):
-  necessary_patterns = set()
-  missing_form = None
-  for form in form_set:
-    having = []
-    for pattern, root in included_patterns:
-      if form in ending_sets[pattern]:
-        having.append((pattern, root))
-    if len(having) == 1:
-      necessary_patterns.add(having[0])
-    if not having:
-      missing_form = form
-      break
-  if missing_form:
-    if DEBUG:
-      print u"brak formy: %s" % missing_form
-    return 'none', []
-  covered_forms = set()
-  for pattern, root in necessary_patterns:
-    covered_forms |= ending_sets[pattern]
-  if form_set.issubset(covered_forms):
-    if DEBUG:
-      print u"pokryte koniecznymi wzorami: %s" % join(necessary_patterns)
-    return 'many', [list(necessary_patterns)]
-  else:
-    #for pattern, root in included_patterns:
-    #  print pattern, ending_sets[pattern]
-    minimal_sets = find_minimal_sets(
-      form_set, covered_forms, necessary_patterns, included_patterns,
-      ending_sets)
-    return 'many', minimal_sets
+    necessary_patterns = set()
+    missing_form = None
+    for form in form_set:
+        having = []
+        for pattern, root in included_patterns:
+            if form in ending_sets[pattern]:
+                having.append((pattern, root))
+        if len(having) == 1:
+            necessary_patterns.add(having[0])
+        if not having:
+            missing_form = form
+            break
+    if missing_form:
+        if DEBUG:
+            print u"brak formy: %s" % missing_form
+        return 'none', []
+    covered_forms = set()
+    for pattern, root in necessary_patterns:
+        covered_forms |= ending_sets[pattern]
+    if form_set.issubset(covered_forms):
+        if DEBUG:
+            print u"pokryte koniecznymi wzorami: %s" % join(necessary_patterns)
+        return 'many', [list(necessary_patterns)]
+    else:
+        #for pattern, root in included_patterns:
+        #  print pattern, ending_sets[pattern]
+        minimal_sets = find_minimal_sets(
+            form_set, covered_forms, necessary_patterns, included_patterns,
+            ending_sets)
+        return 'many', minimal_sets
+
 
 def check_sgjp(lc_sym, entry, form_set, **extra):
-  if lc_sym != 'adj':
-    lexemes = Lexeme.objects.distinct().filter(
-      entry=entry, part_of_speech__lexical_class__symbol=lc_sym)
-  else:
-    lexemes = Lexeme.objects.distinct().filter(
-      entry=entry, part_of_speech__symbol__in=('adj', 'appas'))
-  lexemes = lexemes.filter(pk__in=sgjp)
-  matched_lexemes = []
-  for lexeme in lexemes:
-    if lc_sym == 'adj' and lexeme.refs_to.filter(type='nieadj'):
-      continue
-    if lc_sym == 'subst' and extra['tantum'] == 'sg':
-      sgjp_forms = lexeme.all_forms(affixes=False, label_filter=r'sg:')
-    elif lexeme.part_of_speech.symbol == 'appas':
-      sgjp_forms = lexeme.all_forms(affixes=True)
+    if lc_sym != 'adj':
+        lexemes = Lexeme.objects.distinct().filter(
+            entry=entry, part_of_speech__lexical_class__symbol=lc_sym)
     else:
-      sgjp_forms = lexeme.all_forms(affixes=False)
-    if sgjp_forms == form_set:
-      matched_lexemes.append(lexeme)
-      continue
-    diff = sgjp_forms - form_set
-    exceptions = []
-    if lc_sym == 'subst':
-      if lexeme.lexemeinflectionpattern_set.filter(
-          inflection_characteristic__symbol__in=('m1', 'p1')).exists():
-        # depr
-        exceptions = lexeme.all_forms(affixes=False, label_filter=r'^pl:nom$')
-    elif lc_sym == 'adj':
-      # -o
-      exceptions = lexeme.all_forms(affixes=False, label_filter=r'^0$')
-    if form_set.issubset(sgjp_forms) and diff.issubset(exceptions):
-      matched_lexemes.append(lexeme)
-  if len(matched_lexemes) > 1:
-    if lc_sym == 'subst' and entry.endswith(u'ość'):
-      matched_lexemes_subst = [
-      l for l in matched_lexemes if l.part_of_speech.symbol == 'subst']
-      if matched_lexemes_subst:
-        matched_lexemes = matched_lexemes_subst
+        lexemes = Lexeme.objects.distinct().filter(
+            entry=entry, part_of_speech__symbol__in=('adj', 'appas'))
+    lexemes = lexemes.filter(pk__in=sgjp)
+    matched_lexemes = []
+    for lexeme in lexemes:
+        if lc_sym == 'adj' and lexeme.refs_to.filter(type='nieadj'):
+            continue
+        if lc_sym == 'subst' and extra['tantum'] == 'sg':
+            sgjp_forms = lexeme.all_forms(affixes=False, label_filter=r'sg:')
+        elif lexeme.part_of_speech.symbol == 'appas':
+            sgjp_forms = lexeme.all_forms(affixes=True)
+        else:
+            sgjp_forms = lexeme.all_forms(affixes=False)
+        if sgjp_forms == form_set:
+            matched_lexemes.append(lexeme)
+            continue
+        diff = sgjp_forms - form_set
+        exceptions = []
+        if lc_sym == 'subst':
+            if lexeme.lexemeinflectionpattern_set.filter(
+                    inflection_characteristic__symbol__in=(
+                    'm1', 'p1')).exists():
+                # depr
+                exceptions = lexeme.all_forms(affixes=False,
+                                              label_filter=r'^pl:nom$')
+        elif lc_sym == 'adj':
+            # -o
+            exceptions = lexeme.all_forms(affixes=False, label_filter=r'^0$')
+        if form_set.issubset(sgjp_forms) and diff.issubset(exceptions):
+            matched_lexemes.append(lexeme)
     if len(matched_lexemes) > 1:
-      debug(entry, u'niejednoznaczność dopasowanych leksemów')
-  if len(matched_lexemes) > 0:
-    return matched_lexemes[0]
-  return False
+        if lc_sym == 'subst' and entry.endswith(u'ość'):
+            matched_lexemes_subst = [
+                l for l in matched_lexemes if
+                l.part_of_speech.symbol == 'subst']
+            if matched_lexemes_subst:
+                matched_lexemes = matched_lexemes_subst
+        if len(matched_lexemes) > 1:
+            debug(entry, u'niejednoznaczność dopasowanych leksemów')
+    if len(matched_lexemes) > 0:
+        return matched_lexemes[0]
+    return False
+
 
 def closest_lexeme_subst(entry, gender, patterns, included=None):
-  lexemes = Lexeme.objects.filter(
-    part_of_speech__lexical_class__symbol='subst')
-  lexemes = lexemes.distinct()
-  # ten sam rodzaj
-  genders = expand_gender(gender)
-  lexemes = lexemes.filter(
-    lexemeinflectionpattern__inflection_characteristic__symbol__in=
-    genders)
-  if not included:
-    # posiada wzór zawierający się w pasujących
-    lexemes = lexemes.filter(lexemeinflectionpattern__pattern__in=patterns)
-  else:
-    #print patterns, included
-    new_lexemes = Lexeme.objects.none()
-    # posiada wszystkie wzory z któregoś zestawu
-    for pattern_set in patterns:
-      part = lexemes
-      for pattern, root in pattern_set:
-        part = part.filter(lexemeinflectionpattern__pattern=pattern)
-      new_lexemes |= part
-    lexemes = new_lexemes.distinct()
-  # nie posiada wzorów niezawierających się w pasujących, dobra wielkość
-  uppercase = entry[0].isupper()
-  good_lexemes = []
-  for lexeme in lexemes:
-    if lexeme.entry[0].isupper() == uppercase:
-      for lip in lexeme.lexemeinflectionpattern_set.all():
-        if not included:
-          if lip.pattern not in patterns:
-            break
-        else:
-          if lip.pattern not in included:
-            break
-      else:
-        good_lexemes.append(lexeme)
-  # najdłuższe wspólne zakończenie
-  best = (-1, None)
-  for lexeme in good_lexemes:
-    common_suffix = 0
-    for char1, char2 in zip(entry[::-1], lexeme.entry[::-1]):
-      if char1 == char2:
-        common_suffix += 1
-      else:
-        break
-    if common_suffix > best[0]:
-      best = (common_suffix, lexeme)
-  return best[1]
+    lexemes = Lexeme.objects.filter(
+        part_of_speech__lexical_class__symbol='subst')
+    lexemes = lexemes.distinct()
+    # ten sam rodzaj
+    genders = expand_gender(gender)
+    lexemes = lexemes.filter(
+        lexemeinflectionpattern__inflection_characteristic__symbol__in=
+        genders)
+    if not included:
+        # posiada wzór zawierający się w pasujących
+        lexemes = lexemes.filter(lexemeinflectionpattern__pattern__in=patterns)
+    else:
+        #print patterns, included
+        new_lexemes = Lexeme.objects.none()
+        # posiada wszystkie wzory z któregoś zestawu
+        for pattern_set in patterns:
+            part = lexemes
+            for pattern, root in pattern_set:
+                part = part.filter(lexemeinflectionpattern__pattern=pattern)
+            new_lexemes |= part
+        lexemes = new_lexemes.distinct()
+        # nie posiada wzorów niezawierających się w pasujących, dobra wielkość
+    uppercase = entry[0].isupper()
+    good_lexemes = []
+    for lexeme in lexemes:
+        if lexeme.entry[0].isupper() == uppercase:
+            for lip in lexeme.lexemeinflectionpattern_set.all():
+                if not included:
+                    if lip.pattern not in patterns:
+                        break
+                else:
+                    if lip.pattern not in included:
+                        break
+            else:
+                good_lexemes.append(lexeme)
+        # najdłuższe wspólne zakończenie
+    best = (-1, None)
+    for lexeme in good_lexemes:
+        common_suffix = 0
+        for char1, char2 in zip(entry[::-1], lexeme.entry[::-1]):
+            if char1 == char2:
+                common_suffix += 1
+            else:
+                break
+        if common_suffix > best[0]:
+            best = (common_suffix, lexeme)
+    return best[1]
+
 
 def blacklist_filter(patterns):
-  return [(pattern, root) for (pattern, root) in patterns
-          if pattern.name not in blacklist]
+    return [(pattern, root) for (pattern, root) in patterns
+            if pattern.name not in blacklist]
+
 
 def filter_patterns(filter, action_name, type, patterns, included, including,
                     lexical_class, form_set, entry, **extra):
-  old_patterns = patterns
-  old_included = included
-  bad_patterns = False
-  if type == 'many':
-    if any(pattern_set != filter(pattern_set) for pattern_set in patterns):
-      included = filter(included)
-      ending_sets = {}
-      for pattern, root in included:
-        ending_sets[pattern] = good_ending_set(
-          lexical_class, pattern, root, **extra)
-      type, patterns = find_many_patterns(
-        lexical_class, form_set, entry, included, ending_sets, **extra)
-      if type != 'many':
-        debug(entry, u'mnogie dopasowanie zepsute przez %s (%s)' %
-                     (action_name, join_many(old_patterns)))
-        type = 'many'
-        patterns, included = old_patterns, old_included
-        bad_patterns = True
-  elif type == 'none':
-    including_dict = dict(including)
-    including = [(key, including_dict[key]) for key in filter(including_dict)]
-  else: # type == 'match'
-    patterns = filter(patterns)
-    including_dict = dict(including)
-    including = [(key, including_dict[key]) for key in filter(including_dict)]
-    included = filter(included)
-    if old_patterns and not patterns:
-      ending_sets = {}
-      for pattern, root in included:
-        ending_sets[pattern] = good_ending_set(
-          lexical_class, pattern, root, **extra)
-      type, patterns = find_many_patterns(
-        lexical_class, form_set, entry, included, ending_sets, **extra)
-      if type == 'none':
-        debug(entry, u'znikły wzory przez %s (%s)' %
-                     (action_name, join(old_patterns)))
-        type = 'match'
-        patterns = old_patterns
-        bad_patterns = True
-  return type, patterns, included, including, bad_patterns
+    old_patterns = patterns
+    old_included = included
+    bad_patterns = False
+    if type == 'many':
+        if any(pattern_set != filter(pattern_set) for pattern_set in patterns):
+            included = filter(included)
+            ending_sets = {}
+            for pattern, root in included:
+                ending_sets[pattern] = good_ending_set(
+                    lexical_class, pattern, root, **extra)
+            type, patterns = find_many_patterns(
+                lexical_class, form_set, entry, included, ending_sets, **extra)
+            if type != 'many':
+                debug(entry, u'mnogie dopasowanie zepsute przez %s (%s)' %
+                             (action_name, join_many(old_patterns)))
+                type = 'many'
+                patterns, included = old_patterns, old_included
+                bad_patterns = True
+    elif type == 'none':
+        including_dict = dict(including)
+        including = [(key, including_dict[key]) for key in
+                     filter(including_dict)]
+    else: # type == 'match'
+        patterns = filter(patterns)
+        including_dict = dict(including)
+        including = [(key, including_dict[key]) for key in
+                     filter(including_dict)]
+        included = filter(included)
+        if old_patterns and not patterns:
+            ending_sets = {}
+            for pattern, root in included:
+                ending_sets[pattern] = good_ending_set(
+                    lexical_class, pattern, root, **extra)
+            type, patterns = find_many_patterns(
+                lexical_class, form_set, entry, included, ending_sets, **extra)
+            if type == 'none':
+                debug(entry, u'znikły wzory przez %s (%s)' %
+                             (action_name, join(old_patterns)))
+                type = 'match'
+                patterns = old_patterns
+                bad_patterns = True
+    return type, patterns, included, including, bad_patterns
+
 
 def create_derived(pos, base_forms, forms, patterns):
-  tab = {'ger': ('11', u'ie'), 'pact': ('3', u'cy'), 'ppas': ('10', u'y')}
-  entries = GroupDict()
-  for pattern, root in patterns:
-    bfl = tab[pos][0]
-    ending = pattern.endings.get(base_form_label__symbol=bfl)
-    entry = root + ending.string + tab[pos][1]
-    entries.add(entry, pattern.name)
-  output = []
-  for entry, patterns in entries.iteritems():
-    if entry in forms:
-      output.append((pos, entry, patterns))
-  return output
+    tab = {'ger': ('11', u'ie'), 'pact': ('3', u'cy'), 'ppas': ('10', u'y')}
+    entries = GroupDict()
+    for pattern, root in patterns:
+        bfl = tab[pos][0]
+        ending = pattern.endings.get(base_form_label__symbol=bfl)
+        entry = root + ending.string + tab[pos][1]
+        entries.add(entry, pattern.name)
+    output = []
+    for entry, patterns in entries.iteritems():
+        if entry in forms:
+            output.append((pos, entry, patterns))
+    return output
+
 
 def get_sgjp(lexeme):
-  return {'source': 'sgjp', 'id': lexeme.pk, 'entry': lexeme.entry}
+    return {'source': 'sgjp', 'id': lexeme.pk, 'entry': lexeme.entry}
+
 
 def create_lexeme(entry, part_of_speech, status, comment):
-  return {
-    'source': 'morfologik',
-    'entry': entry,
-    'part_of_speech': part_of_speech,
-    'status': status,
-    'comment': comment,
+    return {
+        'source': 'morfologik',
+        'entry': entry,
+        'part_of_speech': part_of_speech,
+        'status': status,
+        'comment': comment,
     }
 
+
 def create_lip(pattern, root, i, ic, part_of_speech):
-  output = {
-    'pattern': pattern if isinstance(pattern, basestring) else pattern.name,
-    'ind': i,
-    'ic': (ic, part_of_speech),
+    output = {
+        'pattern': pattern if isinstance(pattern, basestring) else pattern.name,
+        'ind': i,
+        'ic': (ic, part_of_speech),
     }
-  if root:
-    output['root'] = {'type': 'string', 'root': root}
-  else:
-    output['root'] = {'type': 'compute'}
-  return output
+    if root:
+        output['root'] = {'type': 'string', 'root': root}
+    else:
+        output['root'] = {'type': 'compute'}
+    return output
+
 
 alternative_gender = {
-  'p1': 'p3',
-  'p3': 'p1',
-  'm1': 'm2/m3',
-  'm': 'm1',
-  }
+    'p1': 'p3',
+    'p3': 'p1',
+    'm1': 'm2/m3',
+    'm': 'm1',
+}
 
 alternative_gender2 = {
-  'p1': 'p3',
-  'p3': 'p1',
-  'm1': 'm',
-  'm': 'm1',
-  }
+    'p1': 'p3',
+    'p3': 'p1',
+    'm1': 'm',
+    'm': 'm1',
+}
+
 
 def lexeme_creation(lc_sym, entry, ic, forms, type, patterns, fitting,
                     bad_patterns, included, other_result, tantum=None,
                     gender=None, negated=None, base_forms=None, derived=None):
-  status = 'desc' if type != 'none' else 'cand'
-  comments = [u'Z importu resztek']
-  copy_lips = False
-  if lc_sym == 'subst':
-    part_of_speech = 'subst' # co z osc i skrs?
-    if ic in ('m2', 'm3'):
-      sure = False
-      if type != 'none' and len(fitting) == 1:
-        for pattern, root in patterns:
-          for e in patterns[0][0].endings.filter(base_form_label__symbol='sg:gen'):
-            if not e.string.endswith('u'):
-              break
-          else:
-            continue
-          break
-        else: # wszystkie sg:gen kończą się na 'u'
-          ic = 'm3'
-          sure = True
-        for pattern, root in patterns:
-          if pattern.type.symbol == 'f':
-            ic = 'm2'
-            sure = True
-            break
-      if not sure:
+    status = 'desc' if type != 'none' else 'cand'
+    comments = [u'Z importu resztek']
+    copy_lips = False
+    if lc_sym == 'subst':
+        part_of_speech = 'subst' # co z osc i skrs?
+        if ic in ('m2', 'm3'):
+            sure = False
+            if type != 'none' and len(fitting) == 1:
+                for pattern, root in patterns:
+                    for e in patterns[0][0].endings.filter(
+                            base_form_label__symbol='sg:gen'):
+                        if not e.string.endswith('u'):
+                            break
+                    else:
+                        continue
+                    break
+                else: # wszystkie sg:gen kończą się na 'u'
+                    ic = 'm3'
+                    sure = True
+                for pattern, root in patterns:
+                    if pattern.type.symbol == 'f':
+                        ic = 'm2'
+                        sure = True
+                        break
+            if not sure:
+                status = 'cand'
+        if tantum is None and ic == 'm1':
+            for pattern, root in patterns:
+                nmo_endings = pattern.endings.filter(
+                    base_form_label__symbol='pl:nom')
+                for e in nmo_endings:
+                    nmo_form = root + e.string
+                    if nmo_form not in forms:
+                        comments.append(u'Dodano formę depr')
+                        break
+                else:
+                    continue
+                break
+        if ic == 'p1':
+            for pattern, root in patterns:
+                nmo_endings = pattern.endings.filter(
+                    base_form_label__symbol='pl:nom')
+                other_endings = pattern.endings.exclude(
+                    base_form_label__symbol='pl:nom')
+                other_strings = other_endings.values_list('string', flat=True)
+                nmo_strings = [e.string for e in nmo_endings if
+                               e.string not in other_strings]
+                nmo_forms = set(root + s for s in nmo_strings)
+                if nmo_forms & set(forms):
+                    comments.append(
+                        u'Usunięto formę depr: %s' % ', '.join(list(nmo_forms)))
+                    break
+        if tantum == 'sg' and type != 'none':
+            if type == 'match':
+                search_patterns = [pattern for pattern, root in fitting]
+                l = closest_lexeme_subst(entry, gender, search_patterns)
+            else:
+                included_patterns = [pattern for pattern, root in included]
+                l = closest_lexeme_subst(entry, gender, fitting,
+                                         included_patterns)
+            if l:
+                copy_lips = l.lexemeinflectionpattern_set.all()
+                #print l
+                comments.append(u'Automatycznie rozszerzone singulare tantum')
+            else:
+                if type == 'match':
+                    p = join(fitting)
+                else:
+                    p = join_many(fitting)
+                debug(entry,
+                      u'nie ma pasujących leksemów dla rozszerzenia sgtant '
+                      u'dla wzorów %s' % p)
+                comments.append(u'Nie udało się rozszerzyć singulare tantum')
+                #status = 'cand'
+                # dodać kwalifikator [po imporcie jednak]
+    if bad_patterns:
+        comments.append(u'Wzory z czarnej listy!')
         status = 'cand'
-    if tantum is None and ic == 'm1':
-      for pattern, root in patterns:
-        nmo_endings = pattern.endings.filter(base_form_label__symbol='pl:nom')
-        for e in nmo_endings:
-          nmo_form = root + e.string
-          if nmo_form not in forms:
-            comments.append(u'Dodano formę depr')
-            break
+    if len(fitting) > 1 or (type == 'none' and fitting):
+        status = 'cand'
+        if type == 'none':
+            comments.append(u'Zawierające wzory:')
+            for (pattern, root), bad_forms in fitting:
+                comments.append('%s: %s' % (pattern.name, ', '.join(bad_forms)))
+        elif type != 'many':
+            comments.append(u'Pasujące wzory: %s' % join(fitting))
         else:
-          continue
-        break
-    if ic == 'p1':
-      for pattern, root in patterns:
-        nmo_endings = pattern.endings.filter(base_form_label__symbol='pl:nom')
-        other_endings = pattern.endings.exclude(base_form_label__symbol='pl:nom')
-        other_strings = other_endings.values_list('string', flat=True)
-        nmo_strings = [e.string for e in nmo_endings if e.string not in other_strings]
-        nmo_forms = set(root + s for s in nmo_strings)
-        if nmo_forms & set(forms):
-          comments.append(
-            u'Usunięto formę depr: %s' % ', '.join(list(nmo_forms)))
-          break
-    if tantum == 'sg' and type != 'none':
-      if type == 'match':
-        search_patterns = [pattern for pattern, root in fitting]
-        l = closest_lexeme_subst(entry, gender, search_patterns)
-      else:
-        included_patterns = [pattern for pattern, root in included]
-        l = closest_lexeme_subst(entry, gender, fitting, included_patterns)
-      if l:
-        copy_lips = l.lexemeinflectionpattern_set.all()
-        #print l
-        comments.append(u'Automatycznie rozszerzone singulare tantum')
-      else:
-        if type == 'match':
-          p = join(fitting)
+            comments.append(u'Pasujące zestawy wzorów: %s' % join_many(fitting))
+    if other_result:
+        status = 'cand'
+        type2, patterns2, included2, including2 = other_result
+        comments.append(u'Alternatywny rodzaj: %s' % alternative_gender[gender])
+        if type2 == 'match':
+            comments.append(u'Pasujące wzory: %s' % join(patterns2))
+        elif type2 == 'many':
+            comments.append(
+                u'Pasujące zestawy wzorów: %s' % join_many(patterns2))
+            # hm?
+    if ic is None and type != 'none':
+        comments.append(u'Dopasowane wzory: %s' % join(patterns))
+        # zbieramy wzory do porównania [fuj, copypasta!]
+    if len(fitting) > 1:
+        if type == 'none':
+            all_patterns = set(p for p, b_f in fitting)
+        elif type != 'many':
+            all_patterns = set(fitting)
         else:
-          p = join_many(fitting)
-        debug(entry, u'nie ma pasujących leksemów dla rozszerzenia sgtant '
-                     u'dla wzorów %s' % p)
-        comments.append(u'Nie udało się rozszerzyć singulare tantum')
-        #status = 'cand'
-        # dodać kwalifikator [po imporcie jednak]
-  if bad_patterns:
-    comments.append(u'Wzory z czarnej listy!')
-    status = 'cand'
-  if len(fitting) > 1 or (type == 'none' and fitting):
-    status = 'cand'
-    if type == 'none':
-      comments.append(u'Zawierające wzory:')
-      for (pattern, root), bad_forms in fitting:
-        comments.append('%s: %s' % (pattern.name, ', '.join(bad_forms)))
-    elif type != 'many':
-      comments.append(u'Pasujące wzory: %s' % join(fitting))
-    else:
-      comments.append(u'Pasujące zestawy wzorów: %s' % join_many(fitting))
-  if other_result:
-    status = 'cand'
-    type2, patterns2, included2, including2 = other_result
-    comments.append(u'Alternatywny rodzaj: %s' % alternative_gender[gender])
-    if type2 == 'match':
-      comments.append(u'Pasujące wzory: %s' % join(patterns2))
-    elif type2 == 'many':
-      comments.append(u'Pasujące zestawy wzorów: %s' % join_many(patterns2))
-    # hm?
-  if ic is None and type != 'none':
-    comments.append(u'Dopasowane wzory: %s' % join(patterns))
-    # zbieramy wzory do porównania [fuj, copypasta!]
-  if len(fitting) > 1:
-    if type == 'none':
-      all_patterns = set(p for p, b_f in fitting)
-    elif type != 'many':
-      all_patterns = set(fitting)
-    else:
-      all_patterns = set()
-      for pattern_set in fitting:
-        all_patterns |= set(pattern_set)
-  if other_result and len(patterns2) > 1:
-    if type2 != 'many':
-      other_patterns = set(patterns2)
-    else:
-      other_patterns = set()
-      for pattern_set in patterns2:
-        other_patterns |= set(pattern_set)
-  comment = '\n'.join(comments)
-  output = {
-    'lexeme': create_lexeme(entry, part_of_speech, status, comment)
-  }
-  lips = []
-  if ic is not None:
-    if not copy_lips:
-      for i, (pattern, root) in enumerate(patterns):
-        lips.append(create_lip(pattern, root, i + 1, ic, part_of_speech))
-    else:
-      for lip in copy_lips:
-        ic = lip.inflection_characteristic.symbol
-        lips.append(
-          create_lip(lip.pattern, None, lip.index, ic, part_of_speech))
-  output['lips'] = lips
-  if lc_sym == 'adj' and negated:
-    output['negated'] = True
-  if lc_sym == 'v':
-    derived_data = []
-    for pos in derived:
-      # wypadałoby informować, jeśli wyszło puste... (?)
-      derived_data += create_derived(pos, base_forms, forms, patterns)
-    output['derived'] = derived_data
-  return output
+            all_patterns = set()
+            for pattern_set in fitting:
+                all_patterns |= set(pattern_set)
+    if other_result and len(patterns2) > 1:
+        if type2 != 'many':
+            other_patterns = set(patterns2)
+        else:
+            other_patterns = set()
+            for pattern_set in patterns2:
+                other_patterns |= set(pattern_set)
+    comment = '\n'.join(comments)
+    output = {
+        'lexeme': create_lexeme(entry, part_of_speech, status, comment)
+    }
+    lips = []
+    if ic is not None:
+        if not copy_lips:
+            for i, (pattern, root) in enumerate(patterns):
+                lips.append(
+                    create_lip(pattern, root, i + 1, ic, part_of_speech))
+        else:
+            for lip in copy_lips:
+                ic = lip.inflection_characteristic.symbol
+                lips.append(
+                    create_lip(lip.pattern, None, lip.index, ic,
+                               part_of_speech))
+    output['lips'] = lips
+    if lc_sym == 'adj' and negated:
+        output['negated'] = True
+    if lc_sym == 'v':
+        derived_data = []
+        for pos in derived:
+            # wypadałoby informować, jeśli wyszło puste... (?)
+            derived_data += create_derived(pos, base_forms, forms, patterns)
+        output['derived'] = derived_data
+    return output
+
 
 def process_forms(entry, forms, lc_sym, **extra):
-  lexical_class = LexicalClass.objects.get(symbol=lc_sym)
-  other_result = None
-  form_set = set(forms)
-  check = check_sgjp(lc_sym, entry, form_set, **extra)
-  if check and not DEBUG:
-    # dopisz leksem do słownika
-    data = {'lexeme': get_sgjp(check)}
-    # TODO negacja przymiotnika
-    print_data(data)
-  else:
-    if lc_sym == 'subst':
-      ic = extra['gender']
-    extra2 = dict(extra)
-    # jeśli rzeczownik męski lub pltant, to puszczamy więcej razy
-    if lc_sym == 'subst' and extra['gender'] in 'pm':
-      if extra['gender'] == 'm':
-        extra2['gender'] = 'm1'
-        type1, patterns1, included1, including1 = find_patterns(
-          lexical_class, entry, forms, **extra2)
-        extra2['gender'] = 'm'
-        type2, patterns2, included2, including2 = find_patterns(
-          lexical_class, entry, forms, **extra)
-      elif extra['gender'] == 'p':
-        extra2['gender'] = 'p1'
-        type1, patterns1, included1, including1 = find_patterns(
-          lexical_class, entry, forms, **extra2)
-        extra2['gender'] = 'p3'
-        type2, patterns2, included2, including2 = find_patterns(
-          lexical_class, entry, forms, **extra2)
-      if type1 != 'none' and type2 == 'none':
-        type, patterns, included, including = type1, patterns1, included1, including1
-        if extra['gender'] == 'm':
-          ic = 'm1'
-        else:
-          ic = 'p1'
-      elif type1 == 'none' and type2 != 'none':
-        type, patterns, included, including = type2, patterns2, included2, including2
-        if extra['gender'] == 'm':
-          ic = 'm'
+    lexical_class = LexicalClass.objects.get(symbol=lc_sym)
+    other_result = None
+    form_set = set(forms)
+    check = check_sgjp(lc_sym, entry, form_set, **extra)
+    if check and not DEBUG:
+        # dopisz leksem do słownika
+        data = {'lexeme': get_sgjp(check)}
+        # TODO negacja przymiotnika
+        print_data(data)
+    else:
+        if lc_sym == 'subst':
+            ic = extra['gender']
+        extra2 = dict(extra)
+        # jeśli rzeczownik męski lub pltant, to puszczamy więcej razy
+        if lc_sym == 'subst' and extra['gender'] in 'pm':
+            if extra['gender'] == 'm':
+                extra2['gender'] = 'm1'
+                type1, patterns1, included1, including1 = find_patterns(
+                    lexical_class, entry, forms, **extra2)
+                extra2['gender'] = 'm'
+                type2, patterns2, included2, including2 = find_patterns(
+                    lexical_class, entry, forms, **extra)
+            elif extra['gender'] == 'p':
+                extra2['gender'] = 'p1'
+                type1, patterns1, included1, including1 = find_patterns(
+                    lexical_class, entry, forms, **extra2)
+                extra2['gender'] = 'p3'
+                type2, patterns2, included2, including2 = find_patterns(
+                    lexical_class, entry, forms, **extra2)
+            if type1 != 'none' and type2 == 'none':
+                type, patterns, included, including = type1, patterns1, included1, including1
+                if extra['gender'] == 'm':
+                    ic = 'm1'
+                else:
+                    ic = 'p1'
+            elif type1 == 'none' and type2 != 'none':
+                type, patterns, included, including = type2, patterns2, included2, including2
+                if extra['gender'] == 'm':
+                    ic = 'm'
+                else:
+                    ic = 'p3'
+            elif type1 == type2 == 'none':
+                type = 'none'
+                patterns = []
+                included = list(set(included1) | set(included2))
+                including = list(set(including1) | set(including2))
+                # chyba warto coś ustawić
+                if extra['gender'] == 'm':
+                    ic = 'm'
+                else:
+                    ic = 'p3'
+            else: # z obu coś wyszło
+                type, patterns, included, including = type1, patterns1, included1, including1
+                if extra['gender'] == 'm':
+                    ic = 'm'
+                else:
+                    ic = 'p1'
+                other_result = (type2, patterns2, included2, including2)
+                if DEBUG:
+                    print u"dwie możliwości na rodzaj"
         else:
-          ic = 'p3'
-      elif type1 == type2 == 'none':
-        type = 'none'
-        patterns = []
-        included = list(set(included1) | set(included2))
-        including = list(set(including1) | set(including2))
-        # chyba warto coś ustawić
-        if extra['gender'] == 'm':
-          ic = 'm'
+            type, patterns, included, including = find_patterns(
+                lexical_class, entry, forms, **extra)
+        if type == 'none':
+            if lc_sym == 'subst' and not extra['tantum']:
+                extra['tantum'] = tantum_a_posteriori(
+                    form_set, [p for p, b_f in including])
+                if extra['tantum']:
+                    if extra['tantum'] == 'pl':
+                        extra['gender'] = 'p'
+                    return process_forms(entry, forms, lc_sym, **extra)
+
+        if lc_sym == 'subst':
+            extra2['gender'] = ic
+        type, patterns, included, including, bad_patterns = filter_patterns(
+            blacklist_filter, u'czarną listę', type, patterns, included,
+            including,
+            lexical_class, form_set, entry, **extra2)
+        if bad_patterns and other_result:
+            type, patterns, included, including = other_result
+            ic = extra2['gender'] = alternative_gender2[ic]
+            type, patterns, included, including, bad_patterns = filter_patterns(
+                blacklist_filter, u'czarną listę', type, patterns, included,
+                including,
+                lexical_class, form_set, entry, **extra2)
+            other_result = None
+        elif other_result:
+            type2, patterns2, included2, including2 = other_result
+            new_other_result = filter_patterns(
+                blacklist_filter, u'czarną listę', type2, patterns2, included2,
+                including2, lexical_class, form_set, entry, **extra2)
+            if not new_other_result[4]:
+                other_result = new_other_result[:4]
+            else:
+                other_result = None
+
+        # wzory się już nie zmienią od tego miejsca
+        if type == 'many':
+            # albo patterns[0]...
+            all_patterns = [p for pattern_set in patterns for p in pattern_set]
         else:
-          ic = 'p3'
-      else: # z obu coś wyszło
-        type, patterns, included, including = type1, patterns1, included1, including1
-        if extra['gender'] == 'm':
-          ic = 'm'
+            all_patterns = patterns
+        if type != 'none':
+            # brzydko...
+            if lexical_class.symbol == 'subst':
+                extra['ic'] = ic
+                del extra['ic']
         else:
-          ic = 'p1'
-        other_result = (type2, patterns2, included2, including2)
-        if DEBUG:
-          print u"dwie możliwości na rodzaj"
-    else:
-      type, patterns, included, including = find_patterns(
-        lexical_class, entry, forms, **extra)
-    if type == 'none':
-      if lc_sym == 'subst' and not extra['tantum']:
-        extra['tantum'] = tantum_a_posteriori(
-          form_set, [p for p, b_f in including])
-        if extra['tantum']:
-          if extra['tantum'] == 'pl':
-            extra['gender'] = 'p'
-          return process_forms(entry, forms, lc_sym, **extra)
+            ic = None
+        if lc_sym == 'subst':
+            # poprawka dla m2/m3
+            if ic in ('m2', 'm3') and patterns and not bad_patterns:
+                new_ic = ''
+                for pattern, root in all_patterns:
+                    for ic2 in ('m2', 'm3'):
+                        # jeśli wszystkie użycia tego wzoru są przy ic2
+                        if not pattern.lexemeinflectionpattern_set.exclude(
+                                inflection_characteristic__symbol=ic2).filter(
+                                lexeme__pk__in=sgjp).exists():
+                            if new_ic == '':
+                                new_ic = ic2
+                            elif new_ic != ic2:
+                                new_ic = None
+                if new_ic:
+                    ic = new_ic
+
+        if type == 'none':
+            debug(entry, u'zawiera się w %s' % join(p for p, b_f in including))
+            chosen = []
+            fitting = including
+        elif type == 'match':
+            patterns.sort(key=lambda p: p[0].name)
+            fitting = patterns
+            chosen = patterns[:1]
+        elif type == 'many':
+            chosen = patterns[0]
+            if DEBUG:
+                print u'zestawy wielu wzorów: %s' % join_many(patterns)
+            fitting = patterns
+        if not DEBUG:
+            data = lexeme_creation(
+                lc_sym, entry, ic, forms, type, chosen, fitting, bad_patterns,
+                included,
+                other_result, **extra2)
+            print_data(data)
 
-    if lc_sym == 'subst':
-      extra2['gender'] = ic
-    type, patterns, included, including, bad_patterns = filter_patterns(
-      blacklist_filter, u'czarną listę', type, patterns, included, including,
-      lexical_class, form_set, entry, **extra2)
-    if bad_patterns and other_result:
-      type, patterns, included, including = other_result
-      ic = extra2['gender'] = alternative_gender2[ic]
-      type, patterns, included, including, bad_patterns = filter_patterns(
-        blacklist_filter, u'czarną listę', type, patterns, included, including,
-        lexical_class, form_set, entry, **extra2)
-      other_result = None
-    elif other_result:
-      type2, patterns2, included2, including2 = other_result
-      new_other_result = filter_patterns(
-        blacklist_filter, u'czarną listę', type2, patterns2, included2,
-        including2, lexical_class, form_set, entry, **extra2)
-      if not new_other_result[4]:
-        other_result = new_other_result[:4]
-      else:
-        other_result = None
-
-    # wzory się już nie zmienią od tego miejsca
-    if type == 'many':
-      # albo patterns[0]...
-      all_patterns = [p for pattern_set in patterns for p in pattern_set]
-    else:
-      all_patterns = patterns
-    if type != 'none':
-      # brzydko...
-      if lexical_class.symbol == 'subst':
-        extra['ic'] = ic
-        del extra['ic']
-    else:
-      ic = None
-    if lc_sym == 'subst':
-      # poprawka dla m2/m3
-      if ic in ('m2', 'm3') and patterns and not bad_patterns:
-        new_ic = ''
-        for pattern, root in all_patterns:
-          for ic2 in ('m2', 'm3'):
-            # jeśli wszystkie użycia tego wzoru są przy ic2
-            if not pattern.lexemeinflectionpattern_set.exclude(
-              inflection_characteristic__symbol=ic2).filter(
-              lexeme__pk__in=sgjp).exists():
-              if new_ic == '':
-                new_ic = ic2
-              elif new_ic != ic2:
-                new_ic = None
-        if new_ic:
-          ic = new_ic
-
-    if type == 'none':
-      debug(entry, u'zawiera się w %s' % join(p for p, b_f in including))
-      chosen = []
-      fitting = including
-    elif type == 'match':
-      patterns.sort(key=lambda p: p[0].name)
-      fitting = patterns
-      chosen = patterns[:1]
-    elif type == 'many':
-      chosen = patterns[0]
-      if DEBUG:
-        print u'zestawy wielu wzorów: %s' % join_many(patterns)
-      fitting = patterns
-    if not DEBUG:
-      data = lexeme_creation(
-        lc_sym, entry, ic, forms, type, chosen, fitting, bad_patterns, included,
-        other_result, **extra2)
-      print_data(data)
 
 def get_pos_ndm(tag):
-  if tag[0] == 'adv':
-    return 'adv' if tag[-1] != 'comp' else 'advcom'
-  elif tag[0] == 'xxx':
-    return 'burk'
-  else:
-    return tag[0]
+    if tag[0] == 'adv':
+        return 'adv' if tag[-1] != 'comp' else 'advcom'
+    elif tag[0] == 'xxx':
+        return 'burk'
+    else:
+        return tag[0]
+
 
 def print_data(data):
-  print json.dumps(data)
+    print json.dumps(data)
+
 
 def import_resztki(input_file):
-  for line in input_file:
-    entry, rest = line.decode('utf-8').strip().replace("'", u'’').split(':')
-    pos, ic, rest = rest.split(';')
-    if ic in ('n2/m3', 'n2/m3/m2', 'm3/m2'):
-      ic = 'm3'
-    elif ic == 'p3/p2':
-      ic = 'p3'
-    elif ic in ('f/m3', 'f/n2'):
-      ic = 'f'
-    forms = rest.split(',')
-    if entry not in forms:
-      forms = [entry] + forms
-    if ic[0] == 'p':
-      tantum = 'pl'
-    else:
-      tantum = None
-    if entry.endswith(u'stwo') and ic == 'p1':
-      # zbędne formy mnogie
-      root = entry[:-1]
-      for suffix in ('', 'ami', 'ach', 'om'):
-        forms.remove(root + suffix)
-    process_forms(entry, forms, pos, gender=ic, tantum=tantum)
\ No newline at end of file
+    for line in input_file:
+        entry, rest = line.decode('utf-8').strip().replace("'", u'’').split(':')
+        pos, ic, rest = rest.split(';')
+        if ic in ('n2/m3', 'n2/m3/m2', 'm3/m2'):
+            ic = 'm3'
+        elif ic == 'p3/p2':
+            ic = 'p3'
+        elif ic in ('f/m3', 'f/n2'):
+            ic = 'f'
+        forms = rest.split(',')
+        if entry not in forms:
+            forms = [entry] + forms
+        if ic[0] == 'p':
+            tantum = 'pl'
+        else:
+            tantum = None
+        if entry.endswith(u'stwo') and ic == 'p1':
+            # zbędne formy mnogie
+            root = entry[:-1]
+            for suffix in ('', 'ami', 'ach', 'om'):
+                forms.remove(root + suffix)
+        process_forms(entry, forms, pos, gender=ic, tantum=tantum)
\ No newline at end of file
diff --git a/dictionary/management/commands/import_sejfek.py b/dictionary/management/commands/import_sejfek.py
index 0517568..cc08fba 100644
--- a/dictionary/management/commands/import_sejfek.py
+++ b/dictionary/management/commands/import_sejfek.py
@@ -3,348 +3,378 @@
 from django.core.management.base import BaseCommand
 from common.util import debug, suffixes, cut_end
 from dictionary.models import Lexeme, Pattern, InflectionCharacteristic, \
-  Ending, BaseFormLabel
+    Ending, BaseFormLabel
 from dictionary.management.commands.import_morfologik import create_lexeme, \
-  create_lip, print_data, find_minimal_sets, blacklist_filter, join_many, \
-  join, get_sgjp
+    create_lip, print_data, find_minimal_sets, blacklist_filter, join_many, \
+    join, get_sgjp
+
 
 class Command(BaseCommand):
-  args = '<input file name>'
-  help = 'importuje leksemy z KIPI 1.0'
+    args = '<input file name>'
+    help = 'importuje leksemy z KIPI 1.0'
+
+    def handle(self, filename, **options):
+        import_sejfek(open(filename))
 
-  def handle(self, filename, **options):
-    import_sejfek(open(filename))
 
 DEBUG = False
 
+
 def inflection_characteristic(forms, pos):
-  # w SEJFKU jest tylko subst i adj
-  tag = forms[0][1]
-  if pos == 'subst':
-    if 'depr' in tag or tag.endswith('m1'):
-      ic = 'm1'
-    else:
-      ic = tag.rsplit(':', 1)[1]
-      # syf
-      if ic == 'n1.n2':
-        ic = 'n2'
-      if '.' in ic:
-        ic = 'm3'
-  elif pos == 'adj':
-    # formy 3+ tu nie występują
-    if any(tag == 'adja' for form, tag in forms):
-      ic = ''
-    else:
-      ic = '0-'
-  return ic
+    # w SEJFKU jest tylko subst i adj
+    tag = forms[0][1]
+    if pos == 'subst':
+        if 'depr' in tag or tag.endswith('m1'):
+            ic = 'm1'
+        else:
+            ic = tag.rsplit(':', 1)[1]
+            # syf
+            if ic == 'n1.n2':
+                ic = 'n2'
+            if '.' in ic:
+                ic = 'm3'
+    elif pos == 'adj':
+        # formy 3+ tu nie występują
+        if any(tag == 'adja' for form, tag in forms):
+            ic = ''
+        else:
+            ic = '0-'
+    return ic
 
 # COPYPASTA HEAVEN
 def get_basic_endings(lexical_class, ic):
-  return Ending.objects.filter(
-    base_form_label=ic.basic_form_label,
-    pattern__type__lexical_class__symbol=lexical_class)
+    return Ending.objects.filter(
+        base_form_label=ic.basic_form_label,
+        pattern__type__lexical_class__symbol=lexical_class)
+
 
 basic_form_endings_dict = {}
 for pos in ('adj', 'subst'):
-  for ic in InflectionCharacteristic.objects.filter(part_of_speech__symbol=pos):
-    basic_form_endings_dict[(pos, ic.symbol)] = get_basic_endings(pos, ic)
+    for ic in InflectionCharacteristic.objects.filter(
+            part_of_speech__symbol=pos):
+        basic_form_endings_dict[(pos, ic.symbol)] = get_basic_endings(pos, ic)
 
 sure_bfls_sg = tuple(
-  BaseFormLabel.objects.filter(
-    symbol__in=['sg:dat', 'sg:gen', 'sg:inst']).values_list('pk', flat=True))
+    BaseFormLabel.objects.filter(
+        symbol__in=['sg:dat', 'sg:gen', 'sg:inst']).values_list('pk',
+                                                                flat=True))
 sure_bfls_pl = tuple(
-  BaseFormLabel.objects.filter(
-    symbol__in=['pl:dat', 'pl:inst', 'pl:loc']).values_list('pk', flat=True))
+    BaseFormLabel.objects.filter(
+        symbol__in=['pl:dat', 'pl:inst', 'pl:loc']).values_list('pk',
+                                                                flat=True))
+
 
 def basic_form_endings(lexical_class, ic, basic_form, form_set):
-  if lexical_class != 'subst':
-    return basic_form_endings_dict[(lexical_class, ic)].filter(
-      string__in=suffixes(basic_form))
-  else:
-    # karkołomne, ale trochę przyśpiesza
-    endings = basic_form_endings_dict[(lexical_class, ic)]
-    new_endings = Ending.objects.none()
-    for suf in suffixes(basic_form):
-      root = cut_end(basic_form, suf)
-      n = len(root)
-      ending_strings = tuple(
-        form[n:] for form in form_set if form.startswith(root))
-      endings_part = endings.filter(string=suf)
-      pattern_ids = endings_part.values_list('pattern', flat=True)
-      patterns = Pattern.objects.filter(pk__in=pattern_ids).extra(
-        where=["(id = '0000' or not exists "
-               "(select id from zakonczenia where w_id = wzory.id "
-               "and zak not in %s and efobaz in %s) or not exists "
-               "(select id from zakonczenia where w_id = wzory.id "
-               "and zak not in %s and efobaz in %s))"],
-        params=[ending_strings, sure_bfls_sg, ending_strings, sure_bfls_pl])
-      new_endings = new_endings | endings_part.filter(pattern__in=patterns)
-    return new_endings
+    if lexical_class != 'subst':
+        return basic_form_endings_dict[(lexical_class, ic)].filter(
+            string__in=suffixes(basic_form))
+    else:
+        # karkołomne, ale trochę przyśpiesza
+        endings = basic_form_endings_dict[(lexical_class, ic)]
+        new_endings = Ending.objects.none()
+        for suf in suffixes(basic_form):
+            root = cut_end(basic_form, suf)
+            n = len(root)
+            ending_strings = tuple(
+                form[n:] for form in form_set if form.startswith(root))
+            endings_part = endings.filter(string=suf)
+            pattern_ids = endings_part.values_list('pattern', flat=True)
+            patterns = Pattern.objects.filter(pk__in=pattern_ids).extra(
+                where=["(id = '0000' or not exists "
+                       "(select id from zakonczenia where w_id = wzory.id "
+                       "and zak not in %s and efobaz in %s) or not exists "
+                       "(select id from zakonczenia where w_id = wzory.id "
+                       "and zak not in %s and efobaz in %s))"],
+                params=[ending_strings, sure_bfls_sg, ending_strings,
+                        sure_bfls_pl])
+            new_endings = new_endings | endings_part.filter(
+                pattern__in=patterns)
+        return new_endings
+
 
 memoized_pattern_ics = {}
 
+
 def bad_pattern_subst(pattern, ic):
-  if (pattern, ic) in memoized_pattern_ics:
-    return memoized_pattern_ics[(pattern, ic)]
-  if not pattern.lexemeinflectionpattern_set.filter(
-       inflection_characteristic__symbol=ic).exclude(lexeme__status='cand'):
-    ret = True
-  elif pattern.type.symbol in 'mn' and ic == 'f':
-    ret = True
-  elif pattern.type.symbol in 'fm' and ic[0] == 'n':
-    ret = True
-  else:
-    ret = False
-  memoized_pattern_ics[(pattern, ic)] = ret
-  return ret
+    if (pattern, ic) in memoized_pattern_ics:
+        return memoized_pattern_ics[(pattern, ic)]
+    if not pattern.lexemeinflectionpattern_set.filter(
+            inflection_characteristic__symbol=ic).exclude(
+            lexeme__status='cand'):
+        ret = True
+    elif pattern.type.symbol in 'mn' and ic == 'f':
+        ret = True
+    elif pattern.type.symbol in 'fm' and ic[0] == 'n':
+        ret = True
+    else:
+        ret = False
+    memoized_pattern_ics[(pattern, ic)] = ret
+    return ret
+
 
 memoized_good_endings = {}
 
+
 def good_ending_set_subst(pattern, ic, root):
-  if (pattern, ic) in memoized_good_endings:
-    good_endings = memoized_good_endings[(pattern, ic)]
+    if (pattern, ic) in memoized_good_endings:
+        good_endings = memoized_good_endings[(pattern, ic)]
+        return set(root + e for e in good_endings)
+    endings = pattern.endings
+    if ic not in ('m1', 'p1'):
+        endings = endings.exclude(base_form_label__symbol='pl:nom:mo')
+    if ic[0] == 'p':
+        endings = endings.filter(base_form_label__symbol__startswith='pl')
+    else:
+        for g in list(set('mfn') - set(ic[0])):
+            endings = endings.exclude(
+                base_form_label__symbol__startswith='pl:gen:' + g)
+    if ic == 'p3':
+        if pattern.type.symbol == 'f':
+            endings = endings.exclude(base_form_label__symbol='pl:gen:m')
+        elif pattern.type.symbol == 'n':
+            endings = endings.exclude(base_form_label__symbol='pl:gen:n')
+    good_endings = list(endings.values_list('string', flat=True))
+    memoized_good_endings[(pattern, ic)] = good_endings
     return set(root + e for e in good_endings)
-  endings = pattern.endings
-  if ic not in ('m1', 'p1'):
-    endings = endings.exclude(base_form_label__symbol='pl:nom:mo')
-  if ic[0] == 'p':
-    endings = endings.filter(base_form_label__symbol__startswith='pl')
-  else:
-    for g in list(set('mfn') - set(ic[0])):
-      endings = endings.exclude(
-        base_form_label__symbol__startswith='pl:gen:' + g)
-  if ic == 'p3':
-    if pattern.type.symbol == 'f':
-      endings = endings.exclude(base_form_label__symbol='pl:gen:m')
-    elif pattern.type.symbol == 'n':
-      endings = endings.exclude(base_form_label__symbol='pl:gen:n')
-  good_endings = list(endings.values_list('string', flat=True))
-  memoized_good_endings[(pattern, ic)] = good_endings
-  return set(root + e for e in good_endings)
+
 
 def good_ending_set(lexical_class, ic, pattern, root=''):
-  if lexical_class != 'subst':
-    return pattern.ending_set(root)
-  else:
-    return good_ending_set_subst(pattern, ic, root)
+    if lexical_class != 'subst':
+        return pattern.ending_set(root)
+    else:
+        return good_ending_set_subst(pattern, ic, root)
+
 
 def relevant_subst(ending, ic):
-  bfl = ending.base_form_label.symbol
-  tag = bfl.split(':')
-  type = ending.pattern.type.symbol
-  return (not (ic in ('m1', 'p1') and bfl == 'pl:nom') and
-          not (len(tag) >= 3 and ic[0] != 'p' and
-               tag[2][0] != ic[0]) and
-          not (ic[0] == 'p' and tag[0] != 'pl') and
-          not (ic == 'p3' and bfl.startswith('pl:gen:') and (
+    bfl = ending.base_form_label.symbol
+    tag = bfl.split(':')
+    type = ending.pattern.type.symbol
+    return (not (ic in ('m1', 'p1') and bfl == 'pl:nom') and
+            not (len(tag) >= 3 and ic[0] != 'p' and
+                 tag[2][0] != ic[0]) and
+            not (ic[0] == 'p' and tag[0] != 'pl') and
+            not (ic == 'p3' and bfl.startswith('pl:gen:') and (
                 (type == 'n' and tag[2] == 'n') or
                 (type == 'f' and tag[2] == 'm')
-              )) and
-          not (ic not in ('m1', 'p1') and bfl == 'pl:nom:mo'))
+            )) and
+            not (ic not in ('m1', 'p1') and bfl == 'pl:nom:mo'))
+
 
 def relevant_adj(ending):
-  tag = ending.base_form_label.symbol
-  return tag not in ('0', '3+')
+    tag = ending.base_form_label.symbol
+    return tag not in ('0', '3+')
+
 
 def relevant(lexical_class, ending, ic):
-  if lexical_class == 'subst':
-    return relevant_subst(ending, ic)
-  elif lexical_class == 'adj':
-    return relevant_adj(ending)
+    if lexical_class == 'subst':
+        return relevant_subst(ending, ic)
+    elif lexical_class == 'adj':
+        return relevant_adj(ending)
+
 
 def find_patterns(basic_form, pos, ic, forms):
-  patterns = Pattern.objects.filter(type__lexical_class__symbol=pos)
-  # znaleźć wszystkie zawarte i zawierające wzory
-  form_set = set(form for form, tag in forms)
-  ending_sets = {}
-  included_patterns = set()
-  including_patterns = set()
-  matching_patterns = set()
-  for basic_ending in basic_form_endings(pos, ic, basic_form, form_set):
-    pattern = basic_ending.pattern
-    if pos == 'subst' and bad_pattern_subst(pattern, ic):
-      #print 'odpadł:', pattern
-      continue # olewamy komentarze że formy odrzucone przez charfle?
-    root = basic_form[:len(basic_form) - len(basic_ending.string)]
-    ending_sets[pattern] = good_ending_set(pos, ic, pattern, root)
-    including = form_set.issubset(ending_sets[pattern])
-    bad_forms = set()
-    for ending in pattern.endings.all():
-      if relevant(pos, ending, ic):
-        if root + ending.string not in form_set:
-          bfl = ending.base_form_label.symbol
-          #print pattern.name, root, ending.string, bfl
-          bad_forms.add(root + ending.string)
-    if not bad_forms:
-      included_patterns.add((pattern, root))
-      if including:
-        matching_patterns.add((pattern, root))
-    elif including:
-      including_patterns.add(((pattern, root), tuple(bad_forms)))
-
-  # nie wiem, czy to potrzebne, ale na wszelki wypadek
-  included_patterns = list(included_patterns)
-  including_patterns = list(including_patterns)
-  matching_patterns = list(matching_patterns)
-  if len(matching_patterns) > 0:
-    if DEBUG:
-      print u'dokładne wzory: %s' % join(matching_patterns)
-    return 'match', matching_patterns, included_patterns, including_patterns
-  # nic nie pasuje albo trzeba wybrać wiele wzorów
-  if DEBUG and len(including_patterns) > 0:
-    print u'zawierające: %s' % join(p for p, b_f in including_patterns)
-  if DEBUG and len(included_patterns) > 0:
-    print u'zawarte: %s' % join(included_patterns)
-  return find_many_patterns(
-    pos, ic, form_set, basic_form, included_patterns, ending_sets) + (
-    included_patterns, including_patterns)
+    patterns = Pattern.objects.filter(type__lexical_class__symbol=pos)
+    # znaleźć wszystkie zawarte i zawierające wzory
+    form_set = set(form for form, tag in forms)
+    ending_sets = {}
+    included_patterns = set()
+    including_patterns = set()
+    matching_patterns = set()
+    for basic_ending in basic_form_endings(pos, ic, basic_form, form_set):
+        pattern = basic_ending.pattern
+        if pos == 'subst' and bad_pattern_subst(pattern, ic):
+            #print 'odpadł:', pattern
+            continue # olewamy komentarze że formy odrzucone przez charfle?
+        root = basic_form[:len(basic_form) - len(basic_ending.string)]
+        ending_sets[pattern] = good_ending_set(pos, ic, pattern, root)
+        including = form_set.issubset(ending_sets[pattern])
+        bad_forms = set()
+        for ending in pattern.endings.all():
+            if relevant(pos, ending, ic):
+                if root + ending.string not in form_set:
+                    bfl = ending.base_form_label.symbol
+                    #print pattern.name, root, ending.string, bfl
+                    bad_forms.add(root + ending.string)
+        if not bad_forms:
+            included_patterns.add((pattern, root))
+            if including:
+                matching_patterns.add((pattern, root))
+        elif including:
+            including_patterns.add(((pattern, root), tuple(bad_forms)))
+
+    # nie wiem, czy to potrzebne, ale na wszelki wypadek
+    included_patterns = list(included_patterns)
+    including_patterns = list(including_patterns)
+    matching_patterns = list(matching_patterns)
+    if len(matching_patterns) > 0:
+        if DEBUG:
+            print u'dokładne wzory: %s' % join(matching_patterns)
+        return 'match', matching_patterns, included_patterns, including_patterns
+        # nic nie pasuje albo trzeba wybrać wiele wzorów
+    if DEBUG and len(including_patterns) > 0:
+        print u'zawierające: %s' % join(p for p, b_f in including_patterns)
+    if DEBUG and len(included_patterns) > 0:
+        print u'zawarte: %s' % join(included_patterns)
+    return find_many_patterns(
+        pos, ic, form_set, basic_form, included_patterns, ending_sets) + (
+               included_patterns, including_patterns)
+
 
 def find_many_patterns(pos, ic, form_set, basic_form, included_patterns,
                        ending_sets):
-  necessary_patterns = set()
-  missing_form = None
-  for form in form_set:
-    having = []
-    for pattern, root in included_patterns:
-      if form in ending_sets[pattern]:
-        having.append((pattern, root))
-    if len(having) == 1:
-      necessary_patterns.add(having[0])
-    if having == []:
-      missing_form = form
-      break
-  if missing_form:
-    if DEBUG:
-      print u"brak formy: %s" % missing_form
-    return 'none', []
-  covered_forms = set()
-  for pattern, root in necessary_patterns:
-    covered_forms |= ending_sets[pattern]
-  if form_set.issubset(covered_forms):
-    if DEBUG:
-      print u"pokryte koniecznymi wzorami: %s" % join(necessary_patterns)
-    return 'many', [list(necessary_patterns)]
-  else:
-    #for pattern, root in included_patterns:
-    #  print pattern, ending_sets[pattern]
-    minimal_sets = find_minimal_sets(
-      form_set, covered_forms, necessary_patterns, included_patterns,
-      ending_sets)
-    return 'many', minimal_sets
+    necessary_patterns = set()
+    missing_form = None
+    for form in form_set:
+        having = []
+        for pattern, root in included_patterns:
+            if form in ending_sets[pattern]:
+                having.append((pattern, root))
+        if len(having) == 1:
+            necessary_patterns.add(having[0])
+        if having == []:
+            missing_form = form
+            break
+    if missing_form:
+        if DEBUG:
+            print u"brak formy: %s" % missing_form
+        return 'none', []
+    covered_forms = set()
+    for pattern, root in necessary_patterns:
+        covered_forms |= ending_sets[pattern]
+    if form_set.issubset(covered_forms):
+        if DEBUG:
+            print u"pokryte koniecznymi wzorami: %s" % join(necessary_patterns)
+        return 'many', [list(necessary_patterns)]
+    else:
+        #for pattern, root in included_patterns:
+        #  print pattern, ending_sets[pattern]
+        minimal_sets = find_minimal_sets(
+            form_set, covered_forms, necessary_patterns, included_patterns,
+            ending_sets)
+        return 'many', minimal_sets
+
 
 def filter_patterns(filter, action_name, type, patterns, included, including,
                     lexical_class, form_set, entry, ic):
-  old_patterns = patterns
-  old_included = included
-  bad_patterns = False
-  if type == 'many':
-    if any(pattern_set != filter(pattern_set) for pattern_set in patterns):
-      included = filter(included)
-      ending_sets = {}
-      for pattern, root in included:
-        ending_sets[pattern] = good_ending_set(lexical_class, ic, pattern, root)
-      type, patterns = find_many_patterns(
-        lexical_class, ic, form_set, entry, included, ending_sets)
-      if type != 'many':
-        debug(entry, u'mnogie dopasowanie zepsute przez %s (%s)' %
-                     (action_name, join_many(old_patterns)))
-        type = 'many'
-        patterns, included = old_patterns, old_included
-        bad_patterns = True
-  elif type == 'none':
-    including_dict = dict(including)
-    including = [(key, including_dict[key]) for key in filter(including_dict)]
-  else: # type == 'match'
-    patterns = filter(patterns)
-    including_dict = dict(including)
-    including = [(key, including_dict[key]) for key in filter(including_dict)]
-    included = filter(included)
-    if old_patterns and not patterns:
-      ending_sets = {}
-      for pattern, root in included:
-        ending_sets[pattern] = good_ending_set(lexical_class, ic, pattern, root)
-      type, patterns = find_many_patterns(
-        lexical_class, ic, form_set, entry, included, ending_sets)
-      if type == 'none':
-        debug(entry, u'znikły wzory przez %s (%s)' %
-                     (action_name, join(old_patterns)))
-        type = 'match'
-        patterns = old_patterns
-        bad_patterns = True
-  return type, patterns, included, including, bad_patterns
+    old_patterns = patterns
+    old_included = included
+    bad_patterns = False
+    if type == 'many':
+        if any(pattern_set != filter(pattern_set) for pattern_set in patterns):
+            included = filter(included)
+            ending_sets = {}
+            for pattern, root in included:
+                ending_sets[pattern] = good_ending_set(lexical_class, ic,
+                                                       pattern, root)
+            type, patterns = find_many_patterns(
+                lexical_class, ic, form_set, entry, included, ending_sets)
+            if type != 'many':
+                debug(entry, u'mnogie dopasowanie zepsute przez %s (%s)' %
+                             (action_name, join_many(old_patterns)))
+                type = 'many'
+                patterns, included = old_patterns, old_included
+                bad_patterns = True
+    elif type == 'none':
+        including_dict = dict(including)
+        including = [(key, including_dict[key]) for key in
+                     filter(including_dict)]
+    else: # type == 'match'
+        patterns = filter(patterns)
+        including_dict = dict(including)
+        including = [(key, including_dict[key]) for key in
+                     filter(including_dict)]
+        included = filter(included)
+        if old_patterns and not patterns:
+            ending_sets = {}
+            for pattern, root in included:
+                ending_sets[pattern] = good_ending_set(lexical_class, ic,
+                                                       pattern, root)
+            type, patterns = find_many_patterns(
+                lexical_class, ic, form_set, entry, included, ending_sets)
+            if type == 'none':
+                debug(entry, u'znikły wzory przez %s (%s)' %
+                             (action_name, join(old_patterns)))
+                type = 'match'
+                patterns = old_patterns
+                bad_patterns = True
+    return type, patterns, included, including, bad_patterns
+
 
 def process_forms(forms, base, pos):
-  old = Lexeme.objects.filter(entry=base)
-  if old:
-    if old.count() > 1:
-      debug(base, u'więcej niż jedna wersja w Kuźni')
-    else:
-      print_data({'lexeme': get_sgjp(old.get())})
-    return
-  ic = inflection_characteristic(forms, pos)
-  form_set = set(form for form, tag in forms)
-  type, patterns, included, including = find_patterns(base, pos, ic, forms)
-  type, patterns, included, including, bad_patterns = filter_patterns(
-    blacklist_filter, u'czarną listę', type, patterns, included, including,
-    pos, form_set, base, ic)
-  # wzory się już nie zmienią od tego miejsca
-
-  if type == 'none':
-    debug(base, u'zawiera się w %s' % join(p for p, b_f in including))
-    chosen = []
-    fitting = including
-  elif type == 'match':
-    patterns.sort(key=lambda p: p[0].name)
-    fitting = patterns
-    chosen = patterns[:1]
-  else: # type == 'many'
-    chosen = patterns[0]
-    if DEBUG:
-      print u'zestawy wielu wzorów: %s' % join_many(patterns)
-    fitting = patterns
-
-  if not DEBUG:
-    comments = []
-    if type != 'match' or len(fitting) > 1:
-      status = 'cand'
-    else:
-      status = 'desc'
-    if bad_patterns:
-      comments.append(u'Wzory z czarnej listy!')
-      status = 'cand'
-    if len(fitting) > 1 or (type == 'none' and fitting):
-      if type == 'none':
-        comments.append(u'Zawierające wzory:')
-        for (pattern, root), bad_forms in fitting:
-          comments.append('%s: %s' % (pattern.name, ', '.join(bad_forms)))
-      elif type != 'many':
-        comments.append(u'Pasujące wzory: %s' % join(fitting))
-      else:
-        comments.append(u'Pasujące zestawy wzorów: %s' % join_many(fitting))
-    comment = '\n'.join(comments)
-    lips = []
-    for i, pattern in enumerate(chosen):
-      lips.append(create_lip(pattern[0], pattern[1], i + 1, ic, pos))
-    lexeme_data = create_lexeme(base, 1, pos, status, comment)
-    data = {
-      'lexeme': lexeme_data,
-      'lips': lips,
-    }
-    print_data(data)
+    old = Lexeme.objects.filter(entry=base)
+    if old:
+        if old.count() > 1:
+            debug(base, u'więcej niż jedna wersja w Kuźni')
+        else:
+            print_data({'lexeme': get_sgjp(old.get())})
+        return
+    ic = inflection_characteristic(forms, pos)
+    form_set = set(form for form, tag in forms)
+    type, patterns, included, including = find_patterns(base, pos, ic, forms)
+    type, patterns, included, including, bad_patterns = filter_patterns(
+        blacklist_filter, u'czarną listę', type, patterns, included, including,
+        pos, form_set, base, ic)
+    # wzory się już nie zmienią od tego miejsca
+
+    if type == 'none':
+        debug(base, u'zawiera się w %s' % join(p for p, b_f in including))
+        chosen = []
+        fitting = including
+    elif type == 'match':
+        patterns.sort(key=lambda p: p[0].name)
+        fitting = patterns
+        chosen = patterns[:1]
+    else: # type == 'many'
+        chosen = patterns[0]
+        if DEBUG:
+            print u'zestawy wielu wzorów: %s' % join_many(patterns)
+        fitting = patterns
+
+    if not DEBUG:
+        comments = []
+        if type != 'match' or len(fitting) > 1:
+            status = 'cand'
+        else:
+            status = 'desc'
+        if bad_patterns:
+            comments.append(u'Wzory z czarnej listy!')
+            status = 'cand'
+        if len(fitting) > 1 or (type == 'none' and fitting):
+            if type == 'none':
+                comments.append(u'Zawierające wzory:')
+                for (pattern, root), bad_forms in fitting:
+                    comments.append(
+                        '%s: %s' % (pattern.name, ', '.join(bad_forms)))
+            elif type != 'many':
+                comments.append(u'Pasujące wzory: %s' % join(fitting))
+            else:
+                comments.append(
+                    u'Pasujące zestawy wzorów: %s' % join_many(fitting))
+        comment = '\n'.join(comments)
+        lips = []
+        for i, pattern in enumerate(chosen):
+            lips.append(create_lip(pattern[0], pattern[1], i + 1, ic, pos))
+        lexeme_data = create_lexeme(base, 1, pos, status, comment)
+        data = {
+            'lexeme': lexeme_data,
+            'lips': lips,
+        }
+        print_data(data)
+
 
 def import_sejfek(input_file):
-  forms = []
-  for line in input_file:
-    data = line.strip().decode('utf-8').replace("'", u'’').split(' ')
-    if len(data) > 1:
-      form, _base, tag = data
-      pos = 'subst' if tag.split(':', 1)[0] == 'subst' else 'adj'
-      if not forms:
-        base = form
-      forms.append((form, tag))
-    else:
-      if forms:
-        process_forms(forms, base, pos)
-      forms = []
-      patterns = set()
-  process_forms(forms, base, pos)
+    forms = []
+    for line in input_file:
+        data = line.strip().decode('utf-8').replace("'", u'’').split(' ')
+        if len(data) > 1:
+            form, _base, tag = data
+            pos = 'subst' if tag.split(':', 1)[0] == 'subst' else 'adj'
+            if not forms:
+                base = form
+            forms.append((form, tag))
+        else:
+            if forms:
+                process_forms(forms, base, pos)
+            forms = []
+            patterns = set()
+    process_forms(forms, base, pos)
diff --git a/dictionary/management/commands/import_variant.py b/dictionary/management/commands/import_variant.py
index 7672dbb..6fca445 100644
--- a/dictionary/management/commands/import_variant.py
+++ b/dictionary/management/commands/import_variant.py
@@ -1,49 +1,51 @@
 #-*- coding:utf-8 -*-
 
-from django.core.management.base import BaseCommand, CommandError
-from common.util import debug
+from django.core.management.base import BaseCommand
 from dictionary.models import TableTemplate, Cell, TableCell, PartOfSpeech, \
-  Variant, PatternType, InflectionCharacteristic, BaseFormLabel
+    Variant, PatternType, InflectionCharacteristic, BaseFormLabel
+
 
 class Command(BaseCommand):
-  args = '<variant name> <input file name>'
-  help = 'Imports variant from text file'
+    args = '<variant name> <input file name>'
+    help = 'Imports variant from text file'
+
+    def handle(self, variant, filename, **options):
+        import_variant(variant, open(filename))
 
-  def handle(self, variant, filename, **options):
-    import_variant(variant, open(filename))
 
 def import_variant(variant, input_file):
-  TableTemplate.objects.filter(variant__id=variant).delete()
-  for line in input_file:
-    if line.startswith(variant):
-      line = line.strip().decode('utf-8')
-      data = line.split('\t')
-      _variant, pos, p_type, ic, row, col, rspan, cspan, bfl, tag, pref, suf, \
-        index = data
-      assert variant == _variant
-      # trochę copypasta
-      lc = PartOfSpeech.objects.get(symbol=pos).lexical_class
-      v, _created = Variant.objects.get_or_create(id=variant)
-      tt_data = {
-        'variant': v,
-        'pattern_type': PatternType.objects.get(symbol=p_type, lexical_class=lc),
-        'inflection_characteristic': InflectionCharacteristic.objects.get(
-          symbol=ic, part_of_speech__symbol=pos),
-      }
-      tt, _created = TableTemplate.objects.get_or_create(**tt_data)
-      c = Cell()
-      c.table_template = tt
-      c.base_form_label = BaseFormLabel.objects.get(symbol=bfl)
-      c.tag = tag
-      c.prefix = pref
-      c.suffix = suf
-      c.index = int(index)
-      c.save()
-      if row:
-        tc = TableCell()
-        tc.cell = c
-        tc.row = int(row)
-        tc.col = int(col)
-        tc.rowspan = int(rspan)
-        tc.colspan = int(cspan)
-        tc.save()
+    TableTemplate.objects.filter(variant__id=variant).delete()
+    for line in input_file:
+        if line.startswith(variant):
+            line = line.strip().decode('utf-8')
+            data = line.split('\t')
+            _variant, pos, p_type, ic, row, col, rspan, cspan, bfl, tag, pref, suf, \
+            index = data
+            assert variant == _variant
+            # trochę copypasta
+            lc = PartOfSpeech.objects.get(symbol=pos).lexical_class
+            v, _created = Variant.objects.get_or_create(id=variant)
+            tt_data = {
+                'variant': v,
+                'pattern_type': PatternType.objects.get(symbol=p_type,
+                                                        lexical_class=lc),
+                'inflection_characteristic': InflectionCharacteristic.objects.get(
+                    symbol=ic, part_of_speech__symbol=pos),
+            }
+            tt, _created = TableTemplate.objects.get_or_create(**tt_data)
+            c = Cell()
+            c.table_template = tt
+            c.base_form_label = BaseFormLabel.objects.get(symbol=bfl)
+            c.tag = tag
+            c.prefix = pref
+            c.suffix = suf
+            c.index = int(index)
+            c.save()
+            if row:
+                tc = TableCell()
+                tc.cell = c
+                tc.row = int(row)
+                tc.col = int(col)
+                tc.rowspan = int(rspan)
+                tc.colspan = int(cspan)
+                tc.save()
diff --git a/dictionary/management/commands/import_warszawa.py b/dictionary/management/commands/import_warszawa.py
index 2b3288b..b1e4e35 100644
--- a/dictionary/management/commands/import_warszawa.py
+++ b/dictionary/management/commands/import_warszawa.py
@@ -3,100 +3,103 @@
 from django.core.management.base import BaseCommand
 from dictionary.models import Lexeme
 from dictionary.management.commands.import_morfologik import create_lexeme, \
-  create_lip, print_data
+    create_lip, print_data
+
 
 class Command(BaseCommand):
-  args = '<input file name>'
-  help = 'importuje nazwy warszawskie'
+    args = '<input file name>'
+    help = 'importuje nazwy warszawskie'
 
-  def handle(self, filename, **options):
-    import_warszawa(open(filename))
+    def handle(self, filename, **options):
+        import_warszawa(open(filename))
 
 
 def inflection_characteristic(forms, pos):
-  # w nazwach warszawskich jest tylko subst i adj
-  tag = forms[0][1]
-  if pos == 'subst':
-    if 'depr' in tag or tag.endswith('m1'):
-      ic = 'm1'
-    else:
-      ic = tag.rsplit(':', 1)[1]
-  elif pos == 'adj':
-    # formy 3+ tu nie występują
-    if any(tag == 'adja' for form, tag in forms):
-      ic = ''
-    else:
-      ic = '0-'
-  #return InflectionCharacteristic.objects.get(
-  #  symbol=ic, part_of_speech__symbol=pos)
-  return ic
+    # w nazwach warszawskich jest tylko subst i adj
+    tag = forms[0][1]
+    if pos == 'subst':
+        if 'depr' in tag or tag.endswith('m1'):
+            ic = 'm1'
+        else:
+            ic = tag.rsplit(':', 1)[1]
+    elif pos == 'adj':
+        # formy 3+ tu nie występują
+        if any(tag == 'adja' for form, tag in forms):
+            ic = ''
+        else:
+            ic = '0-'
+        #return InflectionCharacteristic.objects.get(
+    #  symbol=ic, part_of_speech__symbol=pos)
+    return ic
+
 
 def process_forms(forms, base, pos, patterns):
-  ic = inflection_characteristic(forms, pos)
-  #### wyłączone, bo sprawdzone, że wszystkie wzory się zgadzają
-  #patterns_ok = True
-  #try:
-  #  k_patterns = [Pattern.objects.get(name=p_name) for p_name in patterns]
-  #  # sprawdzić wygenerowane formy...
-  #  p_forms = set()
-  #  for pattern in k_patterns:
-  #    p_forms |= all_forms(pattern, ic, pos, base, affixes=False)
-  #  w_forms = set(form for form, tag in forms)
-  #  if p_forms != w_forms:
-  #    patterns_ok = False
-  #    print p_forms - w_forms, w_forms - p_forms, patterns
-  #except Pattern.DoesNotExist:
-  #  patterns_ok = False
-  #  print patterns
+    ic = inflection_characteristic(forms, pos)
+    #### wyłączone, bo sprawdzone, że wszystkie wzory się zgadzają
+    #patterns_ok = True
+    #try:
+    #  k_patterns = [Pattern.objects.get(name=p_name) for p_name in patterns]
+    #  # sprawdzić wygenerowane formy...
+    #  p_forms = set()
+    #  for pattern in k_patterns:
+    #    p_forms |= all_forms(pattern, ic, pos, base, affixes=False)
+    #  w_forms = set(form for form, tag in forms)
+    #  if p_forms != w_forms:
+    #    patterns_ok = False
+    #    print p_forms - w_forms, w_forms - p_forms, patterns
+    #except Pattern.DoesNotExist:
+    #  patterns_ok = False
+    #  print patterns
 
-  # szukamy leksemów wg base, pos, ic, wzory
-  homonyms = Lexeme.objects.filter(entry=base, part_of_speech__symbol=pos)
-  for l in homonyms:
-    lips = l.lexemeinflectionpattern_set.all()
-    l_patterns = set(lip.pattern.name for lip in lips)
-    l_ics = [lip.inflection_characteristic.symbol for lip in lips]
-    if l_ics in ([ic], ['3+']) and l_patterns == patterns:
-      break # nie importujemy, bo już jest
-    #else:
-    #  diff = ''
-    #  if l_ics != [ic]:
-    #    diff += '%s %s ' % (l_ics, ic)
-    #  if l_patterns != patterns:
-    #    diff += '%s %s' % (l_patterns, patterns)
-    #  debug(base, diff)
-  else:
-    if homonyms:
-      status = 'cand'
-      comment = u'z nazw warszawskich; rozbieżność'
+    # szukamy leksemów wg base, pos, ic, wzory
+    homonyms = Lexeme.objects.filter(entry=base, part_of_speech__symbol=pos)
+    for l in homonyms:
+        lips = l.lexemeinflectionpattern_set.all()
+        l_patterns = set(lip.pattern.name for lip in lips)
+        l_ics = [lip.inflection_characteristic.symbol for lip in lips]
+        if l_ics in ([ic], ['3+']) and l_patterns == patterns:
+            break # nie importujemy, bo już jest
+            #else:
+            #  diff = ''
+            #  if l_ics != [ic]:
+            #    diff += '%s %s ' % (l_ics, ic)
+            #  if l_patterns != patterns:
+            #    diff += '%s %s' % (l_patterns, patterns)
+            #  debug(base, diff)
     else:
-      status = 'desc'
-      comment = u'z nazw warszawskich'
-    lips = []
-    for i, pattern in enumerate(patterns):
-      lips.append(create_lip(pattern, None, i + 1, ic, pos))
-    data = {
-      'lexeme': create_lexeme(base, 1, pos, status, comment),
-      'lips': lips,
-    }
-    print_data(data)
+        if homonyms:
+            status = 'cand'
+            comment = u'z nazw warszawskich; rozbieżność'
+        else:
+            status = 'desc'
+            comment = u'z nazw warszawskich'
+        lips = []
+        for i, pattern in enumerate(patterns):
+            lips.append(create_lip(pattern, None, i + 1, ic, pos))
+        data = {
+            'lexeme': create_lexeme(base, 1, pos, status, comment),
+            'lips': lips,
+        }
+        print_data(data)
+
 
 def import_warszawa(input_file):
-  last_id = None
-  forms = None
-  last_base = None
-  last_pos = None
-  patterns = None
-  for line in input_file:
-    data = line.strip().decode('utf-8').split('\t')
-    w_id, lip_ind, pos, pattern, form, base, tag = data
-    if w_id != last_id:
-      if last_id is not None:
-        process_forms(forms, last_base, last_pos, patterns)
-      last_id = w_id
-      last_base = base
-      last_pos = pos
-      forms = []
-      patterns = set()
-    forms.append((form, tag))
-    patterns.add(pattern)
-  process_forms(forms, last_base, last_pos, patterns)
+    last_id = None
+    forms = None
+    last_base = None
+    last_pos = None
+    patterns = None
+    for line in input_file:
+        data = line.strip().decode('utf-8').split('\t')
+        w_id, lip_ind, pos, pattern, form, base, tag = data
+        if w_id != last_id:
+            if last_id is not None:
+                process_forms(forms, last_base, last_pos, patterns)
+            last_id = w_id
+            last_base = base
+            last_pos = pos
+            forms = []
+            patterns = set()
+        forms.append((form, tag))
+        patterns.add(pattern)
+    process_forms(forms, last_base, last_pos, patterns)
diff --git a/dictionary/management/commands/init_polimorf.py b/dictionary/management/commands/init_polimorf.py
index 16753a2..db8b2bf 100644
--- a/dictionary/management/commands/init_polimorf.py
+++ b/dictionary/management/commands/init_polimorf.py
@@ -4,20 +4,22 @@ from django.core.management.base import BaseCommand
 from common.util import no_history
 from dictionary.models import Lexeme, Vocabulary
 
+
 class Command(BaseCommand):
-  args = 'none'
-  help = 'Initiates PoliMorf'
+    args = 'none'
+    help = 'Initiates PoliMorf'
+
+    def handle(self, **options):
+        init_polimorf()
 
-  def handle(self, **options):
-    init_polimorf()
 
 def init_polimorf():
-  no_history()
-  pm, created = Vocabulary.objects.get_or_create(id='PoliMorf')
-  sgjp = Vocabulary.objects.get(id='SGJP')
-  existing = Lexeme.objects
-  for l in sgjp.owned_lexemes.all():
-    pm.add_lexeme(l)
-  for l in existing.filter(owner_vocabulary__id='Morfologik'):
-    if not existing.filter(entry=l.entry, owner_vocabulary__id='SGJP'):
-      pm.add_lexeme(l)
\ No newline at end of file
+    no_history()
+    pm, created = Vocabulary.objects.get_or_create(id='PoliMorf')
+    sgjp = Vocabulary.objects.get(id='SGJP')
+    existing = Lexeme.objects
+    for l in sgjp.owned_lexemes.all():
+        pm.add_lexeme(l)
+    for l in existing.filter(owner_vocabulary__id='Morfologik'):
+        if not existing.filter(entry=l.entry, owner_vocabulary__id='SGJP'):
+            pm.add_lexeme(l)
\ No newline at end of file
diff --git a/dictionary/management/commands/load_import.py b/dictionary/management/commands/load_import.py
index c4dc130..536bbac 100644
--- a/dictionary/management/commands/load_import.py
+++ b/dictionary/management/commands/load_import.py
@@ -6,22 +6,24 @@ from django.db.models import Max
 from django.core.management.base import BaseCommand
 from common.util import no_history, debug
 from dictionary.models import Lexeme, Pattern, \
-  LexemeInflectionPattern, PartOfSpeech, Vocabulary, InflectionCharacteristic, \
-  CrossReference, CrossReferenceType, ClassificationValue
+    LexemeInflectionPattern, PartOfSpeech, Vocabulary, InflectionCharacteristic, \
+    CrossReference, CrossReferenceType, ClassificationValue
 
 START_ID = 500000
-END_ID =  1000000
+END_ID = 1000000
 
 next_id = Lexeme.objects.filter(
-  pk__gte=START_ID, pk__lt=END_ID).aggregate(Max('id'))['id__max']
+    pk__gte=START_ID, pk__lt=END_ID).aggregate(Max('id'))['id__max']
 next_id = next_id + 1 if next_id else START_ID
 
+
 class Command(BaseCommand):
-  args = '<nazwa pliku wejściowego> <nazwa słownika> <nazwa źródła>'
-  help = 'Load prepared lexeme data'
+    args = '<nazwa pliku wejściowego> <nazwa słownika> <nazwa źródła>'
+    help = 'Load prepared lexeme data'
+
+    def handle(self, input_file, vocab_name, source, **options):
+        load_morfologik(input_file, vocab_name, source)
 
-  def handle(self, input_file, vocab_name, source, **options):
-    load_morfologik(input_file, vocab_name, source)
 
 source = None
 vocab = None # brzydko, ale nie chce mi się przerabiać wszystkiego
@@ -29,125 +31,137 @@ vocab = None # brzydko, ale nie chce mi się przerabiać wszystkiego
 parts_of_speech = PartOfSpeech.objects.all()
 pos_table = {}
 for part_of_speech in parts_of_speech:
-  pos_table[part_of_speech.symbol] = part_of_speech
+    pos_table[part_of_speech.symbol] = part_of_speech
 
 ic_list = InflectionCharacteristic.objects.all()
 ic_table = {}
 for ic in ic_list:
-  ic_table[(ic.symbol, ic.part_of_speech.symbol)] = ic
+    ic_table[(ic.symbol, ic.part_of_speech.symbol)] = ic
 
 pattern_list = Pattern.objects.all()
 pattern_table = {}
 for p in pattern_list:
-  pattern_table[p.name] = p
+    pattern_table[p.name] = p
+
 
 def associate(l):
-  created = vocab.add_lexeme(l)
-  if not created and l.part_of_speech.symbol not in ('ppas', 'pact', 'ger'):
-    debug(l.entry, u'wielokrotne przypisanie leksemu do słownika!')
+    created = vocab.add_lexeme(l)
+    if not created and l.part_of_speech.symbol not in ('ppas', 'pact', 'ger'):
+        debug(l.entry, u'wielokrotne przypisanie leksemu do słownika!')
+
 
 def add_cr(l_from, l_to, symbol):
-  cr_type = CrossReferenceType.objects.get(
-    symbol=symbol, from_pos=l_from.part_of_speech, to_pos=l_to.part_of_speech)
-  CrossReference(from_lexeme=l_from, to_lexeme=l_to, type=cr_type).save()
+    cr_type = CrossReferenceType.objects.get(
+        symbol=symbol, from_pos=l_from.part_of_speech,
+        to_pos=l_to.part_of_speech)
+    CrossReference(from_lexeme=l_from, to_lexeme=l_to, type=cr_type).save()
+
 
 def create_lexeme(entry, part_of_speech, status, comment, commonness=None):
-  global next_id
-  l = Lexeme(id=next_id, entry=entry, part_of_speech=part_of_speech,
-    source=source, status=status, comment=comment, owner_vocabulary=vocab)
-  l.fix_homonym_number()
-  l.save()
-  if commonness:
-    ClassificationValue.objects.get(label=commonness).add_lexeme(l)
-  associate(l)
-  next_id += 1
-  return l
+    global next_id
+    l = Lexeme(id=next_id, entry=entry, part_of_speech=part_of_speech,
+               source=source, status=status, comment=comment,
+               owner_vocabulary=vocab)
+    l.fix_homonym_number()
+    l.save()
+    if commonness:
+        ClassificationValue.objects.get(label=commonness).add_lexeme(l)
+    associate(l)
+    next_id += 1
+    return l
+
 
 def create_negated(l):
-  lneg = create_lexeme(
-    u"nie" + l.entry, l.part_of_speech,
-    "cand" if l.status == "cand" else "desc", '')
-  for lip in l.lexemeinflectionpattern_set.all():
-    if lip.inflection_characteristic.symbol != "0-":
-      ic = ic_table[("0-", "adj")]
-    else:
-      ic = lip.inflection_characteristic
-    LexemeInflectionPattern(lexeme=lneg, index=lip.index,
-      pattern=lip.pattern, root=u"nie" + lip.root,
-      inflection_characteristic=ic).save()
-  add_cr(l, lneg, "adjnie")
-  add_cr(lneg, l, "nieadj")
+    lneg = create_lexeme(
+        u"nie" + l.entry, l.part_of_speech,
+        "cand" if l.status == "cand" else "desc", '')
+    for lip in l.lexemeinflectionpattern_set.all():
+        if lip.inflection_characteristic.symbol != "0-":
+            ic = ic_table[("0-", "adj")]
+        else:
+            ic = lip.inflection_characteristic
+        LexemeInflectionPattern(lexeme=lneg, index=lip.index,
+                                pattern=lip.pattern, root=u"nie" + lip.root,
+                                inflection_characteristic=ic).save()
+    add_cr(l, lneg, "adjnie")
+    add_cr(lneg, l, "nieadj")
+
 
 def check_der(verb, pos, entry, patterns):
-  lips = verb.lexemeinflectionpattern_set.all()
-  if not lips:
-    return None
-  ic = lips[0].inflection_characteristic.symbol
-  matched = []
-  for l in Lexeme.objects.filter(
-      entry=entry, part_of_speech__symbol=pos,
-      lexemeinflectionpattern__inflection_characteristic__symbol=ic):
-    l_lips = l.lexemeinflectionpattern_set.all()
-    if l_lips[0].inflection_characteristic.symbol == ic:
-      l_patterns = set(l.patterns.values_list('name', flat=True))
-      if l_patterns == set(patterns):
-        matched.append(l)
-  if len(matched) > 1:
-    debug(entry, u'niejednoznaczny derywat')
-  if len(matched) > 0:
-    return matched[0]
-  else:
-    return None
+    lips = verb.lexemeinflectionpattern_set.all()
+    if not lips:
+        return None
+    ic = lips[0].inflection_characteristic.symbol
+    matched = []
+    for l in Lexeme.objects.filter(
+            entry=entry, part_of_speech__symbol=pos,
+            lexemeinflectionpattern__inflection_characteristic__symbol=ic):
+        l_lips = l.lexemeinflectionpattern_set.all()
+        if l_lips[0].inflection_characteristic.symbol == ic:
+            l_patterns = set(l.patterns.values_list('name', flat=True))
+            if l_patterns == set(patterns):
+                matched.append(l)
+    if len(matched) > 1:
+        debug(entry, u'niejednoznaczny derywat')
+    if len(matched) > 0:
+        return matched[0]
+    else:
+        return None
+
 
 def create_derived(l, pos, entry, patterns):
-  old_der = check_der(l, pos, entry, patterns)
-  if old_der:
-    if vocab not in old_der.vocabularies.all():
-      associate(old_der)
-    lder = old_der
-  else:
-    lder = create_lexeme(entry, pos_table[pos], l.status, u'')
-    for lip in l.lexemeinflectionpattern_set.all():
-      if lip.pattern.name in patterns:
-        ic = lip.inflection_characteristic.symbol.lstrip("q")
-        LexemeInflectionPattern(lexeme=lder, index=lip.index,
-          pattern=lip.pattern, root=lip.root,
-          inflection_characteristic=ic_table[(ic, pos)]).save()
-  add_cr(l, lder, "ver" + pos)
-  add_cr(lder, l, pos + "ver")
+    old_der = check_der(l, pos, entry, patterns)
+    if old_der:
+        if vocab not in old_der.vocabularies.all():
+            associate(old_der)
+        lder = old_der
+    else:
+        lder = create_lexeme(entry, pos_table[pos], l.status, u'')
+        for lip in l.lexemeinflectionpattern_set.all():
+            if lip.pattern.name in patterns:
+                ic = lip.inflection_characteristic.symbol.lstrip("q")
+                LexemeInflectionPattern(lexeme=lder, index=lip.index,
+                                        pattern=lip.pattern, root=lip.root,
+                                        inflection_characteristic=ic_table[
+                                            (ic, pos)]).save()
+    add_cr(l, lder, "ver" + pos)
+    add_cr(lder, l, pos + "ver")
 
 
 def load_morfologik(filename, vocab_name, source_):
-  global vocab, source
-  vocab = Vocabulary.objects.get(id=vocab_name)
-  source = source_
-  transaction.commit_unless_managed()
-  transaction.enter_transaction_management()
-  transaction.managed()
-  no_history()
-  with open(filename) as file:
-    for line in file:
-      data = json.loads(line.decode('utf-8'))
-      if data['lexeme']['source'] == 'sgjp':
-        l = Lexeme.objects.get(pk=data['lexeme']['id'])
-        associate(l)
-      elif data['lexeme']['source'] == 'morfologik':
-        l_data = data['lexeme']
-        l = create_lexeme(l_data['entry'], pos_table[l_data['part_of_speech']],
-          l_data['status'], l_data['comment'], l_data.get('commonness'))
-        for lip_data in data['lips']:
-          pattern = pattern_table[lip_data['pattern']]
-          ic = ic_table[tuple(lip_data['ic'])]
-          if lip_data['root']['type'] == 'string':
-            root = lip_data['root']['root']
-          elif lip_data['root']['type'] == 'compute':
-            root = l.get_root(pattern, ic)
-          LexemeInflectionPattern(lexeme=l, index=lip_data['ind'],
-            pattern=pattern, root=root, inflection_characteristic=ic).save()
-        if 'derived' in data:
-          for pos, entry, patterns in data['derived']:
-            create_derived(l, pos, entry, patterns)
-      if 'negated' in data:
-        create_negated(l)
-  transaction.commit()
-  transaction.leave_transaction_management()
+    global vocab, source
+    vocab = Vocabulary.objects.get(id=vocab_name)
+    source = source_
+    transaction.commit_unless_managed()
+    transaction.enter_transaction_management()
+    transaction.managed()
+    no_history()
+    with open(filename) as file:
+        for line in file:
+            data = json.loads(line.decode('utf-8'))
+            if data['lexeme']['source'] == 'sgjp':
+                l = Lexeme.objects.get(pk=data['lexeme']['id'])
+                associate(l)
+            elif data['lexeme']['source'] == 'morfologik':
+                l_data = data['lexeme']
+                l = create_lexeme(l_data['entry'],
+                                  pos_table[l_data['part_of_speech']],
+                                  l_data['status'], l_data['comment'],
+                                  l_data.get('commonness'))
+                for lip_data in data['lips']:
+                    pattern = pattern_table[lip_data['pattern']]
+                    ic = ic_table[tuple(lip_data['ic'])]
+                    if lip_data['root']['type'] == 'string':
+                        root = lip_data['root']['root']
+                    elif lip_data['root']['type'] == 'compute':
+                        root = l.get_root(pattern, ic)
+                    LexemeInflectionPattern(lexeme=l, index=lip_data['ind'],
+                                            pattern=pattern, root=root,
+                                            inflection_characteristic=ic).save()
+                if 'derived' in data:
+                    for pos, entry, patterns in data['derived']:
+                        create_derived(l, pos, entry, patterns)
+            if 'negated' in data:
+                create_negated(l)
+    transaction.commit()
+    transaction.leave_transaction_management()
diff --git a/dictionary/management/commands/uncertain_ppas.py b/dictionary/management/commands/uncertain_ppas.py
index 6dd276e..84a6e59 100644
--- a/dictionary/management/commands/uncertain_ppas.py
+++ b/dictionary/management/commands/uncertain_ppas.py
@@ -3,40 +3,42 @@
 from django.core.management.base import BaseCommand
 from dictionary.models import Lexeme, Vocabulary
 
+
 class Command(BaseCommand):
-  args = 'none'
-  help = 'blah'
+    args = 'none'
+    help = 'blah'
+
+    def handle(self, **options):
+        list_verbs()
 
-  def handle(self, **options):
-    list_verbs()
 
 def get_derived(lexeme):
-  derived = set()
-  for pos in ('ger', 'pact', 'ppas'):
-    if lexeme.refs_to.filter(type__symbol='ver' + pos):
-      derived.add(pos)
-  return derived
+    derived = set()
+    for pos in ('ger', 'pact', 'ppas'):
+        if lexeme.refs_to.filter(type__symbol='ver' + pos):
+            derived.add(pos)
+    return derived
 
 
 def list_verbs():
-  morfologik = Vocabulary.objects.get(id='Morfologik')
-  SGJP = Vocabulary.objects.get(id='SGJP')
-  morf = morfologik.owned_lexemes_pk()
-  sgjp = SGJP.owned_lexemes_pk()
-  verbs = Lexeme.objects.filter(part_of_speech__symbol='v')
-  sgjp_verbs = verbs.filter(pk__in=sgjp)
-  morf_verbs = verbs.filter(pk__in=morf)
-  sgjp_entries = set(sgjp_verbs.values_list('entry', flat=True))
-  morf_entries = set(morf_verbs.values_list('entry', flat=True))
-  common_entries = sgjp_entries & morf_entries
-  lexemes = morf_verbs.filter(entry__in=common_entries)
-  for lexeme in lexemes:
-    homonyms = verbs.filter(pk__in=sgjp, entry=lexeme.entry)
-    for hom in homonyms:
-      if set(lexeme.patterns.all()) == set(hom.patterns.all()):
-        m_der = get_derived(lexeme)
-        s_der = get_derived(hom)
-        if (m_der.issuperset(s_der) and m_der - s_der == {'ppas'}
-            or s_der.issuperset(m_der) and s_der - m_der == {'ppas'}):
-          print lexeme.entry.encode('utf-8'),
-          print lexeme.pk, hom.pk, 'morf' if 'ppas' in m_der else 'sgjp'
+    morfologik = Vocabulary.objects.get(id='Morfologik')
+    SGJP = Vocabulary.objects.get(id='SGJP')
+    morf = morfologik.owned_lexemes_pk()
+    sgjp = SGJP.owned_lexemes_pk()
+    verbs = Lexeme.objects.filter(part_of_speech__symbol='v')
+    sgjp_verbs = verbs.filter(pk__in=sgjp)
+    morf_verbs = verbs.filter(pk__in=morf)
+    sgjp_entries = set(sgjp_verbs.values_list('entry', flat=True))
+    morf_entries = set(morf_verbs.values_list('entry', flat=True))
+    common_entries = sgjp_entries & morf_entries
+    lexemes = morf_verbs.filter(entry__in=common_entries)
+    for lexeme in lexemes:
+        homonyms = verbs.filter(pk__in=sgjp, entry=lexeme.entry)
+        for hom in homonyms:
+            if set(lexeme.patterns.all()) == set(hom.patterns.all()):
+                m_der = get_derived(lexeme)
+                s_der = get_derived(hom)
+                if (m_der.issuperset(s_der) and m_der - s_der == {'ppas'}
+                    or s_der.issuperset(m_der) and s_der - m_der == {'ppas'}):
+                    print lexeme.entry.encode('utf-8'),
+                    print lexeme.pk, hom.pk, 'morf' if 'ppas' in m_der else 'sgjp'
diff --git a/dictionary/models.py b/dictionary/models.py
index d10d16c..356b349 100644
--- a/dictionary/models.py
+++ b/dictionary/models.py
@@ -5,784 +5,816 @@ from django.contrib.auth.models import User, Permission
 from common.util import no_history, GroupDict
 from accounts.util import users_with_perm
 
+
 class NotDeletedManager(Manager):
-  use_for_related_field = True
+    use_for_related_field = True
+
+    def get_query_set(self):
+        return super(NotDeletedManager, self).get_query_set().filter(
+            deleted=False)
 
-  def get_query_set(self):
-    return super(NotDeletedManager, self).get_query_set().filter(deleted=False)
 
 class LexemeNotDeletedManager(Manager):
-  use_for_related_field = True
+    use_for_related_field = True
 
-  def get_query_set(self):
-    return super(
-      LexemeNotDeletedManager, self).get_query_set().filter(
-        lexeme__deleted=False)
+    def get_query_set(self):
+        return super(
+            LexemeNotDeletedManager, self).get_query_set().filter(
+            lexeme__deleted=False)
 
 
 class LexicalClass(Model):
-  symbol = CharField(primary_key=True, max_length=16, db_column='czm')
+    symbol = CharField(primary_key=True, max_length=16, db_column='czm')
 
-  def __unicode__(self):
-    return self.symbol
+    def __unicode__(self):
+        return self.symbol
 
-  class Meta:
-    db_table = 'czescimowy'
+    class Meta:
+        db_table = 'czescimowy'
 
 
 class PartOfSpeech(Model):
-  symbol = CharField(primary_key=True, max_length=16, db_column='pos')
-  lexical_class = ForeignKey(LexicalClass, db_column='czm')
-  full_name = CharField(max_length=128, db_column='nazwa')
-  index = IntegerField()
-  color_scheme = IntegerField()
+    symbol = CharField(primary_key=True, max_length=16, db_column='pos')
+    lexical_class = ForeignKey(LexicalClass, db_column='czm')
+    full_name = CharField(max_length=128, db_column='nazwa')
+    index = IntegerField()
+    color_scheme = IntegerField()
 
-  def __unicode__(self):
-    return self.symbol
+    def __unicode__(self):
+        return self.symbol
 
-  class Meta:
-    db_table = 'klasygramatyczne'
-    ordering = ['index']
+    class Meta:
+        db_table = 'klasygramatyczne'
+        ordering = ['index']
 
 
 class QualifierExclusionClass(Model):
-  name = CharField(
-    unique=True, max_length=64, db_column='nazwa', verbose_name=u'nazwa')
-  vocabulary = ForeignKey(
-    'Vocabulary', db_column='slownik', verbose_name=u'słownik')
+    name = CharField(
+        unique=True, max_length=64, db_column='nazwa', verbose_name=u'nazwa')
+    vocabulary = ForeignKey(
+        'Vocabulary', db_column='slownik', verbose_name=u'słownik')
 
-  def __unicode__(self):
-    return self.name
+    def __unicode__(self):
+        return self.name
+
+    class Meta:
+        db_table = 'klasy_wykluczania'
 
-  class Meta:
-    db_table = 'klasy_wykluczania'
 
 def get_exclusion_classes():
-  exclusion_classes = {}
-  for ec in QualifierExclusionClass.objects.all():
-    qualifiers = ec.qualifier_set.all()
-    if qualifiers:
-      q_list = [q.pk for q in qualifiers]
-      exclusion_classes[ec.pk] = q_list
-  return exclusion_classes
+    exclusion_classes = {}
+    for ec in QualifierExclusionClass.objects.all():
+        qualifiers = ec.qualifier_set.all()
+        if qualifiers:
+            q_list = [q.pk for q in qualifiers]
+            exclusion_classes[ec.pk] = q_list
+    return exclusion_classes
 
 
 # kwalifikatory dla leksemów, odmian,
 # zakonczen i form wyjatkowych
 class Qualifier(Model):
-  label = CharField(max_length=64, db_column='kwal', verbose_name=u'nazwa')
-  vocabulary = ForeignKey(
-    'Vocabulary', db_column='slownik', verbose_name=u'słownik',
-    related_name='qualifiers')
-  exclusion_class = ForeignKey(
-    QualifierExclusionClass, db_column='klasa', null=True, blank=True,
-    verbose_name=u'klasa wykluczania')
-  deleted = BooleanField(db_column='usuniety', default=False)
-
-  objects = NotDeletedManager()
-  all_objects = Manager()
-
-  def is_empty(self):
-    return not (
-      self.lexeme_set.exists() or
-      self.ending_set.exists() or
-      self.lexemeinflectionpattern_set.exists())
-
-  def set_for(self, something, add):
-    if add:
-      if self.exclusion_class:
-        qualifiers = (something.qualifiers.all() &
-                      self.exclusion_class.qualifier_set.all())
-        if qualifiers.count() > 0 and list(qualifiers) != [self]:
-          return
-      something.qualifiers.add(self) #add
-    else:
-      something.qualifiers.remove(self) #add
+    label = CharField(max_length=64, db_column='kwal', verbose_name=u'nazwa')
+    vocabulary = ForeignKey(
+        'Vocabulary', db_column='slownik', verbose_name=u'słownik',
+        related_name='qualifiers')
+    exclusion_class = ForeignKey(
+        QualifierExclusionClass, db_column='klasa', null=True, blank=True,
+        verbose_name=u'klasa wykluczania')
+    deleted = BooleanField(db_column='usuniety', default=False)
+
+    objects = NotDeletedManager()
+    all_objects = Manager()
+
+    def is_empty(self):
+        return not (
+            self.lexeme_set.exists() or
+            self.ending_set.exists() or
+            self.lexemeinflectionpattern_set.exists())
+
+    def set_for(self, something, add):
+        if add:
+            if self.exclusion_class:
+                qualifiers = (something.qualifiers.all() &
+                              self.exclusion_class.qualifier_set.all())
+                if qualifiers.count() > 0 and list(qualifiers) != [self]:
+                    return
+            something.qualifiers.add(self) #add
+        else:
+            something.qualifiers.remove(self) #add
+
+    def __unicode__(self):
+        #return u'%s (%s)' % (self.label, self.vocabulary.id)
+        return self.label
+
+    class Meta:
+        unique_together = ('label', 'vocabulary')
+        db_table = 'kwalifikatory'
+        ordering = ['label']
 
-  def __unicode__(self):
-    #return u'%s (%s)' % (self.label, self.vocabulary.id)
-    return self.label
-
-  class Meta:
-    unique_together = ('label', 'vocabulary')
-    db_table = 'kwalifikatory'
-    ordering = ['label']
 
 def visible_qualifiers(user):
-  return Qualifier.objects.filter(vocabulary__in=visible_vocabularies(user))
+    return Qualifier.objects.filter(vocabulary__in=visible_vocabularies(user))
+
 
 def editable_qualifiers(user):
-  return Qualifier.objects.filter(vocabulary__in=editable_vocabularies(user))
+    return Qualifier.objects.filter(vocabulary__in=editable_vocabularies(user))
 
 
 class Classification(Model):
-  name = CharField(
-    unique=True, max_length=64, db_column='nazwa',
-    verbose_name=u'nazwa klasyfikacji')
-  parts_of_speech = ManyToManyField(PartOfSpeech)
+    name = CharField(
+        unique=True, max_length=64, db_column='nazwa',
+        verbose_name=u'nazwa klasyfikacji')
+    parts_of_speech = ManyToManyField(PartOfSpeech)
+
+    def value_tree(self):
+        parts = []
+        all_values = self.values.select_related('parent_node') \
+            .prefetch_related('child_nodes')
+        for v in all_values:
+            if v.parent_node is None:
+                parts.append(v.subtree(all_values))
+        return parts
 
-  def value_tree(self):
-    parts = []
-    all_values = self.values.select_related('parent_node')\
-      .prefetch_related('child_nodes')
-    for v in all_values:
-      if v.parent_node is None:
-        parts.append(v.subtree(all_values))
-    return parts
+    def make_choices(self):
+        return make_choices(self.value_tree())
 
-  def make_choices(self):
-    return make_choices(self.value_tree())
+    def __unicode__(self):
+        return self.name
 
-  def __unicode__(self):
-    return self.name
+    class Meta:
+        db_table = 'klasyfikacje'
 
-  class Meta:
-    db_table = 'klasyfikacje'
 
 def make_choices(tree):
-  choices = []
-  for value, subtree in tree:
-    choices.append((value.pk, value.label))
-    subchoices = make_choices(subtree)
-    choices += [(pk, u'    ' + label) for (pk, label) in subchoices] # &nbsp;
-  return choices
+    choices = []
+    for value, subtree in tree:
+        choices.append((value.pk, value.label))
+        subchoices = make_choices(subtree)
+        choices += [(pk, u'    ' + label) for (pk, label) in
+                    subchoices] # &nbsp;
+    return choices
 
 
 class ClassificationValue(Model):
-  label = CharField(
-    unique=True, max_length=64, db_column='nazwa',
-    verbose_name=u'nazwa wartości')
-  classification = ForeignKey(Classification, db_column='klas_id',
-                              related_name='values')
-  parent_node = ForeignKey(
-    'self', db_column='rodzic', null=True, blank=True,
-    verbose_name=u'rodzic wartości', related_name='child_nodes')
-  lexemes = ManyToManyField('Lexeme', blank=True, through='LexemeCV')
-  deleted = BooleanField(db_column='usunieta', default=False)
-
-  objects = NotDeletedManager()
-  all_objects = Manager()
-
-  def subtree(self, all_values):
-    subtrees = []
-    for child in all_values:
-      if child in self.child_nodes.all():
-        subtrees.append(child.subtree(all_values))
-    return self, subtrees
-
-  def is_empty(self):
-    return not self.lexemes.exists()
-
-  def add_lexeme(self, lexeme):
-    LexemeCV.objects.get_or_create(lexeme=lexeme, classification_value=self)
-
-  def remove_lexeme(self, lexeme):
-    LexemeCV.objects.filter(lexeme=lexeme, classification_value=self).delete()
-
-  def __unicode__(self):
-    return self.label
-
-  class Meta:
-    db_table = 'wartosci_klasyfikacji'
+    label = CharField(
+        unique=True, max_length=64, db_column='nazwa',
+        verbose_name=u'nazwa wartości')
+    classification = ForeignKey(Classification, db_column='klas_id',
+                                related_name='values')
+    parent_node = ForeignKey(
+        'self', db_column='rodzic', null=True, blank=True,
+        verbose_name=u'rodzic wartości', related_name='child_nodes')
+    lexemes = ManyToManyField('Lexeme', blank=True, through='LexemeCV')
+    deleted = BooleanField(db_column='usunieta', default=False)
+
+    objects = NotDeletedManager()
+    all_objects = Manager()
+
+    def subtree(self, all_values):
+        subtrees = []
+        for child in all_values:
+            if child in self.child_nodes.all():
+                subtrees.append(child.subtree(all_values))
+        return self, subtrees
+
+    def is_empty(self):
+        return not self.lexemes.exists()
+
+    def add_lexeme(self, lexeme):
+        LexemeCV.objects.get_or_create(lexeme=lexeme, classification_value=self)
+
+    def remove_lexeme(self, lexeme):
+        LexemeCV.objects.filter(lexeme=lexeme,
+                                classification_value=self).delete()
+
+    def __unicode__(self):
+        return self.label
+
+    class Meta:
+        db_table = 'wartosci_klasyfikacji'
+
 
 class LexemeCV(Model):
-  lexeme = ForeignKey('Lexeme')
-  classification_value = ForeignKey('ClassificationValue')
+    lexeme = ForeignKey('Lexeme')
+    classification_value = ForeignKey('ClassificationValue')
 
-  class Meta:
-    unique_together = ['lexeme', 'classification_value']
+    class Meta:
+        unique_together = ['lexeme', 'classification_value']
 
 
 class BaseFormLabel(Model):
-  symbol = CharField(max_length=32, blank=True, db_column='efobaz')
+    symbol = CharField(max_length=32, blank=True, db_column='efobaz')
 
-  def __unicode__(self):
-    return self.symbol
+    def __unicode__(self):
+        return self.symbol
 
-  class Meta:
-    db_table = 'efobazy'
+    class Meta:
+        db_table = 'efobazy'
 
 
 class InflectionCharacteristic(Model):
-  symbol = CharField(max_length=16, blank=True, db_column='charfl')
-  part_of_speech = ForeignKey(PartOfSpeech, db_column='pos')
-  basic_form_label = ForeignKey(BaseFormLabel, db_column='efobaz')
+    symbol = CharField(max_length=16, blank=True, db_column='charfl')
+    part_of_speech = ForeignKey(PartOfSpeech, db_column='pos')
+    basic_form_label = ForeignKey(BaseFormLabel, db_column='efobaz')
 
-  def __unicode__(self):
-    return '%s:%s' % (self.symbol, self.part_of_speech.symbol)
+    def __unicode__(self):
+        return '%s:%s' % (self.symbol, self.part_of_speech.symbol)
 
-  class Meta:
-    db_table = 'charfle'
-    unique_together = ('symbol', 'part_of_speech')
+    class Meta:
+        db_table = 'charfle'
+        unique_together = ('symbol', 'part_of_speech')
 
 
 class PatternType(Model):
-  lexical_class = ForeignKey(
-    LexicalClass, db_column='czm', verbose_name=u'cz. mowy')
-  # typ wzoru (np. dla rzeczowników:
-  # odmiana męska, żeńska lub nijaka)
-  symbol = CharField(
-    max_length=32, blank=True, db_column='wtyp', verbose_name=u'typ wzoru')
+    lexical_class = ForeignKey(
+        LexicalClass, db_column='czm', verbose_name=u'cz. mowy')
+    # typ wzoru (np. dla rzeczowników:
+    # odmiana męska, żeńska lub nijaka)
+    symbol = CharField(
+        max_length=32, blank=True, db_column='wtyp', verbose_name=u'typ wzoru')
 
-  # TODO to powinno być raczej w bazie
-  def base_form_labels(self):
-    bfl_ids = set(self.tabletemplate_set.distinct()
-                      .values_list('cell__base_form_label', flat=True))
-    # prowizorka ze względu na wzór 0000
-    bfl_ids |= set(self.pattern_set.distinct()
-                       .values_list('endings__base_form_label', flat=True))
-    return BaseFormLabel.objects.filter(pk__in=bfl_ids)
+    # TODO to powinno być raczej w bazie
+    def base_form_labels(self):
+        bfl_ids = set(self.tabletemplate_set.distinct()
+        .values_list('cell__base_form_label', flat=True))
+        # prowizorka ze względu na wzór 0000
+        bfl_ids |= set(self.pattern_set.distinct()
+        .values_list('endings__base_form_label', flat=True))
+        return BaseFormLabel.objects.filter(pk__in=bfl_ids)
 
-  def __unicode__(self):
-    return '%s (%s)' % (self.symbol, self.lexical_class.symbol)
+    def __unicode__(self):
+        return '%s (%s)' % (self.symbol, self.lexical_class.symbol)
 
-  class Meta:
-    db_table = 'typywzorow'
+    class Meta:
+        db_table = 'typywzorow'
 
 
 class Pattern(Model):
-  PATTERN_STATUS_CHOICES = (
+    PATTERN_STATUS_CHOICES = (
     # (<symbol>, u'<opis>'),
-  )
-
-  # kiedyś trzeba zrobić porządek w nazwach.
-  name = CharField(
-    max_length=32, unique=True, db_column='w_id', verbose_name=u'nazwa')
-  type = ForeignKey(PatternType, db_column='typ')
-  # rdzeń przykładowej formy hasłowej
-  example = CharField(max_length=64, db_column='przyklad',
-                      verbose_name=u'przyklad')
-  # zakończenie formy podstawowej (uwaga: w zasadzie tylko dla prezentacji
-  # wzoru, rdzenie w Odmieniasie trzeba tworzyć uważniej, wiedząc, która forma
-  # jest hasłowa dla danego charfla)
-  basic_form_ending = CharField(
-    max_length=32, db_column='zakp', blank=True,
-    verbose_name=u'zakończenie formy podstawowej')
-  # np. "chwilowo nieużywany, ale trzymamy, bo wymyśliliśmy"
-  status = CharField(
-    max_length=8, choices=PATTERN_STATUS_CHOICES, verbose_name=u'status')
-  comment = TextField(blank=True, db_column='komentarz',
-                      verbose_name=u'komentarz')
-
-  def ending_set(self, subroot='', tag_prefix=None):
-    endings = self.endings
-    if tag_prefix:
-      endings = endings.filter(base_form_label__symbol__startswith=tag_prefix)
-    return set(subroot + e for e in
-               endings.values_list('string', flat=True))
-
-  def get_basic_form_ending(self, inflection_characteristic):
-    return self.endings.filter(
-      base_form_label=inflection_characteristic.basic_form_label)[0].string
-
-  def __unicode__(self):
-    return self.name
-
-  class Meta:
-    db_table = 'wzory'
-    ordering = ['name']
-    permissions = (
-      ('view_pattern', u'Może oglądać wzory'),
     )
 
+    # kiedyś trzeba zrobić porządek w nazwach.
+    name = CharField(
+        max_length=32, unique=True, db_column='w_id', verbose_name=u'nazwa')
+    type = ForeignKey(PatternType, db_column='typ')
+    # rdzeń przykładowej formy hasłowej
+    example = CharField(max_length=64, db_column='przyklad',
+                        verbose_name=u'przyklad')
+    # zakończenie formy podstawowej (uwaga: w zasadzie tylko dla prezentacji
+    # wzoru, rdzenie w Odmieniasie trzeba tworzyć uważniej, wiedząc, która forma
+    # jest hasłowa dla danego charfla)
+    basic_form_ending = CharField(
+        max_length=32, db_column='zakp', blank=True,
+        verbose_name=u'zakończenie formy podstawowej')
+    # np. "chwilowo nieużywany, ale trzymamy, bo wymyśliliśmy"
+    status = CharField(
+        max_length=8, choices=PATTERN_STATUS_CHOICES, verbose_name=u'status')
+    comment = TextField(blank=True, db_column='komentarz',
+                        verbose_name=u'komentarz')
+
+    def ending_set(self, subroot='', tag_prefix=None):
+        endings = self.endings
+        if tag_prefix:
+            endings = endings.filter(
+                base_form_label__symbol__startswith=tag_prefix)
+        return set(subroot + e for e in
+                   endings.values_list('string', flat=True))
+
+    def get_basic_form_ending(self, inflection_characteristic):
+        return self.endings.filter(
+            base_form_label=inflection_characteristic.basic_form_label)[
+            0].string
+
+    def __unicode__(self):
+        return self.name
+
+    class Meta:
+        db_table = 'wzory'
+        ordering = ['name']
+        permissions = (
+            ('view_pattern', u'Może oglądać wzory'),
+        )
+
 
 def prepare_table(table):
-  for row in table:
-    for cell in row:
-      if type(cell) == dict and 'forms' in cell:
-        cell['forms'].sort()
-        seen_forms = []
-        unique_forms = []
-        for form in cell['forms']:
-          if form[1] not in seen_forms:
-            seen_forms.append(form[1])
-            unique_forms.append(form)
-        cell['forms'] = [{'form': form, 'qualifiers': qualifiers}
-                         for (key, form, qualifiers) in unique_forms]
-      elif type(cell) == dict and 'label' in cell:
-        seen_labels = []
-        def new(label):
-          new = label not in seen_labels
-          seen_labels.append(label)
-          return new
-        cell['label'] = filter(new, cell['label'])
+    for row in table:
+        for cell in row:
+            if type(cell) == dict and 'forms' in cell:
+                cell['forms'].sort()
+                seen_forms = []
+                unique_forms = []
+                for form in cell['forms']:
+                    if form[1] not in seen_forms:
+                        seen_forms.append(form[1])
+                        unique_forms.append(form)
+                cell['forms'] = [{'form': form, 'qualifiers': qualifiers}
+                                 for (key, form, qualifiers) in unique_forms]
+            elif type(cell) == dict and 'label' in cell:
+                seen_labels = []
+
+                def new(label):
+                    new = label not in seen_labels
+                    seen_labels.append(label)
+                    return new
+
+                cell['label'] = filter(new, cell['label'])
 
 
 # zakonczenie formy bazowej
 class Ending(Model):
-  pattern = ForeignKey(Pattern, related_name='endings', db_column='w_id')
-  # etykieta (tag) formy bazowej
-  base_form_label = ForeignKey(BaseFormLabel, db_column='efobaz')
-  # kolejnosc dla zakonczen o tym samym base_form_label
-  index = IntegerField(db_column='zind')
-  string = CharField(max_length=16, db_column='zak', blank=True)
-  qualifiers = ManyToManyField(
-    Qualifier, blank=True, db_table='kwalifikatory_zakonczen')
+    pattern = ForeignKey(Pattern, related_name='endings', db_column='w_id')
+    # etykieta (tag) formy bazowej
+    base_form_label = ForeignKey(BaseFormLabel, db_column='efobaz')
+    # kolejnosc dla zakonczen o tym samym base_form_label
+    index = IntegerField(db_column='zind')
+    string = CharField(max_length=16, db_column='zak', blank=True)
+    qualifiers = ManyToManyField(
+        Qualifier, blank=True, db_table='kwalifikatory_zakonczen')
 
-  def editable_vocabularies(self, user):
-    return editable_vocabularies(user)
+    def editable_vocabularies(self, user):
+        return editable_vocabularies(user)
 
-  def __unicode__(self):
-    return '%s : %s : %s' % (
-      self.pattern.name, self.string, self.base_form_label)
+    def __unicode__(self):
+        return '%s : %s : %s' % (
+            self.pattern.name, self.string, self.base_form_label)
 
-  class Meta:
-    db_table = 'zakonczenia'
-    unique_together = ('pattern', 'base_form_label', 'index')
-    ordering = ['index']
+    class Meta:
+        db_table = 'zakonczenia'
+        unique_together = ('pattern', 'base_form_label', 'index')
+        ordering = ['index']
 
 
 class Lexeme(Model):
-  STATUS_CHOICES = (
-    ('cand', u'kandydat'),
-    ('desc', u'wprowadzony'),
-    ('conf', u'zatwierdzony'),
-  )
-
-  entry = CharField(max_length=64, db_column='haslo', db_index=True,
-                    verbose_name=u'hasło', blank=True) # dla nowo utworzonych
-  # pozostałość historyczna:
-  entry_suffix = CharField(blank=True, max_length=16, db_column='haslosuf',
-                           verbose_name=u'sufiks hasła')
-  gloss = TextField(blank=True, db_column='glosa', verbose_name=u'glosa')
-  note = TextField(blank=True, db_column='nota', verbose_name=u'nota')
-  pronunciation = TextField(
-    blank=True, db_column='wymowa', verbose_name=u'wymowa')
-  valence = TextField(blank=True, verbose_name=u'łączliwość')
-  homonym_number = IntegerField(db_column='hom', default=1)
-  part_of_speech = ForeignKey(
-    PartOfSpeech, db_column='pos', verbose_name=u'cz. mowy')
-  owner_vocabulary = ForeignKey(
-    'Vocabulary', db_column='slownik', related_name='owned_lexemes')
-  source = CharField(max_length=32, blank=True, db_column='zrodlo')
-  status = CharField(max_length=8, db_column='status', choices=STATUS_CHOICES)
-  qualifiers = ManyToManyField(
-    Qualifier, blank=True, db_table='kwalifikatory_leksemow')
-  comment = TextField(blank=True, db_column='komentarz',
-                      verbose_name=u'komentarz')
-  last_modified = DateTimeField(auto_now=True, db_column='data_modyfikacji')
-  # osoba, ktora ostatnia zmieniala opis leksemu
-  responsible = ForeignKey(
-    User, blank=True, null=True, db_column='odpowiedzialny')
-  patterns = ManyToManyField(Pattern, through='LexemeInflectionPattern')
-  deleted = BooleanField(db_column='usuniety', default=False)
-
-  objects = NotDeletedManager()
-  all_objects = Manager()
-
-  def inflection_tables(self, variant, qualifiers=None):
-    lips = self.lexemeinflectionpattern_set.order_by('index')\
-      .select_related('inflection_characteristic', 'pattern')
-    ics = GroupDict()
-    for lip in lips:
-      ic = lip.inflection_characteristic
-      ics.add(ic, lip.pattern.name)
-    return [(ic, patterns,
-             self.inflection_table(variant, ic, qualifiers=qualifiers))
-            for ic, patterns in ics.iteritems()]
-
-  def inflection_table(self, variant, inflection_characteristic,
-                       qualifiers=None):
-    lips = self.lexemeinflectionpattern_set.filter(
-      inflection_characteristic=inflection_characteristic)\
-      .prefetch_related('qualifiers').select_related(
-      'pattern__type', 'inflection_characteristic')
-    tables = [lip.inflection_table(variant, qualifiers=qualifiers)
-              for lip in lips]
-    table1 = tables[0]
-    for table2 in tables[1:]:
-      for row1, row2 in zip(table1, table2):
-        for cell1, cell2 in zip(row1, row2):
-          if cell1['type'] == 'forms':
-            assert cell2['type'] in ('forms', 'empty')
-            if cell2['type'] == 'forms':
-              cell1['forms'].extend(cell2['forms'])
-          elif cell1['type'] == 'label':
-            assert cell2['type'] in ('label', 'empty')
-            if cell2['type'] == 'label':
-              cell1['label'].extend(cell2['label'])
-          elif cell1['type'] == 'empty':
-            cell1.update(cell2)
-    prepare_table(table1)
-    return table1
-
-  def refresh_forms(self):
-    self.lexemeform_set.all().delete()
-    for form in self.all_forms():
-      self.lexemeform_set.add(LexemeForm(form=form))
-
-  def all_forms(self, affixes=True, label_filter=None, variant='1'):
-    forms = set()
-    for lip in self.lexemeinflectionpattern_set.all():
-      forms |= set(
-        form for (indexes, form, qualifiers)
-        in lip.all_forms(
-          affixes=affixes, label_filter=label_filter, variant=variant))
-    return forms
-
-  def get_root(self, pattern, inflection_characteristic):
-    basic_form = self.entry
-    pos = self.part_of_speech.symbol
-    return get_root(basic_form, pos, pattern, inflection_characteristic)
-
-  def visible_vocabularies(self, user):
-    return visible_vocabularies(user) & self.vocabularies.all()
-
-  def editable_vocabularies(self, user):
-    return editable_vocabularies(user) & self.vocabularies.all()
-
-  def change_owner(self, new_owner):
-    old_owner = self.owner_vocabulary
-    new_owner.add_lexeme(self)
-    self.owner_vocabulary = new_owner
-    old_owner.remove_lexeme(self)
-
-  def classification_values(self, classification):
-    return self.classificationvalue_set.filter(classification=classification)
-
-  def lip_data(self, lips=None):
-    if lips is None:
-      lips = self.lexemeinflectionpattern_set.all()
-    patterns = []
-    ics = []
-    for lip in lips:
-      if patterns == [] or lip.pattern.name != patterns[-1]:
-        patterns.append(lip.pattern.name)
-      if ics == [] or lip.inflection_characteristic.symbol != ics[-1]:
-        ics.append(lip.inflection_characteristic.symbol)
-    patterns = '/'.join(patterns)
-    ics = '/'.join(ics)
-    return {'patterns': patterns, 'inflection_characteristics': ics}
-
-  def fix_homonym_number(self):
-    homonym_numbers = (Lexeme.objects.filter(
-      entry=self.entry, part_of_speech=self.part_of_speech)
-      .exclude(pk=self.pk)).values_list('homonym_number', flat=True)
-    for i in xrange(1, len(homonym_numbers) + 2):
-      if i not in homonym_numbers:
-        self.homonym_number = i
-        break
-
-  def attributes(self, part_of_speech=None, ics=None):
-    if ics is None:
-      lips = self.lexemeinflectionpattern_set.all()
-      ics = tuple(lip.inflection_characteristic for lip in lips)
-    pos = part_of_speech or self.part_of_speech
-    attrs = LexemeAttribute.objects.all()
-    attrs = attrs.filter(parts_of_speech=pos)
-    attrs = (attrs.filter(inflection_characteristics__in=ics)
-             | attrs.filter(takes_ic=False))
-    return attrs
-
-  def attributes_values(self, part_of_speech=None, ics=None):
-    for attr in self.attributes(part_of_speech, ics):
-      yield (attr, self.attribute_value(attr))
-
-  def attribute_value(self, attribute):
-    if attribute.multiple:
-      return attribute.values.filter(lexemes=self)
-    else:
-      try:
-        return attribute.values.get(lexemes=self)
-      except LexemeAttributeValue.DoesNotExist:
-        return None
-
-  def perm(self, user, action):
-    if action == 'view':
-      vocabs = self.vocabularies.all()
-      return bool(vocabs & visible_vocabularies(user))
-    elif action == 'change':
-      priority = (not (self.responsible and
-                       self.responsible.has_perm('dictionary.lexeme_priority'))
-                  or user.has_perm('dictionary.lexeme_priority'))
-      edit_vocab = self.owner_vocabulary in editable_vocabularies(user)
-      return edit_vocab and priority
-
-  def undelete(self):
-    no_history()
-    self.deleted = False
-    self.save()
-    self.history_set.get(column_name='usuniety').delete()
-
-  def sgjp_info(self):
-    commonness = Classification.objects.get(name=u'pospolitość')
-    commonness_labels = list(self.classification_values(
-      commonness).values_list('label', flat=True))
-    if commonness_labels == ['pospolita']:
-      commonness_labels = []
-    return {
-      'SJPDor': bool(self.vocabularies.filter(id='SJPDor')),
-      'commonness': commonness_labels,
-      'qualifiers': self.qualifiers.values_list('label', flat=True),
-    }
-
-  def __unicode__(self):
-    return '%s (%s)' % (self.entry, self.part_of_speech.symbol)
-
-  class Meta:
-    db_table = 'leksemy'
-    permissions = (
-      ('view_lexeme', u'Może oglądać leksemy'),
-      ('view_all_lexemes', u'Może oglądać wszystkie leksemy'),
-      ('lexeme_priority', u'Ważniejszy głos przy modyfikowaniu leksemów'),
-      ('export_lexemes', u'Może eksportować leksemy'),
+    STATUS_CHOICES = (
+        ('cand', u'kandydat'),
+        ('desc', u'wprowadzony'),
+        ('conf', u'zatwierdzony'),
     )
 
+    entry = CharField(max_length=64, db_column='haslo', db_index=True,
+                      verbose_name=u'hasło', blank=True) # dla nowo utworzonych
+    # pozostałość historyczna:
+    entry_suffix = CharField(blank=True, max_length=16, db_column='haslosuf',
+                             verbose_name=u'sufiks hasła')
+    gloss = TextField(blank=True, db_column='glosa', verbose_name=u'glosa')
+    note = TextField(blank=True, db_column='nota', verbose_name=u'nota')
+    pronunciation = TextField(
+        blank=True, db_column='wymowa', verbose_name=u'wymowa')
+    valence = TextField(blank=True, verbose_name=u'łączliwość')
+    homonym_number = IntegerField(db_column='hom', default=1)
+    part_of_speech = ForeignKey(
+        PartOfSpeech, db_column='pos', verbose_name=u'cz. mowy')
+    owner_vocabulary = ForeignKey(
+        'Vocabulary', db_column='slownik', related_name='owned_lexemes')
+    source = CharField(max_length=32, blank=True, db_column='zrodlo')
+    status = CharField(max_length=8, db_column='status', choices=STATUS_CHOICES)
+    qualifiers = ManyToManyField(
+        Qualifier, blank=True, db_table='kwalifikatory_leksemow')
+    comment = TextField(blank=True, db_column='komentarz',
+                        verbose_name=u'komentarz')
+    last_modified = DateTimeField(auto_now=True, db_column='data_modyfikacji')
+    # osoba, ktora ostatnia zmieniala opis leksemu
+    responsible = ForeignKey(
+        User, blank=True, null=True, db_column='odpowiedzialny')
+    patterns = ManyToManyField(Pattern, through='LexemeInflectionPattern')
+    deleted = BooleanField(db_column='usuniety', default=False)
+
+    objects = NotDeletedManager()
+    all_objects = Manager()
+
+    def inflection_tables(self, variant, qualifiers=None):
+        lips = self.lexemeinflectionpattern_set.order_by('index') \
+            .select_related('inflection_characteristic', 'pattern')
+        ics = GroupDict()
+        for lip in lips:
+            ic = lip.inflection_characteristic
+            ics.add(ic, lip.pattern.name)
+        return [(ic, patterns,
+                 self.inflection_table(variant, ic, qualifiers=qualifiers))
+                for ic, patterns in ics.iteritems()]
+
+    def inflection_table(self, variant, inflection_characteristic,
+                         qualifiers=None):
+        lips = self.lexemeinflectionpattern_set.filter(
+            inflection_characteristic=inflection_characteristic) \
+            .prefetch_related('qualifiers').select_related(
+            'pattern__type', 'inflection_characteristic')
+        tables = [lip.inflection_table(variant, qualifiers=qualifiers)
+                  for lip in lips]
+        table1 = tables[0]
+        for table2 in tables[1:]:
+            for row1, row2 in zip(table1, table2):
+                for cell1, cell2 in zip(row1, row2):
+                    if cell1['type'] == 'forms':
+                        assert cell2['type'] in ('forms', 'empty')
+                        if cell2['type'] == 'forms':
+                            cell1['forms'].extend(cell2['forms'])
+                    elif cell1['type'] == 'label':
+                        assert cell2['type'] in ('label', 'empty')
+                        if cell2['type'] == 'label':
+                            cell1['label'].extend(cell2['label'])
+                    elif cell1['type'] == 'empty':
+                        cell1.update(cell2)
+        prepare_table(table1)
+        return table1
+
+    def refresh_forms(self):
+        self.lexemeform_set.all().delete()
+        for form in self.all_forms():
+            self.lexemeform_set.add(LexemeForm(form=form))
+
+    def all_forms(self, affixes=True, label_filter=None, variant='1'):
+        forms = set()
+        for lip in self.lexemeinflectionpattern_set.all():
+            forms |= set(
+                form for (indexes, form, qualifiers)
+                in lip.all_forms(
+                    affixes=affixes, label_filter=label_filter,
+                    variant=variant))
+        return forms
+
+    def get_root(self, pattern, inflection_characteristic):
+        basic_form = self.entry
+        pos = self.part_of_speech.symbol
+        return get_root(basic_form, pos, pattern, inflection_characteristic)
+
+    def visible_vocabularies(self, user):
+        return visible_vocabularies(user) & self.vocabularies.all()
+
+    def editable_vocabularies(self, user):
+        return editable_vocabularies(user) & self.vocabularies.all()
+
+    def change_owner(self, new_owner):
+        old_owner = self.owner_vocabulary
+        new_owner.add_lexeme(self)
+        self.owner_vocabulary = new_owner
+        old_owner.remove_lexeme(self)
+
+    def classification_values(self, classification):
+        return self.classificationvalue_set.filter(
+            classification=classification)
+
+    def lip_data(self, lips=None):
+        if lips is None:
+            lips = self.lexemeinflectionpattern_set.all()
+        patterns = []
+        ics = []
+        for lip in lips:
+            if patterns == [] or lip.pattern.name != patterns[-1]:
+                patterns.append(lip.pattern.name)
+            if ics == [] or lip.inflection_characteristic.symbol != ics[-1]:
+                ics.append(lip.inflection_characteristic.symbol)
+        patterns = '/'.join(patterns)
+        ics = '/'.join(ics)
+        return {'patterns': patterns, 'inflection_characteristics': ics}
+
+    def fix_homonym_number(self):
+        homonym_numbers = (Lexeme.objects.filter(
+            entry=self.entry, part_of_speech=self.part_of_speech)
+                           .exclude(pk=self.pk)).values_list('homonym_number',
+                                                             flat=True)
+        for i in xrange(1, len(homonym_numbers) + 2):
+            if i not in homonym_numbers:
+                self.homonym_number = i
+                break
+
+    def attributes(self, part_of_speech=None, ics=None):
+        if ics is None:
+            lips = self.lexemeinflectionpattern_set.all()
+            ics = tuple(lip.inflection_characteristic for lip in lips)
+        pos = part_of_speech or self.part_of_speech
+        attrs = LexemeAttribute.objects.all()
+        attrs = attrs.filter(parts_of_speech=pos)
+        attrs = (attrs.filter(inflection_characteristics__in=ics)
+                 | attrs.filter(takes_ic=False))
+        return attrs
+
+    def attributes_values(self, part_of_speech=None, ics=None):
+        for attr in self.attributes(part_of_speech, ics):
+            yield (attr, self.attribute_value(attr))
+
+    def attribute_value(self, attribute):
+        if attribute.multiple:
+            return attribute.values.filter(lexemes=self)
+        else:
+            try:
+                return attribute.values.get(lexemes=self)
+            except LexemeAttributeValue.DoesNotExist:
+                return None
+
+    def perm(self, user, action):
+        if action == 'view':
+            vocabs = self.vocabularies.all()
+            return bool(vocabs & visible_vocabularies(user))
+        elif action == 'change':
+            priority = (not (self.responsible and
+                             self.responsible.has_perm(
+                                 'dictionary.lexeme_priority'))
+                        or user.has_perm('dictionary.lexeme_priority'))
+            edit_vocab = self.owner_vocabulary in editable_vocabularies(user)
+            return edit_vocab and priority
+
+    def undelete(self):
+        no_history()
+        self.deleted = False
+        self.save()
+        self.history_set.get(column_name='usuniety').delete()
+
+    def sgjp_info(self):
+        commonness = Classification.objects.get(name=u'pospolitość')
+        commonness_labels = list(self.classification_values(
+            commonness).values_list('label', flat=True))
+        if commonness_labels == ['pospolita']:
+            commonness_labels = []
+        return {
+            'SJPDor': bool(self.vocabularies.filter(id='SJPDor')),
+            'commonness': commonness_labels,
+            'qualifiers': self.qualifiers.values_list('label', flat=True),
+        }
+
+    def __unicode__(self):
+        return '%s (%s)' % (self.entry, self.part_of_speech.symbol)
+
+    class Meta:
+        db_table = 'leksemy'
+        permissions = (
+            ('view_lexeme', u'Może oglądać leksemy'),
+            ('view_all_lexemes', u'Może oglądać wszystkie leksemy'),
+            ('lexeme_priority', u'Ważniejszy głos przy modyfikowaniu leksemów'),
+            ('export_lexemes', u'Może eksportować leksemy'),
+        )
+
+
 def filter_visible(lexemes, user):
-  vocab_ids = [v.id for v in visible_vocabularies(user)]
-  # uniknięcie podzapytania *bardzo* zwiększa wydajność!
-  return lexemes.filter(vocabularies__id__in=vocab_ids).distinct()
+    vocab_ids = [v.id for v in visible_vocabularies(user)]
+    # uniknięcie podzapytania *bardzo* zwiększa wydajność!
+    return lexemes.filter(vocabularies__id__in=vocab_ids).distinct()
+
 
 def get_root(basic_form, pos, pattern, ic, use_pattern_ending=False):
-  bfl = ic.basic_form_label
-  basic_endings = pattern.endings.filter(base_form_label=bfl)
-  ends = []
-  if use_pattern_ending:
-    ends.append(pattern.basic_form_ending)
-  if basic_endings:
-    ends += [e.string for e in pattern.endings.filter(base_form_label=bfl)]
-  if pos == 'ger':
-    ends = [end + 'ie' for end in ends]
-  if pos == 'pact':
-    ends = [end + 'cy' for end in ends]
-  if pos in ('ppas', 'appas'):
-    ends = [end + 'y' for end in ends]
-  good_ends = [end for end in ends if basic_form.endswith(end)]
-  assert len(set(good_ends)) <= 1 # inaczej rdzeń nie jest jednoznaczny
-  if good_ends:
-    return basic_form[:len(basic_form) - len(good_ends[0])]
-  else:
-    if not use_pattern_ending:
-      return get_root(basic_form, pos, pattern, ic, use_pattern_ending=True)
+    bfl = ic.basic_form_label
+    basic_endings = pattern.endings.filter(base_form_label=bfl)
+    ends = []
+    if use_pattern_ending:
+        ends.append(pattern.basic_form_ending)
+    if basic_endings:
+        ends += [e.string for e in pattern.endings.filter(base_form_label=bfl)]
+    if pos == 'ger':
+        ends = [end + 'ie' for end in ends]
+    if pos == 'pact':
+        ends = [end + 'cy' for end in ends]
+    if pos in ('ppas', 'appas'):
+        ends = [end + 'y' for end in ends]
+    good_ends = [end for end in ends if basic_form.endswith(end)]
+    assert len(set(good_ends)) <= 1 # inaczej rdzeń nie jest jednoznaczny
+    if good_ends:
+        return basic_form[:len(basic_form) - len(good_ends[0])]
     else:
-      return None
+        if not use_pattern_ending:
+            return get_root(basic_form, pos, pattern, ic,
+                            use_pattern_ending=True)
+        else:
+            return None
 
 
 class LexemeAttribute(Model):
-  name = CharField(max_length=32)
-  closed = BooleanField() # czy jest zamknięta lista wartości
-  multiple = BooleanField()
-  required = BooleanField()
-  parts_of_speech = ManyToManyField(PartOfSpeech)
-  takes_ic = BooleanField()
-  inflection_characteristics = ManyToManyField(
-    InflectionCharacteristic, blank=True)
+    name = CharField(max_length=32)
+    closed = BooleanField() # czy jest zamknięta lista wartości
+    multiple = BooleanField()
+    required = BooleanField()
+    parts_of_speech = ManyToManyField(PartOfSpeech)
+    takes_ic = BooleanField()
+    inflection_characteristics = ManyToManyField(
+        InflectionCharacteristic, blank=True)
 
-  def __unicode__(self):
-    return self.name
+    def __unicode__(self):
+        return self.name
 
 
 class LexemeAttributeValue(Model):
-  value = CharField(max_length=32, blank=True)
-  display_value = CharField(max_length=32, blank=True)
-  attribute = ForeignKey(LexemeAttribute, related_name='values')
-  lexemes = ManyToManyField(Lexeme, blank=True, through='LexemeAV')
+    value = CharField(max_length=32, blank=True)
+    display_value = CharField(max_length=32, blank=True)
+    attribute = ForeignKey(LexemeAttribute, related_name='values')
+    lexemes = ManyToManyField(Lexeme, blank=True, through='LexemeAV')
+
+    def add_lexeme(self, lexeme):
+        LexemeAV.objects.get_or_create(lexeme=lexeme, attribute_value=self)
 
-  def add_lexeme(self, lexeme):
-    LexemeAV.objects.get_or_create(lexeme=lexeme, attribute_value=self)
+    def remove_lexeme(self, lexeme):
+        LexemeAV.objects.filter(lexeme=lexeme, attribute_value=self).delete()
 
-  def remove_lexeme(self, lexeme):
-    LexemeAV.objects.filter(lexeme=lexeme, attribute_value=self).delete()
+    def __unicode__(self):
+        return self.value
 
-  def __unicode__(self):
-    return self.value
+    class Meta:
+        ordering = ['value']
 
-  class Meta:
-    ordering = ['value']
 
 class LexemeAV(Model):
-  lexeme = ForeignKey('Lexeme')
-  attribute_value = ForeignKey('LexemeAttributeValue')
+    lexeme = ForeignKey('Lexeme')
+    attribute_value = ForeignKey('LexemeAttributeValue')
 
-  class Meta:
-    unique_together = ['lexeme', 'attribute_value']
+    class Meta:
+        unique_together = ['lexeme', 'attribute_value']
 
 
 class LexemeInflectionPattern(Model):
-  lexeme = ForeignKey(Lexeme, db_column='l_id')
-  index = IntegerField(db_column='oind')
-  pattern = ForeignKey(Pattern, db_column='w_id', verbose_name=u'wzór')
-  # charakterystyka fleksyjna (rodzaj, aspekt)
-  inflection_characteristic = ForeignKey(
-    InflectionCharacteristic, db_column='charfl', verbose_name=u'char. fleks.')
-  # rdzen odmiany przy zastosowaniu danego wzoru
-  root = CharField(max_length=64, db_column='rdzen')
-  # tu mozna sygnalizowac, ze dany sposob
-  # odmiany leksemu jest gorszy, przestarzaly, etc
-  qualifiers = ManyToManyField(
-    Qualifier, blank=True, db_table='kwalifikatory_odmieniasiow')
-
-  objects = LexemeNotDeletedManager()
-  all_objects = Manager()
-
-  def table_template(self, variant):
-    return TableTemplate.objects.get(
-      variant=variant, pattern_type=self.pattern.type,
-      inflection_characteristic=self.inflection_characteristic)
-
-  def cells(self, variant='1'):
-    tt = self.table_template(variant)
-    return tt.cell_set.select_related('base_form_label', 'tablecell')
-
-  def base_endings(self, label_filter=None):
-    bfls = self.pattern.type.base_form_labels()
-    endings = Ending.objects.filter(
-      base_form_label__in=bfls, pattern=self.pattern)\
-      .select_related('base_form_label').prefetch_related('qualifiers')
-    if label_filter is not None:
-      endings = endings.filter(base_form_label__symbol__regex=label_filter)
-    bfl_dict = GroupDict((bfl, []) for bfl in bfls)
-    for ending in endings:
-      bfl_dict.add(ending.base_form_label, ending)
-    return bfl_dict
-
-  def inflection_table(self, variant, separated=False, qualifiers=None,
-                       edit_view=False):
-    tt = self.table_template(variant)
-    cells = self.cells(variant)
-    headers = tt.tableheader_set.all()
-    rows = set()
-    last_col = 0
-    for cell in cells:
-      rows.add(cell.tablecell.row)
-      col = cell.tablecell.col + cell.tablecell.colspan - 1
-      if col > last_col:
-        last_col = col
-    for header in headers:
-      rows.add(header.row)
-      col = header.col + header.colspan - 1
-      if col > last_col:
-        last_col = col
-    table = [[{'type': 'empty'}
-              for i in xrange(last_col)] for j in xrange(len(rows))]
-    rows = sorted(rows)
-    # słownik: nr rzędu w bazie -> rzeczywisty numer rzędu
-    row_translate = dict(zip(rows, xrange(len(rows))))
-    base_endings = self.base_endings()
-    for cell in cells:
-      x = cell.tablecell.col - 1
-      y = row_translate[cell.tablecell.row]
-      table_cell = table[y][x]
-      assert table_cell['type'] != 'span'
-      separator = u'·' if separated else u''
-      forms = self.forms(
-        cell, base_endings, separator=separator, qualifiers=qualifiers,
-        edit_view=edit_view)
-      if not forms:
-        continue
-      if table_cell['type'] == 'empty':
-        table[y][x] = {
-          'type': 'forms',
-          'forms': forms,
-          'rowspan': cell.tablecell.rowspan,
-          'colspan': cell.tablecell.colspan,
-        }
-        for i in xrange(cell.tablecell.colspan):
-          for j in xrange(cell.tablecell.rowspan):
-            if (i, j) != (0, 0):
-              assert table[y+j][x+i]['type'] == 'empty'
-              table[y+j][x+i]['type'] = 'span'
-      else:
-        assert cell.tablecell.rowspan == table_cell['rowspan']
-        assert cell.tablecell.colspan == table_cell['colspan']
-        table_cell['forms'] += forms
-    for header in headers:
-      x = header.col - 1
-      y = row_translate[header.row]
-      assert table[y][x]['type'] == 'empty'
-      table[y][x] = {
-        'type': 'label',
-        'label': [header.label],
-        'css_class': header.css_class,
-        'rowspan': header.rowspan,
-        'colspan': header.colspan,
-      }
-      for i in xrange(header.colspan):
-        for j in xrange(header.rowspan):
-          if (i, j) != (0, 0):
-            assert table[y+j][x+i]['type'] == 'empty'
-            table[y+j][x+i]['type'] = 'span'
-    return [row for row in table
-            if not all(cell['type'] == 'empty' for cell in row)]
-
-  def all_forms(self, separator='', affixes=True, label_filter=None,
-                variant='1', qualifiers=None):
-    forms = []
-    base_endings = self.base_endings(label_filter)
-    for cell in self.cells(variant=variant):
-      forms += self.forms(
-        cell, base_endings, separator, affixes, qualifiers=qualifiers)
-    return forms
-
-  def forms(self, cell, base_endings, separator='',
-            affixes=True, qualifiers=None, edit_view=False):
-    if qualifiers:
-      qualifiers_set = set(qualifiers)
-    def filter_quals(quals):
-      if not qualifiers:
-        return set(quals)
-      else:
-        return set(quals) & qualifiers_set
-    endings = base_endings[cell.base_form_label]
-    if not edit_view:
-      #l_qual = set(self.lexeme.qualifiers.all()) & set(qualifiers)
-      lip_qual = filter_quals(self.qualifiers.all())
-    forms = [
-      (
-        (cell.index, self.index, ending.index),
-        (cell.prefix + self.root + separator + ending.string + cell.suffix
-        if affixes else self.root + separator + ending.string),
-        #+ '#' + cell.base_form_label.symbol,
-        combine_qualifiers(lip_qual, filter_quals(ending.qualifiers.all()))
-        if not edit_view else filter_quals(ending.qualifiers.all()),
-      )
-      for ending in endings
-    ]
-    return forms
+    lexeme = ForeignKey(Lexeme, db_column='l_id')
+    index = IntegerField(db_column='oind')
+    pattern = ForeignKey(Pattern, db_column='w_id', verbose_name=u'wzór')
+    # charakterystyka fleksyjna (rodzaj, aspekt)
+    inflection_characteristic = ForeignKey(
+        InflectionCharacteristic, db_column='charfl',
+        verbose_name=u'char. fleks.')
+    # rdzen odmiany przy zastosowaniu danego wzoru
+    root = CharField(max_length=64, db_column='rdzen')
+    # tu mozna sygnalizowac, ze dany sposob
+    # odmiany leksemu jest gorszy, przestarzaly, etc
+    qualifiers = ManyToManyField(
+        Qualifier, blank=True, db_table='kwalifikatory_odmieniasiow')
+
+    objects = LexemeNotDeletedManager()
+    all_objects = Manager()
+
+    def table_template(self, variant):
+        return TableTemplate.objects.get(
+            variant=variant, pattern_type=self.pattern.type,
+            inflection_characteristic=self.inflection_characteristic)
+
+    def cells(self, variant='1'):
+        tt = self.table_template(variant)
+        return tt.cell_set.select_related('base_form_label', 'tablecell')
+
+    def base_endings(self, label_filter=None):
+        bfls = self.pattern.type.base_form_labels()
+        endings = Ending.objects.filter(
+            base_form_label__in=bfls, pattern=self.pattern) \
+            .select_related('base_form_label').prefetch_related('qualifiers')
+        if label_filter is not None:
+            endings = endings.filter(
+                base_form_label__symbol__regex=label_filter)
+        bfl_dict = GroupDict((bfl, []) for bfl in bfls)
+        for ending in endings:
+            bfl_dict.add(ending.base_form_label, ending)
+        return bfl_dict
+
+    def inflection_table(self, variant, separated=False, qualifiers=None,
+                         edit_view=False):
+        tt = self.table_template(variant)
+        cells = self.cells(variant)
+        headers = tt.tableheader_set.all()
+        rows = set()
+        last_col = 0
+        for cell in cells:
+            rows.add(cell.tablecell.row)
+            col = cell.tablecell.col + cell.tablecell.colspan - 1
+            if col > last_col:
+                last_col = col
+        for header in headers:
+            rows.add(header.row)
+            col = header.col + header.colspan - 1
+            if col > last_col:
+                last_col = col
+        table = [[{'type': 'empty'}
+                  for i in xrange(last_col)] for j in xrange(len(rows))]
+        rows = sorted(rows)
+        # słownik: nr rzędu w bazie -> rzeczywisty numer rzędu
+        row_translate = dict(zip(rows, xrange(len(rows))))
+        base_endings = self.base_endings()
+        for cell in cells:
+            x = cell.tablecell.col - 1
+            y = row_translate[cell.tablecell.row]
+            table_cell = table[y][x]
+            assert table_cell['type'] != 'span'
+            separator = u'·' if separated else u''
+            forms = self.forms(
+                cell, base_endings, separator=separator, qualifiers=qualifiers,
+                edit_view=edit_view)
+            if not forms:
+                continue
+            if table_cell['type'] == 'empty':
+                table[y][x] = {
+                    'type': 'forms',
+                    'forms': forms,
+                    'rowspan': cell.tablecell.rowspan,
+                    'colspan': cell.tablecell.colspan,
+                }
+                for i in xrange(cell.tablecell.colspan):
+                    for j in xrange(cell.tablecell.rowspan):
+                        if (i, j) != (0, 0):
+                            assert table[y + j][x + i]['type'] == 'empty'
+                            table[y + j][x + i]['type'] = 'span'
+            else:
+                assert cell.tablecell.rowspan == table_cell['rowspan']
+                assert cell.tablecell.colspan == table_cell['colspan']
+                table_cell['forms'] += forms
+        for header in headers:
+            x = header.col - 1
+            y = row_translate[header.row]
+            assert table[y][x]['type'] == 'empty'
+            table[y][x] = {
+                'type': 'label',
+                'label': [header.label],
+                'css_class': header.css_class,
+                'rowspan': header.rowspan,
+                'colspan': header.colspan,
+            }
+            for i in xrange(header.colspan):
+                for j in xrange(header.rowspan):
+                    if (i, j) != (0, 0):
+                        assert table[y + j][x + i]['type'] == 'empty'
+                        table[y + j][x + i]['type'] = 'span'
+        return [row for row in table
+                if not all(cell['type'] == 'empty' for cell in row)]
+
+    def all_forms(self, separator='', affixes=True, label_filter=None,
+                  variant='1', qualifiers=None):
+        forms = []
+        base_endings = self.base_endings(label_filter)
+        for cell in self.cells(variant=variant):
+            forms += self.forms(
+                cell, base_endings, separator, affixes, qualifiers=qualifiers)
+        return forms
+
+    def forms(self, cell, base_endings, separator='',
+              affixes=True, qualifiers=None, edit_view=False):
+        if qualifiers:
+            qualifiers_set = set(qualifiers)
+
+        def filter_quals(quals):
+            if not qualifiers:
+                return set(quals)
+            else:
+                return set(quals) & qualifiers_set
+
+        endings = base_endings[cell.base_form_label]
+        if not edit_view:
+            #l_qual = set(self.lexeme.qualifiers.all()) & set(qualifiers)
+            lip_qual = filter_quals(self.qualifiers.all())
+        forms = [
+            (
+                (cell.index, self.index, ending.index),
+                (
+                cell.prefix + self.root + separator + ending.string + cell.suffix
+                if affixes else self.root + separator + ending.string),
+                #+ '#' + cell.base_form_label.symbol,
+                combine_qualifiers(lip_qual,
+                                   filter_quals(ending.qualifiers.all()))
+                if not edit_view else filter_quals(ending.qualifiers.all()),
+            )
+            for ending in endings
+        ]
+        return forms
+
+    def editable_vocabularies(self, user):
+        return self.lexeme.editable_vocabularies(user)
+
+    def __unicode__(self):
+        return '%s : %s/%s : %s' % (
+            self.lexeme.entry,
+            self.pattern.name,
+            self.pattern.type.symbol,
+            self.inflection_characteristic.symbol,
+        )
+
+    class Meta:
+        db_table = 'odmieniasie'
+        unique_together = ('lexeme', 'index')
+        ordering = ['index']
 
-  def editable_vocabularies(self, user):
-    return self.lexeme.editable_vocabularies(user)
-
-  def __unicode__(self):
-    return '%s : %s/%s : %s' % (
-      self.lexeme.entry,
-      self.pattern.name,
-      self.pattern.type.symbol,
-      self.inflection_characteristic.symbol,
-    )
-
-  class Meta:
-    db_table = 'odmieniasie'
-    unique_together = ('lexeme', 'index')
-    ordering = ['index']
 
 def all_forms(pattern, ic, pos, base, variant='1', affixes=True):
-  root = get_root(base, pos, pattern, ic)
-  tt = TableTemplate.objects.get(
-    variant=variant, pattern_type=pattern.type, inflection_characteristic=ic)
-  forms = set()
-  for cell in tt.cell_set.all():
-    endings = Ending.objects.filter(
-      base_form_label=cell.base_form_label, pattern=pattern)
-    forms |= set(
-      cell.prefix + root + ending.string + cell.suffix
-      if affixes else root + ending.string
-      for ending in endings)
-  return forms
+    root = get_root(base, pos, pattern, ic)
+    tt = TableTemplate.objects.get(
+        variant=variant, pattern_type=pattern.type,
+        inflection_characteristic=ic)
+    forms = set()
+    for cell in tt.cell_set.all():
+        endings = Ending.objects.filter(
+            base_form_label=cell.base_form_label, pattern=pattern)
+        forms |= set(
+            cell.prefix + root + ending.string + cell.suffix
+            if affixes else root + ending.string
+            for ending in endings)
+    return forms
+
 
 def combine_qualifiers(lip_qualifiers, e_qualifiers):
-  #qualifiers = set(l_qualifiers)
-  qualifiers = set()
-  for q in list(lip_qualifiers) + list(e_qualifiers):
-    if q.exclusion_class:
-      excluded = set(q.exclusion_class.qualifier_set.all())
-      qualifiers -= excluded
-    qualifiers.add(q)
-  return qualifiers
+    #qualifiers = set(l_qualifiers)
+    qualifiers = set()
+    for q in list(lip_qualifiers) + list(e_qualifiers):
+        if q.exclusion_class:
+            excluded = set(q.exclusion_class.qualifier_set.all())
+            qualifiers -= excluded
+        qualifiers.add(q)
+    return qualifiers
+
 
 def filter_visible_lips(lips, user):
-  vocabs = visible_vocabularies(user)
-  return lips.filter(lexeme__vocabularies__in=vocabs).distinct()
+    vocabs = visible_vocabularies(user)
+    return lips.filter(lexeme__vocabularies__in=vocabs).distinct()
 
 
 # Sluzy do doczepienia flag do poszczegolnych form
@@ -804,278 +836,296 @@ def filter_visible_lips(lips, user):
 
 
 class Vocabulary(Model):
-  id = CharField(max_length=64, primary_key=True, db_column='slownik')
-  lexemes = ManyToManyField(Lexeme, blank=True, through='LexemeAssociation',
-                            related_name='vocabularies')
-  managers = ManyToManyField(User, blank=True,
-                             related_name='managed_vocabularies')
-  viewers = ManyToManyField(User, blank=True,
-                            related_name='visible_vocabularies')
-  editors = ManyToManyField(User, blank=True,
-                            related_name='editable_vocabularies')
-  # bardziej by pasowało w Classification, ale już trudno
-  classifications = ManyToManyField(Classification, blank=True,
-                                    related_name='vocabularies')
-
-  def owned_lexemes_pk(self):
-    return self.owned_lexemes.values_list('pk', flat=True)
-
-  def all_viewers(self):
-    perm = Permission.objects.get(codename='view_all_lexemes')
-    return self.viewers.all().distinct() | users_with_perm(perm)
-
-  def all_editors(self):
-    return self.editors.all()
-
-  def all_managers(self):
-    perm = Permission.objects.get(codename='manage_all_vocabularies')
-    return self.managers.all().distinct() | users_with_perm(perm)
-
-  def add_lexeme(self, lexeme):
-    la, created = LexemeAssociation.objects.get_or_create(
-      lexeme=lexeme, vocabulary=self)
-    return created
-
-  def remove_lexeme(self, lexeme):
-    assert self != lexeme.owner_vocabulary
-    LexemeAssociation.objects.filter(lexeme=lexeme, vocabulary=self).delete()
-
-  def set_lexeme(self, lexeme, add):
-    if add:
-      self.add_lexeme(lexeme)
-    else:
-      self.remove_lexeme(lexeme)
+    id = CharField(max_length=64, primary_key=True, db_column='slownik')
+    lexemes = ManyToManyField(Lexeme, blank=True, through='LexemeAssociation',
+                              related_name='vocabularies')
+    managers = ManyToManyField(User, blank=True,
+                               related_name='managed_vocabularies')
+    viewers = ManyToManyField(User, blank=True,
+                              related_name='visible_vocabularies')
+    editors = ManyToManyField(User, blank=True,
+                              related_name='editable_vocabularies')
+    # bardziej by pasowało w Classification, ale już trudno
+    classifications = ManyToManyField(Classification, blank=True,
+                                      related_name='vocabularies')
+
+    def owned_lexemes_pk(self):
+        return self.owned_lexemes.values_list('pk', flat=True)
+
+    def all_viewers(self):
+        perm = Permission.objects.get(codename='view_all_lexemes')
+        return self.viewers.all().distinct() | users_with_perm(perm)
+
+    def all_editors(self):
+        return self.editors.all()
+
+    def all_managers(self):
+        perm = Permission.objects.get(codename='manage_all_vocabularies')
+        return self.managers.all().distinct() | users_with_perm(perm)
+
+    def add_lexeme(self, lexeme):
+        la, created = LexemeAssociation.objects.get_or_create(
+            lexeme=lexeme, vocabulary=self)
+        return created
+
+    def remove_lexeme(self, lexeme):
+        assert self != lexeme.owner_vocabulary
+        LexemeAssociation.objects.filter(lexeme=lexeme,
+                                         vocabulary=self).delete()
+
+    def set_lexeme(self, lexeme, add):
+        if add:
+            self.add_lexeme(lexeme)
+        else:
+            self.remove_lexeme(lexeme)
+
+    def __unicode__(self):
+        return self.id
+
+    class Meta:
+        db_table = 'slowniki'
+        permissions = (
+            ('manage_vocabulary', u'Może zarządzać słownikami'),
+            ('manage_all_vocabularies', u'Zarządza wszystkimi słownikami'),
+        )
 
-  def __unicode__(self):
-    return self.id
-
-  class Meta:
-    db_table = 'slowniki'
-    permissions = (
-      ('manage_vocabulary', u'Może zarządzać słownikami'),
-      ('manage_all_vocabularies', u'Zarządza wszystkimi słownikami'),
-    )
 
 def visible_vocabularies(user):
-  if user.has_perm('dictionary.view_all_lexemes'):
-    return Vocabulary.objects.all()
-  else:
-    return user.visible_vocabularies.all()
+    if user.has_perm('dictionary.view_all_lexemes'):
+        return Vocabulary.objects.all()
+    else:
+        return user.visible_vocabularies.all()
+
 
 def editable_vocabularies(user):
-  return user.editable_vocabularies.all()
+    return user.editable_vocabularies.all()
+
 
 def readonly_vocabularies(user):
-  return visible_vocabularies(user).exclude(
-    id__in=editable_vocabularies(user))
+    return visible_vocabularies(user).exclude(
+        id__in=editable_vocabularies(user))
+
 
 def managed_vocabularies(user):
-  if user.has_perm('dictionary.manage_all_vocabularies'):
-    return Vocabulary.objects.all()
-  else:
-    return user.managed_vocabularies.all()
+    if user.has_perm('dictionary.manage_all_vocabularies'):
+        return Vocabulary.objects.all()
+    else:
+        return user.managed_vocabularies.all()
+
 
 class LexemeAssociation(Model):
-  lexeme = ForeignKey(Lexeme, db_column='l_id')
-  vocabulary = ForeignKey(Vocabulary, db_column='slownik')
+    lexeme = ForeignKey(Lexeme, db_column='l_id')
+    vocabulary = ForeignKey(Vocabulary, db_column='slownik')
 
-  objects = LexemeNotDeletedManager()
-  all_objects = Manager()
+    objects = LexemeNotDeletedManager()
+    all_objects = Manager()
 
-  def __unicode__(self):
-    return '%s/%s' % (self.lexeme.entry, self.vocabulary.id)
+    def __unicode__(self):
+        return '%s/%s' % (self.lexeme.entry, self.vocabulary.id)
 
-  class Meta:
-    db_table = 'leksemy_w_slownikach'
-    unique_together = ['lexeme', 'vocabulary']
+    class Meta:
+        db_table = 'leksemy_w_slownikach'
+        unique_together = ['lexeme', 'vocabulary']
 
 
 class CrossReferenceType(Model):
-  symbol = CharField(max_length=10, db_column='typods')
-  desc = CharField(max_length=40, db_column='naglowek')
-  index = IntegerField(db_column='kolejnosc')
-  from_pos = ForeignKey(
-    PartOfSpeech, db_column='pos1', related_name='crtype_to')
-  to_pos = ForeignKey(
-    PartOfSpeech, db_column='pos2', related_name='crtype_from')
-  #reverse = ForeignKey('self', db_column='odwrotny')
+    symbol = CharField(max_length=10, db_column='typods')
+    desc = CharField(max_length=40, db_column='naglowek')
+    index = IntegerField(db_column='kolejnosc')
+    from_pos = ForeignKey(
+        PartOfSpeech, db_column='pos1', related_name='crtype_to')
+    to_pos = ForeignKey(
+        PartOfSpeech, db_column='pos2', related_name='crtype_from')
+    #reverse = ForeignKey('self', db_column='odwrotny')
 
-  def __unicode__(self):
-    return self.symbol
+    def __unicode__(self):
+        return self.symbol
 
-  class Meta:
-    db_table = 'typyodsylaczy'
+    class Meta:
+        db_table = 'typyodsylaczy'
 
 
 class CRManager(Manager):
-  use_for_related_field = True
+    use_for_related_field = True
+
+    def get_query_set(self):
+        return super(CRManager, self).get_query_set().filter(
+            from_lexeme__deleted=False, to_lexeme__deleted=False)
 
-  def get_query_set(self):
-    return super(CRManager, self).get_query_set().filter(
-      from_lexeme__deleted=False, to_lexeme__deleted=False)
 
 class CrossReference(Model):
-  from_lexeme = ForeignKey(Lexeme, db_column='l_id_od', related_name='refs_to')
-  to_lexeme = ForeignKey(
-    Lexeme, db_column='l_id_do', related_name='refs_from',
-    verbose_name=u'nr docelowy')
-  type = ForeignKey(
-    CrossReferenceType, db_column='typods_id', verbose_name=u'typ')
+    from_lexeme = ForeignKey(Lexeme, db_column='l_id_od',
+                             related_name='refs_to')
+    to_lexeme = ForeignKey(
+        Lexeme, db_column='l_id_do', related_name='refs_from',
+        verbose_name=u'nr docelowy')
+    type = ForeignKey(
+        CrossReferenceType, db_column='typods_id', verbose_name=u'typ')
 
-  objects = CRManager()
-  all_objects = Manager()
+    objects = CRManager()
+    all_objects = Manager()
 
-  def __unicode__(self):
-    return '%s: %s -> %s' % (
-      self.type.symbol, self.from_lexeme.entry, self.to_lexeme.entry)
+    def __unicode__(self):
+        return '%s: %s -> %s' % (
+            self.type.symbol, self.from_lexeme.entry, self.to_lexeme.entry)
 
-  class Meta:
-    db_table = 'odsylacze'
+    class Meta:
+        db_table = 'odsylacze'
 
 
 class Variant(Model):
-  id = CharField(max_length=32, primary_key=True, db_column='wariant')
+    id = CharField(max_length=32, primary_key=True, db_column='wariant')
+
+    def __unicode__(self):
+        return self.id
 
-  def __unicode__(self):
-    return self.id
+    class Meta:
+        db_table = 'warianty'
 
-  class Meta:
-    db_table = 'warianty'
 
 class TableTemplate(Model):
-  variant = ForeignKey(Variant, db_column='wariant')
-  pattern_type = ForeignKey(PatternType, db_column='wtyp')
-  inflection_characteristic = ForeignKey(
-    InflectionCharacteristic, db_column='charfl')
+    variant = ForeignKey(Variant, db_column='wariant')
+    pattern_type = ForeignKey(PatternType, db_column='wtyp')
+    inflection_characteristic = ForeignKey(
+        InflectionCharacteristic, db_column='charfl')
 
-  def __unicode__(self):
-    return '%s : %s : %s : %s' % (
-      self.variant, self.inflection_characteristic.part_of_speech,
-      self.pattern_type.symbol, self.inflection_characteristic)
+    def __unicode__(self):
+        return '%s : %s : %s : %s' % (
+            self.variant, self.inflection_characteristic.part_of_speech,
+            self.pattern_type.symbol, self.inflection_characteristic)
 
-  class Meta:
-    db_table = 'szablony_tabel'
+    class Meta:
+        db_table = 'szablony_tabel'
 
 #klatka paradygmatu
 #(element szablonu tabelki odmiany)
 class Cell(Model):
-  table_template = ForeignKey(TableTemplate, db_column='st_id')
-  #etykieta formy bazowej
-  base_form_label = ForeignKey(BaseFormLabel, db_column='efobaz')
-  #znacznik docelowego tagsetu
-  tag = TextField(blank=True, db_column='tag')
-  prefix = CharField(max_length=20, blank=True, db_column='prefiks')
-  suffix = CharField(max_length=20, blank=True, db_column='sufiks')
-  #kolejnosc klatki w paradygmacie
-  index = IntegerField(db_column='kind')
-
-  def __unicode__(self):
-    return '%s [%s] %s- -%s {%s}' % (
-      self.table_template, self.base_form_label, self.prefix, self.suffix,
-      self.tag)
-
-  class Meta:
-    db_table = 'klatki'
-    ordering = ['index']
+    table_template = ForeignKey(TableTemplate, db_column='st_id')
+    #etykieta formy bazowej
+    base_form_label = ForeignKey(BaseFormLabel, db_column='efobaz')
+    #znacznik docelowego tagsetu
+    tag = TextField(blank=True, db_column='tag')
+    prefix = CharField(max_length=20, blank=True, db_column='prefiks')
+    suffix = CharField(max_length=20, blank=True, db_column='sufiks')
+    #kolejnosc klatki w paradygmacie
+    index = IntegerField(db_column='kind')
+
+    def __unicode__(self):
+        return '%s [%s] %s- -%s {%s}' % (
+            self.table_template, self.base_form_label, self.prefix, self.suffix,
+            self.tag)
+
+    class Meta:
+        db_table = 'klatki'
+        ordering = ['index']
+
 
 class TableCell(Model):
-  cell = OneToOneField(Cell, db_column='k_id')
-  row = IntegerField()
-  col = IntegerField()
-  rowspan = IntegerField()
-  colspan = IntegerField()
+    cell = OneToOneField(Cell, db_column='k_id')
+    row = IntegerField()
+    col = IntegerField()
+    rowspan = IntegerField()
+    colspan = IntegerField()
+
+    def __unicode__(self):
+        return '%s [%s->%s,%s->%s]' % (
+            self.cell, self.row, self.rowspan, self.col, self.colspan)
 
-  def __unicode__(self):
-    return '%s [%s->%s,%s->%s]' % (
-      self.cell, self.row, self.rowspan, self.col, self.colspan)
+    class Meta:
+        db_table = 'komorki_tabel'
 
-  class Meta:
-    db_table = 'komorki_tabel'
 
 class TableHeader(Model):
-  table_template = ForeignKey(TableTemplate, db_column='st_id')
-  row = IntegerField()
-  col = IntegerField()
-  rowspan = IntegerField()
-  colspan = IntegerField()
-  label = CharField(max_length=64, blank=True, db_column='nagl')
-  css_class = CharField(max_length=8, db_column='styl')
+    table_template = ForeignKey(TableTemplate, db_column='st_id')
+    row = IntegerField()
+    col = IntegerField()
+    rowspan = IntegerField()
+    colspan = IntegerField()
+    label = CharField(max_length=64, blank=True, db_column='nagl')
+    css_class = CharField(max_length=8, db_column='styl')
 
-  def __unicode__(self):
-    return '%s (%s,%s) [%s]' % (
-      self.label, self.row, self.col, self.css_class)
+    def __unicode__(self):
+        return '%s (%s,%s) [%s]' % (
+            self.label, self.row, self.col, self.css_class)
 
-  class Meta:
-    db_table = 'naglowki_tabel'
+    class Meta:
+        db_table = 'naglowki_tabel'
 
 # na szybko i brudno
 class ParadygmatyWSJP(Model):
-  wariant = CharField(max_length=4)
-  typr = ForeignKey(PatternType, db_column='typr')
-  charfl = ForeignKey(InflectionCharacteristic, db_column='charfl')
-  podparad = CharField(max_length=4, blank=True)
-  row = IntegerField()
-  col = IntegerField()
-  rowspan = IntegerField()
-  colspan = IntegerField()
-  efobaz = ForeignKey(BaseFormLabel, db_column='efobaz')
-  morf = TextField()
-  pref = CharField(max_length=20, blank=True)
-  suf = CharField(max_length=20, blank=True)
-  kskl = IntegerField()
-
-  class Meta:
-    db_table = 'paradygmatywsjp'
+    wariant = CharField(max_length=4)
+    typr = ForeignKey(PatternType, db_column='typr')
+    charfl = ForeignKey(InflectionCharacteristic, db_column='charfl')
+    podparad = CharField(max_length=4, blank=True)
+    row = IntegerField()
+    col = IntegerField()
+    rowspan = IntegerField()
+    colspan = IntegerField()
+    efobaz = ForeignKey(BaseFormLabel, db_column='efobaz')
+    morf = TextField()
+    pref = CharField(max_length=20, blank=True)
+    suf = CharField(max_length=20, blank=True)
+    kskl = IntegerField()
+
+    class Meta:
+        db_table = 'paradygmatywsjp'
+
 
 class LexemeForm(Model):
-  lexeme = ForeignKey(Lexeme)
-  form = CharField(max_length=128, db_index=True)
+    lexeme = ForeignKey(Lexeme)
+    form = CharField(max_length=128, db_index=True)
+
+    objects = LexemeNotDeletedManager()
+    all_objects = Manager()
 
-  objects = LexemeNotDeletedManager()
-  all_objects = Manager()
 
 class SavedFilter(Model):
-  serialized_filter = TextField()
-  name = CharField(max_length=64)
-  user = ForeignKey(User)
+    serialized_filter = TextField()
+    name = CharField(max_length=64)
+    user = ForeignKey(User)
+
+    class Meta:
+        unique_together = ('name', 'user')
 
-  class Meta:
-    unique_together = ('name', 'user')
 
 class SavedExportData(Model):
-  serialized_data = TextField()
-  name = CharField(max_length=64, unique=True)
+    serialized_data = TextField()
+    name = CharField(max_length=64, unique=True)
 
 # model przeznaczony tylko do odczytu!
 class History(Model):
-  table_name = CharField(max_length=120, db_column='table_name_')
-  column_name = CharField(max_length=120, db_column='column_name_', blank=True)
-  timestamp = DateTimeField(db_column='timestamp_')
-  user = ForeignKey(User, db_column='user_id_', db_index=True)
-  old_value = TextField(db_column='old_value_', blank=True)
-  new_value = TextField(db_column='new_value_', blank=True)
-  lexeme = ForeignKey(
-    Lexeme, db_column='lexeme_id_', null=True, blank=True, db_index=True)
-  pattern = ForeignKey(
-    Pattern, db_column='pattern_id_', null=True, blank=True, db_index=True)
-  row_id = IntegerField(db_column='id_')
-  operation = CharField(max_length=120, db_column='operation_')
-  table_oid = IntegerField(db_column='table_oid_')
-  column_ord = IntegerField(db_column='ordinal_position_of_column_')
-  transaction_began = DateTimeField(db_column='transaction_began_')
-
-  def __unicode__(self):
-    return '%s %s.%s %s -> %s' % (
-      self.operation, self.table_name, self.column_name, repr(self.old_value),
-      repr(self.new_value))
-
-  class Meta:
-    db_table = 'history'
+    table_name = CharField(max_length=120, db_column='table_name_')
+    column_name = CharField(max_length=120, db_column='column_name_',
+                            blank=True)
+    timestamp = DateTimeField(db_column='timestamp_')
+    user = ForeignKey(User, db_column='user_id_', db_index=True)
+    old_value = TextField(db_column='old_value_', blank=True)
+    new_value = TextField(db_column='new_value_', blank=True)
+    lexeme = ForeignKey(
+        Lexeme, db_column='lexeme_id_', null=True, blank=True, db_index=True)
+    pattern = ForeignKey(
+        Pattern, db_column='pattern_id_', null=True, blank=True, db_index=True)
+    row_id = IntegerField(db_column='id_')
+    operation = CharField(max_length=120, db_column='operation_')
+    table_oid = IntegerField(db_column='table_oid_')
+    column_ord = IntegerField(db_column='ordinal_position_of_column_')
+    transaction_began = DateTimeField(db_column='transaction_began_')
+
+    def __unicode__(self):
+        return '%s %s.%s %s -> %s' % (
+            self.operation, self.table_name, self.column_name,
+            repr(self.old_value),
+            repr(self.new_value))
+
+    class Meta:
+        db_table = 'history'
+
 
 class InputLexeme(Model):
-  entry = CharField(max_length=64, db_index=True)
+    entry = CharField(max_length=64, db_index=True)
+
 
 class InputForm(Model):
-  input_lexeme = ForeignKey(InputLexeme)
-  form = CharField(max_length=64, db_index=True)
-  #tag = TextField()
+    input_lexeme = ForeignKey(InputLexeme)
+    form = CharField(max_length=64, db_index=True)
+    #tag = TextField()
diff --git a/dictionary/pagination_types.py b/dictionary/pagination_types.py
index 9e7cd8d..bfc2f6e 100644
--- a/dictionary/pagination_types.py
+++ b/dictionary/pagination_types.py
@@ -7,70 +7,77 @@ from dictionary.models import History, Lexeme, filter_visible
 
 types = {}
 
+
 def lexeme_history_list(params, user):
-  objects = History.objects.exclude(lexeme=None).distinct().values(
-    'lexeme', 'user', 'transaction_began')
-  lexemes = filter_visible(Lexeme.all_objects, user).exclude(entry='')
-  for field, lookup, value in params['filters']:
-    if field == 'user':
-      if lookup == 'eq':
-        objects = objects.filter(user__pk=value)
-      elif lookup == 'ne':
-        objects = objects.exclude(user__username=value)
-    if field == 'time':
-      try:
-        date = datetime.strptime(value, '%d.%m.%Y')
-        if lookup == 'from':
-          objects = objects.filter(transaction_began__gte=date)
-        elif lookup == 'to':
-          objects = objects.filter(transaction_began__lte=date)
-      except ValueError:
-        pass
-
-  objects = objects.filter(lexeme__in=lexemes)
-  objects = objects.order_by(params['order_by'])
-  return objects
+    objects = History.objects.exclude(lexeme=None).distinct().values(
+        'lexeme', 'user', 'transaction_began')
+    lexemes = filter_visible(Lexeme.all_objects, user).exclude(entry='')
+    for field, lookup, value in params['filters']:
+        if field == 'user':
+            if lookup == 'eq':
+                objects = objects.filter(user__pk=value)
+            elif lookup == 'ne':
+                objects = objects.exclude(user__username=value)
+        if field == 'time':
+            try:
+                date = datetime.strptime(value, '%d.%m.%Y')
+                if lookup == 'from':
+                    objects = objects.filter(transaction_began__gte=date)
+                elif lookup == 'to':
+                    objects = objects.filter(transaction_began__lte=date)
+            except ValueError:
+                pass
+
+    objects = objects.filter(lexeme__in=lexemes)
+    objects = objects.order_by(params['order_by'])
+    return objects
+
 
 class LexemeFilterFieldForm(Form):
-  field = ChoiceField(
-    choices=[], label=u'', widget=Select(attrs={'class': 'field-choice'}))
+    field = ChoiceField(
+        choices=[], label=u'', widget=Select(attrs={'class': 'field-choice'}))
+
+    def __init__(self, **kwargs):
+        super(LexemeFilterFieldForm, self).__init__(**kwargs)
+        filters = LEXEME_HISTORY_FILTERS
+        choices = [(key, value[0]) for key, value in filters.iteritems()]
+        self.fields['field'].choices = choices
 
-  def __init__(self, **kwargs):
-    super(LexemeFilterFieldForm, self).__init__(**kwargs)
-    filters = LEXEME_HISTORY_FILTERS
-    choices = [(key, value[0]) for key, value in filters.iteritems()]
-    self.fields['field'].choices = choices
 
 class UserFilterForm(Form):
-  user = ModelChoiceField(
-    queryset=User.objects.order_by('username'), label=u'',
-    widget=Select(attrs={'class': 'value'}))
+    user = ModelChoiceField(
+        queryset=User.objects.order_by('username'), label=u'',
+        widget=Select(attrs={'class': 'value'}))
+
 
 class TimeFilterForm(Form):
-  time = DateField(input_formats=['%d.%m.%Y'], label=u'',
-    widget=DateInput(attrs={'class': 'datepicker value'}))
+    time = DateField(input_formats=['%d.%m.%Y'], label=u'',
+                     widget=DateInput(attrs={'class': 'datepicker value'}))
+
 
 LEXEME_HISTORY_FILTERS = {
-  'user': (
-    u'Użytkownik',
-    [('eq', u'równy')],
-    UserFilterForm,
-  ),
-  'time': (
-    u'Data',
-    [('from', u'od'), ('to', u'do')],
-    TimeFilterForm,
-  ),
+    'user': (
+        u'Użytkownik',
+        [('eq', u'równy')],
+        UserFilterForm,
+    ),
+    'time': (
+        u'Data',
+        [('from', u'od'), ('to', u'do')],
+        TimeFilterForm,
+    ),
 }
 
+
 def dummy_perm(user, object, action):
-  return True
+    return True
+
 
 types['lexeme_history'] = (
-  lexeme_history_list,
-  'lexeme_history_item.html',
-  dummy_perm,
-  {},
-  LEXEME_HISTORY_FILTERS,
-  LexemeFilterFieldForm,
+    lexeme_history_list,
+    'lexeme_history_item.html',
+    dummy_perm,
+    {},
+    LEXEME_HISTORY_FILTERS,
+    LexemeFilterFieldForm,
 )
\ No newline at end of file
diff --git a/dictionary/pattern_blacklist.py b/dictionary/pattern_blacklist.py
index b30c993..3c736a8 100644
--- a/dictionary/pattern_blacklist.py
+++ b/dictionary/pattern_blacklist.py
@@ -1,498 +1,498 @@
 #-*- coding:utf-8 -*-
 
 blacklist = [
-u"0001!",
-u"0001#",
-u"0001'q",
-u"0001'qu",
-u"0001'u",
-u"0001U'",
-u"0001U'v",
-u"0001o@",
-u"0001q",
-u"0001qU'",
-u"0001qU'v",
-u"0001qv",
-u"0002&",
-u"0005ź",
-u"0006!",
-u"0006r",
-u"0006ru",
-u"0007a",
-u"0008<",
-u"0010!",
-u"0010#",
-u"0010#u",
-u"0010'S",
-u"0010C'u",
-u"0010Hu",
-u"0010Xv",
-u"0010cl?",
-u"0010f",
-u"0010h",
-u"0010ig",
-u"0010l",
-u"0010oi",
-u"0010ph",
-u"0010u@",
-u"0010ug",
-u"0010ą",
-u"0010ē",
-u"0010ś",
-u"0011!",
-u"0011'u",
-u"0011-",
-u"0011@",
-u"0011H",
-u"0011e",
-u"0011u!",
-u"0011ue",
-u"0011ź",
-u"0012i",
-u"0012o",
-u"0012v",
-u"0013'S",
-u"0013-",
-u"0013Su",
-u"0013U'",
-u"0013hu",
-u"0013ov",
-u"0013oy",
-u"0013u@",
-u"0013v",
-u"0014#u",
-u"0014%",
-u"0014'S",
-u"0014'hS",
-u"0014-",
-u"0014>",
-u"0014Sś'",
-u"0014agarcie",
-u"0014c<",
-u"0014ci",
-u"0014h'",
-u"0014i'",
-u"0014iT",
-u"0014ocie",
-u"0014owi",
-u"0014ś'",
-u"0014śo",
-u"0015o",
-u"0016",
-u"0016c",
-u"0018",
-u"0019c",
-u"0021ci",
-u"0023u",
-u"0023śu",
-u"0023ź",
-u"0023źi",
-u"0024",
-u"0024u",
-u"0026K",
-u"0026Ku",
-u"0027",
-u"0027c",
-u"0028u",
-u"0028śu",
-u"0029(c)",
-u"0029c",
-u"0029u",
-u"0030",
-u"0030u",
-u"0031",
-u"0032",
-u"0032#u",
-u"0032u",
-u"0033",
-u"0033?",
-u"0035?",
-u"0037ue",
-u"0038e",
-u"0038ue",
-u"0039b",
-u"0039bu",
-u"0039y",
-u"0040",
-u"0042",
-u"0046",
-u"0046u",
-u"0047ń",
-u"0048!y",
-u"0048#",
-u"0048=-",
-u"0048oo!",
-u"0049v",
-u"0049vv",
-u"0049vvv",
-u"0050(!)",
-u"0050v",
-u"0051(jer)",
-u"0051u",
-u"0051w",
-u"0052g",
-u"0052w",
-u"0053!",
-u"0054v",
-u"0055c!",
-u"0055g",
-u"0058w",
-u"0059",
-u"0059w",
-u"0060",
-u"0060+",
-u"0062",
-u"0063",
-u"0063c<",
-u"0063g",
-u"0064#",
-u"0064'u",
-u"0064-",
-u"0064g",
-u"0064g'",
-u"0064o",
-u"0064og",
-u"0064oń",
-u"0064v'",
-u"0066w",
-u"0066ó",
-u"0067Y=",
-u"0069$",
-u"0069Yw",
-u"0072g",
-u"0074g",
-u"0074u",
-u"0075u",
-u"0075w",
-u"0076#",
-u"0076*zi",
-u"0076wg",
-u"0076za",
-u"0076zi",
-u"0076ć",
-u"0076ćg",
-u"0076śg",
-u"0077",
-u"0078w",
-u"0078wg",
-u"0080u",
-u"0081g",
-u"0082",
-u"0082m",
-u"0083wg",
-u"0083ź",
-u"0084hw",
-u"0085K",
-u"0086",
-u"0087K",
-u"0087śu",
-u"0089",
-u"0091",
-u"0091#",
-u"0092H",
-u"0092g",
-u"0092hh",
-u"0092n",
-u"0092o",
-u"0093h",
-u"0093x",
-u"0094o",
-u"0095dz",
-u"0096i",
-u"0096ow",
-u"0096owv",
-u"0096owś",
-u"0096łw",
-u"0097i",
-u"0098(rr)",
-u"0098h",
-u"0098ow",
-u"0099_",
-u"0099eś",
-u"0099h",
-u"0099hw",
-u"0099o",
-u"0099oś",
-u"0100",
-u"0100d",
-u"0101ź",
-u"0102ś",
-u"0103",
-u"0106",
-u"0107 (IE)",
-u"0107ś?",
-u"0110",
-u"0112",
-u"0113",
-u"0115",
-u"0116",
-u"0119",
-u"0121",
-u"0123#",
-u"0129?",
-u"0129o",
-u"0131",
-u"0132",
-u"0132g2",
-u"0133g2",
-u"0134",
-u"0135g-",
-u"0136(IE)g2",
-u"0137",
-u"0137g2",
-u"0138o",
-u"0139",
-u"0140!",
-u"0143",
-u"0145g2",
-u"0145tg2",
-u"0145w",
-u"0145zg2",
-u"0146H",
-u"0146Yw",
-u"0147g2",
-u"0150#",
-u"0151",
-u"0152",
-u"0153",
-u"0154",
-u"0155i",
-u"0156m",
-u"0156ó",
-u"0157",
-u"0158i",
-u"0159(IE)",
-u"0159E",
-u"0159i",
-u"0160im",
-u"0160v",
-u"0161#",
-u"0161E",
-u"0162",
-u"0162i",
-u"0164Ó",
-u"0166",
-u"0168",
-u"0169",
-u"0169m",
-u"0170",
-u"0171#",
-u"0171##",
-u"0171KK",
-u"0171Ku",
-u"0171gc",
-u"0172#",
-u"0172##",
-u"0173#",
-u"0173og",
-u"0174u",
-u"0175",
-u"0177",
-u"0178",
-u"0180eź",
-u"0180g",
-u"0181ś",
-u"0181ź",
-u"0181źv",
-u"0182źg",
-u"0183g",
-u"0183ó",
-u"0184^",
-u"0184e",
-u"0185",
-u"0185ź",
-u"0186M",
-u"0186e",
-u"0186lź",
-u"0187ć",
-u"0187ś",
-u"0187śv",
-u"0189e",
-u"0190",
-u"0191",
-u"0191+",
-u"0193",
-u"0194#",
-u"0196#",
-u"0197",
-u"0199#",
-u"0201",
-u"0201ł",
-u"0203",
-u"0204",
-u"0Nom'",
-u"A",
-u"A'",
-u"A''",
-u"A'''",
-u"A700'/ky",
-u"A700/L",
-u"A700/ij",
-u"A700/oj",
-u"A700/sz",
-u"A700/yj",
-u"A700R<v",
-u"A700RS",
-u"A701RS",
-u"A701ReS",
-u"A703P",
-u"A703Ż",
-u"A708P",
-u"A708R<",
-u"A708R<v",
-u"A711N",
-u"A716+",
-u"A716ś",
-u"A716ź",
-u"A717+",
-u"A717D",
-u"A718ź",
-u"A721",
-u"A722Ż#",
-u"A729",
-u"IXc'*1",
-u"IXc'*2",
-u"IXcYYYY",
-u"La1",
-u"La11",
-u"Lb1",
-u"Lb3",
-u"Lc2",
-u"Lc2a",
-u"Lc2c",
-u"Lc2o",
-u"Lc3",
-u"Lc4",
-u"Ld007",
-u"Ld008",
-u"Ld00K",
-u"Ld00P",
-u"Ld012",
-u"Ld01P",
-u"Ld020",
-u"Ld030",
-u"Ld0K0",
-u"Ld0P0",
-u"Ld0W0",
-u"Ld100",
-u"Ld200",
-u"Ld300",
-u"Ld500",
-u"Ld700",
-u"Ld800",
-u"LdK00",
-u"LdP00",
-u"LdW00",
-u"LdX1",
-u"LdX11",
-u"LdX2",
-u"LdX3",
-u"LdX4",
-u"Ldkr2",
-u"Ldkr3",
-u"Ldkr5",
-u"Ldkr7",
-u"Ldkr8",
-u"P02",
-u"P03",
-u"P05",
-u"P06",
-u"P09",
-u"P10",
-u"P14",
-u"P24",
-u"P26",
-u"P27",
-u"P29",
-u"P33",
-u"P34",
-u"P35",
-u"P36",
-u"P40",
-u"P42",
-u"P44",
-u"P45",
-u"P46",
-u"P48",
-u"P49",
-u"P50",
-u"P51",
-u"P52",
-u"P54",
-u"P55",
-u"P56",
-u"P57",
-u"P58",
-u"P59",
-u"P61",
-u"P62",
-u"P64",
-u"P65",
-u"P66",
-u"P67",
-u"P70",
-u"P74",
-u"P75",
-u"Pdef1",
-u"Pdef2",
-u"VIIaY",
-u"XIIId'Y",
-u"XIIId'Y*1",
-u"XIIId'YY*1",
-u"XIIId*4",
-u"XIIId*5",
-u"XIIId*6",
-u"XIIId*7",
-u"XIIId*8",
-u"XIIIe*1",
-u"XIIIe*2",
-u"XIIIf''''*1",
-u"XIIIh'",
-u"XIIc'''*2",
-u"XIIc'''*3",
-u"XIIc'''*4",
-u"XIIc''*2",
-u"XIIc'*3",
-u"XIIc'*4",
-u"XIIc'*5",
-u"XIIc*2",
-u"XIIc*3",
-u"XIIc*4",
-u"XId*2",
-u"XId*3",
-u"XId*4",
-u"Zap1",
-u"Zap2",
-u"Zap3",
-u"Zas1",
-u"Zas1(ciś)",
-u"Zas1(kol)",
-u"Zas1(si)",
-u"Zas1(sik)",
-u"Zas1(siś)",
-u"Zas1(ś)",
-u"Zas1(ściś)",
-u"Zas1(śkol)",
-u"Zas1(że)",
-u"Zas2",
-u"Zas2(kol)",
-u"Zas3",
-u"Zas5",
-u"Zas6",
-u"Zas7",
-u"Zas7(kol)",
-u"Zas7(ś)",
-u"Zas7(śkol)",
-u"Zas8",
-u"Zas8(kol)",
-u"Zas9",
-u"Zb1",
-u"Zb2",
-u"Zb3",
-u"Zc",
-u"v6",
-u"v7",
-u"v7''",
-u"v8Y",
-u"x1'",
+    u"0001!",
+    u"0001#",
+    u"0001'q",
+    u"0001'qu",
+    u"0001'u",
+    u"0001U'",
+    u"0001U'v",
+    u"0001o@",
+    u"0001q",
+    u"0001qU'",
+    u"0001qU'v",
+    u"0001qv",
+    u"0002&",
+    u"0005ź",
+    u"0006!",
+    u"0006r",
+    u"0006ru",
+    u"0007a",
+    u"0008<",
+    u"0010!",
+    u"0010#",
+    u"0010#u",
+    u"0010'S",
+    u"0010C'u",
+    u"0010Hu",
+    u"0010Xv",
+    u"0010cl?",
+    u"0010f",
+    u"0010h",
+    u"0010ig",
+    u"0010l",
+    u"0010oi",
+    u"0010ph",
+    u"0010u@",
+    u"0010ug",
+    u"0010ą",
+    u"0010ē",
+    u"0010ś",
+    u"0011!",
+    u"0011'u",
+    u"0011-",
+    u"0011@",
+    u"0011H",
+    u"0011e",
+    u"0011u!",
+    u"0011ue",
+    u"0011ź",
+    u"0012i",
+    u"0012o",
+    u"0012v",
+    u"0013'S",
+    u"0013-",
+    u"0013Su",
+    u"0013U'",
+    u"0013hu",
+    u"0013ov",
+    u"0013oy",
+    u"0013u@",
+    u"0013v",
+    u"0014#u",
+    u"0014%",
+    u"0014'S",
+    u"0014'hS",
+    u"0014-",
+    u"0014>",
+    u"0014Sś'",
+    u"0014agarcie",
+    u"0014c<",
+    u"0014ci",
+    u"0014h'",
+    u"0014i'",
+    u"0014iT",
+    u"0014ocie",
+    u"0014owi",
+    u"0014ś'",
+    u"0014śo",
+    u"0015o",
+    u"0016",
+    u"0016c",
+    u"0018",
+    u"0019c",
+    u"0021ci",
+    u"0023u",
+    u"0023śu",
+    u"0023ź",
+    u"0023źi",
+    u"0024",
+    u"0024u",
+    u"0026K",
+    u"0026Ku",
+    u"0027",
+    u"0027c",
+    u"0028u",
+    u"0028śu",
+    u"0029(c)",
+    u"0029c",
+    u"0029u",
+    u"0030",
+    u"0030u",
+    u"0031",
+    u"0032",
+    u"0032#u",
+    u"0032u",
+    u"0033",
+    u"0033?",
+    u"0035?",
+    u"0037ue",
+    u"0038e",
+    u"0038ue",
+    u"0039b",
+    u"0039bu",
+    u"0039y",
+    u"0040",
+    u"0042",
+    u"0046",
+    u"0046u",
+    u"0047ń",
+    u"0048!y",
+    u"0048#",
+    u"0048=-",
+    u"0048oo!",
+    u"0049v",
+    u"0049vv",
+    u"0049vvv",
+    u"0050(!)",
+    u"0050v",
+    u"0051(jer)",
+    u"0051u",
+    u"0051w",
+    u"0052g",
+    u"0052w",
+    u"0053!",
+    u"0054v",
+    u"0055c!",
+    u"0055g",
+    u"0058w",
+    u"0059",
+    u"0059w",
+    u"0060",
+    u"0060+",
+    u"0062",
+    u"0063",
+    u"0063c<",
+    u"0063g",
+    u"0064#",
+    u"0064'u",
+    u"0064-",
+    u"0064g",
+    u"0064g'",
+    u"0064o",
+    u"0064og",
+    u"0064oń",
+    u"0064v'",
+    u"0066w",
+    u"0066ó",
+    u"0067Y=",
+    u"0069$",
+    u"0069Yw",
+    u"0072g",
+    u"0074g",
+    u"0074u",
+    u"0075u",
+    u"0075w",
+    u"0076#",
+    u"0076*zi",
+    u"0076wg",
+    u"0076za",
+    u"0076zi",
+    u"0076ć",
+    u"0076ćg",
+    u"0076śg",
+    u"0077",
+    u"0078w",
+    u"0078wg",
+    u"0080u",
+    u"0081g",
+    u"0082",
+    u"0082m",
+    u"0083wg",
+    u"0083ź",
+    u"0084hw",
+    u"0085K",
+    u"0086",
+    u"0087K",
+    u"0087śu",
+    u"0089",
+    u"0091",
+    u"0091#",
+    u"0092H",
+    u"0092g",
+    u"0092hh",
+    u"0092n",
+    u"0092o",
+    u"0093h",
+    u"0093x",
+    u"0094o",
+    u"0095dz",
+    u"0096i",
+    u"0096ow",
+    u"0096owv",
+    u"0096owś",
+    u"0096łw",
+    u"0097i",
+    u"0098(rr)",
+    u"0098h",
+    u"0098ow",
+    u"0099_",
+    u"0099eś",
+    u"0099h",
+    u"0099hw",
+    u"0099o",
+    u"0099oś",
+    u"0100",
+    u"0100d",
+    u"0101ź",
+    u"0102ś",
+    u"0103",
+    u"0106",
+    u"0107 (IE)",
+    u"0107ś?",
+    u"0110",
+    u"0112",
+    u"0113",
+    u"0115",
+    u"0116",
+    u"0119",
+    u"0121",
+    u"0123#",
+    u"0129?",
+    u"0129o",
+    u"0131",
+    u"0132",
+    u"0132g2",
+    u"0133g2",
+    u"0134",
+    u"0135g-",
+    u"0136(IE)g2",
+    u"0137",
+    u"0137g2",
+    u"0138o",
+    u"0139",
+    u"0140!",
+    u"0143",
+    u"0145g2",
+    u"0145tg2",
+    u"0145w",
+    u"0145zg2",
+    u"0146H",
+    u"0146Yw",
+    u"0147g2",
+    u"0150#",
+    u"0151",
+    u"0152",
+    u"0153",
+    u"0154",
+    u"0155i",
+    u"0156m",
+    u"0156ó",
+    u"0157",
+    u"0158i",
+    u"0159(IE)",
+    u"0159E",
+    u"0159i",
+    u"0160im",
+    u"0160v",
+    u"0161#",
+    u"0161E",
+    u"0162",
+    u"0162i",
+    u"0164Ó",
+    u"0166",
+    u"0168",
+    u"0169",
+    u"0169m",
+    u"0170",
+    u"0171#",
+    u"0171##",
+    u"0171KK",
+    u"0171Ku",
+    u"0171gc",
+    u"0172#",
+    u"0172##",
+    u"0173#",
+    u"0173og",
+    u"0174u",
+    u"0175",
+    u"0177",
+    u"0178",
+    u"0180eź",
+    u"0180g",
+    u"0181ś",
+    u"0181ź",
+    u"0181źv",
+    u"0182źg",
+    u"0183g",
+    u"0183ó",
+    u"0184^",
+    u"0184e",
+    u"0185",
+    u"0185ź",
+    u"0186M",
+    u"0186e",
+    u"0186lź",
+    u"0187ć",
+    u"0187ś",
+    u"0187śv",
+    u"0189e",
+    u"0190",
+    u"0191",
+    u"0191+",
+    u"0193",
+    u"0194#",
+    u"0196#",
+    u"0197",
+    u"0199#",
+    u"0201",
+    u"0201ł",
+    u"0203",
+    u"0204",
+    u"0Nom'",
+    u"A",
+    u"A'",
+    u"A''",
+    u"A'''",
+    u"A700'/ky",
+    u"A700/L",
+    u"A700/ij",
+    u"A700/oj",
+    u"A700/sz",
+    u"A700/yj",
+    u"A700R<v",
+    u"A700RS",
+    u"A701RS",
+    u"A701ReS",
+    u"A703P",
+    u"A703Ż",
+    u"A708P",
+    u"A708R<",
+    u"A708R<v",
+    u"A711N",
+    u"A716+",
+    u"A716ś",
+    u"A716ź",
+    u"A717+",
+    u"A717D",
+    u"A718ź",
+    u"A721",
+    u"A722Ż#",
+    u"A729",
+    u"IXc'*1",
+    u"IXc'*2",
+    u"IXcYYYY",
+    u"La1",
+    u"La11",
+    u"Lb1",
+    u"Lb3",
+    u"Lc2",
+    u"Lc2a",
+    u"Lc2c",
+    u"Lc2o",
+    u"Lc3",
+    u"Lc4",
+    u"Ld007",
+    u"Ld008",
+    u"Ld00K",
+    u"Ld00P",
+    u"Ld012",
+    u"Ld01P",
+    u"Ld020",
+    u"Ld030",
+    u"Ld0K0",
+    u"Ld0P0",
+    u"Ld0W0",
+    u"Ld100",
+    u"Ld200",
+    u"Ld300",
+    u"Ld500",
+    u"Ld700",
+    u"Ld800",
+    u"LdK00",
+    u"LdP00",
+    u"LdW00",
+    u"LdX1",
+    u"LdX11",
+    u"LdX2",
+    u"LdX3",
+    u"LdX4",
+    u"Ldkr2",
+    u"Ldkr3",
+    u"Ldkr5",
+    u"Ldkr7",
+    u"Ldkr8",
+    u"P02",
+    u"P03",
+    u"P05",
+    u"P06",
+    u"P09",
+    u"P10",
+    u"P14",
+    u"P24",
+    u"P26",
+    u"P27",
+    u"P29",
+    u"P33",
+    u"P34",
+    u"P35",
+    u"P36",
+    u"P40",
+    u"P42",
+    u"P44",
+    u"P45",
+    u"P46",
+    u"P48",
+    u"P49",
+    u"P50",
+    u"P51",
+    u"P52",
+    u"P54",
+    u"P55",
+    u"P56",
+    u"P57",
+    u"P58",
+    u"P59",
+    u"P61",
+    u"P62",
+    u"P64",
+    u"P65",
+    u"P66",
+    u"P67",
+    u"P70",
+    u"P74",
+    u"P75",
+    u"Pdef1",
+    u"Pdef2",
+    u"VIIaY",
+    u"XIIId'Y",
+    u"XIIId'Y*1",
+    u"XIIId'YY*1",
+    u"XIIId*4",
+    u"XIIId*5",
+    u"XIIId*6",
+    u"XIIId*7",
+    u"XIIId*8",
+    u"XIIIe*1",
+    u"XIIIe*2",
+    u"XIIIf''''*1",
+    u"XIIIh'",
+    u"XIIc'''*2",
+    u"XIIc'''*3",
+    u"XIIc'''*4",
+    u"XIIc''*2",
+    u"XIIc'*3",
+    u"XIIc'*4",
+    u"XIIc'*5",
+    u"XIIc*2",
+    u"XIIc*3",
+    u"XIIc*4",
+    u"XId*2",
+    u"XId*3",
+    u"XId*4",
+    u"Zap1",
+    u"Zap2",
+    u"Zap3",
+    u"Zas1",
+    u"Zas1(ciś)",
+    u"Zas1(kol)",
+    u"Zas1(si)",
+    u"Zas1(sik)",
+    u"Zas1(siś)",
+    u"Zas1(ś)",
+    u"Zas1(ściś)",
+    u"Zas1(śkol)",
+    u"Zas1(że)",
+    u"Zas2",
+    u"Zas2(kol)",
+    u"Zas3",
+    u"Zas5",
+    u"Zas6",
+    u"Zas7",
+    u"Zas7(kol)",
+    u"Zas7(ś)",
+    u"Zas7(śkol)",
+    u"Zas8",
+    u"Zas8(kol)",
+    u"Zas9",
+    u"Zb1",
+    u"Zb2",
+    u"Zb3",
+    u"Zc",
+    u"v6",
+    u"v7",
+    u"v7''",
+    u"v8Y",
+    u"x1'",
 ]
diff --git a/dictionary/templates/classification_forms.html b/dictionary/templates/classification_forms.html
index 744016d..1e5dd88 100644
--- a/dictionary/templates/classification_forms.html
+++ b/dictionary/templates/classification_forms.html
@@ -1,3 +1,3 @@
 {% for form in forms %}
-  {{ form.as_p }}
+    {{ form.as_p }}
 {% endfor %}
diff --git a/dictionary/templates/classification_value_tree.html b/dictionary/templates/classification_value_tree.html
index 7faae92..bd3ee0b 100644
--- a/dictionary/templates/classification_value_tree.html
+++ b/dictionary/templates/classification_value_tree.html
@@ -1,34 +1,34 @@
 {% load dictionary_extras %}
 <ul class="value-tree">
-  {% for value, subtree in value_tree %}
-    <li>
+    {% for value, subtree in value_tree %}
+        <li>
       <span class="value-name">
         {{ value.label }}
       </span>
       <span class="value-controls">
         {% if value.is_empty and not subtree %}
+            <form action="" method="post">
+                {% csrf_token %}
+                <input type="hidden" name="det" value="value_remove"/>
+                <input type="hidden" name="id" value="{{ value.pk }}"/>
+                <button type="submit">
+                    usuń
+                </button>
+            </form>
+        {% endif %}
           <form action="" method="post">
-            {% csrf_token %}
-            <input type="hidden" name="det" value="value_remove"/>
-            <input type="hidden" name="id" value="{{ value.pk }}"/>
-            <button type="submit">
-              usuń
-            </button>
+              {% csrf_token %}
+              <input type="hidden" name="det" value="value_rename"/>
+              <input type="hidden" name="id" value="{{ value.pk }}"/>
+              <input type="text" name="new_name"/>
+              <button type="submit">
+                  zmień nazwę
+              </button>
           </form>
-        {% endif %}
-        <form action="" method="post">
-          {% csrf_token %}
-          <input type="hidden" name="det" value="value_rename"/>
-          <input type="hidden" name="id" value="{{ value.pk }}"/>
-          <input type="text" name="new_name"/>
-          <button type="submit">
-            zmień nazwę
-          </button>
-        </form>
       </span>
-      {% if subtree %}
-        {% value_tree subtree %}
-      {% endif %}
-    </li>
-  {% endfor %}
+            {% if subtree %}
+                {% value_tree subtree %}
+            {% endif %}
+        </li>
+    {% endfor %}
 </ul>
diff --git a/dictionary/templates/cross_reference_row.html b/dictionary/templates/cross_reference_row.html
index 3e2d5ca..7dfcdc7 100644
--- a/dictionary/templates/cross_reference_row.html
+++ b/dictionary/templates/cross_reference_row.html
@@ -1,6 +1,6 @@
 <li class="cr-row cr-add ui-state-default ui-corner-all">
-  {% if editable %}
-    <span class="remove ui-icon ui-icon-closethick"></span>
-  {% endif %}
-  {{ cr_form.as_table }}
+    {% if editable %}
+        <span class="remove ui-icon ui-icon-closethick"></span>
+    {% endif %}
+    {{ cr_form.as_table }}
 </li>
diff --git a/dictionary/templates/ending_row.html b/dictionary/templates/ending_row.html
index 323293f..da0b40a 100644
--- a/dictionary/templates/ending_row.html
+++ b/dictionary/templates/ending_row.html
@@ -1,15 +1,15 @@
 <li class="ending-row ui-state-default ui-corner-all">
-  {% if editable %}
-    <span class="remove ui-icon ui-icon-closethick"></span>
-    <span class="arrows ui-icon ui-icon-arrowthick-2-n-s"></span>
-  {% endif %}
-  {{ ending.pattern.example }}
-  <input
-    type="text"
-    value="{{ ending.string }}"
-    id="ending-{{ ending.id }}"
-    {{ editable|yesno:',disabled="disabled"' }}
-    size="8"/>
-  {{ ro_qualifiers|join:", " }}
-  {{ form.as_p }}
+    {% if editable %}
+        <span class="remove ui-icon ui-icon-closethick"></span>
+        <span class="arrows ui-icon ui-icon-arrowthick-2-n-s"></span>
+    {% endif %}
+    {{ pattern.example }}
+    <input
+            type="text"
+            value="{{ ending.string }}"
+            id="ending-{{ ending.id }}"
+            {{ editable|yesno:',disabled="disabled"' }}
+            size="8"/>
+    {{ ro_qualifiers|join:", " }}
+    {{ form.as_p }}
 </li>
diff --git a/dictionary/templates/export.html b/dictionary/templates/export.html
index 798bc53..aa18221 100644
--- a/dictionary/templates/export.html
+++ b/dictionary/templates/export.html
@@ -2,34 +2,36 @@
 {% load url from future %}
 
 {% block extrahead %}
-  <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/lib/jquery.multiselect.css"/>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/lib/jquery.multiselect.js"></script>
-  <script type="text/javascript">
-    $.fn.multiselect2 = $.fn.multiselect;
-  </script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/export.js"></script>
+    <link rel="stylesheet" type="text/css"
+          href="{{ MEDIA_URL }}css/lib/jquery.multiselect.css"/>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/jquery.multiselect.js"></script>
+    <script type="text/javascript">
+        $.fn.multiselect2 = $.fn.multiselect;
+    </script>
+    <script type="text/javascript" src="{{ MEDIA_URL }}js/export.js"></script>
 {% endblock %}
 
 {% block title %}Eksport leksemów{% endblock %}
 
 {% block content %}
-  <h3>Eksport leksemów</h3>
-  <form method="get" action="" id="export-form">
-    {{ form.as_p }}
-    Kwalifikatory do wykluczenia (pusty wzorzec wyklucza cały kwalifikator):
-    <button type="button" id="add-magic-qualifier-row">
-      <span class="ui-icon ui-icon-plus"></span>
-    </button>
-    <ul id="magic-qualifiers"></ul>
-    <button type="button" class="save">Zapisz ustawienia</button>
-    <button type="button" class="load">Wczytaj ustawienia</button>
-    <button type="submit">Generuj eksport</button>
-  </form>
+    <h3>Eksport leksemów</h3>
+    <form method="get" action="" id="export-form">
+        {{ form.as_p }}
+        Kwalifikatory do wykluczenia (pusty wzorzec wyklucza cały kwalifikator):
+        <button type="button" id="add-magic-qualifier-row">
+            <span class="ui-icon ui-icon-plus"></span>
+        </button>
+        <ul id="magic-qualifiers"></ul>
+        <button type="button" class="save">Zapisz ustawienia</button>
+        <button type="button" class="load">Wczytaj ustawienia</button>
+        <button type="submit">Generuj eksport</button>
+    </form>
 {% endblock %}
 
 {% block modal_elements %}
-  <div id="load-data-dialog" title="Wybierz ustawienia eksportu">
-    <ul id="data-list" class="load-dialog-list">
-    </ul>
-  </div>
+    <div id="load-data-dialog" title="Wybierz ustawienia eksportu">
+        <ul id="data-list" class="load-dialog-list">
+        </ul>
+    </div>
 {% endblock %}
diff --git a/dictionary/templates/extra_attributes.html b/dictionary/templates/extra_attributes.html
index 33df40a..b8eb855 100644
--- a/dictionary/templates/extra_attributes.html
+++ b/dictionary/templates/extra_attributes.html
@@ -1,3 +1,3 @@
 {% for form in forms %}
-  {{ form.as_p }}
+    {{ form.as_p }}
 {% endfor %}
\ No newline at end of file
diff --git a/dictionary/templates/history_table.html b/dictionary/templates/history_table.html
index 92a7c94..126130b 100644
--- a/dictionary/templates/history_table.html
+++ b/dictionary/templates/history_table.html
@@ -1,8 +1,8 @@
 {% load format_date %}
 {% for table in transaction_tables %}
-  <span>
+    <span>
     {{ table.user.username }}
     {{ table.date|format_date }}
   </span>
-  {% include "lexeme_history_table.html" %}
+    {% include "lexeme_history_table.html" %}
 {% endfor %}
diff --git a/dictionary/templates/history_view.html b/dictionary/templates/history_view.html
index 13d5fb9..a04faf4 100644
--- a/dictionary/templates/history_view.html
+++ b/dictionary/templates/history_view.html
@@ -2,22 +2,25 @@
 {% load format_date pagination_tags %}
 
 {% block extrahead %}
-  <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/lexeme_view.css"/>
-  <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/paginer.css"/>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/history-view.js"></script>
+    <link rel="stylesheet" type="text/css"
+          href="{{ MEDIA_URL }}css/lexeme_view.css"/>
+    <link rel="stylesheet" type="text/css"
+          href="{{ MEDIA_URL }}css/paginer.css"/>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/history-view.js"></script>
 {% endblock %}
 
 {% block title %}Historia{% endblock %}
 
 {% block content %}
-  <h3>Historia zmian</h3>
-  <div class="tabs">
-    <ul>
-      <li><a href="#lexeme_items">Leksemy</a></li>
-    </ul>
-    <div id="lexeme_items">
-      {% paginated_list_panel "lexeme_items" %}
-      {% paginated_list "lexeme_items" %}
+    <h3>Historia zmian</h3>
+    <div class="tabs">
+        <ul>
+            <li><a href="#lexeme_items">Leksemy</a></li>
+        </ul>
+        <div id="lexeme_items">
+            {% paginated_list_panel "lexeme_items" %}
+            {% paginated_list "lexeme_items" %}
+        </div>
     </div>
-  </div>
 {% endblock %}
diff --git a/dictionary/templates/inflection_table.html b/dictionary/templates/inflection_table.html
index 17fcb6e..03fb57e 100644
--- a/dictionary/templates/inflection_table.html
+++ b/dictionary/templates/inflection_table.html
@@ -1,46 +1,48 @@
 <table class='inflection-table'>
-{% if tables and tables|length > 1 %}
-  <caption>
-    {{ inflection_characteristic.symbol }}: {{ patterns|join:" / " }}
-  </caption>
-{% endif %}
-{% for row in table %}
-  <tr>
-    {% for cell in row %}
-      {% if cell.type != 'span' %}
-        {% if cell.type == 'empty' %}
-          <td class='empty' ></td>
-        {% else %}
-          {% if cell.type == 'forms' %}
-            <td rowspan="{{ cell.rowspan }}" colspan="{{ cell.colspan }}">
-              <ul class='form-list'>
-                {% for entry in cell.forms %}
-                  <li>
-                    {{ entry.form }}
+    {% if tables and tables|length > 1 %}
+        <caption>
+            {{ inflection_characteristic.symbol }}: {{ patterns|join:" / " }}
+        </caption>
+    {% endif %}
+    {% for row in table %}
+        <tr>
+            {% for cell in row %}
+                {% if cell.type != 'span' %}
+                    {% if cell.type == 'empty' %}
+                        <td class='empty'></td>
+                    {% else %}
+                        {% if cell.type == 'forms' %}
+                            <td rowspan="{{ cell.rowspan }}"
+                                colspan="{{ cell.colspan }}">
+                                <ul class='form-list'>
+                                    {% for entry in cell.forms %}
+                                        <li>
+                                            {{ entry.form }}
                     <span class="qualifiers">
                       {% for q in entry.qualifiers %}
-                        {{ q.label }}
+                          {{ q.label }}
                       {% endfor %}
                     </span>
-                  </li>
-                {% endfor %}
-              </ul>
-            </td>
-          {% else %}
-            <td rowspan="{{ cell.rowspan }}" colspan="{{ cell.colspan }}"
-                class="{{ cell.css_class }}">
-              <ul class="form-list">
-                {% for label in cell.label %}
-                  <li>
-                    {{ label|safe }}
-                  </li>
-                {% endfor %}
-              </ul>
-            </td>
-          {% endif %}
-        {% endif %}
-      {% endif %}
+                                        </li>
+                                    {% endfor %}
+                                </ul>
+                            </td>
+                        {% else %}
+                            <td rowspan="{{ cell.rowspan }}"
+                                colspan="{{ cell.colspan }}"
+                                class="{{ cell.css_class }}">
+                                <ul class="form-list">
+                                    {% for label in cell.label %}
+                                        <li>
+                                            {{ label|safe }}
+                                        </li>
+                                    {% endfor %}
+                                </ul>
+                            </td>
+                        {% endif %}
+                    {% endif %}
+                {% endif %}
+            {% endfor %}
+        </tr>
     {% endfor %}
-  </tr>
-{% endfor %}
 </table>
diff --git a/dictionary/templates/inflection_tables.html b/dictionary/templates/inflection_tables.html
index 5df0919..f955be2 100644
--- a/dictionary/templates/inflection_tables.html
+++ b/dictionary/templates/inflection_tables.html
@@ -1,60 +1,66 @@
 {% load dictionary_extras %}
 <div class="entry-article scheme{{ lexeme.part_of_speech.color_scheme }}">
-  <h1>
-    {{ lexeme.entry }}
-    {{ lexeme|attribute:"zwrotność" }}
-    {% if lexeme.pronunciation %}
-      <span class="pronunciation">[{{ lexeme.pronunciation|safe }}]</span>
-    {% endif %}
-    {% if lexeme.gloss %}
-      <span class="gloss">{{ lexeme.gloss|safe }}</span>
-    {% endif %}
-  </h1>
-  <p>
-    {{ lexeme.part_of_speech.full_name }}
-    {% if lexeme.part_of_speech.symbol == 'v' %}
-      {{ lexeme|attribute:"właściwy" }}
-      {{ lexeme|attribute:"przechodniość" }}
-    {% endif %}
-    <span class="qualifiers">
+    <h1>
+        {{ lexeme.entry }}
+        {{ lexeme|attribute:"zwrotność" }}
+        {% if lexeme.pronunciation %}
+            <span class="pronunciation">[{{ lexeme.pronunciation|safe }}]</span>
+        {% endif %}
+        {% if lexeme.gloss %}
+            <span class="gloss">{{ lexeme.gloss|safe }}</span>
+        {% endif %}
+    </h1>
+
+    <p>
+        {{ lexeme.part_of_speech.full_name }}
+        {% if lexeme.part_of_speech.symbol == 'v' %}
+            {{ lexeme|attribute:"właściwy" }}
+            {{ lexeme|attribute:"przechodniość" }}
+        {% endif %}
+        <span class="qualifiers">
       {{ info.qualifiers|join:" " }}
-      {% if info.commonness %}
-        n. wł. {{ info.commonness|join:", " }}
-      {% endif %}
+            {% if info.commonness %}
+                n. wł. {{ info.commonness|join:", " }}
+            {% endif %}
     </span>
-    {% if lexeme.note %}
-      ◊ {{ lexeme.note|safe }}
-    {% endif %}
-    <span class="sjpdor">
+        {% if lexeme.note %}
+            ◊ {{ lexeme.note|safe }}
+        {% endif %}
+        <span class="sjpdor">
       {{ info.SJPDor|yesno:"[SJPDor.]," }}
     </span>
-  </p>
-  <p>
-    {% if lexeme.part_of_speech.lexical_class.symbol == 'subst' %}
-      {{ lexeme.lip_data.inflection_characteristics }}
-    {% endif %}
-    {{ lexeme|attribute:"aspekt" }}
-    {% if tables|length == 1 %}
-      {{ lexeme.lip_data.patterns }}
+    </p>
+
+    <p>
+        {% if lexeme.part_of_speech.lexical_class.symbol == 'subst' %}
+            {{ lexeme.lip_data.inflection_characteristics }}
+        {% endif %}
+        {{ lexeme|attribute:"aspekt" }}
+        {% if tables|length == 1 %}
+            {{ lexeme.lip_data.patterns }}
+        {% endif %}
+    </p>
+
+    <p class="separator"></p>
+
+    <div class="inflection-tables">
+        {% for inflection_characteristic, patterns, table in tables %}
+            <div class="inflection-table-container">
+                {% include "inflection_table.html" %}
+            </div>
+        {% endfor %}
+    </div>
+    {% if cross_references %}
+        <table class="cross-references">
+            <tr>
+                <th class="head" colspan="2">Odsyłacze</th>
+            </tr>
+            {% for cr in cross_references %}
+                <tr>
+                    <th>{{ cr.type.desc }}</th>
+                    <td>{{ cr.to_lexeme.entry }}</td>
+                </tr>
+            {% endfor %}
+        </table>
     {% endif %}
-  </p>
-  <p class="separator"></p>
-  <div class="inflection-tables">
-    {% for inflection_characteristic, patterns, table in tables %}
-      <div class="inflection-table-container">
-        {% include "inflection_table.html" %}
-      </div>
-    {% endfor %}
-  </div>
-  {% if cross_references %}
-    <table class="cross-references">
-      <tr><th class="head" colspan="2">Odsyłacze</th></tr>
-      {% for cr in cross_references %}
-        <tr>
-          <th>{{ cr.type.desc }}</th>
-          <td>{{ cr.to_lexeme.entry }}</td>
-        </tr>
-      {% endfor %}
-    </table>
-  {% endif %}
 </div>
\ No newline at end of file
diff --git a/dictionary/templates/info_table.html b/dictionary/templates/info_table.html
index db98313..a670de3 100644
--- a/dictionary/templates/info_table.html
+++ b/dictionary/templates/info_table.html
@@ -2,18 +2,18 @@
 {% load get %}
 
 {% block content %}
-  <table>
-    {% for pos in pos_list %}
-      <tr>
-        <td>
-          {{ pos }}
-        </td>
-        {% for qs, column in columns %}
-          <td>
-            {{ table|get:pos|get:column }}
-          </td>
+    <table>
+        {% for pos in pos_list %}
+            <tr>
+                <td>
+                    {{ pos }}
+                </td>
+                {% for qs, column in columns %}
+                    <td>
+                        {{ table|get:pos|get:column }}
+                    </td>
+                {% endfor %}
+            </tr>
         {% endfor %}
-      </tr>
-    {% endfor %}
-  </table>
+    </table>
 {% endblock %}
diff --git a/dictionary/templates/lexeme_edit_form.html b/dictionary/templates/lexeme_edit_form.html
index 3e61347..124ab9b 100644
--- a/dictionary/templates/lexeme_edit_form.html
+++ b/dictionary/templates/lexeme_edit_form.html
@@ -1,116 +1,119 @@
 <form action="" method="post" id="lexeme-edit-form">
-  {% for field in form %}
-    {% if field.name != 'comment' and field.name != 'vocabularies' and field.name != 'qualifiers' and field.name != 'new_owner' %}
-      <p class="main-field">
-        {{ field.label_tag }} {{ field.as_widget }}
-        {% if field.name == 'part_of_speech' %}
-          <span id="homonym-count"></span>
+    {% for field in form %}
+        {% if field.name != 'comment' and field.name != 'vocabularies' and field.name != 'qualifiers' and field.name != 'new_owner' %}
+            <p class="main-field">
+                {{ field.label_tag }} {{ field.as_widget }}
+                {% if field.name == 'part_of_speech' %}
+                    <span id="homonym-count"></span>
+                {% endif %}
+            </p>
         {% endif %}
-      </p>
-    {% endif %}
-  {% endfor %}
-  <div id ="extra-attributes">
-    {% for form in attribute_forms %}
-      {{ form.as_p }}
-    {% endfor %}
-  </div>
-  <p>
-    Sposoby odmiany:
-    <input type="hidden" name="id" value="{{ id }}"/>
-    {% if editable %}
-      <button type="button" id="add-row">
-        <span class="ui-icon ui-icon-plus"></span>
-      </button>
-    {% endif %}
-  </p>
-  <ul id="pattern-list" {{ editable|yesno:'class="editable",'|safe }}>
-    {% for lip_form, ro_qualifiers in lip_forms %}
-      {% include 'lexeme_edit_form_row.html' %}
     {% endfor %}
-  </ul>
-  <table id="vocab-list">
-    <tr>
-      <th>Słownik właściciel</th>
-      <th>Słowniki używające</th>
-    </tr>
-    <tr>
-      <td>
-        {% if multiple_editable %}
-          {{ form.new_owner.as_widget }}
-        {% else %}
-          <strong id="owner-vocabulary">{{ owner.id }}</strong>
+    <div id="extra-attributes">
+        {% for form in attribute_forms %}
+            {{ form.as_p }}
+        {% endfor %}
+    </div>
+    <p>
+        Sposoby odmiany:
+        <input type="hidden" name="id" value="{{ id }}"/>
+        {% if editable %}
+            <button type="button" id="add-row">
+                <span class="ui-icon ui-icon-plus"></span>
+            </button>
         {% endif %}
-      </td>
-      <td>
-        <ul>
-          {% for v in ro_vocabularies %}
-            <li>
-              {{ v.id }}
-            </li>
-          {% endfor %}
-          <li>
-            {{ form.vocabularies.as_widget }}
-          </li>
-        </ul>
-      </td>
-    </tr>
-  </table>
-  <p>Kwalifikatory:</p>
-  <p>
-    {% if ro_qualifiers %}
-      {{ owner.id }}: {{ ro_qualifiers|join:", " }};
+    </p>
+    <ul id="pattern-list" {{ editable|yesno:'class="editable",'|safe }}>
+        {% for lip_form, ro_qualifiers in lip_forms %}
+            {% include 'lexeme_edit_form_row.html' %}
+        {% endfor %}
+    </ul>
+    <table id="vocab-list">
+        <tr>
+            <th>Słownik właściciel</th>
+            <th>Słowniki używające</th>
+        </tr>
+        <tr>
+            <td>
+                {% if multiple_editable %}
+                    {{ form.new_owner.as_widget }}
+                {% else %}
+                    <strong id="owner-vocabulary">{{ owner.id }}</strong>
+                {% endif %}
+            </td>
+            <td>
+                <ul>
+                    {% for v in ro_vocabularies %}
+                        <li>
+                            {{ v.id }}
+                        </li>
+                    {% endfor %}
+                    <li>
+                        {{ form.vocabularies.as_widget }}
+                    </li>
+                </ul>
+            </td>
+        </tr>
+    </table>
+    <p>Kwalifikatory:</p>
+
+    <p>
+        {% if ro_qualifiers %}
+            {{ owner.id }}: {{ ro_qualifiers|join:", " }};
+        {% endif %}
+        {{ form.qualifiers.as_widget }}
+    </p>
+    {% if classification_forms %}
+        <h4>Klasyfikacje</h4>
+        <div id="classifications">
+            {% for form in classification_forms %}
+                {{ form.as_p }}
+            {% endfor %}
+        </div>
     {% endif %}
-    {{ form.qualifiers.as_widget }}
-  </p>
-  {% if classification_forms %}
-    <h4>Klasyfikacje</h4>
-    <div id="classifications">
-      {% for form in classification_forms %}
-        {{ form.as_p }}
-      {% endfor %}
-    </div>
-  {% endif %}
-  <p>
-    <strong>{{ form.comment.label_tag }}</strong>
-  </p>
-  <p>
-    {{ form.comment.as_widget }}
-  </p>
-  {% if editable or cross_references %}
     <p>
-      Odsyłacze:
-      {% if editable %}
-        <button type="button" id="add-cr-row">
-          <span class="ui-icon ui-icon-plus"></span>
+        <strong>{{ form.comment.label_tag }}</strong>
+    </p>
+
+    <p>
+        {{ form.comment.as_widget }}
+    </p>
+    {% if editable or cross_references %}
+        <p>
+            Odsyłacze:
+            {% if editable %}
+                <button type="button" id="add-cr-row">
+                    <span class="ui-icon ui-icon-plus"></span>
+                </button>
+            {% endif %}
+        </p>
+        <ul id="cr-list">
+            {% for cr in cross_references %}
+                <li class="cr-row ui-state-default ui-corner-all"
+                    id="cr-{{ cr.pk }}">
+                    {% if editable %}
+                        <span class="remove ui-icon ui-icon-closethick"></span>
+                    {% endif %}
+                    <span class="type">{{ cr.type.desc }}</span>
+                    <span class="id">{{ cr.to_lexeme.pk }}</span>
+                    <span class="entry">{{ cr.to_lexeme.entry }}</span>
+                    <span class="ic">{{ cr.to_lexeme.lip_data.inflection_characteristics }}</span>
+                </li>
+            {% endfor %}
+        </ul>
+    {% endif %}
+    <p class="lexeme-save">
+        <button type="submit" disabled="disabled" id="lexeme-edit-submit">
+            Zapisz
+        </button>
+        <button type="reset" disabled="disabled" id="lexeme-edit-cancel">
+            Anuluj
+        </button>
+        <button type="button" id="lexeme-edit-delete"
+                {% if not editable %}disabled="disabled"{% endif %}>
+            Usuń leksem
         </button>
-      {% endif %}
     </p>
-    <ul id="cr-list">
-      {% for cr in cross_references %}
-        <li class="cr-row ui-state-default ui-corner-all" id="cr-{{ cr.pk }}">
-          {% if editable %}
-            <span class="remove ui-icon ui-icon-closethick"></span>
-          {% endif %}
-          <span class="type">{{ cr.type.desc }}</span>
-          <span class="id">{{ cr.to_lexeme.pk }}</span>
-          <span class="entry">{{ cr.to_lexeme.entry }}</span>
-          <span class="ic">{{ cr.to_lexeme.lip_data.inflection_characteristics }}</span>
-        </li>
-      {% endfor %}
-    </ul>
-  {% endif %}
-  <p class="lexeme-save">
-    <button type="submit" disabled="disabled" id="lexeme-edit-submit">
-      Zapisz
-    </button>
-    <button type="reset" disabled="disabled" id="lexeme-edit-cancel">
-      Anuluj
-    </button>
-    <button type="button" id="lexeme-edit-delete"
-            {% if not editable %}disabled="disabled"{% endif %}>
-      Usuń leksem
-    </button>
-  </p>
 </form>
 <div id="table-preview">
 </div>
diff --git a/dictionary/templates/lexeme_edit_form_row.html b/dictionary/templates/lexeme_edit_form_row.html
index a896016..9d945d3 100644
--- a/dictionary/templates/lexeme_edit_form_row.html
+++ b/dictionary/templates/lexeme_edit_form_row.html
@@ -1,22 +1,24 @@
 <li class="lip-row ui-state-default ui-corner-all">
-  {% if editable %}
-    <span class="remove ui-icon ui-icon-closethick"></span>
-    <span class="arrows ui-icon ui-icon-arrowthick-2-n-s"></span>
-  {% endif %}
-  {% for field in lip_form %}
-    {% if field.name != 'qualifiers' %}
-      <span class="lip-field">
+    {% if editable %}
+        <span class="remove ui-icon ui-icon-closethick"></span>
+        <span class="arrows ui-icon ui-icon-arrowthick-2-n-s"></span>
+    {% endif %}
+    {% for field in lip_form %}
+        {% if field.name != 'qualifiers' %}
+            <span class="lip-field">
         {{ field.label_tag }} {{ field.as_widget }}
       </span>
+        {% endif %}
+    {% endfor %}
+    {% if editable %}
+        <button type="button" class="prompter"
+                id="{{ lip_form.prefix }}-prompter">...
+        </button>
     {% endif %}
-  {% endfor %}
-  {% if editable %}
-    <button type="button" class="prompter" id="{{ lip_form.prefix }}-prompter">...</button>
-  {% endif %}
-  <p>
-    {% if ro_qualifiers %}
-      {{ owner.id }}: {{ ro_qualifiers|join:", " }};
-    {% endif %}
-    {{ lip_form.qualifiers.label_tag }} {{ lip_form.qualifiers.as_widget }}
-  </p>
+    <p>
+        {% if ro_qualifiers %}
+            {{ owner.id }}: {{ ro_qualifiers|join:", " }};
+        {% endif %}
+        {{ lip_form.qualifiers.label_tag }} {{ lip_form.qualifiers.as_widget }}
+    </p>
 </li>
diff --git a/dictionary/templates/lexeme_history_item.html b/dictionary/templates/lexeme_history_item.html
index b93b56b..41c38a0 100644
--- a/dictionary/templates/lexeme_history_item.html
+++ b/dictionary/templates/lexeme_history_item.html
@@ -1,11 +1,11 @@
 {% load format_date dictionary_extras %}
 {% with row|lexeme_table as table %}
-  <span>
+    <span>
     {% if 'lexeme' in paginer_obj.params.columns %}
-      <strong>{{ table.lexeme }}</strong>
+        <strong>{{ table.lexeme }}</strong>
     {% endif %}
-    {{ table.user.username }}
+        {{ table.user.username }}
     {{ table.date|format_date }}
   </span>
-  {% include "lexeme_history_table.html" %}
+    {% include "lexeme_history_table.html" %}
 {% endwith %}
diff --git a/dictionary/templates/lexeme_history_table.html b/dictionary/templates/lexeme_history_table.html
index 9645fcd..c9a3ded 100644
--- a/dictionary/templates/lexeme_history_table.html
+++ b/dictionary/templates/lexeme_history_table.html
@@ -1,51 +1,51 @@
 <table class="transaction-table">
-  <tr>
-    <th>atrybut</th>
-    <th>przed</th>
-    <th>po</th>
-  </tr>
-  {% for header, values in table.rows %}
     <tr>
-      <td>{{ header }}</td>
-      <td>
-        {% if values.0 == None %}
-          <em>dodano</em>
-        {% else %}
-          {{ values.0 }}
-        {% endif %}
-      </td>
-      <td>
-        {% if values.1 == None %}
-          <em>usunięto</em>
-        {% else %}
-          {{ values.1 }}
-        {% endif %}
-      </td>
+        <th>atrybut</th>
+        <th>przed</th>
+        <th>po</th>
     </tr>
-  {% endfor %}
-  {% for header, lip_rows in table.lip_tables %}
-    <tr>
-      <th colspan="3" class="lip-header">odmiana {{ header }}:</th>
-    </tr>
-    {% for header, values in lip_rows %}
-      <tr>
-        {# fuj, copypasta #}
-        <td>{{ header }}</td>
-        <td>
-          {% if values.0 == None %}
-            <em>dodano</em>
-          {% else %}
-            {{ values.0 }}
-          {% endif %}
-        </td>
-        <td>
-          {% if values.1 == None %}
-            <em>usunięto</em>
-          {% else %}
-            {{ values.1 }}
-          {% endif %}
-        </td>
-      </tr>
+    {% for header, values in table.rows %}
+        <tr>
+            <td>{{ header }}</td>
+            <td>
+                {% if values.0 == None %}
+                    <em>dodano</em>
+                {% else %}
+                    {{ values.0 }}
+                {% endif %}
+            </td>
+            <td>
+                {% if values.1 == None %}
+                    <em>usunięto</em>
+                {% else %}
+                    {{ values.1 }}
+                {% endif %}
+            </td>
+        </tr>
+    {% endfor %}
+    {% for header, lip_rows in table.lip_tables %}
+        <tr>
+            <th colspan="3" class="lip-header">odmiana {{ header }}:</th>
+        </tr>
+        {% for header, values in lip_rows %}
+            <tr>
+                {# fuj, copypasta #}
+                <td>{{ header }}</td>
+                <td>
+                    {% if values.0 == None %}
+                        <em>dodano</em>
+                    {% else %}
+                        {{ values.0 }}
+                    {% endif %}
+                </td>
+                <td>
+                    {% if values.1 == None %}
+                        <em>usunięto</em>
+                    {% else %}
+                        {{ values.1 }}
+                    {% endif %}
+                </td>
+            </tr>
+        {% endfor %}
     {% endfor %}
-  {% endfor %}
 </table>
diff --git a/dictionary/templates/lexeme_view.html b/dictionary/templates/lexeme_view.html
index 7c25951..f3d4289 100644
--- a/dictionary/templates/lexeme_view.html
+++ b/dictionary/templates/lexeme_view.html
@@ -2,149 +2,171 @@
 {% load i18n %}
 
 {% block extrahead %}
-  <link rel="stylesheet" href="{{ MEDIA_URL }}css/lib/ui.jqgrid.css" type="text/css" media="screen" charset="utf-8" />
-  <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/lib/ui.multiselect.css">
-  <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/lib/jquery.multiselect.css"/>
-  <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/lib/jquery.ui.selectmenu.css"/>
-  <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/jqgrid.css"/>
-  <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/lexeme_view.css"/>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/lib/cvi_busy_lib.js"></script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/lib/splitter.js"></script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/lib/jquery.multiselect.js"></script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/lib/jquery.ui.selectmenu.js"></script>
-  <script type="text/javascript">
-    $.fn.multiselect2 = $.fn.multiselect;
-  </script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/lib/ui.multiselect.js"></script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/lib/grid.locale-pl.js"></script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/lib/jquery.jqGrid.src.js"></script>
-  <script type="text/javascript">
-    jQuery.jgrid.no_legacy_api = true;
-  </script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/jqgrid-patch.js"></script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/jqgrid.js"></script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/sort-dialog.js"></script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/lexeme-view.js"></script>
+    <link rel="stylesheet" href="{{ MEDIA_URL }}css/lib/ui.jqgrid.css"
+          type="text/css" media="screen" charset="utf-8"/>
+    <link rel="stylesheet" type="text/css"
+          href="{{ MEDIA_URL }}css/lib/ui.multiselect.css">
+    <link rel="stylesheet" type="text/css"
+          href="{{ MEDIA_URL }}css/lib/jquery.multiselect.css"/>
+    <link rel="stylesheet" type="text/css"
+          href="{{ MEDIA_URL }}css/lib/jquery.ui.selectmenu.css"/>
+    <link rel="stylesheet" type="text/css"
+          href="{{ MEDIA_URL }}css/jqgrid.css"/>
+    <link rel="stylesheet" type="text/css"
+          href="{{ MEDIA_URL }}css/lexeme_view.css"/>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/cvi_busy_lib.js"></script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/splitter.js"></script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/jquery.multiselect.js"></script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/jquery.ui.selectmenu.js"></script>
+    <script type="text/javascript">
+        $.fn.multiselect2 = $.fn.multiselect;
+    </script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/ui.multiselect.js"></script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/grid.locale-pl.js"></script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/jquery.jqGrid.src.js"></script>
+    <script type="text/javascript">
+        jQuery.jgrid.no_legacy_api = true;
+    </script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/jqgrid-patch.js"></script>
+    <script type="text/javascript" src="{{ MEDIA_URL }}js/jqgrid.js"></script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lexeme-view.js"></script>
 {% endblock %}
 
 {% block title %}Widok leksemów{% endblock %}
 
 {% block content %}
-  <div id="left">
-    <div id="search-panel">
-      <button id="open-sort-dialog" title="sortuj">
-        <span class="ui-icon ui-icon-sort">sortuj</span>
-      </button>
-      <button id="filter-button" title="filtruj">
-        <span class="ui-icon ui-icon-filter">filtruj</span>
-      </button>
-      <button id="show-columns-button" title="pokaż/ukryj">
-        <span class="ui-icon ui-icon-columns">pokaż/ukryj</span>
-      </button>
-      <input type="text" id="phrase_box" class="phrase-box"/>
-      <button id="searchButton" title="szukaj">
-        <span class="ui-icon ui-icon-search">szukaj</span>
-      </button>
-      {% if perms.dictionary.change_lexeme %}
-        <button id="action-button" title="akcje grupowe">
-          <span class="ui-icon ui-icon-star">akcje grupowe</span>
-        </button>
-        <button id="add-button" title="dodaj leksem">
-          <span class="ui-icon ui-icon-plus">dodaj leksem</span>
-        </button>
-      {% endif %}
+    <div id="left">
+        <div id="search-panel">
+            <button id="open-sort-dialog" title="sortuj">
+                <span class="ui-icon ui-icon-sort">sortuj</span>
+            </button>
+            <button id="filter-button" title="filtruj">
+                <span class="ui-icon ui-icon-filter">filtruj</span>
+            </button>
+            <button id="show-columns-button" title="pokaż/ukryj">
+                <span class="ui-icon ui-icon-columns">pokaż/ukryj</span>
+            </button>
+            <input type="text" id="phrase_box" class="phrase-box"/>
+            <button id="searchButton" title="szukaj">
+                <span class="ui-icon ui-icon-search">szukaj</span>
+            </button>
+            {% if perms.dictionary.change_lexeme %}
+                <button id="action-button" title="akcje grupowe">
+                    <span class="ui-icon ui-icon-star">akcje grupowe</span>
+                </button>
+                <button id="add-button" title="dodaj leksem">
+                    <span class="ui-icon ui-icon-plus">dodaj leksem</span>
+                </button>
+            {% endif %}
+        </div>
+        <table id="scroll"></table>
+        <!--div id="pager"></div-->
     </div>
-    <table id="scroll"></table>
-    <!--div id="pager"></div-->
-  </div>
-  <div id="right">
-    <div class="tabs">
-      <ul>
-        <li><a href="#edit" id="edit-tab">Edycja</a></li>
-        <li><a href="#variant0">Formy bazowe</a></li>
-        <li><a href="#variant1">Wszystkie formy</a></li>
-        <li><a href="#odm">Formy z sjp.pl</a></li>
-        <li><a href="#history">Historia</a></li>
-      </ul>
-      <div id="edit"></div>
-      <div id="variant0"></div>
-      <div id="variant1"></div>
-      <div id="odm"></div>
-      <div id="history"></div>
+    <div id="right">
+        <div class="tabs">
+            <ul>
+                <li><a href="#edit" id="edit-tab">Edycja</a></li>
+                <li><a href="#variant0">Formy bazowe</a></li>
+                <li><a href="#variant1">Wszystkie formy</a></li>
+                <li><a href="#odm">Formy z sjp.pl</a></li>
+                <li><a href="#history">Historia</a></li>
+            </ul>
+            <div id="edit"></div>
+            <div id="variant0"></div>
+            <div id="variant1"></div>
+            <div id="odm"></div>
+            <div id="history"></div>
+        </div>
     </div>
-  </div>
 {% endblock %}
 
 {% block modal_elements %}
-  <div id="sort-dialog" title="Porządek sortowania">
-    <ul id='sort-rule-list'>
-    </ul>
-    <input type="button" id="save-sort-order" value="Zatwierdź"/>
-    <input type="button" id="cancel-sort-order" value="Anuluj"/>
-  </div>
-  <div id="load-filter-dialog" title="Wybierz filtr">
-    <ul id="filter-list" class="load-dialog-list">
-    </ul>
-  </div>
-  <div id="group-action-dialog" title="Wybierz akcję grupową">
-    <button id="add-action" title="dodaj akcję">
-      <span class="ui-icon ui-icon-plus">dodaj akcję</span>
-    </button>
-    <table id="action-list" class="group-action-list">
-    </table>
-  </div>
-  <div id="choose-homonym-dialog" title="Wybierz homonim">
-    <table id="homonym-list" class="choose-homonym-list">
-      <thead>
-        <tr>
-          <th>Nr hom.</th>
-          <th>Char. fleks.</th>
-          <th>Wzór</th>
-        </tr>
-      </thead>
-      <tbody>
-      </tbody>
-    </table>
-  </div>
-  <div id="prompter-dialog" title="Podpowiadacz wzorów">
-    <p>
-      <div id="prompter-dialog-left">
-        <table id="prompter-list">
+    <div id="sort-dialog" title="Porządek sortowania">
+        <ul id='sort-rule-list'>
+        </ul>
+        <input type="button" id="save-sort-order" value="Zatwierdź"/>
+        <input type="button" id="cancel-sort-order" value="Anuluj"/>
+    </div>
+    <div id="load-filter-dialog" title="Wybierz filtr">
+        <ul id="filter-list" class="load-dialog-list">
+        </ul>
+    </div>
+    <div id="group-action-dialog" title="Wybierz akcję grupową">
+        <button id="add-action" title="dodaj akcję">
+            <span class="ui-icon ui-icon-plus">dodaj akcję</span>
+        </button>
+        <table id="action-list" class="group-action-list">
         </table>
-        <ul id="prompter-checkboxes">
-          <li>
-            <input type="checkbox" id="prompter-ic"/>
-            <label for="prompter-ic">Uwzględniaj charakterystykę fleksyjną</label>
-          </li>
-          <li>
-            <input type="checkbox" id="prompter-commonness"/>
-            <label for="prompter-commonness">Uwzględniaj pospolitość</label>
-          </li>
-          <li>
-            <input type="checkbox" id="prompter-blacklist"/>
-            <label for="prompter-blacklist">Pomijaj wzory nietypowe</label>
-          </li>
+    </div>
+    <div id="choose-homonym-dialog" title="Wybierz homonim">
+        <table id="homonym-list" class="choose-homonym-list">
+            <thead>
+            <tr>
+                <th>Nr hom.</th>
+                <th>Char. fleks.</th>
+                <th>Wzór</th>
+            </tr>
+            </thead>
+            <tbody>
+            </tbody>
+        </table>
+    </div>
+    <div id="prompter-dialog" title="Podpowiadacz wzorów">
+        <p>
+
+        <div id="prompter-dialog-left">
+            <table id="prompter-list">
+            </table>
+            <ul id="prompter-checkboxes">
+                <li>
+                    <input type="checkbox" id="prompter-ic"/>
+                    <label for="prompter-ic">Uwzględniaj charakterystykę
+                        fleksyjną</label>
+                </li>
+                <li>
+                    <input type="checkbox" id="prompter-commonness"/>
+                    <label for="prompter-commonness">Uwzględniaj
+                        pospolitość</label>
+                </li>
+                <li>
+                    <input type="checkbox" id="prompter-blacklist"/>
+                    <label for="prompter-blacklist">Pomijaj wzory
+                        nietypowe</label>
+                </li>
+            </ul>
+        </div>
+        <div id="prompter-table-preview">
+        </div>
+        </p>
+    </div>
+    <div id="default-owner-dialog" title="Wybór domyślnego słownika">
+        <p>
+            Wybierz słownik domyślnie ustawiany jako właściciel przy dodawaniu
+            leksemów.
+        </p>
+
+        <p>
+            W przyszłości wybór można będzie zmienić w Ustawieniach.
+        </p>
+
+        <p>
+        <ul id="default-owner">
+            {% for vocab in editable_vocabularies %}
+                <li>
+                    <input type="radio" value="{{ vocab.pk }}"
+                           name="owner"/> {{ vocab.id }}
+                </li>
+            {% endfor %}
         </ul>
-      </div>
-      <div id="prompter-table-preview">
-      </div>
-    </p>
-  </div>
-  <div id="default-owner-dialog" title="Wybór domyślnego słownika">
-    <p>
-      Wybierz słownik domyślnie ustawiany jako właściciel przy dodawaniu leksemów.
-    </p>
-    <p>
-      W przyszłości wybór można będzie zmienić w Ustawieniach.
-    </p>
-    <p>
-      <ul id="default-owner">
-        {% for vocab in editable_vocabularies %}
-          <li>
-            <input type="radio" value="{{ vocab.pk }}" name="owner"/> {{ vocab.id }}
-          </li>
-        {% endfor %}
-      </ul>
-    </p>
-  </div>
+        </p>
+    </div>
 {% endblock %}
diff --git a/dictionary/templates/magic_qualifier_row.html b/dictionary/templates/magic_qualifier_row.html
index d3f0b98..29d0456 100644
--- a/dictionary/templates/magic_qualifier_row.html
+++ b/dictionary/templates/magic_qualifier_row.html
@@ -1,6 +1,6 @@
 <li id="magic_NUM">
-  {{ form.as_table }}
-  <button type="button" class="remove">
-    <span class="ui-icon ui-icon-closethick"></span>
-  </button>
+    {{ form.as_table }}
+    <button type="button" class="remove">
+        <span class="ui-icon ui-icon-closethick"></span>
+    </button>
 </li>
diff --git a/dictionary/templates/manage_classifications.html b/dictionary/templates/manage_classifications.html
index 3c30519..9641222 100644
--- a/dictionary/templates/manage_classifications.html
+++ b/dictionary/templates/manage_classifications.html
@@ -2,57 +2,60 @@
 {% load dictionary_extras %}
 
 {% block extrahead %}
-  <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/manage_classifications.css"/>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/manage-classifications.js"></script>
+    <link rel="stylesheet" type="text/css"
+          href="{{ MEDIA_URL }}css/manage_classifications.css"/>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/manage-classifications.js"></script>
 {% endblock %}
 
 {% block title %}Klasyfikacje{% endblock %}
 
 {% block content %}
-  <form action="" method="post" class="add-classification">
-    {% csrf_token %}
-    {{ add_form.as_p }}
-    <p>
-      <button type="submit">Dodaj klasyfikację</button>
-    </p>
-  </form>
-  {% for classification, value_form, vocab_form, using in classification_forms %}
-    <div class="classification">
-      <div class="classification-controls">
-        <form action="" method="post" class="add-value">
-          {% csrf_token %}
-          {{ value_form.as_p }}
-          <p>
-            <button type="submit">Dodaj wartość</button>
-          </p>
-        </form>
-        <div class="vocabs">
-          <p>Używające słowniki:</p>
-          {% if using %}
-            <ul>
-              {% for vocab in using %}
-                <li>{{ vocab.id }}</li>
-              {% endfor %}
-            </ul>
-          {% else %}
-            <p>brak</p>
-          {% endif %}
-          <form action="" method="post">
-            {% csrf_token %}
-            {{ vocab_form.as_p }}
-            <p>
-              <button type="submit">Dodaj słownik</button>
-            </p>
-          </form>
+    <form action="" method="post" class="add-classification">
+        {% csrf_token %}
+        {{ add_form.as_p }}
+        <p>
+            <button type="submit">Dodaj klasyfikację</button>
+        </p>
+    </form>
+    {% for classification, value_form, vocab_form, using in classification_forms %}
+        <div class="classification">
+            <div class="classification-controls">
+                <form action="" method="post" class="add-value">
+                    {% csrf_token %}
+                    {{ value_form.as_p }}
+                    <p>
+                        <button type="submit">Dodaj wartość</button>
+                    </p>
+                </form>
+                <div class="vocabs">
+                    <p>Używające słowniki:</p>
+                    {% if using %}
+                        <ul>
+                            {% for vocab in using %}
+                                <li>{{ vocab.id }}</li>
+                            {% endfor %}
+                        </ul>
+                    {% else %}
+                        <p>brak</p>
+                    {% endif %}
+                    <form action="" method="post">
+                        {% csrf_token %}
+                        {{ vocab_form.as_p }}
+                        <p>
+                            <button type="submit">Dodaj słownik</button>
+                        </p>
+                    </form>
+                </div>
+            </div>
+            <h4>{{ classification.name }}</h4>
+
+            <p>Wartości:</p>
+            {% with tree=classification.value_tree %}
+                {% if tree %}
+                    {% value_tree tree %}
+                {% endif %}
+            {% endwith %}
         </div>
-      </div>
-      <h4>{{ classification.name }}</h4>
-      <p>Wartości:</p>
-      {% with tree=classification.value_tree %}
-        {% if tree %}
-          {% value_tree tree %}
-        {% endif %}
-      {% endwith %}
-    </div>
-  {% endfor %}
+    {% endfor %}
 {% endblock %}
diff --git a/dictionary/templates/manage_qualifiers.html b/dictionary/templates/manage_qualifiers.html
index d917029..2f44e21 100644
--- a/dictionary/templates/manage_qualifiers.html
+++ b/dictionary/templates/manage_qualifiers.html
@@ -1,69 +1,73 @@
 {% extends "base.html" %}
 
 {% block extrahead %}
-  <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/manage_qualifiers.css"/>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/manage-qualifiers.js"></script>
+    <link rel="stylesheet" type="text/css"
+          href="{{ MEDIA_URL }}css/manage_qualifiers.css"/>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/manage-qualifiers.js"></script>
 {% endblock %}
 
 {% block title %}Kwalifikatory{% endblock %}
 
 {% block content %}
-  <div id="vocab-accordion">
-    {% for vocab_name, add_exclusion_class_form, remove_exclusion_class_form, add_qualifier_form, qualifier_forms in form_list %}
-      <h3><a href="#">{{ vocab_name }}</a></h3>
-      <div>
-        <form action="" method="post">
-          {% csrf_token %}
-          {{ add_exclusion_class_form.as_table }}
-          <button type="submit">
-            dodaj klasę wykluczania
-          </button>
-        </form>
-        {% if remove_exclusion_class_form %}
-          <form action="" method="post">
-            {% csrf_token %}
-            {{ remove_exclusion_class_form.as_table }}
-            <button type="submit">
-              usuń klasę wykluczania
-            </button>
-          </form>
-        {% endif %}
-        <form action="" method="post">
-          {% csrf_token %}
-          {{ add_qualifier_form.as_table }}
-          <button type="submit">
-            dodaj kwalifikator
-          </button>
-        </form>
-        <ul>
-          {% for qualifier, form in qualifier_forms %}
-            <li>
+    <div id="vocab-accordion">
+        {% for vocab_name, add_exclusion_class_form, remove_exclusion_class_form, add_qualifier_form, qualifier_forms in form_list %}
+            <h3><a href="#">{{ vocab_name }}</a></h3>
+            <div>
+                <form action="" method="post">
+                    {% csrf_token %}
+                    {{ add_exclusion_class_form.as_table }}
+                    <button type="submit">
+                        dodaj klasę wykluczania
+                    </button>
+                </form>
+                {% if remove_exclusion_class_form %}
+                    <form action="" method="post">
+                        {% csrf_token %}
+                        {{ remove_exclusion_class_form.as_table }}
+                        <button type="submit">
+                            usuń klasę wykluczania
+                        </button>
+                    </form>
+                {% endif %}
+                <form action="" method="post">
+                    {% csrf_token %}
+                    {{ add_qualifier_form.as_table }}
+                    <button type="submit">
+                        dodaj kwalifikator
+                    </button>
+                </form>
+                <ul>
+                    {% for qualifier, form in qualifier_forms %}
+                        <li>
               <span class="qualifier-label">
                 {{ qualifier.label }}
               </span>
               <span class="qualifier-controls">
                 {% if qualifier.is_empty %}
+                    <form action="" method="post">
+                        {% csrf_token %}
+                        <input type="hidden" name="det"
+                               value="remove_qualifier"/>
+                        <input type="hidden" name="id"
+                               value="{{ qualifier.pk }}"/>
+                        <button type="submit">
+                            usuń
+                        </button>
+                    </form>
+                {% endif %}
                   <form action="" method="post">
-                    {% csrf_token %}
-                    <input type="hidden" name="det" value="remove_qualifier"/>
-                    <input type="hidden" name="id" value="{{ qualifier.pk }}"/>
-                    <button type="submit">
-                      usuń
-                    </button>
+                      {% csrf_token %}
+                      {{ form.as_table }}
+                      <button type="submit">
+                          zmień
+                      </button>
                   </form>
-                {% endif %}
-                <form action="" method="post">
-                  {% csrf_token %}
-                  {{ form.as_table }}
-                  <button type="submit">
-                    zmień
-                  </button>
-                </form>
               </span>
-            </li>
-          {% endfor %}
-        </ul>
-      </div>
-    {% endfor %}
-  </div>
+                        </li>
+                    {% endfor %}
+                </ul>
+            </div>
+        {% endfor %}
+    </div>
 {% endblock %}
diff --git a/dictionary/templates/management_menu.html b/dictionary/templates/management_menu.html
index c51af0f..d942e6d 100644
--- a/dictionary/templates/management_menu.html
+++ b/dictionary/templates/management_menu.html
@@ -4,16 +4,17 @@
 {% block title %}Administracja{% endblock %}
 
 {% block content %}
-  <h3>Administracja</h3>
-  <ul>
-    {% if perms.dictionary.manage_vocabulary %}
-      <li><a href="{% url 'manager_view' %}">Słowniki</a></li>
-      <li><a href="{% url 'manage_classifications' %}">Klasyfikacje</a></li>
-      <li><a href="{% url 'manage_qualifiers' %}">Kwalifikatory</a></li>
-    {% endif %}
-    {% if perms.auth.add_user %}
-      <li><a href="{% url 'manage_groups' %}">Role</a></li>
-      <li><a href="{% url 'register' %}">Dodaj użytkownika</a></li>
-    {% endif %}
-  </ul>
+    <h3>Administracja</h3>
+    <ul>
+        {% if perms.dictionary.manage_vocabulary %}
+            <li><a href="{% url 'manager_view' %}">Słowniki</a></li>
+            <li><a href="{% url 'manage_classifications' %}">Klasyfikacje</a>
+            </li>
+            <li><a href="{% url 'manage_qualifiers' %}">Kwalifikatory</a></li>
+        {% endif %}
+        {% if perms.auth.add_user %}
+            <li><a href="{% url 'manage_groups' %}">Role</a></li>
+            <li><a href="{% url 'register' %}">Dodaj użytkownika</a></li>
+        {% endif %}
+    </ul>
 {% endblock %}
diff --git a/dictionary/templates/manager_view.html b/dictionary/templates/manager_view.html
index bba2e1d..fbce1eb 100644
--- a/dictionary/templates/manager_view.html
+++ b/dictionary/templates/manager_view.html
@@ -1,83 +1,85 @@
 {% extends "base.html" %}
 
 {% block extrahead %}
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/manager-view.js"></script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/manager-view.js"></script>
 {% endblock %}
 
 {% block title %}Słowniki{% endblock %}
 
 {% block content %}
-  <h3>Słowniki</h3>
-  <p>
-    <input type="text" id="new-vocabulary"/>
-    <button id="add-vocabulary">
-      dodaj słownik
-    </button>
-  </p>
-  <div id="vocab-accordion">
-    {% for vocab, managed, viewers, editors, managers in vocabularies_info %}
-      <h3><a href="#">{{ vocab.id }}</a></h3>
-      <div>
-        <table class="user-privileges" id="vocab-privileges_{{ vocab.pk }}">
-          <tr>
-            <th></th>
-            <th>ogląda</th>
-            <th>modyfikuje</th>
-            <th>zarządza</th>
-          </tr>
-          {% for u in users %}
-            <tr>
-              <td>{{ u.username }}</td>
-              <td>
-                {% if u.usersettings.views_lexeme%}
-                  <input
-                    type="checkbox"
-                    id="view-{{ u.pk }}"
-                    class="checkbox-view"
-                    {% if u in viewers %}
-                      checked="checked"
-                    {% endif %}
-                    {% if u.usersettings.views_all_lexemes or not managed %}
-                      disabled="disabled"
-                    {% endif %}/>
-                {% else %}
-                  <input type="checkbox" disabled="disabled"/>
-                {% endif %}
-              </td>
-              <td>
-                {% if u.usersettings.changes_lexeme %}
-                  <input
-                    type="checkbox"
-                    id="change-{{ u.pk }}"
-                    class="checkbox-change"
-                    {% if u in editors %}
-                      checked="checked"
-                    {% endif %}
-                    {% if not managed %}disabled="disabled"{% endif %}/>
-                {% else %}
-                  <input type="checkbox" disabled="disabled"/>
-                {% endif %}
-              </td>
-              <td>
-                {% if u.usersettings.manages_vocabulary %}
-                  <input
-                    type="checkbox"
-                    id="manage-{{ u.pk }}"
-                    class="checkbox-manage"
-                    {% if u in managers %}
-                      checked="checked"
-                    {% endif %}
-                    {% if u == user or not managed or u.usersettings.manages_all_vocabs %}
-                      disabled="disabled"
-                    {% endif %}/>
-                {% else %}
-                  <input type="checkbox" disabled="disabled"/>
-                {% endif %}
-              </td>
-            </tr>
-          {% endfor %}
-        </table>
-      </div>
-    {% endfor %}
-  </div>
+    <h3>Słowniki</h3>
+    <p>
+        <input type="text" id="new-vocabulary"/>
+        <button id="add-vocabulary">
+            dodaj słownik
+        </button>
+    </p>
+    <div id="vocab-accordion">
+        {% for vocab, managed, viewers, editors, managers in vocabularies_info %}
+            <h3><a href="#">{{ vocab.id }}</a></h3>
+            <div>
+                <table class="user-privileges"
+                       id="vocab-privileges_{{ vocab.pk }}">
+                    <tr>
+                        <th></th>
+                        <th>ogląda</th>
+                        <th>modyfikuje</th>
+                        <th>zarządza</th>
+                    </tr>
+                    {% for u in users %}
+                        <tr>
+                            <td>{{ u.username }}</td>
+                            <td>
+                                {% if u.usersettings.views_lexeme %}
+                                    <input
+                                            type="checkbox"
+                                            id="view-{{ u.pk }}"
+                                            class="checkbox-view"
+                                            {% if u in viewers %}
+                                            checked="checked"
+                                            {% endif %}
+                                            {% if u.usersettings.views_all_lexemes or not managed %}
+                                            disabled="disabled"
+                                            {% endif %}/>
+                                {% else %}
+                                    <input type="checkbox" disabled="disabled"/>
+                                {% endif %}
+                            </td>
+                            <td>
+                                {% if u.usersettings.changes_lexeme %}
+                                    <input
+                                            type="checkbox"
+                                            id="change-{{ u.pk }}"
+                                            class="checkbox-change"
+                                            {% if u in editors %}
+                                            checked="checked"
+                                            {% endif %}
+                                            {% if not managed %}disabled="disabled"{% endif %}/>
+                                {% else %}
+                                    <input type="checkbox" disabled="disabled"/>
+                                {% endif %}
+                            </td>
+                            <td>
+                                {% if u.usersettings.manages_vocabulary %}
+                                    <input
+                                            type="checkbox"
+                                            id="manage-{{ u.pk }}"
+                                            class="checkbox-manage"
+                                            {% if u in managers %}
+                                            checked="checked"
+                                            {% endif %}
+                                            {% if u == user or not managed or u.usersettings.manages_all_vocabs %}
+                                            disabled="disabled"
+                                            {% endif %}/>
+                                {% else %}
+                                    <input type="checkbox" disabled="disabled"/>
+                                {% endif %}
+                            </td>
+                        </tr>
+                    {% endfor %}
+                </table>
+            </div>
+        {% endfor %}
+    </div>
 {% endblock %}
diff --git a/dictionary/templates/new_action_row.html b/dictionary/templates/new_action_row.html
index 2077e06..2dad876 100644
--- a/dictionary/templates/new_action_row.html
+++ b/dictionary/templates/new_action_row.html
@@ -1,10 +1,10 @@
 <tr>
-  <td class="field">{{ form.field.as_widget }}</td>
-  <td class="action"></td>
-  <td class="value"></td>
-  <td>
-    <button type="button" class="delete-action-row">
-      <span class="ui-icon ui-icon-closethick"></span>
-    </button>
-  </td>
+    <td class="field">{{ form.field.as_widget }}</td>
+    <td class="action"></td>
+    <td class="value"></td>
+    <td>
+        <button type="button" class="delete-action-row">
+            <span class="ui-icon ui-icon-closethick"></span>
+        </button>
+    </td>
 </tr>
\ No newline at end of file
diff --git a/dictionary/templates/odm_forms.html b/dictionary/templates/odm_forms.html
index ce36537..cba857d 100644
--- a/dictionary/templates/odm_forms.html
+++ b/dictionary/templates/odm_forms.html
@@ -1,8 +1,8 @@
 <p>Grupy form odpowiadają wszystkim leksemom w sjp.pl z pasującym hasłem.</p>
 {% for forms in odm_lexemes %}
-  <ul class="forms">
-    {% for form in forms %}
-      <li>{{ form }}</li>
-    {% endfor %}
-  </ul>
+    <ul class="forms">
+        {% for form in forms %}
+            <li>{{ form }}</li>
+        {% endfor %}
+    </ul>
 {% endfor %}
diff --git a/dictionary/templates/pattern_edit_form.html b/dictionary/templates/pattern_edit_form.html
index 9ac1176..753a394 100644
--- a/dictionary/templates/pattern_edit_form.html
+++ b/dictionary/templates/pattern_edit_form.html
@@ -1,45 +1,47 @@
 <form action="" method="post" id="pattern-edit-form">
-  <p><input type="hidden" name="id" value="{{ id }}"/></p>
-  <div id="pattern-properties">
-    {{ type_form.as_p }}
-    {% for field in form %}
-      {% if field.name != 'basic_form_ending' %}
-        <p class="main-field">
-          {{ field.label_tag }} {{ field.as_widget }}
-          {% if field.name == 'example' %}
-            {{ form.basic_form_ending.as_widget }}
-          {% endif %}
-        </p>
-      {% endif %}
-    {% endfor %}
-    <p class="pattern-save">
-      <button type="submit" disabled="disabled" id="pattern-edit-submit">
-        Zapisz
-      </button>
-      <button type="reset" disabled="disabled" id="pattern-edit-cancel">
-        Anuluj
-      </button>
-    </p>
-  </div>
-  <table id="ending-list" {{ editable|yesno:'class="editable",'|safe }}>
-    {% for base_form_label, ending_group in ending_groups.iteritems %}
-      <tr>
-        <td><strong>{{ base_form_label.symbol }}</strong></td>
-        <td>
-          <ul class="ending-group" id="bfl-{{ base_form_label.symbol }}">
-            {% for ending, ro_qualifiers, form in ending_group %}
-              {% include 'ending_row.html' %}
-            {% endfor %}
-          </ul>
-        </td>
-        <td>
-          {% if editable %}
-            <button type="button" class="add-ending">
-              <span class="ui-icon ui-icon-plus"></span>
+    <p><input type="hidden" name="id" value="{{ pattern.id }}"/></p>
+
+    <div id="pattern-properties">
+        {{ type_form.as_p }}
+        {% for field in form %}
+            {% if field.name != 'basic_form_ending' %}
+                <p class="main-field">
+                    {{ field.label_tag }} {{ field.as_widget }}
+                    {% if field.name == 'example' %}
+                        {{ form.basic_form_ending.as_widget }}
+                    {% endif %}
+                </p>
+            {% endif %}
+        {% endfor %}
+        <p class="pattern-save">
+            <button type="submit" disabled="disabled" id="pattern-edit-submit">
+                Zapisz
+            </button>
+            <button type="reset" disabled="disabled" id="pattern-edit-cancel">
+                Anuluj
             </button>
-          {% endif %}
-        </td>
-      </tr>
-    {% endfor %}
-  </table>
+        </p>
+    </div>
+    <table id="ending-list" {{ editable|yesno:'class="editable",'|safe }}>
+        {% for base_form_label, ending_group in ending_groups.iteritems %}
+            <tr>
+                <td><strong>{{ base_form_label.symbol }}</strong></td>
+                <td>
+                    <ul class="ending-group"
+                        id="bfl-{{ base_form_label.symbol }}">
+                        {% for ending, ro_qualifiers, form in ending_group %}
+                            {% include 'ending_row.html' %}
+                        {% endfor %}
+                    </ul>
+                </td>
+                <td>
+                    {% if editable %}
+                        <button type="button" class="add-ending">
+                            <span class="ui-icon ui-icon-plus"></span>
+                        </button>
+                    {% endif %}
+                </td>
+            </tr>
+        {% endfor %}
+    </table>
 </form>
diff --git a/dictionary/templates/pattern_view.html b/dictionary/templates/pattern_view.html
index 759ac76..3180af9 100644
--- a/dictionary/templates/pattern_view.html
+++ b/dictionary/templates/pattern_view.html
@@ -2,63 +2,73 @@
 {% load i18n %}
 
 {% block extrahead %}
-  <link rel="stylesheet" href="{{ MEDIA_URL }}css/lib/ui.jqgrid.css" type="text/css" media="screen" charset="utf-8" />
-  <!--link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/lib/ui.multiselect.css"/-->
-  <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/lib/jquery.multiselect.css"/>
-  <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/jqgrid.css"/>
-  <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/pattern_view.css"/>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/lib/grid.locale-pl.js"></script>
-  <script type="text/javascript">
-    jQuery.jgrid.no_legacy_api = true;
-  </script>
-  <!--script type="text/javascript" src="{{ MEDIA_URL }}js/lib/ui.multiselect.js"></script-->
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/lib/jquery.jqGrid.src.js"></script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/lib/cvi_busy_lib.js"></script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/lib/splitter.js"></script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/lib/jquery.multiselect.js"></script>
-  <script type="text/javascript">
-    $.fn.multiselect2 = $.fn.multiselect;
-  </script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/jqgrid-patch.js"></script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/jqgrid.js"></script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/sort-dialog.js"></script>
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/pattern-view.js"></script>
+    <link rel="stylesheet" href="{{ MEDIA_URL }}css/lib/ui.jqgrid.css"
+          type="text/css" media="screen" charset="utf-8"/>
+    <!--link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}css/lib/ui.multiselect.css"/-->
+    <link rel="stylesheet" type="text/css"
+          href="{{ MEDIA_URL }}css/lib/jquery.multiselect.css"/>
+    <link rel="stylesheet" type="text/css"
+          href="{{ MEDIA_URL }}css/jqgrid.css"/>
+    <link rel="stylesheet" type="text/css"
+          href="{{ MEDIA_URL }}css/pattern_view.css"/>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/grid.locale-pl.js"></script>
+    <script type="text/javascript">
+        jQuery.jgrid.no_legacy_api = true;
+    </script>
+    <!--script type="text/javascript" src="{{ MEDIA_URL }}js/lib/ui.multiselect.js"></script-->
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/jquery.jqGrid.src.js"></script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/cvi_busy_lib.js"></script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/splitter.js"></script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/jquery.multiselect.js"></script>
+    <script type="text/javascript">
+        $.fn.multiselect2 = $.fn.multiselect;
+    </script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/jqgrid-patch.js"></script>
+    <script type="text/javascript" src="{{ MEDIA_URL }}js/jqgrid.js"></script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/pattern-view.js"></script>
 {% endblock %}
 
 {% block title %}Widok wzorów{% endblock %}
 
 {% block content %}
-  <div id="left">
-    <div id="search-panel">
-      <button id="open-sort-dialog" title="sortuj">
-        <span class="ui-icon ui-icon-sort">sortuj</span>
-      </button>
-      <button id="filter-button" title="filtruj">
-        <span class="ui-icon ui-icon-filter">filtruj</span>
-      </button>
-      <button id="show-columns-button" title="pokaż/ukryj">
-        <span class="ui-icon ui-icon-columns">pokaż/ukryj</span>
-      </button>
-      <input type="text" id="phrase_box" class="phrase-box"/>
-      <button id="searchButton" title="szukaj">
-        <span class="ui-icon ui-icon-search">szukaj</span>
-      </button>
+    <div id="left">
+        <div id="search-panel">
+            <button id="open-sort-dialog" title="sortuj">
+                <span class="ui-icon ui-icon-sort">sortuj</span>
+            </button>
+            <button id="filter-button" title="filtruj">
+                <span class="ui-icon ui-icon-filter">filtruj</span>
+            </button>
+            <button id="show-columns-button" title="pokaż/ukryj">
+                <span class="ui-icon ui-icon-columns">pokaż/ukryj</span>
+            </button>
+            <input type="text" id="phrase_box" class="phrase-box"/>
+            <button id="searchButton" title="szukaj">
+                <span class="ui-icon ui-icon-search">szukaj</span>
+            </button>
+        </div>
+        <table id="scroll"></table>
+        <!--div id="pager"></div-->
     </div>
-    <table id="scroll"></table>
-    <!--div id="pager"></div-->
-  </div>
-  <div id="right">
-    <div class="tabs">
-      <ul>
-        <li><a href="#edit" id="edit-tab">Edycja</a></li>
-      </ul>
-      <div id="edit">
-      </div>
+    <div id="right">
+        <div class="tabs">
+            <ul>
+                <li><a href="#edit" id="edit-tab">Edycja</a></li>
+            </ul>
+            <div id="edit">
+            </div>
+        </div>
     </div>
-  </div>
 {% endblock %}
 
 {% block modal_elements %}
-  <div id="sort-dialog">
-  </div>
+    <div id="sort-dialog">
+    </div>
 {% endblock %}
diff --git a/dictionary/templates/prompter_list.html b/dictionary/templates/prompter_list.html
index b20259c..febfc30 100644
--- a/dictionary/templates/prompter_list.html
+++ b/dictionary/templates/prompter_list.html
@@ -1,17 +1,18 @@
 {% for lip, cvs, prefix, suffix in lips %}
-  <tr class="prompter-row">
-    <td class="entry">{{ prefix }}<span class="suffix">{{ suffix }}</span></td>
-    <td class="ic">{{ lip.inflection_characteristic.symbol }}</td>
-    <td class="ic-id">{{ lip.inflection_characteristic.pk }}</td>
-    <td class="cv">
-      <ul>
-        {% for cv in cvs %}
-          <li>
-            {{ cv.label }}
-          </li>
-        {% endfor %}
-      </ul>
-    </td>
-    <td class="pattern">{{ lip.pattern.name }}</td>
-  </tr>
+    <tr class="prompter-row">
+        <td class="entry">{{ prefix }}<span class="suffix">{{ suffix }}</span>
+        </td>
+        <td class="ic">{{ lip.inflection_characteristic.symbol }}</td>
+        <td class="ic-id">{{ lip.inflection_characteristic.pk }}</td>
+        <td class="cv">
+            <ul>
+                {% for cv in cvs %}
+                    <li>
+                        {{ cv.label }}
+                    </li>
+                {% endfor %}
+            </ul>
+        </td>
+        <td class="pattern">{{ lip.pattern.name }}</td>
+    </tr>
 {% endfor %}
diff --git a/dictionary/templates/reports.html b/dictionary/templates/reports.html
index 8e2322d..9b6663c 100644
--- a/dictionary/templates/reports.html
+++ b/dictionary/templates/reports.html
@@ -3,7 +3,7 @@
 {% block title %}Raporty{% endblock %}
 
 {% block content %}
-<p>
-  Tu będą różnorodne zestawienia pokazujące stan opracowywanego słownika.
-</p>
+    <p>
+        Tu będą różnorodne zestawienia pokazujące stan opracowywanego słownika.
+    </p>
 {% endblock %}
diff --git a/dictionary/templates/sort_dialog.html b/dictionary/templates/sort_dialog.html
index 9a72edb..6b8d7c9 100644
--- a/dictionary/templates/sort_dialog.html
+++ b/dictionary/templates/sort_dialog.html
@@ -1,23 +1,23 @@
 <div id="sort-dialog-form" title="Porządek sortowania">
-  <ul id='sort-rule-list'>
-  {% for rule in sort_rules %}
-    <li id="{{rule.code_name}}" class="ui-state-default">
-      <span class="sort-column">{{rule.ui_name}}</span>
+    <ul id='sort-rule-list'>
+        {% for rule in sort_rules %}
+            <li id="{{ rule.code_name }}" class="ui-state-default">
+                <span class="sort-column">{{ rule.ui_name }}</span>
       <span class="sort-dir">
-        <select id="order-{{rule.code_name}}">
-          <option value="asc">Rosnąco</option>
-          <option value="desc">Malejąco</option>
+        <select id="order-{{ rule.code_name }}">
+            <option value="asc">Rosnąco</option>
+            <option value="desc">Malejąco</option>
         </select>
       </span>
-      {% if rule.code_name == "entry" %}
-        <span class="sort-a-tergo">
+                {% if rule.code_name == "entry" %}
+                    <span class="sort-a-tergo">
           <input type="checkbox" id="entries_a_tergo"/> a tergo
         </span>
-      {% endif %}
-    </li>
-  {% endfor %}
-  </ul>
-  
-  <input type="button" id="save-sort-order" value="Zatwierdź"/>
-  <input type="button" id="cancel-sort-order" value="Anuluj"/>
+                {% endif %}
+            </li>
+        {% endfor %}
+    </ul>
+
+    <input type="button" id="save-sort-order" value="Zatwierdź"/>
+    <input type="button" id="cancel-sort-order" value="Anuluj"/>
 </div>
diff --git a/dictionary/templates/tasks.html b/dictionary/templates/tasks.html
index 444f7f5..47350d0 100644
--- a/dictionary/templates/tasks.html
+++ b/dictionary/templates/tasks.html
@@ -3,7 +3,7 @@
 {% block title %}Zadania{% endblock %}
 
 {% block content %}
-<p>
-  Tu będzie lista zadań do wykonania przez danego użytkownika.
-</p>
+    <p>
+        Tu będzie lista zadań do wykonania przez danego użytkownika.
+    </p>
 {% endblock %}
diff --git a/dictionary/templatetags/dictionary_extras.py b/dictionary/templatetags/dictionary_extras.py
index b030dc6..22cf084 100644
--- a/dictionary/templatetags/dictionary_extras.py
+++ b/dictionary/templatetags/dictionary_extras.py
@@ -9,18 +9,20 @@ register = template.Library()
 # potrzebne do rekurencji
 @register.inclusion_tag('classification_value_tree.html')
 def value_tree(tree):
-  return {'value_tree': tree}
+    return {'value_tree': tree}
+
 
 @register.filter
 def lexeme_table(row):
-  return lexeme_table_from_row(row)
+    return lexeme_table_from_row(row)
+
 
 @register.filter
 def attribute(lexeme, attr_name):
-  attribute = LexemeAttribute.objects.get(name=attr_name)
-  if attribute.multiple:
-    return lexeme.attribute_value(attribute).values_list(
-      'display_value', flat=True)
-  else:
-    attr = lexeme.attribute_value(attribute)
-    return attr.display_value if attr else ''
+    attribute = LexemeAttribute.objects.get(name=attr_name)
+    if attribute.multiple:
+        return lexeme.attribute_value(attribute).values_list(
+            'display_value', flat=True)
+    else:
+        attr = lexeme.attribute_value(attribute)
+        return attr.display_value if attr else ''
diff --git a/dictionary/tests.py b/dictionary/tests.py
index 2247054..9ebde4c 100644
--- a/dictionary/tests.py
+++ b/dictionary/tests.py
@@ -7,6 +7,7 @@ Replace these with more appropriate tests for your application.
 
 from django.test import TestCase
 
+
 class SimpleTest(TestCase):
     def test_basic_addition(self):
         """
@@ -14,6 +15,7 @@ class SimpleTest(TestCase):
         """
         self.failUnlessEqual(1 + 1, 2)
 
+
 __test__ = {"doctest": """
 Another way to test that 1 + 1 is equal to 2.
 
diff --git a/dictionary/util.py b/dictionary/util.py
index 45b3f43..895076b 100644
--- a/dictionary/util.py
+++ b/dictionary/util.py
@@ -2,46 +2,51 @@
 
 from dictionary.models import BaseFormLabel
 
+
 def expand_tag(tag):
-  if '+' in tag:
-    tags = tag.split('+')
+    if '+' in tag:
+        tags = tag.split('+')
+        expanded = []
+        for tag in tags:
+            expanded += expand_tag(tag)
+        return expanded
+    parts = tag.split(':')
+    variants_list = []
+    for part in parts:
+        variants_list.append(part.split('.'))
+        #return [':'.join(parts) for parts in expand_variants(variants_list)]
+    return expand_variants(variants_list)
+
+
+def expand_variants(variants_list):
+    if not variants_list:
+        return [()]
     expanded = []
-    for tag in tags:
-      expanded += expand_tag(tag)
+    tails = expand_variants(variants_list[1:])
+    for variant in variants_list[0]:
+        expanded += [(variant,) + tail for tail in tails]
     return expanded
-  parts = tag.split(':')
-  variants_list = []
-  for part in parts:
-    variants_list.append(part.split('.'))
-  #return [':'.join(parts) for parts in expand_variants(variants_list)]
-  return expand_variants(variants_list)
 
-def expand_variants(variants_list):
-  if not variants_list:
-    return [()]
-  expanded = []
-  tails = expand_variants(variants_list[1:])
-  for variant in variants_list[0]:
-    expanded += [(variant,) + tail for tail in tails]
-  return expanded
 
 def compare_patterns(patterns):
-  pattern0, root0 = patterns[0]
-  bfl_pks0 = set(pattern0.endings.values_list('base_form_label', flat=True))
-  differing_bfls = set()
-  forms = dict((p, dict((bfl, root + e) for bfl, e
-                        in p.endings.values_list('base_form_label', 'string')))
-               for p, root in patterns)
-  for pattern, root in patterns[1:]:
-    bfl_pks = set(pattern.endings.values_list('base_form_label', flat=True))
-    for pk in bfl_pks ^ bfl_pks0: # różnica symetryczna
-      differing_bfls.add(pk)
-    for ending in pattern.endings.all():
-      if ending.base_form_label.pk not in differing_bfls:
-        if root + ending.string != forms[pattern0][ending.base_form_label.pk]:
-          differing_bfls.add(ending.base_form_label.pk)
-  differing_bfls = list(BaseFormLabel.objects.filter(pk__in=differing_bfls))
-  diffs = dict((pattern, [(bfl, forms[pattern].get(bfl.pk))
-                          for bfl in differing_bfls])
-               for pattern, root in patterns)
-  return diffs
+    pattern0, root0 = patterns[0]
+    bfl_pks0 = set(pattern0.endings.values_list('base_form_label', flat=True))
+    differing_bfls = set()
+    forms = dict((p, dict((bfl, root + e) for bfl, e
+                          in
+                          p.endings.values_list('base_form_label', 'string')))
+                 for p, root in patterns)
+    for pattern, root in patterns[1:]:
+        bfl_pks = set(pattern.endings.values_list('base_form_label', flat=True))
+        for pk in bfl_pks ^ bfl_pks0: # różnica symetryczna
+            differing_bfls.add(pk)
+        for ending in pattern.endings.all():
+            if ending.base_form_label.pk not in differing_bfls:
+                if root + ending.string != forms[pattern0][
+                    ending.base_form_label.pk]:
+                    differing_bfls.add(ending.base_form_label.pk)
+    differing_bfls = list(BaseFormLabel.objects.filter(pk__in=differing_bfls))
+    diffs = dict((pattern, [(bfl, forms[pattern].get(bfl.pk))
+                            for bfl in differing_bfls])
+                 for pattern, root in patterns)
+    return diffs
diff --git a/dictionary/views.py b/dictionary/views.py
index 76aead1..74a644c 100644
--- a/dictionary/views.py
+++ b/dictionary/views.py
@@ -11,348 +11,366 @@ from common.decorators import render
 from common.util import make_form
 from paginer import PaginationList
 from paginer.decorators import paginated
-from dictionary.forms import AddClassificationForm, ExclusionClassForm,\
-  AddClassificationValueForm, VocabularyForm, AddExclusionClassForm, \
-  AddQualifierForm, ChangeClassForm, ExportForm, MagicQualifierForm
+from dictionary.forms import AddClassificationForm, ExclusionClassForm, \
+    AddClassificationValueForm, VocabularyForm, AddExclusionClassForm, \
+    AddQualifierForm, ChangeClassForm, ExportForm, MagicQualifierForm
 from dictionary.models import visible_vocabularies, PartOfSpeech, Lexeme, \
-  Vocabulary, Classification, ClassificationValue, Qualifier, History, \
-  QualifierExclusionClass, get_exclusion_classes, editable_vocabularies, \
-  managed_vocabularies, CrossReferenceType
+    Vocabulary, Classification, ClassificationValue, Qualifier, History, \
+    QualifierExclusionClass, get_exclusion_classes, editable_vocabularies, \
+    managed_vocabularies, CrossReferenceType
 from dictionary.history import lexeme_tables
 from dictionary.export import export_lexemes
 from dictionary.wsjp import make_data
 
+
 def join_options(options):
-  return ';'.join('%s:%s' % pair for pair in options)
+    return ';'.join('%s:%s' % pair for pair in options)
+
 
 @permission_required('dictionary.view_lexeme')
 @render()
 def lexeme_view(request):
-  exclusion_classes = get_exclusion_classes()
-  visible = visible_vocabularies(request.user)
-  editable_vocabs = editable_vocabularies(request.user)
-  vocabs = {}
-  for v in editable_vocabs:
-    vocabs.update(dict((str(q.pk), v.id) for q in v.qualifiers.all()))
-  qualifier_options = []
-  for vocab in visible:
-    qualifiers = vocab.qualifiers.all()
-    if qualifiers:
-      qualifier_options.append((0, '--%s--' % vocab.id))
-      for q in vocab.qualifiers.all():
-        qualifier_options.append((q.pk, q.label))
-  classifications = Classification.objects.filter(
-    vocabularies__in=visible).distinct()
-  cv_options = []
-  for classification in classifications:
-    cv_options.append((0, '--%s--' % classification.name))
-    cv_options += classification.make_choices()
-  cr_type_options = []
-  for cr_type in CrossReferenceType.objects.order_by('symbol'):
-    cr_type_options.append(
-      (cr_type.pk,
-       '%s %s->%s' % (cr_type.symbol, cr_type.from_pos, cr_type.to_pos)))
-  default_owner = request.user.usersettings.default_owner
-  js_vars = {
-    'ajax_get_page': reverse('get_lexemes'),
-    'ajax_inflection_tables': reverse('get_inflection_tables'),
-    'ajax_history_table': reverse('history_table'),
-    'ajax_odm_forms': reverse('odm_forms'),
-    'ajax_edit_form': reverse('lexeme_edit_form'),
-    'ajax_update_lexeme': reverse('update_lexeme'),
-    'ajax_location': reverse('get_location'),
-    'ajax_find_id': reverse('find_id'),
-    'ajax_save_filter': reverse('save_filter'),
-    'ajax_get_filters': reverse('get_filters'),
-    'ajax_delete_filter': reverse('delete_filter'),
-    'ajax_table_preview': reverse('table_preview'),
-    'ajax_new_lip_row': reverse('new_lip_edit_row'),
-    'ajax_new_cr_row': reverse('new_cross_reference_row'),
-    'ajax_save_columns': reverse('save_columns'),
-    'ajax_delete_lexeme': reverse('delete_lexeme'),
-    'ajax_prompter_list': reverse('prompter_list'),
-    'ajax_check_pos': reverse('check_pos'),
-    'ajax_check_pattern': reverse('check_pattern'),
-    'ajax_check_classifications': reverse('check_classifications'),
-    'ajax_get_ics': reverse('get_ics'),
-    'ajax_save_default_owner': reverse('save_default_owner'),
-    'ajax_create_lexeme': reverse('create_lexeme'),
-    'ajax_classification_forms': reverse('classification_forms'),
-    'ajax_extra_attributes': reverse('extra_attributes'),
-    'ajax_check_attributes': reverse('check_attributes'),
-    'ajax_homonym_count': reverse('homonym_count'),
-    'ajax_cr_homonyms': reverse('cr_homonyms'),
-    'ajax_new_action_row': reverse('new_action_row'),
-    'ajax_dynamic_fields': reverse('dynamic_action_fields'),
-    'ajax_execute_actions': reverse('execute_group_actions'),
-    'visible_vocabularies': join_options((v.pk, v.id) for v in visible),
-    'vocabs': vocabs,
-    'parts_of_speech': join_options(
-      (pos.pk, pos.symbol) for pos in PartOfSpeech.objects.all()),
-    'qualifier_options': join_options(qualifier_options),
-    'cv_options': join_options(cv_options),
-    'commonness': Classification.objects.get(name=u'pospolitość').pk,
-    'exclusion_classes': exclusion_classes,
-    'status_options': dict(Lexeme.STATUS_CHOICES),
-    'cr_type_options': join_options(cr_type_options),
-    'filtering_mode': request.user.usersettings.filter_search,
-    'auto_search': request.user.usersettings.incremental_search,
-    'default_owner': default_owner.id if default_owner else '',
-  }
-  session_variables = ('filters', 'sort_rules', 'colModel', 'colNames', 'remap')
-  for var in session_variables:
-    if var in request.session:
-      js_vars[var] = request.session[var]
-  return {'js_vars': js_vars, 'editable_vocabularies': editable_vocabs}
+    exclusion_classes = get_exclusion_classes()
+    visible = visible_vocabularies(request.user)
+    editable_vocabs = editable_vocabularies(request.user)
+    vocabs = {}
+    for v in editable_vocabs:
+        vocabs.update(dict((str(q.pk), v.id) for q in v.qualifiers.all()))
+    qualifier_options = []
+    for vocab in visible:
+        qualifiers = vocab.qualifiers.all()
+        if qualifiers:
+            qualifier_options.append((0, '--%s--' % vocab.id))
+            for q in vocab.qualifiers.all():
+                qualifier_options.append((q.pk, q.label))
+    classifications = Classification.objects.filter(
+        vocabularies__in=visible).distinct()
+    cv_options = []
+    for classification in classifications:
+        cv_options.append((0, '--%s--' % classification.name))
+        cv_options += classification.make_choices()
+    cr_type_options = []
+    for cr_type in CrossReferenceType.objects.order_by('symbol'):
+        cr_type_options.append(
+            (cr_type.pk,
+             '%s %s->%s' % (cr_type.symbol, cr_type.from_pos, cr_type.to_pos)))
+    default_owner = request.user.usersettings.default_owner
+    js_vars = {
+        'ajax_get_page': reverse('get_lexemes'),
+        'ajax_inflection_tables': reverse('get_inflection_tables'),
+        'ajax_history_table': reverse('history_table'),
+        'ajax_odm_forms': reverse('odm_forms'),
+        'ajax_edit_form': reverse('lexeme_edit_form'),
+        'ajax_update_lexeme': reverse('update_lexeme'),
+        'ajax_location': reverse('get_location'),
+        'ajax_find_id': reverse('find_id'),
+        'ajax_save_filter': reverse('save_filter'),
+        'ajax_get_filters': reverse('get_filters'),
+        'ajax_delete_filter': reverse('delete_filter'),
+        'ajax_table_preview': reverse('table_preview'),
+        'ajax_new_lip_row': reverse('new_lip_edit_row'),
+        'ajax_new_cr_row': reverse('new_cross_reference_row'),
+        'ajax_save_columns': reverse('save_columns'),
+        'ajax_delete_lexeme': reverse('delete_lexeme'),
+        'ajax_prompter_list': reverse('prompter_list'),
+        'ajax_check_pos': reverse('check_pos'),
+        'ajax_check_pattern': reverse('check_pattern'),
+        'ajax_check_classifications': reverse('check_classifications'),
+        'ajax_get_ics': reverse('get_ics'),
+        'ajax_save_default_owner': reverse('save_default_owner'),
+        'ajax_create_lexeme': reverse('create_lexeme'),
+        'ajax_classification_forms': reverse('classification_forms'),
+        'ajax_extra_attributes': reverse('extra_attributes'),
+        'ajax_check_attributes': reverse('check_attributes'),
+        'ajax_homonym_count': reverse('homonym_count'),
+        'ajax_cr_homonyms': reverse('cr_homonyms'),
+        'ajax_new_action_row': reverse('new_action_row'),
+        'ajax_dynamic_fields': reverse('dynamic_action_fields'),
+        'ajax_execute_actions': reverse('execute_group_actions'),
+        'visible_vocabularies': join_options((v.pk, v.id) for v in visible),
+        'vocabs': vocabs,
+        'parts_of_speech': join_options(
+            (pos.pk, pos.symbol) for pos in PartOfSpeech.objects.all()),
+        'qualifier_options': join_options(qualifier_options),
+        'cv_options': join_options(cv_options),
+        'commonness': Classification.objects.get(name=u'pospolitość').pk,
+        'exclusion_classes': exclusion_classes,
+        'status_options': dict(Lexeme.STATUS_CHOICES),
+        'cr_type_options': join_options(cr_type_options),
+        'filtering_mode': request.user.usersettings.filter_search,
+        'auto_search': request.user.usersettings.incremental_search,
+        'default_owner': default_owner.id if default_owner else '',
+    }
+    session_variables = (
+    'filters', 'sort_rules', 'colModel', 'colNames', 'remap')
+    for var in session_variables:
+        if var in request.session:
+            js_vars[var] = request.session[var]
+    return {'js_vars': js_vars, 'editable_vocabularies': editable_vocabs}
+
 
 @permission_required('dictionary.view_pattern')
 @render()
 def pattern_view(request):
-  js_vars = {
-    'ajax_get_page': reverse('get_patterns'),
-    'ajax_edit_form': reverse('pattern_edit_form'),
-    'ajax_update_pattern': reverse('update_pattern'),
-    'ajax_find_id': reverse('patterns_find_id'),
-    'ajax_location': reverse('patterns_get_location'),
-    'ajax_save_columns': reverse('patterns_save_columns'),
-    'ajax_new_ending_row': reverse('new_ending_row'),
-    'exclusion_classes': get_exclusion_classes(),
-    'filtering_mode': request.user.usersettings.filter_search,
-    'auto_search' : request.user.usersettings.incremental_search,
-  }
-  session_variables = (
-    'pattern-filters',
-    'pattern-sort_rules',
-    'pattern-colModel',
-    'pattern-colNames',
-    'pattern-remap'
-  )
-  for var in session_variables:
-    if var in request.session:
-      js_name = var.split('-', 1)[1]
-      js_vars[js_name] = request.session[var]
-  return {'js_vars': js_vars}
+    js_vars = {
+        'ajax_get_page': reverse('get_patterns'),
+        'ajax_edit_form': reverse('pattern_edit_form'),
+        'ajax_update_pattern': reverse('update_pattern'),
+        'ajax_find_id': reverse('patterns_find_id'),
+        'ajax_location': reverse('patterns_get_location'),
+        'ajax_save_columns': reverse('patterns_save_columns'),
+        'ajax_new_ending_row': reverse('new_ending_row'),
+        'exclusion_classes': get_exclusion_classes(),
+        'filtering_mode': request.user.usersettings.filter_search,
+        'auto_search': request.user.usersettings.incremental_search,
+    }
+    session_variables = (
+        'pattern-filters',
+        'pattern-sort_rules',
+        'pattern-colModel',
+        'pattern-colNames',
+        'pattern-remap'
+    )
+    for var in session_variables:
+        if var in request.session:
+            js_name = var.split('-', 1)[1]
+            js_vars[js_name] = request.session[var]
+    return {'js_vars': js_vars}
+
 
 @login_required
 @render()
 def tasks(request):
-  return {}
+    return {}
+
 
 @login_required
 @render()
 def reports(request):
-  return {}
+    return {}
+
 
 @login_required
 @render()
 def management_menu(request):
-  return {}
+    return {}
+
 
 @permission_required('dictionary.manage_vocabulary')
 @render()
 def manager_view(request):
-  to_return = {
-    'users': User.objects.order_by('username'),
-    'vocabularies_info': [
-      (v, request.user in v.all_managers(),
-       v.all_viewers(), v.all_editors(), v.all_managers())
-      for v in Vocabulary.objects.order_by('id')],
-    'js_vars': {
-      'ajax_add_vocabulary': reverse('add_vocabulary'),
-      #'ajax_get_permissions': reverse('vocabulary_permissions'),
-      'ajax_set_permission': reverse('set_vocabulary_permission'),
-    },
-  }
-  return to_return
+    to_return = {
+        'users': User.objects.order_by('username'),
+        'vocabularies_info': [
+            (v, request.user in v.all_managers(),
+             v.all_viewers(), v.all_editors(), v.all_managers())
+            for v in Vocabulary.objects.order_by('id')],
+        'js_vars': {
+            'ajax_add_vocabulary': reverse('add_vocabulary'),
+            #'ajax_get_permissions': reverse('vocabulary_permissions'),
+            'ajax_set_permission': reverse('set_vocabulary_permission'),
+        },
+    }
+    return to_return
+
 
 @permission_required('dictionary.manage_vocabulary')
 @render()
 def manage_classifications(request):
-  to_return = {}
-  add_form = make_form(request, AddClassificationForm)
-  if add_form.is_valid():
-    add_form.save()
-  to_return['add_form'] = add_form
-  if request.POST.get('det') == 'value_form':
-    add_form = AddClassificationValueForm(data=request.POST)
+    to_return = {}
+    add_form = make_form(request, AddClassificationForm)
     if add_form.is_valid():
-      add_form.save()
-  if request.POST.get('det') == 'vocabulary_form':
-    form = VocabularyForm(
-      data=request.POST, queryset=managed_vocabularies(request.user))
-    if form.is_valid():
-      c = form.cleaned_data['classification']
-      v = form.cleaned_data['vocabulary']
-      c.vocabularies.add(v) #add
-  if request.POST.get('det') == 'value_remove':
-    pk = int(request.POST['id'])
-    try:
-      cv = ClassificationValue.objects.get(pk=pk)
-      cv.deleted = True
-      cv.save()
-    except ClassificationValue.DoesNotExist:
-      pass
-  if request.POST.get('det') == 'value_rename':
-    pk = int(request.POST['id'])
-    label = request.POST['new_name']
-    try:
-      v = ClassificationValue.objects.get(pk=pk)
-      v.label = label
-      v.save()
-    except ClassificationValue.DoesNotExist:
-      pass
-  if request.POST:
-    return HttpResponseRedirect(reverse('manage_classifications'))
+        add_form.save()
+    to_return['add_form'] = add_form
+    if request.POST.get('det') == 'value_form':
+        add_form = AddClassificationValueForm(data=request.POST)
+        if add_form.is_valid():
+            add_form.save()
+    if request.POST.get('det') == 'vocabulary_form':
+        form = VocabularyForm(
+            data=request.POST, queryset=managed_vocabularies(request.user))
+        if form.is_valid():
+            c = form.cleaned_data['classification']
+            v = form.cleaned_data['vocabulary']
+            c.vocabularies.add(v) #add
+    if request.POST.get('det') == 'value_remove':
+        pk = int(request.POST['id'])
+        try:
+            cv = ClassificationValue.objects.get(pk=pk)
+            cv.deleted = True
+            cv.save()
+        except ClassificationValue.DoesNotExist:
+            pass
+    if request.POST.get('det') == 'value_rename':
+        pk = int(request.POST['id'])
+        label = request.POST['new_name']
+        try:
+            v = ClassificationValue.objects.get(pk=pk)
+            v.label = label
+            v.save()
+        except ClassificationValue.DoesNotExist:
+            pass
+    if request.POST:
+        return HttpResponseRedirect(reverse('manage_classifications'))
+
+    classification_forms = []
+    for c in Classification.objects.all():
+        value_form = AddClassificationValueForm(classification=c)
+        vocabs = managed_vocabularies(request.user)
+        using = c.vocabularies.all() & vocabs
+        other = vocabs.exclude(pk__in=using.values_list('pk', flat=True))
+        vocab_form = VocabularyForm(classification=c, queryset=other)
+        classification_forms.append((c, value_form, vocab_form, using))
+    to_return['classification_forms'] = classification_forms
+    return to_return
 
-  classification_forms = []
-  for c in Classification.objects.all():
-    value_form = AddClassificationValueForm(classification=c)
-    vocabs = managed_vocabularies(request.user)
-    using = c.vocabularies.all() & vocabs
-    other = vocabs.exclude(pk__in=using.values_list('pk', flat=True))
-    vocab_form = VocabularyForm(classification=c, queryset=other)
-    classification_forms.append((c, value_form, vocab_form, using))
-  to_return['classification_forms'] = classification_forms
-  return to_return
 
 @permission_required('dictionary.manage_vocabulary')
 @render()
 def manage_qualifiers(request):
-  det = request.POST.get('det')
-  if det == 'add_exclusion_class':
-    form = AddExclusionClassForm(data=request.POST)
-    if form.is_valid():
-      form.save()
-  if det == 'remove_exclusion_class':
-    form = ExclusionClassForm(data=request.POST)
-    if form.is_valid():
-      ec = form.cleaned_data['ec']
-      ec.delete()
-  if det == 'add_qualifier':
-    form = AddQualifierForm(data=request.POST)
-    if form.is_valid():
-      form.save()
-  prefix = q = None
-  for name, _value in request.POST.iteritems():
-    if name.startswith('cec'):
-      prefix = name.split('-')[0]
-      q = Qualifier.objects.get(pk=int(prefix[3:]))
-      break
-  if prefix:
-    form = ChangeClassForm(data=request.POST, instance=q, prefix=prefix)
-    if form.is_valid():
-      form.save()
-  if det == 'remove_qualifier':
-    pk = int(request.POST['id'])
-    try:
-      q = Qualifier.objects.get(pk=pk)
-      q.deleted = True
-      q.save()
-    except Qualifier.DoesNotExist:
-      pass
-  if request.POST:
-    return HttpResponseRedirect(reverse('manage_qualifiers'))
+    det = request.POST.get('det')
+    if det == 'add_exclusion_class':
+        form = AddExclusionClassForm(data=request.POST)
+        if form.is_valid():
+            form.save()
+    if det == 'remove_exclusion_class':
+        form = ExclusionClassForm(data=request.POST)
+        if form.is_valid():
+            ec = form.cleaned_data['ec']
+            ec.delete()
+    if det == 'add_qualifier':
+        form = AddQualifierForm(data=request.POST)
+        if form.is_valid():
+            form.save()
+    prefix = q = None
+    for name, _value in request.POST.iteritems():
+        if name.startswith('cec'):
+            prefix = name.split('-')[0]
+            q = Qualifier.objects.get(pk=int(prefix[3:]))
+            break
+    if prefix:
+        form = ChangeClassForm(data=request.POST, instance=q, prefix=prefix)
+        if form.is_valid():
+            form.save()
+    if det == 'remove_qualifier':
+        pk = int(request.POST['id'])
+        try:
+            q = Qualifier.objects.get(pk=pk)
+            q.deleted = True
+            q.save()
+        except Qualifier.DoesNotExist:
+            pass
+    if request.POST:
+        return HttpResponseRedirect(reverse('manage_qualifiers'))
+
+    to_return = {}
+    form_list = []
+    for vocabulary in managed_vocabularies(request.user):
+        add_exclusion_class_form = AddExclusionClassForm(vocabulary=vocabulary)
+        empty_ec = QualifierExclusionClass.objects.filter(
+            vocabulary=vocabulary).extra(where=[
+            'not exists (select * from kwalifikatory '
+            'where klasa = klasy_wykluczania.id)'])
+        if empty_ec:
+            remove_exclusion_class_form = ExclusionClassForm(queryset=empty_ec)
+        else:
+            remove_exclusion_class_form = None
+        add_qualifier_form = AddQualifierForm(vocabulary=vocabulary)
+        qualifiers = Qualifier.objects.filter(vocabulary=vocabulary)
+        qualifier_forms = []
+        for q in qualifiers:
+            change_class_form = ChangeClassForm(instance=q,
+                                                prefix='cec%s' % q.pk)
+            qualifier_forms.append((q, change_class_form))
+        form_list.append(
+            (vocabulary.id, add_exclusion_class_form,
+             remove_exclusion_class_form,
+             add_qualifier_form, qualifier_forms))
+    to_return['form_list'] = form_list
+    return to_return
 
-  to_return = {}
-  form_list = []
-  for vocabulary in managed_vocabularies(request.user):
-    add_exclusion_class_form = AddExclusionClassForm(vocabulary=vocabulary)
-    empty_ec = QualifierExclusionClass.objects.filter(
-      vocabulary=vocabulary).extra(where=[
-        'not exists (select * from kwalifikatory '
-        'where klasa = klasy_wykluczania.id)'])
-    if empty_ec:
-      remove_exclusion_class_form = ExclusionClassForm(queryset=empty_ec)
-    else:
-      remove_exclusion_class_form = None
-    add_qualifier_form = AddQualifierForm(vocabulary=vocabulary)
-    qualifiers = Qualifier.objects.filter(vocabulary=vocabulary)
-    qualifier_forms = []
-    for q in qualifiers:
-      change_class_form = ChangeClassForm(instance=q, prefix='cec%s' % q.pk)
-      qualifier_forms.append((q, change_class_form))
-    form_list.append(
-      (vocabulary.id, add_exclusion_class_form, remove_exclusion_class_form,
-       add_qualifier_form, qualifier_forms))
-  to_return['form_list'] = form_list
-  return to_return
 
 @permission_required('dictionary.view_lexeme')
 @render()
 @paginated
 def history_view(request):
-  paginer = PaginationList()
-  lexeme_history = History.objects.exclude(lexeme=None).distinct().values(
-    'lexeme', 'user', 'transaction_began')
-  paginer.add('lexeme_items', 'lexeme_history', {
-    'columns': ('lexeme',),
-    'order_by': '-transaction_began',
-    'filters': [('user', 'ne', u'Kuźniobot')],
-    'sort_fields': (),
-    'filter_fields': ('user', 'time_from', 'time_to'),
-  })
-  return {
-    'lexeme_tables': lexeme_tables(lexeme_history),
-    'show_lexemes': True,
-    'paginer': paginer,
-  }
+    paginer = PaginationList()
+    lexeme_history = History.objects.exclude(lexeme=None).distinct().values(
+        'lexeme', 'user', 'transaction_began')
+    paginer.add('lexeme_items', 'lexeme_history', {
+        'columns': ('lexeme',),
+        'order_by': '-transaction_began',
+        'filters': [('user', 'ne', u'Kuźniobot')],
+        'sort_fields': (),
+        'filter_fields': ('user', 'time_from', 'time_to'),
+    })
+    return {
+        'lexeme_tables': lexeme_tables(lexeme_history),
+        'show_lexemes': True,
+        'paginer': paginer,
+    }
+
 
 @permission_required('dictionary.export_lexemes')
 @render()
 def export(request):
-  if request.GET:
-    form = ExportForm(data=request.GET)
-    if form.is_valid():
-      data = {
-        'vocabs': [v.id for v in form.cleaned_data['vocabs']],
-        'antivocabs': [v.id for v in form.cleaned_data['antivocabs']],
-        'variant': form.cleaned_data['variant'].id,
-      }
-      #data['excluding_qualifiers'] = [
-      #  q.pk for q in form.cleaned_data['excluding_qualifiers']]
-      magic_ids = set()
-      magic_qualifiers = []
-      normal_qualifiers = []
-      for key in request.GET:
-        split_key = key.split('-')
-        if key.startswith('magic') and split_key[0] not in magic_ids:
-          i, name = split_key
-          magic_ids.add(i)
-          magic_form = MagicQualifierForm(prefix=i, data=request.GET)
-          if magic_form.is_valid():
-            regex = magic_form.cleaned_data['regex']
-            if regex:
-              magic_qualifiers.append(
-                (regex, magic_form.cleaned_data['qualifier'].pk))
-            else:
-              normal_qualifiers.append(magic_form.cleaned_data['qualifier'].pk)
-      data['magic_qualifiers'] = magic_qualifiers
-      data['excluding_qualifiers'] = normal_qualifiers
-      data['refl'] = form.cleaned_data['refl']
-      data['commonness'] = form.cleaned_data['commonness']
-      ###
-      response = HttpResponse(mimetype='application/x-gzip')
-      export_gz = gzip.GzipFile(fileobj=response, mode='w')
-      export_lexemes(data, export_gz)
-      filename = 'eksport.tab.gz'
-      response['Content-Disposition'] = 'attachment; filename=%s' % filename
-      return response
-  else:
-    form = ExportForm()
-  vocabs = {}
-  for v in Vocabulary.objects.all():
-    vocabs.update(dict((str(q.pk), v.id) for q in v.qualifiers.all()))
-  js_vars = {
-    'vocabs': vocabs,
-    'ajax_new_qualifier_row': reverse('magic_qualifier_row'),
-    'ajax_save_export_data': reverse('save_export_data'),
-    'ajax_get_export_data': reverse('get_export_data'),
-    'ajax_delete_export_data': reverse('delete_export_data'),
-  }
-  return {'form': form, 'js_vars': js_vars}
+    if request.GET:
+        form = ExportForm(data=request.GET)
+        if form.is_valid():
+            data = {
+                'vocabs': [v.id for v in form.cleaned_data['vocabs']],
+                'antivocabs': [v.id for v in form.cleaned_data['antivocabs']],
+                'variant': form.cleaned_data['variant'].id,
+            }
+            #data['excluding_qualifiers'] = [
+            #  q.pk for q in form.cleaned_data['excluding_qualifiers']]
+            magic_ids = set()
+            magic_qualifiers = []
+            normal_qualifiers = []
+            for key in request.GET:
+                split_key = key.split('-')
+                if key.startswith('magic') and split_key[0] not in magic_ids:
+                    i, name = split_key
+                    magic_ids.add(i)
+                    magic_form = MagicQualifierForm(prefix=i, data=request.GET)
+                    if magic_form.is_valid():
+                        regex = magic_form.cleaned_data['regex']
+                        if regex:
+                            magic_qualifiers.append(
+                                (
+                                regex, magic_form.cleaned_data['qualifier'].pk))
+                        else:
+                            normal_qualifiers.append(
+                                magic_form.cleaned_data['qualifier'].pk)
+            data['magic_qualifiers'] = magic_qualifiers
+            data['excluding_qualifiers'] = normal_qualifiers
+            data['refl'] = form.cleaned_data['refl']
+            data['commonness'] = form.cleaned_data['commonness']
+            ###
+            response = HttpResponse(mimetype='application/x-gzip')
+            export_gz = gzip.GzipFile(fileobj=response, mode='w')
+            export_lexemes(data, export_gz)
+            filename = 'eksport.tab.gz'
+            response[
+                'Content-Disposition'] = 'attachment; filename=%s' % filename
+            return response
+    else:
+        form = ExportForm()
+    vocabs = {}
+    for v in Vocabulary.objects.all():
+        vocabs.update(dict((str(q.pk), v.id) for q in v.qualifiers.all()))
+    js_vars = {
+        'vocabs': vocabs,
+        'ajax_new_qualifier_row': reverse('magic_qualifier_row'),
+        'ajax_save_export_data': reverse('save_export_data'),
+        'ajax_get_export_data': reverse('get_export_data'),
+        'ajax_delete_export_data': reverse('delete_export_data'),
+    }
+    return {'form': form, 'js_vars': js_vars}
+
 
 def wsjp_table(request, entry):
-  data = make_data([entry])
-  result = '\n'.join(
-    '\t'.join(['%s'] * len(data_row)) % data_row for data_row in data)
-  return HttpResponse(result, content_type="text/plain")
\ No newline at end of file
+    data = make_data([entry])
+    result = '\n'.join(
+        '\t'.join(['%s'] * len(data_row)) % data_row for data_row in data)
+    return HttpResponse(result, content_type="text/plain")
\ No newline at end of file
diff --git a/dictionary/wsjp.py b/dictionary/wsjp.py
index 9656bad..17fb7de 100644
--- a/dictionary/wsjp.py
+++ b/dictionary/wsjp.py
@@ -4,16 +4,16 @@ from dictionary.models import LexemeAttributeValue
 
 
 def make_data(entries):
-  entry_placeholders = ', '.join('%s' for entry in entries)
-  refls = dict(LexemeAttributeValue.objects.filter(
-    attribute__name=u'zwrotność').values_list('pk', 'value'))
-  refl_ids = ', '.join(str(pk) for pk in refls)
-  refls_rev = dict(LexemeAttributeValue.objects.filter(
-    attribute__name=u'zwrotność').values_list('value', 'pk'))
-  nonrefl = [refls_rev[v] for v in (u'—', u'(się)', u'(sobie)')]
-  nonrefl_ids = ', '.join(str(pk) for pk in nonrefl)
-  empty_refl = refls_rev[u'—']
-  base_query = '''
+    entry_placeholders = ', '.join('%s' for entry in entries)
+    refls = dict(LexemeAttributeValue.objects.filter(
+        attribute__name=u'zwrotność').values_list('pk', 'value'))
+    refl_ids = ', '.join(str(pk) for pk in refls)
+    refls_rev = dict(LexemeAttributeValue.objects.filter(
+        attribute__name=u'zwrotność').values_list('value', 'pk'))
+    nonrefl = [refls_rev[v] for v in (u'—', u'(się)', u'(sobie)')]
+    nonrefl_ids = ', '.join(str(pk) for pk in nonrefl)
+    empty_refl = refls_rev[u'—']
+    base_query = '''
     select distinct pref||rdzen||zak||suf slowo, %(haslo_tab)s, hom,
       l.pos,
       case when l.pos in ('subst','osc','v') then ch.charfl else '' end
@@ -31,7 +31,7 @@ def make_data(entries):
     where slownik in ('SGJP', 'WSJP') and
       %(haslo)s in (%(entry_placeholders)s) and %(leks_clause)s and wariant=%%s
   '''
-  nested_base = '''
+    nested_base = '''
     select rdzen||zak||suf slowo, %(haslo)s, g.hom, l.pos,
       case when l.pos = 'ppas' then ch.charfl else '' end as rodzaj,
       podparad, row, col, rowspan, colspan, kskl
@@ -50,84 +50,84 @@ def make_data(entries):
     where l.slownik in ('SGJP', 'WSJP') and
       g.haslo in (%(entry_placeholders)s) and %(main_clause)s
   '''
-  query_parts = [
-    (
-      base_query % {
-        'haslo_tab': 'haslo',
-        'haslo': 'haslo',
-        'entry_placeholders': entry_placeholders,
-        'leks_clause': '''l.pos not in ('skrl','skrw') and
+    query_parts = [
+        (
+            base_query % {
+                'haslo_tab': 'haslo',
+                'haslo': 'haslo',
+                'entry_placeholders': entry_placeholders,
+                'leks_clause': '''l.pos not in ('skrl','skrw') and
           (l.pos != 'v' or refl.attribute_value_id in (%s))'''
-          % nonrefl_ids,
-        'refl': refl_ids,
-      },
-      entries + ['1']
-    ),
-    # czasowniki sięiczne:
-    (
-      base_query % {
-        'haslo_tab': u"haslo||' się'",
-        'haslo': 'haslo',
-        'entry_placeholders': entry_placeholders,
-        'leks_clause': '''(l.pos='v' and refl.attribute_value_id <> %s)''',
-        'refl': refl_ids,
-      },
-      entries + [empty_refl, 's']
-    ),
-    # czasowniki zanegowane:
-    (
-      base_query % {
-        'haslo_tab': "'nie '||haslo",
-        'haslo': "'nie '||haslo",
-        'entry_placeholders': entry_placeholders,
-        'leks_clause': '''l.pos='v' and refl.attribute_value_id in (%s)'''
-          % nonrefl_ids,
-        'refl': refl_ids,
-      },
-      entries + ['n']
-    ),
-    # czasowniki sięiczne zanegowane:
-    (
-      base_query % {
-        'haslo_tab': u"'nie '||haslo||' się'",
-        'haslo': "'nie '||haslo",
-        'entry_placeholders': entry_placeholders,
-        'leks_clause': '''(l.pos='v' and refl.attribute_value_id <> %s)''',
-        'refl': refl_ids,
-      },
-      entries + [empty_refl, 'ns']
-    ),
-    # wymagające gniazdowania: adjcom, advcom i ppas
-    (
-      nested_base % {
-        'haslo': 'g.haslo',
-        'entry_placeholders': entry_placeholders,
-        'main_clause': '''typods in ('comadj','comadv','ppasver') and
+                               % nonrefl_ids,
+                'refl': refl_ids,
+            },
+            entries + ['1']
+        ),
+        # czasowniki sięiczne:
+        (
+            base_query % {
+                'haslo_tab': u"haslo||' się'",
+                'haslo': 'haslo',
+                'entry_placeholders': entry_placeholders,
+                'leks_clause': '''(l.pos='v' and refl.attribute_value_id <> %s)''',
+                'refl': refl_ids,
+            },
+            entries + [empty_refl, 's']
+        ),
+        # czasowniki zanegowane:
+        (
+            base_query % {
+                'haslo_tab': "'nie '||haslo",
+                'haslo': "'nie '||haslo",
+                'entry_placeholders': entry_placeholders,
+                'leks_clause': '''l.pos='v' and refl.attribute_value_id in (%s)'''
+                               % nonrefl_ids,
+                'refl': refl_ids,
+            },
+            entries + ['n']
+        ),
+        # czasowniki sięiczne zanegowane:
+        (
+            base_query % {
+                'haslo_tab': u"'nie '||haslo||' się'",
+                'haslo': "'nie '||haslo",
+                'entry_placeholders': entry_placeholders,
+                'leks_clause': '''(l.pos='v' and refl.attribute_value_id <> %s)''',
+                'refl': refl_ids,
+            },
+            entries + [empty_refl, 'ns']
+        ),
+        # wymagające gniazdowania: adjcom, advcom i ppas
+        (
+            nested_base % {
+                'haslo': 'g.haslo',
+                'entry_placeholders': entry_placeholders,
+                'main_clause': '''typods in ('comadj','comadv','ppasver') and
           l.pos in ('adjcom','advcom','ppas') and
           (l.pos != 'ppas' or refl.attribute_value_id in (%s))'''
-          % nonrefl_ids,
-        'refl': refl_ids,
-      },
-      entries
-    ),
-    # imiesłowy bierne czasowników sięicznych:
-    (
-      nested_base % {
-        'haslo': u"g.haslo||' się'",
-        'entry_placeholders': entry_placeholders,
-        'main_clause': '''(typods ='ppasver' and l.pos ='ppas' and
+                               % nonrefl_ids,
+                'refl': refl_ids,
+            },
+            entries
+        ),
+        # imiesłowy bierne czasowników sięicznych:
+        (
+            nested_base % {
+                'haslo': u"g.haslo||' się'",
+                'entry_placeholders': entry_placeholders,
+                'main_clause': '''(typods ='ppasver' and l.pos ='ppas' and
           refl.attribute_value_id <> %s)''',
-        'refl': refl_ids,
-      },
-      entries + [empty_refl]
-    )
-  ]
-  query = ' union all '.join(qp[0] for qp in query_parts) + '''
+                'refl': refl_ids,
+            },
+            entries + [empty_refl]
+        )
+    ]
+    query = ' union all '.join(qp[0] for qp in query_parts) + '''
     order by haslo, hom, rodzaj, podparad, row, col, kskl, slowo
   '''
-  params = []
-  for qp in query_parts:
-    params += qp[1]
-  cursor = connection.cursor()
-  cursor.execute(query, params)
-  return list(cursor)
+    params = []
+    for qp in query_parts:
+        params += qp[1]
+    cursor = connection.cursor()
+    cursor.execute(query, params)
+    return list(cursor)
diff --git a/manage.py b/manage.py
index 5e78ea9..5fc4c5e 100755
--- a/manage.py
+++ b/manage.py
@@ -1,10 +1,13 @@
 #!/usr/bin/env python
 from django.core.management import execute_manager
+
 try:
     import settings # Assumed to be in the same directory.
 except ImportError:
     import sys
-    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
+
+    sys.stderr.write(
+        "Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
     sys.exit(1)
 
 if __name__ == "__main__":
diff --git a/media/css/general.css b/media/css/general.css
index 60a6688..18c184d 100644
--- a/media/css/general.css
+++ b/media/css/general.css
@@ -26,8 +26,9 @@ ul#main_menu li a {
     height: 43px;
     color: #777;
     text-decoration: none;
-    display: block; float:
-    left; line-height: 200%;
+    display: block;
+    float: left;
+    line-height: 200%;
     padding: 8px 8px 0;
 }
 
@@ -64,11 +65,11 @@ body {
 }
 
 ul {
-  padding-left: 0;
+    padding-left: 0;
 }
 
 li {
-  display: block;
+    display: block;
 }
 
 .ui-jqgrid-titlebar {
@@ -88,6 +89,7 @@ li {
     white-space: nowrap;
     overflow: hidden;
 }
+
 .tabs .ui-tabs-nav li {
     display: inline-block;
     float: none;
@@ -139,12 +141,12 @@ li {
 /* różne */
 
 li span.remove {
-  float: right;
+    float: right;
 }
 
 .load-dialog-list li {
-  padding: 3px;
-  margin-bottom: 3px;
+    padding: 3px;
+    margin-bottom: 3px;
 }
 
 label.disabled {
diff --git a/media/css/inflection_table.css b/media/css/inflection_table.css
index 7e5a805..e30977e 100644
--- a/media/css/inflection_table.css
+++ b/media/css/inflection_table.css
@@ -63,6 +63,7 @@ table.inflection-table td span.qualifiers {
 .scheme0 table.inflection-table td {
     background-color: #ebf3ff;
 }
+
 .scheme0 h1,
 .scheme0 caption,
 .scheme0 table.cross-references tr th.head,
@@ -76,6 +77,7 @@ table.inflection-table td span.qualifiers {
 .scheme1 table.inflection-table td {
     background-color: #e2ffde;
 }
+
 .scheme1 h1,
 .scheme1 caption,
 .scheme1 table.cross-references tr th.head,
@@ -89,6 +91,7 @@ table.inflection-table td span.qualifiers {
 .scheme2 table.inflection-table td {
     background-color: #ffebde;
 }
+
 .scheme2 h1,
 .scheme2 caption,
 .scheme2 table.cross-references tr th.head,
@@ -102,6 +105,7 @@ table.inflection-table td span.qualifiers {
 .scheme3 table.inflection-table td {
     background-color: #f4deff;
 }
+
 .scheme3 h1,
 .scheme3 caption,
 .scheme3 table.cross-references tr th.head,
@@ -115,6 +119,7 @@ table.inflection-table td span.qualifiers {
 .scheme4 table.inflection-table td {
     background-color: #eeeeee;
 }
+
 .scheme4 h1,
 .scheme4 caption,
 .scheme4 table.cross-references tr th.head,
diff --git a/media/css/jqgrid.css b/media/css/jqgrid.css
index d98d4a0..7ee2509 100644
--- a/media/css/jqgrid.css
+++ b/media/css/jqgrid.css
@@ -1,111 +1,111 @@
 #content {
-  margin: 0 !important;
+    margin: 0 !important;
 }
 
 p {
-  font-size: small;
-  margin: 1ex 0;
+    font-size: small;
+    margin: 1ex 0;
 }
 
 p.buttons {
-  text-align: center;
-  line-height: 2.5em;
+    text-align: center;
+    line-height: 2.5em;
 }
 
 button {
-  line-height: normal;
+    line-height: normal;
 }
 
 .hidden {
-  display: none;
+    display: none;
 }
 
 ul ul li {
-  padding: 3px 1em 3px 5px;
+    padding: 3px 1em 3px 5px;
 }
 
 ul ul li:hover {
-  background-color: #FF9;
+    background-color: #FF9;
 }
 
 ul li:hover ul {
-  display: block;
-  background-color: #EEE;
+    display: block;
+    background-color: #EEE;
 }
 
 .ui-widget-content .ui-state-highlight {
-  background: blue none;
-  color: #ddd;
+    background: blue none;
+    color: #ddd;
 }
 
 .ui-jqgrid-titlebar {
-  display: none;
+    display: none;
 }
 
 .vsplitbar {
-  width: 7px;
-  background: #bbc;
+    width: 7px;
+    background: #bbc;
 }
 
 .phrase-box {
-  margin-left: 1em;
-  width: 160px;
+    margin-left: 1em;
+    width: 160px;
 }
 
 .sort_priority {
-  float: right;
+    float: right;
 }
 
 /* edycja */
 
 #lexeme-edit-form, #pattern-properties {
-  width: 425px;
-  display: inline-block;
-  vertical-align: top;
+    width: 425px;
+    display: inline-block;
+    vertical-align: top;
 }
 
 #table-preview, #ending-list {
-  display: inline-block;
-  vertical-align: top;
+    display: inline-block;
+    vertical-align: top;
 }
 
 #pattern-list li, #ending-list li, #cr-list li, #prompter-list li {
-  padding: 0.4em;
-  margin-bottom: 1px;
+    padding: 0.4em;
+    margin-bottom: 1px;
 }
 
 #pattern-list li, #ending-list li {
-  padding-left: 1.5em;
+    padding-left: 1.5em;
 }
 
 #pattern-list li span.arrows, #ending-list li span.arrows {
-  position: absolute;
-  margin-left: -1.3em;
+    position: absolute;
+    margin-left: -1.3em;
 }
 
 #pattern-list li.ui-state-active, #prompter-list li.ui-state-active {
-  border: blue solid 1px;
+    border: blue solid 1px;
 }
 
 #lexeme-edit-form p.main-field label,
 #pattern-edit-form p.main-field label {
-  width: 6em;
-  line-height: 2em;
-  float: left;
-  text-align: right;
-  padding-right: 0.5em;
+    width: 6em;
+    line-height: 2em;
+    float: left;
+    text-align: right;
+    padding-right: 0.5em;
 }
 
 /* sort dialog */
 
 #sort-rule-list li {
-  padding: 0.4px;
-  margin-bottom: 2px;
+    padding: 0.4px;
+    margin-bottom: 2px;
 }
 
 #sort-rule-list span {
-  width: 100px;
-  display: inline-block;
+    width: 100px;
+    display: inline-block;
 }
 
 /*#sort-rule-list .sort-dir {
diff --git a/media/css/lexeme_view.css b/media/css/lexeme_view.css
index bf3a4f1..a049185 100644
--- a/media/css/lexeme_view.css
+++ b/media/css/lexeme_view.css
@@ -1,141 +1,142 @@
 #pattern-list {
-  list-style-type: none;
-  margin: 0;
-  padding: 0;
+    list-style-type: none;
+    margin: 0;
+    padding: 0;
 }
 
 table.transaction-table {
-  width: 620px;
-  border-collapse: collapse;
-  margin-top: 5px;
-  margin-bottom: 20px;
+    width: 620px;
+    border-collapse: collapse;
+    margin-top: 5px;
+    margin-bottom: 20px;
 }
 
 table.transaction-table td, table.transaction-table th {
-  border: 1px solid;
-  width: 33%;
-  padding: 3px;
+    border: 1px solid;
+    width: 33%;
+    padding: 3px;
 }
 
 table.transaction-table td em {
-  font-style: normal;
-  color: gray;
+    font-style: normal;
+    color: gray;
 }
 
 table.transaction-table th {
-  background-color: #E6E6FF;
+    background-color: #E6E6FF;
 }
 
 table.transaction-table th.lip-header {
-  text-align: left;
+    text-align: left;
 }
 
 ul#cr-list li span, ul#prompter-list li span {
-  display: inline-block;
+    display: inline-block;
 }
 
 #prompter-dialog {
-  white-space: nowrap;
+    white-space: nowrap;
 }
 
 #prompter-dialog-left {
-  display: inline-block;
-  vertical-align: top;
-  width: 280px;
-  white-space: normal;
+    display: inline-block;
+    vertical-align: top;
+    width: 280px;
+    white-space: normal;
 }
 
 #prompter-table-preview {
-  display: inline-block;
-  vertical-align: top;
+    display: inline-block;
+    vertical-align: top;
 }
 
 ul#cr-list li span.type {
-  width: 175px;
-  white-space: normal;
+    width: 175px;
+    white-space: normal;
 }
 
 ul#cr-list li span.id {
-  width: 50px;
+    width: 50px;
 }
 
-ul#cr-list li span.entry { /*, ul#prompter-list li span.entry {*/
-  width: 110px;
+ul#cr-list li span.entry {
+    /*, ul#prompter-list li span.entry {*/
+    width: 110px;
 }
 
 table#prompter-list, table#prompter-list td {
-  border-style: solid;
-  border-color: gray;
-  border-collapse: collapse;
+    border-style: solid;
+    border-color: gray;
+    border-collapse: collapse;
 }
 
 table#prompter-list {
-  border-width: 1px 1px 0 1px;
+    border-width: 1px 1px 0 1px;
 }
 
 table#prompter-list td {
-  border-width: 0 0 1px 0;
-  padding: 5px;
+    border-width: 0 0 1px 0;
+    padding: 5px;
 }
 
 table#prompter-list .entry {
-  text-align: right;
+    text-align: right;
 }
 
 table#prompter-list .prompter-row-active td {
-  background: blue;
-  color: #AAA;
+    background: blue;
+    color: #AAA;
 }
 
 table#prompter-list .entry span.suffix {
-  font-weight: bold;
+    font-weight: bold;
 }
 
 table#prompter-list .ic-id {
-  display: none;
+    display: none;
 }
 
 table#prompter-list .cv ul {
-  margin: 0;
+    margin: 0;
 }
 
 table#prompter-list .cv ul li {
-  padding: 0;
+    padding: 0;
 }
 
 #move-lexeme {
-  margin-bottom: 15px;
+    margin-bottom: 15px;
 }
 
 #move-lexeme.move-hidden .label {
-  color: gray;
+    color: gray;
 }
 
 #move-lexeme.move-hidden .form {
-  display: none;
+    display: none;
 }
 
 #move-lexeme .label {
-  cursor: pointer;
+    cursor: pointer;
 }
 
 #homonym-count {
-  margin-left: 10px;
-  color: red;
+    margin-left: 10px;
+    color: red;
 }
 
 #vocab-list {
-  margin-top: 1em;
+    margin-top: 1em;
 }
 
 #vocab-list ul {
-  margin: 0;
+    margin: 0;
 }
 
 #vocab-list li {
-  display: inline;
+    display: inline;
 }
 
 #vocab-list th {
-  font-size: smaller;
+    font-size: smaller;
 }
diff --git a/media/css/lib/examples.css b/media/css/lib/examples.css
index 77569af..11f33c8 100644
--- a/media/css/lib/examples.css
+++ b/media/css/lib/examples.css
@@ -26,7 +26,7 @@ li {
 
     list-style: none;
     margin: 0;
-} 
+}
 
 #myGrid {
     background: white;
@@ -35,18 +35,18 @@ li {
 }
 
 .grid-header {
-	border: 1px solid gray;
-	border-bottom: 0;
-	border-top: 0;
-	background: url('/media/css/lib/smoothness/images/header-bg.gif') repeat-x center top;
-	color: black;
-	height: 24px;
-	line-height: 24px;
-}	
+    border: 1px solid gray;
+    border-bottom: 0;
+    border-top: 0;
+    background: url('/media/css/lib/smoothness/images/header-bg.gif') repeat-x center top;
+    color: black;
+    height: 24px;
+    line-height: 24px;
+}
 
 .grid-header label {
-	display: inline-block;
-	font-weight: bold;
+    display: inline-block;
+    font-weight: bold;
     margin: auto auto auto 6px;
 }
 
@@ -61,112 +61,107 @@ li {
 }
 
 .grid-header #txtSearch {
-	margin: 0 4px 0 4px;
-	padding: 2px 2px;
-	-moz-border-radius: 2px;
-	-webkit-border-radius: 2px;
-	border: 1px solid silver;
+    margin: 0 4px 0 4px;
+    padding: 2px 2px;
+    -moz-border-radius: 2px;
+    -webkit-border-radius: 2px;
+    border: 1px solid silver;
 }
 
 .options-panel {
-	-moz-border-radius: 6px;
-	-webkit-border-radius: 6px;
-	border: 1px solid silver;
-	background: #f0f0f0;	
-	padding: 4px;		
-	margin-bottom: 20px;
+    -moz-border-radius: 6px;
+    -webkit-border-radius: 6px;
+    border: 1px solid silver;
+    background: #f0f0f0;
+    padding: 4px;
+    margin-bottom: 20px;
 }
 
- 
-
 /* Individual cell styles */
 .slick-cell.task-name {
-	font-weight: bold;
-	text-align: right;
+    font-weight: bold;
+    text-align: right;
 }
 
-
 .slick-cell.task-percent {
-	text-align: right;
+    text-align: right;
 }
 
-
 .slick-cell.cell-move-handle {
-	font-weight: bold;
-	text-align: right;
+    font-weight: bold;
+    text-align: right;
     border-right: solid gray;
 
     background: #efefef;
-	cursor: move;
+    cursor: move;
 }
 
 .cell-move-handle:hover {
-	background: #b6b9bd;
+    background: #b6b9bd;
 }
 
 .slick-row.selected .cell-move-handle {
-	background: #D5DC8D;
+    background: #D5DC8D;
 }
 
 .slick-row .cell-actions {
-	text-align: left;
+    text-align: left;
 }
 
 .slick-row.complete {
-	background-color: #DFD;
-	color: #555;
+    background-color: #DFD;
+    color: #555;
 }
 
 .percent-complete-bar {
-	display: inline-block;
-	height: 6px;
-	-moz-border-radius: 3px;
-	-webkit-border-radius: 3px;
+    display: inline-block;
+    height: 6px;
+    -moz-border-radius: 3px;
+    -webkit-border-radius: 3px;
 }
 
-
 /* TextCellEditor, DateCellEditor */
 input.editor-text {
-	width: 100%;
-	height: 100%;
-	border: 0;
-	margin: 0;
-	background: transparent;
-	outline: 0;
+    width: 100%;
+    height: 100%;
+    border: 0;
+    margin: 0;
+    background: transparent;
+    outline: 0;
     padding: 0;
 
 }
 
 .slick-cell .ui-datepicker-trigger {
-	margin-top: 2px;
-	padding: 0;
-	vertical-align: top;
+    margin-top: 2px;
+    padding: 0;
+    vertical-align: top;
 }
 
 /* PercentCompleteCellEditor */
 input.editor-percentcomplete {
-	width: 100%;
-	height: 100%;
-	border: 0;
-	margin: 0;
-	background: transparent;
-	outline: 0;
+    width: 100%;
+    height: 100%;
+    border: 0;
+    margin: 0;
+    background: transparent;
+    outline: 0;
     padding: 0;
 
     float: left;
 }
 
 .editor-percentcomplete-picker {
-	position: relative;
+    position: relative;
     display: inline-block;
     width: 16px;
     height: 100%;
-    background: url("/media/css/lib/smoothness/images/pencil.gif") no-repeat center center;	
-	overflow: visible;
-	z-index: 1000;
-	float: right;
+    background: url("/media/css/lib/smoothness/images/pencil.gif") no-repeat center center;
+    overflow: visible;
+    z-index: 1000;
+    float: right;
 }
-	
+
 .editor-percentcomplete-helper {
     border: 0 solid gray;
     position: absolute;
@@ -177,57 +172,53 @@ input.editor-percentcomplete {
 
     width: 120px;
     height: 140px;
-    display: none;	
-	overflow: visible;
+    display: none;
+    overflow: visible;
 }
 
-
 .editor-percentcomplete-wrapper {
-	background:beige;
+    background: beige;
     padding: 20px 8px;
 
-    width:100%;
-	height:98px;
-	border:1px solid gray;
-	border-left:0;
+    width: 100%;
+    height: 98px;
+    border: 1px solid gray;
+    border-left: 0;
 }
 
 .editor-percentcomplete-buttons {
-	float: right;	
+    float: right;
 }
 
 .editor-percentcomplete-buttons button {
-	width: 80px;	
+    width: 80px;
 }
 
-
 .editor-percentcomplete-slider {
-	float: left;	
+    float: left;
 }
 
- .editor-percentcomplete-picker:hover .editor-percentcomplete-helper {
-	display: block;
+.editor-percentcomplete-picker:hover .editor-percentcomplete-helper {
+    display: block;
 }
 
 .editor-percentcomplete-helper:hover {
-	display: block;
+    display: block;
 }
 
-
-
 /* YesNoSelectCellEditor */
 select.editor-yesno {
-	width: 100%;
-	margin: 0;
-	vertical-align: middle;		
+    width: 100%;
+    margin: 0;
+    vertical-align: middle;
 }
 
 /* YesNoCheckboxCellEditor */
 input.editor-checkbox {
-	margin: 0;
-	height: 100%;
-	padding: 0;
-	border: 0;
+    margin: 0;
+    height: 100%;
+    padding: 0;
+    border: 0;
 }
 
 
diff --git a/media/css/lib/jquery.multiselect.css b/media/css/lib/jquery.multiselect.css
index 4015f14..f9cdd4e 100644
--- a/media/css/lib/jquery.multiselect.css
+++ b/media/css/lib/jquery.multiselect.css
@@ -1,23 +1,98 @@
-.ui-multiselect2 { padding:2px 0 2px 4px; text-align:left }
-.ui-multiselect2 span.ui-icon { float:right }
-.ui-multiselect-single .ui-multiselect-checkboxes input { position:absolute !important; top: auto !important; left:-9999px; }
-.ui-multiselect-single .ui-multiselect-checkboxes label { padding:5px !important }
-
-.ui-multiselect-header { margin-bottom:3px; padding:3px 0 3px 4px }
-.ui-multiselect-header ul { font-size:0.9em }
-.ui-multiselect-header ul li { float:left; padding:0 10px 0 0 }
-.ui-multiselect-header a { text-decoration:none }
-.ui-multiselect-header a:hover { text-decoration:underline }
-.ui-multiselect-header span.ui-icon { float:left }
-.ui-multiselect-header li.ui-multiselect-close { float:right; text-align:right; padding-right:0 }
-
-.ui-multiselect-menu { display:none; padding:3px; position:absolute; z-index:10000 }
-.ui-multiselect-checkboxes { position:relative /* fixes bug in IE6/7 */; overflow-y:scroll }
-.ui-multiselect-checkboxes label { cursor:default; display:block; border:1px solid transparent; padding:3px 1px }
-.ui-multiselect-checkboxes label input { position:relative; top:1px }
-.ui-multiselect-checkboxes li { clear:both; font-size:0.9em; padding-right:3px }
-.ui-multiselect-checkboxes li.ui-multiselect-optgroup-label { text-align:center; font-weight:bold; border-bottom:1px solid }
-.ui-multiselect-checkboxes li.ui-multiselect-optgroup-label a { display:block; padding:3px; margin:1px 0; text-decoration:none }
+.ui-multiselect2 {
+    padding: 2px 0 2px 4px;
+    text-align: left
+}
+
+.ui-multiselect2 span.ui-icon {
+    float: right
+}
+
+.ui-multiselect-single .ui-multiselect-checkboxes input {
+    position: absolute !important;
+    top: auto !important;
+    left: -9999px;
+}
+
+.ui-multiselect-single .ui-multiselect-checkboxes label {
+    padding: 5px !important
+}
+
+.ui-multiselect-header {
+    margin-bottom: 3px;
+    padding: 3px 0 3px 4px
+}
+
+.ui-multiselect-header ul {
+    font-size: 0.9em
+}
+
+.ui-multiselect-header ul li {
+    float: left;
+    padding: 0 10px 0 0
+}
+
+.ui-multiselect-header a {
+    text-decoration: none
+}
+
+.ui-multiselect-header a:hover {
+    text-decoration: underline
+}
+
+.ui-multiselect-header span.ui-icon {
+    float: left
+}
+
+.ui-multiselect-header li.ui-multiselect-close {
+    float: right;
+    text-align: right;
+    padding-right: 0
+}
+
+.ui-multiselect-menu {
+    display: none;
+    padding: 3px;
+    position: absolute;
+    z-index: 10000
+}
+
+.ui-multiselect-checkboxes {
+    position: relative /* fixes bug in IE6/7 */;
+    overflow-y: scroll
+}
+
+.ui-multiselect-checkboxes label {
+    cursor: default;
+    display: block;
+    border: 1px solid transparent;
+    padding: 3px 1px
+}
+
+.ui-multiselect-checkboxes label input {
+    position: relative;
+    top: 1px
+}
+
+.ui-multiselect-checkboxes li {
+    clear: both;
+    font-size: 0.9em;
+    padding-right: 3px
+}
+
+.ui-multiselect-checkboxes li.ui-multiselect-optgroup-label {
+    text-align: center;
+    font-weight: bold;
+    border-bottom: 1px solid
+}
+
+.ui-multiselect-checkboxes li.ui-multiselect-optgroup-label a {
+    display: block;
+    padding: 3px;
+    margin: 1px 0;
+    text-decoration: none
+}
 
 /* remove label borders in IE6 because IE6 does not support transparency */
-* html .ui-multiselect-checkboxes label { border:none }
+* html .ui-multiselect-checkboxes label {
+    border: none
+}
diff --git a/media/css/lib/jquery.ui.selectmenu.css b/media/css/lib/jquery.ui.selectmenu.css
index 1383603..f726e10 100644
--- a/media/css/lib/jquery.ui.selectmenu.css
+++ b/media/css/lib/jquery.ui.selectmenu.css
@@ -1,27 +1,134 @@
 /* Selectmenu
 ----------------------------------*/
-.ui-selectmenu { display: block; display: inline-block; position: relative; /*height: 2.2em;*/ vertical-align: middle; text-decoration: none; overflow: hidden; zoom: 1; }
-.ui-selectmenu-icon { position:absolute; right:6px; margin-top:-8px; top: 50%; }
-.ui-selectmenu-menu { padding:0; margin:0; position:absolute; top: 0; display: none; z-index: 1005;} /* z-index: 1005 to make selectmenu work with dialog */
-.ui-selectmenu-menu  ul { padding:0; margin:0; list-style:none; position: relative; overflow: auto; overflow-y: auto ; overflow-x: hidden; -webkit-overflow-scrolling: touch;}
-.ui-selectmenu-open { display: block; }
-.ui-selectmenu-menu-popup { margin-top: -1px; }
-.ui-selectmenu-menu li { padding:0; margin:0; display: block; border-top: 1px dotted transparent; border-bottom: 1px dotted transparent; border-right-width: 0 !important; border-left-width: 0 !important; font-weight: normal !important; }
-.ui-selectmenu-menu li a,.ui-selectmenu-status { line-height: 1.4em; display: block; padding: 2px 2.1em 2px 4px; outline:none; text-decoration:none; }
-.ui-selectmenu-menu li.ui-state-disabled a, .ui-state-disabled { cursor: default; }
+.ui-selectmenu {
+    display: block;
+    display: inline-block;
+    position: relative; /*height: 2.2em;*/
+    vertical-align: middle;
+    text-decoration: none;
+    overflow: hidden;
+    zoom: 1;
+}
+
+.ui-selectmenu-icon {
+    position: absolute;
+    right: 6px;
+    margin-top: -8px;
+    top: 50%;
+}
+
+.ui-selectmenu-menu {
+    padding: 0;
+    margin: 0;
+    position: absolute;
+    top: 0;
+    display: none;
+    z-index: 1005;
+}
+
+/* z-index: 1005 to make selectmenu work with dialog */
+.ui-selectmenu-menu  ul {
+    padding: 0;
+    margin: 0;
+    list-style: none;
+    position: relative;
+    overflow: auto;
+    overflow-y: auto;
+    overflow-x: hidden;
+    -webkit-overflow-scrolling: touch;
+}
+
+.ui-selectmenu-open {
+    display: block;
+}
+
+.ui-selectmenu-menu-popup {
+    margin-top: -1px;
+}
+
+.ui-selectmenu-menu li {
+    padding: 0;
+    margin: 0;
+    display: block;
+    border-top: 1px dotted transparent;
+    border-bottom: 1px dotted transparent;
+    border-right-width: 0 !important;
+    border-left-width: 0 !important;
+    font-weight: normal !important;
+}
+
+.ui-selectmenu-menu li a, .ui-selectmenu-status {
+    line-height: 1.4em;
+    display: block;
+    padding: 2px 2.1em 2px 4px;
+    outline: none;
+    text-decoration: none;
+}
+
+.ui-selectmenu-menu li.ui-state-disabled a, .ui-state-disabled {
+    cursor: default;
+}
+
 .ui-selectmenu-menu li.ui-selectmenu-hasIcon a,
-.ui-selectmenu-hasIcon .ui-selectmenu-status { padding-left: 20px; position: relative; margin-left: 5px; }
-.ui-selectmenu-menu li .ui-icon, .ui-selectmenu-status .ui-icon { position: absolute; top: 1em; margin-top: -8px; left: 0; }
-.ui-selectmenu-status { line-height: 1.4em; }
-.ui-selectmenu-menu li span,.ui-selectmenu-status span { display:block; margin-bottom: .2em; }
-.ui-selectmenu-menu li .ui-selectmenu-item-header { font-weight: bold; }
-.ui-selectmenu-menu li .ui-selectmenu-item-footer { opacity: .8; }
+.ui-selectmenu-hasIcon .ui-selectmenu-status {
+    padding-left: 20px;
+    position: relative;
+    margin-left: 5px;
+}
+
+.ui-selectmenu-menu li .ui-icon, .ui-selectmenu-status .ui-icon {
+    position: absolute;
+    top: 1em;
+    margin-top: -8px;
+    left: 0;
+}
+
+.ui-selectmenu-status {
+    line-height: 1.4em;
+}
+
+.ui-selectmenu-menu li span, .ui-selectmenu-status span {
+    display: block;
+    margin-bottom: .2em;
+}
+
+.ui-selectmenu-menu li .ui-selectmenu-item-header {
+    font-weight: bold;
+}
+
+.ui-selectmenu-menu li .ui-selectmenu-item-footer {
+    opacity: .8;
+}
+
 /* for optgroups */
-.ui-selectmenu-menu .ui-selectmenu-group { font-size: 1em; }
-.ui-selectmenu-menu .ui-selectmenu-group .ui-selectmenu-group-label { line-height: 1.4em; display:block; padding: .6em .5em 0; font-weight: bold; }
-.ui-selectmenu-menu .ui-selectmenu-group ul { margin: 0; padding: 0; }
+.ui-selectmenu-menu .ui-selectmenu-group {
+    font-size: 1em;
+}
+
+.ui-selectmenu-menu .ui-selectmenu-group .ui-selectmenu-group-label {
+    line-height: 1.4em;
+    display: block;
+    padding: .6em .5em 0;
+    font-weight: bold;
+}
+
+.ui-selectmenu-menu .ui-selectmenu-group ul {
+    margin: 0;
+    padding: 0;
+}
+
 /* IE6 workaround (dotted transparent borders) */
-* html .ui-selectmenu-menu li { border-color: pink; filter:chroma(color=pink); width:100%; }
-* html .ui-selectmenu-menu li a { position: relative }
+* html .ui-selectmenu-menu li {
+    border-color: pink;
+    filter: chroma(color=pink);
+    width: 100%;
+}
+
+* html .ui-selectmenu-menu li a {
+    position: relative
+}
+
 /* IE7 workaround (opacity disabled) */
-*+html .ui-state-disabled, *+html .ui-state-disabled a { color: silver; }
+*+html .ui-state-disabled, *+html .ui-state-disabled a {
+    color: silver;
+}
diff --git a/media/css/lib/layout-default-latest.css b/media/css/lib/layout-default-latest.css
index 8bdad95..fad591b 100644
--- a/media/css/lib/layout-default-latest.css
+++ b/media/css/lib/layout-default-latest.css
@@ -19,112 +19,149 @@
  *	Just to make demo-pages look better - not actually relevant to Layout!
  */
 body {
-	font-family: Geneva, Arial, Helvetica, sans-serif;
-	font-size:   100%;
-	*font-size:  80%;
+    font-family: Geneva, Arial, Helvetica, sans-serif;
+    font-size: 100%;
+    *font-size: 80%;
 }
 
 /*
  *	PANES & CONTENT-DIVs
  */
-.ui-layout-pane { /* all 'panes' */
-	background:	#FFF; 
-	border:		1px solid #BBB;
-	/* DO NOT add scrolling (or padding) to 'panes' that have a content-div,
-	   otherwise you may get double-scrollbars - on the pane AND on the content-div
-	*/
-	padding:	10px; 
-	overflow:	auto;
-	}
-	/* (scrolling) content-div inside pane allows for fixed header(s) and/or footer(s) */
-	.ui-layout-content {
-		padding:	10px;
-		position:	relative; /* contain floated or positioned elements */
-		overflow:	auto; /* add scrolling to content-div */
-	}
+.ui-layout-pane {
+    /* all 'panes' */
+    background: #FFF;
+    border: 1px solid #BBB;
+    /* DO NOT add scrolling (or padding) to 'panes' that have a content-div,
+       otherwise you may get double-scrollbars - on the pane AND on the content-div
+    */
+    padding: 10px;
+    overflow: auto;
+}
+
+/* (scrolling) content-div inside pane allows for fixed header(s) and/or footer(s) */
+.ui-layout-content {
+    padding: 10px;
+    position: relative; /* contain floated or positioned elements */
+    overflow: auto; /* add scrolling to content-div */
+}
 
 /*
  *	RESIZER-BARS
  */
-.ui-layout-resizer	{ /* all 'resizer-bars' */
-	background:		#DDD;
-	border:			1px solid #BBB;
-	border-width:	0;
-	}
-	.ui-layout-resizer-drag {		/* REAL resizer while resize in progress */
-	}
-	.ui-layout-resizer-hover	{	/* affects both open and closed states */
-	}
-	/* NOTE: It looks best when 'hover' and 'dragging' are set to the same color,
-		otherwise color shifts while dragging when bar can't keep up with mouse */
-	.ui-layout-resizer-open-hover ,	/* hover-color to 'resize' */
-	.ui-layout-resizer-dragging {	/* resizer beging 'dragging' */
-		background: #C4E1A4;
-	}
-	.ui-layout-resizer-dragging {	/* CLONED resizer being dragged */
-		border-left:  1px solid #BBB;
-		border-right: 1px solid #BBB;
-	}
-	/* NOTE: Add a 'dragging-limit' color to provide visual feedback when resizer hits min/max size limits */
-	.ui-layout-resizer-dragging-limit {	/* CLONED resizer at min or max size-limit */
-		background: #E1A4A4; /* red */
-	}
-
-	.ui-layout-resizer-closed-hover	{ /* hover-color to 'slide open' */
-		background: #EBD5AA;
-	}
-	.ui-layout-resizer-sliding {	/* resizer when pane is 'slid open' */
-		opacity: .10; /* show only a slight shadow */
-		filter:  alpha(opacity=10);
-		}
-		.ui-layout-resizer-sliding-hover {	/* sliding resizer - hover */
-			opacity: 1.00; /* on-hover, show the resizer-bar normally */
-			filter:  alpha(opacity=100);
-		}
-		/* sliding resizer - add 'outside-border' to resizer on-hover 
-		 * this sample illustrates how to target specific panes and states */
-		.ui-layout-resizer-north-sliding-hover	{ border-bottom-width:	1px; }
-		.ui-layout-resizer-south-sliding-hover	{ border-top-width:		1px; }
-		.ui-layout-resizer-west-sliding-hover	{ border-right-width:	1px; }
-		.ui-layout-resizer-east-sliding-hover	{ border-left-width:	1px; }
+.ui-layout-resizer {
+    /* all 'resizer-bars' */
+    background: #DDD;
+    border: 1px solid #BBB;
+    border-width: 0;
+}
+
+.ui-layout-resizer-drag {
+    /* REAL resizer while resize in progress */
+}
+
+.ui-layout-resizer-hover {
+    /* affects both open and closed states */
+}
+
+/* NOTE: It looks best when 'hover' and 'dragging' are set to the same color,
+    otherwise color shifts while dragging when bar can't keep up with mouse */
+.ui-layout-resizer-open-hover, /* hover-color to 'resize' */
+.ui-layout-resizer-dragging {
+    /* resizer beging 'dragging' */
+    background: #C4E1A4;
+}
+
+.ui-layout-resizer-dragging {
+    /* CLONED resizer being dragged */
+    border-left: 1px solid #BBB;
+    border-right: 1px solid #BBB;
+}
+
+/* NOTE: Add a 'dragging-limit' color to provide visual feedback when resizer hits min/max size limits */
+.ui-layout-resizer-dragging-limit {
+    /* CLONED resizer at min or max size-limit */
+    background: #E1A4A4; /* red */
+}
+
+.ui-layout-resizer-closed-hover {
+    /* hover-color to 'slide open' */
+    background: #EBD5AA;
+}
+
+.ui-layout-resizer-sliding {
+    /* resizer when pane is 'slid open' */
+    opacity: .10; /* show only a slight shadow */
+    filter: alpha(opacity=10);
+}
+
+.ui-layout-resizer-sliding-hover {
+    /* sliding resizer - hover */
+    opacity: 1.00; /* on-hover, show the resizer-bar normally */
+    filter: alpha(opacity=100);
+}
+
+/* sliding resizer - add 'outside-border' to resizer on-hover
+ * this sample illustrates how to target specific panes and states */
+.ui-layout-resizer-north-sliding-hover {
+    border-bottom-width: 1px;
+}
+
+.ui-layout-resizer-south-sliding-hover {
+    border-top-width: 1px;
+}
+
+.ui-layout-resizer-west-sliding-hover {
+    border-right-width: 1px;
+}
+
+.ui-layout-resizer-east-sliding-hover {
+    border-left-width: 1px;
+}
 
 /*
  *	TOGGLER-BUTTONS
  */
 .ui-layout-toggler {
-	border: 1px solid #BBB; /* match pane-border */
-	background-color: #BBB;
-	}
-	.ui-layout-resizer-hover .ui-layout-toggler {
-		opacity: .60;
-		filter:  alpha(opacity=60);
-	}
-	.ui-layout-toggler-hover , /* need when NOT resizable */
-	.ui-layout-resizer-hover .ui-layout-toggler-hover { /* need specificity when IS resizable */
-		background-color: #FC6;
-		opacity: 1.00;
-		filter:  alpha(opacity=100);
-	}
-	.ui-layout-toggler-north ,
-	.ui-layout-toggler-south {
-		border-width: 0 1px; /* left/right borders */
-	}
-	.ui-layout-toggler-west ,
-	.ui-layout-toggler-east {
-		border-width: 1px 0; /* top/bottom borders */
-	}
-	/* hide the toggler-button when the pane is 'slid open' */
-	.ui-layout-resizer-sliding  ui-layout-toggler {
-		display: none;
-	}
-	/*
-	 *	style the text we put INSIDE the togglers
-	 */
-	.ui-layout-toggler .content {
-		color:			#666;
-		font-size:		12px;
-		font-weight:	bold;
-		width:			100%;
-		padding-bottom:	0.35ex; /* to 'vertically center' text inside text-span */
-	}
+    border: 1px solid #BBB; /* match pane-border */
+    background-color: #BBB;
+}
+
+.ui-layout-resizer-hover .ui-layout-toggler {
+    opacity: .60;
+    filter: alpha(opacity=60);
+}
+
+.ui-layout-toggler-hover, /* need when NOT resizable */
+.ui-layout-resizer-hover .ui-layout-toggler-hover {
+    /* need specificity when IS resizable */
+    background-color: #FC6;
+    opacity: 1.00;
+    filter: alpha(opacity=100);
+}
+
+.ui-layout-toggler-north,
+.ui-layout-toggler-south {
+    border-width: 0 1px; /* left/right borders */
+}
+
+.ui-layout-toggler-west,
+.ui-layout-toggler-east {
+    border-width: 1px 0; /* top/bottom borders */
+}
+
+/* hide the toggler-button when the pane is 'slid open' */
+.ui-layout-resizer-sliding  ui-layout-toggler {
+    display: none;
+}
+
+/*
+ *	style the text we put INSIDE the togglers
+ */
+.ui-layout-toggler .content {
+    color: #666;
+    font-size: 12px;
+    font-weight: bold;
+    width: 100%;
+    padding-bottom: 0.35ex; /* to 'vertically center' text inside text-span */
+}
 
diff --git a/media/css/lib/qunit.css b/media/css/lib/qunit.css
index 5714bf4..89f2ba7 100644
--- a/media/css/lib/qunit.css
+++ b/media/css/lib/qunit.css
@@ -1,119 +1,134 @@
-
 ol#qunit-tests {
-	font-family:"Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial;
-	margin:0;
-	padding:0;
-	list-style-position:inside;
-
-	font-size: smaller;
-}
-ol#qunit-tests li{
-	padding:0.4em 0.5em 0.4em 2.5em;
-	border-bottom:1px solid #fff;
-	font-size:small;
-	list-style-position:inside;
-}
-ol#qunit-tests li ol{
-	box-shadow: inset 0px 2px 13px #999;
-	-moz-box-shadow: inset 0px 2px 13px #999;
-	-webkit-box-shadow: inset 0px 2px 13px #999;
-	margin-top:0.5em;
-	margin-left:0;
-	padding:0.5em;
-	background-color:#fff;
-	border-radius:15px;
-	-moz-border-radius: 15px;
-	-webkit-border-radius: 15px;
-}
-ol#qunit-tests li li{
-	border-bottom:none;
-	margin:0.5em;
-	background-color:#fff;
-	list-style-position: inside;
-	padding:0.4em 0.5em 0.4em 0.5em;
-}
-
-ol#qunit-tests li li.pass{
-	border-left:26px solid #C6E746;
-	background-color:#fff;
-	color:#5E740B;
-	}
-ol#qunit-tests li li.fail{
-	border-left:26px solid #EE5757;
-	background-color:#fff;
-	color:#710909;
-}
-ol#qunit-tests li.pass{
-	background-color:#D2E0E6;
-	color:#528CE0;
-}
-ol#qunit-tests li.fail{
-	background-color:#EE5757;
-	color:#000;
+    font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial;
+    margin: 0;
+    padding: 0;
+    list-style-position: inside;
+
+    font-size: smaller;
 }
+
+ol#qunit-tests li {
+    padding: 0.4em 0.5em 0.4em 2.5em;
+    border-bottom: 1px solid #fff;
+    font-size: small;
+    list-style-position: inside;
+}
+
+ol#qunit-tests li ol {
+    box-shadow: inset 0px 2px 13px #999;
+    -moz-box-shadow: inset 0px 2px 13px #999;
+    -webkit-box-shadow: inset 0px 2px 13px #999;
+    margin-top: 0.5em;
+    margin-left: 0;
+    padding: 0.5em;
+    background-color: #fff;
+    border-radius: 15px;
+    -moz-border-radius: 15px;
+    -webkit-border-radius: 15px;
+}
+
+ol#qunit-tests li li {
+    border-bottom: none;
+    margin: 0.5em;
+    background-color: #fff;
+    list-style-position: inside;
+    padding: 0.4em 0.5em 0.4em 0.5em;
+}
+
+ol#qunit-tests li li.pass {
+    border-left: 26px solid #C6E746;
+    background-color: #fff;
+    color: #5E740B;
+}
+
+ol#qunit-tests li li.fail {
+    border-left: 26px solid #EE5757;
+    background-color: #fff;
+    color: #710909;
+}
+
+ol#qunit-tests li.pass {
+    background-color: #D2E0E6;
+    color: #528CE0;
+}
+
+ol#qunit-tests li.fail {
+    background-color: #EE5757;
+    color: #000;
+}
+
 ol#qunit-tests li strong {
-	cursor:pointer;
-}
-h1#qunit-header{
-	background-color:#0d3349;
-	margin:0;
-	padding:0.5em 0 0.5em 1em;
-	color:#fff;
-	font-family:"Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial;
-	border-top-right-radius:15px;
-	border-top-left-radius:15px;
-	-moz-border-radius-topright:15px;
-	-moz-border-radius-topleft:15px;
-	-webkit-border-top-right-radius:15px;
-	-webkit-border-top-left-radius:15px;
-	text-shadow: rgba(0, 0, 0, 0.5) 4px 4px 1px;
-}
-h2#qunit-banner{
-	font-family:"Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial;
-	height:5px;
-	margin:0;
-	padding:0;
-}
-h2#qunit-banner.qunit-pass{
-	background-color:#C6E746;
+    cursor: pointer;
 }
+
+h1#qunit-header {
+    background-color: #0d3349;
+    margin: 0;
+    padding: 0.5em 0 0.5em 1em;
+    color: #fff;
+    font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial;
+    border-top-right-radius: 15px;
+    border-top-left-radius: 15px;
+    -moz-border-radius-topright: 15px;
+    -moz-border-radius-topleft: 15px;
+    -webkit-border-top-right-radius: 15px;
+    -webkit-border-top-left-radius: 15px;
+    text-shadow: rgba(0, 0, 0, 0.5) 4px 4px 1px;
+}
+
+h2#qunit-banner {
+    font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial;
+    height: 5px;
+    margin: 0;
+    padding: 0;
+}
+
+h2#qunit-banner.qunit-pass {
+    background-color: #C6E746;
+}
+
 h2#qunit-banner.qunit-fail, #qunit-testrunner-toolbar {
-	background-color:#EE5757;
+    background-color: #EE5757;
 }
+
 #qunit-testrunner-toolbar {
-	font-family:"Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial;
-	padding:0;
-	/*width:80%;*/
-	padding:0em 0 0.5em 2em;
-	font-size: small;
+    font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial;
+    padding: 0;
+    /*width:80%;*/
+    padding: 0em 0 0.5em 2em;
+    font-size: small;
 }
+
 h2#qunit-userAgent {
-	font-family:"Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial;
-	background-color:#2b81af;
-	margin:0;
-	padding:0;
-	color:#fff;
-	font-size: small;
-	padding:0.5em 0 0.5em 2.5em;
-	text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px;
-}
-p#qunit-testresult{
-	font-family:"Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial;
-	margin:0;
-	font-size: small;
-	color:#2b81af;
-	border-bottom-right-radius:15px;
-	border-bottom-left-radius:15px;
-	-moz-border-radius-bottomright:15px;
-	-moz-border-radius-bottomleft:15px;
-	-webkit-border-bottom-right-radius:15px;
-	-webkit-border-bottom-left-radius:15px;
-	background-color:#D2E0E6;
-	padding:0.5em 0.5em 0.5em 2.5em;
-}
-strong b.fail{
-	color:#710909;
-	}
-strong b.pass{
-	color:#5E740B;
-	}
+    font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial;
+    background-color: #2b81af;
+    margin: 0;
+    padding: 0;
+    color: #fff;
+    font-size: small;
+    padding: 0.5em 0 0.5em 2.5em;
+    text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px;
+}
+
+p#qunit-testresult {
+    font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial;
+    margin: 0;
+    font-size: small;
+    color: #2b81af;
+    border-bottom-right-radius: 15px;
+    border-bottom-left-radius: 15px;
+    -moz-border-radius-bottomright: 15px;
+    -moz-border-radius-bottomleft: 15px;
+    -webkit-border-bottom-right-radius: 15px;
+    -webkit-border-bottom-left-radius: 15px;
+    background-color: #D2E0E6;
+    padding: 0.5em 0.5em 0.5em 2.5em;
+}
+
+strong b.fail {
+    color: #710909;
+}
+
+strong b.pass {
+    color: #5E740B;
+}
diff --git a/media/css/lib/slick-default-theme.css b/media/css/lib/slick-default-theme.css
index cd211cd..4ebca31 100644
--- a/media/css/lib/slick-default-theme.css
+++ b/media/css/lib/slick-default-theme.css
@@ -44,12 +44,11 @@ classes should alter those!
     border-style: solid;
 }
 
-
 .slick-sortable-placeholder {
-    background: silver!important;
+    background: silver !important;
 }
 
-.slick-row[row$="1"], .slick-row[row$="3"], .slick-row[row$="5"], .slick-row[row$="7"],	.slick-row[row$="9"] {
+.slick-row[row$="1"], .slick-row[row$="3"], .slick-row[row$="5"], .slick-row[row$="7"], .slick-row[row$="9"] {
     background: #fafafa;
 }
 
@@ -63,5 +62,5 @@ classes should alter those!
 }
 
 .slick-cell.invalid {
-	border-color: red;
+    border-color: red;
 }
diff --git a/media/css/lib/slick.grid.css b/media/css/lib/slick.grid.css
index 0c04e56..aa81bc7 100644
--- a/media/css/lib/slick.grid.css
+++ b/media/css/lib/slick.grid.css
@@ -5,108 +5,107 @@ No built-in (selected, editable, highlight, flashing, invalid, loading, :focus) 
 classes should alter those!
 */
 
-
 .slick-header.ui-state-default {
-	width: 100%;
-	overflow: hidden;
-	border-left: 0px;
+    width: 100%;
+    overflow: hidden;
+    border-left: 0px;
 }
 
 .slick-header-columns {
-	width: 999999px;
-	position: relative;
-	white-space: nowrap;
-	cursor: default;
-	overflow: hidden;
+    width: 999999px;
+    position: relative;
+    white-space: nowrap;
+    cursor: default;
+    overflow: hidden;
 }
 
 .slick-header-column.ui-state-default {
-	position: relative;
-	display: inline-block;
-	overflow: hidden;
-	text-overflow: ellipsis;
-	height: 16px;
-	line-height: 16px;
-	margin: 0;
-	padding: 4px;
-	border-right: 1px solid silver;
-	border-left: 0px;
-	border-top: 0px;
-	border-bottom: 0px;
-	float: left;
+    position: relative;
+    display: inline-block;
+    overflow: hidden;
+    text-overflow: ellipsis;
+    height: 16px;
+    line-height: 16px;
+    margin: 0;
+    padding: 4px;
+    border-right: 1px solid silver;
+    border-left: 0px;
+    border-top: 0px;
+    border-bottom: 0px;
+    float: left;
 }
 
 .slick-header-column-sorted {
-	font-style: italic;
+    font-style: italic;
 }
 
 .slick-sort-indicator {
-	display: inline-block;
-	width: 8px;
-	height: 5px;
-	margin-left: 4px;
+    display: inline-block;
+    width: 8px;
+    height: 5px;
+    margin-left: 4px;
 }
 
 .slick-sort-indicator-desc {
-	background: url(/media/css/lib/smoothness/images/sort-desc.gif);
+    background: url(/media/css/lib/smoothness/images/sort-desc.gif);
 }
 
 .slick-sort-indicator-asc {
-	background: url(/media/css/lib/smoothness/images/sort-asc.gif);
+    background: url(/media/css/lib/smoothness/images/sort-asc.gif);
 }
 
 .slick-resizable-handle {
-	position: absolute;
-	font-size: 0.1px;
-	display: block;
-	cursor: col-resize;
-	width: 4px;
-	right: -2px;
-	top: 0;
-	height: 100%;
+    position: absolute;
+    font-size: 0.1px;
+    display: block;
+    cursor: col-resize;
+    width: 4px;
+    right: -2px;
+    top: 0;
+    height: 100%;
 }
 
 .slick-resizable-handle:hover {
-	background: gray;
+    background: gray;
 }
 
 .slick-sortable-placeholder {
-	background: silver;
+    background: silver;
 }
 
 .grid-canvas {
-	position: relative;
-	outline: 0;
+    position: relative;
+    outline: 0;
 }
 
 .slick-row.ui-widget-content, .slick-row.ui-state-active {
-	position: absolute;
-	border: 0px;
+    position: absolute;
+    border: 0px;
 }
 
 .slick-cell {
-	float: left;
-
-	border: 1px solid transparent;
-	border-right: 1px dotted silver;
-	border-bottom-color: silver;
-
-	overflow: hidden;
-	text-overflow: ellipsis;
-	white-space: nowrap;
-	vertical-align: middle;
-	z-index: 1;
-	padding: 1px 2px 2px 1px;
+    float: left;
+
+    border: 1px solid transparent;
+    border-right: 1px dotted silver;
+    border-bottom-color: silver;
+
+    overflow: hidden;
+    text-overflow: ellipsis;
+    white-space: nowrap;
+    vertical-align: middle;
+    z-index: 1;
+    padding: 1px 2px 2px 1px;
     margin: 0;
-    
-	white-space: nowrap;
 
-	cursor: default;
+    white-space: nowrap;
+
+    cursor: default;
 }
 
 .slick-cell.highlighted {
     background: lightskyblue;
-    background: rgba(0,0,255,0.2);
+    background: rgba(0, 0, 255, 0.2);
     -webkit-transition: all 0.5s;
     -moz-transition: all 0.5s;
     transition: all 0.5s;
@@ -117,29 +116,29 @@ classes should alter those!
 }
 
 .slick-cell.editable {
-	z-index: 11;
-	overflow: visible;
-	background: white;
-	border-color: black;
-	border-style: solid;
+    z-index: 11;
+    overflow: visible;
+    background: white;
+    border-color: black;
+    border-style: solid;
 }
 
 .slick-cell:focus {
-	outline: none;
+    outline: none;
 }
 
 .slick-reorder-proxy {
-	display: inline-block;
-	background: blue;
-	opacity: 0.15;
-	filter: alpha(opacity=15);
-	cursor: move;
+    display: inline-block;
+    background: blue;
+    opacity: 0.15;
+    filter: alpha(opacity=15);
+    cursor: move;
 }
 
 .slick-reorder-guide {
-	display: inline-block;
-	height: 2px;
-	background: blue;
-	opacity: 0.7;
-	filter: alpha(opacity=70);
+    display: inline-block;
+    height: 2px;
+    background: blue;
+    opacity: 0.7;
+    filter: alpha(opacity=70);
 }
diff --git a/media/css/lib/smoothness/jquery-ui-1.8.21.custom.css b/media/css/lib/smoothness/jquery-ui-1.8.21.custom.css
index f7bb7db..b4bf8a1 100644
--- a/media/css/lib/smoothness/jquery-ui-1.8.21.custom.css
+++ b/media/css/lib/smoothness/jquery-ui-1.8.21.custom.css
@@ -10,33 +10,78 @@
 
 /* Layout helpers
 ----------------------------------*/
-.ui-helper-hidden { display: none; }
-.ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); }
-.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; }
-.ui-helper-clearfix:before, .ui-helper-clearfix:after { content: ""; display: table; }
-.ui-helper-clearfix:after { clear: both; }
-.ui-helper-clearfix { zoom: 1; }
-.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); }
+.ui-helper-hidden {
+    display: none;
+}
 
+.ui-helper-hidden-accessible {
+    position: absolute !important;
+    clip: rect(1px 1px 1px 1px);
+    clip: rect(1px, 1px, 1px, 1px);
+}
+
+.ui-helper-reset {
+    margin: 0;
+    padding: 0;
+    border: 0;
+    outline: 0;
+    line-height: 1.3;
+    text-decoration: none;
+    font-size: 100%;
+    list-style: none;
+}
+
+.ui-helper-clearfix:before, .ui-helper-clearfix:after {
+    content: "";
+    display: table;
+}
+
+.ui-helper-clearfix:after {
+    clear: both;
+}
+
+.ui-helper-clearfix {
+    zoom: 1;
+}
+
+.ui-helper-zfix {
+    width: 100%;
+    height: 100%;
+    top: 0;
+    left: 0;
+    position: absolute;
+    opacity: 0;
+    filter: Alpha(Opacity=0);
+}
 
 /* Interaction Cues
 ----------------------------------*/
-.ui-state-disabled { cursor: default !important; }
-
+.ui-state-disabled {
+    cursor: default !important;
+}
 
 /* Icons
 ----------------------------------*/
 
 /* states and images */
-.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; }
-
+.ui-icon {
+    display: block;
+    text-indent: -99999px;
+    overflow: hidden;
+    background-repeat: no-repeat;
+}
 
 /* Misc visuals
 ----------------------------------*/
 
 /* Overlays */
-.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
-
+.ui-widget-overlay {
+    position: absolute;
+    top: 0;
+    left: 0;
+    width: 100%;
+    height: 100%;
+}
 
 /*!
  * jQuery UI CSS Framework 1.8.21
@@ -50,241 +95,915 @@
  * To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Verdana,Arial,sans-serif&fwDefault=normal&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=cccccc&bgTextureHeader=03_highlight_soft.png&bgImgOpacityHeader=75&borderColorHeader=aaaaaa&fcHeader=222222&iconColorHeader=222222&bgColorContent=ffffff&bgTextureContent=01_flat.png&bgImgOpacityContent=75&borderColorContent=aaaaaa&fcContent=222222&iconColorContent=222222&bgColorDefault=e6e6e6&bgTextureDefault=02_glass.png&bgImgOpacityDefault=75&borderColorDefault=d3d3d3&fcDefault=555555&iconColorDefault=888888&bgColorHover=dadada&bgTextureHover=02_glass.png&bgImgOpacityHover=75&borderColorHover=999999&fcHover=212121&iconColorHover=454545&bgColorActive=ffffff&bgTextureActive=02_glass.png&bgImgOpacityActive=65&borderColorActive=aaaaaa&fcActive=212121&iconColorActive=454545&bgColorHighlight=fbf9ee&bgTextureHighlight=02_glass.png&bgImgOpacityHighlight=55&borderColorHighlight=fcefa1&fcHighlight=363636&iconColorHighlight=2e83ff&bgColorError=fef1ec&bgTextureError=02_glass.png&bgImgOpacityError=95&borderColorError=cd0a0a&fcError=cd0a0a&iconColorError=cd0a0a&bgColorOverlay=aaaaaa&bgTextureOverlay=01_flat.png&bgImgOpacityOverlay=0&opacityOverlay=30&bgColorShadow=aaaaaa&bgTextureShadow=01_flat.png&bgImgOpacityShadow=0&opacityShadow=30&thicknessShadow=8px&offsetTopShadow=-8px&offsetLeftShadow=-8px&cornerRadiusShadow=8px
  */
 
-
 /* Component containers
 ----------------------------------*/
-.ui-widget { font-family: Verdana,Arial,sans-serif; font-size: 1.1em; }
-.ui-widget .ui-widget { font-size: 1em; }
-.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Verdana,Arial,sans-serif; font-size: 1em; }
-.ui-widget-content { border: 1px solid #aaaaaa; background: #ffffff url(images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x; color: #222222; }
-.ui-widget-content a { color: #222222; }
-.ui-widget-header { border: 1px solid #aaaaaa; background: #cccccc url(images/ui-bg_highlight-soft_75_cccccc_1x100.png) 50% 50% repeat-x; color: #222222; font-weight: bold; }
-.ui-widget-header a { color: #222222; }
+.ui-widget {
+    font-family: Verdana, Arial, sans-serif;
+    font-size: 1.1em;
+}
+
+.ui-widget .ui-widget {
+    font-size: 1em;
+}
+
+.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button {
+    font-family: Verdana, Arial, sans-serif;
+    font-size: 1em;
+}
+
+.ui-widget-content {
+    border: 1px solid #aaaaaa;
+    background: #ffffff url(images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x;
+    color: #222222;
+}
+
+.ui-widget-content a {
+    color: #222222;
+}
+
+.ui-widget-header {
+    border: 1px solid #aaaaaa;
+    background: #cccccc url(images/ui-bg_highlight-soft_75_cccccc_1x100.png) 50% 50% repeat-x;
+    color: #222222;
+    font-weight: bold;
+}
+
+.ui-widget-header a {
+    color: #222222;
+}
 
 /* Interaction states
 ----------------------------------*/
-.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #d3d3d3; background: #e6e6e6 url(images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat-x; font-weight: normal; color: #555555; }
-.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #555555; text-decoration: none; }
-.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #999999; background: #dadada url(images/ui-bg_glass_75_dadada_1x400.png) 50% 50% repeat-x; font-weight: normal; color: #212121; }
-.ui-state-hover a, .ui-state-hover a:hover { color: #212121; text-decoration: none; }
-.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #aaaaaa; background: #ffffff url(images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x; font-weight: normal; color: #212121; }
-.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #212121; text-decoration: none; }
-.ui-widget :active { outline: none; }
+.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default {
+    border: 1px solid #d3d3d3;
+    background: #e6e6e6 url(images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat-x;
+    font-weight: normal;
+    color: #555555;
+}
+
+.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited {
+    color: #555555;
+    text-decoration: none;
+}
+
+.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus {
+    border: 1px solid #999999;
+    background: #dadada url(images/ui-bg_glass_75_dadada_1x400.png) 50% 50% repeat-x;
+    font-weight: normal;
+    color: #212121;
+}
+
+.ui-state-hover a, .ui-state-hover a:hover {
+    color: #212121;
+    text-decoration: none;
+}
+
+.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active {
+    border: 1px solid #aaaaaa;
+    background: #ffffff url(images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x;
+    font-weight: normal;
+    color: #212121;
+}
+
+.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited {
+    color: #212121;
+    text-decoration: none;
+}
+
+.ui-widget :active {
+    outline: none;
+}
 
 /* Interaction Cues
 ----------------------------------*/
-.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight  {border: 1px solid #fcefa1; background: #fbf9ee url(images/ui-bg_glass_55_fbf9ee_1x400.png) 50% 50% repeat-x; color: #363636; }
-.ui-state-highlight a, .ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a { color: #363636; }
-.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {border: 1px solid #cd0a0a; background: #fef1ec url(images/ui-bg_glass_95_fef1ec_1x400.png) 50% 50% repeat-x; color: #cd0a0a; }
-.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #cd0a0a; }
-.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #cd0a0a; }
-.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; }
-.ui-priority-secondary, .ui-widget-content .ui-priority-secondary,  .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; }
-.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; }
+.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {
+    border: 1px solid #fcefa1;
+    background: #fbf9ee url(images/ui-bg_glass_55_fbf9ee_1x400.png) 50% 50% repeat-x;
+    color: #363636;
+}
+
+.ui-state-highlight a, .ui-widget-content .ui-state-highlight a, .ui-widget-header .ui-state-highlight a {
+    color: #363636;
+}
+
+.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {
+    border: 1px solid #cd0a0a;
+    background: #fef1ec url(images/ui-bg_glass_95_fef1ec_1x400.png) 50% 50% repeat-x;
+    color: #cd0a0a;
+}
+
+.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a {
+    color: #cd0a0a;
+}
+
+.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text {
+    color: #cd0a0a;
+}
+
+.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary {
+    font-weight: bold;
+}
+
+.ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary {
+    opacity: .7;
+    filter: Alpha(Opacity=70);
+    font-weight: normal;
+}
+
+.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled {
+    opacity: .35;
+    filter: Alpha(Opacity=35);
+    background-image: none;
+}
 
 /* Icons
 ----------------------------------*/
 
 /* states and images */
-.ui-icon { width: 16px; height: 16px; background-image: url(images/ui-icons_222222_256x240.png); }
-.ui-widget-content .ui-icon {background-image: url(images/ui-icons_222222_256x240.png); }
-.ui-widget-header .ui-icon {background-image: url(images/ui-icons_222222_256x240.png); }
-.ui-state-default .ui-icon { background-image: url(images/ui-icons_888888_256x240.png); }
-.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(images/ui-icons_454545_256x240.png); }
-.ui-state-active .ui-icon {background-image: url(images/ui-icons_454545_256x240.png); }
-.ui-state-highlight .ui-icon {background-image: url(images/ui-icons_2e83ff_256x240.png); }
-.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(images/ui-icons_cd0a0a_256x240.png); }
+.ui-icon {
+    width: 16px;
+    height: 16px;
+    background-image: url(images/ui-icons_222222_256x240.png);
+}
+
+.ui-widget-content .ui-icon {
+    background-image: url(images/ui-icons_222222_256x240.png);
+}
+
+.ui-widget-header .ui-icon {
+    background-image: url(images/ui-icons_222222_256x240.png);
+}
+
+.ui-state-default .ui-icon {
+    background-image: url(images/ui-icons_888888_256x240.png);
+}
+
+.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {
+    background-image: url(images/ui-icons_454545_256x240.png);
+}
+
+.ui-state-active .ui-icon {
+    background-image: url(images/ui-icons_454545_256x240.png);
+}
+
+.ui-state-highlight .ui-icon {
+    background-image: url(images/ui-icons_2e83ff_256x240.png);
+}
+
+.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {
+    background-image: url(images/ui-icons_cd0a0a_256x240.png);
+}
 
 /* positioning */
-.ui-icon-carat-1-n { background-position: 0 0; }
-.ui-icon-carat-1-ne { background-position: -16px 0; }
-.ui-icon-carat-1-e { background-position: -32px 0; }
-.ui-icon-carat-1-se { background-position: -48px 0; }
-.ui-icon-carat-1-s { background-position: -64px 0; }
-.ui-icon-carat-1-sw { background-position: -80px 0; }
-.ui-icon-carat-1-w { background-position: -96px 0; }
-.ui-icon-carat-1-nw { background-position: -112px 0; }
-.ui-icon-carat-2-n-s { background-position: -128px 0; }
-.ui-icon-carat-2-e-w { background-position: -144px 0; }
-.ui-icon-triangle-1-n { background-position: 0 -16px; }
-.ui-icon-triangle-1-ne { background-position: -16px -16px; }
-.ui-icon-triangle-1-e { background-position: -32px -16px; }
-.ui-icon-triangle-1-se { background-position: -48px -16px; }
-.ui-icon-triangle-1-s { background-position: -64px -16px; }
-.ui-icon-triangle-1-sw { background-position: -80px -16px; }
-.ui-icon-triangle-1-w { background-position: -96px -16px; }
-.ui-icon-triangle-1-nw { background-position: -112px -16px; }
-.ui-icon-triangle-2-n-s { background-position: -128px -16px; }
-.ui-icon-triangle-2-e-w { background-position: -144px -16px; }
-.ui-icon-arrow-1-n { background-position: 0 -32px; }
-.ui-icon-arrow-1-ne { background-position: -16px -32px; }
-.ui-icon-arrow-1-e { background-position: -32px -32px; }
-.ui-icon-arrow-1-se { background-position: -48px -32px; }
-.ui-icon-arrow-1-s { background-position: -64px -32px; }
-.ui-icon-arrow-1-sw { background-position: -80px -32px; }
-.ui-icon-arrow-1-w { background-position: -96px -32px; }
-.ui-icon-arrow-1-nw { background-position: -112px -32px; }
-.ui-icon-arrow-2-n-s { background-position: -128px -32px; }
-.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; }
-.ui-icon-arrow-2-e-w { background-position: -160px -32px; }
-.ui-icon-arrow-2-se-nw { background-position: -176px -32px; }
-.ui-icon-arrowstop-1-n { background-position: -192px -32px; }
-.ui-icon-arrowstop-1-e { background-position: -208px -32px; }
-.ui-icon-arrowstop-1-s { background-position: -224px -32px; }
-.ui-icon-arrowstop-1-w { background-position: -240px -32px; }
-.ui-icon-arrowthick-1-n { background-position: 0 -48px; }
-.ui-icon-arrowthick-1-ne { background-position: -16px -48px; }
-.ui-icon-arrowthick-1-e { background-position: -32px -48px; }
-.ui-icon-arrowthick-1-se { background-position: -48px -48px; }
-.ui-icon-arrowthick-1-s { background-position: -64px -48px; }
-.ui-icon-arrowthick-1-sw { background-position: -80px -48px; }
-.ui-icon-arrowthick-1-w { background-position: -96px -48px; }
-.ui-icon-arrowthick-1-nw { background-position: -112px -48px; }
-.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; }
-.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; }
-.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; }
-.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; }
-.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; }
-.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; }
-.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; }
-.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; }
-.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; }
-.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; }
-.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; }
-.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; }
-.ui-icon-arrowreturn-1-w { background-position: -64px -64px; }
-.ui-icon-arrowreturn-1-n { background-position: -80px -64px; }
-.ui-icon-arrowreturn-1-e { background-position: -96px -64px; }
-.ui-icon-arrowreturn-1-s { background-position: -112px -64px; }
-.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; }
-.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; }
-.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; }
-.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; }
-.ui-icon-arrow-4 { background-position: 0 -80px; }
-.ui-icon-arrow-4-diag { background-position: -16px -80px; }
-.ui-icon-extlink { background-position: -32px -80px; }
-.ui-icon-newwin { background-position: -48px -80px; }
-.ui-icon-refresh { background-position: -64px -80px; }
-.ui-icon-shuffle { background-position: -80px -80px; }
-.ui-icon-transfer-e-w { background-position: -96px -80px; }
-.ui-icon-transferthick-e-w { background-position: -112px -80px; }
-.ui-icon-folder-collapsed { background-position: 0 -96px; }
-.ui-icon-folder-open { background-position: -16px -96px; }
-.ui-icon-document { background-position: -32px -96px; }
-.ui-icon-document-b { background-position: -48px -96px; }
-.ui-icon-note { background-position: -64px -96px; }
-.ui-icon-mail-closed { background-position: -80px -96px; }
-.ui-icon-mail-open { background-position: -96px -96px; }
-.ui-icon-suitcase { background-position: -112px -96px; }
-.ui-icon-comment { background-position: -128px -96px; }
-.ui-icon-person { background-position: -144px -96px; }
-.ui-icon-print { background-position: -160px -96px; }
-.ui-icon-trash { background-position: -176px -96px; }
-.ui-icon-locked { background-position: -192px -96px; }
-.ui-icon-unlocked { background-position: -208px -96px; }
-.ui-icon-bookmark { background-position: -224px -96px; }
-.ui-icon-tag { background-position: -240px -96px; }
-.ui-icon-home { background-position: 0 -112px; }
-.ui-icon-flag { background-position: -16px -112px; }
-.ui-icon-calendar { background-position: -32px -112px; }
-.ui-icon-cart { background-position: -48px -112px; }
-.ui-icon-pencil { background-position: -64px -112px; }
-.ui-icon-clock { background-position: -80px -112px; }
-.ui-icon-disk { background-position: -96px -112px; }
-.ui-icon-calculator { background-position: -112px -112px; }
-.ui-icon-zoomin { background-position: -128px -112px; }
-.ui-icon-zoomout { background-position: -144px -112px; }
-.ui-icon-search { background-position: -160px -112px; }
-.ui-icon-wrench { background-position: -176px -112px; }
-.ui-icon-gear { background-position: -192px -112px; }
-.ui-icon-heart { background-position: -208px -112px; }
-.ui-icon-star { background-position: -224px -112px; }
-.ui-icon-link { background-position: -240px -112px; }
-.ui-icon-cancel { background-position: 0 -128px; }
-.ui-icon-plus { background-position: -16px -128px; }
-.ui-icon-plusthick { background-position: -32px -128px; }
-.ui-icon-minus { background-position: -48px -128px; }
-.ui-icon-minusthick { background-position: -64px -128px; }
-.ui-icon-close { background-position: -80px -128px; }
-.ui-icon-closethick { background-position: -96px -128px; }
-.ui-icon-key { background-position: -112px -128px; }
-.ui-icon-lightbulb { background-position: -128px -128px; }
-.ui-icon-scissors { background-position: -144px -128px; }
-.ui-icon-clipboard { background-position: -160px -128px; }
-.ui-icon-copy { background-position: -176px -128px; }
-.ui-icon-contact { background-position: -192px -128px; }
-.ui-icon-image { background-position: -208px -128px; }
-.ui-icon-video { background-position: -224px -128px; }
-.ui-icon-script { background-position: -240px -128px; }
-.ui-icon-alert { background-position: 0 -144px; }
-.ui-icon-info { background-position: -16px -144px; }
-.ui-icon-notice { background-position: -32px -144px; }
-.ui-icon-help { background-position: -48px -144px; }
-.ui-icon-check { background-position: -64px -144px; }
-.ui-icon-bullet { background-position: -80px -144px; }
-.ui-icon-radio-off { background-position: -96px -144px; }
-.ui-icon-radio-on { background-position: -112px -144px; }
-.ui-icon-pin-w { background-position: -128px -144px; }
-.ui-icon-pin-s { background-position: -144px -144px; }
-.ui-icon-play { background-position: 0 -160px; }
-.ui-icon-pause { background-position: -16px -160px; }
-.ui-icon-seek-next { background-position: -32px -160px; }
-.ui-icon-seek-prev { background-position: -48px -160px; }
-.ui-icon-seek-end { background-position: -64px -160px; }
-.ui-icon-seek-start { background-position: -80px -160px; }
+.ui-icon-carat-1-n {
+    background-position: 0 0;
+}
+
+.ui-icon-carat-1-ne {
+    background-position: -16px 0;
+}
+
+.ui-icon-carat-1-e {
+    background-position: -32px 0;
+}
+
+.ui-icon-carat-1-se {
+    background-position: -48px 0;
+}
+
+.ui-icon-carat-1-s {
+    background-position: -64px 0;
+}
+
+.ui-icon-carat-1-sw {
+    background-position: -80px 0;
+}
+
+.ui-icon-carat-1-w {
+    background-position: -96px 0;
+}
+
+.ui-icon-carat-1-nw {
+    background-position: -112px 0;
+}
+
+.ui-icon-carat-2-n-s {
+    background-position: -128px 0;
+}
+
+.ui-icon-carat-2-e-w {
+    background-position: -144px 0;
+}
+
+.ui-icon-triangle-1-n {
+    background-position: 0 -16px;
+}
+
+.ui-icon-triangle-1-ne {
+    background-position: -16px -16px;
+}
+
+.ui-icon-triangle-1-e {
+    background-position: -32px -16px;
+}
+
+.ui-icon-triangle-1-se {
+    background-position: -48px -16px;
+}
+
+.ui-icon-triangle-1-s {
+    background-position: -64px -16px;
+}
+
+.ui-icon-triangle-1-sw {
+    background-position: -80px -16px;
+}
+
+.ui-icon-triangle-1-w {
+    background-position: -96px -16px;
+}
+
+.ui-icon-triangle-1-nw {
+    background-position: -112px -16px;
+}
+
+.ui-icon-triangle-2-n-s {
+    background-position: -128px -16px;
+}
+
+.ui-icon-triangle-2-e-w {
+    background-position: -144px -16px;
+}
+
+.ui-icon-arrow-1-n {
+    background-position: 0 -32px;
+}
+
+.ui-icon-arrow-1-ne {
+    background-position: -16px -32px;
+}
+
+.ui-icon-arrow-1-e {
+    background-position: -32px -32px;
+}
+
+.ui-icon-arrow-1-se {
+    background-position: -48px -32px;
+}
+
+.ui-icon-arrow-1-s {
+    background-position: -64px -32px;
+}
+
+.ui-icon-arrow-1-sw {
+    background-position: -80px -32px;
+}
+
+.ui-icon-arrow-1-w {
+    background-position: -96px -32px;
+}
+
+.ui-icon-arrow-1-nw {
+    background-position: -112px -32px;
+}
+
+.ui-icon-arrow-2-n-s {
+    background-position: -128px -32px;
+}
+
+.ui-icon-arrow-2-ne-sw {
+    background-position: -144px -32px;
+}
+
+.ui-icon-arrow-2-e-w {
+    background-position: -160px -32px;
+}
+
+.ui-icon-arrow-2-se-nw {
+    background-position: -176px -32px;
+}
+
+.ui-icon-arrowstop-1-n {
+    background-position: -192px -32px;
+}
+
+.ui-icon-arrowstop-1-e {
+    background-position: -208px -32px;
+}
+
+.ui-icon-arrowstop-1-s {
+    background-position: -224px -32px;
+}
+
+.ui-icon-arrowstop-1-w {
+    background-position: -240px -32px;
+}
+
+.ui-icon-arrowthick-1-n {
+    background-position: 0 -48px;
+}
+
+.ui-icon-arrowthick-1-ne {
+    background-position: -16px -48px;
+}
+
+.ui-icon-arrowthick-1-e {
+    background-position: -32px -48px;
+}
+
+.ui-icon-arrowthick-1-se {
+    background-position: -48px -48px;
+}
+
+.ui-icon-arrowthick-1-s {
+    background-position: -64px -48px;
+}
+
+.ui-icon-arrowthick-1-sw {
+    background-position: -80px -48px;
+}
+
+.ui-icon-arrowthick-1-w {
+    background-position: -96px -48px;
+}
+
+.ui-icon-arrowthick-1-nw {
+    background-position: -112px -48px;
+}
+
+.ui-icon-arrowthick-2-n-s {
+    background-position: -128px -48px;
+}
+
+.ui-icon-arrowthick-2-ne-sw {
+    background-position: -144px -48px;
+}
+
+.ui-icon-arrowthick-2-e-w {
+    background-position: -160px -48px;
+}
+
+.ui-icon-arrowthick-2-se-nw {
+    background-position: -176px -48px;
+}
+
+.ui-icon-arrowthickstop-1-n {
+    background-position: -192px -48px;
+}
+
+.ui-icon-arrowthickstop-1-e {
+    background-position: -208px -48px;
+}
+
+.ui-icon-arrowthickstop-1-s {
+    background-position: -224px -48px;
+}
+
+.ui-icon-arrowthickstop-1-w {
+    background-position: -240px -48px;
+}
+
+.ui-icon-arrowreturnthick-1-w {
+    background-position: 0 -64px;
+}
+
+.ui-icon-arrowreturnthick-1-n {
+    background-position: -16px -64px;
+}
+
+.ui-icon-arrowreturnthick-1-e {
+    background-position: -32px -64px;
+}
+
+.ui-icon-arrowreturnthick-1-s {
+    background-position: -48px -64px;
+}
+
+.ui-icon-arrowreturn-1-w {
+    background-position: -64px -64px;
+}
+
+.ui-icon-arrowreturn-1-n {
+    background-position: -80px -64px;
+}
+
+.ui-icon-arrowreturn-1-e {
+    background-position: -96px -64px;
+}
+
+.ui-icon-arrowreturn-1-s {
+    background-position: -112px -64px;
+}
+
+.ui-icon-arrowrefresh-1-w {
+    background-position: -128px -64px;
+}
+
+.ui-icon-arrowrefresh-1-n {
+    background-position: -144px -64px;
+}
+
+.ui-icon-arrowrefresh-1-e {
+    background-position: -160px -64px;
+}
+
+.ui-icon-arrowrefresh-1-s {
+    background-position: -176px -64px;
+}
+
+.ui-icon-arrow-4 {
+    background-position: 0 -80px;
+}
+
+.ui-icon-arrow-4-diag {
+    background-position: -16px -80px;
+}
+
+.ui-icon-extlink {
+    background-position: -32px -80px;
+}
+
+.ui-icon-newwin {
+    background-position: -48px -80px;
+}
+
+.ui-icon-refresh {
+    background-position: -64px -80px;
+}
+
+.ui-icon-shuffle {
+    background-position: -80px -80px;
+}
+
+.ui-icon-transfer-e-w {
+    background-position: -96px -80px;
+}
+
+.ui-icon-transferthick-e-w {
+    background-position: -112px -80px;
+}
+
+.ui-icon-folder-collapsed {
+    background-position: 0 -96px;
+}
+
+.ui-icon-folder-open {
+    background-position: -16px -96px;
+}
+
+.ui-icon-document {
+    background-position: -32px -96px;
+}
+
+.ui-icon-document-b {
+    background-position: -48px -96px;
+}
+
+.ui-icon-note {
+    background-position: -64px -96px;
+}
+
+.ui-icon-mail-closed {
+    background-position: -80px -96px;
+}
+
+.ui-icon-mail-open {
+    background-position: -96px -96px;
+}
+
+.ui-icon-suitcase {
+    background-position: -112px -96px;
+}
+
+.ui-icon-comment {
+    background-position: -128px -96px;
+}
+
+.ui-icon-person {
+    background-position: -144px -96px;
+}
+
+.ui-icon-print {
+    background-position: -160px -96px;
+}
+
+.ui-icon-trash {
+    background-position: -176px -96px;
+}
+
+.ui-icon-locked {
+    background-position: -192px -96px;
+}
+
+.ui-icon-unlocked {
+    background-position: -208px -96px;
+}
+
+.ui-icon-bookmark {
+    background-position: -224px -96px;
+}
+
+.ui-icon-tag {
+    background-position: -240px -96px;
+}
+
+.ui-icon-home {
+    background-position: 0 -112px;
+}
+
+.ui-icon-flag {
+    background-position: -16px -112px;
+}
+
+.ui-icon-calendar {
+    background-position: -32px -112px;
+}
+
+.ui-icon-cart {
+    background-position: -48px -112px;
+}
+
+.ui-icon-pencil {
+    background-position: -64px -112px;
+}
+
+.ui-icon-clock {
+    background-position: -80px -112px;
+}
+
+.ui-icon-disk {
+    background-position: -96px -112px;
+}
+
+.ui-icon-calculator {
+    background-position: -112px -112px;
+}
+
+.ui-icon-zoomin {
+    background-position: -128px -112px;
+}
+
+.ui-icon-zoomout {
+    background-position: -144px -112px;
+}
+
+.ui-icon-search {
+    background-position: -160px -112px;
+}
+
+.ui-icon-wrench {
+    background-position: -176px -112px;
+}
+
+.ui-icon-gear {
+    background-position: -192px -112px;
+}
+
+.ui-icon-heart {
+    background-position: -208px -112px;
+}
+
+.ui-icon-star {
+    background-position: -224px -112px;
+}
+
+.ui-icon-link {
+    background-position: -240px -112px;
+}
+
+.ui-icon-cancel {
+    background-position: 0 -128px;
+}
+
+.ui-icon-plus {
+    background-position: -16px -128px;
+}
+
+.ui-icon-plusthick {
+    background-position: -32px -128px;
+}
+
+.ui-icon-minus {
+    background-position: -48px -128px;
+}
+
+.ui-icon-minusthick {
+    background-position: -64px -128px;
+}
+
+.ui-icon-close {
+    background-position: -80px -128px;
+}
+
+.ui-icon-closethick {
+    background-position: -96px -128px;
+}
+
+.ui-icon-key {
+    background-position: -112px -128px;
+}
+
+.ui-icon-lightbulb {
+    background-position: -128px -128px;
+}
+
+.ui-icon-scissors {
+    background-position: -144px -128px;
+}
+
+.ui-icon-clipboard {
+    background-position: -160px -128px;
+}
+
+.ui-icon-copy {
+    background-position: -176px -128px;
+}
+
+.ui-icon-contact {
+    background-position: -192px -128px;
+}
+
+.ui-icon-image {
+    background-position: -208px -128px;
+}
+
+.ui-icon-video {
+    background-position: -224px -128px;
+}
+
+.ui-icon-script {
+    background-position: -240px -128px;
+}
+
+.ui-icon-alert {
+    background-position: 0 -144px;
+}
+
+.ui-icon-info {
+    background-position: -16px -144px;
+}
+
+.ui-icon-notice {
+    background-position: -32px -144px;
+}
+
+.ui-icon-help {
+    background-position: -48px -144px;
+}
+
+.ui-icon-check {
+    background-position: -64px -144px;
+}
+
+.ui-icon-bullet {
+    background-position: -80px -144px;
+}
+
+.ui-icon-radio-off {
+    background-position: -96px -144px;
+}
+
+.ui-icon-radio-on {
+    background-position: -112px -144px;
+}
+
+.ui-icon-pin-w {
+    background-position: -128px -144px;
+}
+
+.ui-icon-pin-s {
+    background-position: -144px -144px;
+}
+
+.ui-icon-play {
+    background-position: 0 -160px;
+}
+
+.ui-icon-pause {
+    background-position: -16px -160px;
+}
+
+.ui-icon-seek-next {
+    background-position: -32px -160px;
+}
+
+.ui-icon-seek-prev {
+    background-position: -48px -160px;
+}
+
+.ui-icon-seek-end {
+    background-position: -64px -160px;
+}
+
+.ui-icon-seek-start {
+    background-position: -80px -160px;
+}
+
 /* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */
-.ui-icon-seek-first { background-position: -80px -160px; }
-.ui-icon-stop { background-position: -96px -160px; }
-.ui-icon-eject { background-position: -112px -160px; }
-.ui-icon-volume-off { background-position: -128px -160px; }
-.ui-icon-volume-on { background-position: -144px -160px; }
-.ui-icon-power { background-position: 0 -176px; }
-.ui-icon-signal-diag { background-position: -16px -176px; }
-.ui-icon-signal { background-position: -32px -176px; }
-.ui-icon-battery-0 { background-position: -48px -176px; }
-.ui-icon-battery-1 { background-position: -64px -176px; }
-.ui-icon-battery-2 { background-position: -80px -176px; }
-.ui-icon-battery-3 { background-position: -96px -176px; }
-.ui-icon-circle-plus { background-position: 0 -192px; }
-.ui-icon-circle-minus { background-position: -16px -192px; }
-.ui-icon-circle-close { background-position: -32px -192px; }
-.ui-icon-circle-triangle-e { background-position: -48px -192px; }
-.ui-icon-circle-triangle-s { background-position: -64px -192px; }
-.ui-icon-circle-triangle-w { background-position: -80px -192px; }
-.ui-icon-circle-triangle-n { background-position: -96px -192px; }
-.ui-icon-circle-arrow-e { background-position: -112px -192px; }
-.ui-icon-circle-arrow-s { background-position: -128px -192px; }
-.ui-icon-circle-arrow-w { background-position: -144px -192px; }
-.ui-icon-circle-arrow-n { background-position: -160px -192px; }
-.ui-icon-circle-zoomin { background-position: -176px -192px; }
-.ui-icon-circle-zoomout { background-position: -192px -192px; }
-.ui-icon-circle-check { background-position: -208px -192px; }
-.ui-icon-circlesmall-plus { background-position: 0 -208px; }
-.ui-icon-circlesmall-minus { background-position: -16px -208px; }
-.ui-icon-circlesmall-close { background-position: -32px -208px; }
-.ui-icon-squaresmall-plus { background-position: -48px -208px; }
-.ui-icon-squaresmall-minus { background-position: -64px -208px; }
-.ui-icon-squaresmall-close { background-position: -80px -208px; }
-.ui-icon-grip-dotted-vertical { background-position: 0 -224px; }
-.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; }
-.ui-icon-grip-solid-vertical { background-position: -32px -224px; }
-.ui-icon-grip-solid-horizontal { background-position: -48px -224px; }
-.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; }
-.ui-icon-grip-diagonal-se { background-position: -80px -224px; }
+.ui-icon-seek-first {
+    background-position: -80px -160px;
+}
+
+.ui-icon-stop {
+    background-position: -96px -160px;
+}
+
+.ui-icon-eject {
+    background-position: -112px -160px;
+}
+
+.ui-icon-volume-off {
+    background-position: -128px -160px;
+}
+
+.ui-icon-volume-on {
+    background-position: -144px -160px;
+}
+
+.ui-icon-power {
+    background-position: 0 -176px;
+}
+
+.ui-icon-signal-diag {
+    background-position: -16px -176px;
+}
+
+.ui-icon-signal {
+    background-position: -32px -176px;
+}
+
+.ui-icon-battery-0 {
+    background-position: -48px -176px;
+}
+
+.ui-icon-battery-1 {
+    background-position: -64px -176px;
+}
+
+.ui-icon-battery-2 {
+    background-position: -80px -176px;
+}
+
+.ui-icon-battery-3 {
+    background-position: -96px -176px;
+}
+
+.ui-icon-circle-plus {
+    background-position: 0 -192px;
+}
+
+.ui-icon-circle-minus {
+    background-position: -16px -192px;
+}
+
+.ui-icon-circle-close {
+    background-position: -32px -192px;
+}
+
+.ui-icon-circle-triangle-e {
+    background-position: -48px -192px;
+}
+
+.ui-icon-circle-triangle-s {
+    background-position: -64px -192px;
+}
+
+.ui-icon-circle-triangle-w {
+    background-position: -80px -192px;
+}
+
+.ui-icon-circle-triangle-n {
+    background-position: -96px -192px;
+}
+
+.ui-icon-circle-arrow-e {
+    background-position: -112px -192px;
+}
+
+.ui-icon-circle-arrow-s {
+    background-position: -128px -192px;
+}
+
+.ui-icon-circle-arrow-w {
+    background-position: -144px -192px;
+}
+
+.ui-icon-circle-arrow-n {
+    background-position: -160px -192px;
+}
+
+.ui-icon-circle-zoomin {
+    background-position: -176px -192px;
+}
 
+.ui-icon-circle-zoomout {
+    background-position: -192px -192px;
+}
+
+.ui-icon-circle-check {
+    background-position: -208px -192px;
+}
+
+.ui-icon-circlesmall-plus {
+    background-position: 0 -208px;
+}
+
+.ui-icon-circlesmall-minus {
+    background-position: -16px -208px;
+}
+
+.ui-icon-circlesmall-close {
+    background-position: -32px -208px;
+}
+
+.ui-icon-squaresmall-plus {
+    background-position: -48px -208px;
+}
+
+.ui-icon-squaresmall-minus {
+    background-position: -64px -208px;
+}
+
+.ui-icon-squaresmall-close {
+    background-position: -80px -208px;
+}
+
+.ui-icon-grip-dotted-vertical {
+    background-position: 0 -224px;
+}
+
+.ui-icon-grip-dotted-horizontal {
+    background-position: -16px -224px;
+}
+
+.ui-icon-grip-solid-vertical {
+    background-position: -32px -224px;
+}
+
+.ui-icon-grip-solid-horizontal {
+    background-position: -48px -224px;
+}
+
+.ui-icon-gripsmall-diagonal-se {
+    background-position: -64px -224px;
+}
+
+.ui-icon-grip-diagonal-se {
+    background-position: -80px -224px;
+}
 
 /* Misc visuals
 ----------------------------------*/
 
 /* Corner radius */
-.ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -khtml-border-top-left-radius: 4px; border-top-left-radius: 4px; }
-.ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; -khtml-border-top-right-radius: 4px; border-top-right-radius: 4px; }
-.ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; -khtml-border-bottom-left-radius: 4px; border-bottom-left-radius: 4px; }
-.ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; -khtml-border-bottom-right-radius: 4px; border-bottom-right-radius: 4px; }
+.ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl {
+    -moz-border-radius-topleft: 4px;
+    -webkit-border-top-left-radius: 4px;
+    -khtml-border-top-left-radius: 4px;
+    border-top-left-radius: 4px;
+}
+
+.ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr {
+    -moz-border-radius-topright: 4px;
+    -webkit-border-top-right-radius: 4px;
+    -khtml-border-top-right-radius: 4px;
+    border-top-right-radius: 4px;
+}
+
+.ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl {
+    -moz-border-radius-bottomleft: 4px;
+    -webkit-border-bottom-left-radius: 4px;
+    -khtml-border-bottom-left-radius: 4px;
+    border-bottom-left-radius: 4px;
+}
+
+.ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br {
+    -moz-border-radius-bottomright: 4px;
+    -webkit-border-bottom-right-radius: 4px;
+    -khtml-border-bottom-right-radius: 4px;
+    border-bottom-right-radius: 4px;
+}
 
 /* Overlays */
-.ui-widget-overlay { background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30); }
-.ui-widget-shadow { margin: -8px 0 0 -8px; padding: 8px; background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30); -moz-border-radius: 8px; -khtml-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px; }/*!
+.ui-widget-overlay {
+    background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x;
+    opacity: .30;
+    filter: Alpha(Opacity=30);
+}
+
+.ui-widget-shadow {
+    margin: -8px 0 0 -8px;
+    padding: 8px;
+    background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x;
+    opacity: .30;
+    filter: Alpha(Opacity=30);
+    -moz-border-radius: 8px;
+    -khtml-border-radius: 8px;
+    -webkit-border-radius: 8px;
+    border-radius: 8px;
+}
+
+/*!
  * jQuery UI Resizable 1.8.21
  *
  * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about)
@@ -293,17 +1012,85 @@
  *
  * http://docs.jquery.com/UI/Resizable#theming
  */
-.ui-resizable { position: relative;}
-.ui-resizable-handle { position: absolute;font-size: 0.1px; display: block; }
-.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; }
-.ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; }
-.ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; }
-.ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; }
-.ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; }
-.ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; }
-.ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; }
-.ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; }
-.ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;}/*!
+.ui-resizable {
+    position: relative;
+}
+
+.ui-resizable-handle {
+    position: absolute;
+    font-size: 0.1px;
+    display: block;
+}
+
+.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle {
+    display: none;
+}
+
+.ui-resizable-n {
+    cursor: n-resize;
+    height: 7px;
+    width: 100%;
+    top: -5px;
+    left: 0;
+}
+
+.ui-resizable-s {
+    cursor: s-resize;
+    height: 7px;
+    width: 100%;
+    bottom: -5px;
+    left: 0;
+}
+
+.ui-resizable-e {
+    cursor: e-resize;
+    width: 7px;
+    right: -5px;
+    top: 0;
+    height: 100%;
+}
+
+.ui-resizable-w {
+    cursor: w-resize;
+    width: 7px;
+    left: -5px;
+    top: 0;
+    height: 100%;
+}
+
+.ui-resizable-se {
+    cursor: se-resize;
+    width: 12px;
+    height: 12px;
+    right: 1px;
+    bottom: 1px;
+}
+
+.ui-resizable-sw {
+    cursor: sw-resize;
+    width: 9px;
+    height: 9px;
+    left: -5px;
+    bottom: -5px;
+}
+
+.ui-resizable-nw {
+    cursor: nw-resize;
+    width: 9px;
+    height: 9px;
+    left: -5px;
+    top: -5px;
+}
+
+.ui-resizable-ne {
+    cursor: ne-resize;
+    width: 9px;
+    height: 9px;
+    right: -5px;
+    top: -5px;
+}
+
+/*!
  * jQuery UI Accordion 1.8.21
  *
  * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about)
@@ -313,15 +1100,58 @@
  * http://docs.jquery.com/UI/Accordion#theming
  */
 /* IE/Win - Fix animation bug - #4615 */
-.ui-accordion { width: 100%; }
-.ui-accordion .ui-accordion-header { cursor: pointer; position: relative; margin-top: 1px; zoom: 1; }
-.ui-accordion .ui-accordion-li-fix { display: inline; }
-.ui-accordion .ui-accordion-header-active { border-bottom: 0 !important; }
-.ui-accordion .ui-accordion-header a { display: block; font-size: 1em; padding: .5em .5em .5em .7em; }
-.ui-accordion-icons .ui-accordion-header a { padding-left: 2.2em; }
-.ui-accordion .ui-accordion-header .ui-icon { position: absolute; left: .5em; top: 50%; margin-top: -8px; }
-.ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; margin-top: -2px; position: relative; top: 1px; margin-bottom: 2px; overflow: auto; display: none; zoom: 1; }
-.ui-accordion .ui-accordion-content-active { display: block; }
+.ui-accordion {
+    width: 100%;
+}
+
+.ui-accordion .ui-accordion-header {
+    cursor: pointer;
+    position: relative;
+    margin-top: 1px;
+    zoom: 1;
+}
+
+.ui-accordion .ui-accordion-li-fix {
+    display: inline;
+}
+
+.ui-accordion .ui-accordion-header-active {
+    border-bottom: 0 !important;
+}
+
+.ui-accordion .ui-accordion-header a {
+    display: block;
+    font-size: 1em;
+    padding: .5em .5em .5em .7em;
+}
+
+.ui-accordion-icons .ui-accordion-header a {
+    padding-left: 2.2em;
+}
+
+.ui-accordion .ui-accordion-header .ui-icon {
+    position: absolute;
+    left: .5em;
+    top: 50%;
+    margin-top: -8px;
+}
+
+.ui-accordion .ui-accordion-content {
+    padding: 1em 2.2em;
+    border-top: 0;
+    margin-top: -2px;
+    position: relative;
+    top: 1px;
+    margin-bottom: 2px;
+    overflow: auto;
+    display: none;
+    zoom: 1;
+}
+
+.ui-accordion .ui-accordion-content-active {
+    display: block;
+}
+
 /*!
  * jQuery UI Button 1.8.21
  *
@@ -331,35 +1161,111 @@
  *
  * http://docs.jquery.com/UI/Button#theming
  */
-.ui-button { display: inline-block; position: relative; padding: 0; margin-right: .1em; text-decoration: none !important; cursor: pointer; text-align: center; zoom: 1; overflow: visible; } /* the overflow property removes extra width in IE */
-.ui-button-icon-only { width: 2.2em; } /* to make room for the icon, a width needs to be set here */
-button.ui-button-icon-only { width: 2.4em; } /* button elements seem to need a little more width */
-.ui-button-icons-only { width: 3.4em; } 
-button.ui-button-icons-only { width: 3.7em; } 
+.ui-button {
+    display: inline-block;
+    position: relative;
+    padding: 0;
+    margin-right: .1em;
+    text-decoration: none !important;
+    cursor: pointer;
+    text-align: center;
+    zoom: 1;
+    overflow: visible;
+}
+
+/* the overflow property removes extra width in IE */
+.ui-button-icon-only {
+    width: 2.2em;
+}
+
+/* to make room for the icon, a width needs to be set here */
+button.ui-button-icon-only {
+    width: 2.4em;
+}
+
+/* button elements seem to need a little more width */
+.ui-button-icons-only {
+    width: 3.4em;
+}
+
+button.ui-button-icons-only {
+    width: 3.7em;
+}
 
 /*button text element */
-.ui-button .ui-button-text { display: block; line-height: 1.4;  }
-.ui-button-text-only .ui-button-text { padding: .4em 1em; }
-.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: .4em; text-indent: -9999999px; }
-.ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 1em .4em 2.1em; }
-.ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 2.1em .4em 1em; }
-.ui-button-text-icons .ui-button-text { padding-left: 2.1em; padding-right: 2.1em; }
+.ui-button .ui-button-text {
+    display: block;
+    line-height: 1.4;
+}
+
+.ui-button-text-only .ui-button-text {
+    padding: .4em 1em;
+}
+
+.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text {
+    padding: .4em;
+    text-indent: -9999999px;
+}
+
+.ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text {
+    padding: .4em 1em .4em 2.1em;
+}
+
+.ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text {
+    padding: .4em 2.1em .4em 1em;
+}
+
+.ui-button-text-icons .ui-button-text {
+    padding-left: 2.1em;
+    padding-right: 2.1em;
+}
+
 /* no icon support for input elements, provide padding by default */
-input.ui-button { padding: .4em 1em; }
+input.ui-button {
+    padding: .4em 1em;
+}
 
 /*button icon element(s) */
-.ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon { position: absolute; top: 50%; margin-top: -8px; }
-.ui-button-icon-only .ui-icon { left: 50%; margin-left: -8px; }
-.ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary { left: .5em; }
-.ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; }
-.ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; }
+.ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon {
+    position: absolute;
+    top: 50%;
+    margin-top: -8px;
+}
+
+.ui-button-icon-only .ui-icon {
+    left: 50%;
+    margin-left: -8px;
+}
+
+.ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary {
+    left: .5em;
+}
+
+.ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary {
+    right: .5em;
+}
+
+.ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary {
+    right: .5em;
+}
 
 /*button sets*/
-.ui-buttonset { margin-right: 7px; }
-.ui-buttonset .ui-button { margin-left: 0; margin-right: -.3em; }
+.ui-buttonset {
+    margin-right: 7px;
+}
+
+.ui-buttonset .ui-button {
+    margin-left: 0;
+    margin-right: -.3em;
+}
 
 /* workarounds */
-button.ui-button::-moz-focus-inner { border: 0; padding: 0; } /* reset extra padding in Firefox */
+button.ui-button::-moz-focus-inner {
+    border: 0;
+    padding: 0;
+}
+
+/* reset extra padding in Firefox */
 /*!
  * jQuery UI Dialog 1.8.21
  *
@@ -369,18 +1275,79 @@ button.ui-button::-moz-focus-inner { border: 0; padding: 0; } /* reset extra pad
  *
  * http://docs.jquery.com/UI/Dialog#theming
  */
-.ui-dialog { position: absolute; padding: .2em; width: 300px; overflow: hidden; }
-.ui-dialog .ui-dialog-titlebar { padding: .4em 1em; position: relative;  }
-.ui-dialog .ui-dialog-title { float: left; margin: .1em 16px .1em 0; } 
-.ui-dialog .ui-dialog-titlebar-close { position: absolute; right: .3em; top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; }
-.ui-dialog .ui-dialog-titlebar-close span { display: block; margin: 1px; }
-.ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus { padding: 0; }
-.ui-dialog .ui-dialog-content { position: relative; border: 0; padding: .5em 1em; background: none; overflow: auto; zoom: 1; }
-.ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .5em .4em; }
-.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { float: right; }
-.ui-dialog .ui-dialog-buttonpane button { margin: .5em .4em .5em 0; cursor: pointer; }
-.ui-dialog .ui-resizable-se { width: 14px; height: 14px; right: 3px; bottom: 3px; }
-.ui-draggable .ui-dialog-titlebar { cursor: move; }
+.ui-dialog {
+    position: absolute;
+    padding: .2em;
+    width: 300px;
+    overflow: hidden;
+}
+
+.ui-dialog .ui-dialog-titlebar {
+    padding: .4em 1em;
+    position: relative;
+}
+
+.ui-dialog .ui-dialog-title {
+    float: left;
+    margin: .1em 16px .1em 0;
+}
+
+.ui-dialog .ui-dialog-titlebar-close {
+    position: absolute;
+    right: .3em;
+    top: 50%;
+    width: 19px;
+    margin: -10px 0 0 0;
+    padding: 1px;
+    height: 18px;
+}
+
+.ui-dialog .ui-dialog-titlebar-close span {
+    display: block;
+    margin: 1px;
+}
+
+.ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus {
+    padding: 0;
+}
+
+.ui-dialog .ui-dialog-content {
+    position: relative;
+    border: 0;
+    padding: .5em 1em;
+    background: none;
+    overflow: auto;
+    zoom: 1;
+}
+
+.ui-dialog .ui-dialog-buttonpane {
+    text-align: left;
+    border-width: 1px 0 0 0;
+    background-image: none;
+    margin: .5em 0 0 0;
+    padding: .3em 1em .5em .4em;
+}
+
+.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset {
+    float: right;
+}
+
+.ui-dialog .ui-dialog-buttonpane button {
+    margin: .5em .4em .5em 0;
+    cursor: pointer;
+}
+
+.ui-dialog .ui-resizable-se {
+    width: 14px;
+    height: 14px;
+    right: 3px;
+    bottom: 3px;
+}
+
+.ui-draggable .ui-dialog-titlebar {
+    cursor: move;
+}
+
 /*!
  * jQuery UI Tabs 1.8.21
  *
@@ -390,15 +1357,60 @@ button.ui-button::-moz-focus-inner { border: 0; padding: 0; } /* reset extra pad
  *
  * http://docs.jquery.com/UI/Tabs#theming
  */
-.ui-tabs { position: relative; padding: .2em; zoom: 1; } /* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */
-.ui-tabs .ui-tabs-nav { margin: 0; padding: .2em .2em 0; }
-.ui-tabs .ui-tabs-nav li { list-style: none; float: left; position: relative; top: 1px; margin: 0 .2em 1px 0; border-bottom: 0 !important; padding: 0; white-space: nowrap; }
-.ui-tabs .ui-tabs-nav li a { float: left; padding: .5em 1em; text-decoration: none; }
-.ui-tabs .ui-tabs-nav li.ui-tabs-selected { margin-bottom: 0; padding-bottom: 1px; }
-.ui-tabs .ui-tabs-nav li.ui-tabs-selected a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-state-processing a { cursor: text; }
-.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a { cursor: pointer; } /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */
-.ui-tabs .ui-tabs-panel { display: block; border-width: 0; padding: 1em 1.4em; background: none; }
-.ui-tabs .ui-tabs-hide { display: none !important; }
+.ui-tabs {
+    position: relative;
+    padding: .2em;
+    zoom: 1;
+}
+
+/* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */
+.ui-tabs .ui-tabs-nav {
+    margin: 0;
+    padding: .2em .2em 0;
+}
+
+.ui-tabs .ui-tabs-nav li {
+    list-style: none;
+    float: left;
+    position: relative;
+    top: 1px;
+    margin: 0 .2em 1px 0;
+    border-bottom: 0 !important;
+    padding: 0;
+    white-space: nowrap;
+}
+
+.ui-tabs .ui-tabs-nav li a {
+    float: left;
+    padding: .5em 1em;
+    text-decoration: none;
+}
+
+.ui-tabs .ui-tabs-nav li.ui-tabs-selected {
+    margin-bottom: 0;
+    padding-bottom: 1px;
+}
+
+.ui-tabs .ui-tabs-nav li.ui-tabs-selected a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-state-processing a {
+    cursor: text;
+}
+
+.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a {
+    cursor: pointer;
+}
+
+/* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */
+.ui-tabs .ui-tabs-panel {
+    display: block;
+    border-width: 0;
+    padding: 1em 1.4em;
+    background: none;
+}
+
+.ui-tabs .ui-tabs-hide {
+    display: none !important;
+}
+
 /*!
  * jQuery UI Datepicker 1.8.21
  *
@@ -408,57 +1420,220 @@ button.ui-button::-moz-focus-inner { border: 0; padding: 0; } /* reset extra pad
  *
  * http://docs.jquery.com/UI/Datepicker#theming
  */
-.ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; }
-.ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; }
-.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; }
-.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; }
-.ui-datepicker .ui-datepicker-prev { left:2px; }
-.ui-datepicker .ui-datepicker-next { right:2px; }
-.ui-datepicker .ui-datepicker-prev-hover { left:1px; }
-.ui-datepicker .ui-datepicker-next-hover { right:1px; }
-.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px;  }
-.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; }
-.ui-datepicker .ui-datepicker-title select { font-size:1em; margin:1px 0; }
-.ui-datepicker select.ui-datepicker-month-year {width: 100%;}
-.ui-datepicker select.ui-datepicker-month, 
-.ui-datepicker select.ui-datepicker-year { width: 49%;}
-.ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; }
-.ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0;  }
-.ui-datepicker td { border: 0; padding: 1px; }
-.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; }
-.ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; }
-.ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; }
-.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; }
+.ui-datepicker {
+    width: 17em;
+    padding: .2em .2em 0;
+    display: none;
+}
+
+.ui-datepicker .ui-datepicker-header {
+    position: relative;
+    padding: .2em 0;
+}
+
+.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next {
+    position: absolute;
+    top: 2px;
+    width: 1.8em;
+    height: 1.8em;
+}
+
+.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover {
+    top: 1px;
+}
+
+.ui-datepicker .ui-datepicker-prev {
+    left: 2px;
+}
+
+.ui-datepicker .ui-datepicker-next {
+    right: 2px;
+}
+
+.ui-datepicker .ui-datepicker-prev-hover {
+    left: 1px;
+}
+
+.ui-datepicker .ui-datepicker-next-hover {
+    right: 1px;
+}
+
+.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span {
+    display: block;
+    position: absolute;
+    left: 50%;
+    margin-left: -8px;
+    top: 50%;
+    margin-top: -8px;
+}
+
+.ui-datepicker .ui-datepicker-title {
+    margin: 0 2.3em;
+    line-height: 1.8em;
+    text-align: center;
+}
+
+.ui-datepicker .ui-datepicker-title select {
+    font-size: 1em;
+    margin: 1px 0;
+}
+
+.ui-datepicker select.ui-datepicker-month-year {
+    width: 100%;
+}
+
+.ui-datepicker select.ui-datepicker-month,
+.ui-datepicker select.ui-datepicker-year {
+    width: 49%;
+}
+
+.ui-datepicker table {
+    width: 100%;
+    font-size: .9em;
+    border-collapse: collapse;
+    margin: 0 0 .4em;
+}
+
+.ui-datepicker th {
+    padding: .7em .3em;
+    text-align: center;
+    font-weight: bold;
+    border: 0;
+}
+
+.ui-datepicker td {
+    border: 0;
+    padding: 1px;
+}
+
+.ui-datepicker td span, .ui-datepicker td a {
+    display: block;
+    padding: .2em;
+    text-align: right;
+    text-decoration: none;
+}
+
+.ui-datepicker .ui-datepicker-buttonpane {
+    background-image: none;
+    margin: .7em 0 0 0;
+    padding: 0 .2em;
+    border-left: 0;
+    border-right: 0;
+    border-bottom: 0;
+}
+
+.ui-datepicker .ui-datepicker-buttonpane button {
+    float: right;
+    margin: .5em .2em .4em;
+    cursor: pointer;
+    padding: .2em .6em .3em .6em;
+    width: auto;
+    overflow: visible;
+}
+
+.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current {
+    float: left;
+}
 
 /* with multiple calendars */
-.ui-datepicker.ui-datepicker-multi { width:auto; }
-.ui-datepicker-multi .ui-datepicker-group { float:left; }
-.ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; }
-.ui-datepicker-multi-2 .ui-datepicker-group { width:50%; }
-.ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; }
-.ui-datepicker-multi-4 .ui-datepicker-group { width:25%; }
-.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; }
-.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; }
-.ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; }
-.ui-datepicker-row-break { clear:both; width:100%; font-size:0em; }
+.ui-datepicker.ui-datepicker-multi {
+    width: auto;
+}
+
+.ui-datepicker-multi .ui-datepicker-group {
+    float: left;
+}
+
+.ui-datepicker-multi .ui-datepicker-group table {
+    width: 95%;
+    margin: 0 auto .4em;
+}
+
+.ui-datepicker-multi-2 .ui-datepicker-group {
+    width: 50%;
+}
+
+.ui-datepicker-multi-3 .ui-datepicker-group {
+    width: 33.3%;
+}
+
+.ui-datepicker-multi-4 .ui-datepicker-group {
+    width: 25%;
+}
+
+.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header {
+    border-left-width: 0;
+}
+
+.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header {
+    border-left-width: 0;
+}
+
+.ui-datepicker-multi .ui-datepicker-buttonpane {
+    clear: left;
+}
+
+.ui-datepicker-row-break {
+    clear: both;
+    width: 100%;
+    font-size: 0em;
+}
 
 /* RTL support */
-.ui-datepicker-rtl { direction: rtl; }
-.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; }
-.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; }
-.ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; }
-.ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; }
-.ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; }
-.ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; }
-.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; }
-.ui-datepicker-rtl .ui-datepicker-group { float:right; }
-.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
-.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
+.ui-datepicker-rtl {
+    direction: rtl;
+}
+
+.ui-datepicker-rtl .ui-datepicker-prev {
+    right: 2px;
+    left: auto;
+}
+
+.ui-datepicker-rtl .ui-datepicker-next {
+    left: 2px;
+    right: auto;
+}
+
+.ui-datepicker-rtl .ui-datepicker-prev:hover {
+    right: 1px;
+    left: auto;
+}
+
+.ui-datepicker-rtl .ui-datepicker-next:hover {
+    left: 1px;
+    right: auto;
+}
+
+.ui-datepicker-rtl .ui-datepicker-buttonpane {
+    clear: right;
+}
+
+.ui-datepicker-rtl .ui-datepicker-buttonpane button {
+    float: left;
+}
+
+.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current {
+    float: right;
+}
+
+.ui-datepicker-rtl .ui-datepicker-group {
+    float: right;
+}
+
+.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header {
+    border-right-width: 0;
+    border-left-width: 1px;
+}
+
+.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header {
+    border-right-width: 0;
+    border-left-width: 1px;
+}
 
 /* IE6 IFRAME FIX (taken from datepicker 1.5.3 */
 .ui-datepicker-cover {
     display: none; /*sorry for IE5*/
-    display/**/: block; /*sorry for IE5*/
+    display /**/: block; /*sorry for IE5*/
     position: absolute; /*must have*/
     z-index: -1; /*must have*/
     filter: mask(); /*must have*/
diff --git a/media/css/lib/ui.jqgrid.css b/media/css/lib/ui.jqgrid.css
index 35f2e5a..48c90c1 100644
--- a/media/css/lib/ui.jqgrid.css
+++ b/media/css/lib/ui.jqgrid.css
@@ -1,144 +1,779 @@
 /*Grid*/
-.ui-jqgrid {position: relative;}
-.ui-jqgrid .ui-jqgrid-view {position: relative;left:0px; top: 0px; padding: .0em; font-size:11px;}
+.ui-jqgrid {
+    position: relative;
+}
+
+.ui-jqgrid .ui-jqgrid-view {
+    position: relative;
+    left: 0px;
+    top: 0px;
+    padding: .0em;
+    font-size: 11px;
+}
+
 /* caption*/
-.ui-jqgrid .ui-jqgrid-titlebar {padding: .3em .2em .2em .3em; position: relative; border-left: 0px none;border-right: 0px none; border-top: 0px none;}
-.ui-jqgrid .ui-jqgrid-title { float: left; margin: .1em 0 .2em; }
-.ui-jqgrid .ui-jqgrid-titlebar-close { position: absolute;top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height:18px;}.ui-jqgrid .ui-jqgrid-titlebar-close span { display: block; margin: 1px; }
-.ui-jqgrid .ui-jqgrid-titlebar-close:hover { padding: 0; }
+.ui-jqgrid .ui-jqgrid-titlebar {
+    padding: .3em .2em .2em .3em;
+    position: relative;
+    border-left: 0px none;
+    border-right: 0px none;
+    border-top: 0px none;
+}
+
+.ui-jqgrid .ui-jqgrid-title {
+    float: left;
+    margin: .1em 0 .2em;
+}
+
+.ui-jqgrid .ui-jqgrid-titlebar-close {
+    position: absolute;
+    top: 50%;
+    width: 19px;
+    margin: -10px 0 0 0;
+    padding: 1px;
+    height: 18px;
+}
+
+.ui-jqgrid .ui-jqgrid-titlebar-close span {
+    display: block;
+    margin: 1px;
+}
+
+.ui-jqgrid .ui-jqgrid-titlebar-close:hover {
+    padding: 0;
+}
+
 /* header*/
-.ui-jqgrid .ui-jqgrid-hdiv {position: relative; margin: 0em;padding: 0em; overflow-x: hidden; border-left: 0px none !important; border-top : 0px none !important; border-right : 0px none !important;}
-.ui-jqgrid .ui-jqgrid-hbox {float: left; padding-right: 20px;}
-.ui-jqgrid .ui-jqgrid-htable {table-layout:fixed;margin:0em;}
-.ui-jqgrid .ui-jqgrid-htable th {height:22px;padding: 0 2px 0 2px;}
-.ui-jqgrid .ui-jqgrid-htable th div {overflow: hidden; position:relative; height:17px;}
-.ui-th-column, .ui-jqgrid .ui-jqgrid-htable th.ui-th-column {overflow: hidden;white-space: nowrap;text-align:center;border-top : 0px none;border-bottom : 0px none;}
-.ui-th-ltr, .ui-jqgrid .ui-jqgrid-htable th.ui-th-ltr {border-left : 0px none;}
-.ui-th-rtl, .ui-jqgrid .ui-jqgrid-htable th.ui-th-rtl {border-right : 0px none;}
-.ui-first-th-ltr {border-right: 1px solid; }
-.ui-first-th-rtl {border-left: 1px solid; }
-.ui-jqgrid .ui-th-div-ie {white-space: nowrap; zoom :1; height:17px;}
-.ui-jqgrid .ui-jqgrid-resize {height:20px !important;position: relative; cursor :e-resize;display: inline;overflow: hidden;}
-.ui-jqgrid .ui-grid-ico-sort {overflow:hidden;position:absolute;display:inline; cursor: pointer !important;}
-.ui-jqgrid .ui-icon-asc {margin-top:-3px; height:12px;}
-.ui-jqgrid .ui-icon-desc {margin-top:3px;height:12px;}
-.ui-jqgrid .ui-i-asc {margin-top:0px;height:16px;}
-.ui-jqgrid .ui-i-desc {margin-top:0px;margin-left:13px;height:16px;}
-.ui-jqgrid .ui-jqgrid-sortable {cursor:pointer;}
-.ui-jqgrid tr.ui-search-toolbar th { border-top-width: 1px !important; border-top-color: inherit !important; border-top-style: ridge !important }
-tr.ui-search-toolbar input {margin: 1px 0px 0px 0px}
-tr.ui-search-toolbar select {margin: 1px 0px 0px 0px}
-/* body */ 
-.ui-jqgrid .ui-jqgrid-bdiv {position: relative; margin: 0em; padding:0; overflow: auto; text-align:left;}
-.ui-jqgrid .ui-jqgrid-btable {table-layout:fixed; margin:0em; outline-style: none; }
-.ui-jqgrid tr.jqgrow { outline-style: none; }
-.ui-jqgrid tr.jqgroup { outline-style: none; }
-.ui-jqgrid tr.jqgrow td {font-weight: normal; overflow: hidden; white-space: pre; height: 22px;padding: 0 2px 0 2px;border-bottom-width: 1px; border-bottom-color: inherit; border-bottom-style: solid;}
-.ui-jqgrid tr.jqgfirstrow td {padding: 0 2px 0 2px;border-right-width: 1px; border-right-style: solid;}
-.ui-jqgrid tr.jqgroup td {font-weight: normal; overflow: hidden; white-space: pre; height: 22px;padding: 0 2px 0 2px;border-bottom-width: 1px; border-bottom-color: inherit; border-bottom-style: solid;}
-.ui-jqgrid tr.jqfoot td {font-weight: bold; overflow: hidden; white-space: pre; height: 22px;padding: 0 2px 0 2px;border-bottom-width: 1px; border-bottom-color: inherit; border-bottom-style: solid;}
-.ui-jqgrid tr.ui-row-ltr td {text-align:left;border-right-width: 1px; border-right-color: inherit; border-right-style: solid;}
-.ui-jqgrid tr.ui-row-rtl td {text-align:right;border-left-width: 1px; border-left-color: inherit; border-left-style: solid;}
-.ui-jqgrid td.jqgrid-rownum { padding: 0 2px 0 2px; margin: 0px; border: 0px none;}
-.ui-jqgrid .ui-jqgrid-resize-mark { width:2px; left:0; background-color:#777; cursor: e-resize; cursor: col-resize; position:absolute; top:0; height:100px; overflow:hidden; display:none; border:0 none; z-index: 99999;}
+.ui-jqgrid .ui-jqgrid-hdiv {
+    position: relative;
+    margin: 0em;
+    padding: 0em;
+    overflow-x: hidden;
+    border-left: 0px none !important;
+    border-top: 0px none !important;
+    border-right: 0px none !important;
+}
+
+.ui-jqgrid .ui-jqgrid-hbox {
+    float: left;
+    padding-right: 20px;
+}
+
+.ui-jqgrid .ui-jqgrid-htable {
+    table-layout: fixed;
+    margin: 0em;
+}
+
+.ui-jqgrid .ui-jqgrid-htable th {
+    height: 22px;
+    padding: 0 2px 0 2px;
+}
+
+.ui-jqgrid .ui-jqgrid-htable th div {
+    overflow: hidden;
+    position: relative;
+    height: 17px;
+}
+
+.ui-th-column, .ui-jqgrid .ui-jqgrid-htable th.ui-th-column {
+    overflow: hidden;
+    white-space: nowrap;
+    text-align: center;
+    border-top: 0px none;
+    border-bottom: 0px none;
+}
+
+.ui-th-ltr, .ui-jqgrid .ui-jqgrid-htable th.ui-th-ltr {
+    border-left: 0px none;
+}
+
+.ui-th-rtl, .ui-jqgrid .ui-jqgrid-htable th.ui-th-rtl {
+    border-right: 0px none;
+}
+
+.ui-first-th-ltr {
+    border-right: 1px solid;
+}
+
+.ui-first-th-rtl {
+    border-left: 1px solid;
+}
+
+.ui-jqgrid .ui-th-div-ie {
+    white-space: nowrap;
+    zoom: 1;
+    height: 17px;
+}
+
+.ui-jqgrid .ui-jqgrid-resize {
+    height: 20px !important;
+    position: relative;
+    cursor: e-resize;
+    display: inline;
+    overflow: hidden;
+}
+
+.ui-jqgrid .ui-grid-ico-sort {
+    overflow: hidden;
+    position: absolute;
+    display: inline;
+    cursor: pointer !important;
+}
+
+.ui-jqgrid .ui-icon-asc {
+    margin-top: -3px;
+    height: 12px;
+}
+
+.ui-jqgrid .ui-icon-desc {
+    margin-top: 3px;
+    height: 12px;
+}
+
+.ui-jqgrid .ui-i-asc {
+    margin-top: 0px;
+    height: 16px;
+}
+
+.ui-jqgrid .ui-i-desc {
+    margin-top: 0px;
+    margin-left: 13px;
+    height: 16px;
+}
+
+.ui-jqgrid .ui-jqgrid-sortable {
+    cursor: pointer;
+}
+
+.ui-jqgrid tr.ui-search-toolbar th {
+    border-top-width: 1px !important;
+    border-top-color: inherit !important;
+    border-top-style: ridge !important
+}
+
+tr.ui-search-toolbar input {
+    margin: 1px 0px 0px 0px
+}
+
+tr.ui-search-toolbar select {
+    margin: 1px 0px 0px 0px
+}
+
+/* body */
+.ui-jqgrid .ui-jqgrid-bdiv {
+    position: relative;
+    margin: 0em;
+    padding: 0;
+    overflow: auto;
+    text-align: left;
+}
+
+.ui-jqgrid .ui-jqgrid-btable {
+    table-layout: fixed;
+    margin: 0em;
+    outline-style: none;
+}
+
+.ui-jqgrid tr.jqgrow {
+    outline-style: none;
+}
+
+.ui-jqgrid tr.jqgroup {
+    outline-style: none;
+}
+
+.ui-jqgrid tr.jqgrow td {
+    font-weight: normal;
+    overflow: hidden;
+    white-space: pre;
+    height: 22px;
+    padding: 0 2px 0 2px;
+    border-bottom-width: 1px;
+    border-bottom-color: inherit;
+    border-bottom-style: solid;
+}
+
+.ui-jqgrid tr.jqgfirstrow td {
+    padding: 0 2px 0 2px;
+    border-right-width: 1px;
+    border-right-style: solid;
+}
+
+.ui-jqgrid tr.jqgroup td {
+    font-weight: normal;
+    overflow: hidden;
+    white-space: pre;
+    height: 22px;
+    padding: 0 2px 0 2px;
+    border-bottom-width: 1px;
+    border-bottom-color: inherit;
+    border-bottom-style: solid;
+}
+
+.ui-jqgrid tr.jqfoot td {
+    font-weight: bold;
+    overflow: hidden;
+    white-space: pre;
+    height: 22px;
+    padding: 0 2px 0 2px;
+    border-bottom-width: 1px;
+    border-bottom-color: inherit;
+    border-bottom-style: solid;
+}
+
+.ui-jqgrid tr.ui-row-ltr td {
+    text-align: left;
+    border-right-width: 1px;
+    border-right-color: inherit;
+    border-right-style: solid;
+}
+
+.ui-jqgrid tr.ui-row-rtl td {
+    text-align: right;
+    border-left-width: 1px;
+    border-left-color: inherit;
+    border-left-style: solid;
+}
+
+.ui-jqgrid td.jqgrid-rownum {
+    padding: 0 2px 0 2px;
+    margin: 0px;
+    border: 0px none;
+}
+
+.ui-jqgrid .ui-jqgrid-resize-mark {
+    width: 2px;
+    left: 0;
+    background-color: #777;
+    cursor: e-resize;
+    cursor: col-resize;
+    position: absolute;
+    top: 0;
+    height: 100px;
+    overflow: hidden;
+    display: none;
+    border: 0 none;
+    z-index: 99999;
+}
+
 /* footer */
-.ui-jqgrid .ui-jqgrid-sdiv {position: relative; margin: 0em;padding: 0em; overflow: hidden; border-left: 0px none !important; border-top : 0px none !important; border-right : 0px none !important;}
-.ui-jqgrid .ui-jqgrid-ftable {table-layout:fixed; margin-bottom:0em;}
-.ui-jqgrid tr.footrow td {font-weight: bold; overflow: hidden; white-space:nowrap; height: 21px;padding: 0 2px 0 2px;border-top-width: 1px; border-top-color: inherit; border-top-style: solid;}
-.ui-jqgrid tr.footrow-ltr td {text-align:left;border-right-width: 1px; border-right-color: inherit; border-right-style: solid;}
-.ui-jqgrid tr.footrow-rtl td {text-align:right;border-left-width: 1px; border-left-color: inherit; border-left-style: solid;}
+.ui-jqgrid .ui-jqgrid-sdiv {
+    position: relative;
+    margin: 0em;
+    padding: 0em;
+    overflow: hidden;
+    border-left: 0px none !important;
+    border-top: 0px none !important;
+    border-right: 0px none !important;
+}
+
+.ui-jqgrid .ui-jqgrid-ftable {
+    table-layout: fixed;
+    margin-bottom: 0em;
+}
+
+.ui-jqgrid tr.footrow td {
+    font-weight: bold;
+    overflow: hidden;
+    white-space: nowrap;
+    height: 21px;
+    padding: 0 2px 0 2px;
+    border-top-width: 1px;
+    border-top-color: inherit;
+    border-top-style: solid;
+}
+
+.ui-jqgrid tr.footrow-ltr td {
+    text-align: left;
+    border-right-width: 1px;
+    border-right-color: inherit;
+    border-right-style: solid;
+}
+
+.ui-jqgrid tr.footrow-rtl td {
+    text-align: right;
+    border-left-width: 1px;
+    border-left-color: inherit;
+    border-left-style: solid;
+}
+
 /* Pager*/
-.ui-jqgrid .ui-jqgrid-pager { border-left: 0px none !important;border-right: 0px none !important; border-bottom: 0px none !important; margin: 0px !important; padding: 0px !important; position: relative; height: 25px;white-space: nowrap;overflow: hidden;font-size:11px;}
-.ui-jqgrid .ui-pager-control {position: relative;}
-.ui-jqgrid .ui-pg-table {position: relative; padding-bottom:2px; width:auto; margin: 0em;}
-.ui-jqgrid .ui-pg-table td {font-weight:normal; vertical-align:middle; padding:1px;}
-.ui-jqgrid .ui-pg-button  { height:19px !important;}
-.ui-jqgrid .ui-pg-button span { display: block; margin: 1px; float:left;}
-.ui-jqgrid .ui-pg-button:hover { padding: 0px; }
-.ui-jqgrid .ui-state-disabled:hover {padding:1px;}
-.ui-jqgrid .ui-pg-input { height:13px;font-size:.8em; margin: 0em;}
-.ui-jqgrid .ui-pg-selbox {font-size:.8em; line-height:18px; display:block; height:18px; margin: 0em;}
-.ui-jqgrid .ui-separator {height: 18px; border-left: 1px solid #ccc ; border-right: 1px solid #ccc ; margin: 1px; float: right;}
-.ui-jqgrid .ui-paging-info {font-weight: normal;height:19px; margin-top:3px;margin-right:4px;}
-.ui-jqgrid .ui-jqgrid-pager .ui-pg-div {padding:1px 0;float:left;position:relative;}
-.ui-jqgrid .ui-jqgrid-pager .ui-pg-button { cursor:pointer; }
-.ui-jqgrid .ui-jqgrid-pager .ui-pg-div  span.ui-icon {float:left;margin:0 2px;}
-.ui-jqgrid td input, .ui-jqgrid td select .ui-jqgrid td textarea { margin: 0em;}
-.ui-jqgrid td textarea {width:auto;height:auto;}
-.ui-jqgrid .ui-jqgrid-toppager {border-left: 0px none !important;border-right: 0px none !important; border-top: 0px none !important; margin: 0px !important; padding: 0px !important; position: relative; height: 25px !important;white-space: nowrap;overflow: hidden;}
-.ui-jqgrid .ui-jqgrid-toppager .ui-pg-div {padding:1px 0;float:left;position:relative;}
-.ui-jqgrid .ui-jqgrid-toppager .ui-pg-button { cursor:pointer; }
-.ui-jqgrid .ui-jqgrid-toppager .ui-pg-div  span.ui-icon {float:left;margin:0 2px;}
+.ui-jqgrid .ui-jqgrid-pager {
+    border-left: 0px none !important;
+    border-right: 0px none !important;
+    border-bottom: 0px none !important;
+    margin: 0px !important;
+    padding: 0px !important;
+    position: relative;
+    height: 25px;
+    white-space: nowrap;
+    overflow: hidden;
+    font-size: 11px;
+}
+
+.ui-jqgrid .ui-pager-control {
+    position: relative;
+}
+
+.ui-jqgrid .ui-pg-table {
+    position: relative;
+    padding-bottom: 2px;
+    width: auto;
+    margin: 0em;
+}
+
+.ui-jqgrid .ui-pg-table td {
+    font-weight: normal;
+    vertical-align: middle;
+    padding: 1px;
+}
+
+.ui-jqgrid .ui-pg-button {
+    height: 19px !important;
+}
+
+.ui-jqgrid .ui-pg-button span {
+    display: block;
+    margin: 1px;
+    float: left;
+}
+
+.ui-jqgrid .ui-pg-button:hover {
+    padding: 0px;
+}
+
+.ui-jqgrid .ui-state-disabled:hover {
+    padding: 1px;
+}
+
+.ui-jqgrid .ui-pg-input {
+    height: 13px;
+    font-size: .8em;
+    margin: 0em;
+}
+
+.ui-jqgrid .ui-pg-selbox {
+    font-size: .8em;
+    line-height: 18px;
+    display: block;
+    height: 18px;
+    margin: 0em;
+}
+
+.ui-jqgrid .ui-separator {
+    height: 18px;
+    border-left: 1px solid #ccc;
+    border-right: 1px solid #ccc;
+    margin: 1px;
+    float: right;
+}
+
+.ui-jqgrid .ui-paging-info {
+    font-weight: normal;
+    height: 19px;
+    margin-top: 3px;
+    margin-right: 4px;
+}
+
+.ui-jqgrid .ui-jqgrid-pager .ui-pg-div {
+    padding: 1px 0;
+    float: left;
+    position: relative;
+}
+
+.ui-jqgrid .ui-jqgrid-pager .ui-pg-button {
+    cursor: pointer;
+}
+
+.ui-jqgrid .ui-jqgrid-pager .ui-pg-div  span.ui-icon {
+    float: left;
+    margin: 0 2px;
+}
+
+.ui-jqgrid td input, .ui-jqgrid td select .ui-jqgrid td textarea {
+    margin: 0em;
+}
+
+.ui-jqgrid td textarea {
+    width: auto;
+    height: auto;
+}
+
+.ui-jqgrid .ui-jqgrid-toppager {
+    border-left: 0px none !important;
+    border-right: 0px none !important;
+    border-top: 0px none !important;
+    margin: 0px !important;
+    padding: 0px !important;
+    position: relative;
+    height: 25px !important;
+    white-space: nowrap;
+    overflow: hidden;
+}
+
+.ui-jqgrid .ui-jqgrid-toppager .ui-pg-div {
+    padding: 1px 0;
+    float: left;
+    position: relative;
+}
+
+.ui-jqgrid .ui-jqgrid-toppager .ui-pg-button {
+    cursor: pointer;
+}
+
+.ui-jqgrid .ui-jqgrid-toppager .ui-pg-div  span.ui-icon {
+    float: left;
+    margin: 0 2px;
+}
+
 /*subgrid*/
-.ui-jqgrid .ui-jqgrid-btable .ui-sgcollapsed span {display: block;}
-.ui-jqgrid .ui-subgrid {margin:0em;padding:0em; width:100%;}
-.ui-jqgrid .ui-subgrid table {table-layout: fixed;}
-.ui-jqgrid .ui-subgrid tr.ui-subtblcell td {height:18px;border-right-width: 1px; border-right-color: inherit; border-right-style: solid;border-bottom-width: 1px; border-bottom-color: inherit; border-bottom-style: solid;}
-.ui-jqgrid .ui-subgrid td.subgrid-data {border-top:  0px none !important;}
-.ui-jqgrid .ui-subgrid td.subgrid-cell {border-width: 0px 0px 1px 0px;}
-.ui-jqgrid .ui-th-subgrid {height:20px;}
+.ui-jqgrid .ui-jqgrid-btable .ui-sgcollapsed span {
+    display: block;
+}
+
+.ui-jqgrid .ui-subgrid {
+    margin: 0em;
+    padding: 0em;
+    width: 100%;
+}
+
+.ui-jqgrid .ui-subgrid table {
+    table-layout: fixed;
+}
+
+.ui-jqgrid .ui-subgrid tr.ui-subtblcell td {
+    height: 18px;
+    border-right-width: 1px;
+    border-right-color: inherit;
+    border-right-style: solid;
+    border-bottom-width: 1px;
+    border-bottom-color: inherit;
+    border-bottom-style: solid;
+}
+
+.ui-jqgrid .ui-subgrid td.subgrid-data {
+    border-top: 0px none !important;
+}
+
+.ui-jqgrid .ui-subgrid td.subgrid-cell {
+    border-width: 0px 0px 1px 0px;
+}
+
+.ui-jqgrid .ui-th-subgrid {
+    height: 20px;
+}
+
 /* loading */
-.ui-jqgrid .loading {position: absolute; top: 45%;left: 45%;width: auto;z-index:101;padding: 6px; margin: 5px;text-align: center;font-weight: bold;display: none;border-width: 2px !important; font-size:11px;}
-.ui-jqgrid .jqgrid-overlay {display:none;z-index:100;}
-* html .jqgrid-overlay {width: expression(this.parentNode.offsetWidth+'px');height: expression(this.parentNode.offsetHeight+'px');}
-* .jqgrid-overlay iframe {position:absolute;top:0;left:0;z-index:-1;width: expression(this.parentNode.offsetWidth+'px');height: expression(this.parentNode.offsetHeight+'px');}
+.ui-jqgrid .loading {
+    position: absolute;
+    top: 45%;
+    left: 45%;
+    width: auto;
+    z-index: 101;
+    padding: 6px;
+    margin: 5px;
+    text-align: center;
+    font-weight: bold;
+    display: none;
+    border-width: 2px !important;
+    font-size: 11px;
+}
+
+.ui-jqgrid .jqgrid-overlay {
+    display: none;
+    z-index: 100;
+}
+
+* html .jqgrid-overlay {
+    width: expression(this.parentNode.offsetWidth+'px');
+    height: expression(this.parentNode.offsetHeight+'px');
+}
+
+* .jqgrid-overlay iframe {
+    position: absolute;
+    top: 0;
+    left: 0;
+    z-index: -1;
+    width: expression(this.parentNode.offsetWidth+'px');
+    height: expression(this.parentNode.offsetHeight+'px');
+}
+
 /* end loading div */
 /* toolbar */
-.ui-jqgrid .ui-userdata {border-left: 0px none;	border-right: 0px none;	height : 21px;overflow: hidden;	}
+.ui-jqgrid .ui-userdata {
+    border-left: 0px none;
+    border-right: 0px none;
+    height: 21px;
+    overflow: hidden;
+}
+
 /*Modal Window */
-.ui-jqdialog { display: none; width: 300px; position: absolute; padding: .2em; font-size:11px; overflow:visible;}
-.ui-jqdialog .ui-jqdialog-titlebar { padding: .3em .2em; position: relative;  }
-.ui-jqdialog .ui-jqdialog-title { margin: .1em 0 .2em; } 
-.ui-jqdialog .ui-jqdialog-titlebar-close { position: absolute;  top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; }
-
-.ui-jqdialog .ui-jqdialog-titlebar-close span { display: block; margin: 1px; }
-.ui-jqdialog .ui-jqdialog-titlebar-close:hover, .ui-jqdialog .ui-jqdialog-titlebar-close:focus { padding: 0; }
-.ui-jqdialog-content, .ui-jqdialog .ui-jqdialog-content { border: 0; padding: .3em .2em; background: none; height:auto;}
-.ui-jqdialog .ui-jqconfirm {padding: .4em 1em; border-width:3px;position:absolute;bottom:10px;right:10px;overflow:visible;display:none;height:80px;width:220px;text-align:center;}
+.ui-jqdialog {
+    display: none;
+    width: 300px;
+    position: absolute;
+    padding: .2em;
+    font-size: 11px;
+    overflow: visible;
+}
+
+.ui-jqdialog .ui-jqdialog-titlebar {
+    padding: .3em .2em;
+    position: relative;
+}
+
+.ui-jqdialog .ui-jqdialog-title {
+    margin: .1em 0 .2em;
+}
+
+.ui-jqdialog .ui-jqdialog-titlebar-close {
+    position: absolute;
+    top: 50%;
+    width: 19px;
+    margin: -10px 0 0 0;
+    padding: 1px;
+    height: 18px;
+}
+
+.ui-jqdialog .ui-jqdialog-titlebar-close span {
+    display: block;
+    margin: 1px;
+}
+
+.ui-jqdialog .ui-jqdialog-titlebar-close:hover, .ui-jqdialog .ui-jqdialog-titlebar-close:focus {
+    padding: 0;
+}
+
+.ui-jqdialog-content, .ui-jqdialog .ui-jqdialog-content {
+    border: 0;
+    padding: .3em .2em;
+    background: none;
+    height: auto;
+}
+
+.ui-jqdialog .ui-jqconfirm {
+    padding: .4em 1em;
+    border-width: 3px;
+    position: absolute;
+    bottom: 10px;
+    right: 10px;
+    overflow: visible;
+    display: none;
+    height: 80px;
+    width: 220px;
+    text-align: center;
+}
+
 /* end Modal window*/
 /* Form edit */
-.ui-jqdialog-content .FormGrid {margin: 0px;}
-.ui-jqdialog-content .EditTable { width: 100%; margin-bottom:0em;}
-.ui-jqdialog-content .DelTable { width: 100%; margin-bottom:0em;}
-.EditTable td input, .EditTable td select, .EditTable td textarea {margin: 0em;}
-.EditTable td textarea { width:auto; height:auto;}
-.ui-jqdialog-content td.EditButton {text-align: right;border-top: 0px none;border-left: 0px none;border-right: 0px none; padding-bottom:5px; padding-top:5px;}
-.ui-jqdialog-content td.navButton {text-align: center; border-left: 0px none;border-top: 0px none;border-right: 0px none; padding-bottom:5px; padding-top:5px;}
-.ui-jqdialog-content input.FormElement {padding:.3em}
-.ui-jqdialog-content .data-line {padding-top:.1em;border: 0px none;}
-
-.ui-jqdialog-content .CaptionTD {vertical-align: middle;border: 0px none; padding: 2px;white-space: nowrap;}
-.ui-jqdialog-content .DataTD {padding: 2px; border: 0px none; vertical-align: top;}
-.ui-jqdialog-content .form-view-data {white-space:pre}
-.fm-button { display: inline-block; margin:0 4px 0 0; padding: .4em .5em; text-decoration:none !important; cursor:pointer; position: relative; text-align: center; zoom: 1; }
-.fm-button-icon-left { padding-left: 1.9em; }
-.fm-button-icon-right { padding-right: 1.9em; }
-.fm-button-icon-left .ui-icon { right: auto; left: .2em; margin-left: 0; position: absolute; top: 50%; margin-top: -8px; }
-.fm-button-icon-right .ui-icon { left: auto; right: .2em; margin-left: 0; position: absolute; top: 50%; margin-top: -8px;}
-#nData, #pData { float: left; margin:3px;padding: 0; width: 15px; }
+.ui-jqdialog-content .FormGrid {
+    margin: 0px;
+}
+
+.ui-jqdialog-content .EditTable {
+    width: 100%;
+    margin-bottom: 0em;
+}
+
+.ui-jqdialog-content .DelTable {
+    width: 100%;
+    margin-bottom: 0em;
+}
+
+.EditTable td input, .EditTable td select, .EditTable td textarea {
+    margin: 0em;
+}
+
+.EditTable td textarea {
+    width: auto;
+    height: auto;
+}
+
+.ui-jqdialog-content td.EditButton {
+    text-align: right;
+    border-top: 0px none;
+    border-left: 0px none;
+    border-right: 0px none;
+    padding-bottom: 5px;
+    padding-top: 5px;
+}
+
+.ui-jqdialog-content td.navButton {
+    text-align: center;
+    border-left: 0px none;
+    border-top: 0px none;
+    border-right: 0px none;
+    padding-bottom: 5px;
+    padding-top: 5px;
+}
+
+.ui-jqdialog-content input.FormElement {
+    padding: .3em
+}
+
+.ui-jqdialog-content .data-line {
+    padding-top: .1em;
+    border: 0px none;
+}
+
+.ui-jqdialog-content .CaptionTD {
+    vertical-align: middle;
+    border: 0px none;
+    padding: 2px;
+    white-space: nowrap;
+}
+
+.ui-jqdialog-content .DataTD {
+    padding: 2px;
+    border: 0px none;
+    vertical-align: top;
+}
+
+.ui-jqdialog-content .form-view-data {
+    white-space: pre
+}
+
+.fm-button {
+    display: inline-block;
+    margin: 0 4px 0 0;
+    padding: .4em .5em;
+    text-decoration: none !important;
+    cursor: pointer;
+    position: relative;
+    text-align: center;
+    zoom: 1;
+}
+
+.fm-button-icon-left {
+    padding-left: 1.9em;
+}
+
+.fm-button-icon-right {
+    padding-right: 1.9em;
+}
+
+.fm-button-icon-left .ui-icon {
+    right: auto;
+    left: .2em;
+    margin-left: 0;
+    position: absolute;
+    top: 50%;
+    margin-top: -8px;
+}
+
+.fm-button-icon-right .ui-icon {
+    left: auto;
+    right: .2em;
+    margin-left: 0;
+    position: absolute;
+    top: 50%;
+    margin-top: -8px;
+}
+
+#nData, #pData {
+    float: left;
+    margin: 3px;
+    padding: 0;
+    width: 15px;
+}
+
 /* End Eorm edit */
 /*.ui-jqgrid .edit-cell {}*/
-.ui-jqgrid .selected-row, div.ui-jqgrid .selected-row td {font-style : normal;border-left: 0px none;}
+.ui-jqgrid .selected-row, div.ui-jqgrid .selected-row td {
+    font-style: normal;
+    border-left: 0px none;
+}
+
 /* inline edit actions button*/
 .ui-inline-del.ui-state-hover span, .ui-inline-edit.ui-state-hover span,
 .ui-inline-save.ui-state-hover span, .ui-inline-cancel.ui-state-hover span {
     margin: -1px;
 }
+
 /* Tree Grid */
-.ui-jqgrid .tree-wrap {float: left; position: relative;height: 18px;white-space: nowrap;overflow: hidden;}
-.ui-jqgrid .tree-minus {position: absolute; height: 18px; width: 18px; overflow: hidden;}
-.ui-jqgrid .tree-plus {position: absolute;	height: 18px; width: 18px;	overflow: hidden;}
-.ui-jqgrid .tree-leaf {position: absolute;	height: 18px; width: 18px;overflow: hidden;}
-.ui-jqgrid .treeclick {cursor: pointer;}
+.ui-jqgrid .tree-wrap {
+    float: left;
+    position: relative;
+    height: 18px;
+    white-space: nowrap;
+    overflow: hidden;
+}
+
+.ui-jqgrid .tree-minus {
+    position: absolute;
+    height: 18px;
+    width: 18px;
+    overflow: hidden;
+}
+
+.ui-jqgrid .tree-plus {
+    position: absolute;
+    height: 18px;
+    width: 18px;
+    overflow: hidden;
+}
+
+.ui-jqgrid .tree-leaf {
+    position: absolute;
+    height: 18px;
+    width: 18px;
+    overflow: hidden;
+}
+
+.ui-jqgrid .treeclick {
+    cursor: pointer;
+}
+
 /* moda dialog */
-* iframe.jqm {position:absolute;top:0;left:0;z-index:-1;width: expression(this.parentNode.offsetWidth+'px');height: expression(this.parentNode.offsetHeight+'px');}
-.ui-jqgrid-dnd tr td {border-right-width: 1px; border-right-color: inherit; border-right-style: solid; height:20px}
+* iframe.jqm {
+    position: absolute;
+    top: 0;
+    left: 0;
+    z-index: -1;
+    width: expression(this.parentNode.offsetWidth+'px');
+    height: expression(this.parentNode.offsetHeight+'px');
+}
+
+.ui-jqgrid-dnd tr td {
+    border-right-width: 1px;
+    border-right-color: inherit;
+    border-right-style: solid;
+    height: 20px
+}
+
 /* RTL Support */
-.ui-jqgrid .ui-jqgrid-title-rtl {float:right;margin: .1em 0 .2em; }
-.ui-jqgrid .ui-jqgrid-hbox-rtl {float: right; padding-left: 20px;}
-.ui-jqgrid .ui-jqgrid-resize-ltr {float: right;margin: -2px -2px -2px 0px;}
-.ui-jqgrid .ui-jqgrid-resize-rtl {float: left;margin: -2px 0px -1px -3px;}
-.ui-jqgrid .ui-sort-rtl {left:0px;}
-.ui-jqgrid .tree-wrap-ltr {float: left;}
-.ui-jqgrid .tree-wrap-rtl {float: right;}
-.ui-jqgrid .ui-ellipsis {text-overflow:ellipsis;}
+.ui-jqgrid .ui-jqgrid-title-rtl {
+    float: right;
+    margin: .1em 0 .2em;
+}
+
+.ui-jqgrid .ui-jqgrid-hbox-rtl {
+    float: right;
+    padding-left: 20px;
+}
+
+.ui-jqgrid .ui-jqgrid-resize-ltr {
+    float: right;
+    margin: -2px -2px -2px 0px;
+}
+
+.ui-jqgrid .ui-jqgrid-resize-rtl {
+    float: left;
+    margin: -2px 0px -1px -3px;
+}
+
+.ui-jqgrid .ui-sort-rtl {
+    left: 0px;
+}
+
+.ui-jqgrid .tree-wrap-ltr {
+    float: left;
+}
+
+.ui-jqgrid .tree-wrap-rtl {
+    float: right;
+}
+
+.ui-jqgrid .ui-ellipsis {
+    text-overflow: ellipsis;
+}
diff --git a/media/css/lib/ui.multiselect.css b/media/css/lib/ui.multiselect.css
index fe20cf7..5a4c6c8 100644
--- a/media/css/lib/ui.multiselect.css
+++ b/media/css/lib/ui.multiselect.css
@@ -1,30 +1,139 @@
 /* Multiselect
 ----------------------------------*/
 
-.ui-multiselect { border: solid 1px; font-size: 0.8em; }
-.ui-multiselect ul { -moz-user-select: none; }
-.ui-multiselect li { margin: 0; padding: 0; cursor: default; line-height: 20px; height: 20px; font-size: 11px; list-style: none; }
-.ui-multiselect li a { color: #999; text-decoration: none; padding: 0; display: block; float: left; cursor: pointer;}
-.ui-multiselect li.ui-draggable-dragging { padding-left: 10px; }
-
-.ui-multiselect div.selected { position: relative; padding: 0; margin: 0; border: 0; float:left; }
-.ui-multiselect ul.selected { position: relative; padding: 0; overflow: auto; overflow-x: hidden; background: #fff; margin: 0; list-style: none; border: 0; position: relative; width: 100%; }
-.ui-multiselect ul.selected li { }
-
-.ui-multiselect div.available { position: relative; padding: 0; margin: 0; border: 0; float:left; border-left: 1px solid; }
-.ui-multiselect ul.available { position: relative; padding: 0; overflow: auto; overflow-x: hidden; background: #fff; margin: 0; list-style: none; border: 0; width: 100%; }
-.ui-multiselect ul.available li { padding-left: 10px; }
- 
-.ui-multiselect .ui-state-default { border: none; margin-bottom: 1px; position: relative; padding-left: 20px;}
-.ui-multiselect .ui-state-hover { border: none; }
-.ui-multiselect .ui-widget-header {border: none; font-size: 11px; margin-bottom: 1px;}
- 
-.ui-multiselect .add-all { float: right; padding: 7px;}
-.ui-multiselect .remove-all { float: right; padding: 7px;}
-.ui-multiselect .search { float: left; padding: 4px;}
-.ui-multiselect .count { float: left; padding: 7px;}
-
-.ui-multiselect li span.ui-icon-arrowthick-2-n-s { position: absolute; left: 2px; }
-.ui-multiselect li a.action { position: absolute; right: 2px; top: 2px; }
- 
-.ui-multiselect input.search { height: 14px; padding: 1px; opacity: 0.5; margin: 4px; width: 100px; }
\ No newline at end of file
+.ui-multiselect {
+    border: solid 1px;
+    font-size: 0.8em;
+}
+
+.ui-multiselect ul {
+    -moz-user-select: none;
+}
+
+.ui-multiselect li {
+    margin: 0;
+    padding: 0;
+    cursor: default;
+    line-height: 20px;
+    height: 20px;
+    font-size: 11px;
+    list-style: none;
+}
+
+.ui-multiselect li a {
+    color: #999;
+    text-decoration: none;
+    padding: 0;
+    display: block;
+    float: left;
+    cursor: pointer;
+}
+
+.ui-multiselect li.ui-draggable-dragging {
+    padding-left: 10px;
+}
+
+.ui-multiselect div.selected {
+    position: relative;
+    padding: 0;
+    margin: 0;
+    border: 0;
+    float: left;
+}
+
+.ui-multiselect ul.selected {
+    position: relative;
+    padding: 0;
+    overflow: auto;
+    overflow-x: hidden;
+    background: #fff;
+    margin: 0;
+    list-style: none;
+    border: 0;
+    position: relative;
+    width: 100%;
+}
+
+.ui-multiselect ul.selected li {
+}
+
+.ui-multiselect div.available {
+    position: relative;
+    padding: 0;
+    margin: 0;
+    border: 0;
+    float: left;
+    border-left: 1px solid;
+}
+
+.ui-multiselect ul.available {
+    position: relative;
+    padding: 0;
+    overflow: auto;
+    overflow-x: hidden;
+    background: #fff;
+    margin: 0;
+    list-style: none;
+    border: 0;
+    width: 100%;
+}
+
+.ui-multiselect ul.available li {
+    padding-left: 10px;
+}
+
+.ui-multiselect .ui-state-default {
+    border: none;
+    margin-bottom: 1px;
+    position: relative;
+    padding-left: 20px;
+}
+
+.ui-multiselect .ui-state-hover {
+    border: none;
+}
+
+.ui-multiselect .ui-widget-header {
+    border: none;
+    font-size: 11px;
+    margin-bottom: 1px;
+}
+
+.ui-multiselect .add-all {
+    float: right;
+    padding: 7px;
+}
+
+.ui-multiselect .remove-all {
+    float: right;
+    padding: 7px;
+}
+
+.ui-multiselect .search {
+    float: left;
+    padding: 4px;
+}
+
+.ui-multiselect .count {
+    float: left;
+    padding: 7px;
+}
+
+.ui-multiselect li span.ui-icon-arrowthick-2-n-s {
+    position: absolute;
+    left: 2px;
+}
+
+.ui-multiselect li a.action {
+    position: absolute;
+    right: 2px;
+    top: 2px;
+}
+
+.ui-multiselect input.search {
+    height: 14px;
+    padding: 1px;
+    opacity: 0.5;
+    margin: 4px;
+    width: 100px;
+}
\ No newline at end of file
diff --git a/media/css/paginer.css b/media/css/paginer.css
index 9947738..b00de3b 100644
--- a/media/css/paginer.css
+++ b/media/css/paginer.css
@@ -1,40 +1,59 @@
 /* kompilowane ze źródła SASS */
 .paginer-links {
-  padding: 0.5em 0.75em;
-  font: normal 0.8em arial;
-  margin-bottom: 20px; }
-  .paginer-links .page_nr {
-    display: none; }
-  .paginer-links .link {
-    cursor: pointer; }
-  .paginer-links .disabled {
+    padding: 0.5em 0.75em;
+    font: normal 0.8em arial;
+    margin-bottom: 20px;
+}
+
+.paginer-links .page_nr {
+    display: none;
+}
+
+.paginer-links .link {
+    cursor: pointer;
+}
+
+.paginer-links .disabled {
     padding: 0.3em;
     border: 1px solid #cccccc;
     background-color: #e6e6ff;
     color: #aaaaaa;
-    font-weight: normal; }
-  .paginer-links a.prev, .paginer-links a.next {
+    font-weight: normal;
+}
+
+.paginer-links a.prev, .paginer-links a.next {
     color: #32324f !important;
     border: 1px solid #8282ce;
     background-color: #a9a9cd;
-    padding: 0.3em; }
-  .paginer-links .prev {
-    margin-right: 0.5em; }
-  .paginer-links .next {
-    margin-left: 0.5em; }
-  .paginer-links .page {
+    padding: 0.3em;
+}
+
+.paginer-links .prev {
+    margin-right: 0.5em;
+}
+
+.paginer-links .next {
+    margin-left: 0.5em;
+}
+
+.paginer-links .page {
     color: navy !important;
     border: 1px solid #8282ce;
     background-color: #a9a9cd;
     padding: 0.25em;
-    margin: 0em 0.25em; }
-  .paginer-links .current {
+    margin: 0em 0.25em;
+}
+
+.paginer-links .current {
     color: white !important;
     border: 1px solid #32324f;
     background-color: #32324f;
     font-weight: bold;
-    font-size: 1em; }
-  .paginer-links a:hover.link, .paginer-links a:hover.page {
+    font-size: 1em;
+}
+
+.paginer-links a:hover.link, .paginer-links a:hover.page {
     color: white !important;
     border: 1px solid #32324f;
-    background-color: #32324f; }
\ No newline at end of file
+    background-color: #32324f;
+}
\ No newline at end of file
diff --git a/media/css/pattern_view.css b/media/css/pattern_view.css
index 8b51612..d103a9d 100644
--- a/media/css/pattern_view.css
+++ b/media/css/pattern_view.css
@@ -1,3 +1,3 @@
 #ending-list p {
-  display: inline;
+    display: inline;
 }
diff --git a/media/js/base-layout.js b/media/js/base-layout.js
index 55bce69..2233e0f 100644
--- a/media/js/base-layout.js
+++ b/media/js/base-layout.js
@@ -1,58 +1,58 @@
 var layout = {};
 
 function adjust_grid_height() {
-  "use strict";
-  $('#scroll').jqGrid(
-    'setGridHeight',
-    $('#left').height() - 25 - $('#search-panel').height());
+    "use strict";
+    $('#scroll').jqGrid(
+        'setGridHeight',
+        $('#left').height() - 25 - $('#search-panel').height());
 }
 
 function adjust_grid_width() {
-  "use strict";
-  $('#scroll').jqGrid('setGridWidth', $('#left').width() - 2, true);
+    "use strict";
+    $('#scroll').jqGrid('setGridWidth', $('#left').width() - 2, true);
 }
 
 layout.adjust_grid_width = adjust_grid_width;
 
 function adjust_grid_size() {
-  "use strict";
-  adjust_grid_height();
-  adjust_grid_width();
+    "use strict";
+    adjust_grid_height();
+    adjust_grid_width();
 }
 
 function adjust_tabs() {
-  "use strict";
-  var right = $('#right');
-  var height = right.height() - right.find('.ui-tabs-nav').height() - 35;
-  right.find('.ui-tabs-panel').height(height);
-  right.width(
-    $('#content').width() - $('#left').width() - $('.vsplitbar').width());
+    "use strict";
+    var right = $('#right');
+    var height = right.height() - right.find('.ui-tabs-nav').height() - 35;
+    right.find('.ui-tabs-panel').height(height);
+    right.width(
+        $('#content').width() - $('#left').width() - $('.vsplitbar').width());
 }
 layout.adjust_tabs = adjust_tabs;
 
-$(function() {
-  "use strict";
-  var content = $('#content'), left = $('#left');
-  content.height($(window).height() - $('#main_menu').height());
-  $(window).resize(function() {
+$(function () {
+    "use strict";
+    var content = $('#content'), left = $('#left');
     content.height($(window).height() - $('#main_menu').height());
-    if ($.fn.jqGrid) {
-      adjust_grid_height();
-    }
-  });
-  if ($.fn.splitter) {
-    left.bind('resize', function(e) {
-      adjust_grid_size();
-      e.stopPropagation();
-    });
-    $('#right').bind('resize', function(e) {
-      adjust_tabs();
-      e.stopPropagation();
+    $(window).resize(function () {
+        content.height($(window).height() - $('#main_menu').height());
+        if ($.fn.jqGrid) {
+            adjust_grid_height();
+        }
     });
-    content.splitter({
-      type: "v",
-      minLeft: 200, sizeLeft: 390, minRight: 100,
-      resizeToWidth: true
-    });
-  }
+    if ($.fn.splitter) {
+        left.bind('resize', function (e) {
+            adjust_grid_size();
+            e.stopPropagation();
+        });
+        $('#right').bind('resize', function (e) {
+            adjust_tabs();
+            e.stopPropagation();
+        });
+        content.splitter({
+            type: "v",
+            minLeft: 200, sizeLeft: 390, minRight: 100,
+            resizeToWidth: true
+        });
+    }
 });
diff --git a/media/js/common.js b/media/js/common.js
index 382dfa3..815b6bf 100644
--- a/media/js/common.js
+++ b/media/js/common.js
@@ -2,393 +2,399 @@ var hash_interpreted = false;
 
 var common = {};
 
-$(function(){
-  "use strict";
-  var tabs = $('.tabs');
-  tabs.tabs({
-    show: function() {
-      if (hash_interpreted)
-        update_hash();
-    }
-  });
-  $('button').button();
-  $('input.datepicker').datepicker($.datepicker.regional.pl);
-  $(document).on('mouseover', '.ui-state-default', function() {
-    $(this).addClass('ui-state-hover');
-  });
-  $(document).on('mouseout', '.ui-state-default', function() {
-    $(this).removeClass('ui-state-hover');
-  });
-  if ($dj.paginer || tabs.length > 0) {
-    $(window).bind('hashchange', function() {
-      var hash = location.hash.substr(1);
-      interpret_hash(hash);
-      hash_interpreted = true;
+$(function () {
+    "use strict";
+    var tabs = $('.tabs');
+    tabs.tabs({
+        show: function () {
+            if (hash_interpreted)
+                update_hash();
+        }
+    });
+    $('button').button();
+    $('input.datepicker').datepicker($.datepicker.regional.pl);
+    $(document).on('mouseover', '.ui-state-default', function () {
+        $(this).addClass('ui-state-hover');
     });
-    if (!$dj.paginer)
-      $(window).trigger('hashchange');
-  }
+    $(document).on('mouseout', '.ui-state-default', function () {
+        $(this).removeClass('ui-state-hover');
+    });
+    if ($dj.paginer || tabs.length > 0) {
+        $(window).bind('hashchange', function () {
+            var hash = location.hash.substr(1);
+            interpret_hash(hash);
+            hash_interpreted = true;
+        });
+        if (!$dj.paginer)
+            $(window).trigger('hashchange');
+    }
 });
 
-$.fn.disable = function() {
-  "use strict";
-  return this.prop('disabled', true);
+$.fn.disable = function () {
+    "use strict";
+    return this.prop('disabled', true);
 };
 
-$.fn.enable = function() {
-  "use strict";
-  return this.prop('disabled', false);
+$.fn.enable = function () {
+    "use strict";
+    return this.prop('disabled', false);
 };
 
-$.fn.value = function() {
-  "use strict";
-  if (this.is(':checkbox'))
-    return this.prop('checked');
-  else if (this.is(':radio'))
-    return this.prop('checked')? this.val() : null;
-  else
-    return this.val();
+$.fn.value = function () {
+    "use strict";
+    if (this.is(':checkbox'))
+        return this.prop('checked');
+    else if (this.is(':radio'))
+        return this.prop('checked') ? this.val() : null;
+    else
+        return this.val();
 };
 
-$.fn.bind_hover = function(c) {
-  "use strict";
-  var elem = this;
-  this.hover(
-    function() {elem.addClass(c);},
-    function() {elem.removeClass(c);}
-  );
+$.fn.bind_hover = function (c) {
+    "use strict";
+    var elem = this;
+    this.hover(
+        function () {
+            elem.addClass(c);
+        },
+        function () {
+            elem.removeClass(c);
+        }
+    );
 };
 
 // skopiowane z http://jsfiddle.net/DkHyd/
-$.fn.togglepanels = function(){
-  "use strict";
-  return this.each(function(){
-    $(this).addClass("ui-accordion ui-accordion-icons ui-widget ui-helper-reset")
-      .find("h3")
-      .addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-top ui-corner-bottom")
-      .hover(function() { $(this).toggleClass("ui-state-hover"); })
-      .prepend('<span class="ui-icon ui-icon-triangle-1-e"></span>')
-      .click(function() {
-        $(this)
-          .toggleClass("ui-accordion-header-active ui-state-active ui-state-default ui-corner-bottom")
-          .find("> .ui-icon").toggleClass("ui-icon-triangle-1-e ui-icon-triangle-1-s").end()
-          .next().slideToggle();
-        return false;
-      })
-      .next()
-      .addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom")
-      .hide();
-  });
+$.fn.togglepanels = function () {
+    "use strict";
+    return this.each(function () {
+        $(this).addClass("ui-accordion ui-accordion-icons ui-widget ui-helper-reset")
+            .find("h3")
+            .addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-top ui-corner-bottom")
+            .hover(function () {
+                $(this).toggleClass("ui-state-hover");
+            })
+            .prepend('<span class="ui-icon ui-icon-triangle-1-e"></span>')
+            .click(function () {
+                $(this)
+                    .toggleClass("ui-accordion-header-active ui-state-active ui-state-default ui-corner-bottom")
+                    .find("> .ui-icon").toggleClass("ui-icon-triangle-1-e ui-icon-triangle-1-s").end()
+                    .next().slideToggle();
+                return false;
+            })
+            .next()
+            .addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom")
+            .hide();
+    });
 };
 
 function multiselect_toggle(select_el, option_value, enable) {
-  "use strict";
-  var select, widget, option;
-  select = $(select_el);
-  widget = select.multiselect2("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);
+    "use strict";
+    var select, widget, option;
+    select = $(select_el);
+    widget = select.multiselect2("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);
 }
 common.multiselect_toggle = multiselect_toggle;
 
 function multiselect_enable(select_el, option_value) {
-  "use strict";
-  var select, widget, option;
-  select = $(select_el);
-  widget = select.multiselect2("widget");
-  option = widget.find('[value="' + option_value + '"]');
-  option.enable();
-  option.parent().removeClass('ui-state-disabled');
-  option.parent().parent().removeClass('ui-multiselect-disabled');
+    "use strict";
+    var select, widget, option;
+    select = $(select_el);
+    widget = select.multiselect2("widget");
+    option = widget.find('[value="' + option_value + '"]');
+    option.enable();
+    option.parent().removeClass('ui-state-disabled');
+    option.parent().parent().removeClass('ui-multiselect-disabled');
 }
 common.multiselect_enable = multiselect_enable;
 
 function error_alert(text) {
-  "use strict";
-  window.alert(text);
+    "use strict";
+    window.alert(text);
 }
 common.error_alert = error_alert;
 
 // parametry: method, url, data
 // description, dest, callback, callback_args
-$.ajaxJSON = function(params) {
-  "use strict";
-  var encoded_data = {};
-  if (params.save && !before_save())
-    return false;
-  if (params.async === undefined)
-    params.async = true;
-  $.each(params.data, function(key, value) {
-    encoded_data[key] = $.toJSON(value);
-  });
-  if (params.async === true) {
-    $.ajax({
-      type: params.method,
-      url: params.url,
-      dataType: 'json',
-      data: encoded_data,
-      success: parse_result(params),
-      error: params.error_callback
+$.ajaxJSON = function (params) {
+    "use strict";
+    var encoded_data = {};
+    if (params.save && !before_save())
+        return false;
+    if (params.async === undefined)
+        params.async = true;
+    $.each(params.data, function (key, value) {
+        encoded_data[key] = $.toJSON(value);
     });
-    return true;
-  } else {
-    return $.parseJSON($.ajax({
-      type: params.method,
-      url: params.url,
-      dataType: 'json',
-      data: encoded_data,
-      async: false
-    }).responseText);
-  }
+    if (params.async === true) {
+        $.ajax({
+            type: params.method,
+            url: params.url,
+            dataType: 'json',
+            data: encoded_data,
+            success: parse_result(params),
+            error: params.error_callback
+        });
+        return true;
+    } else {
+        return $.parseJSON($.ajax({
+            type: params.method,
+            url: params.url,
+            dataType: 'json',
+            data: encoded_data,
+            async: false
+        }).responseText);
+    }
 };
 
 function blank(str) {
-  "use strict";
-  var re = /^[\t\n ]*$/;
-  return re.test(str);
+    "use strict";
+    var re = /^[\t\n ]*$/;
+    return re.test(str);
 }
 common.blank = blank;
 
 function strip(str) {
-  "use strict";
-  return str.replace(/^\s+|\s+$/g, '');
+    "use strict";
+    return str.replace(/^\s+|\s+$/g, '');
 }
 common.strip = strip;
 
 // parametry: description, dest, callback, callback_args
 function parse_result(params) {
-  "use strict";
-  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)) {
-          var msg = params.description + ' ' + "nie powiodło się:\n";
-          msg += data.result;
-          error_alert(msg);
+    "use strict";
+    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)) {
+                var msg = params.description + ' ' + "nie powiodło się:\n";
+                msg += data.result;
+                error_alert(msg);
+            }
         }
-    }
-    else { // OK
-      if (params.dest) {
-        params.dest.html(data.html);
-      }
-      if (params.callback) {
-        if (!params.callback_args)
-          params.callback_args = [];
-        var args = [data].concat(params.callback_args);
-        params.callback.apply({}, args);
-      }
-    }
-  };
+        else { // OK
+            if (params.dest) {
+                params.dest.html(data.html);
+            }
+            if (params.callback) {
+                if (!params.callback_args)
+                    params.callback_args = [];
+                var args = [data].concat(params.callback_args);
+                params.callback.apply({}, args);
+            }
+        }
+    };
 }
 
 function debug(content) {
-  "use strict";
-  var doc = $('#debug').contents().get(0);
-  doc.open();
-  doc.writeln(content);
-  doc.close();
+    "use strict";
+    var doc = $('#debug').contents().get(0);
+    doc.open();
+    doc.writeln(content);
+    doc.close();
 }
 
-$(function() {
-  "use strict";
-  var debug = $('#debug'), main_menu = $('#main_menu');
-  $('#show-debug').click(function() {
-    debug.toggle();
-  });
-  debug.height($(window).height() - main_menu.height());
-  debug.css('top', main_menu.height());
+$(function () {
+    "use strict";
+    var debug = $('#debug'), main_menu = $('#main_menu');
+    $('#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) {
-  "use strict";
-  debug(request.responseText);
-  $('#show-debug').show();
+    "use strict";
+    debug(request.responseText);
+    $('#show-debug').show();
 }
 
 //$.ajaxSetup({global: true, error: parse_error});
 
-$(function() {
-  "use strict";
-  $('#debug').ajaxError(parse_error);
+$(function () {
+    "use strict";
+    $('#debug').ajaxError(parse_error);
 });
 
-$('html').ajaxSend(function(event, xhr, settings) {
-  "use strict";
-  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;
+$('html').ajaxSend(function (event, xhr, settings) {
+    "use strict";
+    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'));
     }
-    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'));
-  }
 });
 
 // http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/2117698#2117698
-(function($) {
-  "use strict";
-  $.fn.textMetrics = function() {
-    var h, w, el = this;
-    var div = document.createElement('div');
-    document.body.appendChild(div);
-    $(div).css({
-      position: 'absolute',
-      left: -1000,
-      top: -1000,
-      display: 'none'
-    });
-    $(div).html($(el).html());
-    var styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'];
-    $(styles).each(function() {
-     var s = this.toString();
-     $(div).css(s, $(el).css(s));
-    });
-    h = $(div).outerHeight();
-    w = $(div).outerWidth();
-    $(div).remove();
-    return {
-     height: h,
-     width: w
+(function ($) {
+    "use strict";
+    $.fn.textMetrics = function () {
+        var h, w, el = this;
+        var div = document.createElement('div');
+        document.body.appendChild(div);
+        $(div).css({
+            position: 'absolute',
+            left: -1000,
+            top: -1000,
+            display: 'none'
+        });
+        $(div).html($(el).html());
+        var styles = ['font-size', 'font-style', 'font-weight', 'font-family', 'line-height', 'text-transform', 'letter-spacing'];
+        $(styles).each(function () {
+            var s = this.toString();
+            $(div).css(s, $(el).css(s));
+        });
+        h = $(div).outerHeight();
+        w = $(div).outerWidth();
+        $(div).remove();
+        return {
+            height: h,
+            width: w
+        };
     };
-  };
 })(jQuery);
 
 function update_hash() {
-  "use strict";
-  var new_hash = make_hash();
-  old_hash = new_hash;
-  location.href = '#' + new_hash;
+    "use strict";
+    var new_hash = make_hash();
+    old_hash = new_hash;
+    location.href = '#' + new_hash;
 }
 common.update_hash = update_hash;
 
 function make_hash() {
-  "use strict";
-  var bottom_tabs, tabs, tab_path = [], query, id, data, original_data;
-  var paginer_el;
-  var are_tabs = $('.tabs').length > 0;
-  if (are_tabs) {
-    tabs = $('.tabs:visible').first();
-    while (tabs.find('.tabs:visible').length > 0) {
-      tabs = tabs.find('.tabs:visible').first();
-    }
-    bottom_tabs = tabs;
-    do {
-      tab_path.unshift(tabs.children('.ui-tabs-panel:visible')[0].id);
-      tabs = tabs.parents('.tabs').first();
-    } while (tabs.length > 0);
-  } else
-    tab_path = [''];
-  paginer_el = $('.paginer:visible', bottom_tabs);
-  if (paginer_el.length > 0) {
-    id = paginer_el[0].id;
-    data = $dj.paginer[id][1];
-    original_data = $dj.original_paginer[id][1];
-    query = [];
-    if (data.order_by !== original_data.order_by)
-      query.push('order_by=' + data.order_by);
-    $.each(data.filters, function(i, filter) {
-      if (i >= original_data.filters.length)
-        query.push(filter[0] + '-' + filter[1] + '=' + filter[2]);
-    });
-    if (paginer.get_page_number(id) > 1)
-      query.push('page=' + paginer.get_page_number(id));
-    tab_path.push(query.join('&'));
-  } else
-    tab_path.push('');
-  return tab_path.join('/');
+    "use strict";
+    var bottom_tabs, tabs, tab_path = [], query, id, data, original_data;
+    var paginer_el;
+    var are_tabs = $('.tabs').length > 0;
+    if (are_tabs) {
+        tabs = $('.tabs:visible').first();
+        while (tabs.find('.tabs:visible').length > 0) {
+            tabs = tabs.find('.tabs:visible').first();
+        }
+        bottom_tabs = tabs;
+        do {
+            tab_path.unshift(tabs.children('.ui-tabs-panel:visible')[0].id);
+            tabs = tabs.parents('.tabs').first();
+        } while (tabs.length > 0);
+    } else
+        tab_path = [''];
+    paginer_el = $('.paginer:visible', bottom_tabs);
+    if (paginer_el.length > 0) {
+        id = paginer_el[0].id;
+        data = $dj.paginer[id][1];
+        original_data = $dj.original_paginer[id][1];
+        query = [];
+        if (data.order_by !== original_data.order_by)
+            query.push('order_by=' + data.order_by);
+        $.each(data.filters, function (i, filter) {
+            if (i >= original_data.filters.length)
+                query.push(filter[0] + '-' + filter[1] + '=' + filter[2]);
+        });
+        if (paginer.get_page_number(id) > 1)
+            query.push('page=' + paginer.get_page_number(id));
+        tab_path.push(query.join('&'));
+    } else
+        tab_path.push('');
+    return tab_path.join('/');
 }
 
 var old_hash = 'not gonna happen';
 
 function interpret_hash(hash) {
-  "use strict";
-  var data = hash.split('/'), children;
-  if (hash === old_hash)
-    return;
-  var id, paginer_data, original_data, new_order_by, new_filters, new_page;
-  var paginer_container, paginer_el;
-  if (hash !== '')
-    $.each(data.slice(0, data.length - 1), function(i, part) {
-      if (part)
-        $('#' + part).parents('.tabs').first().tabs('select', '#' + part);
-    });
-  else {
-    paginer_container = $('.ui-tabs-panel').first();
-    //hash_interpreted = false; // HACK
-    while (paginer_container.length > 0) {
-      paginer_container.parents('.tabs').first().tabs(
-        'select', '#' + paginer_container[0].id);
-      children = $('.ui-tabs-panel', paginer_container);
-      if (children.length > 0)
-        paginer_container = children.first();
-      else
-        paginer_container = children;
-    }
-    hash_interpreted = true; // HACK
-  }
-  if (window.paginer) {
-    if (data[0] !== '')
-      paginer_container = $('#' + data[data.length - 2]);
-    else { // nie ma tabów (lub pusty hash...)
-      paginer_container = $(document.body);
-      do {
-        children = $('.ui-tabs-panel:visible', paginer_container);
-        if (children.length)
-          paginer_container = children[0];
-      } while(children.length);
-    }
-    paginer_el = $('.paginer', paginer_container);
-    if (paginer_el.length > 0) {
-      id = paginer_el[0].id;
-      paginer_data = $dj.paginer[id][1];
-      original_data = $dj.original_paginer[id][1];
-      new_order_by = original_data.order_by;
-      new_page = 1;
-      new_filters = $.extend([], original_data.filters);
-      if (data[data.length - 1])
-        $.each(data[data.length - 1].split('&'), function(i, pair) {
-          if (pair) {
-            var p = pair.split('=', 2);
-            var field_lookup = p[0].split('-', 2), value = p[1];
-            var field = field_lookup[0], lookup = field_lookup[1];
-            if (value === 'false')
-              value = false;
-            if (value === 'true')
-              value = true; // nieodporne na tekstowe filtry (jeśli będą)
-            if (p[0] === 'order_by') {
-              new_order_by = value;
-            } else if (p[0] === 'page') {
-              new_page = window.parseInt(value);
-            } else { // jakieś sprawdzanie poprawności? w sumie serwer to zrobi...
-              new_filters.push([field, lookup, value]);
-            }
-          }
+    "use strict";
+    var data = hash.split('/'), children;
+    if (hash === old_hash)
+        return;
+    var id, paginer_data, original_data, new_order_by, new_filters, new_page;
+    var paginer_container, paginer_el;
+    if (hash !== '')
+        $.each(data.slice(0, data.length - 1), function (i, part) {
+            if (part)
+                $('#' + part).parents('.tabs').first().tabs('select', '#' + part);
         });
-      paginer_data.order_by = new_order_by;
-      paginer_data.filters = new_filters;
-      paginer.page_numbers[id] = new_page;
-      paginer.update_list(id, true); // protect hash
-      paginer.show_order(id);
-      paginer.reload_panel(id);
+    else {
+        paginer_container = $('.ui-tabs-panel').first();
+        //hash_interpreted = false; // HACK
+        while (paginer_container.length > 0) {
+            paginer_container.parents('.tabs').first().tabs(
+                'select', '#' + paginer_container[0].id);
+            children = $('.ui-tabs-panel', paginer_container);
+            if (children.length > 0)
+                paginer_container = children.first();
+            else
+                paginer_container = children;
+        }
+        hash_interpreted = true; // HACK
+    }
+    if (window.paginer) {
+        if (data[0] !== '')
+            paginer_container = $('#' + data[data.length - 2]);
+        else { // nie ma tabów (lub pusty hash...)
+            paginer_container = $(document.body);
+            do {
+                children = $('.ui-tabs-panel:visible', paginer_container);
+                if (children.length)
+                    paginer_container = children[0];
+            } while (children.length);
+        }
+        paginer_el = $('.paginer', paginer_container);
+        if (paginer_el.length > 0) {
+            id = paginer_el[0].id;
+            paginer_data = $dj.paginer[id][1];
+            original_data = $dj.original_paginer[id][1];
+            new_order_by = original_data.order_by;
+            new_page = 1;
+            new_filters = $.extend([], original_data.filters);
+            if (data[data.length - 1])
+                $.each(data[data.length - 1].split('&'), function (i, pair) {
+                    if (pair) {
+                        var p = pair.split('=', 2);
+                        var field_lookup = p[0].split('-', 2), value = p[1];
+                        var field = field_lookup[0], lookup = field_lookup[1];
+                        if (value === 'false')
+                            value = false;
+                        if (value === 'true')
+                            value = true; // nieodporne na tekstowe filtry (jeśli będą)
+                        if (p[0] === 'order_by') {
+                            new_order_by = value;
+                        } else if (p[0] === 'page') {
+                            new_page = window.parseInt(value);
+                        } else { // jakieś sprawdzanie poprawności? w sumie serwer to zrobi...
+                            new_filters.push([field, lookup, value]);
+                        }
+                    }
+                });
+            paginer_data.order_by = new_order_by;
+            paginer_data.filters = new_filters;
+            paginer.page_numbers[id] = new_page;
+            paginer.update_list(id, true); // protect hash
+            paginer.show_order(id);
+            paginer.reload_panel(id);
+        }
     }
-  }
-  old_hash = hash;
+    old_hash = hash;
 }
diff --git a/media/js/export.js b/media/js/export.js
index e26495c..3c792b0 100644
--- a/media/js/export.js
+++ b/media/js/export.js
@@ -1,190 +1,190 @@
 // straszna i zła copypasta
 function selected_qualifiers_text(num, total, checked) {
-  "use strict";
-  if (num >= 4)
-    return num + ' kwalifikatorów';
-  var grouped = {};
-  $.each(checked, function(i, elem) {
-    var id = elem.value;
-    var vocab = $dj.vocabs[id];
-    if (grouped[vocab] === undefined)
-      grouped[vocab] = [];
-    grouped[vocab].push(elem.title);
-  });
-  var vocab_table = [];
-  var owner = $('#owner-vocabulary').text();
-  if (grouped[owner])
-    vocab_table.push(owner + ': ' + grouped[owner].join(', '));
-  $.each(grouped, function(vocab, qualifiers) {
-    if (vocab !== owner)
-      vocab_table.push(vocab + ': ' + qualifiers.join(', '));
-  });
-  return vocab_table.join('; ');
+    "use strict";
+    if (num >= 4)
+        return num + ' kwalifikatorów';
+    var grouped = {};
+    $.each(checked, function (i, elem) {
+        var id = elem.value;
+        var vocab = $dj.vocabs[id];
+        if (grouped[vocab] === undefined)
+            grouped[vocab] = [];
+        grouped[vocab].push(elem.title);
+    });
+    var vocab_table = [];
+    var owner = $('#owner-vocabulary').text();
+    if (grouped[owner])
+        vocab_table.push(owner + ': ' + grouped[owner].join(', '));
+    $.each(grouped, function (vocab, qualifiers) {
+        if (vocab !== owner)
+            vocab_table.push(vocab + ': ' + qualifiers.join(', '));
+    });
+    return vocab_table.join('; ');
 }
 
 var qualifier_options = {
-  noneSelectedText: 'Wybierz',
-  selectedText: selected_qualifiers_text,
-  selectedList: 4,
-  header: false
+    noneSelectedText: 'Wybierz',
+    selectedText: selected_qualifiers_text,
+    selectedList: 4,
+    header: false
 };
 
 var new_row_counter = 1;
 function get_new_qualifier_row_html() {
-  "use strict";
-  var new_row_html = $.ajax({
-    type: 'get',
-    url: $dj.ajax_new_qualifier_row,
-    async: false
-  }).responseText;
-  var row_html = new_row_html.replace(/NUM/g, new_row_counter);
-  new_row_counter++;
-  return row_html;
+    "use strict";
+    var new_row_html = $.ajax({
+        type: 'get',
+        url: $dj.ajax_new_qualifier_row,
+        async: false
+    }).responseText;
+    var row_html = new_row_html.replace(/NUM/g, new_row_counter);
+    new_row_counter++;
+    return row_html;
 }
 
 function add_qualifier_row() {
-  "use strict";
-  var new_row = $(get_new_qualifier_row_html());
-  $('#magic-qualifiers').append(new_row);
-  new_row.find('button').button();
-  return new_row.prop('id');
+    "use strict";
+    var new_row = $(get_new_qualifier_row_html());
+    $('#magic-qualifiers').append(new_row);
+    new_row.find('button').button();
+    return new_row.prop('id');
 }
 
-var remove_qualifier_row = function() {
-  "use strict";
-  $(this).closest('li').remove();
+var remove_qualifier_row = function () {
+    "use strict";
+    $(this).closest('li').remove();
 };
 
 function save_export_data() {
-  "use strict";
-  var name, post_data;
-  name = window.prompt('Wybierz nazwę');
-  if(name) {
-    post_data = {
-      name: name,
-      serialized_data: $.toJSON($('#export-form').serializeArray())
-    };
-    var save_data = {
-      method: 'post',
-      url: $dj.ajax_save_export_data,
-      data: post_data,
-      description: 'Zapisanie ustawień'
-    };
-    $.ajaxJSON($.extend(save_data, {
-      callback: function(data) {
-        if (data.exists && window.confirm('Ta nazwa jest zajęta. Nadpisać?')) {
-          $.ajaxJSON($.extend(save_data, {
-            data: $.extend(post_data, {force: true})
-          }));
-        }
-      }
-    }));
-  }
-  return false;
+    "use strict";
+    var name, post_data;
+    name = window.prompt('Wybierz nazwę');
+    if (name) {
+        post_data = {
+            name: name,
+            serialized_data: $.toJSON($('#export-form').serializeArray())
+        };
+        var save_data = {
+            method: 'post',
+            url: $dj.ajax_save_export_data,
+            data: post_data,
+            description: 'Zapisanie ustawień'
+        };
+        $.ajaxJSON($.extend(save_data, {
+            callback: function (data) {
+                if (data.exists && window.confirm('Ta nazwa jest zajęta. Nadpisać?')) {
+                    $.ajaxJSON($.extend(save_data, {
+                        data: $.extend(post_data, {force: true})
+                    }));
+                }
+            }
+        }));
+    }
+    return false;
 }
 
 function put_data(json) {
-  "use strict";
-  var data = $.parseJSON(json),
-      qualifier_rows = {}, vocabs = [], antivocabs = [], parts;
-  $('#id_refl').attr('checked', false);
-  $('#id_commonness').attr('checked', false);
-  $('#magic-qualifiers li').remove();
-  $.each(data, function(i, item) {
-    if (item.name === 'vocabs') {
-      vocabs.push(item.value);
-    }
-    if (item.name === 'antivocabs') {
-      antivocabs.push(item.value);
-    }
-    if (item.name === 'variant') {
-      $('#id_variant').val(item.value);
-    }
-    if (item.name === 'refl' || item.name === 'commonness') {
-      $('#id_' + item.name).attr('checked', true);
-    }
-    if (item.name.indexOf('magic') === 0) {
-      parts = item.name.split('-');
-      if (!qualifier_rows[parts[0]]) {
-        qualifier_rows[parts[0]] = {};
-      }
-      qualifier_rows[parts[0]][parts[1]] = item.value;
-    }
-  });
-  $('#id_vocabs').val(vocabs).multiselect2("refresh");
-  $('#id_antivocabs').val(antivocabs).multiselect2("refresh");
-  $.each(qualifier_rows, function(id, item) {
-    var row_id = add_qualifier_row();
-    $('#id_' + row_id + '-qualifier').val(item.qualifier);
-    $('#id_' + row_id + '-regex').val(item.regex);
-  });
+    "use strict";
+    var data = $.parseJSON(json),
+        qualifier_rows = {}, vocabs = [], antivocabs = [], parts;
+    $('#id_refl').attr('checked', false);
+    $('#id_commonness').attr('checked', false);
+    $('#magic-qualifiers li').remove();
+    $.each(data, function (i, item) {
+        if (item.name === 'vocabs') {
+            vocabs.push(item.value);
+        }
+        if (item.name === 'antivocabs') {
+            antivocabs.push(item.value);
+        }
+        if (item.name === 'variant') {
+            $('#id_variant').val(item.value);
+        }
+        if (item.name === 'refl' || item.name === 'commonness') {
+            $('#id_' + item.name).attr('checked', true);
+        }
+        if (item.name.indexOf('magic') === 0) {
+            parts = item.name.split('-');
+            if (!qualifier_rows[parts[0]]) {
+                qualifier_rows[parts[0]] = {};
+            }
+            qualifier_rows[parts[0]][parts[1]] = item.value;
+        }
+    });
+    $('#id_vocabs').val(vocabs).multiselect2("refresh");
+    $('#id_antivocabs').val(antivocabs).multiselect2("refresh");
+    $.each(qualifier_rows, function (id, item) {
+        var row_id = add_qualifier_row();
+        $('#id_' + row_id + '-qualifier').val(item.qualifier);
+        $('#id_' + row_id + '-regex').val(item.regex);
+    });
 }
 
 function export_choice(ajax_data) {
-  "use strict";
-  var exports = ajax_data.data_list,
-      list = $('#data-list');
-  list.html('');
-  $.each(exports, function(i, data) {
-    var item = $('<li/>').addClass('ui-state-default').attr('id', data.id);
-    var delete_button = $('<span/>')
-      .addClass('remove ui-icon ui-icon-closethick');
-    delete_button.click(function() {
-      if (window.confirm('Usunąć eksport "' + data.name + '"?')) {
-        $.ajaxJSON({
-          method: 'post',
-          url: $dj.ajax_delete_export_data,
-          data: {data_id: data.id},
-          description: 'Usunięcie ustawień eksportu',
-          callback: function() {
-            item.remove();
-          }
+    "use strict";
+    var exports = ajax_data.data_list,
+        list = $('#data-list');
+    list.html('');
+    $.each(exports, function (i, data) {
+        var item = $('<li/>').addClass('ui-state-default').attr('id', data.id);
+        var delete_button = $('<span/>')
+            .addClass('remove ui-icon ui-icon-closethick');
+        delete_button.click(function () {
+            if (window.confirm('Usunąć eksport "' + data.name + '"?')) {
+                $.ajaxJSON({
+                    method: 'post',
+                    url: $dj.ajax_delete_export_data,
+                    data: {data_id: data.id},
+                    description: 'Usunięcie ustawień eksportu',
+                    callback: function () {
+                        item.remove();
+                    }
+                });
+            }
+            return false;
         });
-      }
-      return false;
-    });
-    item.append(delete_button);
-    item.append(data.name);
-    item.click(function() {
-      put_data(data.json);
-      $("#load-data-dialog").dialog('close');
+        item.append(delete_button);
+        item.append(data.name);
+        item.click(function () {
+            put_data(data.json);
+            $("#load-data-dialog").dialog('close');
+        });
+        list.append(item);
     });
-    list.append(item);
-  });
-  $("#load-data-dialog").dialog('open');
+    $("#load-data-dialog").dialog('open');
 }
 
 function load_export_data() {
-  "use strict";
-  $.ajaxJSON({
-    method: 'get',
-    url: $dj.ajax_get_export_data,
-    data: {},
-    description: 'Pobranie zapisanych eksportów',
-    callback: export_choice
-  });
-  return false;
+    "use strict";
+    $.ajaxJSON({
+        method: 'get',
+        url: $dj.ajax_get_export_data,
+        data: {},
+        description: 'Pobranie zapisanych eksportów',
+        callback: export_choice
+    });
+    return false;
 }
 
-$(function() {
-  "use strict";
-  var opts = {
-    noneSelectedText: 'Wybierz słowniki',
-    selectedText: '# słowników',
-    selectedList: 4,
-    header: false
-  };
-  $('#id_vocabs').multiselect2(opts);
-  $('#id_antivocabs').multiselect2(opts);
-  $('#id_excluding_qualifiers').multiselect2(qualifier_options);
-  $('#add-magic-qualifier-row').click(add_qualifier_row);
-  $('button.save').click(save_export_data);
-  $('button.load').click(load_export_data);
-  $("#load-data-dialog").dialog({
-    autoOpen: false,
-    height: 'auto',
-    width: 'auto',
-    modal: true
-  });
-  $(document).on('click', '#magic-qualifiers .remove', remove_qualifier_row);
+$(function () {
+    "use strict";
+    var opts = {
+        noneSelectedText: 'Wybierz słowniki',
+        selectedText: '# słowników',
+        selectedList: 4,
+        header: false
+    };
+    $('#id_vocabs').multiselect2(opts);
+    $('#id_antivocabs').multiselect2(opts);
+    $('#id_excluding_qualifiers').multiselect2(qualifier_options);
+    $('#add-magic-qualifier-row').click(add_qualifier_row);
+    $('button.save').click(save_export_data);
+    $('button.load').click(load_export_data);
+    $("#load-data-dialog").dialog({
+        autoOpen: false,
+        height: 'auto',
+        width: 'auto',
+        modal: true
+    });
+    $(document).on('click', '#magic-qualifiers .remove', remove_qualifier_row);
 });
diff --git a/media/js/history-view.js b/media/js/history-view.js
index 46f793e..7fb0248 100644
--- a/media/js/history-view.js
+++ b/media/js/history-view.js
@@ -1,6 +1,6 @@
 paginer.init_widget.lexeme_history = {
-  'time': function(row) {
-    "use strict";
-    row.find('input.datepicker').datepicker($.datepicker.regional.pl);
-  }
+    'time': function (row) {
+        "use strict";
+        row.find('input.datepicker').datepicker($.datepicker.regional.pl);
+    }
 };
\ No newline at end of file
diff --git a/media/js/jqgrid-patch.js b/media/js/jqgrid-patch.js
index 313d71b..aa3ef6f 100644
--- a/media/js/jqgrid-patch.js
+++ b/media/js/jqgrid-patch.js
@@ -1,67 +1,67 @@
 // przerobiony fragment kodu jqgrid
 $.jgrid.extend({
-  //ostatnio zaznaczony wiersz
-  lastSelectedId : undefined,
-  //pomocnicza zmienna : jeśli true, to po załadowaniu grida
-  //należy odpalić setSelection z parametrem lastSelectedId
-  //uwaga: to nie to samo co odpalić scrollToLastSelection
-  setOnComplete : false,
-  //widok z funkcją mówiącą, który w kolejności będzie wiersz o danym id
-  findIdUrl : undefined,
+    //ostatnio zaznaczony wiersz
+    lastSelectedId: undefined,
+    //pomocnicza zmienna : jeśli true, to po załadowaniu grida
+    //należy odpalić setSelection z parametrem lastSelectedId
+    //uwaga: to nie to samo co odpalić scrollToLastSelection
+    setOnComplete: false,
+    //widok z funkcją mówiącą, który w kolejności będzie wiersz o danym id
+    findIdUrl: undefined,
 
-  //scrolluje do wiersza który jest 'row'-ty od góry, przy założeniu
-  //że wszystkich wierszy jest rowcount
-  scrollToRow : function(row, rowcount) {
-    "use strict";
-    return this.each(function(){
-      var clientHeight = $(this.grid.bDiv)[0].clientHeight;
-      var scrollRange = $(this.grid.bDiv)[0].scrollHeight;
-      //Załóżmy, że wiersze mają jedną wysokość...
-      var rowTop = Math.round((row - 1) * (scrollRange / rowcount));
-      $(this.grid.bDiv)[0].scrollTop = rowTop - Math.round(clientHeight / 2);
-    });
-  },
+    //scrolluje do wiersza który jest 'row'-ty od góry, przy założeniu
+    //że wszystkich wierszy jest rowcount
+    scrollToRow: function (row, rowcount) {
+        "use strict";
+        return this.each(function () {
+            var clientHeight = $(this.grid.bDiv)[0].clientHeight;
+            var scrollRange = $(this.grid.bDiv)[0].scrollHeight;
+            //Załóżmy, że wiersze mają jedną wysokość...
+            var rowTop = Math.round((row - 1) * (scrollRange / rowcount));
+            $(this.grid.bDiv)[0].scrollTop = rowTop - Math.round(clientHeight / 2);
+        });
+    },
 
-  //scrolls to row and sets selection
-  scrollAndSet : function(id, row, count) {
-    "use strict";
-    return this.each(function(){
-      var $t = this;
-      $($t).jqGrid('setGridParam', {'lastSelectedId' : id});
-      if ($t.rows.namedItem(id)) {
-        $($t).jqGrid('setSelection', id);
-      }
-      else {//odwlekamy zaznaczanie do załadowania (complete)
-        $($t).jqGrid('setGridParam', {'setOnComplete' : true});
-      }
-      $($t).jqGrid('scrollToRow', row, count);
-      });
-  },
+    //scrolls to row and sets selection
+    scrollAndSet: function (id, row, count) {
+        "use strict";
+        return this.each(function () {
+            var $t = this;
+            $($t).jqGrid('setGridParam', {'lastSelectedId': id});
+            if ($t.rows.namedItem(id)) {
+                $($t).jqGrid('setSelection', id);
+            }
+            else {//odwlekamy zaznaczanie do załadowania (complete)
+                $($t).jqGrid('setGridParam', {'setOnComplete': true});
+            }
+            $($t).jqGrid('scrollToRow', row, count);
+        });
+    },
 
-  scrollToId : function(id) {
-    "use strict";
-    return this.each(function(){
-        var $t = this;
-        var data = {
-          id: id
-        };
-        $.extend(data, $($t).jqGrid('getGridParam','postData'));
+    scrollToId: function (id) {
+        "use strict";
+        return this.each(function () {
+            var $t = this;
+            var data = {
+                id: id
+            };
+            $.extend(data, $($t).jqGrid('getGridParam', 'postData'));
 
-        $.get($t.p.findIdUrl, data, function(resp){
-          var rowIndex = resp.rowIndex;
-          var recordsCount = resp.records;
-          $($t).jqGrid('scrollAndSet', id, rowIndex, recordsCount);
+            $.get($t.p.findIdUrl, data, function (resp) {
+                var rowIndex = resp.rowIndex;
+                var recordsCount = resp.records;
+                $($t).jqGrid('scrollAndSet', id, rowIndex, recordsCount);
+            });
         });
-    });
-  },
+    },
 
-  //wracamy do ostatniego zaznaczenia
-  scrollToLastSelection : function() {
-    "use strict";
-    return this.each(function() {
-      if(this.p.lastSelectedId !== undefined) {
-        $(this).jqGrid('scrollToId', this.p.lastSelectedId);
-      }
-    });
-  }
+    //wracamy do ostatniego zaznaczenia
+    scrollToLastSelection: function () {
+        "use strict";
+        return this.each(function () {
+            if (this.p.lastSelectedId !== undefined) {
+                $(this).jqGrid('scrollToId', this.p.lastSelectedId);
+            }
+        });
+    }
 });
diff --git a/media/js/jqgrid.js b/media/js/jqgrid.js
index 3f9f1a8..b37a449 100644
--- a/media/js/jqgrid.js
+++ b/media/js/jqgrid.js
@@ -1,385 +1,394 @@
 var sort_rules = $dj.sort_rules, colModel = $dj.colModel,
-  colNames = $dj.colNames, jqgrid_filteroptions;
+    colNames = $dj.colNames, jqgrid_filteroptions;
 var timeoutHnd;
 var changed;
 var jqgrid = {
-  grid: undefined,
-  ctrl: undefined // do pokazywania, ze laduje
+    grid: undefined,
+    ctrl: undefined // do pokazywania, ze laduje
 };
 
 function put_filter(filter) {
-  "use strict";
-  jqgrid.grid.jqGrid('getGridParam', 'postData').filters = filter;
-  var filter_element = $('.searchFilter')[0],
-    coord = $.jgrid.findPos(filter_element);
-  jqgrid.grid.jqGrid('searchGrid', $.extend(jqgrid_filteroptions, {
-    left: coord[0] - filter_element.offsetLeft,
-    top: coord[1] - filter_element.offsetTop,
-    recreateFilter: true,
-    loadDefaults: true
-  }));
+    "use strict";
+    jqgrid.grid.jqGrid('getGridParam', 'postData').filters = filter;
+    var filter_element = $('.searchFilter')[0],
+        coord = $.jgrid.findPos(filter_element);
+    jqgrid.grid.jqGrid('searchGrid', $.extend(jqgrid_filteroptions, {
+        left: coord[0] - filter_element.offsetLeft,
+        top: coord[1] - filter_element.offsetTop,
+        recreateFilter: true,
+        loadDefaults: true
+    }));
 }
 jqgrid.put_filter = put_filter;
 
 function refresh_column_headers() {
-  "use strict";
-  var thd= $("thead:first", $('#scroll')[0].grid.hDiv).get(0);
-  var rules = $.evalJSON(
-    jqgrid.grid.jqGrid('getGridParam', 'postData').sort_rules);
-  $("tr th span.s-ico",thd).hide();
-  $("tr th span.ui-icon",thd).addClass('ui-state-disabled');
-  $("text").remove('.sort_priority');
-  for (var i = 0; i < rules.length; i++) {
-    $("tr th[id='scroll_"+rules[i].field+"'] span.s-ico",thd).show();
-    $("tr th[id='scroll_"+rules[i].field+"'] span.ui-icon-" + rules[i].order,thd).removeClass('ui-state-disabled');
-    $('tr th div#jqgh_'+rules[i].field+"'", thd).append('<text class="sort_priority">'+(i+1)+'</text>');
-  }
+    "use strict";
+    var thd = $("thead:first", $('#scroll')[0].grid.hDiv).get(0);
+    var rules = $.evalJSON(
+        jqgrid.grid.jqGrid('getGridParam', 'postData').sort_rules);
+    $("tr th span.s-ico", thd).hide();
+    $("tr th span.ui-icon", thd).addClass('ui-state-disabled');
+    $("text").remove('.sort_priority');
+    for (var i = 0; i < rules.length; i++) {
+        $("tr th[id='scroll_" + rules[i].field + "'] span.s-ico", thd).show();
+        $("tr th[id='scroll_" + rules[i].field + "'] span.ui-icon-" + rules[i].order, thd).removeClass('ui-state-disabled');
+        $('tr th div#jqgh_' + rules[i].field + "'", thd).append('<text class="sort_priority">' + (i + 1) + '</text>');
+    }
 }
 jqgrid.refresh_column_headers = refresh_column_headers;
 
 function sort_column(colName, index, order) {
-  "use strict";
-  var data = jqgrid.grid.jqGrid('getGridParam', 'postData');
-  var sort_rules = [{field: colName, order: order}];
-  if ($.isFunction(jqgrid.prepare_sort_rules)) {
-    var old_sort_rules = $.evalJSON(data.sort_rules);
-    jqgrid.prepare_sort_rules(sort_rules, old_sort_rules);
-  }
+    "use strict";
+    var data = jqgrid.grid.jqGrid('getGridParam', 'postData');
+    var sort_rules = [
+        {field: colName, order: order}
+    ];
+    if ($.isFunction(jqgrid.prepare_sort_rules)) {
+        var old_sort_rules = $.evalJSON(data.sort_rules);
+        jqgrid.prepare_sort_rules(sort_rules, old_sort_rules);
+    }
 
-  data.sort_rules = $.toJSON(sort_rules);
-  jqgrid.grid.jqGrid('setGridParam', {setOnComplete: true});
-  refresh_column_headers();
+    data.sort_rules = $.toJSON(sort_rules);
+    jqgrid.grid.jqGrid('setGridParam', {setOnComplete: true});
+    refresh_column_headers();
 }
 
-$(function() {
-  "use strict";
-  jqgrid_filteroptions = {
-    multipleSearch: true,
-    overlay: false,
-    top: 300,
-    left: 300,
-    sopt: ['eq','ne','bw','bn','ew','en','cn','nc', 're', 'nr'],
-    ops: [
-      {"name": "eq", "description": "equal", "operator":"="},
-      {"name": "ne", "description": "not equal", "operator":"<>"},
-      {"name": "lt", "description": "less", "operator":"<"},
-      {"name": "le", "description": "less or equal","operator":"<="},
-      {"name": "gt", "description": "greater", "operator":">"},
-      {"name": "ge", "description": "greater or equal", "operator":">="},
-      {"name": "bw", "description": "begins with", "operator":"LIKE"},
-      {"name": "bn", "description": "does not begin with", "operator":"NOT LIKE"},
-      {"name": "in", "description": "in", "operator":"IN"},
-      {"name": "ni", "description": "not in", "operator":"NOT IN"},
-      {"name": "ew", "description": "ends with", "operator":"LIKE"},
-      {"name": "en", "description": "does not end with", "operator":"NOT LIKE"},
-      {"name": "cn", "description": "contains", "operator":"LIKE"},
-      {"name": "nc", "description": "does not contain", "operator":"NOT LIKE"},
-      {"name": "nu", "description": "is null", "operator":"IS NULL"},
-      {"name": "nn", "description": "is not null", "operator":"IS NOT NULL"},
-      {"name": "re", "description": "matches regex", "operator":"REGEXP"},
-      {"name": "nr", "description": "does not match regex", "operator":"NOT REGEXP"},
-      {"name": "se", "description": "equal for sure", "operator":"="},
-      {"name": "sd", "description": "different for sure", "operator":"<>"},
-      {"name": "me", "description": "maybe equal", "operator":"="},
-      {"name": "md", "description": "maybe different", "operator":"<>"}
-    ],
-    beforeShowSearch: function(f) {
-      f.closest('.ui-jqdialog').appendTo('body')
-       .dialog('option', 'position', 'center');
-      return true;
-    },
-    onReset: function() {
-      var init = {
-        "groupOp": "AND",
-        rules: [{"field": jqgrid.main_field, "op": "eq", "data": ""}]
-      };
-      put_filter(init);
-    },
-    onSearch: function() {
-      $('#phrase_box').val('');
-      jqgrid.grid.jqGrid('getGridParam', 'postData').force_reload = true;
-    },
-    onInitializeSearch: jqgrid.add_buttons
-  };
+$(function () {
+    "use strict";
+    jqgrid_filteroptions = {
+        multipleSearch: true,
+        overlay: false,
+        top: 300,
+        left: 300,
+        sopt: ['eq', 'ne', 'bw', 'bn', 'ew', 'en', 'cn', 'nc', 're', 'nr'],
+        ops: [
+            {"name": "eq", "description": "equal", "operator": "="},
+            {"name": "ne", "description": "not equal", "operator": "<>"},
+            {"name": "lt", "description": "less", "operator": "<"},
+            {"name": "le", "description": "less or equal", "operator": "<="},
+            {"name": "gt", "description": "greater", "operator": ">"},
+            {"name": "ge", "description": "greater or equal", "operator": ">="},
+            {"name": "bw", "description": "begins with", "operator": "LIKE"},
+            {"name": "bn", "description": "does not begin with", "operator": "NOT LIKE"},
+            {"name": "in", "description": "in", "operator": "IN"},
+            {"name": "ni", "description": "not in", "operator": "NOT IN"},
+            {"name": "ew", "description": "ends with", "operator": "LIKE"},
+            {"name": "en", "description": "does not end with", "operator": "NOT LIKE"},
+            {"name": "cn", "description": "contains", "operator": "LIKE"},
+            {"name": "nc", "description": "does not contain", "operator": "NOT LIKE"},
+            {"name": "nu", "description": "is null", "operator": "IS NULL"},
+            {"name": "nn", "description": "is not null", "operator": "IS NOT NULL"},
+            {"name": "re", "description": "matches regex", "operator": "REGEXP"},
+            {"name": "nr", "description": "does not match regex", "operator": "NOT REGEXP"},
+            {"name": "se", "description": "equal for sure", "operator": "="},
+            {"name": "sd", "description": "different for sure", "operator": "<>"},
+            {"name": "me", "description": "maybe equal", "operator": "="},
+            {"name": "md", "description": "maybe different", "operator": "<>"}
+        ],
+        beforeShowSearch: function (f) {
+            f.closest('.ui-jqdialog').appendTo('body')
+                .dialog('option', 'position', 'center');
+            return true;
+        },
+        onReset: function () {
+            var init = {
+                "groupOp": "AND",
+                rules: [
+                    {"field": jqgrid.main_field, "op": "eq", "data": ""}
+                ]
+            };
+            put_filter(init);
+        },
+        onSearch: function () {
+            $('#phrase_box').val('');
+            jqgrid.grid.jqGrid('getGridParam', 'postData').force_reload = true;
+        },
+        onInitializeSearch: jqgrid.add_buttons
+    };
 
-  if (!colModel) {
-    colModel = jqgrid.initialColModel;
-  }
-  if (!colNames) {
-    colNames = jqgrid.initialColNames;
-  }
+    if (!colModel) {
+        colModel = jqgrid.initialColModel;
+    }
+    if (!colNames) {
+        colNames = jqgrid.initialColNames;
+    }
 
-  jqgrid.grid = $('#scroll');
-  var session_data = {};
-  if ($dj.filters) {
-    session_data.filters = $dj.filters;
-  }
-  if (sort_rules) {
-    sort_rules = $.evalJSON(sort_rules);
-  } else {
-    sort_rules = jqgrid.initial_sort_rules;
-  }
-  session_data.sort_rules = $.toJSON(sort_rules);
-  jqgrid.grid.jqGrid({
-    url: $dj.ajax_get_page,
-    findIdUrl : $dj.ajax_find_id,
-    datatype: "json",
-    colNames: colNames,
-    colModel: colModel,
-    rowNum: 50,
-    rowList : [20,30,50],
-    scroll: 1,
-    autowidth: true,
-    height: $('#left').height() - 27 - $('#search-panel').height(),
-    mtype: "GET",
-    rownumbers: false,
-    gridview: true,
-    viewrecords: true,
-    caption: jqgrid.grid_caption,
-    sortname: jqgrid.main_field,
-    sortorder: 'asc',
-    forceFit: true,
-    beforeSelectRow: function() {
-      var ok = true;
-      if (changed) {
-        ok = window.confirm('Czy chcesz porzucić niezapisane zmiany?');
-      }
-      return ok;
-    },
-    onSelectRow: jqgrid.load_content,
-    beforeRequest: function() {
-      var empty, filters;
-      if (!jqgrid.grid.jqGrid('getGridParam', 'search')) {
-        empty = true;
-      } else {
-        filters = jqgrid.grid.jqGrid('getGridParam', 'postData').filters;
+    jqgrid.grid = $('#scroll');
+    var session_data = {};
+    if ($dj.filters) {
+        session_data.filters = $dj.filters;
+    }
+    if (sort_rules) {
+        sort_rules = $.evalJSON(sort_rules);
+    } else {
+        sort_rules = jqgrid.initial_sort_rules;
+    }
+    session_data.sort_rules = $.toJSON(sort_rules);
+    jqgrid.grid.jqGrid({
+        url: $dj.ajax_get_page,
+        findIdUrl: $dj.ajax_find_id,
+        datatype: "json",
+        colNames: colNames,
+        colModel: colModel,
+        rowNum: 50,
+        rowList: [20, 30, 50],
+        scroll: 1,
+        autowidth: true,
+        height: $('#left').height() - 27 - $('#search-panel').height(),
+        mtype: "GET",
+        rownumbers: false,
+        gridview: true,
+        viewrecords: true,
+        caption: jqgrid.grid_caption,
+        sortname: jqgrid.main_field,
+        sortorder: 'asc',
+        forceFit: true,
+        beforeSelectRow: function () {
+            var ok = true;
+            if (changed) {
+                ok = window.confirm('Czy chcesz porzucić niezapisane zmiany?');
+            }
+            return ok;
+        },
+        onSelectRow: jqgrid.load_content,
+        beforeRequest: function () {
+            var empty, filters;
+            if (!jqgrid.grid.jqGrid('getGridParam', 'search')) {
+                empty = true;
+            } else {
+                filters = jqgrid.grid.jqGrid('getGridParam', 'postData').filters;
 
-        if (typeof(filters) === "string") {
-          filters = $.parseJSON(filters);
-        }
-        if (typeof(filters) !== "object" || filters === null || !filters.rules) {
-          empty = true;
-        } else {
-          empty = (filters.rules.length === 0);
-        }
-      }
-      $('#filter-button').children().first().toggleClass('ui-state-highlight', !empty);
-    },
-    gridComplete: function() {
-      if (jqgrid.grid.jqGrid('getGridParam', 'setOnComplete') === true) {
-        jqgrid.grid.jqGrid('scrollToLastSelection');
-        jqgrid.grid.jqGrid('setGridParam', {'setOnComplete' : false});
-      }
-    },
-    onSortCol: sort_column,
-    loadComplete: function(data) {
-      var num = data.records;
-      document.title = jqgrid.grid_caption + ' (' + num + ')';
-      if (jqgrid.grid.jqGrid('getGridParam', 'postData').force_reload === true) {
-        jqgrid.grid.jqGrid('getGridParam', 'postData').force_reload = false;
-        setTimeout(findAndScroll, 100);
-      }
-      layout.adjust_grid_width();
-    },
-    remapColumns: $dj.remap,
-    postData: session_data,
-    search: Boolean(session_data.filters)
-  });
-  // nawigacja klawiaturą powoduje zmulenie,
-  // bo wszystkie leksemy muszą się załadować
-  //jqgrid.grid.jqGrid('bindKeys');
-  $('#filter-button').click(function() {
-    jqgrid.grid.jqGrid('searchGrid', jqgrid_filteroptions);
-  });
+                if (typeof(filters) === "string") {
+                    filters = $.parseJSON(filters);
+                }
+                if (typeof(filters) !== "object" || filters === null || !filters.rules) {
+                    empty = true;
+                } else {
+                    empty = (filters.rules.length === 0);
+                }
+            }
+            $('#filter-button').children().first().toggleClass('ui-state-highlight', !empty);
+        },
+        gridComplete: function () {
+            if (jqgrid.grid.jqGrid('getGridParam', 'setOnComplete') === true) {
+                jqgrid.grid.jqGrid('scrollToLastSelection');
+                jqgrid.grid.jqGrid('setGridParam', {'setOnComplete': false});
+            }
+        },
+        onSortCol: sort_column,
+        loadComplete: function (data) {
+            var num = data.records;
+            document.title = jqgrid.grid_caption + ' (' + num + ')';
+            if (jqgrid.grid.jqGrid('getGridParam', 'postData').force_reload === true) {
+                jqgrid.grid.jqGrid('getGridParam', 'postData').force_reload = false;
+                setTimeout(findAndScroll, 100);
+            }
+            layout.adjust_grid_width();
+        },
+        remapColumns: $dj.remap,
+        postData: session_data,
+        search: Boolean(session_data.filters)
+    });
+    // nawigacja klawiaturą powoduje zmulenie,
+    // bo wszystkie leksemy muszą się załadować
+    //jqgrid.grid.jqGrid('bindKeys');
+    $('#filter-button').click(function () {
+        jqgrid.grid.jqGrid('searchGrid', jqgrid_filteroptions);
+    });
 
-  refresh_column_headers();
-  findAndScroll();
+    refresh_column_headers();
+    findAndScroll();
 
-  $(document).on('submit', '#' + jqgrid.edit_form_id, jqgrid.edit_form_submit);
-  $(document).on('click', '#' + jqgrid.edit_form_cancel_id, function() {
-    var id = $('input[name=id]', this.form).value();
-    $.ajaxJSON({
-      method: 'get',
-      dest: $('#edit'),
-      url: $dj.ajax_edit_form,
-      data: {id: id},
-      callback: jqgrid.edit_form_init
+    $(document).on('submit', '#' + jqgrid.edit_form_id, jqgrid.edit_form_submit);
+    $(document).on('click', '#' + jqgrid.edit_form_cancel_id, function () {
+        var id = $('input[name=id]', this.form).value();
+        $.ajaxJSON({
+            method: 'get',
+            dest: $('#edit'),
+            url: $dj.ajax_edit_form,
+            data: {id: id},
+            callback: jqgrid.edit_form_init
+        });
     });
-  });
-  var keyup = function() {
-    if (this.value !== this.defaultValue) {
-      show_changed();
-    }
-  };
-  $(document).on('keyup', '#' + jqgrid.edit_form_id + ' input', keyup);
-  $(document).on('keyup', '#' + jqgrid.edit_form_id + ' textarea', keyup);
-  $(document).on('change', '#' + jqgrid.edit_form_id + ' select', keyup);
-  $(document).on(
-    'change', '#' + jqgrid.edit_form_id + ' input[type=checkbox]',
-    show_changed);
+    var keyup = function () {
+        if (this.value !== this.defaultValue) {
+            show_changed();
+        }
+    };
+    $(document).on('keyup', '#' + jqgrid.edit_form_id + ' input', keyup);
+    $(document).on('keyup', '#' + jqgrid.edit_form_id + ' textarea', keyup);
+    $(document).on('change', '#' + jqgrid.edit_form_id + ' select', keyup);
+    $(document).on(
+        'change', '#' + jqgrid.edit_form_id + ' input[type=checkbox]',
+        show_changed);
 
-  $('#searchButton').click(findAndScroll);
-  $('#phrase_box').keydown(doSearch);
+    $('#searchButton').click(findAndScroll);
+    $('#phrase_box').keydown(doSearch);
 
-  for (var i = 0; i < colNames.length; i++) {
-    if (colModel[i].sortable !== false) {
-      var label = colNames[i];
-      var index = colModel[i].index;
-      var li = $(
-        '<li class="ui-state-default">' +
-          '<span class="sort-column"></span>' +
-          '<span class="sort-dir">' +
-            '<select>' +
-              '<option value="asc">Rosnąco</option>' +
-              '<option value="desc">Malejąco</option>' +
-            '</select>' +
-          '</span>' +
-        '</li>');
-      li.attr('id', index);
-      $('.sort-column', li).text(label);
-      $('select', li).attr('id', 'order-' + index);
-      if (index === 'entry') {
-        var span = $(
-          '<span class="sort-a-tergo">' +
-            '<input type="checkbox" id="entries_a_tergo"/> a tergo' +
-          '</span>');
-        span.appendTo(li);
-      }
-      li.appendTo($('#sort-rule-list'));
+    for (var i = 0; i < colNames.length; i++) {
+        if (colModel[i].sortable !== false) {
+            var label = colNames[i];
+            var index = colModel[i].index;
+            var li = $(
+                '<li class="ui-state-default">' +
+                    '<span class="sort-column"></span>' +
+                    '<span class="sort-dir">' +
+                    '<select>' +
+                    '<option value="asc">Rosnąco</option>' +
+                    '<option value="desc">Malejąco</option>' +
+                    '</select>' +
+                    '</span>' +
+                    '</li>');
+            li.attr('id', index);
+            $('.sort-column', li).text(label);
+            $('select', li).attr('id', 'order-' + index);
+            if (index === 'entry') {
+                var span = $(
+                    '<span class="sort-a-tergo">' +
+                        '<input type="checkbox" id="entries_a_tergo"/> a tergo' +
+                        '</span>');
+                span.appendTo(li);
+            }
+            li.appendTo($('#sort-rule-list'));
+        }
     }
-  }
-  $("#sort-dialog").dialog({
-    autoOpen: false,
-    height: 'auto',
-    width: 'auto',
-    modal: true
-  });
-  $("#sort-rule-list").sortable();
+    $("#sort-dialog").dialog({
+        autoOpen: false,
+        height: 'auto',
+        width: 'auto',
+        modal: true
+    });
+    $("#sort-rule-list").sortable();
 
-  $('#cancel-sort-order').click(function(){
-    $( "#sort-dialog" ).dialog( "close" );
-  });
+    $('#cancel-sort-order').click(function () {
+        $("#sort-dialog").dialog("close");
+    });
 
-  $('#save-sort-order').click(function() {
-    var a_tergo = $('#sort-dialog').find('#entries_a_tergo').value();
-    var list_table = $('#sort-rule-list').find('li');
-    //lista par (nazwa pola - porzadek sortowania)
-    var rules = [];
-    for (var i = 0; i < list_table.length; i++){
-      var col_name = list_table[i].id;
-      var rule = {
-        field : col_name,
-        order : $('#order-' + col_name).value()
-      };
-      if (col_name === 'entry') {
-        rule.a_tergo = a_tergo;
-      }
-      rules.push(rule);
-    }
-    //dobieramy sie do danych grida
-    $('#scroll').jqGrid('getGridParam', 'postData').sort_rules = $.toJSON(rules);
-    jqgrid.grid.jqGrid('setGridParam', {'setOnComplete' : true});
+    $('#save-sort-order').click(function () {
+        var a_tergo = $('#sort-dialog').find('#entries_a_tergo').value();
+        var list_table = $('#sort-rule-list').find('li');
+        //lista par (nazwa pola - porzadek sortowania)
+        var rules = [];
+        for (var i = 0; i < list_table.length; i++) {
+            var col_name = list_table[i].id;
+            var rule = {
+                field: col_name,
+                order: $('#order-' + col_name).value()
+            };
+            if (col_name === 'entry') {
+                rule.a_tergo = a_tergo;
+            }
+            rules.push(rule);
+        }
+        //dobieramy sie do danych grida
+        $('#scroll').jqGrid('getGridParam', 'postData').sort_rules = $.toJSON(rules);
+        jqgrid.grid.jqGrid('setGridParam', {'setOnComplete': true});
 
-    //zmiany w nagłówkach kolumn
-    jqgrid.refresh_column_headers();
+        //zmiany w nagłówkach kolumn
+        jqgrid.refresh_column_headers();
 
-    $( "#sort-dialog" ).dialog("close");
-    jqgrid.grid.trigger("reloadGrid");
-  });
+        $("#sort-dialog").dialog("close");
+        jqgrid.grid.trigger("reloadGrid");
+    });
 
-  $('#open-sort-dialog').click(function() {
-    $('#sort-dialog').dialog("open");
-    var rules = $.evalJSON($('#scroll').jqGrid(
-      'getGridParam', 'postData').sort_rules);
-    $('#sort-rule-list').find('li').removeClass('ui-state-default');
-    $.each(rules.reverse(), function(i, rule) {
-      var colName = rule.field,
-          sort_row = $('li#' + colName);
-      if ($.isFunction(jqgrid.sort_rule_special_features))
-        jqgrid.sort_rule_special_features(rule);
-      sort_row.addClass('ui-state-default');
-      sort_row.find('select').val(rule.order);
-      $('#sort-rule-list').prepend(sort_row);
+    $('#open-sort-dialog').click(function () {
+        $('#sort-dialog').dialog("open");
+        var rules = $.evalJSON($('#scroll').jqGrid(
+            'getGridParam', 'postData').sort_rules);
+        $('#sort-rule-list').find('li').removeClass('ui-state-default');
+        $.each(rules.reverse(), function (i, rule) {
+            var colName = rule.field,
+                sort_row = $('li#' + colName);
+            if ($.isFunction(jqgrid.sort_rule_special_features))
+                jqgrid.sort_rule_special_features(rule);
+            sort_row.addClass('ui-state-default');
+            sort_row.find('select').val(rule.order);
+            $('#sort-rule-list').prepend(sort_row);
+        });
     });
-  });
 
-  $('#show-columns-button').click(function(){
-    jqgrid.grid.jqGrid('columnChooser', {
-      done: function(perm) {
-        if (perm) {
-          this.jqGrid('remapColumns', perm, true);
-          layout.adjust_grid_width();
-        }
-        var col_model = jqgrid.grid.jqGrid('getGridParam', 'colModel');
-        var col_names = jqgrid.grid.jqGrid('getGridParam', 'colNames');
-        var remap = jqgrid.grid.jqGrid('getGridParam', 'remapColumns');
-        $.ajaxJSON({
-          method: 'post',
-          url: $dj.ajax_save_columns,
-          data: {col_model: col_model, col_names: col_names, remap: remap}
+    $('#show-columns-button').click(function () {
+        jqgrid.grid.jqGrid('columnChooser', {
+            done: function (perm) {
+                if (perm) {
+                    this.jqGrid('remapColumns', perm, true);
+                    layout.adjust_grid_width();
+                }
+                var col_model = jqgrid.grid.jqGrid('getGridParam', 'colModel');
+                var col_names = jqgrid.grid.jqGrid('getGridParam', 'colNames');
+                var remap = jqgrid.grid.jqGrid('getGridParam', 'remapColumns');
+                $.ajaxJSON({
+                    method: 'post',
+                    url: $dj.ajax_save_columns,
+                    data: {col_model: col_model, col_names: col_names, remap: remap}
+                });
+            }
         });
-      }
     });
-  });
 
-  $(document).on('keypress', '.searchFilter input', function(e) {
-    if (e.which === 13) { // enter
-      $(this).change();
-      // powinno być .ui-search, niegroźny byk w jqGrid
-      setTimeout(function () {
-        $('.searchFilter').next().find('.ui-reset').click();}, 100);
-    }
-  });
+    $(document).on('keypress', '.searchFilter input', function (e) {
+        if (e.which === 13) { // enter
+            $(this).change();
+            // powinno być .ui-search, niegroźny byk w jqGrid
+            setTimeout(function () {
+                $('.searchFilter').next().find('.ui-reset').click();
+            }, 100);
+        }
+    });
 
-  jqgrid.init_form_widgets();
-  // brzydko, ale cóż
-  layout.adjust_tabs();
+    jqgrid.init_form_widgets();
+    // brzydko, ale cóż
+    layout.adjust_tabs();
 });
 
-function doSearch(){
-  "use strict";
-  if (!$dj.auto_search)
-    return;
-  if(timeoutHnd)
-    clearTimeout(timeoutHnd);
-  timeoutHnd = setTimeout(findAndScroll, 500);
+function doSearch() {
+    "use strict";
+    if (!$dj.auto_search)
+        return;
+    if (timeoutHnd)
+        clearTimeout(timeoutHnd);
+    timeoutHnd = setTimeout(findAndScroll, 500);
 }
 
-function findAndScroll(){
-  "use strict";
-  var data = jqgrid.grid.jqGrid('getGridParam', 'postData');
-  data.mask = $("#phrase_box").val();
-  // przeładowanie można pominąć jeśli nie jesteśmy w trybie filtrowania
-  if ($dj.filtering_mode) {
-    jqgrid.grid.trigger('reloadGrid');
-  }
-  $.get($dj.ajax_location, data, function(resp) {
-    var selectedRow = resp.selected_id + "";
-    var rowIndex = resp.rowIndex;
-    var recordsCount = resp.records;
-    if (recordsCount > 0) {
-      jqgrid.grid.jqGrid('scrollAndSet', selectedRow, rowIndex, recordsCount);
+function findAndScroll() {
+    "use strict";
+    var data = jqgrid.grid.jqGrid('getGridParam', 'postData');
+    data.mask = $("#phrase_box").val();
+    // przeładowanie można pominąć jeśli nie jesteśmy w trybie filtrowania
+    if ($dj.filtering_mode) {
+        jqgrid.grid.trigger('reloadGrid');
     }
-  });
+    $.get($dj.ajax_location, data, function (resp) {
+        var selectedRow = resp.selected_id + "";
+        var rowIndex = resp.rowIndex;
+        var recordsCount = resp.records;
+        if (recordsCount > 0) {
+            jqgrid.grid.jqGrid('scrollAndSet', selectedRow, rowIndex, recordsCount);
+        }
+    });
 }
 jqgrid.findAndScroll = findAndScroll;
 
 function show_changed() {
-  "use strict";
-  if (!changed) {
-    changed = true;
-    $('#' + jqgrid.edit_form_submit_id).button('enable');
-    $('#' + jqgrid.edit_form_cancel_id).button('enable');
-    $('#edit-tab').html('<strong>Edycja (niezapisane)</strong>');
-  }
+    "use strict";
+    if (!changed) {
+        changed = true;
+        $('#' + jqgrid.edit_form_submit_id).button('enable');
+        $('#' + jqgrid.edit_form_cancel_id).button('enable');
+        $('#edit-tab').html('<strong>Edycja (niezapisane)</strong>');
+        $(window).on('beforeunload', function() {
+            return "Są niezapisane zmiany.";
+        });
+    }
 }
 jqgrid.show_changed = show_changed;
 
 function hide_changed() {
-  "use strict";
-  if (changed) {
-    changed = false;
-    $('#edit-tab').html('Edycja');
-  }
+    "use strict";
+    if (changed) {
+        changed = false;
+        $('#edit-tab').html('Edycja');
+        $(window).off('beforeunload');
+    }
 }
 jqgrid.hide_changed = hide_changed;
diff --git a/media/js/lexeme-view.js b/media/js/lexeme-view.js
index 72fc666..a1013a2 100644
--- a/media/js/lexeme-view.js
+++ b/media/js/lexeme-view.js
@@ -1,1257 +1,1264 @@
 var prompter_ctrl, created;
 
 function init_selection(jq) {
-  "use strict";
-  jq.find('option:selected').addClass('last-selected');
+    "use strict";
+    jq.find('option:selected').addClass('last-selected');
 }
 
 function revert_selection(jq) {
-  "use strict";
-  jq.find('option.last-selected').prop('selected', true);
+    "use strict";
+    jq.find('option.last-selected').prop('selected', true);
 }
 
 function confirm_selection(jq) {
-  "use strict";
-  jq.find('option.last-selected').removeClass('last-selected');
-  jq.find('option:selected').addClass('last-selected');
+    "use strict";
+    jq.find('option.last-selected').removeClass('last-selected');
+    jq.find('option:selected').addClass('last-selected');
 }
 
 function selected_qualifiers_text(num, total, checked) {
-  "use strict";
-  if (num >= 4)
-    return num + ' kwalifikatorów';
-  var grouped = {};
-  $.each(checked, function(i, elem) {
-    var id = elem.value;
-    var vocab = $dj.vocabs[id];
-    if (grouped[vocab] === undefined)
-      grouped[vocab] = [];
-    grouped[vocab].push(elem.title);
-  });
-  var vocab_table = [];
-  var owner = $('#owner-vocabulary').text();
-  if (grouped[owner])
-    vocab_table.push(owner + ': ' + grouped[owner].join(', '));
-  $.each(grouped, function(vocab, qualifiers) {
-    if (vocab !== owner)
-      vocab_table.push(vocab + ': ' + qualifiers.join(', '));
-  });
-  return vocab_table.join('; ');
+    "use strict";
+    if (num >= 4)
+        return num + ' kwalifikatorów';
+    var grouped = {};
+    $.each(checked, function (i, elem) {
+        var id = elem.value;
+        var vocab = $dj.vocabs[id];
+        if (grouped[vocab] === undefined)
+            grouped[vocab] = [];
+        grouped[vocab].push(elem.title);
+    });
+    var vocab_table = [];
+    var owner = $('#owner-vocabulary').text();
+    if (grouped[owner])
+        vocab_table.push(owner + ': ' + grouped[owner].join(', '));
+    $.each(grouped, function (vocab, qualifiers) {
+        if (vocab !== owner)
+            vocab_table.push(vocab + ': ' + qualifiers.join(', '));
+    });
+    return vocab_table.join('; ');
 }
 
 function selected_cvs_text(num, total, checked) {
-  "use strict";
-  if (num >= 4)
-    return num + ' wartości';
-  var values = $.map(checked, function(elem) {
-    return common.strip(elem.title);
-  });
-  return values.join(', ');
+    "use strict";
+    if (num >= 4)
+        return num + ' wartości';
+    var values = $.map(checked, function (elem) {
+        return common.strip(elem.title);
+    });
+    return values.join(', ');
 }
 
 var main_field = 'entry';
 var qualifier_options = {
-  noneSelectedText: 'Wybierz',
+    noneSelectedText: 'Wybierz',
     selectedText: selected_qualifiers_text,//'# kwalifikatorów',
     selectedList: 4,
     header: false,
-    create: function() {
-    "use strict";
-    var select = $(this);
-    var selected = select.val();
-    if (selected) {
-      $.each(selected, function(i, value) {
-        toggle_excluded(select, value, false);
-      });
+    create: function () {
+        "use strict";
+        var select = $(this);
+        var selected = select.val();
+        if (selected) {
+            $.each(selected, function (i, value) {
+                toggle_excluded(select, value, false);
+            });
+        }
+    },
+    click: function (event, ui) {
+        "use strict";
+        toggle_excluded(this, ui.value, !ui.checked);
     }
-  },
-  click: function(event, ui) {
-    "use strict";
-    toggle_excluded(this, ui.value, !ui.checked);
-  }
 };
 
 function list_searchoptions(list) {
-  "use strict";
-  return {
-    searchhidden: true,
-    sopt: ['eq', 'ne'],
-    value: list
-  };
+    "use strict";
+    return {
+        searchhidden: true,
+        sopt: ['eq', 'ne'],
+        value: list
+    };
 }
 
 function list_column(name, displayed, list) {
-  "use strict";
-  return {
-    name: name,
-    index: name,
-    hidden: true,
-    hidedlg: !displayed,
-    sortable: false,
-    searchoptions: list_searchoptions(list),
-    stype: 'select'
-  };
+    "use strict";
+    return {
+        name: name,
+        index: name,
+        hidden: true,
+        hidedlg: !displayed,
+        sortable: false,
+        searchoptions: list_searchoptions(list),
+        stype: 'select'
+    };
 }
 
 function text_column(name) {
-  "use strict";
-  return {
-    name: name,
-    index: name,
-    hidden: true,
-    hidedlg: true,
-    sortable: false,
-    searchoptions: {searchhidden: true}
-  };
+    "use strict";
+    return {
+        name: name,
+        index: name,
+        hidden: true,
+        hidedlg: true,
+        sortable: false,
+        searchoptions: {searchhidden: true}
+    };
 }
 
 function lip_column(name) {
-  "use strict";
-  return {
-    name: name,
-    index: name,
-    hidden: true,
-    sortable: false,
-    searchoptions: {searchhidden: true, sopt: ['eq', 'ne']}
-  };
+    "use strict";
+    return {
+        name: name,
+        index: name,
+        hidden: true,
+        sortable: false,
+        searchoptions: {searchhidden: true, sopt: ['eq', 'ne']}
+    };
 }
 
 function count_column(name) {
-  "use strict";
-  return {
-    name: name,
-    index: name,
-    hidden: true,
-    hidedlg: true,
-    sortable: false,
-    searchoptions: {searchhidden: true, sopt: ['eq', 'ge', 'le']}
-  };
+    "use strict";
+    return {
+        name: name,
+        index: name,
+        hidden: true,
+        hidedlg: true,
+        sortable: false,
+        searchoptions: {searchhidden: true, sopt: ['eq', 'ge', 'le']}
+    };
 }
 
 $.extend(jqgrid, {
-  main_field: main_field,
-  initialColModel: [
-    {name: 'id', index: 'id', search: false, hidden: true},
-    {name: 'entry',index: 'entry'},
-    {
-      name: 'part_of_speech',
-      index: 'part_of_speech',
-      searchoptions: list_searchoptions($dj.parts_of_speech),
-      stype: 'select'
-    },
-    lip_column('pattern_name'),
-    count_column('pattern_count'),
-    lip_column('inflection_characteristic'),
-    count_column('ic_count'),
-    {
-      name: 'form',
-      index: 'form',
-      hidden: true,
-      hidedlg: true,
-      sortable: false,
-      searchoptions: {searchhidden: true}
-    },
-    list_column('containing_vocabulary', true, $dj.visible_vocabularies),
-    list_column('owner_vocabulary', true, $dj.visible_vocabularies),
-    list_column('status', true, $dj.status_options),
-    text_column('comment'),
-    list_column('lexeme_qualifier', false, $dj.qualifier_options),
-    list_column('lip_qualifier', false, $dj.qualifier_options),
-    list_column('qualifier', false, $dj.qualifier_options),
-    list_column('classification_value', false, $dj.cv_options),
-    text_column('gloss'),
-    text_column('note'),
-    list_column('cr_type', false, $dj.cr_type_options)
-  ],
-  initialColNames: [
-    'Id', 'Hasło','Część mowy', 'Wzór', 'Liczba wzorów', 'Char. fleks.',
-    'Liczba char. fleks.', 'Forma', 'Słownik używający', 'Słownik właściciel',
-    'Status', 'Komentarz', 'Kwal. leksemu', 'Kwal. odmieniasia',
-    'Kwal. przy dow. formie', 'Wartość klasyfikacji', 'Glosa', 'Nota',
-    'Typ odsyłacza'
-  ],
-  initial_sort_rules: [{field: main_field, order: 'asc', a_tergo: false}],
-  grid_caption: "Leksemy",
-  edit_form_id: 'lexeme-edit-form',
-  edit_form_cancel_id: 'lexeme-edit-cancel',
-  edit_form_submit_id: 'lexeme-edit-submit',
-  reverse_exclusion_classes: {}
+    main_field: main_field,
+    initialColModel: [
+        {name: 'id', index: 'id', search: false, hidden: true},
+        {name: 'entry', index: 'entry'},
+        {
+            name: 'part_of_speech',
+            index: 'part_of_speech',
+            searchoptions: list_searchoptions($dj.parts_of_speech),
+            stype: 'select'
+        },
+        lip_column('pattern_name'),
+        count_column('pattern_count'),
+        lip_column('inflection_characteristic'),
+        count_column('ic_count'),
+        {
+            name: 'form',
+            index: 'form',
+            hidden: true,
+            hidedlg: true,
+            sortable: false,
+            searchoptions: {searchhidden: true}
+        },
+        list_column('containing_vocabulary', true, $dj.visible_vocabularies),
+        list_column('owner_vocabulary', true, $dj.visible_vocabularies),
+        list_column('status', true, $dj.status_options),
+        text_column('comment'),
+        list_column('lexeme_qualifier', false, $dj.qualifier_options),
+        list_column('lip_qualifier', false, $dj.qualifier_options),
+        list_column('qualifier', false, $dj.qualifier_options),
+        list_column('classification_value', false, $dj.cv_options),
+        text_column('gloss'),
+        text_column('note'),
+        list_column('cr_type', false, $dj.cr_type_options)
+    ],
+    initialColNames: [
+        'Id', 'Hasło', 'Część mowy', 'Wzór', 'Liczba wzorów', 'Char. fleks.',
+        'Liczba char. fleks.', 'Forma', 'Słownik używający', 'Słownik właściciel',
+        'Status', 'Komentarz', 'Kwal. leksemu', 'Kwal. odmieniasia',
+        'Kwal. przy dow. formie', 'Wartość klasyfikacji', 'Glosa', 'Nota',
+        'Typ odsyłacza'
+    ],
+    initial_sort_rules: [
+        {field: main_field, order: 'asc', a_tergo: false}
+    ],
+    grid_caption: "Leksemy",
+    edit_form_id: 'lexeme-edit-form',
+    edit_form_cancel_id: 'lexeme-edit-cancel',
+    edit_form_submit_id: 'lexeme-edit-submit',
+    reverse_exclusion_classes: {}
 });
 var deleted, deleted_cr;
 $dj.reverse_exclusion_classes = {};
 
-$.each($dj.exclusion_classes, function(ec, qualifiers) {
-  "use strict";
-  $.each(qualifiers, function(i, q_id) {
-    $dj.reverse_exclusion_classes[q_id] = ec;
-  });
+$.each($dj.exclusion_classes, function (ec, qualifiers) {
+    "use strict";
+    $.each(qualifiers, function (i, q_id) {
+        $dj.reverse_exclusion_classes[q_id] = ec;
+    });
 });
 
 function toggle_excluded(select, value, enable) {
-  "use strict";
-  var ec = $dj.reverse_exclusion_classes[Number(value)],
-      values = $dj.exclusion_classes[ec];
-  if (values)
-    $.each(values, function(i, v) {
-      if (v !== Number(value))
-        common.multiselect_toggle(select, v, enable);
-    });
+    "use strict";
+    var ec = $dj.reverse_exclusion_classes[Number(value)],
+        values = $dj.exclusion_classes[ec];
+    if (values)
+        $.each(values, function (i, v) {
+            if (v !== Number(value))
+                common.multiselect_toggle(select, v, enable);
+        });
 }
 
 function sort_rule_special_features(rule) {
-  "use strict";
-  $('#entries_a_tergo').prop('checked', rule.a_tergo);
+    "use strict";
+    $('#entries_a_tergo').prop('checked', rule.a_tergo);
 }
 jqgrid.sort_rule_special_features = sort_rule_special_features;
 
 function prepare_sort_rules(sort_rules, old_sort_rules) {
-  "use strict";
-  if (sort_rules[0].field === 'entry') {
-    var a_tergo = false;
-    $.each(old_sort_rules, function(i, rule) {
-      if (rule.field === 'entry') {
-        a_tergo = rule.a_tergo;
-        return false;
-      }
-      return null;
-    });
-    sort_rules[0].a_tergo = a_tergo;
-  }
+    "use strict";
+    if (sort_rules[0].field === 'entry') {
+        var a_tergo = false;
+        $.each(old_sort_rules, function (i, rule) {
+            if (rule.field === 'entry') {
+                a_tergo = rule.a_tergo;
+                return false;
+            }
+            return null;
+        });
+        sort_rules[0].a_tergo = a_tergo;
+    }
 }
 jqgrid.prepare_sort_rules = prepare_sort_rules;
 
 function get_pos() {
-  "use strict";
-  return $('#id_part_of_speech').val();
+    "use strict";
+    return $('#id_part_of_speech').val();
 }
 
 function get_ics() {
-  "use strict";
-  return $('.inflection-characteristic').map(function(i, el) {
-    return parseInt($(el).val(), 10);}).toArray();
+    "use strict";
+    return $('.inflection-characteristic').map(function (i, el) {
+        return parseInt($(el).val(), 10);
+    }).toArray();
 }
 
 function get_ic_symbols() {
-  "use strict";
-  return $('.inflection-characteristic option:selected').map(function(i, el) {
-    return $(el).text();}).toArray();
+    "use strict";
+    return $('.inflection-characteristic option:selected').map(function (i, el) {
+        return $(el).text();
+    }).toArray();
 }
 
 function get_entry() {
-  "use strict";
-  return $('#id_entry').val();
+    "use strict";
+    return $('#id_entry').val();
 }
 
 function get_owner() {
-  "use strict";
-  return $('#id_new_owner').val();
+    "use strict";
+    return $('#id_new_owner').val();
 }
 
 function join_attrs(attrs) {
-  "use strict";
-  return $.map(attrs, function(attr) {
-    return $("[for='id_attr" + attr + "-value']").text().replace(':', '');
-  }).join(', ');
+    "use strict";
+    return $.map(attrs,function (attr) {
+        return $("[for='id_attr" + attr + "-value']").text().replace(':', '');
+    }).join(', ');
 }
 
 function join_classifications(clas_ids) {
-  "use strict";
-  return $.map(clas_ids, function(c_id) {
-    return $("[for='id_cl" + c_id + "-values']").text().replace(':', '');
-  }).join(', ');
+    "use strict";
+    return $.map(clas_ids,function (c_id) {
+        return $("[for='id_cl" + c_id + "-values']").text().replace(':', '');
+    }).join(', ');
 }
 
 function init_form_widgets() {
-  "use strict";
-  $(document).on('click', '.lip-row span.remove', function() {
-    var li = $(this).closest('li');
-    var name = $('input', li)[0].name;
-    var ic_symbol = li.find('.inflection-characteristic option:selected').text();
-    var ics = get_ic_symbols();
-    ics.splice(ics.indexOf(ic_symbol), 1);
-    var stale_attrs = check_attrs(ics);
-    if (stale_attrs.length > 0) {
-      if (!window.confirm("Atrybuty: " + join_attrs(stale_attrs) +
-        ' zostaną usunięte. Kontynouwać?')) {
-        return;
-      }
-    }
-    if (name.substring(0,7) !== 'lip_add')
-      deleted.push(name.split('-')[0]);
-    li.remove();
-    jqgrid.show_changed();
-    $('#table-preview').html('');
-    reload_attributes();
-  });
-  $(document).on('click', '#add-row', function() {
-    var id = lexeme_id();
-    var new_row = $(get_new_row_html(id));
-    init_selection(new_row.find('.inflection-characteristic'));
-    var pattern_list = $('#pattern-list');
-    pattern_list.append(new_row);
-    var elem = pattern_list.find('.lip-qualifiers').last();
-    elem.multiselect2(qualifier_options);
-    elem.next().width('220px');
-    jqgrid.show_changed();
-  });
-
-  $(document).on('click', '.cr-row span.remove', function() {
-    var li = $(this).closest('li');
-    if (!li.hasClass('cr-add'))
-      deleted_cr.push(Number(li[0].id.split('-')[1]));
-    li.remove();
-    jqgrid.show_changed();
-  });
-  $(document).on('click', '#add-cr-row', function() {
-    var id = lexeme_id();
-    var pos = get_pos();
-    var new_row = $(get_new_cr_row_html(id, pos));
-    $('#cr-list').append(new_row);
-    jqgrid.show_changed();
-  });
-
-  var update_preview = function() {
-    var lip_row = $(this).closest('.lip-row');
-    if (lip_row.hasClass('lip-row-active')) {
-      set_active_lip_row.call(lip_row);
-    }
-  };
-  $(document).on(
-    'change', '#' + jqgrid.edit_form_id + ' input', update_preview);
-  $(document).on(
-    'change', '#' + jqgrid.edit_form_id + ' textarea', update_preview);
-  $(document).on(
-    'change', '#' + jqgrid.edit_form_id + ' select', update_preview);
-
-  $(document).on('click', '.lip-row', set_active_lip_row);
-
-  $(document).on('click', '#lexeme-edit-delete', delete_lexeme);
-
-  $(document).on('change', '.cr-add .entry', set_cr_homonym_number);
-  $(document).on('click', '.cr-add .homonym-number', set_cr_homonym_number);
-
-  $("#load-filter-dialog").dialog({
-    autoOpen: false,
-    width: 'auto',
-    modal: true
-  });
-  $('#choose-homonym-dialog').dialog({
-    autoOpen: false,
-    width: 'auto',
-    modal: true
-  });
-  $('#prompter-dialog').dialog({
-    autoOpen: false,
-    width: 'auto',
-    modal: true,
-    buttons: [
-      {
-        text: "Anuluj",
-        click: function() { $(this).dialog("close"); }
-      },
-      {
-        text: "Wybierz",
-        click: input_prompter_pattern
-      }
-    ]
-  });
-  $('#action-button').click(function() {
-    $('#group-action-dialog').dialog("open");
-  });
-  var add_action = $('#add-action');
-  add_action.click(new_action_row);
-  $(document).on('change', '.field-choice', update_action_row);
-  $(document).on('click', '.delete-action-row', function() {
-    $(this).closest('tr').remove();
-  });
-  $('#group-action-dialog').dialog({
-    autoOpen: false,
-    modal: true,
-    width: 'auto',
-    buttons: [
-      {
-        text: "Wykonaj",
-        click: execute_actions
-      }
-    ]
-  });
-  add_action.click();
-  $(document).on('click', 'button.prompter', display_prompter);
-  $(document).on('click', '.prompter-row', set_active_prompter_row);
-  $(document).on('click', '#prompter-checkboxes :checkbox', reload_prompter);
-
-  $('#add-button').click(add_lexeme);
-  $('#default-owner-dialog').dialog({
-    autoOpen: false,
-    modal: true,
-    buttons: [
-      {
-        text: "Anuluj",
-        click: function() { $(this).dialog("close"); }
-      },
-      {
-        text: "Wybierz",
-        click: function() {
-          var value = $('#default-owner').find(':checked').val();
-          if (value) {
-            set_default_owner(value);
-            $(this).dialog("close");
-            make_new_lexeme();
-          }
+    "use strict";
+    $(document).on('click', '.lip-row span.remove', function () {
+        var li = $(this).closest('li');
+        var name = $('input', li)[0].name;
+        var ic_symbol = li.find('.inflection-characteristic option:selected').text();
+        var ics = get_ic_symbols();
+        ics.splice(ics.indexOf(ic_symbol), 1);
+        var stale_attrs = check_attrs(ics);
+        if (stale_attrs.length > 0) {
+            if (!window.confirm("Atrybuty: " + join_attrs(stale_attrs) +
+                ' zostaną usunięte. Kontynouwać?')) {
+                return;
+            }
         }
-      }
-    ]
-  });
-
-  $(document).on('click', '#move-lexeme .label', function() {
-    $('#move-lexeme').toggleClass('move-hidden');
-  });
-  $(document).on('change', '#id_part_of_speech', check_pos);
-  $(document).on('change', '#id_new_owner', function() {
-    var stale_classifications = check_classifications(), confirmed;
-    if (stale_classifications.length > 0) {
-      confirmed = window.confirm(
-        'Zostaną usunięte klasyfikacje: ' +
-          join_classifications(stale_classifications) +  '. Kontynuować?');
-      if (!confirmed) {
-        revert_selection($(this));
-      }
-    }
-    if (confirmed || stale_classifications.length === 0) {
-      confirm_selection($(this));
-      reload_classifications();
-    }
-  });
-  $(document).on('change', '.inflection-characteristic', function() {
-    var new_ics = get_ic_symbols();
-    var stale_attrs = check_attrs(new_ics);
-    var confirmed;
-    if (stale_attrs.length > 0) {
-      confirmed = window.confirm("Atrybuty: " + join_attrs(stale_attrs) +
-        ' zostaną usunięte. Kontynouwać?');
-      if (!confirmed) {
-        revert_selection($(this));
-      }
-    }
-    if (confirmed || stale_attrs.length === 0) {
-      confirm_selection($(this));
-      reload_attributes();
-    }
-  });
-  $(document).on('keyup', '#id_entry', show_homonym_count);
+        if (name.substring(0, 7) !== 'lip_add')
+            deleted.push(name.split('-')[0]);
+        li.remove();
+        jqgrid.show_changed();
+        $('#table-preview').html('');
+        reload_attributes();
+    });
+    $(document).on('click', '#add-row', function () {
+        var id = lexeme_id();
+        var new_row = $(get_new_row_html(id));
+        init_selection(new_row.find('.inflection-characteristic'));
+        var pattern_list = $('#pattern-list');
+        pattern_list.append(new_row);
+        var elem = pattern_list.find('.lip-qualifiers').last();
+        elem.multiselect2(qualifier_options);
+        elem.next().width('220px');
+        jqgrid.show_changed();
+    });
+
+    $(document).on('click', '.cr-row span.remove', function () {
+        var li = $(this).closest('li');
+        if (!li.hasClass('cr-add'))
+            deleted_cr.push(Number(li[0].id.split('-')[1]));
+        li.remove();
+        jqgrid.show_changed();
+    });
+    $(document).on('click', '#add-cr-row', function () {
+        var id = lexeme_id();
+        var pos = get_pos();
+        var new_row = $(get_new_cr_row_html(id, pos));
+        $('#cr-list').append(new_row);
+        jqgrid.show_changed();
+    });
+
+    var update_preview = function () {
+        var lip_row = $(this).closest('.lip-row');
+        if (lip_row.hasClass('lip-row-active')) {
+            set_active_lip_row.call(lip_row);
+        }
+    };
+    $(document).on(
+        'change', '#' + jqgrid.edit_form_id + ' input', update_preview);
+    $(document).on(
+        'change', '#' + jqgrid.edit_form_id + ' textarea', update_preview);
+    $(document).on(
+        'change', '#' + jqgrid.edit_form_id + ' select', update_preview);
+
+    $(document).on('click', '.lip-row', set_active_lip_row);
+
+    $(document).on('click', '#lexeme-edit-delete', delete_lexeme);
+
+    $(document).on('change', '.cr-add .entry', set_cr_homonym_number);
+    $(document).on('click', '.cr-add .homonym-number', set_cr_homonym_number);
+
+    $("#load-filter-dialog").dialog({
+        autoOpen: false,
+        width: 'auto',
+        modal: true
+    });
+    $('#choose-homonym-dialog').dialog({
+        autoOpen: false,
+        width: 'auto',
+        modal: true
+    });
+    $('#prompter-dialog').dialog({
+        autoOpen: false,
+        width: 'auto',
+        modal: true,
+        buttons: [
+            {
+                text: "Anuluj",
+                click: function () {
+                    $(this).dialog("close");
+                }
+            },
+            {
+                text: "Wybierz",
+                click: input_prompter_pattern
+            }
+        ]
+    });
+    $('#action-button').click(function () {
+        $('#group-action-dialog').dialog("open");
+    });
+    var add_action = $('#add-action');
+    add_action.click(new_action_row);
+    $(document).on('change', '.field-choice', update_action_row);
+    $(document).on('click', '.delete-action-row', function () {
+        $(this).closest('tr').remove();
+    });
+    $('#group-action-dialog').dialog({
+        autoOpen: false,
+        modal: true,
+        width: 'auto',
+        buttons: [
+            {
+                text: "Wykonaj",
+                click: execute_actions
+            }
+        ]
+    });
+    add_action.click();
+    $(document).on('click', 'button.prompter', display_prompter);
+    $(document).on('click', '.prompter-row', set_active_prompter_row);
+    $(document).on('click', '#prompter-checkboxes :checkbox', reload_prompter);
+
+    $('#add-button').click(add_lexeme);
+    $('#default-owner-dialog').dialog({
+        autoOpen: false,
+        modal: true,
+        buttons: [
+            {
+                text: "Anuluj",
+                click: function () {
+                    $(this).dialog("close");
+                }
+            },
+            {
+                text: "Wybierz",
+                click: function () {
+                    var value = $('#default-owner').find(':checked').val();
+                    if (value) {
+                        set_default_owner(value);
+                        $(this).dialog("close");
+                        make_new_lexeme();
+                    }
+                }
+            }
+        ]
+    });
+
+    $(document).on('click', '#move-lexeme .label', function () {
+        $('#move-lexeme').toggleClass('move-hidden');
+    });
+    $(document).on('change', '#id_part_of_speech', check_pos);
+    $(document).on('change', '#id_new_owner', function () {
+        var stale_classifications = check_classifications(), confirmed;
+        if (stale_classifications.length > 0) {
+            confirmed = window.confirm(
+                'Zostaną usunięte klasyfikacje: ' +
+                    join_classifications(stale_classifications) + '. Kontynuować?');
+            if (!confirmed) {
+                revert_selection($(this));
+            }
+        }
+        if (confirmed || stale_classifications.length === 0) {
+            confirm_selection($(this));
+            reload_classifications();
+        }
+    });
+    $(document).on('change', '.inflection-characteristic', function () {
+        var new_ics = get_ic_symbols();
+        var stale_attrs = check_attrs(new_ics);
+        var confirmed;
+        if (stale_attrs.length > 0) {
+            confirmed = window.confirm("Atrybuty: " + join_attrs(stale_attrs) +
+                ' zostaną usunięte. Kontynouwać?');
+            if (!confirmed) {
+                revert_selection($(this));
+            }
+        }
+        if (confirmed || stale_attrs.length === 0) {
+            confirm_selection($(this));
+            reload_attributes();
+        }
+    });
+    $(document).on('keyup', '#id_entry', show_homonym_count);
 }
 jqgrid.init_form_widgets = init_form_widgets;
 
 function lexeme_id() {
-  "use strict";
-  return $('#' + jqgrid.edit_form_id).find('input[name=id]').value();
+    "use strict";
+    return $('#' + jqgrid.edit_form_id).find('input[name=id]').value();
 }
 
 // TODO zachować wybrane wartości
 function reload_classifications() {
-  "use strict";
-  var data = {
-    lexeme_id: lexeme_id(),
-    vocab_id: get_owner(),
-    pos: get_pos()
-  };
-  $.ajaxJSON({
-    method: 'get',
-    url: $dj.ajax_classification_forms,
-    data: data,
-    dest: $('#classifications'),
-    callback: init_classification_forms,
-    description: "Przeładowanie klasyfikacji"
-  });
+    "use strict";
+    var data = {
+        lexeme_id: lexeme_id(),
+        vocab_id: get_owner(),
+        pos: get_pos()
+    };
+    $.ajaxJSON({
+        method: 'get',
+        url: $dj.ajax_classification_forms,
+        data: data,
+        dest: $('#classifications'),
+        callback: init_classification_forms,
+        description: "Przeładowanie klasyfikacji"
+    });
 }
 
 function reload_attributes() {
-  "use strict";
-  // TODO wartości atrybutów...
-  var data = {
-    lexeme_id: lexeme_id(),
-    pos: get_pos(),
-    ics: get_ics()
-  };
-  $.ajaxJSON({
-    method: 'get',
-    url: $dj.ajax_extra_attributes,
-    data: data,
-    dest: $('#extra-attributes'),
-    description: "Przeładowanie atrybutów"
-  });
+    "use strict";
+    // TODO wartości atrybutów...
+    var data = {
+        lexeme_id: lexeme_id(),
+        pos: get_pos(),
+        ics: get_ics()
+    };
+    $.ajaxJSON({
+        method: 'get',
+        url: $dj.ajax_extra_attributes,
+        data: data,
+        dest: $('#extra-attributes'),
+        description: "Przeładowanie atrybutów"
+    });
 }
 
 function load_content(id, is_created) {
-  "use strict";
-  $.ajaxJSON({
-    method: 'get',
-    url: $dj.ajax_edit_form,
-    dest: $('#edit'),
-    data: {id: id},
-    callback: function() {
-      edit_form_init();
-      created = Boolean(is_created);
-    }
-  });
-  $.ajaxJSON({
-    method: 'get',
-    url: $dj.ajax_inflection_tables,
-    dest: $('#variant0'),
-    data: {lexeme_id: id, variant: 0}
-  });
-  $.ajaxJSON({
-    method: 'get',
-    url: $dj.ajax_inflection_tables,
-    dest: $('#variant1'),
-    data: {lexeme_id: id, variant: 1}
-  });
-  $.ajaxJSON({
-    method: 'get',
-    url: $dj.ajax_odm_forms,
-    dest: $('#odm'),
-    data: {lexeme_id: id}
-  });
-  $.ajaxJSON({
-    method: 'get',
-    url: $dj.ajax_history_table,
-    dest: $('#history'),
-    data: {lexeme_id: id}
-  });
-  jqgrid.grid.jqGrid('setGridParam', {'lastSelectedId' : id});
+    "use strict";
+    $.ajaxJSON({
+        method: 'get',
+        url: $dj.ajax_edit_form,
+        dest: $('#edit'),
+        data: {id: id},
+        callback: function () {
+            edit_form_init();
+            created = Boolean(is_created);
+        }
+    });
+    $.ajaxJSON({
+        method: 'get',
+        url: $dj.ajax_inflection_tables,
+        dest: $('#variant0'),
+        data: {lexeme_id: id, variant: 0}
+    });
+    $.ajaxJSON({
+        method: 'get',
+        url: $dj.ajax_inflection_tables,
+        dest: $('#variant1'),
+        data: {lexeme_id: id, variant: 1}
+    });
+    $.ajaxJSON({
+        method: 'get',
+        url: $dj.ajax_odm_forms,
+        dest: $('#odm'),
+        data: {lexeme_id: id}
+    });
+    $.ajaxJSON({
+        method: 'get',
+        url: $dj.ajax_history_table,
+        dest: $('#history'),
+        data: {lexeme_id: id}
+    });
+    jqgrid.grid.jqGrid('setGridParam', {'lastSelectedId': id});
 }
 jqgrid.load_content = load_content;
 
 function init_classification_forms() {
-  "use strict";
-  $('.classification-values').multiselect2({
-    noneSelectedText: 'Wybierz',
-    selectedText: selected_cvs_text,//'# wartości',
-    selectedList: 4,
-    header: false
-  });
+    "use strict";
+    $('.classification-values').multiselect2({
+        noneSelectedText: 'Wybierz',
+        selectedText: selected_cvs_text,//'# wartości',
+        selectedList: 4,
+        header: false
+    });
 }
 
 function edit_form_init() {
-  "use strict";
-  $('button', '#edit').button();
-  $('#pattern-list.editable').sortable().sortable({
-    change: function() {
-      jqgrid.show_changed();
-    }
-  });
-  //$('#pattern-list').disableSelection();
-  $('.lip-row', '#pattern-list').first().click();
-  $('#id_vocabularies').multiselect2({
-    noneSelectedText: 'Wybierz słowniki',
-    selectedText: '# słowników',
-    selectedList: 4,
-    header: false
-  });
-  $('#id_qualifiers').multiselect2(qualifier_options);
-  $('.lip-qualifiers').multiselect2(qualifier_options).next().width('220px');
-  init_classification_forms();
-  $('button.prompter').button();
-  var new_owner_elem = $('#id_new_owner');
-  var owner = new_owner_elem.find(':selected').text();
-  var bold_owner = function(text) {
-    if (text === owner)
-      return '<strong>' + text + '</strong>';
-    else
-      return text;
-  };
-  new_owner_elem.selectmenu({
-    width:'auto', style: 'popup', format: bold_owner});
-  show_homonym_count();
-  deleted = [];
-  deleted_cr = [];
-  created = false;
-  init_selection($('#id_part_of_speech'));
-  init_selection($('.inflection-characteristic'));
-  init_selection(new_owner_elem);
-  jqgrid.hide_changed();
-  if (jqgrid.ctrl)
-    jqgrid.ctrl.remove();
+    "use strict";
+    $('button', '#edit').button();
+    $('#pattern-list.editable').sortable().sortable({
+        change: function () {
+            jqgrid.show_changed();
+        }
+    });
+    //$('#pattern-list').disableSelection();
+    $('.lip-row', '#pattern-list').first().click();
+    $('#id_vocabularies').multiselect2({
+        noneSelectedText: 'Wybierz słowniki',
+        selectedText: '# słowników',
+        selectedList: 4,
+        header: false
+    });
+    $('#id_qualifiers').multiselect2(qualifier_options);
+    $('.lip-qualifiers').multiselect2(qualifier_options).next().width('220px');
+    init_classification_forms();
+    $('button.prompter').button();
+    var new_owner_elem = $('#id_new_owner');
+    var owner = new_owner_elem.find(':selected').text();
+    var bold_owner = function (text) {
+        if (text === owner)
+            return '<strong>' + text + '</strong>';
+        else
+            return text;
+    };
+    new_owner_elem.selectmenu({
+        width: 'auto', style: 'popup', format: bold_owner});
+    show_homonym_count();
+    deleted = [];
+    deleted_cr = [];
+    created = false;
+    init_selection($('#id_part_of_speech'));
+    init_selection($('.inflection-characteristic'));
+    init_selection(new_owner_elem);
+    jqgrid.hide_changed();
+    if (jqgrid.ctrl)
+        jqgrid.ctrl.remove();
 }
 jqgrid.edit_form_init = edit_form_init;
 
-jqgrid.edit_form_submit = function() {
-  "use strict";
-  var this_form = $(this);
-  var form_data = this_form.serializeArray();
-  form_data.push({name: 'deleted', value: deleted});
-  form_data.push({name: 'deleted_cr', value: deleted_cr});
-  var vocabularies = [];
-  var qualifiers = [];
-  var cvs = {};
-  var multi_attrs = {};
-  form_data = $.map(form_data, function(elem) {
-    if (elem.name !== 'vocabularies' && elem.name !== 'qualifiers' &&
-        !(/^cl[0-9]+-values$/.test(elem.name)) &&
-        !(/^attrmulti[0-9]+-value$/.test(elem.name)))
-      return elem;
-    else {
-      if (elem.name === 'vocabularies')
-        vocabularies.push(elem.value);
-      if (elem.name === 'qualifiers')
-        qualifiers.push(elem.value);
-      if (/^cl[0-9]+-values$/.test(elem.name)) {
-        if (cvs[elem.name] === undefined)
-          cvs[elem.name] = [];
-        cvs[elem.name].push(elem.value);
-      }
-      if (/^attrmulti[0-9]+-value$/.test(elem.name)) {
-        if (multi_attrs[elem.name] === undefined)
-          multi_attrs[elem.name] = [];
-        multi_attrs[elem.name].push(elem.value);
-      }
-      return null;
-    }
-  });
-  form_data.push({name: 'vocabularies', value: vocabularies});
-  form_data.push({name: 'qualifiers', value: qualifiers});
-  $.each(cvs, function(name, value) {
-    form_data.push({name: name, value: value});
-  });
-  $.each(multi_attrs, function(name, value) {
-    form_data.push({name: name, value: value});
-  });
-  form_data.push({name: 'classification_values', value: cvs});
-  jqgrid.ctrl = getBusyOverlay(
-    'viewport',
-    {color: 'black', opacity: 0.5},
-    {size: 100});
-  var result = $.ajaxJSON({
-    method: 'post',
-    url: $dj.ajax_update_lexeme,
-    save: true,
-    data: {
-      form_data: form_data,
-      mask: jqgrid.grid.jqGrid('getGridParam', 'postData').mask
-    },
-    description: "Zapisanie zmian",
-    callback: function() {
-      jqgrid.hide_changed();
-      jqgrid.grid.jqGrid('setGridParam', {'setOnComplete' : true});
-      jqgrid.grid.trigger("reloadGrid");
-      load_content(lexeme_id());
-    },
-    error_callback: function(xhr, status, error) {
-      common.error_alert(status + ': ' + error);
-      if (jqgrid.ctrl)
-        jqgrid.ctrl.remove();
-    },
-    bad_data_callback: function() {
-      if (jqgrid.ctrl)
+jqgrid.edit_form_submit = function () {
+    "use strict";
+    var this_form = $(this);
+    var form_data = this_form.serializeArray();
+    form_data.push({name: 'deleted', value: deleted});
+    form_data.push({name: 'deleted_cr', value: deleted_cr});
+    var vocabularies = [];
+    var qualifiers = [];
+    var cvs = {};
+    var multi_attrs = {};
+    form_data = $.map(form_data, function (elem) {
+        if (elem.name !== 'vocabularies' && elem.name !== 'qualifiers' && !(/^cl[0-9]+-values$/.test(elem.name)) && !(/^attrmulti[0-9]+-value$/.test(elem.name)))
+            return elem;
+        else {
+            if (elem.name === 'vocabularies')
+                vocabularies.push(elem.value);
+            if (elem.name === 'qualifiers')
+                qualifiers.push(elem.value);
+            if (/^cl[0-9]+-values$/.test(elem.name)) {
+                if (cvs[elem.name] === undefined)
+                    cvs[elem.name] = [];
+                cvs[elem.name].push(elem.value);
+            }
+            if (/^attrmulti[0-9]+-value$/.test(elem.name)) {
+                if (multi_attrs[elem.name] === undefined)
+                    multi_attrs[elem.name] = [];
+                multi_attrs[elem.name].push(elem.value);
+            }
+            return null;
+        }
+    });
+    form_data.push({name: 'vocabularies', value: vocabularies});
+    form_data.push({name: 'qualifiers', value: qualifiers});
+    $.each(cvs, function (name, value) {
+        form_data.push({name: name, value: value});
+    });
+    $.each(multi_attrs, function (name, value) {
+        form_data.push({name: name, value: value});
+    });
+    form_data.push({name: 'classification_values', value: cvs});
+    jqgrid.ctrl = getBusyOverlay(
+        'viewport',
+        {color: 'black', opacity: 0.5},
+        {size: 100});
+    var result = $.ajaxJSON({
+        method: 'post',
+        url: $dj.ajax_update_lexeme,
+        save: true,
+        data: {
+            form_data: form_data,
+            mask: jqgrid.grid.jqGrid('getGridParam', 'postData').mask
+        },
+        description: "Zapisanie zmian",
+        callback: function () {
+            jqgrid.hide_changed();
+            jqgrid.grid.jqGrid('setGridParam', {'setOnComplete': true});
+            jqgrid.grid.trigger("reloadGrid");
+            load_content(lexeme_id());
+        },
+        error_callback: function (xhr, status, error) {
+            common.error_alert(status + ': ' + error);
+            if (jqgrid.ctrl)
+                jqgrid.ctrl.remove();
+        },
+        bad_data_callback: function () {
+            if (jqgrid.ctrl)
+                jqgrid.ctrl.remove();
+            return true;
+        }
+    });
+    if (result === false && jqgrid.ctrl) {
         jqgrid.ctrl.remove();
-      return true;
     }
-  });
-  if (result === false && jqgrid.ctrl) {
-    jqgrid.ctrl.remove();
-  }
-  return false;
+    return false;
 };
 
-function before_save(){
-  "use strict";
-  // sprawdzić wzór z charflem
-  var ok = true;
-  $('.lip-row').each(function() {
-    var ic = $(this).find('select.inflection-characteristic').val();
-    var pattern = $(this).find('input.pattern').val();
-    var result = $.ajax({
-      type: 'get',
-      url: $dj.ajax_check_pattern,
-      data: {pattern_name: pattern, ic_id: ic},
-      async: false
-    }).responseText;
-    if ($.parseJSON(result).answer !== 'yes')
-      ok = false;
-  });
-  return (ok ||
-    window.confirm("Wzór nie pasuje do charakterystyki - na pewno zapisać?"));
+function before_save() {
+    "use strict";
+    // sprawdzić wzór z charflem
+    var ok = true;
+    $('.lip-row').each(function () {
+        var ic = $(this).find('select.inflection-characteristic').val();
+        var pattern = $(this).find('input.pattern').val();
+        var result = $.ajax({
+            type: 'get',
+            url: $dj.ajax_check_pattern,
+            data: {pattern_name: pattern, ic_id: ic},
+            async: false
+        }).responseText;
+        if ($.parseJSON(result).answer !== 'yes')
+            ok = false;
+    });
+    return (ok ||
+        window.confirm("Wzór nie pasuje do charakterystyki - na pewno zapisać?"));
 }
 
 var new_row_counter = 1; // potrzebne tylko dla niepowtarzalności idów
 function get_new_row_html(id) {
-  "use strict";
-  var new_row_html = $.ajaxJSON({
-    method: 'get',
-    url: $dj.ajax_new_lip_row,
-    data: {lexeme_id: id, pos_id: get_pos(), num: new_row_counter},
-    async: false // w zasadzie się tak nie powinno robić
-  }).html;
-  new_row_counter++;
-  return new_row_html;
+    "use strict";
+    var new_row_html = $.ajaxJSON({
+        method: 'get',
+        url: $dj.ajax_new_lip_row,
+        data: {lexeme_id: id, pos_id: get_pos(), num: new_row_counter},
+        async: false // w zasadzie się tak nie powinno robić
+    }).html;
+    new_row_counter++;
+    return new_row_html;
 }
 
 var new_cr_row_counter = 1; // potrzebne tylko dla niepowtarzalności idów
 function get_new_cr_row_html(id, pos) {
-  "use strict";
-  var new_row_html = $.ajax({
-    type: 'get',
-    url: $dj.ajax_new_cr_row,
-    data: {id: id, pos_id: pos},
-    async: false
-  }).responseText;
-  var row_html = new_row_html.replace(/NUM/g, new_cr_row_counter);
-  new_cr_row_counter++;
-  return row_html;
+    "use strict";
+    var new_row_html = $.ajax({
+        type: 'get',
+        url: $dj.ajax_new_cr_row,
+        data: {id: id, pos_id: pos},
+        async: false
+    }).responseText;
+    var row_html = new_row_html.replace(/NUM/g, new_cr_row_counter);
+    new_cr_row_counter++;
+    return row_html;
 }
 
-var set_active_lip_row = function() {
-  "use strict";
-  $('.lip-row-active').removeClass('lip-row-active ui-state-active');
-  $(this).addClass('lip-row-active ui-state-active');
-  // tabelka
-  var data = {
-    lexeme_id: lexeme_id(),
-    entry: get_entry(),
-    pattern: $('input.pattern', this).value(),
-    inflection_characteristic:
-      $('.inflection-characteristic', this).value(),
-    lip_id: $('input.pattern', this)[0].name.split('-')[0]
-  };
-  $.ajaxJSON({
-    method: 'get',
-    dest: $('#table-preview'),
-    url: $dj.ajax_table_preview,
-    data: data,
-    error_callback: function() {
-      $('#table-preview').html('');
-    }
-  });
+var set_active_lip_row = function () {
+    "use strict";
+    $('.lip-row-active').removeClass('lip-row-active ui-state-active');
+    $(this).addClass('lip-row-active ui-state-active');
+    // tabelka
+    var data = {
+        lexeme_id: lexeme_id(),
+        entry: get_entry(),
+        pattern: $('input.pattern', this).value(),
+        inflection_characteristic: $('.inflection-characteristic', this).value(),
+        lip_id: $('input.pattern', this)[0].name.split('-')[0]
+    };
+    $.ajaxJSON({
+        method: 'get',
+        dest: $('#table-preview'),
+        url: $dj.ajax_table_preview,
+        data: data,
+        error_callback: function () {
+            $('#table-preview').html('');
+        }
+    });
 };
 
 function delete_lexeme() {
-  "use strict";
-  var id = lexeme_id();
-  if (window.confirm("Na pewno usunąć leksem?")) {
-    $.ajaxJSON({
-      method: 'post',
-      url: $dj.ajax_delete_lexeme,
-      data: {lexeme_id: id},
-      description: 'Usunięcie leksemu',
-      callback: function() {
-        jqgrid.grid.trigger("reloadGrid");
-        jqgrid.findAndScroll();
-      }
-    });
-  }
+    "use strict";
+    var id = lexeme_id();
+    if (window.confirm("Na pewno usunąć leksem?")) {
+        $.ajaxJSON({
+            method: 'post',
+            url: $dj.ajax_delete_lexeme,
+            data: {lexeme_id: id},
+            description: 'Usunięcie leksemu',
+            callback: function () {
+                jqgrid.grid.trigger("reloadGrid");
+                jqgrid.findAndScroll();
+            }
+        });
+    }
 }
 
 // filtry
 
 function create_button(button_class, icon_class, text) {
-  "use strict";
-  var button = $('<a/>')
-    .addClass('ui-state-default ui-corner-all ' + button_class)
-    .addClass('fm-button fm-button-icon-left');
-  var icon = $('<span/>').addClass('ui-icon ' + icon_class);
-  button.append(icon).append(text);
-  return button;
+    "use strict";
+    var button = $('<a/>')
+        .addClass('ui-state-default ui-corner-all ' + button_class)
+        .addClass('fm-button fm-button-icon-left');
+    var icon = $('<span/>').addClass('ui-icon ' + icon_class);
+    button.append(icon).append(text);
+    return button;
 }
 
 function add_buttons(f) {
-  "use strict";
-  if (f[0].p) {
-    var button_save = create_button(
-      'ui-save', 'ui-icon-disk', 'Zapisz filtr');
-    var button_load = create_button(
-      'ui-load', 'ui-icon-arrowthickstop-1-s', 'Załaduj filtr');
-    f.next().find('tr').last().children().first()
-      .append(button_save).append(button_load);
-    button_save.click(function() {
-      var filter_name, filters, post_data;
-      filter_name = window.prompt("Wybierz nazwę filtru do zapisania");
-      if(filter_name) {
-        filters = $('.searchFilter').jqFilter('filterData');
-        post_data = {
-          name: filter_name,
-          serialized_filter: $.toJSON(filters)
-        };
-        var save_filter_data = {
-          method: 'post',
-          url: $dj.ajax_save_filter,
-          data: post_data,
-          description: 'Zapisanie filtru'
-        };
-        $.ajaxJSON($.extend(save_filter_data, {
-          callback: function(data) {
-            if (data.exists &&
-                window.confirm("Filtr o tej nazwie już istnieje. Nadpisać?")) {
-              $.ajaxJSON($.extend(save_filter_data, {
-                data: $.extend(post_data, {force: true})
-              }));
+    "use strict";
+    if (f[0].p) {
+        var button_save = create_button(
+            'ui-save', 'ui-icon-disk', 'Zapisz filtr');
+        var button_load = create_button(
+            'ui-load', 'ui-icon-arrowthickstop-1-s', 'Załaduj filtr');
+        f.next().find('tr').last().children().first()
+            .append(button_save).append(button_load);
+        button_save.click(function () {
+            var filter_name, filters, post_data;
+            filter_name = window.prompt("Wybierz nazwę filtru do zapisania");
+            if (filter_name) {
+                filters = $('.searchFilter').jqFilter('filterData');
+                post_data = {
+                    name: filter_name,
+                    serialized_filter: $.toJSON(filters)
+                };
+                var save_filter_data = {
+                    method: 'post',
+                    url: $dj.ajax_save_filter,
+                    data: post_data,
+                    description: 'Zapisanie filtru'
+                };
+                $.ajaxJSON($.extend(save_filter_data, {
+                    callback: function (data) {
+                        if (data.exists &&
+                            window.confirm("Filtr o tej nazwie już istnieje. Nadpisać?")) {
+                            $.ajaxJSON($.extend(save_filter_data, {
+                                data: $.extend(post_data, {force: true})
+                            }));
+                        }
+                    }
+                }));
             }
-          }
-        }));
-      }
-      return false;
-    });
-    button_load.click(function() {
-      $.ajaxJSON({
-        method: 'get',
-        url: $dj.ajax_get_filters,
-        data: {},
-        description: 'Pobranie listy filtrów',
-        callback: filter_choice
-      });
-      return false;
-    });
-  }
+            return false;
+        });
+        button_load.click(function () {
+            $.ajaxJSON({
+                method: 'get',
+                url: $dj.ajax_get_filters,
+                data: {},
+                description: 'Pobranie listy filtrów',
+                callback: filter_choice
+            });
+            return false;
+        });
+    }
 }
 jqgrid.add_buttons = add_buttons;
 
 function filter_choice(ajax_data) {
-  "use strict";
-  var filters = ajax_data.filters;
-  var list = $('#filter-list');
-  list.html('');
-  // napakować okienko na podstawie wyniku z ajaxa
-  $.each(filters, function(i, filter) {
-    var item = $('<li/>').addClass('ui-state-default').attr('id', filter.id);
-    var delete_button = $('<span/>')
-      .addClass('remove ui-icon ui-icon-closethick');
-    delete_button.click(function() {
-      if (window.confirm('Usunąć filtr "' + filter.name + '"?')) {
-        $.ajaxJSON({
-          method: 'post',
-          url: $dj.ajax_delete_filter,
-          data: {id: filter.id},
-          description: 'Usunięcie filtru',
-          callback: function() {
-            item.remove();
-          }
+    "use strict";
+    var filters = ajax_data.filters;
+    var list = $('#filter-list');
+    list.html('');
+    // napakować okienko na podstawie wyniku z ajaxa
+    $.each(filters, function (i, filter) {
+        var item = $('<li/>').addClass('ui-state-default').attr('id', filter.id);
+        var delete_button = $('<span/>')
+            .addClass('remove ui-icon ui-icon-closethick');
+        delete_button.click(function () {
+            if (window.confirm('Usunąć filtr "' + filter.name + '"?')) {
+                $.ajaxJSON({
+                    method: 'post',
+                    url: $dj.ajax_delete_filter,
+                    data: {id: filter.id},
+                    description: 'Usunięcie filtru',
+                    callback: function () {
+                        item.remove();
+                    }
+                });
+            }
+            return false;
         });
-      }
-      return false;
-    });
-    item.append(delete_button);
-    item.append(filter.name);
-    item.click(function() {
-      jqgrid.put_filter(filter.json);
-      $("#load-filter-dialog").dialog('close');
+        item.append(delete_button);
+        item.append(filter.name);
+        item.click(function () {
+            jqgrid.put_filter(filter.json);
+            $("#load-filter-dialog").dialog('close');
+        });
+        list.append(item);
     });
-    list.append(item);
-  });
-  $("#load-filter-dialog").dialog('open');
+    $("#load-filter-dialog").dialog('open');
 }
 
 // podpowiadacz
 
-var display_prompter = function() {
-  "use strict";
-  var prompter_checkboxes = $('#prompter-checkboxes');
-  var prompter_commonness = $('#prompter-commonness');
-  $('#prompter-list').html('');
-  $('#prompter-table-preview').html('');
-  prompter_checkboxes.hide();
-  prompter_checkboxes.find(':checkbox').prop('checked', true);
-  var cvs = $('#id_cl' + $dj.commonness + '-values').val();
-  if (!cvs || cvs.length === 0) {
-    prompter_commonness.prop('checked', false);
-    prompter_commonness.prop('disabled', true);
-    prompter_commonness.next().addClass('disabled');
-  } else {
-    prompter_commonness.prop('disabled', false);
-    prompter_commonness.next().removeClass('disabled');
-  }
-  $('#prompter-dialog').dialog('open');
-  reload_prompter({button: this});
+var display_prompter = function () {
+    "use strict";
+    var prompter_checkboxes = $('#prompter-checkboxes');
+    var prompter_commonness = $('#prompter-commonness');
+    $('#prompter-list').html('');
+    $('#prompter-table-preview').html('');
+    prompter_checkboxes.hide();
+    prompter_checkboxes.find(':checkbox').prop('checked', true);
+    var cvs = $('#id_cl' + $dj.commonness + '-values').val();
+    if (!cvs || cvs.length === 0) {
+        prompter_commonness.prop('checked', false);
+        prompter_commonness.prop('disabled', true);
+        prompter_commonness.next().addClass('disabled');
+    } else {
+        prompter_commonness.prop('disabled', false);
+        prompter_commonness.next().removeClass('disabled');
+    }
+    $('#prompter-dialog').dialog('open');
+    reload_prompter({button: this});
 };
 
 function reload_prompter(arg) {
-  "use strict";
-  prompter_ctrl = getBusyOverlay(
-    $('#prompter-dialog')[0],
-    {},
-    {size: 30});
-  // załadować dane do promptera
-  var elem;
-  if (arg.button)
-    elem = $(arg.button).closest('.lip-row');
-  else
-    elem = $('.lip-row-active');
-  var ic = elem.find('select.inflection-characteristic').val();
-  var id = lexeme_id();
-  var cvs = $('#id_cl' + $dj.commonness + '-values').val();
-  if (!cvs) cvs = [];
-  var ic_check, cv_check, bl_check;
-  var entry = get_entry();
-  var pos = get_pos();
-  ic_check = $('#prompter-ic').prop('checked');
-  cv_check = $('#prompter-commonness').prop('checked');
-  bl_check = $('#prompter-blacklist').prop('checked');
-  $.ajaxJSON({
-    method: 'get',
-    dest: $('#prompter-list'),
-    url: $dj.ajax_prompter_list,
-    data: {
-      ic_id: ic,
-      lexeme_id: id,
-      entry: entry,
-      pos_id: pos,
-      commonness_ids: cvs,
-      ic_check: ic_check,
-      cv_check: cv_check,
-      bl_check: bl_check
-    },
-    callback: function() {
-      prompter_ctrl.remove();
-      $('#prompter-list').children().first().click();
-      $('#prompter-checkboxes').show();
-    }
-  });
+    "use strict";
+    prompter_ctrl = getBusyOverlay(
+        $('#prompter-dialog')[0],
+        {},
+        {size: 30});
+    // załadować dane do promptera
+    var elem;
+    if (arg.button)
+        elem = $(arg.button).closest('.lip-row');
+    else
+        elem = $('.lip-row-active');
+    var ic = elem.find('select.inflection-characteristic').val();
+    var id = lexeme_id();
+    var cvs = $('#id_cl' + $dj.commonness + '-values').val();
+    if (!cvs) cvs = [];
+    var ic_check, cv_check, bl_check;
+    var entry = get_entry();
+    var pos = get_pos();
+    ic_check = $('#prompter-ic').prop('checked');
+    cv_check = $('#prompter-commonness').prop('checked');
+    bl_check = $('#prompter-blacklist').prop('checked');
+    $.ajaxJSON({
+        method: 'get',
+        dest: $('#prompter-list'),
+        url: $dj.ajax_prompter_list,
+        data: {
+            ic_id: ic,
+            lexeme_id: id,
+            entry: entry,
+            pos_id: pos,
+            commonness_ids: cvs,
+            ic_check: ic_check,
+            cv_check: cv_check,
+            bl_check: bl_check
+        },
+        callback: function () {
+            prompter_ctrl.remove();
+            $('#prompter-list').children().first().click();
+            $('#prompter-checkboxes').show();
+        }
+    });
 }
 
-var set_active_prompter_row = function() {
-  "use strict";
-  $('.prompter-row-active').removeClass('prompter-row-active');
-  $(this).addClass('prompter-row-active');
-  // tabelka
-  var data = {
-    lexeme_id: lexeme_id(),
-    entry: get_entry(),
-    pos: get_pos(),
-    pattern: $('.pattern', this).text(),
-    inflection_characteristic: $('.ic-id', this).text(),
-    lip_id: 'lip_add'
-  };
-  $.ajaxJSON({
-    method: 'get',
-    dest: $('#prompter-table-preview'),
-    url: $dj.ajax_table_preview,
-    data: data,
-    error_callback: function() {
-      $('#prompter-table-preview').html('');
-    }
-  });
+var set_active_prompter_row = function () {
+    "use strict";
+    $('.prompter-row-active').removeClass('prompter-row-active');
+    $(this).addClass('prompter-row-active');
+    // tabelka
+    var data = {
+        lexeme_id: lexeme_id(),
+        entry: get_entry(),
+        pos: get_pos(),
+        pattern: $('.pattern', this).text(),
+        inflection_characteristic: $('.ic-id', this).text(),
+        lip_id: 'lip_add'
+    };
+    $.ajaxJSON({
+        method: 'get',
+        dest: $('#prompter-table-preview'),
+        url: $dj.ajax_table_preview,
+        data: data,
+        error_callback: function () {
+            $('#prompter-table-preview').html('');
+        }
+    });
 };
 
 function input_prompter_pattern() {
-  "use strict";
-  var active = $('.prompter-row-active');
-  var pattern;
-  if (active.length > 0) {
-    $('#prompter-dialog').dialog('close');
-    pattern = active.find('.pattern').text();
-    $('.lip-row-active').find('input.pattern').val(pattern);
-    jqgrid.show_changed();
-  }
+    "use strict";
+    var active = $('.prompter-row-active');
+    var pattern;
+    if (active.length > 0) {
+        $('#prompter-dialog').dialog('close');
+        pattern = active.find('.pattern').text();
+        $('.lip-row-active').find('input.pattern').val(pattern);
+        jqgrid.show_changed();
+    }
 }
 
 function check_classifications() {
-  "use strict";
-  var new_classifications = $.ajaxJSON({
-    method: 'get',
-    url: $dj.ajax_check_classifications,
-    data: {lexeme_id: lexeme_id(), pos: get_pos(), owner_id: get_owner()},
-    async: false
-  }).classifications;
-  var old_classifications = $('#classifications').find('.classification-values')
-    .map(function(i, el) {
-      return parseInt(el.id.replace('id_cl', '').replace('-values', ''), 10);
+    "use strict";
+    var new_classifications = $.ajaxJSON({
+        method: 'get',
+        url: $dj.ajax_check_classifications,
+        data: {lexeme_id: lexeme_id(), pos: get_pos(), owner_id: get_owner()},
+        async: false
+    }).classifications;
+    var old_classifications = $('#classifications').find('.classification-values')
+        .map(function (i, el) {
+            return parseInt(el.id.replace('id_cl', '').replace('-values', ''), 10);
+        });
+    var stale_classifications = [];
+    old_classifications.each(function (i, c_id) {
+        if (new_classifications.indexOf(c_id) === -1)
+            stale_classifications.push(c_id);
     });
-  var stale_classifications = [];
-  old_classifications.each(function(i, c_id) {
-    if (new_classifications.indexOf(c_id) === -1)
-      stale_classifications.push(c_id);
-  });
-  return stale_classifications;
+    return stale_classifications;
 }
 
 function check_attrs(ics) {
-  "use strict";
-  var new_attrs = $.ajaxJSON({
-    method: 'get',
-    url: $dj.ajax_check_attributes,
-    data: {lexeme_id: lexeme_id(), pos: get_pos(), ics: ics},
-    async: false
-  }).attrs;
-  var old_attrs = $('#extra-attributes').find('select').map(function(i, el) {
-    return parseInt(el.id.split('-')[0].substring('id_attr'.length), 10);
-  });
-  var stale_attrs = [];
-  old_attrs.each(function(i, attr) {
-    if (new_attrs.indexOf(attr) === -1)
-      stale_attrs.push(attr);
-  });
-  return stale_attrs;
+    "use strict";
+    var new_attrs = $.ajaxJSON({
+        method: 'get',
+        url: $dj.ajax_check_attributes,
+        data: {lexeme_id: lexeme_id(), pos: get_pos(), ics: ics},
+        async: false
+    }).attrs;
+    var old_attrs = $('#extra-attributes').find('select').map(function (i, el) {
+        return parseInt(el.id.split('-')[0].substring('id_attr'.length), 10);
+    });
+    var stale_attrs = [];
+    old_attrs.each(function (i, attr) {
+        if (new_attrs.indexOf(attr) === -1)
+            stale_attrs.push(attr);
+    });
+    return stale_attrs;
 }
 
-var check_pos = function() {
-  "use strict";
-  var pos = get_pos();
-  var bad_lips = [], good_ics = [], confirmed;
-  var lip_row_elems = $('.lip-row'), cr_row_elems = $('.cr-row');
-  lip_row_elems.each(function() {
-    var ic = $(this).find('select.inflection-characteristic').val();
-    var ic_symbol = $(this).find(
-      'select.inflection-characteristic :selected').text();
-    var pattern = $(this).find('input.pattern').val();
-    var answer = $.ajaxJSON({
-      method: 'get',
-      url: $dj.ajax_check_pos,
-      data: {pos_id: pos, ic_id: ic},
-      async: false
-    }).answer;
-    if (answer !== 'yes')
-      bad_lips.push({ic: ic_symbol, pattern: pattern});
-    else
-      good_ics.push(ic_symbol);
-  });
-  var stale_attrs = check_attrs(good_ics);
-  var stale_classifications = check_classifications();
-  if (bad_lips.length > 0 || cr_row_elems.length > 0 ||
-      stale_attrs.length > 0 || stale_classifications.length > 0) {
-    var lips_text = '', cr_text = '', lips = [];
-    if (bad_lips.length > 0) {
-      $.each(bad_lips, function(i, t) {
-        lips.push('(' + t.ic + ', ' + t.pattern + ')');
-      });
-    }
-    if (lips.length > 0) {
-      lips_text = "sposoby odmiany: " + lips.join(', ') + '\n';
-    }
-    if (cr_row_elems.length > 0) {
-      cr_text += "wszystkie odsyłacze\n";
-    }
-    var attr_text = '';
-    if (stale_attrs.length > 0) {
-      attr_text = "atrybuty: " + join_attrs(stale_attrs) + '\n';
-    }
-    var clas_text = '';
-    if (stale_classifications.length > 0) {
-      clas_text = "klasyfikacje: " +
-        join_classifications(stale_classifications) + '\n';
-    }
-    confirmed = window.confirm(
-      'Zostaną usunięte:\n' + lips_text + cr_text + attr_text + clas_text +
-        'Kontynuować?');
-    if (!confirmed) {
-      revert_selection($(this));
+var check_pos = function () {
+    "use strict";
+    var pos = get_pos();
+    var bad_lips = [], good_ics = [], confirmed;
+    var lip_row_elems = $('.lip-row'), cr_row_elems = $('.cr-row');
+    lip_row_elems.each(function () {
+        var ic = $(this).find('select.inflection-characteristic').val();
+        var ic_symbol = $(this).find(
+            'select.inflection-characteristic :selected').text();
+        var pattern = $(this).find('input.pattern').val();
+        var answer = $.ajaxJSON({
+            method: 'get',
+            url: $dj.ajax_check_pos,
+            data: {pos_id: pos, ic_id: ic},
+            async: false
+        }).answer;
+        if (answer !== 'yes')
+            bad_lips.push({ic: ic_symbol, pattern: pattern});
+        else
+            good_ics.push(ic_symbol);
+    });
+    var stale_attrs = check_attrs(good_ics);
+    var stale_classifications = check_classifications();
+    if (bad_lips.length > 0 || cr_row_elems.length > 0 ||
+        stale_attrs.length > 0 || stale_classifications.length > 0) {
+        var lips_text = '', cr_text = '', lips = [];
+        if (bad_lips.length > 0) {
+            $.each(bad_lips, function (i, t) {
+                lips.push('(' + t.ic + ', ' + t.pattern + ')');
+            });
+        }
+        if (lips.length > 0) {
+            lips_text = "sposoby odmiany: " + lips.join(', ') + '\n';
+        }
+        if (cr_row_elems.length > 0) {
+            cr_text += "wszystkie odsyłacze\n";
+        }
+        var attr_text = '';
+        if (stale_attrs.length > 0) {
+            attr_text = "atrybuty: " + join_attrs(stale_attrs) + '\n';
+        }
+        var clas_text = '';
+        if (stale_classifications.length > 0) {
+            clas_text = "klasyfikacje: " +
+                join_classifications(stale_classifications) + '\n';
+        }
+        confirmed = window.confirm(
+            'Zostaną usunięte:\n' + lips_text + cr_text + attr_text + clas_text +
+                'Kontynuować?');
+        if (!confirmed) {
+            revert_selection($(this));
+        }
     }
-  }
-  if (confirmed || !(bad_lips.length > 0 || cr_row_elems.length > 0 ||
+    if (confirmed || !(bad_lips.length > 0 || cr_row_elems.length > 0 ||
         stale_attrs.length > 0 || stale_classifications.length > 0)) {
-    confirm_selection($(this));
-    var result = $.ajax({ // znowu brzydko...
-      type: 'get',
-      url: $dj.ajax_get_ics,
-      data: {pos_id: pos},
-      async: false
-    });
-    var ics = $.parseJSON(result.responseText).ics;
-    var ic_symbols = $.map(ics, function(a) { return a[1]; });
-    var reload_preview = false;
-    lip_row_elems.each(function() {
-      var select = $(this).find('select.inflection-characteristic');
-      var ic_symbol = select.find(':selected').text();
-      var index;
-      // chyba trochę przekombinowane...
-      if (ic_symbols.indexOf(ic_symbol) !== -1) {
-        select.empty();
-        $.each(ics, function(i, a) {
-          var option = new Option(a[1], a[0]);
-          if (a[1] === ic_symbol) {
-            index = i;
-          }
-          select.prop('options').add(option);
+        confirm_selection($(this));
+        var result = $.ajax({ // znowu brzydko...
+            type: 'get',
+            url: $dj.ajax_get_ics,
+            data: {pos_id: pos},
+            async: false
         });
-        select[0].selectedIndex = index;
-      } else {
-        var li = $(this);
-        // copypasta...
-        var name = li.find('input')[0].name;
-        if (name.substring(0,7) !== 'lip_add')
-          deleted.push(name.split('-')[0]);
-        li.remove();
-        reload_preview = true;
-      }
-    });
-    if (reload_preview)
-      $('#table-preview').html('');
-    cr_row_elems.each(function() {
-      var li = $(this);
-      // copypasta...
-      if (!li.hasClass('cr-add'))
-        deleted_cr.push(Number(li[0].id.split('-')[1]));
-      li.remove();
-    });
-    reload_attributes();
-    reload_classifications();
-  }
+        var ics = $.parseJSON(result.responseText).ics;
+        var ic_symbols = $.map(ics, function (a) {
+            return a[1];
+        });
+        var reload_preview = false;
+        lip_row_elems.each(function () {
+            var select = $(this).find('select.inflection-characteristic');
+            var ic_symbol = select.find(':selected').text();
+            var index;
+            // chyba trochę przekombinowane...
+            if (ic_symbols.indexOf(ic_symbol) !== -1) {
+                select.empty();
+                $.each(ics, function (i, a) {
+                    var option = new Option(a[1], a[0]);
+                    if (a[1] === ic_symbol) {
+                        index = i;
+                    }
+                    select.prop('options').add(option);
+                });
+                select[0].selectedIndex = index;
+            } else {
+                var li = $(this);
+                // copypasta...
+                var name = li.find('input')[0].name;
+                if (name.substring(0, 7) !== 'lip_add')
+                    deleted.push(name.split('-')[0]);
+                li.remove();
+                reload_preview = true;
+            }
+        });
+        if (reload_preview)
+            $('#table-preview').html('');
+        cr_row_elems.each(function () {
+            var li = $(this);
+            // copypasta...
+            if (!li.hasClass('cr-add'))
+                deleted_cr.push(Number(li[0].id.split('-')[1]));
+            li.remove();
+        });
+        reload_attributes();
+        reload_classifications();
+    }
 };
 
 // dodawanie
 
 function add_lexeme() {
-  "use strict";
-  // trzeba zdecydować, jaki słownik właściciel
-  if ($dj.default_owner === '') {
-    $('#default-owner-dialog').dialog('open');
-  } else {
-    make_new_lexeme();
-  }
+    "use strict";
+    // trzeba zdecydować, jaki słownik właściciel
+    if ($dj.default_owner === '') {
+        $('#default-owner-dialog').dialog('open');
+    } else {
+        make_new_lexeme();
+    }
 }
 
 function set_default_owner(vocab_id) {
-  "use strict";
-  $dj.default_owner = vocab_id;
-  $.ajaxJSON({
-    method: 'post',
-    url: $dj.ajax_save_default_owner,
-    data: {vocab_id: vocab_id},
-    description: "Zapisanie domyślnego słownika"
-  });
+    "use strict";
+    $dj.default_owner = vocab_id;
+    $.ajaxJSON({
+        method: 'post',
+        url: $dj.ajax_save_default_owner,
+        data: {vocab_id: vocab_id},
+        description: "Zapisanie domyślnego słownika"
+    });
 }
 
 function make_new_lexeme() {
-  "use strict";
-  // stworzyć ajaxem nowy leksem i go po prostu otworzyć...
-  $.ajaxJSON({
-    method: 'post',
-    url: $dj.ajax_create_lexeme,
-    data: {vocab_id: $dj.default_owner},
-    description: "Utworzenie leksemu",
-    callback: function(data) {
-      load_content(data.id, true);
-    }
-  });
+    "use strict";
+    // stworzyć ajaxem nowy leksem i go po prostu otworzyć...
+    $.ajaxJSON({
+        method: 'post',
+        url: $dj.ajax_create_lexeme,
+        data: {vocab_id: $dj.default_owner},
+        description: "Utworzenie leksemu",
+        callback: function (data) {
+            load_content(data.id, true);
+        }
+    });
 }
 
 function show_homonym_count() {
-  "use strict";
-  var entry = get_entry();
-  $.ajaxJSON({
-    method: 'get',
-    url: $dj.ajax_homonym_count,
-    data: {entry: entry, lexeme_id: lexeme_id()},
-    descripton: "Pobranie liczby homonimów",
-    callback: function(data) {
-      var info = '';
-      if (entry === get_entry()) {
-        if (data.count > 0) {
-          info = data.count + ' homonim';
-          if (data.count > 1 && data.count < 5)
-            info += 'y';
-          else if (data.count >= 5)
-            info += 'ów'; // "22 homonimów", ale nigdy nie będzie aż tyle
+    "use strict";
+    var entry = get_entry();
+    $.ajaxJSON({
+        method: 'get',
+        url: $dj.ajax_homonym_count,
+        data: {entry: entry, lexeme_id: lexeme_id()},
+        descripton: "Pobranie liczby homonimów",
+        callback: function (data) {
+            var info = '';
+            if (entry === get_entry()) {
+                if (data.count > 0) {
+                    info = data.count + ' homonim';
+                    if (data.count > 1 && data.count < 5)
+                        info += 'y';
+                    else if (data.count >= 5)
+                        info += 'ów'; // "22 homonimów", ale nigdy nie będzie aż tyle
+                }
+                $('#homonym-count').text(info);
+            }
         }
-        $('#homonym-count').text(info);
-      }
-    }
-  });
+    });
 }
 
 // odsyłacze
 
 function homonym_choice(lexemes, hom_field) {
-  "use strict";
-  var table = $('#homonym-list').find('tbody');
-  table.html('');
-  // napakować okienko na podstawie wyniku z ajaxa
-  $.each(lexemes, function(i, data) {
-    var item = $('<tr/>').addClass('ui-state-default')
-      .attr('id', 'hom' + data.homonym_number);
-    item.append($('<td/>').text(data.homonym_number));
-    item.append($('<td/>').text(data.lip_data.inflection_characteristics));
-    item.append($('<td/>').text(data.lip_data.patterns));
-    item.click(function() {
-      hom_field.val($(this).children().first().text());
-      $("#choose-homonym-dialog").dialog('close');
+    "use strict";
+    var table = $('#homonym-list').find('tbody');
+    table.html('');
+    // napakować okienko na podstawie wyniku z ajaxa
+    $.each(lexemes, function (i, data) {
+        var item = $('<tr/>').addClass('ui-state-default')
+            .attr('id', 'hom' + data.homonym_number);
+        item.append($('<td/>').text(data.homonym_number));
+        item.append($('<td/>').text(data.lip_data.inflection_characteristics));
+        item.append($('<td/>').text(data.lip_data.patterns));
+        item.click(function () {
+            hom_field.val($(this).children().first().text());
+            $("#choose-homonym-dialog").dialog('close');
+        });
+        table.append(item);
     });
-    table.append(item);
-  });
-  $("#choose-homonym-dialog").dialog('open');
+    $("#choose-homonym-dialog").dialog('open');
 }
 
-var set_cr_homonym_number = function() {
-  "use strict";
-  var $t = $(this).parent();
-  $.ajaxJSON({
-    method: 'get',
-    url: $dj.ajax_cr_homonyms,
-    data: {
-      entry: $t.find('.entry').val(),
-      cr_type: $t.find('.type').val()
-    },
-    description: "Sprawdzenie homonimów",
-    callback: function(data) {
-      var lexemes = data.lexemes;
-      if (lexemes.length === 1)
-        $t.find('.homonym-number').val(lexemes[0].homonym_number);
-      else if (lexemes.length > 1) {
-        homonym_choice(lexemes, $t.find('.homonym-number'));
-      } else { // nie ma żadnego
-        window.alert('Brak pasujących leksemów.');
-        $t.find('.entry').val('');
-        $t.find('.homonym-number').val('');
-      }
-    }
-  });
+var set_cr_homonym_number = function () {
+    "use strict";
+    var $t = $(this).parent();
+    $.ajaxJSON({
+        method: 'get',
+        url: $dj.ajax_cr_homonyms,
+        data: {
+            entry: $t.find('.entry').val(),
+            cr_type: $t.find('.type').val()
+        },
+        description: "Sprawdzenie homonimów",
+        callback: function (data) {
+            var lexemes = data.lexemes;
+            if (lexemes.length === 1)
+                $t.find('.homonym-number').val(lexemes[0].homonym_number);
+            else if (lexemes.length > 1) {
+                homonym_choice(lexemes, $t.find('.homonym-number'));
+            } else { // nie ma żadnego
+                window.alert('Brak pasujących leksemów.');
+                $t.find('.entry').val('');
+                $t.find('.homonym-number').val('');
+            }
+        }
+    });
 };
 
 // akcje grupowe
 
 var filter_row_counter = 1; // dla niepowtarzalności idów
 function new_action_row_html() {
-  "use strict";
-  var new_row_html = $.ajax({
-    type: 'get',
-    url: $dj.ajax_new_action_row,
-    async: false
-  }).responseText.replace(/NUM/g, filter_row_counter);
-  filter_row_counter++;
-  return new_row_html;
+    "use strict";
+    var new_row_html = $.ajax({
+        type: 'get',
+        url: $dj.ajax_new_action_row,
+        async: false
+    }).responseText.replace(/NUM/g, filter_row_counter);
+    filter_row_counter++;
+    return new_row_html;
 }
 
-var update_action_row = function() {
-  "use strict";
-  var num = this.id.split('-')[0].split('_')[2];
-  var row = $(this).closest('tr');
-  var field_name = $(this).val();
-  $.ajaxJSON({
-    method: 'get',
-    url: $dj.ajax_dynamic_fields,
-    data: {field_name: field_name},
-    callback: function(data) {
-      row.find('.action').html(data.action.replace('NUM', num));
-      row.find('.value').html(data.value.replace('NUM', num));
-    }
-  });
+var update_action_row = function () {
+    "use strict";
+    var num = this.id.split('-')[0].split('_')[2];
+    var row = $(this).closest('tr');
+    var field_name = $(this).val();
+    $.ajaxJSON({
+        method: 'get',
+        url: $dj.ajax_dynamic_fields,
+        data: {field_name: field_name},
+        callback: function (data) {
+            row.find('.action').html(data.action.replace('NUM', num));
+            row.find('.value').html(data.value.replace('NUM', num));
+        }
+    });
 };
 
 function new_action_row() {
-  "use strict";
-  var row_html = new_action_row_html();
-  var action_tr = $(row_html);
-  $('#action-list').append(action_tr);
-  action_tr.find('.field-choice').change();
+    "use strict";
+    var row_html = new_action_row_html();
+    var action_tr = $(row_html);
+    $('#action-list').append(action_tr);
+    action_tr.find('.field-choice').change();
 }
 
-var execute_actions = function() {
-  "use strict";
-  var actions = $('#action-list').find('tr').map(function() {
+var execute_actions = function () {
+    "use strict";
+    var actions = $('#action-list').find('tr').map(function () {
+        var $t = $(this);
+        return {
+            field: $t.find('.field-choice').val(),
+            type: $t.find('.action-choice').val(),
+            value: $t.find('.value-choice').val()
+        };
+    }).get();
+    var filters = jqgrid.grid.jqGrid('getGridParam', 'postData').filters;
     var $t = $(this);
-    return {
-      field: $t.find('.field-choice').val(),
-      type: $t.find('.action-choice').val(),
-      value: $t.find('.value-choice').val()
-    };
-  }).get();
-  var filters = jqgrid.grid.jqGrid('getGridParam', 'postData').filters;
-  var $t = $(this);
-  $.ajaxJSON({
-    method: 'post',
-    url: $dj.ajax_execute_actions,
-    data: {filters: filters, actions: actions},
-    callback: function() {
-      $t.dialog("close");
-      jqgrid.grid.jqGrid('getGridParam', 'postData').force_reload = true;
-      jqgrid.grid.trigger('reloadGrid');
-    }
-  });
+    $.ajaxJSON({
+        method: 'post',
+        url: $dj.ajax_execute_actions,
+        data: {filters: filters, actions: actions},
+        callback: function () {
+            $t.dialog("close");
+            jqgrid.grid.jqGrid('getGridParam', 'postData').force_reload = true;
+            jqgrid.grid.trigger('reloadGrid');
+        }
+    });
 };
\ No newline at end of file
diff --git a/media/js/lib/cvi_busy_lib.js b/media/js/lib/cvi_busy_lib.js
index 424cc5d..ffaa87e 100644
--- a/media/js/lib/cvi_busy_lib.js
+++ b/media/js/lib/cvi_busy_lib.js
@@ -1,275 +1,706 @@
 /**
- * cvi_busy_lib.js 1.3 (14-Aug-2010) (c) by Christian Effenberger 
+ * cvi_busy_lib.js 1.3 (14-Aug-2010) (c) by Christian Effenberger
  * All Rights Reserved. Source: busy.netzgesta.de
  * Distributed under Netzgestade Software License Agreement.
- * This license permits free of charge use on non-commercial 
- * and private web sites only under special conditions. 
+ * This license permits free of charge use on non-commercial
+ * and private web sites only under special conditions.
  * Read more at... http://www.netzgesta.de/cvi/LICENSE.txt
  * syntax:
- 
+
  Add:
-	OBJECT = getBusyOverlay(parent[,overlay[,busy]]);
+ OBJECT = getBusyOverlay(parent[,overlay[,busy]]);
 
-	parent		== element to add the overlay (e.g. document.getElementById(id) or 'viewport')
+ parent        == element to add the overlay (e.g. document.getElementById(id) or 'viewport')
 
-	overlay 	== OBJECT e.g. {color: 'black', opacity: 0.5, ...}
-		color	== STR 'black' or '#000000' or 'rgb(0,0,0)' Default: 'white'
-		opacity	== FLOAT 0.0 - 1.0  Default: 0.0
-		text	== STR e.g. "loading" Default: ''
-		style	== STR e.g. "color: black;" or "my_text_class" Default: ''
+ overlay    == OBJECT e.g. {color: 'black', opacity: 0.5, ...}
+ color    == STR 'black' or '#000000' or 'rgb(0,0,0)' Default: 'white'
+ opacity    == FLOAT 0.0 - 1.0  Default: 0.0
+ text    == STR e.g. "loading" Default: ''
+ style    == STR e.g. "color: black;" or "my_text_class" Default: ''
 
-	busy		== OBJECT e.g. {color: '#fff', size: 48, ...}
-		color	== STR '#000000' - '#ffffff' or '#000' - '#fff' Default: '#000'
-		size	== INT 16 - 512 (pixel) Default: 32
-		type	== STR 'circle|oval|polygon|rectangle|tube' or 'c|o|p|r|t' Default: 'tube'
-		iradius	== INT 6 - 254 (pixel) Default: 8
-		weight	== INT 1 - 254 (pixel) Default: 3
-		count	== INT 5 - 36 (rays) Default: 12
-		speed	== INT 30 - 1000 (millisec) Default: 96
-		minopac	== FLOAT 0.0 - 0.5  Default: 0.25
+ busy        == OBJECT e.g. {color: '#fff', size: 48, ...}
+ color    == STR '#000000' - '#ffffff' or '#000' - '#fff' Default: '#000'
+ size    == INT 16 - 512 (pixel) Default: 32
+ type    == STR 'circle|oval|polygon|rectangle|tube' or 'c|o|p|r|t' Default: 'tube'
+ iradius    == INT 6 - 254 (pixel) Default: 8
+ weight    == INT 1 - 254 (pixel) Default: 3
+ count    == INT 5 - 36 (rays) Default: 12
+ speed    == INT 30 - 1000 (millisec) Default: 96
+ minopac    == FLOAT 0.0 - 0.5  Default: 0.25
 
  Remove:
-	OBJECT.remove();
-	
+ OBJECT.remove();
+
  Set Overlay text:
-	OBJECT.settext(string);
+ OBJECT.settext(string);
 
  *
-**/
+ **/
 
 function onIEWinResize(event) {
-	function parseWidth(val) {return (isNaN(parseInt(val,10))?0:parseInt(val,10));}
-	if(!event) {event=window.event;} var i,cs,parent=this, div=parent.getElementsByTagName("div");
-	if(div.length>0) {if(parent.currentStyle){cs=parent.currentStyle;}else if(document.defaultView&&document.defaultView.getComputedStyle){cs=document.defaultView.getComputedStyle(parent,"");}else{cs=parent.style;}
-		for(i=0; i<div.length; i++) {if(div[i].className=='buzy_ele') {
-				div[i].style.height=(parent.offsetHeight-parseWidth(cs.borderBottomWidth)-parseWidth(cs.borderTopWidth));
-				div[i].style.width=(parent.offsetWidth-parseWidth(cs.borderLeftWidth)-parseWidth(cs.borderRightWidth)); 
-				div[i].firstChild.style.height=div[i].style.height; div[i].firstChild.style.width=div[i].style.width; 
-				break;
-			}
-		}
-	}
+    function parseWidth(val) {
+        return (isNaN(parseInt(val, 10)) ? 0 : parseInt(val, 10));
+    }
+
+    if (!event) {
+        event = window.event;
+    }
+    var i, cs, parent = this, div = parent.getElementsByTagName("div");
+    if (div.length > 0) {
+        if (parent.currentStyle) {
+            cs = parent.currentStyle;
+        } else if (document.defaultView && document.defaultView.getComputedStyle) {
+            cs = document.defaultView.getComputedStyle(parent, "");
+        } else {
+            cs = parent.style;
+        }
+        for (i = 0; i < div.length; i++) {
+            if (div[i].className == 'buzy_ele') {
+                div[i].style.height = (parent.offsetHeight - parseWidth(cs.borderBottomWidth) - parseWidth(cs.borderTopWidth));
+                div[i].style.width = (parent.offsetWidth - parseWidth(cs.borderLeftWidth) - parseWidth(cs.borderRightWidth));
+                div[i].firstChild.style.height = div[i].style.height;
+                div[i].firstChild.style.width = div[i].style.width;
+                break;
+            }
+        }
+    }
 }
 function onIEVPResize(event) {
-	if(!event) {event=window.event;} var vp=document.getElementById('viewport'); if(vp) {
-		if(typeof document.documentElement!='undefined') {vp.style.width=document.documentElement.clientWidth+'px'; vp.style.height=document.documentElement.clientHeight+'px';}
-		else {vp.style.width=document.getElementsByTagName('body')[0].clientWidth+'px'; vp.style.height=document.getElementsByTagName('body')[0].clientHeight+'px';}
-	}
+    if (!event) {
+        event = window.event;
+    }
+    var vp = document.getElementById('viewport');
+    if (vp) {
+        if (typeof document.documentElement != 'undefined') {
+            vp.style.width = document.documentElement.clientWidth + 'px';
+            vp.style.height = document.documentElement.clientHeight + 'px';
+        }
+        else {
+            vp.style.width = document.getElementsByTagName('body')[0].clientWidth + 'px';
+            vp.style.height = document.getElementsByTagName('body')[0].clientHeight + 'px';
+        }
+    }
 }
 function onIEVPScroll(event) {
-	if(!event) {event=window.event;} var vp=document.getElementById('viewport'); if(vp) {
-		if(typeof document.documentElement!='undefined') {vp.style.left=document.documentElement.scrollLeft+'px'; vp.style.top=document.documentElement.scrollTop+'px';}
-		else {vp.style.left=document.getElementsByTagName('body')[0].scrollLeft+'px'; vp.style.top=document.getElementsByTagName('body')[0].scrollTop+'px';}
-	}
+    if (!event) {
+        event = window.event;
+    }
+    var vp = document.getElementById('viewport');
+    if (vp) {
+        if (typeof document.documentElement != 'undefined') {
+            vp.style.left = document.documentElement.scrollLeft + 'px';
+            vp.style.top = document.documentElement.scrollTop + 'px';
+        }
+        else {
+            vp.style.left = document.getElementsByTagName('body')[0].scrollLeft + 'px';
+            vp.style.top = document.getElementsByTagName('body')[0].scrollTop + 'px';
+        }
+    }
 }
-function getBusyOverlay(parent,overlay,busy) {
-	if((typeof(parent)==='object' || parent=='viewport') && document.getElementsByTagName) {
-		function parseWidth(val) {return (isNaN(parseInt(val,10))?0:parseInt(val,10));}
-		var isIE,isVL,isCV,isWK,isGE,i,b,o,lt,rt,lb,rb,cz,cs,size,viewport,inner,outer,string,canvas,context,ctrl,opacity,color,text,styles,waiting=true;
-		if(parent=='viewport') {viewport=document.getElementById('viewport');
-			if(!viewport) {viewport=document.createElement('div'); viewport.id='viewport'; cz=viewport.style;
-				cz.backgroundColor='transparent'; cz.position='fixed'; cz.overflow='hidden';
-				cz.display='block'; cz.zIndex=999999; cz.left='0px'; cz.top='0px'; cz.zoom=1;
-				cz.width='100%'; cz.height='100%'; cz.margin='0px'; cz.padding='0px';
-				if(document.all&&!window.opera&&!window.XMLHttpRequest&&(!document.documentMode||document.documentMode<9)) {cz.position='absolute'; 
-					if(typeof document.documentElement!='undefined') {cz.width=document.documentElement.clientWidth+'px'; cz.height=document.documentElement.clientHeight+'px';}
-					else {cz.width=document.getElementsByTagName('body')[0].clientWidth+'px'; cz.height=document.getElementsByTagName('body')[0].clientHeight+'px';}
-				}document.getElementsByTagName("body")[0].appendChild(viewport);
-			}else {viewport.style.display='block';
-				if(document.all&&!window.opera&&!window.XMLHttpRequest&&(!document.documentMode||document.documentMode<9)) { 
-					if(typeof document.documentElement!='undefined') {viewport.style.width=document.documentElement.clientWidth+'px'; viewport.style.height=document.documentElement.clientHeight+'px';}
-					else {viewport.style.width=document.getElementsByTagName('body')[0].clientWidth+'px'; viewport.style.height=document.getElementsByTagName('body')[0].clientHeight+'px';}
-				}
-			}parent=viewport;
-		}
-		if(parent.currentStyle){cs=parent.currentStyle;}else if(document.defaultView&&document.defaultView.getComputedStyle){cs=document.defaultView.getComputedStyle(parent,"");}else{cs=parent.style;}
-		while(cs.display.search(/block|inline-block|table|inline-table|list-item/i)<0) {parent=parent.parentNode; if(parent.currentStyle){cs=parent.currentStyle;}else if(document.defaultView&&document.defaultView.getComputedStyle){cs=document.defaultView.getComputedStyle(parent,"");}else{cs=parent.style;} if(parent.tagName.toUpperCase()=='BODY') {parent="";}}
-		if(typeof(parent)==='object') {
-			if(!overlay) {overlay=new Object(); overlay['opacity']=0; overlay['color']='white'; overlay['text']=''; overlay['style']='';}
-			if(!busy) {busy=new Object(); busy['size']=32; busy['color']='#000'; busy['type']='tube'; busy['iradius']=8; busy['weight']=3; busy['count']=12; busy['speed']=96; busy['minopac']=.25;}
-			opacity=Math.max(0.0,Math.min(1.0,(typeof overlay['opacity']==='number'?overlay['opacity']:0)||0)); color=(typeof overlay['color']==='string'?overlay['color']:'white');
-			text=(typeof overlay['text']==='string'?overlay['text']:''); styles=(typeof overlay['style']==='string'?overlay['style']:'');
-			canvas=document.createElement("canvas"); isCV=canvas.getContext?1:0; 
-			isWK=navigator.userAgent.indexOf('WebKit')>-1?1:0; isGE=navigator.userAgent.indexOf('Gecko')>-1&&window.updateCommands?1:0;
-			isIE=navigator.appName=='Microsoft Internet Explorer'&&window.navigator.systemLanguage&&!window.opera&&(!document.documentMode||document.documentMode<9)?1:0; 
-			isVL=document.all&&document.namespaces&&(!document.documentMode||document.documentMode<9)?1:0; outer=document.createElement('div'); parent.style.position=(cs.position=='static'?'relative':cs.position);
-			cz=parent.style.zIndex>=0?(parent.style.zIndex-0+2):2; if(isIE && !cs.hasLayout) {parent.style.zoom=1;}
-			outer.style.position='absolute'; outer.style.overflow='hidden'; outer.style.display='block'; outer.style.zIndex=cz; 
-			outer.style.left=0+'px'; outer.style.top=0+'px'; outer.style.width='100%'; outer.style.height='100%';
-			if(isIE) {outer.className='buzy_ele'; outer.style.zoom=1; outer.style.margin='0px'; outer.style.padding='0px'; outer.style.height=(parent.offsetHeight-parseWidth(cs.borderBottomWidth)-parseWidth(cs.borderTopWidth)); outer.style.width=(parent.offsetWidth-parseWidth(cs.borderLeftWidth)-parseWidth(cs.borderRightWidth));}
-			if(typeof(cs.borderRadius)=="undefined"){
-				if(typeof(cs.MozBorderRadius)!="undefined"){
-					lt=parseFloat(cs.MozBorderRadiusTopleft)-Math.min(parseFloat(cs.borderLeftWidth),parseFloat(cs.borderTopWidth));
-					rt=parseFloat(cs.MozBorderRadiusTopright)-Math.min(parseFloat(cs.borderRightWidth),parseFloat(cs.borderTopWidth));
-					lb=parseFloat(cs.MozBorderRadiusBottomleft)-Math.min(parseFloat(cs.borderLeftWidth),parseFloat(cs.borderBottomWidth));
-					rb=parseFloat(cs.MozBorderRadiusBottomright)-Math.min(parseFloat(cs.borderRightWidth),parseFloat(cs.borderBottomWidth));
-					outer.style.MozBorderRadiusTopleft=lt+"px"; outer.style.MozBorderRadiusTopright=rt+"px"; outer.style.MozBorderRadiusBottomleft=lb+"px"; outer.style.MozBorderRadiusBottomright=rb+"px";
-				}else if(typeof(cs.WebkitBorderRadius)!="undefined"){
-					lt=parseFloat(cs.WebkitBorderTopLeftRadius)-Math.min(parseFloat(cs.borderLeftWidth),parseFloat(cs.borderTopWidth));
-					rt=parseFloat(cs.WebkitBorderTopRightRadius)-Math.min(parseFloat(cs.borderRightWidth),parseFloat(cs.borderTopWidth));
-					lb=parseFloat(cs.WebkitBorderBottomLeftRadius)-Math.min(parseFloat(cs.borderLeftWidth),parseFloat(cs.borderBottomWidth));
-					rb=parseFloat(cs.WebkitBorderBottomRightRadius)-Math.min(parseFloat(cs.borderRightWidth),parseFloat(cs.borderBottomWidth));
-					outer.style.WebkitBorderTopLeftRadius=lt+"px"; outer.style.WebkitBorderTopRightRadius=rt+"px"; outer.style.WebkitBorderBottomLeftRadius=lb+"px"; outer.style.WebkitBorderBottomRightRadius=rb+"px";
-				}
-			}else {
-				lt=parseFloat(cs.borderTopLeftRadius)-Math.min(parseFloat(cs.borderLeftWidth),parseFloat(cs.borderTopWidth));
-				rt=parseFloat(cs.borderTopRightRadius)-Math.min(parseFloat(cs.borderRightWidth),parseFloat(cs.borderTopWidth));
-				lb=parseFloat(cs.borderBottomLeftRadius)-Math.min(parseFloat(cs.borderLeftWidth),parseFloat(cs.borderBottomWidth));
-				rb=parseFloat(cs.borderBottomRightRadius)-Math.min(parseFloat(cs.borderRightWidth),parseFloat(cs.borderBottomWidth));
-				outer.style.borderTopLeftRadius=lt+"px"; outer.style.borderTopRightRadius=rt+"px"; outer.style.borderBottomLeftRadius=lb+"px"; outer.style.borderBottomRightRadius=rb+"px";
-			}
-			parent.appendChild(outer); inner=document.createElement('div');
-			inner.style.position='absolute'; inner.style.cursor='progress'; inner.style.display='block'; 
-			inner.style.zIndex=(cz-1); inner.style.left=0+'px'; inner.style.top=0+'px';
-			inner.style.width=100+'%'; inner.style.height=100+'%'; inner.style.backgroundColor=color;
-			if(isIE) {inner.style.zoom=1; inner.style.margin='0px'; inner.style.padding='0px'; inner.style.height=outer.style.height; inner.style.width=outer.style.width; }
-			if(typeof(cs.borderRadius)=="undefined"){
-				if(typeof(cs.MozBorderRadius)!="undefined"){inner.style.MozBorderRadiusTopleft=lt+"px"; inner.style.MozBorderRadiusTopright=rt+"px"; inner.style.MozBorderRadiusBottomleft=lb+"px"; inner.style.MozBorderRadiusBottomright=rb+"px";}else 
-				if(typeof(cs.WebkitBorderRadius)!="undefined"){inner.style.WebkitBorderTopLeftRadius=lt+"px"; inner.style.WebkitBorderTopRightRadius=rt+"px"; inner.style.WebkitBorderBottomLeftRadius=lb+"px"; inner.style.WebkitBorderBottomRightRadius=rb+"px";}
-			}else {inner.style.borderTopLeftRadius=lt+"px"; inner.style.borderTopRightRadius=rt+"px"; inner.style.borderBottomLeftRadius=lb+"px"; inner.style.borderBottomRightRadius=rb+"px";}
-			if(isIE) {inner.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity="+parseInt(opacity*100)+")";}else {inner.style.opacity=opacity;}
-			outer.appendChild(inner); size=Math.max(16,Math.min(512,(typeof busy['size']==='number'?(busy['size']==0?32:busy['size']):32)));
-			if(isVL){
-				if(document.namespaces['v']==null) {
-					var e=["shape","shapetype","group","background","path","formulas","handles","fill","stroke","shadow","textbox","textpath","imagedata","line","polyline","curve","roundrect","oval","rect","arc","image"],s=document.createStyleSheet(); 
-					for(i=0; i<e.length; i++) {s.addRule("v\\:"+e[i],"behavior: url(#default#VML);");} document.namespaces.add("v","urn:schemas-microsoft-com:vml");
-				} 
-			}
-			if(!isCV){canvas=document.createElement("div");}
-			canvas.style.position='absolute'; canvas.style.cursor='progress'; canvas.style.zIndex=(cz-0+1);
-			canvas.style.top='50%'; canvas.style.left='50%'; canvas.style.marginTop='-'+(size/2)+'px'; canvas.style.marginLeft='-'+(size/2)+'px';
-			canvas.width=size; canvas.height=size; canvas.style.width=size+"px"; canvas.style.height=size+"px";
-			outer.appendChild(canvas);
-			if(text!=""){
-				string=document.createElement('div'); string.style.position='absolute'; string.style.overflow='hidden'; 
-				string.style.cursor='progress'; string.style.zIndex=(cz-0+1); string.style.top='50%'; string.style.left='0px';
-				string.style.marginTop=2+(size/2)+'px'; string.style.textAlign='center'; string.style.width=100+'%'; string.style.height='auto';
-				if(styles!="") {string.innerHTML='<span '+(styles.match(/:/i)?'style':'class')+'="'+styles+'">'+text+'</span>';}
-				else {string.innerHTML='<span>'+text+'</span>';} outer.appendChild(string);
-			}
-			if(isGE){outer.style.MozUserSelect="none"; inner.style.MozUserSelect="none"; canvas.style.MozUserSelect="none";}else 
-			if(isWK){outer.style.KhtmlUserSelect="none"; inner.style.KhtmlUserSelect="none"; canvas.style.KhtmlUserSelect="none";}else 
-			if(isIE){outer.unselectable="on"; inner.unselectable="on"; canvas.unselectable="on";}
-			if(isVL){ctrl=getBusyVL(canvas,busy['color'],busy['size'],busy['type'],busy['iradius'],busy['weight'],busy['count'],busy['speed'],busy['minopac']); ctrl.start();}else 
-			if(isCV){ctrl=getBusyCV(canvas.getContext("2d"),busy['color'],busy['size'],busy['type'],busy['iradius'],busy['weight'],busy['count'],busy['speed'],busy['minopac']); ctrl.start();}
-			else {ctrl=getBusy(canvas,busy['color'],busy['size'],busy['type'],busy['iradius'],busy['weight'],busy['count'],busy['speed'],busy['minopac']); ctrl.start();}
-			if(isIE) {parent.onresize=onIEWinResize; if(parent.id=='viewport'&&!window.XMLHttpRequest) {window.onresize=onIEVPResize; window.onscroll=onIEVPScroll;}}
-			return {
-				remove: function (){if(waiting){waiting=false; ctrl.stop(); delete ctrl; parent.removeChild(outer); if(parent.id=='viewport') {parent.style.display='none';}}},
-				settext: function (v){if(string&&typeof(v)=='string') {string.firstChild.innerHTML=v; return false;}}
-			};
-		}
-	}
+function getBusyOverlay(parent, overlay, busy) {
+    if ((typeof(parent) === 'object' || parent == 'viewport') && document.getElementsByTagName) {
+        function parseWidth(val) {
+            return (isNaN(parseInt(val, 10)) ? 0 : parseInt(val, 10));
+        }
+
+        var isIE, isVL, isCV, isWK, isGE, i, b, o, lt, rt, lb, rb, cz, cs, size, viewport, inner, outer, string, canvas, context, ctrl, opacity, color, text, styles, waiting = true;
+        if (parent == 'viewport') {
+            viewport = document.getElementById('viewport');
+            if (!viewport) {
+                viewport = document.createElement('div');
+                viewport.id = 'viewport';
+                cz = viewport.style;
+                cz.backgroundColor = 'transparent';
+                cz.position = 'fixed';
+                cz.overflow = 'hidden';
+                cz.display = 'block';
+                cz.zIndex = 999999;
+                cz.left = '0px';
+                cz.top = '0px';
+                cz.zoom = 1;
+                cz.width = '100%';
+                cz.height = '100%';
+                cz.margin = '0px';
+                cz.padding = '0px';
+                if (document.all && !window.opera && !window.XMLHttpRequest && (!document.documentMode || document.documentMode < 9)) {
+                    cz.position = 'absolute';
+                    if (typeof document.documentElement != 'undefined') {
+                        cz.width = document.documentElement.clientWidth + 'px';
+                        cz.height = document.documentElement.clientHeight + 'px';
+                    }
+                    else {
+                        cz.width = document.getElementsByTagName('body')[0].clientWidth + 'px';
+                        cz.height = document.getElementsByTagName('body')[0].clientHeight + 'px';
+                    }
+                }
+                document.getElementsByTagName("body")[0].appendChild(viewport);
+            } else {
+                viewport.style.display = 'block';
+                if (document.all && !window.opera && !window.XMLHttpRequest && (!document.documentMode || document.documentMode < 9)) {
+                    if (typeof document.documentElement != 'undefined') {
+                        viewport.style.width = document.documentElement.clientWidth + 'px';
+                        viewport.style.height = document.documentElement.clientHeight + 'px';
+                    }
+                    else {
+                        viewport.style.width = document.getElementsByTagName('body')[0].clientWidth + 'px';
+                        viewport.style.height = document.getElementsByTagName('body')[0].clientHeight + 'px';
+                    }
+                }
+            }
+            parent = viewport;
+        }
+        if (parent.currentStyle) {
+            cs = parent.currentStyle;
+        } else if (document.defaultView && document.defaultView.getComputedStyle) {
+            cs = document.defaultView.getComputedStyle(parent, "");
+        } else {
+            cs = parent.style;
+        }
+        while (cs.display.search(/block|inline-block|table|inline-table|list-item/i) < 0) {
+            parent = parent.parentNode;
+            if (parent.currentStyle) {
+                cs = parent.currentStyle;
+            } else if (document.defaultView && document.defaultView.getComputedStyle) {
+                cs = document.defaultView.getComputedStyle(parent, "");
+            } else {
+                cs = parent.style;
+            }
+            if (parent.tagName.toUpperCase() == 'BODY') {
+                parent = "";
+            }
+        }
+        if (typeof(parent) === 'object') {
+            if (!overlay) {
+                overlay = new Object();
+                overlay['opacity'] = 0;
+                overlay['color'] = 'white';
+                overlay['text'] = '';
+                overlay['style'] = '';
+            }
+            if (!busy) {
+                busy = new Object();
+                busy['size'] = 32;
+                busy['color'] = '#000';
+                busy['type'] = 'tube';
+                busy['iradius'] = 8;
+                busy['weight'] = 3;
+                busy['count'] = 12;
+                busy['speed'] = 96;
+                busy['minopac'] = .25;
+            }
+            opacity = Math.max(0.0, Math.min(1.0, (typeof overlay['opacity'] === 'number' ? overlay['opacity'] : 0) || 0));
+            color = (typeof overlay['color'] === 'string' ? overlay['color'] : 'white');
+            text = (typeof overlay['text'] === 'string' ? overlay['text'] : '');
+            styles = (typeof overlay['style'] === 'string' ? overlay['style'] : '');
+            canvas = document.createElement("canvas");
+            isCV = canvas.getContext ? 1 : 0;
+            isWK = navigator.userAgent.indexOf('WebKit') > -1 ? 1 : 0;
+            isGE = navigator.userAgent.indexOf('Gecko') > -1 && window.updateCommands ? 1 : 0;
+            isIE = navigator.appName == 'Microsoft Internet Explorer' && window.navigator.systemLanguage && !window.opera && (!document.documentMode || document.documentMode < 9) ? 1 : 0;
+            isVL = document.all && document.namespaces && (!document.documentMode || document.documentMode < 9) ? 1 : 0;
+            outer = document.createElement('div');
+            parent.style.position = (cs.position == 'static' ? 'relative' : cs.position);
+            cz = parent.style.zIndex >= 0 ? (parent.style.zIndex - 0 + 2) : 2;
+            if (isIE && !cs.hasLayout) {
+                parent.style.zoom = 1;
+            }
+            outer.style.position = 'absolute';
+            outer.style.overflow = 'hidden';
+            outer.style.display = 'block';
+            outer.style.zIndex = cz;
+            outer.style.left = 0 + 'px';
+            outer.style.top = 0 + 'px';
+            outer.style.width = '100%';
+            outer.style.height = '100%';
+            if (isIE) {
+                outer.className = 'buzy_ele';
+                outer.style.zoom = 1;
+                outer.style.margin = '0px';
+                outer.style.padding = '0px';
+                outer.style.height = (parent.offsetHeight - parseWidth(cs.borderBottomWidth) - parseWidth(cs.borderTopWidth));
+                outer.style.width = (parent.offsetWidth - parseWidth(cs.borderLeftWidth) - parseWidth(cs.borderRightWidth));
+            }
+            if (typeof(cs.borderRadius) == "undefined") {
+                if (typeof(cs.MozBorderRadius) != "undefined") {
+                    lt = parseFloat(cs.MozBorderRadiusTopleft) - Math.min(parseFloat(cs.borderLeftWidth), parseFloat(cs.borderTopWidth));
+                    rt = parseFloat(cs.MozBorderRadiusTopright) - Math.min(parseFloat(cs.borderRightWidth), parseFloat(cs.borderTopWidth));
+                    lb = parseFloat(cs.MozBorderRadiusBottomleft) - Math.min(parseFloat(cs.borderLeftWidth), parseFloat(cs.borderBottomWidth));
+                    rb = parseFloat(cs.MozBorderRadiusBottomright) - Math.min(parseFloat(cs.borderRightWidth), parseFloat(cs.borderBottomWidth));
+                    outer.style.MozBorderRadiusTopleft = lt + "px";
+                    outer.style.MozBorderRadiusTopright = rt + "px";
+                    outer.style.MozBorderRadiusBottomleft = lb + "px";
+                    outer.style.MozBorderRadiusBottomright = rb + "px";
+                } else if (typeof(cs.WebkitBorderRadius) != "undefined") {
+                    lt = parseFloat(cs.WebkitBorderTopLeftRadius) - Math.min(parseFloat(cs.borderLeftWidth), parseFloat(cs.borderTopWidth));
+                    rt = parseFloat(cs.WebkitBorderTopRightRadius) - Math.min(parseFloat(cs.borderRightWidth), parseFloat(cs.borderTopWidth));
+                    lb = parseFloat(cs.WebkitBorderBottomLeftRadius) - Math.min(parseFloat(cs.borderLeftWidth), parseFloat(cs.borderBottomWidth));
+                    rb = parseFloat(cs.WebkitBorderBottomRightRadius) - Math.min(parseFloat(cs.borderRightWidth), parseFloat(cs.borderBottomWidth));
+                    outer.style.WebkitBorderTopLeftRadius = lt + "px";
+                    outer.style.WebkitBorderTopRightRadius = rt + "px";
+                    outer.style.WebkitBorderBottomLeftRadius = lb + "px";
+                    outer.style.WebkitBorderBottomRightRadius = rb + "px";
+                }
+            } else {
+                lt = parseFloat(cs.borderTopLeftRadius) - Math.min(parseFloat(cs.borderLeftWidth), parseFloat(cs.borderTopWidth));
+                rt = parseFloat(cs.borderTopRightRadius) - Math.min(parseFloat(cs.borderRightWidth), parseFloat(cs.borderTopWidth));
+                lb = parseFloat(cs.borderBottomLeftRadius) - Math.min(parseFloat(cs.borderLeftWidth), parseFloat(cs.borderBottomWidth));
+                rb = parseFloat(cs.borderBottomRightRadius) - Math.min(parseFloat(cs.borderRightWidth), parseFloat(cs.borderBottomWidth));
+                outer.style.borderTopLeftRadius = lt + "px";
+                outer.style.borderTopRightRadius = rt + "px";
+                outer.style.borderBottomLeftRadius = lb + "px";
+                outer.style.borderBottomRightRadius = rb + "px";
+            }
+            parent.appendChild(outer);
+            inner = document.createElement('div');
+            inner.style.position = 'absolute';
+            inner.style.cursor = 'progress';
+            inner.style.display = 'block';
+            inner.style.zIndex = (cz - 1);
+            inner.style.left = 0 + 'px';
+            inner.style.top = 0 + 'px';
+            inner.style.width = 100 + '%';
+            inner.style.height = 100 + '%';
+            inner.style.backgroundColor = color;
+            if (isIE) {
+                inner.style.zoom = 1;
+                inner.style.margin = '0px';
+                inner.style.padding = '0px';
+                inner.style.height = outer.style.height;
+                inner.style.width = outer.style.width;
+            }
+            if (typeof(cs.borderRadius) == "undefined") {
+                if (typeof(cs.MozBorderRadius) != "undefined") {
+                    inner.style.MozBorderRadiusTopleft = lt + "px";
+                    inner.style.MozBorderRadiusTopright = rt + "px";
+                    inner.style.MozBorderRadiusBottomleft = lb + "px";
+                    inner.style.MozBorderRadiusBottomright = rb + "px";
+                } else if (typeof(cs.WebkitBorderRadius) != "undefined") {
+                    inner.style.WebkitBorderTopLeftRadius = lt + "px";
+                    inner.style.WebkitBorderTopRightRadius = rt + "px";
+                    inner.style.WebkitBorderBottomLeftRadius = lb + "px";
+                    inner.style.WebkitBorderBottomRightRadius = rb + "px";
+                }
+            } else {
+                inner.style.borderTopLeftRadius = lt + "px";
+                inner.style.borderTopRightRadius = rt + "px";
+                inner.style.borderBottomLeftRadius = lb + "px";
+                inner.style.borderBottomRightRadius = rb + "px";
+            }
+            if (isIE) {
+                inner.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + parseInt(opacity * 100) + ")";
+            } else {
+                inner.style.opacity = opacity;
+            }
+            outer.appendChild(inner);
+            size = Math.max(16, Math.min(512, (typeof busy['size'] === 'number' ? (busy['size'] == 0 ? 32 : busy['size']) : 32)));
+            if (isVL) {
+                if (document.namespaces['v'] == null) {
+                    var e = ["shape", "shapetype", "group", "background", "path", "formulas", "handles", "fill", "stroke", "shadow", "textbox", "textpath", "imagedata", "line", "polyline", "curve", "roundrect", "oval", "rect", "arc", "image"], s = document.createStyleSheet();
+                    for (i = 0; i < e.length; i++) {
+                        s.addRule("v\\:" + e[i], "behavior: url(#default#VML);");
+                    }
+                    document.namespaces.add("v", "urn:schemas-microsoft-com:vml");
+                }
+            }
+            if (!isCV) {
+                canvas = document.createElement("div");
+            }
+            canvas.style.position = 'absolute';
+            canvas.style.cursor = 'progress';
+            canvas.style.zIndex = (cz - 0 + 1);
+            canvas.style.top = '50%';
+            canvas.style.left = '50%';
+            canvas.style.marginTop = '-' + (size / 2) + 'px';
+            canvas.style.marginLeft = '-' + (size / 2) + 'px';
+            canvas.width = size;
+            canvas.height = size;
+            canvas.style.width = size + "px";
+            canvas.style.height = size + "px";
+            outer.appendChild(canvas);
+            if (text != "") {
+                string = document.createElement('div');
+                string.style.position = 'absolute';
+                string.style.overflow = 'hidden';
+                string.style.cursor = 'progress';
+                string.style.zIndex = (cz - 0 + 1);
+                string.style.top = '50%';
+                string.style.left = '0px';
+                string.style.marginTop = 2 + (size / 2) + 'px';
+                string.style.textAlign = 'center';
+                string.style.width = 100 + '%';
+                string.style.height = 'auto';
+                if (styles != "") {
+                    string.innerHTML = '<span ' + (styles.match(/:/i) ? 'style' : 'class') + '="' + styles + '">' + text + '</span>';
+                }
+                else {
+                    string.innerHTML = '<span>' + text + '</span>';
+                }
+                outer.appendChild(string);
+            }
+            if (isGE) {
+                outer.style.MozUserSelect = "none";
+                inner.style.MozUserSelect = "none";
+                canvas.style.MozUserSelect = "none";
+            } else if (isWK) {
+                outer.style.KhtmlUserSelect = "none";
+                inner.style.KhtmlUserSelect = "none";
+                canvas.style.KhtmlUserSelect = "none";
+            } else if (isIE) {
+                outer.unselectable = "on";
+                inner.unselectable = "on";
+                canvas.unselectable = "on";
+            }
+            if (isVL) {
+                ctrl = getBusyVL(canvas, busy['color'], busy['size'], busy['type'], busy['iradius'], busy['weight'], busy['count'], busy['speed'], busy['minopac']);
+                ctrl.start();
+            } else if (isCV) {
+                ctrl = getBusyCV(canvas.getContext("2d"), busy['color'], busy['size'], busy['type'], busy['iradius'], busy['weight'], busy['count'], busy['speed'], busy['minopac']);
+                ctrl.start();
+            }
+            else {
+                ctrl = getBusy(canvas, busy['color'], busy['size'], busy['type'], busy['iradius'], busy['weight'], busy['count'], busy['speed'], busy['minopac']);
+                ctrl.start();
+            }
+            if (isIE) {
+                parent.onresize = onIEWinResize;
+                if (parent.id == 'viewport' && !window.XMLHttpRequest) {
+                    window.onresize = onIEVPResize;
+                    window.onscroll = onIEVPScroll;
+                }
+            }
+            return {
+                remove: function () {
+                    if (waiting) {
+                        waiting = false;
+                        ctrl.stop();
+                        delete ctrl;
+                        parent.removeChild(outer);
+                        if (parent.id == 'viewport') {
+                            parent.style.display = 'none';
+                        }
+                    }
+                },
+                settext: function (v) {
+                    if (string && typeof(v) == 'string') {
+                        string.firstChild.innerHTML = v;
+                        return false;
+                    }
+                }
+            };
+        }
+    }
 }
-function getBusy(obj,cl,sz,tp,ir,w,ct,sp,mo) {
-	function getHEX(v) {var col=v||'#000000';
-		if(!col.match(/^#[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]$/i)) {
-			if(v.match(/^#[0-9a-f][0-9a-f][0-9a-f]$/i)) {col='#'+v.substr(1,1)+v.substr(1,1)+v.substr(2,1)+v.substr(2,1)+v.substr(3,1)+v.substr(3,1);}
-		}return col;
-	}
-	var running=false,i=0,os=0,al=0,f=100,c,h,p,t,x,y,v,hp,ph,sh,ele=new Array();
-	c=getHEX(cl); tp=tp||"t"; t=(tp.match(/^[coprt]/i)?tp.substr(0,1).toLowerCase():'t');
-	ct=Math.max(5,Math.min(36,ct||12)); sp=Math.max(30,Math.min(1000,sp||96));
-	sz=Math.max(16,Math.min(512,sz||32)); ir=Math.max(1,Math.min((sz/2)-2,ir||sz/4));
-	w=Math.max(1,Math.min((sz/2)-ir,w||sz/10)); mo=Math.max(0,Math.min(0.5,mo||0.25));
-	al=360/ct; hp=(Math.PI/2)*-1; ph=Math.PI/180; w=(t!='c'?parseInt((w/2)*3):w); v=parseInt((sz/2)-(w/2));		
-	for(i=0;i<ct;i++) {
-		sh=document.createElement('div'); x=Math.round(v+v*Math.cos(hp+(i+1)*al*ph)); y=Math.round(v+v*Math.sin(hp+(i+1)*al*ph));
-		sh.style.position='absolute'; sh.style.margin='0px'; sh.style.width=w+'px'; sh.style.height=w+'px';
-		sh.style.lineHeight='1px'; sh.style.fontSize='0px'; sh.style.top=y+'px'; sh.style.left=x+'px'; sh.style.backgroundColor=c;
-		if(document.all&&!window.opera&&(!document.documentMode||document.documentMode<9)) {sh.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity="+parseInt(Math.min(1,Math.max(mo,1-((ct+1-i)/(ct+1))))*100)+")";}else {sh.style.opacity=Math.min(1,Math.max(mo,1-((ct+1-i)/(ct+1))));}
-		obj.appendChild(sh); ele[i]=sh;
-	}
-	function nextLoop(){
-		if(!running) {return;} os=(os+1)%ct; 
-		if(document.all&&!window.opera&&(!document.documentMode||document.documentMode<9)) {for(i=0;i<ct;i++){al=((os+i)%ct); ele[al].style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity="+parseInt(Math.min(1,Math.max(mo,1-((ct+1-i)/(ct+1))))*100)+")";}}
-		else {for(i=0;i<ct;i++){al=((os+i)%ct); ele[al].style.opacity=Math.min(1,Math.max(mo,1-((ct+1-i)/(ct+1))));}} 
-		setTimeout(nextLoop,sp);
-	}
-	nextLoop(0);
-	return {
-		start: function (){if(!running){running=true; nextLoop(0);}},
-		stop: function (){running=false; for(i=0;i<ct;i++) {if(document.all&&!window.opera&&(!document.documentMode||document.documentMode<9)) {ele[i].style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity=0)";}else {ele[i].setAttribute('opacity',0);}}},
-		pause: function (){running=false; }
-	};
+function getBusy(obj, cl, sz, tp, ir, w, ct, sp, mo) {
+    function getHEX(v) {
+        var col = v || '#000000';
+        if (!col.match(/^#[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]$/i)) {
+            if (v.match(/^#[0-9a-f][0-9a-f][0-9a-f]$/i)) {
+                col = '#' + v.substr(1, 1) + v.substr(1, 1) + v.substr(2, 1) + v.substr(2, 1) + v.substr(3, 1) + v.substr(3, 1);
+            }
+        }
+        return col;
+    }
+
+    var running = false, i = 0, os = 0, al = 0, f = 100, c, h, p, t, x, y, v, hp, ph, sh, ele = new Array();
+    c = getHEX(cl);
+    tp = tp || "t";
+    t = (tp.match(/^[coprt]/i) ? tp.substr(0, 1).toLowerCase() : 't');
+    ct = Math.max(5, Math.min(36, ct || 12));
+    sp = Math.max(30, Math.min(1000, sp || 96));
+    sz = Math.max(16, Math.min(512, sz || 32));
+    ir = Math.max(1, Math.min((sz / 2) - 2, ir || sz / 4));
+    w = Math.max(1, Math.min((sz / 2) - ir, w || sz / 10));
+    mo = Math.max(0, Math.min(0.5, mo || 0.25));
+    al = 360 / ct;
+    hp = (Math.PI / 2) * -1;
+    ph = Math.PI / 180;
+    w = (t != 'c' ? parseInt((w / 2) * 3) : w);
+    v = parseInt((sz / 2) - (w / 2));
+    for (i = 0; i < ct; i++) {
+        sh = document.createElement('div');
+        x = Math.round(v + v * Math.cos(hp + (i + 1) * al * ph));
+        y = Math.round(v + v * Math.sin(hp + (i + 1) * al * ph));
+        sh.style.position = 'absolute';
+        sh.style.margin = '0px';
+        sh.style.width = w + 'px';
+        sh.style.height = w + 'px';
+        sh.style.lineHeight = '1px';
+        sh.style.fontSize = '0px';
+        sh.style.top = y + 'px';
+        sh.style.left = x + 'px';
+        sh.style.backgroundColor = c;
+        if (document.all && !window.opera && (!document.documentMode || document.documentMode < 9)) {
+            sh.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + parseInt(Math.min(1, Math.max(mo, 1 - ((ct + 1 - i) / (ct + 1)))) * 100) + ")";
+        } else {
+            sh.style.opacity = Math.min(1, Math.max(mo, 1 - ((ct + 1 - i) / (ct + 1))));
+        }
+        obj.appendChild(sh);
+        ele[i] = sh;
+    }
+    function nextLoop() {
+        if (!running) {
+            return;
+        }
+        os = (os + 1) % ct;
+        if (document.all && !window.opera && (!document.documentMode || document.documentMode < 9)) {
+            for (i = 0; i < ct; i++) {
+                al = ((os + i) % ct);
+                ele[al].style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + parseInt(Math.min(1, Math.max(mo, 1 - ((ct + 1 - i) / (ct + 1)))) * 100) + ")";
+            }
+        }
+        else {
+            for (i = 0; i < ct; i++) {
+                al = ((os + i) % ct);
+                ele[al].style.opacity = Math.min(1, Math.max(mo, 1 - ((ct + 1 - i) / (ct + 1))));
+            }
+        }
+        setTimeout(nextLoop, sp);
+    }
+
+    nextLoop(0);
+    return {
+        start: function () {
+            if (!running) {
+                running = true;
+                nextLoop(0);
+            }
+        },
+        stop: function () {
+            running = false;
+            for (i = 0; i < ct; i++) {
+                if (document.all && !window.opera && (!document.documentMode || document.documentMode < 9)) {
+                    ele[i].style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=0)";
+                } else {
+                    ele[i].setAttribute('opacity', 0);
+                }
+            }
+        },
+        pause: function () {
+            running = false;
+        }
+    };
 }
-function getBusyVL(obj,cl,sz,tp,ir,w,ct,sp,mo) {
-	function getHEX(v) {var col=v||'#000000';
-		if(!col.match(/^#[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]$/i)) {
-			if(v.match(/^#[0-9a-f][0-9a-f][0-9a-f]$/i)) {col='#'+v.substr(1,1)+v.substr(1,1)+v.substr(2,1)+v.substr(2,1)+v.substr(3,1)+v.substr(3,1);}
-		}return col;
-	}
-	var running=false,os=0,al=0,f=100,c,i,h,p,t,x,y,hs,qs,hw,qw,rp,sh,fl,ele=new Array();
-	c=getHEX(cl); tp=tp||"t"; t=(tp.match(/^[coprt]/i)?tp.substr(0,1).toLowerCase():'t');
-	ct=Math.max(5,Math.min(36,ct||12)); sp=Math.max(30,Math.min(1000,sp||96));
-	sz=Math.max(16,Math.min(512,sz||32)); ir=Math.max(1,Math.min((sz/2)-2,ir||sz/4));
-	w=Math.max(1,Math.min((sz/2)-ir,w||sz/10)); mo=Math.max(0,Math.min(0.5,mo||0.25));
-	h=(sz/2)-ir; x=sz/2; y=x; al=360/ct; hs=parseInt((sz/2)*f); qs=parseInt(hs/2); 
-	hw=parseInt((w/2)*f); qw=parseInt(hw/2); rp=hs-parseInt(ir*f); 
-	switch(t) {
-		case "c": p='m '+hs+','+(rp-hw)+' ar '+(hs-hw)+','+(rp-hw-hw)+','+(hs+hw)+','+rp+','+(hs-hw)+','+(rp-hw-hw)+','+(hs-hw)+','+(rp-hw-hw)+' e'; break;
-		case "p": p='m '+(hs-qw)+',0 l '+(hs-hw)+','+rp+','+(hs+hw)+','+rp+','+(hs+qw)+',0 x e'; break;
-		case "o": p='m '+hs+','+(rp-qs)+' ar '+(hs-hw)+',0,'+(hs+hw)+','+rp+','+(hs-hw)+',0,'+(hs-hw)+',0 e'; break;
-		case "t": p='m '+(hs-hw)+','+rp+' l '+(hs-hw)+','+hw+' qy '+hs+',0 qx '+(hs+hw)+','+hw+' l '+(hs+hw)+','+rp+' x e'; break;
-		default: p='m '+(hs-hw)+',0 l '+(hs-hw)+','+rp+','+(hs+hw)+','+rp+','+(hs+hw)+',0 x e'; break;
-	} 
-	for(i=0;i<ct;i++) {
-		sh=document.createElement('v:shape'); sh.setAttribute('filled','t'); sh.setAttribute('stroked','f');
-		sh.setAttribute('coordorigin','0,0'); sh.setAttribute('coordsize',(sz*f)+','+(sz*f));
-		sh.setAttribute('path',p); sh.style.rotation=(i*al); sh.style.position='absolute'; sh.style.margin='0px';
-		sh.style.width=sz+'px'; sh.style.height=sz+'px'; sh.style.top='-1px'; sh.style.left='-1px';
-		obj.appendChild(sh); fl=document.createElement('v:fill');
-		fl.setAttribute('opacity',Math.min(1,Math.max(mo,1-((ct+1-i)/(ct+1)))));
-		fl.setAttribute('color',c); sh.appendChild(fl); ele[i]=fl;
-	}
-	function nextLoop(){
-		if(!running) {return;} os=(os+1)%ct; 
-		if(document.documentMode==8) {
-			for(i=0;i<ct;i++) {al=((os+i)%ct); ele[al].opacity=Math.min(1,Math.max(mo,1-((ct+1-i)/(ct+1))));}
-		}else {
-			for(i=0;i<ct;i++) {al=((os+i)%ct); ele[al].setAttribute('opacity',Math.min(1,Math.max(mo,1-((ct+1-i)/(ct+1)))));}
-		}
-		setTimeout(nextLoop,sp);
-	}
-	nextLoop(0);
-	return {
-		start: function (){if(!running){running=true; nextLoop(0);}},
-		stop: function (){running=false; for(i=0;i<ct;i++) {ele[i].setAttribute('opacity',0);}},
-		pause: function (){running=false; }
-	};
+function getBusyVL(obj, cl, sz, tp, ir, w, ct, sp, mo) {
+    function getHEX(v) {
+        var col = v || '#000000';
+        if (!col.match(/^#[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]$/i)) {
+            if (v.match(/^#[0-9a-f][0-9a-f][0-9a-f]$/i)) {
+                col = '#' + v.substr(1, 1) + v.substr(1, 1) + v.substr(2, 1) + v.substr(2, 1) + v.substr(3, 1) + v.substr(3, 1);
+            }
+        }
+        return col;
+    }
+
+    var running = false, os = 0, al = 0, f = 100, c, i, h, p, t, x, y, hs, qs, hw, qw, rp, sh, fl, ele = new Array();
+    c = getHEX(cl);
+    tp = tp || "t";
+    t = (tp.match(/^[coprt]/i) ? tp.substr(0, 1).toLowerCase() : 't');
+    ct = Math.max(5, Math.min(36, ct || 12));
+    sp = Math.max(30, Math.min(1000, sp || 96));
+    sz = Math.max(16, Math.min(512, sz || 32));
+    ir = Math.max(1, Math.min((sz / 2) - 2, ir || sz / 4));
+    w = Math.max(1, Math.min((sz / 2) - ir, w || sz / 10));
+    mo = Math.max(0, Math.min(0.5, mo || 0.25));
+    h = (sz / 2) - ir;
+    x = sz / 2;
+    y = x;
+    al = 360 / ct;
+    hs = parseInt((sz / 2) * f);
+    qs = parseInt(hs / 2);
+    hw = parseInt((w / 2) * f);
+    qw = parseInt(hw / 2);
+    rp = hs - parseInt(ir * f);
+    switch (t) {
+        case "c":
+            p = 'm ' + hs + ',' + (rp - hw) + ' ar ' + (hs - hw) + ',' + (rp - hw - hw) + ',' + (hs + hw) + ',' + rp + ',' + (hs - hw) + ',' + (rp - hw - hw) + ',' + (hs - hw) + ',' + (rp - hw - hw) + ' e';
+            break;
+        case "p":
+            p = 'm ' + (hs - qw) + ',0 l ' + (hs - hw) + ',' + rp + ',' + (hs + hw) + ',' + rp + ',' + (hs + qw) + ',0 x e';
+            break;
+        case "o":
+            p = 'm ' + hs + ',' + (rp - qs) + ' ar ' + (hs - hw) + ',0,' + (hs + hw) + ',' + rp + ',' + (hs - hw) + ',0,' + (hs - hw) + ',0 e';
+            break;
+        case "t":
+            p = 'm ' + (hs - hw) + ',' + rp + ' l ' + (hs - hw) + ',' + hw + ' qy ' + hs + ',0 qx ' + (hs + hw) + ',' + hw + ' l ' + (hs + hw) + ',' + rp + ' x e';
+            break;
+        default:
+            p = 'm ' + (hs - hw) + ',0 l ' + (hs - hw) + ',' + rp + ',' + (hs + hw) + ',' + rp + ',' + (hs + hw) + ',0 x e';
+            break;
+    }
+    for (i = 0; i < ct; i++) {
+        sh = document.createElement('v:shape');
+        sh.setAttribute('filled', 't');
+        sh.setAttribute('stroked', 'f');
+        sh.setAttribute('coordorigin', '0,0');
+        sh.setAttribute('coordsize', (sz * f) + ',' + (sz * f));
+        sh.setAttribute('path', p);
+        sh.style.rotation = (i * al);
+        sh.style.position = 'absolute';
+        sh.style.margin = '0px';
+        sh.style.width = sz + 'px';
+        sh.style.height = sz + 'px';
+        sh.style.top = '-1px';
+        sh.style.left = '-1px';
+        obj.appendChild(sh);
+        fl = document.createElement('v:fill');
+        fl.setAttribute('opacity', Math.min(1, Math.max(mo, 1 - ((ct + 1 - i) / (ct + 1)))));
+        fl.setAttribute('color', c);
+        sh.appendChild(fl);
+        ele[i] = fl;
+    }
+    function nextLoop() {
+        if (!running) {
+            return;
+        }
+        os = (os + 1) % ct;
+        if (document.documentMode == 8) {
+            for (i = 0; i < ct; i++) {
+                al = ((os + i) % ct);
+                ele[al].opacity = Math.min(1, Math.max(mo, 1 - ((ct + 1 - i) / (ct + 1))));
+            }
+        } else {
+            for (i = 0; i < ct; i++) {
+                al = ((os + i) % ct);
+                ele[al].setAttribute('opacity', Math.min(1, Math.max(mo, 1 - ((ct + 1 - i) / (ct + 1)))));
+            }
+        }
+        setTimeout(nextLoop, sp);
+    }
+
+    nextLoop(0);
+    return {
+        start: function () {
+            if (!running) {
+                running = true;
+                nextLoop(0);
+            }
+        },
+        stop: function () {
+            running = false;
+            for (i = 0; i < ct; i++) {
+                ele[i].setAttribute('opacity', 0);
+            }
+        },
+        pause: function () {
+            running = false;
+        }
+    };
 }
-function getBusyCV(ctx,cl,sz,tp,ir,w,ct,sp,mo) {
-	function getRGB(v){
-		function hex2dec(h){return(Math.max(0,Math.min(parseInt(h,16),255)));}
-		var r=0,g=0,b=0; v=v||'#000'; if(v.match(/^#[0-9a-f][0-9a-f][0-9a-f]$/i)) {
-			r=hex2dec(v.substr(1,1)+v.substr(1,1)),g=hex2dec(v.substr(2,1)+v.substr(2,1)),b=hex2dec(v.substr(3,1)+v.substr(3,1));
-		}else if(v.match(/^#[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]$/i)) {
-			r=hex2dec(v.substr(1,2)),g=hex2dec(v.substr(3,2)),b=hex2dec(v.substr(5,2));
-		} return r+','+g+','+b;
-	}
-	function drawOval(ctx,w,h){ctx.beginPath(); ctx.moveTo(-w/2,h/2); ctx.quadraticCurveTo(-w/2,0,0,0); ctx.quadraticCurveTo(w/2,0,w/2,h/2); ctx.quadraticCurveTo(w/2,h,0,h); ctx.quadraticCurveTo(-w/2,h,-w/2,h/2); ctx.fill();}
-	function drawTube(ctx,w,h){ctx.beginPath(); ctx.moveTo(w/2,0); ctx.lineTo(-w/2,0); ctx.lineTo(-w/2,h-(w/2)); ctx.quadraticCurveTo(-w/2,h,0,h); ctx.quadraticCurveTo(w/2,h,w/2,h-(w/2)); ctx.fill();}
-	function drawPoly(ctx,w,h){ctx.beginPath(); ctx.moveTo(w/2,0); ctx.lineTo(-w/2,0); ctx.lineTo(-w/4,h); ctx.lineTo(w/4,h); ctx.fill();}
-	function drawCirc(ctx,r,z){ctx.beginPath(); ctx.arc(r,r,r,0,Math.PI*2,false); ctx.fill();}  
-	var running=false,os=0,al=0,c,i,h,t,x,y;
-	c=getRGB(cl); tp=tp||"t"; t=(tp.match(/^[coprt]/i)?tp.substr(0,1).toLowerCase():'t');
-	ct=Math.max(5,Math.min(36,ct||12)); sp=Math.max(30,Math.min(1000,sp||96));
-	sz=Math.max(16,Math.min(512,sz||32)); ir=Math.max(1,Math.min((sz/2)-2,ir||sz/4));
-	w=Math.max(1,Math.min((sz/2)-ir,w||sz/10)); mo=Math.max(0,Math.min(0.5,mo||0.25));
-	h=(sz/2)-ir; x=sz/2; y=x;
-	function nextLoop(){
-		if(!running) {return;} os=(os+1)%ct; ctx.clearRect(0,0,sz,sz); ctx.save(); ctx.translate(x,y);
-		for(i=0;i<ct;i++) {al=2*((os+i)%ct)*Math.PI/ct; 
-			ctx.save(); ctx.translate(ir*Math.sin(-al),ir*Math.cos(-al)); ctx.rotate(al);
-			ctx.fillStyle='rgba('+c+','+Math.min(1,Math.max(mo,1-((ct+1-i)/(ct+1))))+')';
-			switch(t) {case "c": drawCirc(ctx,w/2,h); break; case "o": drawOval(ctx,w,h); break; case "p": drawPoly(ctx,w,h); break; case "t": drawTube(ctx,w,h); break; default: ctx.fillRect(-w/2,0,w,h); break;} ctx.restore();
-		} ctx.restore();
-		setTimeout(nextLoop,sp);
-	}
-	nextLoop(0);
-	return {
-		start: function (){if(!running){running=true; nextLoop(0);}},
-		stop: function (){running=false; ctx.clearRect(0,0,sz,sz); },
-		pause: function (){running=false; }
-	};
+function getBusyCV(ctx, cl, sz, tp, ir, w, ct, sp, mo) {
+    function getRGB(v) {
+        function hex2dec(h) {
+            return(Math.max(0, Math.min(parseInt(h, 16), 255)));
+        }
+
+        var r = 0, g = 0, b = 0;
+        v = v || '#000';
+        if (v.match(/^#[0-9a-f][0-9a-f][0-9a-f]$/i)) {
+            r = hex2dec(v.substr(1, 1) + v.substr(1, 1)), g = hex2dec(v.substr(2, 1) + v.substr(2, 1)), b = hex2dec(v.substr(3, 1) + v.substr(3, 1));
+        } else if (v.match(/^#[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]$/i)) {
+            r = hex2dec(v.substr(1, 2)), g = hex2dec(v.substr(3, 2)), b = hex2dec(v.substr(5, 2));
+        }
+        return r + ',' + g + ',' + b;
+    }
+
+    function drawOval(ctx, w, h) {
+        ctx.beginPath();
+        ctx.moveTo(-w / 2, h / 2);
+        ctx.quadraticCurveTo(-w / 2, 0, 0, 0);
+        ctx.quadraticCurveTo(w / 2, 0, w / 2, h / 2);
+        ctx.quadraticCurveTo(w / 2, h, 0, h);
+        ctx.quadraticCurveTo(-w / 2, h, -w / 2, h / 2);
+        ctx.fill();
+    }
+
+    function drawTube(ctx, w, h) {
+        ctx.beginPath();
+        ctx.moveTo(w / 2, 0);
+        ctx.lineTo(-w / 2, 0);
+        ctx.lineTo(-w / 2, h - (w / 2));
+        ctx.quadraticCurveTo(-w / 2, h, 0, h);
+        ctx.quadraticCurveTo(w / 2, h, w / 2, h - (w / 2));
+        ctx.fill();
+    }
+
+    function drawPoly(ctx, w, h) {
+        ctx.beginPath();
+        ctx.moveTo(w / 2, 0);
+        ctx.lineTo(-w / 2, 0);
+        ctx.lineTo(-w / 4, h);
+        ctx.lineTo(w / 4, h);
+        ctx.fill();
+    }
+
+    function drawCirc(ctx, r, z) {
+        ctx.beginPath();
+        ctx.arc(r, r, r, 0, Math.PI * 2, false);
+        ctx.fill();
+    }
+
+    var running = false, os = 0, al = 0, c, i, h, t, x, y;
+    c = getRGB(cl);
+    tp = tp || "t";
+    t = (tp.match(/^[coprt]/i) ? tp.substr(0, 1).toLowerCase() : 't');
+    ct = Math.max(5, Math.min(36, ct || 12));
+    sp = Math.max(30, Math.min(1000, sp || 96));
+    sz = Math.max(16, Math.min(512, sz || 32));
+    ir = Math.max(1, Math.min((sz / 2) - 2, ir || sz / 4));
+    w = Math.max(1, Math.min((sz / 2) - ir, w || sz / 10));
+    mo = Math.max(0, Math.min(0.5, mo || 0.25));
+    h = (sz / 2) - ir;
+    x = sz / 2;
+    y = x;
+    function nextLoop() {
+        if (!running) {
+            return;
+        }
+        os = (os + 1) % ct;
+        ctx.clearRect(0, 0, sz, sz);
+        ctx.save();
+        ctx.translate(x, y);
+        for (i = 0; i < ct; i++) {
+            al = 2 * ((os + i) % ct) * Math.PI / ct;
+            ctx.save();
+            ctx.translate(ir * Math.sin(-al), ir * Math.cos(-al));
+            ctx.rotate(al);
+            ctx.fillStyle = 'rgba(' + c + ',' + Math.min(1, Math.max(mo, 1 - ((ct + 1 - i) / (ct + 1)))) + ')';
+            switch (t) {
+                case "c":
+                    drawCirc(ctx, w / 2, h);
+                    break;
+                case "o":
+                    drawOval(ctx, w, h);
+                    break;
+                case "p":
+                    drawPoly(ctx, w, h);
+                    break;
+                case "t":
+                    drawTube(ctx, w, h);
+                    break;
+                default:
+                    ctx.fillRect(-w / 2, 0, w, h);
+                    break;
+            }
+            ctx.restore();
+        }
+        ctx.restore();
+        setTimeout(nextLoop, sp);
+    }
+
+    nextLoop(0);
+    return {
+        start: function () {
+            if (!running) {
+                running = true;
+                nextLoop(0);
+            }
+        },
+        stop: function () {
+            running = false;
+            ctx.clearRect(0, 0, sz, sz);
+        },
+        pause: function () {
+            running = false;
+        }
+    };
 }
diff --git a/media/js/lib/grid.locale-pl.js b/media/js/lib/grid.locale-pl.js
index fcba586..60cbb13 100644
--- a/media/js/lib/grid.locale-pl.js
+++ b/media/js/lib/grid.locale-pl.js
@@ -1,133 +1,139 @@
-;(function($){
-/**
- * jqGrid Polish Translation
- * Łukasz Schab lukasz@freetree.pl
- * http://FreeTree.pl
- *
- * Updated names, abbreviations, currency and date/time formats for Polish norms (also corresponding with CLDR v21.0.1 --> http://cldr.unicode.org/index)
- * Tomasz Pęczek tpeczek@gmail.com
- * http://tpeczek.blogspot.com; http://tpeczek.codeplex.com
- *
- * Dual licensed under the MIT and GPL licenses:
- * http://www.opensource.org/licenses/mit-license.php
- * http://www.gnu.org/licenses/gpl.html
-**/
-$.jgrid = $.jgrid || {};
-$.extend($.jgrid,{
-	defaults : {
-		recordtext: "Pokaż {0} - {1} z {2}",
-		emptyrecords: "Brak rekordów do pokazania",
-		loadtext: "Ładowanie...",
-		pgtext : "Strona {0} z {1}"
-	},
-	search : {
-		caption: "Wyszukiwanie...",
-		Find: "Szukaj",
-		Reset: "Czyść",
-		odata : ['równe', 'różne od', 'mniejsze od', 'co najwyżej','większe od','co najmniej', 'zaczyna się od','nie zaczyna się od','zawiera','nie zawiera','kończy się na','nie kończy się na','zawiera','nie zawiera','jest null','nie jest null','pasuje do wzorca','nie pasuje do wzorca','na pewno równy','na pewno inny','być może równy','być może inny'],
-		groupOps: [	{ op: "AND", text: "oraz" },	{ op: "OR",  text: "lub" }	],
-		matchText: " pasuje",
-		rulesText: " reguły"
-	},
-	edit : {
-		addCaption: "Dodaj rekord",
-		editCaption: "Edytuj rekord",
-		bSubmit: "Zapisz",
-		bCancel: "Anuluj",
-		bClose: "Zamknij",
-		saveData: "Dane zostały zmienione! Zapisać zmiany?",
-		bYes: "Tak",
-		bNo: "Nie",
-		bExit: "Anuluj",
-		msg: {
-			required: "Pole jest wymagane",
-			number: "Proszę wpisać poprawną liczbę",
-			minValue: "wartość musi być większa lub równa od",
-			maxValue: "wartość musi być mniejsza lub równa od",
-			email: "nie jest poprawnym adresem e-mail",
-			integer: "Proszę wpisać poprawną liczbę",
-			date: "Proszę podaj poprawną datę",
-			url: "jest niewłaściwym adresem URL. Pamiętaj o prefiksie ('http://' lub 'https://')",
-			nodefined: " niezdefiniowane!",
-			novalue: " wymagana jest wartość zwracana!",
-			customarray: "Funkcja niestandardowa powinna zwracać tablicę!",
-			customfcheck: "Funkcja niestandardowa powinna być obecna w przypadku niestandardowego sprawdzania!"
-		}
-	},
-	view : {
-		caption: "Pokaż rekord",
-		bClose: "Zamknij"
-	},
-	del : {
-		caption: "Usuń",
-		msg: "Czy usunąć wybrany rekord(y)?",
-		bSubmit: "Usuń",
-		bCancel: "Anuluj"
-	},
-	nav : {
-		edittext: "",
-		edittitle: "Edytuj wybrany wiersz",
-		addtext: "",
-		addtitle: "Dodaj nowy wiersz",
-		deltext: "",
-		deltitle: "Usuń wybrany wiersz",
-		searchtext: "",
-		searchtitle: "Wyszukaj rekord",
-		refreshtext: "",
-		refreshtitle: "Przeładuj",
-		alertcap: "Uwaga",
-		alerttext: "Proszę wybrać wiersz",
-		viewtext: "",
-		viewtitle: "Pokaż wybrany wiersz"
-	},
-	col : {
-		caption: "Pokaż/Ukryj kolumny",
-		bSubmit: "Zatwierdź",
-		bCancel: "Anuluj"
-	},
-	errors : {
-		errcap: "Błąd",
-		nourl: "Brak adresu url",
-		norecords: "Brak danych",
-		model : "Długość colNames <> colModel!"
-	},
-	formatter : {
-		integer : {thousandsSeparator: " ", defaultValue: '0'},
-		number : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0,00'},
-		currency : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:" zł", defaultValue: '0,00'},
-		date : {
-			dayNames:   [
-				"niedz.", "pon.", "wt.", "śr.", "czw.", "pt.", "sob.",
-				"niedziela", "poniedziałek", "wtorek", "środa", "czwartek", "piątek", "sobota"
-			],
-			monthNames: [
-				"sty", "lut", "mar", "kwi", "maj", "cze", "lip", "sie", "wrz", "paź", "lis", "gru",
-				"styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień"
-				],
-			AmPm : ["","","",""],
-			S: function (j) {return '';},
-			srcformat: 'Y-m-d',
-			newformat: 'd.m.Y',
-			masks : {
-				ISO8601Long: "Y-m-d H:i:s",
-				ISO8601Short: "Y-m-d",
-				ShortDate: "d.m.y",
-				LongDate: "l, j F Y",
-				FullDateTime: "l, j F Y H:i:s",
-				MonthDay: "j F",
-				ShortTime: "H:i",
-				LongTime: "H:i:s",
-				SortableDateTime: "Y-m-d\\TH:i:s",
-				UniversalSortableDateTime: "Y-m-d H:i:sO",
-				YearMonth: "F Y"
-			},
-			reformatAfterEdit : false
-		},
-		baseLinkUrl: '',
-		showAction: '',
-		target: '',
-		checkbox : {disabled:true},
-		idName : 'id'
-	}
-});
+;
+(function ($) {
+    /**
+     * jqGrid Polish Translation
+     * Łukasz Schab lukasz@freetree.pl
+     * http://FreeTree.pl
+     *
+     * Updated names, abbreviations, currency and date/time formats for Polish norms (also corresponding with CLDR v21.0.1 --> http://cldr.unicode.org/index)
+     * Tomasz Pęczek tpeczek@gmail.com
+     * http://tpeczek.blogspot.com; http://tpeczek.codeplex.com
+     *
+     * Dual licensed under the MIT and GPL licenses:
+     * http://www.opensource.org/licenses/mit-license.php
+     * http://www.gnu.org/licenses/gpl.html
+     **/
+    $.jgrid = $.jgrid || {};
+    $.extend($.jgrid, {
+        defaults: {
+            recordtext: "Pokaż {0} - {1} z {2}",
+            emptyrecords: "Brak rekordów do pokazania",
+            loadtext: "Ładowanie...",
+            pgtext: "Strona {0} z {1}"
+        },
+        search: {
+            caption: "Wyszukiwanie...",
+            Find: "Szukaj",
+            Reset: "Czyść",
+            odata: ['równe', 'różne od', 'mniejsze od', 'co najwyżej', 'większe od', 'co najmniej', 'zaczyna się od', 'nie zaczyna się od', 'zawiera', 'nie zawiera', 'kończy się na', 'nie kończy się na', 'zawiera', 'nie zawiera', 'jest null', 'nie jest null', 'pasuje do wzorca', 'nie pasuje do wzorca', 'na pewno równy', 'na pewno inny', 'być może równy', 'być może inny'],
+            groupOps: [
+                { op: "AND", text: "oraz" },
+                { op: "OR", text: "lub" }
+            ],
+            matchText: " pasuje",
+            rulesText: " reguły"
+        },
+        edit: {
+            addCaption: "Dodaj rekord",
+            editCaption: "Edytuj rekord",
+            bSubmit: "Zapisz",
+            bCancel: "Anuluj",
+            bClose: "Zamknij",
+            saveData: "Dane zostały zmienione! Zapisać zmiany?",
+            bYes: "Tak",
+            bNo: "Nie",
+            bExit: "Anuluj",
+            msg: {
+                required: "Pole jest wymagane",
+                number: "Proszę wpisać poprawną liczbę",
+                minValue: "wartość musi być większa lub równa od",
+                maxValue: "wartość musi być mniejsza lub równa od",
+                email: "nie jest poprawnym adresem e-mail",
+                integer: "Proszę wpisać poprawną liczbę",
+                date: "Proszę podaj poprawną datę",
+                url: "jest niewłaściwym adresem URL. Pamiętaj o prefiksie ('http://' lub 'https://')",
+                nodefined: " niezdefiniowane!",
+                novalue: " wymagana jest wartość zwracana!",
+                customarray: "Funkcja niestandardowa powinna zwracać tablicę!",
+                customfcheck: "Funkcja niestandardowa powinna być obecna w przypadku niestandardowego sprawdzania!"
+            }
+        },
+        view: {
+            caption: "Pokaż rekord",
+            bClose: "Zamknij"
+        },
+        del: {
+            caption: "Usuń",
+            msg: "Czy usunąć wybrany rekord(y)?",
+            bSubmit: "Usuń",
+            bCancel: "Anuluj"
+        },
+        nav: {
+            edittext: "",
+            edittitle: "Edytuj wybrany wiersz",
+            addtext: "",
+            addtitle: "Dodaj nowy wiersz",
+            deltext: "",
+            deltitle: "Usuń wybrany wiersz",
+            searchtext: "",
+            searchtitle: "Wyszukaj rekord",
+            refreshtext: "",
+            refreshtitle: "Przeładuj",
+            alertcap: "Uwaga",
+            alerttext: "Proszę wybrać wiersz",
+            viewtext: "",
+            viewtitle: "Pokaż wybrany wiersz"
+        },
+        col: {
+            caption: "Pokaż/Ukryj kolumny",
+            bSubmit: "Zatwierdź",
+            bCancel: "Anuluj"
+        },
+        errors: {
+            errcap: "Błąd",
+            nourl: "Brak adresu url",
+            norecords: "Brak danych",
+            model: "Długość colNames <> colModel!"
+        },
+        formatter: {
+            integer: {thousandsSeparator: " ", defaultValue: '0'},
+            number: {decimalSeparator: ",", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0,00'},
+            currency: {decimalSeparator: ",", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix: " zł", defaultValue: '0,00'},
+            date: {
+                dayNames: [
+                    "niedz.", "pon.", "wt.", "śr.", "czw.", "pt.", "sob.",
+                    "niedziela", "poniedziałek", "wtorek", "środa", "czwartek", "piątek", "sobota"
+                ],
+                monthNames: [
+                    "sty", "lut", "mar", "kwi", "maj", "cze", "lip", "sie", "wrz", "paź", "lis", "gru",
+                    "styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień"
+                ],
+                AmPm: ["", "", "", ""],
+                S: function (j) {
+                    return '';
+                },
+                srcformat: 'Y-m-d',
+                newformat: 'd.m.Y',
+                masks: {
+                    ISO8601Long: "Y-m-d H:i:s",
+                    ISO8601Short: "Y-m-d",
+                    ShortDate: "d.m.y",
+                    LongDate: "l, j F Y",
+                    FullDateTime: "l, j F Y H:i:s",
+                    MonthDay: "j F",
+                    ShortTime: "H:i",
+                    LongTime: "H:i:s",
+                    SortableDateTime: "Y-m-d\\TH:i:s",
+                    UniversalSortableDateTime: "Y-m-d H:i:sO",
+                    YearMonth: "F Y"
+                },
+                reformatAfterEdit: false
+            },
+            baseLinkUrl: '',
+            showAction: '',
+            target: '',
+            checkbox: {disabled: true},
+            idName: 'id'
+        }
+    });
 })(jQuery);
diff --git a/media/js/lib/jquery-1.7.1.js b/media/js/lib/jquery-1.7.1.js
index 8ccd0ea..b321018 100644
--- a/media/js/lib/jquery-1.7.1.js
+++ b/media/js/lib/jquery-1.7.1.js
@@ -13,9237 +13,9221 @@
  *
  * Date: Mon Nov 21 21:11:03 2011 -0500
  */
-(function( window, undefined ) {
+(function (window, undefined) {
 
 // Use the correct document accordingly with window argument (sandbox)
-var document = window.document,
-	navigator = window.navigator,
-	location = window.location;
-var jQuery = (function() {
+    var document = window.document,
+        navigator = window.navigator,
+        location = window.location;
+    var jQuery = (function () {
 
 // Define a local copy of jQuery
-var jQuery = function( selector, context ) {
-		// The jQuery object is actually just the init constructor 'enhanced'
-		return new jQuery.fn.init( selector, context, rootjQuery );
-	},
-
-	// Map over jQuery in case of overwrite
-	_jQuery = window.jQuery,
-
-	// Map over the $ in case of overwrite
-	_$ = window.$,
-
-	// A central reference to the root jQuery(document)
-	rootjQuery,
-
-	// A simple way to check for HTML strings or ID strings
-	// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
-	quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
-
-	// Check if a string has a non-whitespace character in it
-	rnotwhite = /\S/,
-
-	// Used for trimming whitespace
-	trimLeft = /^\s+/,
-	trimRight = /\s+$/,
-
-	// Match a standalone tag
-	rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
-
-	// JSON RegExp
-	rvalidchars = /^[\],:{}\s]*$/,
-	rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
-	rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
-	rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
-
-	// Useragent RegExp
-	rwebkit = /(webkit)[ \/]([\w.]+)/,
-	ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
-	rmsie = /(msie) ([\w.]+)/,
-	rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
-
-	// Matches dashed string for camelizing
-	rdashAlpha = /-([a-z]|[0-9])/ig,
-	rmsPrefix = /^-ms-/,
-
-	// Used by jQuery.camelCase as callback to replace()
-	fcamelCase = function( all, letter ) {
-		return ( letter + "" ).toUpperCase();
-	},
-
-	// Keep a UserAgent string for use with jQuery.browser
-	userAgent = navigator.userAgent,
-
-	// For matching the engine and version of the browser
-	browserMatch,
-
-	// The deferred used on DOM ready
-	readyList,
-
-	// The ready event handler
-	DOMContentLoaded,
-
-	// Save a reference to some core methods
-	toString = Object.prototype.toString,
-	hasOwn = Object.prototype.hasOwnProperty,
-	push = Array.prototype.push,
-	slice = Array.prototype.slice,
-	trim = String.prototype.trim,
-	indexOf = Array.prototype.indexOf,
-
-	// [[Class]] -> type pairs
-	class2type = {};
-
-jQuery.fn = jQuery.prototype = {
-	constructor: jQuery,
-	init: function( selector, context, rootjQuery ) {
-		var match, elem, ret, doc;
-
-		// Handle $(""), $(null), or $(undefined)
-		if ( !selector ) {
-			return this;
-		}
-
-		// Handle $(DOMElement)
-		if ( selector.nodeType ) {
-			this.context = this[0] = selector;
-			this.length = 1;
-			return this;
-		}
-
-		// The body element only exists once, optimize finding it
-		if ( selector === "body" && !context && document.body ) {
-			this.context = document;
-			this[0] = document.body;
-			this.selector = selector;
-			this.length = 1;
-			return this;
-		}
-
-		// Handle HTML strings
-		if ( typeof selector === "string" ) {
-			// Are we dealing with HTML string or an ID?
-			if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
-				// Assume that strings that start and end with <> are HTML and skip the regex check
-				match = [ null, selector, null ];
-
-			} else {
-				match = quickExpr.exec( selector );
-			}
-
-			// Verify a match, and that no context was specified for #id
-			if ( match && (match[1] || !context) ) {
-
-				// HANDLE: $(html) -> $(array)
-				if ( match[1] ) {
-					context = context instanceof jQuery ? context[0] : context;
-					doc = ( context ? context.ownerDocument || context : document );
-
-					// If a single string is passed in and it's a single tag
-					// just do a createElement and skip the rest
-					ret = rsingleTag.exec( selector );
-
-					if ( ret ) {
-						if ( jQuery.isPlainObject( context ) ) {
-							selector = [ document.createElement( ret[1] ) ];
-							jQuery.fn.attr.call( selector, context, true );
-
-						} else {
-							selector = [ doc.createElement( ret[1] ) ];
-						}
-
-					} else {
-						ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
-						selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes;
-					}
-
-					return jQuery.merge( this, selector );
-
-				// HANDLE: $("#id")
-				} else {
-					elem = document.getElementById( match[2] );
-
-					// Check parentNode to catch when Blackberry 4.6 returns
-					// nodes that are no longer in the document #6963
-					if ( elem && elem.parentNode ) {
-						// Handle the case where IE and Opera return items
-						// by name instead of ID
-						if ( elem.id !== match[2] ) {
-							return rootjQuery.find( selector );
-						}
-
-						// Otherwise, we inject the element directly into the jQuery object
-						this.length = 1;
-						this[0] = elem;
-					}
-
-					this.context = document;
-					this.selector = selector;
-					return this;
-				}
-
-			// HANDLE: $(expr, $(...))
-			} else if ( !context || context.jquery ) {
-				return ( context || rootjQuery ).find( selector );
-
-			// HANDLE: $(expr, context)
-			// (which is just equivalent to: $(context).find(expr)
-			} else {
-				return this.constructor( context ).find( selector );
-			}
-
-		// HANDLE: $(function)
-		// Shortcut for document ready
-		} else if ( jQuery.isFunction( selector ) ) {
-			return rootjQuery.ready( selector );
-		}
-
-		if ( selector.selector !== undefined ) {
-			this.selector = selector.selector;
-			this.context = selector.context;
-		}
-
-		return jQuery.makeArray( selector, this );
-	},
-
-	// Start with an empty selector
-	selector: "",
-
-	// The current version of jQuery being used
-	jquery: "1.7.1",
-
-	// The default length of a jQuery object is 0
-	length: 0,
-
-	// The number of elements contained in the matched element set
-	size: function() {
-		return this.length;
-	},
-
-	toArray: function() {
-		return slice.call( this, 0 );
-	},
-
-	// Get the Nth element in the matched element set OR
-	// Get the whole matched element set as a clean array
-	get: function( num ) {
-		return num == null ?
-
-			// Return a 'clean' array
-			this.toArray() :
-
-			// Return just the object
-			( num < 0 ? this[ this.length + num ] : this[ num ] );
-	},
-
-	// Take an array of elements and push it onto the stack
-	// (returning the new matched element set)
-	pushStack: function( elems, name, selector ) {
-		// Build a new jQuery matched element set
-		var ret = this.constructor();
-
-		if ( jQuery.isArray( elems ) ) {
-			push.apply( ret, elems );
-
-		} else {
-			jQuery.merge( ret, elems );
-		}
-
-		// Add the old object onto the stack (as a reference)
-		ret.prevObject = this;
-
-		ret.context = this.context;
-
-		if ( name === "find" ) {
-			ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
-		} else if ( name ) {
-			ret.selector = this.selector + "." + name + "(" + selector + ")";
-		}
-
-		// Return the newly-formed element set
-		return ret;
-	},
-
-	// Execute a callback for every element in the matched set.
-	// (You can seed the arguments with an array of args, but this is
-	// only used internally.)
-	each: function( callback, args ) {
-		return jQuery.each( this, callback, args );
-	},
-
-	ready: function( fn ) {
-		// Attach the listeners
-		jQuery.bindReady();
-
-		// Add the callback
-		readyList.add( fn );
-
-		return this;
-	},
-
-	eq: function( i ) {
-		i = +i;
-		return i === -1 ?
-			this.slice( i ) :
-			this.slice( i, i + 1 );
-	},
-
-	first: function() {
-		return this.eq( 0 );
-	},
-
-	last: function() {
-		return this.eq( -1 );
-	},
-
-	slice: function() {
-		return this.pushStack( slice.apply( this, arguments ),
-			"slice", slice.call(arguments).join(",") );
-	},
-
-	map: function( callback ) {
-		return this.pushStack( jQuery.map(this, function( elem, i ) {
-			return callback.call( elem, i, elem );
-		}));
-	},
-
-	end: function() {
-		return this.prevObject || this.constructor(null);
-	},
-
-	// For internal use only.
-	// Behaves like an Array's method, not like a jQuery method.
-	push: push,
-	sort: [].sort,
-	splice: [].splice
-};
+        var jQuery = function (selector, context) {
+                // The jQuery object is actually just the init constructor 'enhanced'
+                return new jQuery.fn.init(selector, context, rootjQuery);
+            },
+
+        // Map over jQuery in case of overwrite
+            _jQuery = window.jQuery,
+
+        // Map over the $ in case of overwrite
+            _$ = window.$,
+
+        // A central reference to the root jQuery(document)
+            rootjQuery,
+
+        // A simple way to check for HTML strings or ID strings
+        // Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
+            quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
+
+        // Check if a string has a non-whitespace character in it
+            rnotwhite = /\S/,
+
+        // Used for trimming whitespace
+            trimLeft = /^\s+/,
+            trimRight = /\s+$/,
+
+        // Match a standalone tag
+            rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
+
+        // JSON RegExp
+            rvalidchars = /^[\],:{}\s]*$/,
+            rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
+            rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
+            rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
+
+        // Useragent RegExp
+            rwebkit = /(webkit)[ \/]([\w.]+)/,
+            ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
+            rmsie = /(msie) ([\w.]+)/,
+            rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
+
+        // Matches dashed string for camelizing
+            rdashAlpha = /-([a-z]|[0-9])/ig,
+            rmsPrefix = /^-ms-/,
+
+        // Used by jQuery.camelCase as callback to replace()
+            fcamelCase = function (all, letter) {
+                return ( letter + "" ).toUpperCase();
+            },
+
+        // Keep a UserAgent string for use with jQuery.browser
+            userAgent = navigator.userAgent,
+
+        // For matching the engine and version of the browser
+            browserMatch,
+
+        // The deferred used on DOM ready
+            readyList,
+
+        // The ready event handler
+            DOMContentLoaded,
+
+        // Save a reference to some core methods
+            toString = Object.prototype.toString,
+            hasOwn = Object.prototype.hasOwnProperty,
+            push = Array.prototype.push,
+            slice = Array.prototype.slice,
+            trim = String.prototype.trim,
+            indexOf = Array.prototype.indexOf,
+
+        // [[Class]] -> type pairs
+            class2type = {};
+
+        jQuery.fn = jQuery.prototype = {
+            constructor: jQuery,
+            init: function (selector, context, rootjQuery) {
+                var match, elem, ret, doc;
+
+                // Handle $(""), $(null), or $(undefined)
+                if (!selector) {
+                    return this;
+                }
+
+                // Handle $(DOMElement)
+                if (selector.nodeType) {
+                    this.context = this[0] = selector;
+                    this.length = 1;
+                    return this;
+                }
+
+                // The body element only exists once, optimize finding it
+                if (selector === "body" && !context && document.body) {
+                    this.context = document;
+                    this[0] = document.body;
+                    this.selector = selector;
+                    this.length = 1;
+                    return this;
+                }
+
+                // Handle HTML strings
+                if (typeof selector === "string") {
+                    // Are we dealing with HTML string or an ID?
+                    if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3) {
+                        // Assume that strings that start and end with <> are HTML and skip the regex check
+                        match = [ null, selector, null ];
+
+                    } else {
+                        match = quickExpr.exec(selector);
+                    }
+
+                    // Verify a match, and that no context was specified for #id
+                    if (match && (match[1] || !context)) {
+
+                        // HANDLE: $(html) -> $(array)
+                        if (match[1]) {
+                            context = context instanceof jQuery ? context[0] : context;
+                            doc = ( context ? context.ownerDocument || context : document );
+
+                            // If a single string is passed in and it's a single tag
+                            // just do a createElement and skip the rest
+                            ret = rsingleTag.exec(selector);
+
+                            if (ret) {
+                                if (jQuery.isPlainObject(context)) {
+                                    selector = [ document.createElement(ret[1]) ];
+                                    jQuery.fn.attr.call(selector, context, true);
+
+                                } else {
+                                    selector = [ doc.createElement(ret[1]) ];
+                                }
+
+                            } else {
+                                ret = jQuery.buildFragment([ match[1] ], [ doc ]);
+                                selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes;
+                            }
+
+                            return jQuery.merge(this, selector);
+
+                            // HANDLE: $("#id")
+                        } else {
+                            elem = document.getElementById(match[2]);
+
+                            // Check parentNode to catch when Blackberry 4.6 returns
+                            // nodes that are no longer in the document #6963
+                            if (elem && elem.parentNode) {
+                                // Handle the case where IE and Opera return items
+                                // by name instead of ID
+                                if (elem.id !== match[2]) {
+                                    return rootjQuery.find(selector);
+                                }
+
+                                // Otherwise, we inject the element directly into the jQuery object
+                                this.length = 1;
+                                this[0] = elem;
+                            }
+
+                            this.context = document;
+                            this.selector = selector;
+                            return this;
+                        }
+
+                        // HANDLE: $(expr, $(...))
+                    } else if (!context || context.jquery) {
+                        return ( context || rootjQuery ).find(selector);
+
+                        // HANDLE: $(expr, context)
+                        // (which is just equivalent to: $(context).find(expr)
+                    } else {
+                        return this.constructor(context).find(selector);
+                    }
+
+                    // HANDLE: $(function)
+                    // Shortcut for document ready
+                } else if (jQuery.isFunction(selector)) {
+                    return rootjQuery.ready(selector);
+                }
+
+                if (selector.selector !== undefined) {
+                    this.selector = selector.selector;
+                    this.context = selector.context;
+                }
+
+                return jQuery.makeArray(selector, this);
+            },
+
+            // Start with an empty selector
+            selector: "",
+
+            // The current version of jQuery being used
+            jquery: "1.7.1",
+
+            // The default length of a jQuery object is 0
+            length: 0,
+
+            // The number of elements contained in the matched element set
+            size: function () {
+                return this.length;
+            },
+
+            toArray: function () {
+                return slice.call(this, 0);
+            },
+
+            // Get the Nth element in the matched element set OR
+            // Get the whole matched element set as a clean array
+            get: function (num) {
+                return num == null ?
+
+                    // Return a 'clean' array
+                    this.toArray() :
+
+                    // Return just the object
+                    ( num < 0 ? this[ this.length + num ] : this[ num ] );
+            },
+
+            // Take an array of elements and push it onto the stack
+            // (returning the new matched element set)
+            pushStack: function (elems, name, selector) {
+                // Build a new jQuery matched element set
+                var ret = this.constructor();
+
+                if (jQuery.isArray(elems)) {
+                    push.apply(ret, elems);
+
+                } else {
+                    jQuery.merge(ret, elems);
+                }
+
+                // Add the old object onto the stack (as a reference)
+                ret.prevObject = this;
+
+                ret.context = this.context;
+
+                if (name === "find") {
+                    ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
+                } else if (name) {
+                    ret.selector = this.selector + "." + name + "(" + selector + ")";
+                }
+
+                // Return the newly-formed element set
+                return ret;
+            },
+
+            // Execute a callback for every element in the matched set.
+            // (You can seed the arguments with an array of args, but this is
+            // only used internally.)
+            each: function (callback, args) {
+                return jQuery.each(this, callback, args);
+            },
+
+            ready: function (fn) {
+                // Attach the listeners
+                jQuery.bindReady();
+
+                // Add the callback
+                readyList.add(fn);
+
+                return this;
+            },
+
+            eq: function (i) {
+                i = +i;
+                return i === -1 ?
+                    this.slice(i) :
+                    this.slice(i, i + 1);
+            },
+
+            first: function () {
+                return this.eq(0);
+            },
+
+            last: function () {
+                return this.eq(-1);
+            },
+
+            slice: function () {
+                return this.pushStack(slice.apply(this, arguments),
+                    "slice", slice.call(arguments).join(","));
+            },
+
+            map: function (callback) {
+                return this.pushStack(jQuery.map(this, function (elem, i) {
+                    return callback.call(elem, i, elem);
+                }));
+            },
+
+            end: function () {
+                return this.prevObject || this.constructor(null);
+            },
+
+            // For internal use only.
+            // Behaves like an Array's method, not like a jQuery method.
+            push: push,
+            sort: [].sort,
+            splice: [].splice
+        };
 
 // Give the init function the jQuery prototype for later instantiation
-jQuery.fn.init.prototype = jQuery.fn;
-
-jQuery.extend = jQuery.fn.extend = function() {
-	var options, name, src, copy, copyIsArray, clone,
-		target = arguments[0] || {},
-		i = 1,
-		length = arguments.length,
-		deep = false;
-
-	// Handle a deep copy situation
-	if ( typeof target === "boolean" ) {
-		deep = target;
-		target = arguments[1] || {};
-		// skip the boolean and the target
-		i = 2;
-	}
-
-	// Handle case when target is a string or something (possible in deep copy)
-	if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
-		target = {};
-	}
-
-	// extend jQuery itself if only one argument is passed
-	if ( length === i ) {
-		target = this;
-		--i;
-	}
-
-	for ( ; i < length; i++ ) {
-		// Only deal with non-null/undefined values
-		if ( (options = arguments[ i ]) != null ) {
-			// Extend the base object
-			for ( name in options ) {
-				src = target[ name ];
-				copy = options[ name ];
-
-				// Prevent never-ending loop
-				if ( target === copy ) {
-					continue;
-				}
-
-				// Recurse if we're merging plain objects or arrays
-				if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
-					if ( copyIsArray ) {
-						copyIsArray = false;
-						clone = src && jQuery.isArray(src) ? src : [];
-
-					} else {
-						clone = src && jQuery.isPlainObject(src) ? src : {};
-					}
-
-					// Never move original objects, clone them
-					target[ name ] = jQuery.extend( deep, clone, copy );
-
-				// Don't bring in undefined values
-				} else if ( copy !== undefined ) {
-					target[ name ] = copy;
-				}
-			}
-		}
-	}
-
-	// Return the modified object
-	return target;
-};
-
-jQuery.extend({
-	noConflict: function( deep ) {
-		if ( window.$ === jQuery ) {
-			window.$ = _$;
-		}
-
-		if ( deep && window.jQuery === jQuery ) {
-			window.jQuery = _jQuery;
-		}
-
-		return jQuery;
-	},
-
-	// Is the DOM ready to be used? Set to true once it occurs.
-	isReady: false,
-
-	// A counter to track how many items to wait for before
-	// the ready event fires. See #6781
-	readyWait: 1,
-
-	// Hold (or release) the ready event
-	holdReady: function( hold ) {
-		if ( hold ) {
-			jQuery.readyWait++;
-		} else {
-			jQuery.ready( true );
-		}
-	},
-
-	// Handle when the DOM is ready
-	ready: function( wait ) {
-		// Either a released hold or an DOMready/load event and not yet ready
-		if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
-			// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
-			if ( !document.body ) {
-				return setTimeout( jQuery.ready, 1 );
-			}
-
-			// Remember that the DOM is ready
-			jQuery.isReady = true;
-
-			// If a normal DOM Ready event fired, decrement, and wait if need be
-			if ( wait !== true && --jQuery.readyWait > 0 ) {
-				return;
-			}
-
-			// If there are functions bound, to execute
-			readyList.fireWith( document, [ jQuery ] );
-
-			// Trigger any bound ready events
-			if ( jQuery.fn.trigger ) {
-				jQuery( document ).trigger( "ready" ).off( "ready" );
-			}
-		}
-	},
-
-	bindReady: function() {
-		if ( readyList ) {
-			return;
-		}
-
-		readyList = jQuery.Callbacks( "once memory" );
-
-		// Catch cases where $(document).ready() is called after the
-		// browser event has already occurred.
-		if ( document.readyState === "complete" ) {
-			// Handle it asynchronously to allow scripts the opportunity to delay ready
-			return setTimeout( jQuery.ready, 1 );
-		}
-
-		// Mozilla, Opera and webkit nightlies currently support this event
-		if ( document.addEventListener ) {
-			// Use the handy event callback
-			document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
-
-			// A fallback to window.onload, that will always work
-			window.addEventListener( "load", jQuery.ready, false );
-
-		// If IE event model is used
-		} else if ( document.attachEvent ) {
-			// ensure firing before onload,
-			// maybe late but safe also for iframes
-			document.attachEvent( "onreadystatechange", DOMContentLoaded );
-
-			// A fallback to window.onload, that will always work
-			window.attachEvent( "onload", jQuery.ready );
-
-			// If IE and not a frame
-			// continually check to see if the document is ready
-			var toplevel = false;
-
-			try {
-				toplevel = window.frameElement == null;
-			} catch(e) {}
-
-			if ( document.documentElement.doScroll && toplevel ) {
-				doScrollCheck();
-			}
-		}
-	},
-
-	// See test/unit/core.js for details concerning isFunction.
-	// Since version 1.3, DOM methods and functions like alert
-	// aren't supported. They return false on IE (#2968).
-	isFunction: function( obj ) {
-		return jQuery.type(obj) === "function";
-	},
-
-	isArray: Array.isArray || function( obj ) {
-		return jQuery.type(obj) === "array";
-	},
-
-	// A crude way of determining if an object is a window
-	isWindow: function( obj ) {
-		return obj && typeof obj === "object" && "setInterval" in obj;
-	},
-
-	isNumeric: function( obj ) {
-		return !isNaN( parseFloat(obj) ) && isFinite( obj );
-	},
-
-	type: function( obj ) {
-		return obj == null ?
-			String( obj ) :
-			class2type[ toString.call(obj) ] || "object";
-	},
-
-	isPlainObject: function( obj ) {
-		// Must be an Object.
-		// Because of IE, we also have to check the presence of the constructor property.
-		// Make sure that DOM nodes and window objects don't pass through, as well
-		if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
-			return false;
-		}
-
-		try {
-			// Not own constructor property must be Object
-			if ( obj.constructor &&
-				!hasOwn.call(obj, "constructor") &&
-				!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
-				return false;
-			}
-		} catch ( e ) {
-			// IE8,9 Will throw exceptions on certain host objects #9897
-			return false;
-		}
-
-		// Own properties are enumerated firstly, so to speed up,
-		// if last one is own, then all properties are own.
-
-		var key;
-		for ( key in obj ) {}
-
-		return key === undefined || hasOwn.call( obj, key );
-	},
-
-	isEmptyObject: function( obj ) {
-		for ( var name in obj ) {
-			return false;
-		}
-		return true;
-	},
-
-	error: function( msg ) {
-		throw new Error( msg );
-	},
-
-	parseJSON: function( data ) {
-		if ( typeof data !== "string" || !data ) {
-			return null;
-		}
-
-		// Make sure leading/trailing whitespace is removed (IE can't handle it)
-		data = jQuery.trim( data );
-
-		// Attempt to parse using the native JSON parser first
-		if ( window.JSON && window.JSON.parse ) {
-			return window.JSON.parse( data );
-		}
-
-		// Make sure the incoming data is actual JSON
-		// Logic borrowed from http://json.org/json2.js
-		if ( rvalidchars.test( data.replace( rvalidescape, "@" )
-			.replace( rvalidtokens, "]" )
-			.replace( rvalidbraces, "")) ) {
-
-			return ( new Function( "return " + data ) )();
-
-		}
-		jQuery.error( "Invalid JSON: " + data );
-	},
-
-	// Cross-browser xml parsing
-	parseXML: function( data ) {
-		var xml, tmp;
-		try {
-			if ( window.DOMParser ) { // Standard
-				tmp = new DOMParser();
-				xml = tmp.parseFromString( data , "text/xml" );
-			} else { // IE
-				xml = new ActiveXObject( "Microsoft.XMLDOM" );
-				xml.async = "false";
-				xml.loadXML( data );
-			}
-		} catch( e ) {
-			xml = undefined;
-		}
-		if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
-			jQuery.error( "Invalid XML: " + data );
-		}
-		return xml;
-	},
-
-	noop: function() {},
-
-	// Evaluates a script in a global context
-	// Workarounds based on findings by Jim Driscoll
-	// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
-	globalEval: function( data ) {
-		if ( data && rnotwhite.test( data ) ) {
-			// We use execScript on Internet Explorer
-			// We use an anonymous function so that context is window
-			// rather than jQuery in Firefox
-			( window.execScript || function( data ) {
-				window[ "eval" ].call( window, data );
-			} )( data );
-		}
-	},
-
-	// Convert dashed to camelCase; used by the css and data modules
-	// Microsoft forgot to hump their vendor prefix (#9572)
-	camelCase: function( string ) {
-		return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
-	},
-
-	nodeName: function( elem, name ) {
-		return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
-	},
-
-	// args is for internal usage only
-	each: function( object, callback, args ) {
-		var name, i = 0,
-			length = object.length,
-			isObj = length === undefined || jQuery.isFunction( object );
-
-		if ( args ) {
-			if ( isObj ) {
-				for ( name in object ) {
-					if ( callback.apply( object[ name ], args ) === false ) {
-						break;
-					}
-				}
-			} else {
-				for ( ; i < length; ) {
-					if ( callback.apply( object[ i++ ], args ) === false ) {
-						break;
-					}
-				}
-			}
-
-		// A special, fast, case for the most common use of each
-		} else {
-			if ( isObj ) {
-				for ( name in object ) {
-					if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
-						break;
-					}
-				}
-			} else {
-				for ( ; i < length; ) {
-					if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
-						break;
-					}
-				}
-			}
-		}
-
-		return object;
-	},
-
-	// Use native String.trim function wherever possible
-	trim: trim ?
-		function( text ) {
-			return text == null ?
-				"" :
-				trim.call( text );
-		} :
-
-		// Otherwise use our own trimming functionality
-		function( text ) {
-			return text == null ?
-				"" :
-				text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
-		},
-
-	// results is for internal usage only
-	makeArray: function( array, results ) {
-		var ret = results || [];
-
-		if ( array != null ) {
-			// The window, strings (and functions) also have 'length'
-			// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
-			var type = jQuery.type( array );
-
-			if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
-				push.call( ret, array );
-			} else {
-				jQuery.merge( ret, array );
-			}
-		}
-
-		return ret;
-	},
-
-	inArray: function( elem, array, i ) {
-		var len;
-
-		if ( array ) {
-			if ( indexOf ) {
-				return indexOf.call( array, elem, i );
-			}
-
-			len = array.length;
-			i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
-
-			for ( ; i < len; i++ ) {
-				// Skip accessing in sparse arrays
-				if ( i in array && array[ i ] === elem ) {
-					return i;
-				}
-			}
-		}
-
-		return -1;
-	},
-
-	merge: function( first, second ) {
-		var i = first.length,
-			j = 0;
-
-		if ( typeof second.length === "number" ) {
-			for ( var l = second.length; j < l; j++ ) {
-				first[ i++ ] = second[ j ];
-			}
-
-		} else {
-			while ( second[j] !== undefined ) {
-				first[ i++ ] = second[ j++ ];
-			}
-		}
-
-		first.length = i;
-
-		return first;
-	},
-
-	grep: function( elems, callback, inv ) {
-		var ret = [], retVal;
-		inv = !!inv;
-
-		// Go through the array, only saving the items
-		// that pass the validator function
-		for ( var i = 0, length = elems.length; i < length; i++ ) {
-			retVal = !!callback( elems[ i ], i );
-			if ( inv !== retVal ) {
-				ret.push( elems[ i ] );
-			}
-		}
-
-		return ret;
-	},
-
-	// arg is for internal usage only
-	map: function( elems, callback, arg ) {
-		var value, key, ret = [],
-			i = 0,
-			length = elems.length,
-			// jquery objects are treated as arrays
-			isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
-
-		// Go through the array, translating each of the items to their
-		if ( isArray ) {
-			for ( ; i < length; i++ ) {
-				value = callback( elems[ i ], i, arg );
-
-				if ( value != null ) {
-					ret[ ret.length ] = value;
-				}
-			}
-
-		// Go through every key on the object,
-		} else {
-			for ( key in elems ) {
-				value = callback( elems[ key ], key, arg );
-
-				if ( value != null ) {
-					ret[ ret.length ] = value;
-				}
-			}
-		}
-
-		// Flatten any nested arrays
-		return ret.concat.apply( [], ret );
-	},
-
-	// A global GUID counter for objects
-	guid: 1,
-
-	// Bind a function to a context, optionally partially applying any
-	// arguments.
-	proxy: function( fn, context ) {
-		if ( typeof context === "string" ) {
-			var tmp = fn[ context ];
-			context = fn;
-			fn = tmp;
-		}
-
-		// Quick check to determine if target is callable, in the spec
-		// this throws a TypeError, but we will just return undefined.
-		if ( !jQuery.isFunction( fn ) ) {
-			return undefined;
-		}
-
-		// Simulated bind
-		var args = slice.call( arguments, 2 ),
-			proxy = function() {
-				return fn.apply( context, args.concat( slice.call( arguments ) ) );
-			};
-
-		// Set the guid of unique handler to the same of original handler, so it can be removed
-		proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
-
-		return proxy;
-	},
-
-	// Mutifunctional method to get and set values to a collection
-	// The value/s can optionally be executed if it's a function
-	access: function( elems, key, value, exec, fn, pass ) {
-		var length = elems.length;
-
-		// Setting many attributes
-		if ( typeof key === "object" ) {
-			for ( var k in key ) {
-				jQuery.access( elems, k, key[k], exec, fn, value );
-			}
-			return elems;
-		}
-
-		// Setting one attribute
-		if ( value !== undefined ) {
-			// Optionally, function values get executed if exec is true
-			exec = !pass && exec && jQuery.isFunction(value);
-
-			for ( var i = 0; i < length; i++ ) {
-				fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
-			}
-
-			return elems;
-		}
-
-		// Getting an attribute
-		return length ? fn( elems[0], key ) : undefined;
-	},
-
-	now: function() {
-		return ( new Date() ).getTime();
-	},
-
-	// Use of jQuery.browser is frowned upon.
-	// More details: http://docs.jquery.com/Utilities/jQuery.browser
-	uaMatch: function( ua ) {
-		ua = ua.toLowerCase();
-
-		var match = rwebkit.exec( ua ) ||
-			ropera.exec( ua ) ||
-			rmsie.exec( ua ) ||
-			ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
-			[];
-
-		return { browser: match[1] || "", version: match[2] || "0" };
-	},
-
-	sub: function() {
-		function jQuerySub( selector, context ) {
-			return new jQuerySub.fn.init( selector, context );
-		}
-		jQuery.extend( true, jQuerySub, this );
-		jQuerySub.superclass = this;
-		jQuerySub.fn = jQuerySub.prototype = this();
-		jQuerySub.fn.constructor = jQuerySub;
-		jQuerySub.sub = this.sub;
-		jQuerySub.fn.init = function init( selector, context ) {
-			if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
-				context = jQuerySub( context );
-			}
-
-			return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
-		};
-		jQuerySub.fn.init.prototype = jQuerySub.fn;
-		var rootjQuerySub = jQuerySub(document);
-		return jQuerySub;
-	},
-
-	browser: {}
-});
+        jQuery.fn.init.prototype = jQuery.fn;
+
+        jQuery.extend = jQuery.fn.extend = function () {
+            var options, name, src, copy, copyIsArray, clone,
+                target = arguments[0] || {},
+                i = 1,
+                length = arguments.length,
+                deep = false;
+
+            // Handle a deep copy situation
+            if (typeof target === "boolean") {
+                deep = target;
+                target = arguments[1] || {};
+                // skip the boolean and the target
+                i = 2;
+            }
+
+            // Handle case when target is a string or something (possible in deep copy)
+            if (typeof target !== "object" && !jQuery.isFunction(target)) {
+                target = {};
+            }
+
+            // extend jQuery itself if only one argument is passed
+            if (length === i) {
+                target = this;
+                --i;
+            }
+
+            for (; i < length; i++) {
+                // Only deal with non-null/undefined values
+                if ((options = arguments[ i ]) != null) {
+                    // Extend the base object
+                    for (name in options) {
+                        src = target[ name ];
+                        copy = options[ name ];
+
+                        // Prevent never-ending loop
+                        if (target === copy) {
+                            continue;
+                        }
+
+                        // Recurse if we're merging plain objects or arrays
+                        if (deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) )) {
+                            if (copyIsArray) {
+                                copyIsArray = false;
+                                clone = src && jQuery.isArray(src) ? src : [];
+
+                            } else {
+                                clone = src && jQuery.isPlainObject(src) ? src : {};
+                            }
+
+                            // Never move original objects, clone them
+                            target[ name ] = jQuery.extend(deep, clone, copy);
+
+                            // Don't bring in undefined values
+                        } else if (copy !== undefined) {
+                            target[ name ] = copy;
+                        }
+                    }
+                }
+            }
+
+            // Return the modified object
+            return target;
+        };
+
+        jQuery.extend({
+            noConflict: function (deep) {
+                if (window.$ === jQuery) {
+                    window.$ = _$;
+                }
+
+                if (deep && window.jQuery === jQuery) {
+                    window.jQuery = _jQuery;
+                }
+
+                return jQuery;
+            },
+
+            // Is the DOM ready to be used? Set to true once it occurs.
+            isReady: false,
+
+            // A counter to track how many items to wait for before
+            // the ready event fires. See #6781
+            readyWait: 1,
+
+            // Hold (or release) the ready event
+            holdReady: function (hold) {
+                if (hold) {
+                    jQuery.readyWait++;
+                } else {
+                    jQuery.ready(true);
+                }
+            },
+
+            // Handle when the DOM is ready
+            ready: function (wait) {
+                // Either a released hold or an DOMready/load event and not yet ready
+                if ((wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady)) {
+                    // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
+                    if (!document.body) {
+                        return setTimeout(jQuery.ready, 1);
+                    }
+
+                    // Remember that the DOM is ready
+                    jQuery.isReady = true;
+
+                    // If a normal DOM Ready event fired, decrement, and wait if need be
+                    if (wait !== true && --jQuery.readyWait > 0) {
+                        return;
+                    }
+
+                    // If there are functions bound, to execute
+                    readyList.fireWith(document, [ jQuery ]);
+
+                    // Trigger any bound ready events
+                    if (jQuery.fn.trigger) {
+                        jQuery(document).trigger("ready").off("ready");
+                    }
+                }
+            },
+
+            bindReady: function () {
+                if (readyList) {
+                    return;
+                }
+
+                readyList = jQuery.Callbacks("once memory");
+
+                // Catch cases where $(document).ready() is called after the
+                // browser event has already occurred.
+                if (document.readyState === "complete") {
+                    // Handle it asynchronously to allow scripts the opportunity to delay ready
+                    return setTimeout(jQuery.ready, 1);
+                }
+
+                // Mozilla, Opera and webkit nightlies currently support this event
+                if (document.addEventListener) {
+                    // Use the handy event callback
+                    document.addEventListener("DOMContentLoaded", DOMContentLoaded, false);
+
+                    // A fallback to window.onload, that will always work
+                    window.addEventListener("load", jQuery.ready, false);
+
+                    // If IE event model is used
+                } else if (document.attachEvent) {
+                    // ensure firing before onload,
+                    // maybe late but safe also for iframes
+                    document.attachEvent("onreadystatechange", DOMContentLoaded);
+
+                    // A fallback to window.onload, that will always work
+                    window.attachEvent("onload", jQuery.ready);
+
+                    // If IE and not a frame
+                    // continually check to see if the document is ready
+                    var toplevel = false;
+
+                    try {
+                        toplevel = window.frameElement == null;
+                    } catch (e) {
+                    }
+
+                    if (document.documentElement.doScroll && toplevel) {
+                        doScrollCheck();
+                    }
+                }
+            },
+
+            // See test/unit/core.js for details concerning isFunction.
+            // Since version 1.3, DOM methods and functions like alert
+            // aren't supported. They return false on IE (#2968).
+            isFunction: function (obj) {
+                return jQuery.type(obj) === "function";
+            },
+
+            isArray: Array.isArray || function (obj) {
+                return jQuery.type(obj) === "array";
+            },
+
+            // A crude way of determining if an object is a window
+            isWindow: function (obj) {
+                return obj && typeof obj === "object" && "setInterval" in obj;
+            },
+
+            isNumeric: function (obj) {
+                return !isNaN(parseFloat(obj)) && isFinite(obj);
+            },
+
+            type: function (obj) {
+                return obj == null ?
+                    String(obj) :
+                    class2type[ toString.call(obj) ] || "object";
+            },
+
+            isPlainObject: function (obj) {
+                // Must be an Object.
+                // Because of IE, we also have to check the presence of the constructor property.
+                // Make sure that DOM nodes and window objects don't pass through, as well
+                if (!obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow(obj)) {
+                    return false;
+                }
+
+                try {
+                    // Not own constructor property must be Object
+                    if (obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
+                        return false;
+                    }
+                } catch (e) {
+                    // IE8,9 Will throw exceptions on certain host objects #9897
+                    return false;
+                }
+
+                // Own properties are enumerated firstly, so to speed up,
+                // if last one is own, then all properties are own.
+
+                var key;
+                for (key in obj) {
+                }
+
+                return key === undefined || hasOwn.call(obj, key);
+            },
+
+            isEmptyObject: function (obj) {
+                for (var name in obj) {
+                    return false;
+                }
+                return true;
+            },
+
+            error: function (msg) {
+                throw new Error(msg);
+            },
+
+            parseJSON: function (data) {
+                if (typeof data !== "string" || !data) {
+                    return null;
+                }
+
+                // Make sure leading/trailing whitespace is removed (IE can't handle it)
+                data = jQuery.trim(data);
+
+                // Attempt to parse using the native JSON parser first
+                if (window.JSON && window.JSON.parse) {
+                    return window.JSON.parse(data);
+                }
+
+                // Make sure the incoming data is actual JSON
+                // Logic borrowed from http://json.org/json2.js
+                if (rvalidchars.test(data.replace(rvalidescape, "@")
+                    .replace(rvalidtokens, "]")
+                    .replace(rvalidbraces, ""))) {
+
+                    return ( new Function("return " + data) )();
+
+                }
+                jQuery.error("Invalid JSON: " + data);
+            },
+
+            // Cross-browser xml parsing
+            parseXML: function (data) {
+                var xml, tmp;
+                try {
+                    if (window.DOMParser) { // Standard
+                        tmp = new DOMParser();
+                        xml = tmp.parseFromString(data, "text/xml");
+                    } else { // IE
+                        xml = new ActiveXObject("Microsoft.XMLDOM");
+                        xml.async = "false";
+                        xml.loadXML(data);
+                    }
+                } catch (e) {
+                    xml = undefined;
+                }
+                if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) {
+                    jQuery.error("Invalid XML: " + data);
+                }
+                return xml;
+            },
+
+            noop: function () {
+            },
+
+            // Evaluates a script in a global context
+            // Workarounds based on findings by Jim Driscoll
+            // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
+            globalEval: function (data) {
+                if (data && rnotwhite.test(data)) {
+                    // We use execScript on Internet Explorer
+                    // We use an anonymous function so that context is window
+                    // rather than jQuery in Firefox
+                    ( window.execScript || function (data) {
+                        window[ "eval" ].call(window, data);
+                    } )(data);
+                }
+            },
+
+            // Convert dashed to camelCase; used by the css and data modules
+            // Microsoft forgot to hump their vendor prefix (#9572)
+            camelCase: function (string) {
+                return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase);
+            },
+
+            nodeName: function (elem, name) {
+                return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
+            },
+
+            // args is for internal usage only
+            each: function (object, callback, args) {
+                var name, i = 0,
+                    length = object.length,
+                    isObj = length === undefined || jQuery.isFunction(object);
+
+                if (args) {
+                    if (isObj) {
+                        for (name in object) {
+                            if (callback.apply(object[ name ], args) === false) {
+                                break;
+                            }
+                        }
+                    } else {
+                        for (; i < length;) {
+                            if (callback.apply(object[ i++ ], args) === false) {
+                                break;
+                            }
+                        }
+                    }
+
+                    // A special, fast, case for the most common use of each
+                } else {
+                    if (isObj) {
+                        for (name in object) {
+                            if (callback.call(object[ name ], name, object[ name ]) === false) {
+                                break;
+                            }
+                        }
+                    } else {
+                        for (; i < length;) {
+                            if (callback.call(object[ i ], i, object[ i++ ]) === false) {
+                                break;
+                            }
+                        }
+                    }
+                }
+
+                return object;
+            },
+
+            // Use native String.trim function wherever possible
+            trim: trim ?
+                function (text) {
+                    return text == null ?
+                        "" :
+                        trim.call(text);
+                } :
+
+                // Otherwise use our own trimming functionality
+                function (text) {
+                    return text == null ?
+                        "" :
+                        text.toString().replace(trimLeft, "").replace(trimRight, "");
+                },
+
+            // results is for internal usage only
+            makeArray: function (array, results) {
+                var ret = results || [];
+
+                if (array != null) {
+                    // The window, strings (and functions) also have 'length'
+                    // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
+                    var type = jQuery.type(array);
+
+                    if (array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow(array)) {
+                        push.call(ret, array);
+                    } else {
+                        jQuery.merge(ret, array);
+                    }
+                }
+
+                return ret;
+            },
+
+            inArray: function (elem, array, i) {
+                var len;
+
+                if (array) {
+                    if (indexOf) {
+                        return indexOf.call(array, elem, i);
+                    }
+
+                    len = array.length;
+                    i = i ? i < 0 ? Math.max(0, len + i) : i : 0;
+
+                    for (; i < len; i++) {
+                        // Skip accessing in sparse arrays
+                        if (i in array && array[ i ] === elem) {
+                            return i;
+                        }
+                    }
+                }
+
+                return -1;
+            },
+
+            merge: function (first, second) {
+                var i = first.length,
+                    j = 0;
+
+                if (typeof second.length === "number") {
+                    for (var l = second.length; j < l; j++) {
+                        first[ i++ ] = second[ j ];
+                    }
+
+                } else {
+                    while (second[j] !== undefined) {
+                        first[ i++ ] = second[ j++ ];
+                    }
+                }
+
+                first.length = i;
+
+                return first;
+            },
+
+            grep: function (elems, callback, inv) {
+                var ret = [], retVal;
+                inv = !!inv;
+
+                // Go through the array, only saving the items
+                // that pass the validator function
+                for (var i = 0, length = elems.length; i < length; i++) {
+                    retVal = !!callback(elems[ i ], i);
+                    if (inv !== retVal) {
+                        ret.push(elems[ i ]);
+                    }
+                }
+
+                return ret;
+            },
+
+            // arg is for internal usage only
+            map: function (elems, callback, arg) {
+                var value, key, ret = [],
+                    i = 0,
+                    length = elems.length,
+                // jquery objects are treated as arrays
+                    isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length - 1 ] ) || length === 0 || jQuery.isArray(elems) );
+
+                // Go through the array, translating each of the items to their
+                if (isArray) {
+                    for (; i < length; i++) {
+                        value = callback(elems[ i ], i, arg);
+
+                        if (value != null) {
+                            ret[ ret.length ] = value;
+                        }
+                    }
+
+                    // Go through every key on the object,
+                } else {
+                    for (key in elems) {
+                        value = callback(elems[ key ], key, arg);
+
+                        if (value != null) {
+                            ret[ ret.length ] = value;
+                        }
+                    }
+                }
+
+                // Flatten any nested arrays
+                return ret.concat.apply([], ret);
+            },
+
+            // A global GUID counter for objects
+            guid: 1,
+
+            // Bind a function to a context, optionally partially applying any
+            // arguments.
+            proxy: function (fn, context) {
+                if (typeof context === "string") {
+                    var tmp = fn[ context ];
+                    context = fn;
+                    fn = tmp;
+                }
+
+                // Quick check to determine if target is callable, in the spec
+                // this throws a TypeError, but we will just return undefined.
+                if (!jQuery.isFunction(fn)) {
+                    return undefined;
+                }
+
+                // Simulated bind
+                var args = slice.call(arguments, 2),
+                    proxy = function () {
+                        return fn.apply(context, args.concat(slice.call(arguments)));
+                    };
+
+                // Set the guid of unique handler to the same of original handler, so it can be removed
+                proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
+
+                return proxy;
+            },
+
+            // Mutifunctional method to get and set values to a collection
+            // The value/s can optionally be executed if it's a function
+            access: function (elems, key, value, exec, fn, pass) {
+                var length = elems.length;
+
+                // Setting many attributes
+                if (typeof key === "object") {
+                    for (var k in key) {
+                        jQuery.access(elems, k, key[k], exec, fn, value);
+                    }
+                    return elems;
+                }
+
+                // Setting one attribute
+                if (value !== undefined) {
+                    // Optionally, function values get executed if exec is true
+                    exec = !pass && exec && jQuery.isFunction(value);
+
+                    for (var i = 0; i < length; i++) {
+                        fn(elems[i], key, exec ? value.call(elems[i], i, fn(elems[i], key)) : value, pass);
+                    }
+
+                    return elems;
+                }
+
+                // Getting an attribute
+                return length ? fn(elems[0], key) : undefined;
+            },
+
+            now: function () {
+                return ( new Date() ).getTime();
+            },
+
+            // Use of jQuery.browser is frowned upon.
+            // More details: http://docs.jquery.com/Utilities/jQuery.browser
+            uaMatch: function (ua) {
+                ua = ua.toLowerCase();
+
+                var match = rwebkit.exec(ua) ||
+                    ropera.exec(ua) ||
+                    rmsie.exec(ua) ||
+                    ua.indexOf("compatible") < 0 && rmozilla.exec(ua) ||
+                    [];
+
+                return { browser: match[1] || "", version: match[2] || "0" };
+            },
+
+            sub: function () {
+                function jQuerySub(selector, context) {
+                    return new jQuerySub.fn.init(selector, context);
+                }
+
+                jQuery.extend(true, jQuerySub, this);
+                jQuerySub.superclass = this;
+                jQuerySub.fn = jQuerySub.prototype = this();
+                jQuerySub.fn.constructor = jQuerySub;
+                jQuerySub.sub = this.sub;
+                jQuerySub.fn.init = function init(selector, context) {
+                    if (context && context instanceof jQuery && !(context instanceof jQuerySub)) {
+                        context = jQuerySub(context);
+                    }
+
+                    return jQuery.fn.init.call(this, selector, context, rootjQuerySub);
+                };
+                jQuerySub.fn.init.prototype = jQuerySub.fn;
+                var rootjQuerySub = jQuerySub(document);
+                return jQuerySub;
+            },
+
+            browser: {}
+        });
 
 // Populate the class2type map
-jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
-	class2type[ "[object " + name + "]" ] = name.toLowerCase();
-});
+        jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function (i, name) {
+            class2type[ "[object " + name + "]" ] = name.toLowerCase();
+        });
 
-browserMatch = jQuery.uaMatch( userAgent );
-if ( browserMatch.browser ) {
-	jQuery.browser[ browserMatch.browser ] = true;
-	jQuery.browser.version = browserMatch.version;
-}
+        browserMatch = jQuery.uaMatch(userAgent);
+        if (browserMatch.browser) {
+            jQuery.browser[ browserMatch.browser ] = true;
+            jQuery.browser.version = browserMatch.version;
+        }
 
 // Deprecated, use jQuery.browser.webkit instead
-if ( jQuery.browser.webkit ) {
-	jQuery.browser.safari = true;
-}
+        if (jQuery.browser.webkit) {
+            jQuery.browser.safari = true;
+        }
 
 // IE doesn't match non-breaking spaces with \s
-if ( rnotwhite.test( "\xA0" ) ) {
-	trimLeft = /^[\s\xA0]+/;
-	trimRight = /[\s\xA0]+$/;
-}
+        if (rnotwhite.test("\xA0")) {
+            trimLeft = /^[\s\xA0]+/;
+            trimRight = /[\s\xA0]+$/;
+        }
 
 // All jQuery objects should point back to these
-rootjQuery = jQuery(document);
+        rootjQuery = jQuery(document);
 
 // Cleanup functions for the document ready method
-if ( document.addEventListener ) {
-	DOMContentLoaded = function() {
-		document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
-		jQuery.ready();
-	};
-
-} else if ( document.attachEvent ) {
-	DOMContentLoaded = function() {
-		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
-		if ( document.readyState === "complete" ) {
-			document.detachEvent( "onreadystatechange", DOMContentLoaded );
-			jQuery.ready();
-		}
-	};
-}
+        if (document.addEventListener) {
+            DOMContentLoaded = function () {
+                document.removeEventListener("DOMContentLoaded", DOMContentLoaded, false);
+                jQuery.ready();
+            };
+
+        } else if (document.attachEvent) {
+            DOMContentLoaded = function () {
+                // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
+                if (document.readyState === "complete") {
+                    document.detachEvent("onreadystatechange", DOMContentLoaded);
+                    jQuery.ready();
+                }
+            };
+        }
 
 // The DOM ready check for Internet Explorer
-function doScrollCheck() {
-	if ( jQuery.isReady ) {
-		return;
-	}
+        function doScrollCheck() {
+            if (jQuery.isReady) {
+                return;
+            }
 
-	try {
-		// If IE is used, use the trick by Diego Perini
-		// http://javascript.nwbox.com/IEContentLoaded/
-		document.documentElement.doScroll("left");
-	} catch(e) {
-		setTimeout( doScrollCheck, 1 );
-		return;
-	}
+            try {
+                // If IE is used, use the trick by Diego Perini
+                // http://javascript.nwbox.com/IEContentLoaded/
+                document.documentElement.doScroll("left");
+            } catch (e) {
+                setTimeout(doScrollCheck, 1);
+                return;
+            }
 
-	// and execute any waiting functions
-	jQuery.ready();
-}
+            // and execute any waiting functions
+            jQuery.ready();
+        }
 
-return jQuery;
+        return jQuery;
 
-})();
+    })();
 
 
 // String to Object flags format cache
-var flagsCache = {};
+    var flagsCache = {};
 
 // Convert String-formatted flags into Object-formatted ones and store in cache
-function createFlags( flags ) {
-	var object = flagsCache[ flags ] = {},
-		i, length;
-	flags = flags.split( /\s+/ );
-	for ( i = 0, length = flags.length; i < length; i++ ) {
-		object[ flags[i] ] = true;
-	}
-	return object;
-}
-
-/*
- * Create a callback list using the following parameters:
- *
- *	flags:	an optional list of space-separated flags that will change how
- *			the callback list behaves
- *
- * By default a callback list will act like an event callback list and can be
- * "fired" multiple times.
- *
- * Possible flags:
- *
- *	once:			will ensure the callback list can only be fired once (like a Deferred)
- *
- *	memory:			will keep track of previous values and will call any callback added
- *					after the list has been fired right away with the latest "memorized"
- *					values (like a Deferred)
- *
- *	unique:			will ensure a callback can only be added once (no duplicate in the list)
- *
- *	stopOnFalse:	interrupt callings when a callback returns false
- *
- */
-jQuery.Callbacks = function( flags ) {
-
-	// Convert flags from String-formatted to Object-formatted
-	// (we check in cache first)
-	flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {};
-
-	var // Actual callback list
-		list = [],
-		// Stack of fire calls for repeatable lists
-		stack = [],
-		// Last fire value (for non-forgettable lists)
-		memory,
-		// Flag to know if list is currently firing
-		firing,
-		// First callback to fire (used internally by add and fireWith)
-		firingStart,
-		// End of the loop when firing
-		firingLength,
-		// Index of currently firing callback (modified by remove if needed)
-		firingIndex,
-		// Add one or several callbacks to the list
-		add = function( args ) {
-			var i,
-				length,
-				elem,
-				type,
-				actual;
-			for ( i = 0, length = args.length; i < length; i++ ) {
-				elem = args[ i ];
-				type = jQuery.type( elem );
-				if ( type === "array" ) {
-					// Inspect recursively
-					add( elem );
-				} else if ( type === "function" ) {
-					// Add if not in unique mode and callback is not in
-					if ( !flags.unique || !self.has( elem ) ) {
-						list.push( elem );
-					}
-				}
-			}
-		},
-		// Fire callbacks
-		fire = function( context, args ) {
-			args = args || [];
-			memory = !flags.memory || [ context, args ];
-			firing = true;
-			firingIndex = firingStart || 0;
-			firingStart = 0;
-			firingLength = list.length;
-			for ( ; list && firingIndex < firingLength; firingIndex++ ) {
-				if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) {
-					memory = true; // Mark as halted
-					break;
-				}
-			}
-			firing = false;
-			if ( list ) {
-				if ( !flags.once ) {
-					if ( stack && stack.length ) {
-						memory = stack.shift();
-						self.fireWith( memory[ 0 ], memory[ 1 ] );
-					}
-				} else if ( memory === true ) {
-					self.disable();
-				} else {
-					list = [];
-				}
-			}
-		},
-		// Actual Callbacks object
-		self = {
-			// Add a callback or a collection of callbacks to the list
-			add: function() {
-				if ( list ) {
-					var length = list.length;
-					add( arguments );
-					// Do we need to add the callbacks to the
-					// current firing batch?
-					if ( firing ) {
-						firingLength = list.length;
-					// With memory, if we're not firing then
-					// we should call right away, unless previous
-					// firing was halted (stopOnFalse)
-					} else if ( memory && memory !== true ) {
-						firingStart = length;
-						fire( memory[ 0 ], memory[ 1 ] );
-					}
-				}
-				return this;
-			},
-			// Remove a callback from the list
-			remove: function() {
-				if ( list ) {
-					var args = arguments,
-						argIndex = 0,
-						argLength = args.length;
-					for ( ; argIndex < argLength ; argIndex++ ) {
-						for ( var i = 0; i < list.length; i++ ) {
-							if ( args[ argIndex ] === list[ i ] ) {
-								// Handle firingIndex and firingLength
-								if ( firing ) {
-									if ( i <= firingLength ) {
-										firingLength--;
-										if ( i <= firingIndex ) {
-											firingIndex--;
-										}
-									}
-								}
-								// Remove the element
-								list.splice( i--, 1 );
-								// If we have some unicity property then
-								// we only need to do this once
-								if ( flags.unique ) {
-									break;
-								}
-							}
-						}
-					}
-				}
-				return this;
-			},
-			// Control if a given callback is in the list
-			has: function( fn ) {
-				if ( list ) {
-					var i = 0,
-						length = list.length;
-					for ( ; i < length; i++ ) {
-						if ( fn === list[ i ] ) {
-							return true;
-						}
-					}
-				}
-				return false;
-			},
-			// Remove all callbacks from the list
-			empty: function() {
-				list = [];
-				return this;
-			},
-			// Have the list do nothing anymore
-			disable: function() {
-				list = stack = memory = undefined;
-				return this;
-			},
-			// Is it disabled?
-			disabled: function() {
-				return !list;
-			},
-			// Lock the list in its current state
-			lock: function() {
-				stack = undefined;
-				if ( !memory || memory === true ) {
-					self.disable();
-				}
-				return this;
-			},
-			// Is it locked?
-			locked: function() {
-				return !stack;
-			},
-			// Call all callbacks with the given context and arguments
-			fireWith: function( context, args ) {
-				if ( stack ) {
-					if ( firing ) {
-						if ( !flags.once ) {
-							stack.push( [ context, args ] );
-						}
-					} else if ( !( flags.once && memory ) ) {
-						fire( context, args );
-					}
-				}
-				return this;
-			},
-			// Call all the callbacks with the given arguments
-			fire: function() {
-				self.fireWith( this, arguments );
-				return this;
-			},
-			// To know if the callbacks have already been called at least once
-			fired: function() {
-				return !!memory;
-			}
-		};
-
-	return self;
-};
-
-
-
-
-var // Static reference to slice
-	sliceDeferred = [].slice;
-
-jQuery.extend({
-
-	Deferred: function( func ) {
-		var doneList = jQuery.Callbacks( "once memory" ),
-			failList = jQuery.Callbacks( "once memory" ),
-			progressList = jQuery.Callbacks( "memory" ),
-			state = "pending",
-			lists = {
-				resolve: doneList,
-				reject: failList,
-				notify: progressList
-			},
-			promise = {
-				done: doneList.add,
-				fail: failList.add,
-				progress: progressList.add,
-
-				state: function() {
-					return state;
-				},
-
-				// Deprecated
-				isResolved: doneList.fired,
-				isRejected: failList.fired,
-
-				then: function( doneCallbacks, failCallbacks, progressCallbacks ) {
-					deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks );
-					return this;
-				},
-				always: function() {
-					deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments );
-					return this;
-				},
-				pipe: function( fnDone, fnFail, fnProgress ) {
-					return jQuery.Deferred(function( newDefer ) {
-						jQuery.each( {
-							done: [ fnDone, "resolve" ],
-							fail: [ fnFail, "reject" ],
-							progress: [ fnProgress, "notify" ]
-						}, function( handler, data ) {
-							var fn = data[ 0 ],
-								action = data[ 1 ],
-								returned;
-							if ( jQuery.isFunction( fn ) ) {
-								deferred[ handler ](function() {
-									returned = fn.apply( this, arguments );
-									if ( returned && jQuery.isFunction( returned.promise ) ) {
-										returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify );
-									} else {
-										newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
-									}
-								});
-							} else {
-								deferred[ handler ]( newDefer[ action ] );
-							}
-						});
-					}).promise();
-				},
-				// Get a promise for this deferred
-				// If obj is provided, the promise aspect is added to the object
-				promise: function( obj ) {
-					if ( obj == null ) {
-						obj = promise;
-					} else {
-						for ( var key in promise ) {
-							obj[ key ] = promise[ key ];
-						}
-					}
-					return obj;
-				}
-			},
-			deferred = promise.promise({}),
-			key;
-
-		for ( key in lists ) {
-			deferred[ key ] = lists[ key ].fire;
-			deferred[ key + "With" ] = lists[ key ].fireWith;
-		}
-
-		// Handle state
-		deferred.done( function() {
-			state = "resolved";
-		}, failList.disable, progressList.lock ).fail( function() {
-			state = "rejected";
-		}, doneList.disable, progressList.lock );
-
-		// Call given func if any
-		if ( func ) {
-			func.call( deferred, deferred );
-		}
-
-		// All done!
-		return deferred;
-	},
-
-	// Deferred helper
-	when: function( firstParam ) {
-		var args = sliceDeferred.call( arguments, 0 ),
-			i = 0,
-			length = args.length,
-			pValues = new Array( length ),
-			count = length,
-			pCount = length,
-			deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
-				firstParam :
-				jQuery.Deferred(),
-			promise = deferred.promise();
-		function resolveFunc( i ) {
-			return function( value ) {
-				args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
-				if ( !( --count ) ) {
-					deferred.resolveWith( deferred, args );
-				}
-			};
-		}
-		function progressFunc( i ) {
-			return function( value ) {
-				pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
-				deferred.notifyWith( promise, pValues );
-			};
-		}
-		if ( length > 1 ) {
-			for ( ; i < length; i++ ) {
-				if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) {
-					args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) );
-				} else {
-					--count;
-				}
-			}
-			if ( !count ) {
-				deferred.resolveWith( deferred, args );
-			}
-		} else if ( deferred !== firstParam ) {
-			deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
-		}
-		return promise;
-	}
-});
-
-
-
-
-jQuery.support = (function() {
-
-	var support,
-		all,
-		a,
-		select,
-		opt,
-		input,
-		marginDiv,
-		fragment,
-		tds,
-		events,
-		eventName,
-		i,
-		isSupported,
-		div = document.createElement( "div" ),
-		documentElement = document.documentElement;
-
-	// Preliminary tests
-	div.setAttribute("className", "t");
-	div.innerHTML = "   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
-
-	all = div.getElementsByTagName( "*" );
-	a = div.getElementsByTagName( "a" )[ 0 ];
-
-	// Can't get basic test support
-	if ( !all || !all.length || !a ) {
-		return {};
-	}
-
-	// First batch of supports tests
-	select = document.createElement( "select" );
-	opt = select.appendChild( document.createElement("option") );
-	input = div.getElementsByTagName( "input" )[ 0 ];
-
-	support = {
-		// IE strips leading whitespace when .innerHTML is used
-		leadingWhitespace: ( div.firstChild.nodeType === 3 ),
-
-		// Make sure that tbody elements aren't automatically inserted
-		// IE will insert them into empty tables
-		tbody: !div.getElementsByTagName("tbody").length,
-
-		// Make sure that link elements get serialized correctly by innerHTML
-		// This requires a wrapper element in IE
-		htmlSerialize: !!div.getElementsByTagName("link").length,
-
-		// Get the style information from getAttribute
-		// (IE uses .cssText instead)
-		style: /top/.test( a.getAttribute("style") ),
-
-		// Make sure that URLs aren't manipulated
-		// (IE normalizes it by default)
-		hrefNormalized: ( a.getAttribute("href") === "/a" ),
-
-		// Make sure that element opacity exists
-		// (IE uses filter instead)
-		// Use a regex to work around a WebKit issue. See #5145
-		opacity: /^0.55/.test( a.style.opacity ),
-
-		// Verify style float existence
-		// (IE uses styleFloat instead of cssFloat)
-		cssFloat: !!a.style.cssFloat,
-
-		// Make sure that if no value is specified for a checkbox
-		// that it defaults to "on".
-		// (WebKit defaults to "" instead)
-		checkOn: ( input.value === "on" ),
-
-		// Make sure that a selected-by-default option has a working selected property.
-		// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
-		optSelected: opt.selected,
-
-		// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
-		getSetAttribute: div.className !== "t",
-
-		// Tests for enctype support on a form(#6743)
-		enctype: !!document.createElement("form").enctype,
-
-		// Makes sure cloning an html5 element does not cause problems
-		// Where outerHTML is undefined, this still works
-		html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
-
-		// Will be defined later
-		submitBubbles: true,
-		changeBubbles: true,
-		focusinBubbles: false,
-		deleteExpando: true,
-		noCloneEvent: true,
-		inlineBlockNeedsLayout: false,
-		shrinkWrapBlocks: false,
-		reliableMarginRight: true
-	};
-
-	// Make sure checked status is properly cloned
-	input.checked = true;
-	support.noCloneChecked = input.cloneNode( true ).checked;
-
-	// Make sure that the options inside disabled selects aren't marked as disabled
-	// (WebKit marks them as disabled)
-	select.disabled = true;
-	support.optDisabled = !opt.disabled;
-
-	// Test to see if it's possible to delete an expando from an element
-	// Fails in Internet Explorer
-	try {
-		delete div.test;
-	} catch( e ) {
-		support.deleteExpando = false;
-	}
-
-	if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
-		div.attachEvent( "onclick", function() {
-			// Cloning a node shouldn't copy over any
-			// bound event handlers (IE does this)
-			support.noCloneEvent = false;
-		});
-		div.cloneNode( true ).fireEvent( "onclick" );
-	}
-
-	// Check if a radio maintains its value
-	// after being appended to the DOM
-	input = document.createElement("input");
-	input.value = "t";
-	input.setAttribute("type", "radio");
-	support.radioValue = input.value === "t";
-
-	input.setAttribute("checked", "checked");
-	div.appendChild( input );
-	fragment = document.createDocumentFragment();
-	fragment.appendChild( div.lastChild );
-
-	// WebKit doesn't clone checked state correctly in fragments
-	support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
-
-	// Check if a disconnected checkbox will retain its checked
-	// value of true after appended to the DOM (IE6/7)
-	support.appendChecked = input.checked;
-
-	fragment.removeChild( input );
-	fragment.appendChild( div );
-
-	div.innerHTML = "";
-
-	// Check if div with explicit width and no margin-right incorrectly
-	// gets computed margin-right based on width of container. For more
-	// info see bug #3333
-	// Fails in WebKit before Feb 2011 nightlies
-	// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
-	if ( window.getComputedStyle ) {
-		marginDiv = document.createElement( "div" );
-		marginDiv.style.width = "0";
-		marginDiv.style.marginRight = "0";
-		div.style.width = "2px";
-		div.appendChild( marginDiv );
-		support.reliableMarginRight =
-			( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
-	}
-
-	// Technique from Juriy Zaytsev
-	// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
-	// We only care about the case where non-standard event systems
-	// are used, namely in IE. Short-circuiting here helps us to
-	// avoid an eval call (in setAttribute) which can cause CSP
-	// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
-	if ( div.attachEvent ) {
-		for( i in {
-			submit: 1,
-			change: 1,
-			focusin: 1
-		}) {
-			eventName = "on" + i;
-			isSupported = ( eventName in div );
-			if ( !isSupported ) {
-				div.setAttribute( eventName, "return;" );
-				isSupported = ( typeof div[ eventName ] === "function" );
-			}
-			support[ i + "Bubbles" ] = isSupported;
-		}
-	}
-
-	fragment.removeChild( div );
-
-	// Null elements to avoid leaks in IE
-	fragment = select = opt = marginDiv = div = input = null;
-
-	// Run tests that need a body at doc ready
-	jQuery(function() {
-		var container, outer, inner, table, td, offsetSupport,
-			conMarginTop, ptlm, vb, style, html,
-			body = document.getElementsByTagName("body")[0];
-
-		if ( !body ) {
-			// Return for frameset docs that don't have a body
-			return;
-		}
-
-		conMarginTop = 1;
-		ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;";
-		vb = "visibility:hidden;border:0;";
-		style = "style='" + ptlm + "border:5px solid #000;padding:0;'";
-		html = "<div " + style + "><div></div></div>" +
-			"<table " + style + " cellpadding='0' cellspacing='0'>" +
-			"<tr><td></td></tr></table>";
-
-		container = document.createElement("div");
-		container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
-		body.insertBefore( container, body.firstChild );
-
-		// Construct the test element
-		div = document.createElement("div");
-		container.appendChild( div );
-
-		// Check if table cells still have offsetWidth/Height when they are set
-		// to display:none and there are still other visible table cells in a
-		// table row; if so, offsetWidth/Height are not reliable for use when
-		// determining if an element has been hidden directly using
-		// display:none (it is still safe to use offsets if a parent element is
-		// hidden; don safety goggles and see bug #4512 for more information).
-		// (only IE 8 fails this test)
-		div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
-		tds = div.getElementsByTagName( "td" );
-		isSupported = ( tds[ 0 ].offsetHeight === 0 );
-
-		tds[ 0 ].style.display = "";
-		tds[ 1 ].style.display = "none";
-
-		// Check if empty table cells still have offsetWidth/Height
-		// (IE <= 8 fail this test)
-		support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
-
-		// Figure out if the W3C box model works as expected
-		div.innerHTML = "";
-		div.style.width = div.style.paddingLeft = "1px";
-		jQuery.boxModel = support.boxModel = div.offsetWidth === 2;
-
-		if ( typeof div.style.zoom !== "undefined" ) {
-			// Check if natively block-level elements act like inline-block
-			// elements when setting their display to 'inline' and giving
-			// them layout
-			// (IE < 8 does this)
-			div.style.display = "inline";
-			div.style.zoom = 1;
-			support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 );
-
-			// Check if elements with layout shrink-wrap their children
-			// (IE 6 does this)
-			div.style.display = "";
-			div.innerHTML = "<div style='width:4px;'></div>";
-			support.shrinkWrapBlocks = ( div.offsetWidth !== 2 );
-		}
-
-		div.style.cssText = ptlm + vb;
-		div.innerHTML = html;
-
-		outer = div.firstChild;
-		inner = outer.firstChild;
-		td = outer.nextSibling.firstChild.firstChild;
-
-		offsetSupport = {
-			doesNotAddBorder: ( inner.offsetTop !== 5 ),
-			doesAddBorderForTableAndCells: ( td.offsetTop === 5 )
-		};
-
-		inner.style.position = "fixed";
-		inner.style.top = "20px";
-
-		// safari subtracts parent border width here which is 5px
-		offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 );
-		inner.style.position = inner.style.top = "";
-
-		outer.style.overflow = "hidden";
-		outer.style.position = "relative";
-
-		offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 );
-		offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop );
-
-		body.removeChild( container );
-		div  = container = null;
-
-		jQuery.extend( support, offsetSupport );
-	});
-
-	return support;
-})();
-
-
-
-
-var rbrace = /^(?:\{.*\}|\[.*\])$/,
-	rmultiDash = /([A-Z])/g;
-
-jQuery.extend({
-	cache: {},
-
-	// Please use with caution
-	uuid: 0,
-
-	// Unique for each copy of jQuery on the page
-	// Non-digits removed to match rinlinejQuery
-	expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
-
-	// The following elements throw uncatchable exceptions if you
-	// attempt to add expando properties to them.
-	noData: {
-		"embed": true,
-		// Ban all objects except for Flash (which handle expandos)
-		"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
-		"applet": true
-	},
-
-	hasData: function( elem ) {
-		elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
-		return !!elem && !isEmptyDataObject( elem );
-	},
-
-	data: function( elem, name, data, pvt /* Internal Use Only */ ) {
-		if ( !jQuery.acceptData( elem ) ) {
-			return;
-		}
-
-		var privateCache, thisCache, ret,
-			internalKey = jQuery.expando,
-			getByName = typeof name === "string",
-
-			// We have to handle DOM nodes and JS objects differently because IE6-7
-			// can't GC object references properly across the DOM-JS boundary
-			isNode = elem.nodeType,
-
-			// Only DOM nodes need the global jQuery cache; JS object data is
-			// attached directly to the object so GC can occur automatically
-			cache = isNode ? jQuery.cache : elem,
-
-			// Only defining an ID for JS objects if its cache already exists allows
-			// the code to shortcut on the same path as a DOM node with no cache
-			id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey,
-			isEvents = name === "events";
-
-		// Avoid doing any more work than we need to when trying to get data on an
-		// object that has no data at all
-		if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) {
-			return;
-		}
-
-		if ( !id ) {
-			// Only DOM nodes need a new unique ID for each element since their data
-			// ends up in the global cache
-			if ( isNode ) {
-				elem[ internalKey ] = id = ++jQuery.uuid;
-			} else {
-				id = internalKey;
-			}
-		}
-
-		if ( !cache[ id ] ) {
-			cache[ id ] = {};
-
-			// Avoids exposing jQuery metadata on plain JS objects when the object
-			// is serialized using JSON.stringify
-			if ( !isNode ) {
-				cache[ id ].toJSON = jQuery.noop;
-			}
-		}
-
-		// An object can be passed to jQuery.data instead of a key/value pair; this gets
-		// shallow copied over onto the existing cache
-		if ( typeof name === "object" || typeof name === "function" ) {
-			if ( pvt ) {
-				cache[ id ] = jQuery.extend( cache[ id ], name );
-			} else {
-				cache[ id ].data = jQuery.extend( cache[ id ].data, name );
-			}
-		}
-
-		privateCache = thisCache = cache[ id ];
-
-		// jQuery data() is stored in a separate object inside the object's internal data
-		// cache in order to avoid key collisions between internal data and user-defined
-		// data.
-		if ( !pvt ) {
-			if ( !thisCache.data ) {
-				thisCache.data = {};
-			}
-
-			thisCache = thisCache.data;
-		}
-
-		if ( data !== undefined ) {
-			thisCache[ jQuery.camelCase( name ) ] = data;
-		}
-
-		// Users should not attempt to inspect the internal events object using jQuery.data,
-		// it is undocumented and subject to change. But does anyone listen? No.
-		if ( isEvents && !thisCache[ name ] ) {
-			return privateCache.events;
-		}
-
-		// Check for both converted-to-camel and non-converted data property names
-		// If a data property was specified
-		if ( getByName ) {
-
-			// First Try to find as-is property data
-			ret = thisCache[ name ];
-
-			// Test for null|undefined property data
-			if ( ret == null ) {
-
-				// Try to find the camelCased property
-				ret = thisCache[ jQuery.camelCase( name ) ];
-			}
-		} else {
-			ret = thisCache;
-		}
-
-		return ret;
-	},
-
-	removeData: function( elem, name, pvt /* Internal Use Only */ ) {
-		if ( !jQuery.acceptData( elem ) ) {
-			return;
-		}
-
-		var thisCache, i, l,
-
-			// Reference to internal data cache key
-			internalKey = jQuery.expando,
-
-			isNode = elem.nodeType,
-
-			// See jQuery.data for more information
-			cache = isNode ? jQuery.cache : elem,
-
-			// See jQuery.data for more information
-			id = isNode ? elem[ internalKey ] : internalKey;
-
-		// If there is already no cache entry for this object, there is no
-		// purpose in continuing
-		if ( !cache[ id ] ) {
-			return;
-		}
-
-		if ( name ) {
-
-			thisCache = pvt ? cache[ id ] : cache[ id ].data;
-
-			if ( thisCache ) {
-
-				// Support array or space separated string names for data keys
-				if ( !jQuery.isArray( name ) ) {
-
-					// try the string as a key before any manipulation
-					if ( name in thisCache ) {
-						name = [ name ];
-					} else {
-
-						// split the camel cased version by spaces unless a key with the spaces exists
-						name = jQuery.camelCase( name );
-						if ( name in thisCache ) {
-							name = [ name ];
-						} else {
-							name = name.split( " " );
-						}
-					}
-				}
-
-				for ( i = 0, l = name.length; i < l; i++ ) {
-					delete thisCache[ name[i] ];
-				}
-
-				// If there is no data left in the cache, we want to continue
-				// and let the cache object itself get destroyed
-				if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
-					return;
-				}
-			}
-		}
-
-		// See jQuery.data for more information
-		if ( !pvt ) {
-			delete cache[ id ].data;
-
-			// Don't destroy the parent cache unless the internal data object
-			// had been the only thing left in it
-			if ( !isEmptyDataObject(cache[ id ]) ) {
-				return;
-			}
-		}
-
-		// Browsers that fail expando deletion also refuse to delete expandos on
-		// the window, but it will allow it on all other JS objects; other browsers
-		// don't care
-		// Ensure that `cache` is not a window object #10080
-		if ( jQuery.support.deleteExpando || !cache.setInterval ) {
-			delete cache[ id ];
-		} else {
-			cache[ id ] = null;
-		}
-
-		// We destroyed the cache and need to eliminate the expando on the node to avoid
-		// false lookups in the cache for entries that no longer exist
-		if ( isNode ) {
-			// IE does not allow us to delete expando properties from nodes,
-			// nor does it have a removeAttribute function on Document nodes;
-			// we must handle all of these cases
-			if ( jQuery.support.deleteExpando ) {
-				delete elem[ internalKey ];
-			} else if ( elem.removeAttribute ) {
-				elem.removeAttribute( internalKey );
-			} else {
-				elem[ internalKey ] = null;
-			}
-		}
-	},
-
-	// For internal use only.
-	_data: function( elem, name, data ) {
-		return jQuery.data( elem, name, data, true );
-	},
-
-	// A method for determining if a DOM node can handle the data expando
-	acceptData: function( elem ) {
-		if ( elem.nodeName ) {
-			var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
-
-			if ( match ) {
-				return !(match === true || elem.getAttribute("classid") !== match);
-			}
-		}
-
-		return true;
-	}
-});
-
-jQuery.fn.extend({
-	data: function( key, value ) {
-		var parts, attr, name,
-			data = null;
-
-		if ( typeof key === "undefined" ) {
-			if ( this.length ) {
-				data = jQuery.data( this[0] );
-
-				if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) {
-					attr = this[0].attributes;
-					for ( var i = 0, l = attr.length; i < l; i++ ) {
-						name = attr[i].name;
-
-						if ( name.indexOf( "data-" ) === 0 ) {
-							name = jQuery.camelCase( name.substring(5) );
-
-							dataAttr( this[0], name, data[ name ] );
-						}
-					}
-					jQuery._data( this[0], "parsedAttrs", true );
-				}
-			}
-
-			return data;
-
-		} else if ( typeof key === "object" ) {
-			return this.each(function() {
-				jQuery.data( this, key );
-			});
-		}
-
-		parts = key.split(".");
-		parts[1] = parts[1] ? "." + parts[1] : "";
-
-		if ( value === undefined ) {
-			data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
-
-			// Try to fetch any internally stored data first
-			if ( data === undefined && this.length ) {
-				data = jQuery.data( this[0], key );
-				data = dataAttr( this[0], key, data );
-			}
-
-			return data === undefined && parts[1] ?
-				this.data( parts[0] ) :
-				data;
-
-		} else {
-			return this.each(function() {
-				var self = jQuery( this ),
-					args = [ parts[0], value ];
-
-				self.triggerHandler( "setData" + parts[1] + "!", args );
-				jQuery.data( this, key, value );
-				self.triggerHandler( "changeData" + parts[1] + "!", args );
-			});
-		}
-	},
-
-	removeData: function( key ) {
-		return this.each(function() {
-			jQuery.removeData( this, key );
-		});
-	}
-});
-
-function dataAttr( elem, key, data ) {
-	// If nothing was found internally, try to fetch any
-	// data from the HTML5 data-* attribute
-	if ( data === undefined && elem.nodeType === 1 ) {
-
-		var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
-
-		data = elem.getAttribute( name );
-
-		if ( typeof data === "string" ) {
-			try {
-				data = data === "true" ? true :
-				data === "false" ? false :
-				data === "null" ? null :
-				jQuery.isNumeric( data ) ? parseFloat( data ) :
-					rbrace.test( data ) ? jQuery.parseJSON( data ) :
-					data;
-			} catch( e ) {}
-
-			// Make sure we set the data so it isn't changed later
-			jQuery.data( elem, key, data );
-
-		} else {
-			data = undefined;
-		}
-	}
-
-	return data;
-}
+    function createFlags(flags) {
+        var object = flagsCache[ flags ] = {},
+            i, length;
+        flags = flags.split(/\s+/);
+        for (i = 0, length = flags.length; i < length; i++) {
+            object[ flags[i] ] = true;
+        }
+        return object;
+    }
+
+    /*
+     * Create a callback list using the following parameters:
+     *
+     *	flags:	an optional list of space-separated flags that will change how
+     *			the callback list behaves
+     *
+     * By default a callback list will act like an event callback list and can be
+     * "fired" multiple times.
+     *
+     * Possible flags:
+     *
+     *	once:			will ensure the callback list can only be fired once (like a Deferred)
+     *
+     *	memory:			will keep track of previous values and will call any callback added
+     *					after the list has been fired right away with the latest "memorized"
+     *					values (like a Deferred)
+     *
+     *	unique:			will ensure a callback can only be added once (no duplicate in the list)
+     *
+     *	stopOnFalse:	interrupt callings when a callback returns false
+     *
+     */
+    jQuery.Callbacks = function (flags) {
+
+        // Convert flags from String-formatted to Object-formatted
+        // (we check in cache first)
+        flags = flags ? ( flagsCache[ flags ] || createFlags(flags) ) : {};
+
+        var // Actual callback list
+            list = [],
+        // Stack of fire calls for repeatable lists
+            stack = [],
+        // Last fire value (for non-forgettable lists)
+            memory,
+        // Flag to know if list is currently firing
+            firing,
+        // First callback to fire (used internally by add and fireWith)
+            firingStart,
+        // End of the loop when firing
+            firingLength,
+        // Index of currently firing callback (modified by remove if needed)
+            firingIndex,
+        // Add one or several callbacks to the list
+            add = function (args) {
+                var i,
+                    length,
+                    elem,
+                    type,
+                    actual;
+                for (i = 0, length = args.length; i < length; i++) {
+                    elem = args[ i ];
+                    type = jQuery.type(elem);
+                    if (type === "array") {
+                        // Inspect recursively
+                        add(elem);
+                    } else if (type === "function") {
+                        // Add if not in unique mode and callback is not in
+                        if (!flags.unique || !self.has(elem)) {
+                            list.push(elem);
+                        }
+                    }
+                }
+            },
+        // Fire callbacks
+            fire = function (context, args) {
+                args = args || [];
+                memory = !flags.memory || [ context, args ];
+                firing = true;
+                firingIndex = firingStart || 0;
+                firingStart = 0;
+                firingLength = list.length;
+                for (; list && firingIndex < firingLength; firingIndex++) {
+                    if (list[ firingIndex ].apply(context, args) === false && flags.stopOnFalse) {
+                        memory = true; // Mark as halted
+                        break;
+                    }
+                }
+                firing = false;
+                if (list) {
+                    if (!flags.once) {
+                        if (stack && stack.length) {
+                            memory = stack.shift();
+                            self.fireWith(memory[ 0 ], memory[ 1 ]);
+                        }
+                    } else if (memory === true) {
+                        self.disable();
+                    } else {
+                        list = [];
+                    }
+                }
+            },
+        // Actual Callbacks object
+            self = {
+                // Add a callback or a collection of callbacks to the list
+                add: function () {
+                    if (list) {
+                        var length = list.length;
+                        add(arguments);
+                        // Do we need to add the callbacks to the
+                        // current firing batch?
+                        if (firing) {
+                            firingLength = list.length;
+                            // With memory, if we're not firing then
+                            // we should call right away, unless previous
+                            // firing was halted (stopOnFalse)
+                        } else if (memory && memory !== true) {
+                            firingStart = length;
+                            fire(memory[ 0 ], memory[ 1 ]);
+                        }
+                    }
+                    return this;
+                },
+                // Remove a callback from the list
+                remove: function () {
+                    if (list) {
+                        var args = arguments,
+                            argIndex = 0,
+                            argLength = args.length;
+                        for (; argIndex < argLength; argIndex++) {
+                            for (var i = 0; i < list.length; i++) {
+                                if (args[ argIndex ] === list[ i ]) {
+                                    // Handle firingIndex and firingLength
+                                    if (firing) {
+                                        if (i <= firingLength) {
+                                            firingLength--;
+                                            if (i <= firingIndex) {
+                                                firingIndex--;
+                                            }
+                                        }
+                                    }
+                                    // Remove the element
+                                    list.splice(i--, 1);
+                                    // If we have some unicity property then
+                                    // we only need to do this once
+                                    if (flags.unique) {
+                                        break;
+                                    }
+                                }
+                            }
+                        }
+                    }
+                    return this;
+                },
+                // Control if a given callback is in the list
+                has: function (fn) {
+                    if (list) {
+                        var i = 0,
+                            length = list.length;
+                        for (; i < length; i++) {
+                            if (fn === list[ i ]) {
+                                return true;
+                            }
+                        }
+                    }
+                    return false;
+                },
+                // Remove all callbacks from the list
+                empty: function () {
+                    list = [];
+                    return this;
+                },
+                // Have the list do nothing anymore
+                disable: function () {
+                    list = stack = memory = undefined;
+                    return this;
+                },
+                // Is it disabled?
+                disabled: function () {
+                    return !list;
+                },
+                // Lock the list in its current state
+                lock: function () {
+                    stack = undefined;
+                    if (!memory || memory === true) {
+                        self.disable();
+                    }
+                    return this;
+                },
+                // Is it locked?
+                locked: function () {
+                    return !stack;
+                },
+                // Call all callbacks with the given context and arguments
+                fireWith: function (context, args) {
+                    if (stack) {
+                        if (firing) {
+                            if (!flags.once) {
+                                stack.push([ context, args ]);
+                            }
+                        } else if (!( flags.once && memory )) {
+                            fire(context, args);
+                        }
+                    }
+                    return this;
+                },
+                // Call all the callbacks with the given arguments
+                fire: function () {
+                    self.fireWith(this, arguments);
+                    return this;
+                },
+                // To know if the callbacks have already been called at least once
+                fired: function () {
+                    return !!memory;
+                }
+            };
+
+        return self;
+    };
+
+
+    var // Static reference to slice
+        sliceDeferred = [].slice;
+
+    jQuery.extend({
+
+        Deferred: function (func) {
+            var doneList = jQuery.Callbacks("once memory"),
+                failList = jQuery.Callbacks("once memory"),
+                progressList = jQuery.Callbacks("memory"),
+                state = "pending",
+                lists = {
+                    resolve: doneList,
+                    reject: failList,
+                    notify: progressList
+                },
+                promise = {
+                    done: doneList.add,
+                    fail: failList.add,
+                    progress: progressList.add,
+
+                    state: function () {
+                        return state;
+                    },
+
+                    // Deprecated
+                    isResolved: doneList.fired,
+                    isRejected: failList.fired,
+
+                    then: function (doneCallbacks, failCallbacks, progressCallbacks) {
+                        deferred.done(doneCallbacks).fail(failCallbacks).progress(progressCallbacks);
+                        return this;
+                    },
+                    always: function () {
+                        deferred.done.apply(deferred, arguments).fail.apply(deferred, arguments);
+                        return this;
+                    },
+                    pipe: function (fnDone, fnFail, fnProgress) {
+                        return jQuery.Deferred(function (newDefer) {
+                            jQuery.each({
+                                done: [ fnDone, "resolve" ],
+                                fail: [ fnFail, "reject" ],
+                                progress: [ fnProgress, "notify" ]
+                            }, function (handler, data) {
+                                var fn = data[ 0 ],
+                                    action = data[ 1 ],
+                                    returned;
+                                if (jQuery.isFunction(fn)) {
+                                    deferred[ handler ](function () {
+                                        returned = fn.apply(this, arguments);
+                                        if (returned && jQuery.isFunction(returned.promise)) {
+                                            returned.promise().then(newDefer.resolve, newDefer.reject, newDefer.notify);
+                                        } else {
+                                            newDefer[ action + "With" ](this === deferred ? newDefer : this, [ returned ]);
+                                        }
+                                    });
+                                } else {
+                                    deferred[ handler ](newDefer[ action ]);
+                                }
+                            });
+                        }).promise();
+                    },
+                    // Get a promise for this deferred
+                    // If obj is provided, the promise aspect is added to the object
+                    promise: function (obj) {
+                        if (obj == null) {
+                            obj = promise;
+                        } else {
+                            for (var key in promise) {
+                                obj[ key ] = promise[ key ];
+                            }
+                        }
+                        return obj;
+                    }
+                },
+                deferred = promise.promise({}),
+                key;
+
+            for (key in lists) {
+                deferred[ key ] = lists[ key ].fire;
+                deferred[ key + "With" ] = lists[ key ].fireWith;
+            }
+
+            // Handle state
+            deferred.done(function () {
+                state = "resolved";
+            }, failList.disable, progressList.lock).fail(function () {
+                    state = "rejected";
+                }, doneList.disable, progressList.lock);
+
+            // Call given func if any
+            if (func) {
+                func.call(deferred, deferred);
+            }
+
+            // All done!
+            return deferred;
+        },
+
+        // Deferred helper
+        when: function (firstParam) {
+            var args = sliceDeferred.call(arguments, 0),
+                i = 0,
+                length = args.length,
+                pValues = new Array(length),
+                count = length,
+                pCount = length,
+                deferred = length <= 1 && firstParam && jQuery.isFunction(firstParam.promise) ?
+                    firstParam :
+                    jQuery.Deferred(),
+                promise = deferred.promise();
+
+            function resolveFunc(i) {
+                return function (value) {
+                    args[ i ] = arguments.length > 1 ? sliceDeferred.call(arguments, 0) : value;
+                    if (!( --count )) {
+                        deferred.resolveWith(deferred, args);
+                    }
+                };
+            }
+
+            function progressFunc(i) {
+                return function (value) {
+                    pValues[ i ] = arguments.length > 1 ? sliceDeferred.call(arguments, 0) : value;
+                    deferred.notifyWith(promise, pValues);
+                };
+            }
+
+            if (length > 1) {
+                for (; i < length; i++) {
+                    if (args[ i ] && args[ i ].promise && jQuery.isFunction(args[ i ].promise)) {
+                        args[ i ].promise().then(resolveFunc(i), deferred.reject, progressFunc(i));
+                    } else {
+                        --count;
+                    }
+                }
+                if (!count) {
+                    deferred.resolveWith(deferred, args);
+                }
+            } else if (deferred !== firstParam) {
+                deferred.resolveWith(deferred, length ? [ firstParam ] : []);
+            }
+            return promise;
+        }
+    });
+
+
+    jQuery.support = (function () {
+
+        var support,
+            all,
+            a,
+            select,
+            opt,
+            input,
+            marginDiv,
+            fragment,
+            tds,
+            events,
+            eventName,
+            i,
+            isSupported,
+            div = document.createElement("div"),
+            documentElement = document.documentElement;
+
+        // Preliminary tests
+        div.setAttribute("className", "t");
+        div.innerHTML = "   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
+
+        all = div.getElementsByTagName("*");
+        a = div.getElementsByTagName("a")[ 0 ];
+
+        // Can't get basic test support
+        if (!all || !all.length || !a) {
+            return {};
+        }
+
+        // First batch of supports tests
+        select = document.createElement("select");
+        opt = select.appendChild(document.createElement("option"));
+        input = div.getElementsByTagName("input")[ 0 ];
+
+        support = {
+            // IE strips leading whitespace when .innerHTML is used
+            leadingWhitespace: ( div.firstChild.nodeType === 3 ),
+
+            // Make sure that tbody elements aren't automatically inserted
+            // IE will insert them into empty tables
+            tbody: !div.getElementsByTagName("tbody").length,
+
+            // Make sure that link elements get serialized correctly by innerHTML
+            // This requires a wrapper element in IE
+            htmlSerialize: !!div.getElementsByTagName("link").length,
+
+            // Get the style information from getAttribute
+            // (IE uses .cssText instead)
+            style: /top/.test(a.getAttribute("style")),
+
+            // Make sure that URLs aren't manipulated
+            // (IE normalizes it by default)
+            hrefNormalized: ( a.getAttribute("href") === "/a" ),
+
+            // Make sure that element opacity exists
+            // (IE uses filter instead)
+            // Use a regex to work around a WebKit issue. See #5145
+            opacity: /^0.55/.test(a.style.opacity),
+
+            // Verify style float existence
+            // (IE uses styleFloat instead of cssFloat)
+            cssFloat: !!a.style.cssFloat,
+
+            // Make sure that if no value is specified for a checkbox
+            // that it defaults to "on".
+            // (WebKit defaults to "" instead)
+            checkOn: ( input.value === "on" ),
+
+            // Make sure that a selected-by-default option has a working selected property.
+            // (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
+            optSelected: opt.selected,
+
+            // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
+            getSetAttribute: div.className !== "t",
+
+            // Tests for enctype support on a form(#6743)
+            enctype: !!document.createElement("form").enctype,
+
+            // Makes sure cloning an html5 element does not cause problems
+            // Where outerHTML is undefined, this still works
+            html5Clone: document.createElement("nav").cloneNode(true).outerHTML !== "<:nav></:nav>",
+
+            // Will be defined later
+            submitBubbles: true,
+            changeBubbles: true,
+            focusinBubbles: false,
+            deleteExpando: true,
+            noCloneEvent: true,
+            inlineBlockNeedsLayout: false,
+            shrinkWrapBlocks: false,
+            reliableMarginRight: true
+        };
+
+        // Make sure checked status is properly cloned
+        input.checked = true;
+        support.noCloneChecked = input.cloneNode(true).checked;
+
+        // Make sure that the options inside disabled selects aren't marked as disabled
+        // (WebKit marks them as disabled)
+        select.disabled = true;
+        support.optDisabled = !opt.disabled;
+
+        // Test to see if it's possible to delete an expando from an element
+        // Fails in Internet Explorer
+        try {
+            delete div.test;
+        } catch (e) {
+            support.deleteExpando = false;
+        }
+
+        if (!div.addEventListener && div.attachEvent && div.fireEvent) {
+            div.attachEvent("onclick", function () {
+                // Cloning a node shouldn't copy over any
+                // bound event handlers (IE does this)
+                support.noCloneEvent = false;
+            });
+            div.cloneNode(true).fireEvent("onclick");
+        }
+
+        // Check if a radio maintains its value
+        // after being appended to the DOM
+        input = document.createElement("input");
+        input.value = "t";
+        input.setAttribute("type", "radio");
+        support.radioValue = input.value === "t";
+
+        input.setAttribute("checked", "checked");
+        div.appendChild(input);
+        fragment = document.createDocumentFragment();
+        fragment.appendChild(div.lastChild);
+
+        // WebKit doesn't clone checked state correctly in fragments
+        support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked;
+
+        // Check if a disconnected checkbox will retain its checked
+        // value of true after appended to the DOM (IE6/7)
+        support.appendChecked = input.checked;
+
+        fragment.removeChild(input);
+        fragment.appendChild(div);
+
+        div.innerHTML = "";
+
+        // Check if div with explicit width and no margin-right incorrectly
+        // gets computed margin-right based on width of container. For more
+        // info see bug #3333
+        // Fails in WebKit before Feb 2011 nightlies
+        // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
+        if (window.getComputedStyle) {
+            marginDiv = document.createElement("div");
+            marginDiv.style.width = "0";
+            marginDiv.style.marginRight = "0";
+            div.style.width = "2px";
+            div.appendChild(marginDiv);
+            support.reliableMarginRight =
+                ( parseInt(( window.getComputedStyle(marginDiv, null) || { marginRight: 0 } ).marginRight, 10) || 0 ) === 0;
+        }
+
+        // Technique from Juriy Zaytsev
+        // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
+        // We only care about the case where non-standard event systems
+        // are used, namely in IE. Short-circuiting here helps us to
+        // avoid an eval call (in setAttribute) which can cause CSP
+        // to go haywire. See: https://developer.mozilla.org/en/Security/CSP
+        if (div.attachEvent) {
+            for (i in {
+                submit: 1,
+                change: 1,
+                focusin: 1
+            }) {
+                eventName = "on" + i;
+                isSupported = ( eventName in div );
+                if (!isSupported) {
+                    div.setAttribute(eventName, "return;");
+                    isSupported = ( typeof div[ eventName ] === "function" );
+                }
+                support[ i + "Bubbles" ] = isSupported;
+            }
+        }
+
+        fragment.removeChild(div);
+
+        // Null elements to avoid leaks in IE
+        fragment = select = opt = marginDiv = div = input = null;
+
+        // Run tests that need a body at doc ready
+        jQuery(function () {
+            var container, outer, inner, table, td, offsetSupport,
+                conMarginTop, ptlm, vb, style, html,
+                body = document.getElementsByTagName("body")[0];
+
+            if (!body) {
+                // Return for frameset docs that don't have a body
+                return;
+            }
+
+            conMarginTop = 1;
+            ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;";
+            vb = "visibility:hidden;border:0;";
+            style = "style='" + ptlm + "border:5px solid #000;padding:0;'";
+            html = "<div " + style + "><div></div></div>" +
+                "<table " + style + " cellpadding='0' cellspacing='0'>" +
+                "<tr><td></td></tr></table>";
+
+            container = document.createElement("div");
+            container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
+            body.insertBefore(container, body.firstChild);
+
+            // Construct the test element
+            div = document.createElement("div");
+            container.appendChild(div);
+
+            // Check if table cells still have offsetWidth/Height when they are set
+            // to display:none and there are still other visible table cells in a
+            // table row; if so, offsetWidth/Height are not reliable for use when
+            // determining if an element has been hidden directly using
+            // display:none (it is still safe to use offsets if a parent element is
+            // hidden; don safety goggles and see bug #4512 for more information).
+            // (only IE 8 fails this test)
+            div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
+            tds = div.getElementsByTagName("td");
+            isSupported = ( tds[ 0 ].offsetHeight === 0 );
+
+            tds[ 0 ].style.display = "";
+            tds[ 1 ].style.display = "none";
+
+            // Check if empty table cells still have offsetWidth/Height
+            // (IE <= 8 fail this test)
+            support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
+
+            // Figure out if the W3C box model works as expected
+            div.innerHTML = "";
+            div.style.width = div.style.paddingLeft = "1px";
+            jQuery.boxModel = support.boxModel = div.offsetWidth === 2;
+
+            if (typeof div.style.zoom !== "undefined") {
+                // Check if natively block-level elements act like inline-block
+                // elements when setting their display to 'inline' and giving
+                // them layout
+                // (IE < 8 does this)
+                div.style.display = "inline";
+                div.style.zoom = 1;
+                support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 );
+
+                // Check if elements with layout shrink-wrap their children
+                // (IE 6 does this)
+                div.style.display = "";
+                div.innerHTML = "<div style='width:4px;'></div>";
+                support.shrinkWrapBlocks = ( div.offsetWidth !== 2 );
+            }
+
+            div.style.cssText = ptlm + vb;
+            div.innerHTML = html;
+
+            outer = div.firstChild;
+            inner = outer.firstChild;
+            td = outer.nextSibling.firstChild.firstChild;
+
+            offsetSupport = {
+                doesNotAddBorder: ( inner.offsetTop !== 5 ),
+                doesAddBorderForTableAndCells: ( td.offsetTop === 5 )
+            };
+
+            inner.style.position = "fixed";
+            inner.style.top = "20px";
+
+            // safari subtracts parent border width here which is 5px
+            offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 );
+            inner.style.position = inner.style.top = "";
+
+            outer.style.overflow = "hidden";
+            outer.style.position = "relative";
+
+            offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 );
+            offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop );
+
+            body.removeChild(container);
+            div = container = null;
+
+            jQuery.extend(support, offsetSupport);
+        });
+
+        return support;
+    })();
+
+
+    var rbrace = /^(?:\{.*\}|\[.*\])$/,
+        rmultiDash = /([A-Z])/g;
+
+    jQuery.extend({
+        cache: {},
+
+        // Please use with caution
+        uuid: 0,
+
+        // Unique for each copy of jQuery on the page
+        // Non-digits removed to match rinlinejQuery
+        expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace(/\D/g, ""),
+
+        // The following elements throw uncatchable exceptions if you
+        // attempt to add expando properties to them.
+        noData: {
+            "embed": true,
+            // Ban all objects except for Flash (which handle expandos)
+            "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
+            "applet": true
+        },
+
+        hasData: function (elem) {
+            elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
+            return !!elem && !isEmptyDataObject(elem);
+        },
+
+        data: function (elem, name, data, pvt /* Internal Use Only */) {
+            if (!jQuery.acceptData(elem)) {
+                return;
+            }
+
+            var privateCache, thisCache, ret,
+                internalKey = jQuery.expando,
+                getByName = typeof name === "string",
+
+            // We have to handle DOM nodes and JS objects differently because IE6-7
+            // can't GC object references properly across the DOM-JS boundary
+                isNode = elem.nodeType,
+
+            // Only DOM nodes need the global jQuery cache; JS object data is
+            // attached directly to the object so GC can occur automatically
+                cache = isNode ? jQuery.cache : elem,
+
+            // Only defining an ID for JS objects if its cache already exists allows
+            // the code to shortcut on the same path as a DOM node with no cache
+                id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey,
+                isEvents = name === "events";
+
+            // Avoid doing any more work than we need to when trying to get data on an
+            // object that has no data at all
+            if ((!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined) {
+                return;
+            }
+
+            if (!id) {
+                // Only DOM nodes need a new unique ID for each element since their data
+                // ends up in the global cache
+                if (isNode) {
+                    elem[ internalKey ] = id = ++jQuery.uuid;
+                } else {
+                    id = internalKey;
+                }
+            }
+
+            if (!cache[ id ]) {
+                cache[ id ] = {};
+
+                // Avoids exposing jQuery metadata on plain JS objects when the object
+                // is serialized using JSON.stringify
+                if (!isNode) {
+                    cache[ id ].toJSON = jQuery.noop;
+                }
+            }
+
+            // An object can be passed to jQuery.data instead of a key/value pair; this gets
+            // shallow copied over onto the existing cache
+            if (typeof name === "object" || typeof name === "function") {
+                if (pvt) {
+                    cache[ id ] = jQuery.extend(cache[ id ], name);
+                } else {
+                    cache[ id ].data = jQuery.extend(cache[ id ].data, name);
+                }
+            }
+
+            privateCache = thisCache = cache[ id ];
+
+            // jQuery data() is stored in a separate object inside the object's internal data
+            // cache in order to avoid key collisions between internal data and user-defined
+            // data.
+            if (!pvt) {
+                if (!thisCache.data) {
+                    thisCache.data = {};
+                }
+
+                thisCache = thisCache.data;
+            }
+
+            if (data !== undefined) {
+                thisCache[ jQuery.camelCase(name) ] = data;
+            }
+
+            // Users should not attempt to inspect the internal events object using jQuery.data,
+            // it is undocumented and subject to change. But does anyone listen? No.
+            if (isEvents && !thisCache[ name ]) {
+                return privateCache.events;
+            }
+
+            // Check for both converted-to-camel and non-converted data property names
+            // If a data property was specified
+            if (getByName) {
+
+                // First Try to find as-is property data
+                ret = thisCache[ name ];
+
+                // Test for null|undefined property data
+                if (ret == null) {
+
+                    // Try to find the camelCased property
+                    ret = thisCache[ jQuery.camelCase(name) ];
+                }
+            } else {
+                ret = thisCache;
+            }
+
+            return ret;
+        },
+
+        removeData: function (elem, name, pvt /* Internal Use Only */) {
+            if (!jQuery.acceptData(elem)) {
+                return;
+            }
+
+            var thisCache, i, l,
+
+            // Reference to internal data cache key
+                internalKey = jQuery.expando,
+
+                isNode = elem.nodeType,
+
+            // See jQuery.data for more information
+                cache = isNode ? jQuery.cache : elem,
+
+            // See jQuery.data for more information
+                id = isNode ? elem[ internalKey ] : internalKey;
+
+            // If there is already no cache entry for this object, there is no
+            // purpose in continuing
+            if (!cache[ id ]) {
+                return;
+            }
+
+            if (name) {
+
+                thisCache = pvt ? cache[ id ] : cache[ id ].data;
+
+                if (thisCache) {
+
+                    // Support array or space separated string names for data keys
+                    if (!jQuery.isArray(name)) {
+
+                        // try the string as a key before any manipulation
+                        if (name in thisCache) {
+                            name = [ name ];
+                        } else {
+
+                            // split the camel cased version by spaces unless a key with the spaces exists
+                            name = jQuery.camelCase(name);
+                            if (name in thisCache) {
+                                name = [ name ];
+                            } else {
+                                name = name.split(" ");
+                            }
+                        }
+                    }
+
+                    for (i = 0, l = name.length; i < l; i++) {
+                        delete thisCache[ name[i] ];
+                    }
+
+                    // If there is no data left in the cache, we want to continue
+                    // and let the cache object itself get destroyed
+                    if (!( pvt ? isEmptyDataObject : jQuery.isEmptyObject )(thisCache)) {
+                        return;
+                    }
+                }
+            }
+
+            // See jQuery.data for more information
+            if (!pvt) {
+                delete cache[ id ].data;
+
+                // Don't destroy the parent cache unless the internal data object
+                // had been the only thing left in it
+                if (!isEmptyDataObject(cache[ id ])) {
+                    return;
+                }
+            }
+
+            // Browsers that fail expando deletion also refuse to delete expandos on
+            // the window, but it will allow it on all other JS objects; other browsers
+            // don't care
+            // Ensure that `cache` is not a window object #10080
+            if (jQuery.support.deleteExpando || !cache.setInterval) {
+                delete cache[ id ];
+            } else {
+                cache[ id ] = null;
+            }
+
+            // We destroyed the cache and need to eliminate the expando on the node to avoid
+            // false lookups in the cache for entries that no longer exist
+            if (isNode) {
+                // IE does not allow us to delete expando properties from nodes,
+                // nor does it have a removeAttribute function on Document nodes;
+                // we must handle all of these cases
+                if (jQuery.support.deleteExpando) {
+                    delete elem[ internalKey ];
+                } else if (elem.removeAttribute) {
+                    elem.removeAttribute(internalKey);
+                } else {
+                    elem[ internalKey ] = null;
+                }
+            }
+        },
+
+        // For internal use only.
+        _data: function (elem, name, data) {
+            return jQuery.data(elem, name, data, true);
+        },
+
+        // A method for determining if a DOM node can handle the data expando
+        acceptData: function (elem) {
+            if (elem.nodeName) {
+                var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
+
+                if (match) {
+                    return !(match === true || elem.getAttribute("classid") !== match);
+                }
+            }
+
+            return true;
+        }
+    });
+
+    jQuery.fn.extend({
+        data: function (key, value) {
+            var parts, attr, name,
+                data = null;
+
+            if (typeof key === "undefined") {
+                if (this.length) {
+                    data = jQuery.data(this[0]);
+
+                    if (this[0].nodeType === 1 && !jQuery._data(this[0], "parsedAttrs")) {
+                        attr = this[0].attributes;
+                        for (var i = 0, l = attr.length; i < l; i++) {
+                            name = attr[i].name;
+
+                            if (name.indexOf("data-") === 0) {
+                                name = jQuery.camelCase(name.substring(5));
+
+                                dataAttr(this[0], name, data[ name ]);
+                            }
+                        }
+                        jQuery._data(this[0], "parsedAttrs", true);
+                    }
+                }
+
+                return data;
+
+            } else if (typeof key === "object") {
+                return this.each(function () {
+                    jQuery.data(this, key);
+                });
+            }
+
+            parts = key.split(".");
+            parts[1] = parts[1] ? "." + parts[1] : "";
+
+            if (value === undefined) {
+                data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
+
+                // Try to fetch any internally stored data first
+                if (data === undefined && this.length) {
+                    data = jQuery.data(this[0], key);
+                    data = dataAttr(this[0], key, data);
+                }
+
+                return data === undefined && parts[1] ?
+                    this.data(parts[0]) :
+                    data;
+
+            } else {
+                return this.each(function () {
+                    var self = jQuery(this),
+                        args = [ parts[0], value ];
+
+                    self.triggerHandler("setData" + parts[1] + "!", args);
+                    jQuery.data(this, key, value);
+                    self.triggerHandler("changeData" + parts[1] + "!", args);
+                });
+            }
+        },
+
+        removeData: function (key) {
+            return this.each(function () {
+                jQuery.removeData(this, key);
+            });
+        }
+    });
+
+    function dataAttr(elem, key, data) {
+        // If nothing was found internally, try to fetch any
+        // data from the HTML5 data-* attribute
+        if (data === undefined && elem.nodeType === 1) {
+
+            var name = "data-" + key.replace(rmultiDash, "-$1").toLowerCase();
+
+            data = elem.getAttribute(name);
+
+            if (typeof data === "string") {
+                try {
+                    data = data === "true" ? true :
+                        data === "false" ? false :
+                            data === "null" ? null :
+                                jQuery.isNumeric(data) ? parseFloat(data) :
+                                    rbrace.test(data) ? jQuery.parseJSON(data) :
+                                        data;
+                } catch (e) {
+                }
+
+                // Make sure we set the data so it isn't changed later
+                jQuery.data(elem, key, data);
+
+            } else {
+                data = undefined;
+            }
+        }
+
+        return data;
+    }
 
 // checks a cache object for emptiness
-function isEmptyDataObject( obj ) {
-	for ( var name in obj ) {
-
-		// if the public data object is empty, the private is still empty
-		if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
-			continue;
-		}
-		if ( name !== "toJSON" ) {
-			return false;
-		}
-	}
-
-	return true;
-}
-
-
-
-
-function handleQueueMarkDefer( elem, type, src ) {
-	var deferDataKey = type + "defer",
-		queueDataKey = type + "queue",
-		markDataKey = type + "mark",
-		defer = jQuery._data( elem, deferDataKey );
-	if ( defer &&
-		( src === "queue" || !jQuery._data(elem, queueDataKey) ) &&
-		( src === "mark" || !jQuery._data(elem, markDataKey) ) ) {
-		// Give room for hard-coded callbacks to fire first
-		// and eventually mark/queue something else on the element
-		setTimeout( function() {
-			if ( !jQuery._data( elem, queueDataKey ) &&
-				!jQuery._data( elem, markDataKey ) ) {
-				jQuery.removeData( elem, deferDataKey, true );
-				defer.fire();
-			}
-		}, 0 );
-	}
-}
-
-jQuery.extend({
-
-	_mark: function( elem, type ) {
-		if ( elem ) {
-			type = ( type || "fx" ) + "mark";
-			jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 );
-		}
-	},
-
-	_unmark: function( force, elem, type ) {
-		if ( force !== true ) {
-			type = elem;
-			elem = force;
-			force = false;
-		}
-		if ( elem ) {
-			type = type || "fx";
-			var key = type + "mark",
-				count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 );
-			if ( count ) {
-				jQuery._data( elem, key, count );
-			} else {
-				jQuery.removeData( elem, key, true );
-				handleQueueMarkDefer( elem, type, "mark" );
-			}
-		}
-	},
-
-	queue: function( elem, type, data ) {
-		var q;
-		if ( elem ) {
-			type = ( type || "fx" ) + "queue";
-			q = jQuery._data( elem, type );
-
-			// Speed up dequeue by getting out quickly if this is just a lookup
-			if ( data ) {
-				if ( !q || jQuery.isArray(data) ) {
-					q = jQuery._data( elem, type, jQuery.makeArray(data) );
-				} else {
-					q.push( data );
-				}
-			}
-			return q || [];
-		}
-	},
-
-	dequeue: function( elem, type ) {
-		type = type || "fx";
-
-		var queue = jQuery.queue( elem, type ),
-			fn = queue.shift(),
-			hooks = {};
-
-		// If the fx queue is dequeued, always remove the progress sentinel
-		if ( fn === "inprogress" ) {
-			fn = queue.shift();
-		}
-
-		if ( fn ) {
-			// Add a progress sentinel to prevent the fx queue from being
-			// automatically dequeued
-			if ( type === "fx" ) {
-				queue.unshift( "inprogress" );
-			}
-
-			jQuery._data( elem, type + ".run", hooks );
-			fn.call( elem, function() {
-				jQuery.dequeue( elem, type );
-			}, hooks );
-		}
-
-		if ( !queue.length ) {
-			jQuery.removeData( elem, type + "queue " + type + ".run", true );
-			handleQueueMarkDefer( elem, type, "queue" );
-		}
-	}
-});
-
-jQuery.fn.extend({
-	queue: function( type, data ) {
-		if ( typeof type !== "string" ) {
-			data = type;
-			type = "fx";
-		}
-
-		if ( data === undefined ) {
-			return jQuery.queue( this[0], type );
-		}
-		return this.each(function() {
-			var queue = jQuery.queue( this, type, data );
-
-			if ( type === "fx" && queue[0] !== "inprogress" ) {
-				jQuery.dequeue( this, type );
-			}
-		});
-	},
-	dequeue: function( type ) {
-		return this.each(function() {
-			jQuery.dequeue( this, type );
-		});
-	},
-	// Based off of the plugin by Clint Helfers, with permission.
-	// http://blindsignals.com/index.php/2009/07/jquery-delay/
-	delay: function( time, type ) {
-		time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
-		type = type || "fx";
-
-		return this.queue( type, function( next, hooks ) {
-			var timeout = setTimeout( next, time );
-			hooks.stop = function() {
-				clearTimeout( timeout );
-			};
-		});
-	},
-	clearQueue: function( type ) {
-		return this.queue( type || "fx", [] );
-	},
-	// Get a promise resolved when queues of a certain type
-	// are emptied (fx is the type by default)
-	promise: function( type, object ) {
-		if ( typeof type !== "string" ) {
-			object = type;
-			type = undefined;
-		}
-		type = type || "fx";
-		var defer = jQuery.Deferred(),
-			elements = this,
-			i = elements.length,
-			count = 1,
-			deferDataKey = type + "defer",
-			queueDataKey = type + "queue",
-			markDataKey = type + "mark",
-			tmp;
-		function resolve() {
-			if ( !( --count ) ) {
-				defer.resolveWith( elements, [ elements ] );
-			}
-		}
-		while( i-- ) {
-			if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
-					( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
-						jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
-					jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) {
-				count++;
-				tmp.add( resolve );
-			}
-		}
-		resolve();
-		return defer.promise();
-	}
-});
-
-
-
-
-var rclass = /[\n\t\r]/g,
-	rspace = /\s+/,
-	rreturn = /\r/g,
-	rtype = /^(?:button|input)$/i,
-	rfocusable = /^(?:button|input|object|select|textarea)$/i,
-	rclickable = /^a(?:rea)?$/i,
-	rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
-	getSetAttribute = jQuery.support.getSetAttribute,
-	nodeHook, boolHook, fixSpecified;
-
-jQuery.fn.extend({
-	attr: function( name, value ) {
-		return jQuery.access( this, name, value, true, jQuery.attr );
-	},
-
-	removeAttr: function( name ) {
-		return this.each(function() {
-			jQuery.removeAttr( this, name );
-		});
-	},
-
-	prop: function( name, value ) {
-		return jQuery.access( this, name, value, true, jQuery.prop );
-	},
-
-	removeProp: function( name ) {
-		name = jQuery.propFix[ name ] || name;
-		return this.each(function() {
-			// try/catch handles cases where IE balks (such as removing a property on window)
-			try {
-				this[ name ] = undefined;
-				delete this[ name ];
-			} catch( e ) {}
-		});
-	},
-
-	addClass: function( value ) {
-		var classNames, i, l, elem,
-			setClass, c, cl;
-
-		if ( jQuery.isFunction( value ) ) {
-			return this.each(function( j ) {
-				jQuery( this ).addClass( value.call(this, j, this.className) );
-			});
-		}
-
-		if ( value && typeof value === "string" ) {
-			classNames = value.split( rspace );
-
-			for ( i = 0, l = this.length; i < l; i++ ) {
-				elem = this[ i ];
-
-				if ( elem.nodeType === 1 ) {
-					if ( !elem.className && classNames.length === 1 ) {
-						elem.className = value;
-
-					} else {
-						setClass = " " + elem.className + " ";
-
-						for ( c = 0, cl = classNames.length; c < cl; c++ ) {
-							if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
-								setClass += classNames[ c ] + " ";
-							}
-						}
-						elem.className = jQuery.trim( setClass );
-					}
-				}
-			}
-		}
-
-		return this;
-	},
-
-	removeClass: function( value ) {
-		var classNames, i, l, elem, className, c, cl;
-
-		if ( jQuery.isFunction( value ) ) {
-			return this.each(function( j ) {
-				jQuery( this ).removeClass( value.call(this, j, this.className) );
-			});
-		}
-
-		if ( (value && typeof value === "string") || value === undefined ) {
-			classNames = ( value || "" ).split( rspace );
-
-			for ( i = 0, l = this.length; i < l; i++ ) {
-				elem = this[ i ];
-
-				if ( elem.nodeType === 1 && elem.className ) {
-					if ( value ) {
-						className = (" " + elem.className + " ").replace( rclass, " " );
-						for ( c = 0, cl = classNames.length; c < cl; c++ ) {
-							className = className.replace(" " + classNames[ c ] + " ", " ");
-						}
-						elem.className = jQuery.trim( className );
-
-					} else {
-						elem.className = "";
-					}
-				}
-			}
-		}
-
-		return this;
-	},
-
-	toggleClass: function( value, stateVal ) {
-		var type = typeof value,
-			isBool = typeof stateVal === "boolean";
-
-		if ( jQuery.isFunction( value ) ) {
-			return this.each(function( i ) {
-				jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
-			});
-		}
-
-		return this.each(function() {
-			if ( type === "string" ) {
-				// toggle individual class names
-				var className,
-					i = 0,
-					self = jQuery( this ),
-					state = stateVal,
-					classNames = value.split( rspace );
-
-				while ( (className = classNames[ i++ ]) ) {
-					// check each className given, space seperated list
-					state = isBool ? state : !self.hasClass( className );
-					self[ state ? "addClass" : "removeClass" ]( className );
-				}
-
-			} else if ( type === "undefined" || type === "boolean" ) {
-				if ( this.className ) {
-					// store className if set
-					jQuery._data( this, "__className__", this.className );
-				}
-
-				// toggle whole className
-				this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
-			}
-		});
-	},
-
-	hasClass: function( selector ) {
-		var className = " " + selector + " ",
-			i = 0,
-			l = this.length;
-		for ( ; i < l; i++ ) {
-			if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
-				return true;
-			}
-		}
-
-		return false;
-	},
-
-	val: function( value ) {
-		var hooks, ret, isFunction,
-			elem = this[0];
-
-		if ( !arguments.length ) {
-			if ( elem ) {
-				hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
-
-				if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
-					return ret;
-				}
-
-				ret = elem.value;
-
-				return typeof ret === "string" ?
-					// handle most common string cases
-					ret.replace(rreturn, "") :
-					// handle cases where value is null/undef or number
-					ret == null ? "" : ret;
-			}
-
-			return;
-		}
-
-		isFunction = jQuery.isFunction( value );
-
-		return this.each(function( i ) {
-			var self = jQuery(this), val;
-
-			if ( this.nodeType !== 1 ) {
-				return;
-			}
-
-			if ( isFunction ) {
-				val = value.call( this, i, self.val() );
-			} else {
-				val = value;
-			}
-
-			// Treat null/undefined as ""; convert numbers to string
-			if ( val == null ) {
-				val = "";
-			} else if ( typeof val === "number" ) {
-				val += "";
-			} else if ( jQuery.isArray( val ) ) {
-				val = jQuery.map(val, function ( value ) {
-					return value == null ? "" : value + "";
-				});
-			}
-
-			hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];
-
-			// If set returns undefined, fall back to normal setting
-			if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
-				this.value = val;
-			}
-		});
-	}
-});
-
-jQuery.extend({
-	valHooks: {
-		option: {
-			get: function( elem ) {
-				// attributes.value is undefined in Blackberry 4.7 but
-				// uses .value. See #6932
-				var val = elem.attributes.value;
-				return !val || val.specified ? elem.value : elem.text;
-			}
-		},
-		select: {
-			get: function( elem ) {
-				var value, i, max, option,
-					index = elem.selectedIndex,
-					values = [],
-					options = elem.options,
-					one = elem.type === "select-one";
-
-				// Nothing was selected
-				if ( index < 0 ) {
-					return null;
-				}
-
-				// Loop through all the selected options
-				i = one ? index : 0;
-				max = one ? index + 1 : options.length;
-				for ( ; i < max; i++ ) {
-					option = options[ i ];
-
-					// Don't return options that are disabled or in a disabled optgroup
-					if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
-							(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
-
-						// Get the specific value for the option
-						value = jQuery( option ).val();
-
-						// We don't need an array for one selects
-						if ( one ) {
-							return value;
-						}
-
-						// Multi-Selects return an array
-						values.push( value );
-					}
-				}
-
-				// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
-				if ( one && !values.length && options.length ) {
-					return jQuery( options[ index ] ).val();
-				}
-
-				return values;
-			},
-
-			set: function( elem, value ) {
-				var values = jQuery.makeArray( value );
-
-				jQuery(elem).find("option").each(function() {
-					this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
-				});
-
-				if ( !values.length ) {
-					elem.selectedIndex = -1;
-				}
-				return values;
-			}
-		}
-	},
-
-	attrFn: {
-		val: true,
-		css: true,
-		html: true,
-		text: true,
-		data: true,
-		width: true,
-		height: true,
-		offset: true
-	},
-
-	attr: function( elem, name, value, pass ) {
-		var ret, hooks, notxml,
-			nType = elem.nodeType;
-
-		// don't get/set attributes on text, comment and attribute nodes
-		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
-			return;
-		}
-
-		if ( pass && name in jQuery.attrFn ) {
-			return jQuery( elem )[ name ]( value );
-		}
-
-		// Fallback to prop when attributes are not supported
-		if ( typeof elem.getAttribute === "undefined" ) {
-			return jQuery.prop( elem, name, value );
-		}
-
-		notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
-
-		// All attributes are lowercase
-		// Grab necessary hook if one is defined
-		if ( notxml ) {
-			name = name.toLowerCase();
-			hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
-		}
-
-		if ( value !== undefined ) {
-
-			if ( value === null ) {
-				jQuery.removeAttr( elem, name );
-				return;
-
-			} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
-				return ret;
-
-			} else {
-				elem.setAttribute( name, "" + value );
-				return value;
-			}
-
-		} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
-			return ret;
-
-		} else {
-
-			ret = elem.getAttribute( name );
-
-			// Non-existent attributes return null, we normalize to undefined
-			return ret === null ?
-				undefined :
-				ret;
-		}
-	},
-
-	removeAttr: function( elem, value ) {
-		var propName, attrNames, name, l,
-			i = 0;
-
-		if ( value && elem.nodeType === 1 ) {
-			attrNames = value.toLowerCase().split( rspace );
-			l = attrNames.length;
-
-			for ( ; i < l; i++ ) {
-				name = attrNames[ i ];
-
-				if ( name ) {
-					propName = jQuery.propFix[ name ] || name;
-
-					// See #9699 for explanation of this approach (setting first, then removal)
-					jQuery.attr( elem, name, "" );
-					elem.removeAttribute( getSetAttribute ? name : propName );
-
-					// Set corresponding property to false for boolean attributes
-					if ( rboolean.test( name ) && propName in elem ) {
-						elem[ propName ] = false;
-					}
-				}
-			}
-		}
-	},
-
-	attrHooks: {
-		type: {
-			set: function( elem, value ) {
-				// We can't allow the type property to be changed (since it causes problems in IE)
-				if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
-					jQuery.error( "type property can't be changed" );
-				} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
-					// Setting the type on a radio button after the value resets the value in IE6-9
-					// Reset value to it's default in case type is set after value
-					// This is for element creation
-					var val = elem.value;
-					elem.setAttribute( "type", value );
-					if ( val ) {
-						elem.value = val;
-					}
-					return value;
-				}
-			}
-		},
-		// Use the value property for back compat
-		// Use the nodeHook for button elements in IE6/7 (#1954)
-		value: {
-			get: function( elem, name ) {
-				if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
-					return nodeHook.get( elem, name );
-				}
-				return name in elem ?
-					elem.value :
-					null;
-			},
-			set: function( elem, value, name ) {
-				if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
-					return nodeHook.set( elem, value, name );
-				}
-				// Does not return so that setAttribute is also used
-				elem.value = value;
-			}
-		}
-	},
-
-	propFix: {
-		tabindex: "tabIndex",
-		readonly: "readOnly",
-		"for": "htmlFor",
-		"class": "className",
-		maxlength: "maxLength",
-		cellspacing: "cellSpacing",
-		cellpadding: "cellPadding",
-		rowspan: "rowSpan",
-		colspan: "colSpan",
-		usemap: "useMap",
-		frameborder: "frameBorder",
-		contenteditable: "contentEditable"
-	},
-
-	prop: function( elem, name, value ) {
-		var ret, hooks, notxml,
-			nType = elem.nodeType;
-
-		// don't get/set properties on text, comment and attribute nodes
-		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
-			return;
-		}
-
-		notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
-
-		if ( notxml ) {
-			// Fix name and attach hooks
-			name = jQuery.propFix[ name ] || name;
-			hooks = jQuery.propHooks[ name ];
-		}
-
-		if ( value !== undefined ) {
-			if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
-				return ret;
-
-			} else {
-				return ( elem[ name ] = value );
-			}
-
-		} else {
-			if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
-				return ret;
-
-			} else {
-				return elem[ name ];
-			}
-		}
-	},
-
-	propHooks: {
-		tabIndex: {
-			get: function( elem ) {
-				// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
-				// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
-				var attributeNode = elem.getAttributeNode("tabindex");
-
-				return attributeNode && attributeNode.specified ?
-					parseInt( attributeNode.value, 10 ) :
-					rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
-						0 :
-						undefined;
-			}
-		}
-	}
-});
+    function isEmptyDataObject(obj) {
+        for (var name in obj) {
+
+            // if the public data object is empty, the private is still empty
+            if (name === "data" && jQuery.isEmptyObject(obj[name])) {
+                continue;
+            }
+            if (name !== "toJSON") {
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+
+    function handleQueueMarkDefer(elem, type, src) {
+        var deferDataKey = type + "defer",
+            queueDataKey = type + "queue",
+            markDataKey = type + "mark",
+            defer = jQuery._data(elem, deferDataKey);
+        if (defer &&
+            ( src === "queue" || !jQuery._data(elem, queueDataKey) ) &&
+            ( src === "mark" || !jQuery._data(elem, markDataKey) )) {
+            // Give room for hard-coded callbacks to fire first
+            // and eventually mark/queue something else on the element
+            setTimeout(function () {
+                if (!jQuery._data(elem, queueDataKey) && !jQuery._data(elem, markDataKey)) {
+                    jQuery.removeData(elem, deferDataKey, true);
+                    defer.fire();
+                }
+            }, 0);
+        }
+    }
+
+    jQuery.extend({
+
+        _mark: function (elem, type) {
+            if (elem) {
+                type = ( type || "fx" ) + "mark";
+                jQuery._data(elem, type, (jQuery._data(elem, type) || 0) + 1);
+            }
+        },
+
+        _unmark: function (force, elem, type) {
+            if (force !== true) {
+                type = elem;
+                elem = force;
+                force = false;
+            }
+            if (elem) {
+                type = type || "fx";
+                var key = type + "mark",
+                    count = force ? 0 : ( (jQuery._data(elem, key) || 1) - 1 );
+                if (count) {
+                    jQuery._data(elem, key, count);
+                } else {
+                    jQuery.removeData(elem, key, true);
+                    handleQueueMarkDefer(elem, type, "mark");
+                }
+            }
+        },
+
+        queue: function (elem, type, data) {
+            var q;
+            if (elem) {
+                type = ( type || "fx" ) + "queue";
+                q = jQuery._data(elem, type);
+
+                // Speed up dequeue by getting out quickly if this is just a lookup
+                if (data) {
+                    if (!q || jQuery.isArray(data)) {
+                        q = jQuery._data(elem, type, jQuery.makeArray(data));
+                    } else {
+                        q.push(data);
+                    }
+                }
+                return q || [];
+            }
+        },
+
+        dequeue: function (elem, type) {
+            type = type || "fx";
+
+            var queue = jQuery.queue(elem, type),
+                fn = queue.shift(),
+                hooks = {};
+
+            // If the fx queue is dequeued, always remove the progress sentinel
+            if (fn === "inprogress") {
+                fn = queue.shift();
+            }
+
+            if (fn) {
+                // Add a progress sentinel to prevent the fx queue from being
+                // automatically dequeued
+                if (type === "fx") {
+                    queue.unshift("inprogress");
+                }
+
+                jQuery._data(elem, type + ".run", hooks);
+                fn.call(elem, function () {
+                    jQuery.dequeue(elem, type);
+                }, hooks);
+            }
+
+            if (!queue.length) {
+                jQuery.removeData(elem, type + "queue " + type + ".run", true);
+                handleQueueMarkDefer(elem, type, "queue");
+            }
+        }
+    });
+
+    jQuery.fn.extend({
+        queue: function (type, data) {
+            if (typeof type !== "string") {
+                data = type;
+                type = "fx";
+            }
+
+            if (data === undefined) {
+                return jQuery.queue(this[0], type);
+            }
+            return this.each(function () {
+                var queue = jQuery.queue(this, type, data);
+
+                if (type === "fx" && queue[0] !== "inprogress") {
+                    jQuery.dequeue(this, type);
+                }
+            });
+        },
+        dequeue: function (type) {
+            return this.each(function () {
+                jQuery.dequeue(this, type);
+            });
+        },
+        // Based off of the plugin by Clint Helfers, with permission.
+        // http://blindsignals.com/index.php/2009/07/jquery-delay/
+        delay: function (time, type) {
+            time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
+            type = type || "fx";
+
+            return this.queue(type, function (next, hooks) {
+                var timeout = setTimeout(next, time);
+                hooks.stop = function () {
+                    clearTimeout(timeout);
+                };
+            });
+        },
+        clearQueue: function (type) {
+            return this.queue(type || "fx", []);
+        },
+        // Get a promise resolved when queues of a certain type
+        // are emptied (fx is the type by default)
+        promise: function (type, object) {
+            if (typeof type !== "string") {
+                object = type;
+                type = undefined;
+            }
+            type = type || "fx";
+            var defer = jQuery.Deferred(),
+                elements = this,
+                i = elements.length,
+                count = 1,
+                deferDataKey = type + "defer",
+                queueDataKey = type + "queue",
+                markDataKey = type + "mark",
+                tmp;
+
+            function resolve() {
+                if (!( --count )) {
+                    defer.resolveWith(elements, [ elements ]);
+                }
+            }
+
+            while (i--) {
+                if (( tmp = jQuery.data(elements[ i ], deferDataKey, undefined, true) ||
+                    ( jQuery.data(elements[ i ], queueDataKey, undefined, true) ||
+                        jQuery.data(elements[ i ], markDataKey, undefined, true) ) &&
+                        jQuery.data(elements[ i ], deferDataKey, jQuery.Callbacks("once memory"), true) )) {
+                    count++;
+                    tmp.add(resolve);
+                }
+            }
+            resolve();
+            return defer.promise();
+        }
+    });
+
+
+    var rclass = /[\n\t\r]/g,
+        rspace = /\s+/,
+        rreturn = /\r/g,
+        rtype = /^(?:button|input)$/i,
+        rfocusable = /^(?:button|input|object|select|textarea)$/i,
+        rclickable = /^a(?:rea)?$/i,
+        rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
+        getSetAttribute = jQuery.support.getSetAttribute,
+        nodeHook, boolHook, fixSpecified;
+
+    jQuery.fn.extend({
+        attr: function (name, value) {
+            return jQuery.access(this, name, value, true, jQuery.attr);
+        },
+
+        removeAttr: function (name) {
+            return this.each(function () {
+                jQuery.removeAttr(this, name);
+            });
+        },
+
+        prop: function (name, value) {
+            return jQuery.access(this, name, value, true, jQuery.prop);
+        },
+
+        removeProp: function (name) {
+            name = jQuery.propFix[ name ] || name;
+            return this.each(function () {
+                // try/catch handles cases where IE balks (such as removing a property on window)
+                try {
+                    this[ name ] = undefined;
+                    delete this[ name ];
+                } catch (e) {
+                }
+            });
+        },
+
+        addClass: function (value) {
+            var classNames, i, l, elem,
+                setClass, c, cl;
+
+            if (jQuery.isFunction(value)) {
+                return this.each(function (j) {
+                    jQuery(this).addClass(value.call(this, j, this.className));
+                });
+            }
+
+            if (value && typeof value === "string") {
+                classNames = value.split(rspace);
+
+                for (i = 0, l = this.length; i < l; i++) {
+                    elem = this[ i ];
+
+                    if (elem.nodeType === 1) {
+                        if (!elem.className && classNames.length === 1) {
+                            elem.className = value;
+
+                        } else {
+                            setClass = " " + elem.className + " ";
+
+                            for (c = 0, cl = classNames.length; c < cl; c++) {
+                                if (!~setClass.indexOf(" " + classNames[ c ] + " ")) {
+                                    setClass += classNames[ c ] + " ";
+                                }
+                            }
+                            elem.className = jQuery.trim(setClass);
+                        }
+                    }
+                }
+            }
+
+            return this;
+        },
+
+        removeClass: function (value) {
+            var classNames, i, l, elem, className, c, cl;
+
+            if (jQuery.isFunction(value)) {
+                return this.each(function (j) {
+                    jQuery(this).removeClass(value.call(this, j, this.className));
+                });
+            }
+
+            if ((value && typeof value === "string") || value === undefined) {
+                classNames = ( value || "" ).split(rspace);
+
+                for (i = 0, l = this.length; i < l; i++) {
+                    elem = this[ i ];
+
+                    if (elem.nodeType === 1 && elem.className) {
+                        if (value) {
+                            className = (" " + elem.className + " ").replace(rclass, " ");
+                            for (c = 0, cl = classNames.length; c < cl; c++) {
+                                className = className.replace(" " + classNames[ c ] + " ", " ");
+                            }
+                            elem.className = jQuery.trim(className);
+
+                        } else {
+                            elem.className = "";
+                        }
+                    }
+                }
+            }
+
+            return this;
+        },
+
+        toggleClass: function (value, stateVal) {
+            var type = typeof value,
+                isBool = typeof stateVal === "boolean";
+
+            if (jQuery.isFunction(value)) {
+                return this.each(function (i) {
+                    jQuery(this).toggleClass(value.call(this, i, this.className, stateVal), stateVal);
+                });
+            }
+
+            return this.each(function () {
+                if (type === "string") {
+                    // toggle individual class names
+                    var className,
+                        i = 0,
+                        self = jQuery(this),
+                        state = stateVal,
+                        classNames = value.split(rspace);
+
+                    while ((className = classNames[ i++ ])) {
+                        // check each className given, space seperated list
+                        state = isBool ? state : !self.hasClass(className);
+                        self[ state ? "addClass" : "removeClass" ](className);
+                    }
+
+                } else if (type === "undefined" || type === "boolean") {
+                    if (this.className) {
+                        // store className if set
+                        jQuery._data(this, "__className__", this.className);
+                    }
+
+                    // toggle whole className
+                    this.className = this.className || value === false ? "" : jQuery._data(this, "__className__") || "";
+                }
+            });
+        },
+
+        hasClass: function (selector) {
+            var className = " " + selector + " ",
+                i = 0,
+                l = this.length;
+            for (; i < l; i++) {
+                if (this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf(className) > -1) {
+                    return true;
+                }
+            }
+
+            return false;
+        },
+
+        val: function (value) {
+            var hooks, ret, isFunction,
+                elem = this[0];
+
+            if (!arguments.length) {
+                if (elem) {
+                    hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
+
+                    if (hooks && "get" in hooks && (ret = hooks.get(elem, "value")) !== undefined) {
+                        return ret;
+                    }
+
+                    ret = elem.value;
+
+                    return typeof ret === "string" ?
+                        // handle most common string cases
+                        ret.replace(rreturn, "") :
+                        // handle cases where value is null/undef or number
+                        ret == null ? "" : ret;
+                }
+
+                return;
+            }
+
+            isFunction = jQuery.isFunction(value);
+
+            return this.each(function (i) {
+                var self = jQuery(this), val;
+
+                if (this.nodeType !== 1) {
+                    return;
+                }
+
+                if (isFunction) {
+                    val = value.call(this, i, self.val());
+                } else {
+                    val = value;
+                }
+
+                // Treat null/undefined as ""; convert numbers to string
+                if (val == null) {
+                    val = "";
+                } else if (typeof val === "number") {
+                    val += "";
+                } else if (jQuery.isArray(val)) {
+                    val = jQuery.map(val, function (value) {
+                        return value == null ? "" : value + "";
+                    });
+                }
+
+                hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];
+
+                // If set returns undefined, fall back to normal setting
+                if (!hooks || !("set" in hooks) || hooks.set(this, val, "value") === undefined) {
+                    this.value = val;
+                }
+            });
+        }
+    });
+
+    jQuery.extend({
+        valHooks: {
+            option: {
+                get: function (elem) {
+                    // attributes.value is undefined in Blackberry 4.7 but
+                    // uses .value. See #6932
+                    var val = elem.attributes.value;
+                    return !val || val.specified ? elem.value : elem.text;
+                }
+            },
+            select: {
+                get: function (elem) {
+                    var value, i, max, option,
+                        index = elem.selectedIndex,
+                        values = [],
+                        options = elem.options,
+                        one = elem.type === "select-one";
+
+                    // Nothing was selected
+                    if (index < 0) {
+                        return null;
+                    }
+
+                    // Loop through all the selected options
+                    i = one ? index : 0;
+                    max = one ? index + 1 : options.length;
+                    for (; i < max; i++) {
+                        option = options[ i ];
+
+                        // Don't return options that are disabled or in a disabled optgroup
+                        if (option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
+                            (!option.parentNode.disabled || !jQuery.nodeName(option.parentNode, "optgroup"))) {
+
+                            // Get the specific value for the option
+                            value = jQuery(option).val();
+
+                            // We don't need an array for one selects
+                            if (one) {
+                                return value;
+                            }
+
+                            // Multi-Selects return an array
+                            values.push(value);
+                        }
+                    }
+
+                    // Fixes Bug #2551 -- select.val() broken in IE after form.reset()
+                    if (one && !values.length && options.length) {
+                        return jQuery(options[ index ]).val();
+                    }
+
+                    return values;
+                },
+
+                set: function (elem, value) {
+                    var values = jQuery.makeArray(value);
+
+                    jQuery(elem).find("option").each(function () {
+                        this.selected = jQuery.inArray(jQuery(this).val(), values) >= 0;
+                    });
+
+                    if (!values.length) {
+                        elem.selectedIndex = -1;
+                    }
+                    return values;
+                }
+            }
+        },
+
+        attrFn: {
+            val: true,
+            css: true,
+            html: true,
+            text: true,
+            data: true,
+            width: true,
+            height: true,
+            offset: true
+        },
+
+        attr: function (elem, name, value, pass) {
+            var ret, hooks, notxml,
+                nType = elem.nodeType;
+
+            // don't get/set attributes on text, comment and attribute nodes
+            if (!elem || nType === 3 || nType === 8 || nType === 2) {
+                return;
+            }
+
+            if (pass && name in jQuery.attrFn) {
+                return jQuery(elem)[ name ](value);
+            }
+
+            // Fallback to prop when attributes are not supported
+            if (typeof elem.getAttribute === "undefined") {
+                return jQuery.prop(elem, name, value);
+            }
+
+            notxml = nType !== 1 || !jQuery.isXMLDoc(elem);
+
+            // All attributes are lowercase
+            // Grab necessary hook if one is defined
+            if (notxml) {
+                name = name.toLowerCase();
+                hooks = jQuery.attrHooks[ name ] || ( rboolean.test(name) ? boolHook : nodeHook );
+            }
+
+            if (value !== undefined) {
+
+                if (value === null) {
+                    jQuery.removeAttr(elem, name);
+                    return;
+
+                } else if (hooks && "set" in hooks && notxml && (ret = hooks.set(elem, value, name)) !== undefined) {
+                    return ret;
+
+                } else {
+                    elem.setAttribute(name, "" + value);
+                    return value;
+                }
+
+            } else if (hooks && "get" in hooks && notxml && (ret = hooks.get(elem, name)) !== null) {
+                return ret;
+
+            } else {
+
+                ret = elem.getAttribute(name);
+
+                // Non-existent attributes return null, we normalize to undefined
+                return ret === null ?
+                    undefined :
+                    ret;
+            }
+        },
+
+        removeAttr: function (elem, value) {
+            var propName, attrNames, name, l,
+                i = 0;
+
+            if (value && elem.nodeType === 1) {
+                attrNames = value.toLowerCase().split(rspace);
+                l = attrNames.length;
+
+                for (; i < l; i++) {
+                    name = attrNames[ i ];
+
+                    if (name) {
+                        propName = jQuery.propFix[ name ] || name;
+
+                        // See #9699 for explanation of this approach (setting first, then removal)
+                        jQuery.attr(elem, name, "");
+                        elem.removeAttribute(getSetAttribute ? name : propName);
+
+                        // Set corresponding property to false for boolean attributes
+                        if (rboolean.test(name) && propName in elem) {
+                            elem[ propName ] = false;
+                        }
+                    }
+                }
+            }
+        },
+
+        attrHooks: {
+            type: {
+                set: function (elem, value) {
+                    // We can't allow the type property to be changed (since it causes problems in IE)
+                    if (rtype.test(elem.nodeName) && elem.parentNode) {
+                        jQuery.error("type property can't be changed");
+                    } else if (!jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input")) {
+                        // Setting the type on a radio button after the value resets the value in IE6-9
+                        // Reset value to it's default in case type is set after value
+                        // This is for element creation
+                        var val = elem.value;
+                        elem.setAttribute("type", value);
+                        if (val) {
+                            elem.value = val;
+                        }
+                        return value;
+                    }
+                }
+            },
+            // Use the value property for back compat
+            // Use the nodeHook for button elements in IE6/7 (#1954)
+            value: {
+                get: function (elem, name) {
+                    if (nodeHook && jQuery.nodeName(elem, "button")) {
+                        return nodeHook.get(elem, name);
+                    }
+                    return name in elem ?
+                        elem.value :
+                        null;
+                },
+                set: function (elem, value, name) {
+                    if (nodeHook && jQuery.nodeName(elem, "button")) {
+                        return nodeHook.set(elem, value, name);
+                    }
+                    // Does not return so that setAttribute is also used
+                    elem.value = value;
+                }
+            }
+        },
+
+        propFix: {
+            tabindex: "tabIndex",
+            readonly: "readOnly",
+            "for": "htmlFor",
+            "class": "className",
+            maxlength: "maxLength",
+            cellspacing: "cellSpacing",
+            cellpadding: "cellPadding",
+            rowspan: "rowSpan",
+            colspan: "colSpan",
+            usemap: "useMap",
+            frameborder: "frameBorder",
+            contenteditable: "contentEditable"
+        },
+
+        prop: function (elem, name, value) {
+            var ret, hooks, notxml,
+                nType = elem.nodeType;
+
+            // don't get/set properties on text, comment and attribute nodes
+            if (!elem || nType === 3 || nType === 8 || nType === 2) {
+                return;
+            }
+
+            notxml = nType !== 1 || !jQuery.isXMLDoc(elem);
+
+            if (notxml) {
+                // Fix name and attach hooks
+                name = jQuery.propFix[ name ] || name;
+                hooks = jQuery.propHooks[ name ];
+            }
+
+            if (value !== undefined) {
+                if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) {
+                    return ret;
+
+                } else {
+                    return ( elem[ name ] = value );
+                }
+
+            } else {
+                if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) {
+                    return ret;
+
+                } else {
+                    return elem[ name ];
+                }
+            }
+        },
+
+        propHooks: {
+            tabIndex: {
+                get: function (elem) {
+                    // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
+                    // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
+                    var attributeNode = elem.getAttributeNode("tabindex");
+
+                    return attributeNode && attributeNode.specified ?
+                        parseInt(attributeNode.value, 10) :
+                        rfocusable.test(elem.nodeName) || rclickable.test(elem.nodeName) && elem.href ?
+                            0 :
+                            undefined;
+                }
+            }
+        }
+    });
 
 // Add the tabIndex propHook to attrHooks for back-compat (different case is intentional)
-jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex;
+    jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex;
 
 // Hook for boolean attributes
-boolHook = {
-	get: function( elem, name ) {
-		// Align boolean attributes with corresponding properties
-		// Fall back to attribute presence where some booleans are not supported
-		var attrNode,
-			property = jQuery.prop( elem, name );
-		return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
-			name.toLowerCase() :
-			undefined;
-	},
-	set: function( elem, value, name ) {
-		var propName;
-		if ( value === false ) {
-			// Remove boolean attributes when set to false
-			jQuery.removeAttr( elem, name );
-		} else {
-			// value is true since we know at this point it's type boolean and not false
-			// Set boolean attributes to the same name and set the DOM property
-			propName = jQuery.propFix[ name ] || name;
-			if ( propName in elem ) {
-				// Only set the IDL specifically if it already exists on the element
-				elem[ propName ] = true;
-			}
-
-			elem.setAttribute( name, name.toLowerCase() );
-		}
-		return name;
-	}
-};
+    boolHook = {
+        get: function (elem, name) {
+            // Align boolean attributes with corresponding properties
+            // Fall back to attribute presence where some booleans are not supported
+            var attrNode,
+                property = jQuery.prop(elem, name);
+            return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
+                name.toLowerCase() :
+                undefined;
+        },
+        set: function (elem, value, name) {
+            var propName;
+            if (value === false) {
+                // Remove boolean attributes when set to false
+                jQuery.removeAttr(elem, name);
+            } else {
+                // value is true since we know at this point it's type boolean and not false
+                // Set boolean attributes to the same name and set the DOM property
+                propName = jQuery.propFix[ name ] || name;
+                if (propName in elem) {
+                    // Only set the IDL specifically if it already exists on the element
+                    elem[ propName ] = true;
+                }
+
+                elem.setAttribute(name, name.toLowerCase());
+            }
+            return name;
+        }
+    };
 
 // IE6/7 do not support getting/setting some attributes with get/setAttribute
-if ( !getSetAttribute ) {
-
-	fixSpecified = {
-		name: true,
-		id: true
-	};
-
-	// Use this for any attribute in IE6/7
-	// This fixes almost every IE6/7 issue
-	nodeHook = jQuery.valHooks.button = {
-		get: function( elem, name ) {
-			var ret;
-			ret = elem.getAttributeNode( name );
-			return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ?
-				ret.nodeValue :
-				undefined;
-		},
-		set: function( elem, value, name ) {
-			// Set the existing or create a new attribute node
-			var ret = elem.getAttributeNode( name );
-			if ( !ret ) {
-				ret = document.createAttribute( name );
-				elem.setAttributeNode( ret );
-			}
-			return ( ret.nodeValue = value + "" );
-		}
-	};
-
-	// Apply the nodeHook to tabindex
-	jQuery.attrHooks.tabindex.set = nodeHook.set;
-
-	// Set width and height to auto instead of 0 on empty string( Bug #8150 )
-	// This is for removals
-	jQuery.each([ "width", "height" ], function( i, name ) {
-		jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
-			set: function( elem, value ) {
-				if ( value === "" ) {
-					elem.setAttribute( name, "auto" );
-					return value;
-				}
-			}
-		});
-	});
-
-	// Set contenteditable to false on removals(#10429)
-	// Setting to empty string throws an error as an invalid value
-	jQuery.attrHooks.contenteditable = {
-		get: nodeHook.get,
-		set: function( elem, value, name ) {
-			if ( value === "" ) {
-				value = "false";
-			}
-			nodeHook.set( elem, value, name );
-		}
-	};
-}
+    if (!getSetAttribute) {
+
+        fixSpecified = {
+            name: true,
+            id: true
+        };
+
+        // Use this for any attribute in IE6/7
+        // This fixes almost every IE6/7 issue
+        nodeHook = jQuery.valHooks.button = {
+            get: function (elem, name) {
+                var ret;
+                ret = elem.getAttributeNode(name);
+                return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ?
+                    ret.nodeValue :
+                    undefined;
+            },
+            set: function (elem, value, name) {
+                // Set the existing or create a new attribute node
+                var ret = elem.getAttributeNode(name);
+                if (!ret) {
+                    ret = document.createAttribute(name);
+                    elem.setAttributeNode(ret);
+                }
+                return ( ret.nodeValue = value + "" );
+            }
+        };
+
+        // Apply the nodeHook to tabindex
+        jQuery.attrHooks.tabindex.set = nodeHook.set;
+
+        // Set width and height to auto instead of 0 on empty string( Bug #8150 )
+        // This is for removals
+        jQuery.each([ "width", "height" ], function (i, name) {
+            jQuery.attrHooks[ name ] = jQuery.extend(jQuery.attrHooks[ name ], {
+                set: function (elem, value) {
+                    if (value === "") {
+                        elem.setAttribute(name, "auto");
+                        return value;
+                    }
+                }
+            });
+        });
+
+        // Set contenteditable to false on removals(#10429)
+        // Setting to empty string throws an error as an invalid value
+        jQuery.attrHooks.contenteditable = {
+            get: nodeHook.get,
+            set: function (elem, value, name) {
+                if (value === "") {
+                    value = "false";
+                }
+                nodeHook.set(elem, value, name);
+            }
+        };
+    }
 
 
 // Some attributes require a special call on IE
-if ( !jQuery.support.hrefNormalized ) {
-	jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
-		jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
-			get: function( elem ) {
-				var ret = elem.getAttribute( name, 2 );
-				return ret === null ? undefined : ret;
-			}
-		});
-	});
-}
-
-if ( !jQuery.support.style ) {
-	jQuery.attrHooks.style = {
-		get: function( elem ) {
-			// Return undefined in the case of empty string
-			// Normalize to lowercase since IE uppercases css property names
-			return elem.style.cssText.toLowerCase() || undefined;
-		},
-		set: function( elem, value ) {
-			return ( elem.style.cssText = "" + value );
-		}
-	};
-}
+    if (!jQuery.support.hrefNormalized) {
+        jQuery.each([ "href", "src", "width", "height" ], function (i, name) {
+            jQuery.attrHooks[ name ] = jQuery.extend(jQuery.attrHooks[ name ], {
+                get: function (elem) {
+                    var ret = elem.getAttribute(name, 2);
+                    return ret === null ? undefined : ret;
+                }
+            });
+        });
+    }
+
+    if (!jQuery.support.style) {
+        jQuery.attrHooks.style = {
+            get: function (elem) {
+                // Return undefined in the case of empty string
+                // Normalize to lowercase since IE uppercases css property names
+                return elem.style.cssText.toLowerCase() || undefined;
+            },
+            set: function (elem, value) {
+                return ( elem.style.cssText = "" + value );
+            }
+        };
+    }
 
 // Safari mis-reports the default selected property of an option
 // Accessing the parent's selectedIndex property fixes it
-if ( !jQuery.support.optSelected ) {
-	jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
-		get: function( elem ) {
-			var parent = elem.parentNode;
-
-			if ( parent ) {
-				parent.selectedIndex;
-
-				// Make sure that it also works with optgroups, see #5701
-				if ( parent.parentNode ) {
-					parent.parentNode.selectedIndex;
-				}
-			}
-			return null;
-		}
-	});
-}
+    if (!jQuery.support.optSelected) {
+        jQuery.propHooks.selected = jQuery.extend(jQuery.propHooks.selected, {
+            get: function (elem) {
+                var parent = elem.parentNode;
+
+                if (parent) {
+                    parent.selectedIndex;
+
+                    // Make sure that it also works with optgroups, see #5701
+                    if (parent.parentNode) {
+                        parent.parentNode.selectedIndex;
+                    }
+                }
+                return null;
+            }
+        });
+    }
 
 // IE6/7 call enctype encoding
-if ( !jQuery.support.enctype ) {
-	jQuery.propFix.enctype = "encoding";
-}
+    if (!jQuery.support.enctype) {
+        jQuery.propFix.enctype = "encoding";
+    }
 
 // Radios and checkboxes getter/setter
-if ( !jQuery.support.checkOn ) {
-	jQuery.each([ "radio", "checkbox" ], function() {
-		jQuery.valHooks[ this ] = {
-			get: function( elem ) {
-				// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
-				return elem.getAttribute("value") === null ? "on" : elem.value;
-			}
-		};
-	});
-}
-jQuery.each([ "radio", "checkbox" ], function() {
-	jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
-		set: function( elem, value ) {
-			if ( jQuery.isArray( value ) ) {
-				return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
-			}
-		}
-	});
-});
-
-
-
-
-var rformElems = /^(?:textarea|input|select)$/i,
-	rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/,
-	rhoverHack = /\bhover(\.\S+)?\b/,
-	rkeyEvent = /^key/,
-	rmouseEvent = /^(?:mouse|contextmenu)|click/,
-	rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
-	rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,
-	quickParse = function( selector ) {
-		var quick = rquickIs.exec( selector );
-		if ( quick ) {
-			//   0  1    2   3
-			// [ _, tag, id, class ]
-			quick[1] = ( quick[1] || "" ).toLowerCase();
-			quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" );
-		}
-		return quick;
-	},
-	quickIs = function( elem, m ) {
-		var attrs = elem.attributes || {};
-		return (
-			(!m[1] || elem.nodeName.toLowerCase() === m[1]) &&
-			(!m[2] || (attrs.id || {}).value === m[2]) &&
-			(!m[3] || m[3].test( (attrs[ "class" ] || {}).value ))
-		);
-	},
-	hoverHack = function( events ) {
-		return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
-	};
-
-/*
- * Helper functions for managing events -- not part of the public interface.
- * Props to Dean Edwards' addEvent library for many of the ideas.
- */
-jQuery.event = {
-
-	add: function( elem, types, handler, data, selector ) {
-
-		var elemData, eventHandle, events,
-			t, tns, type, namespaces, handleObj,
-			handleObjIn, quick, handlers, special;
-
-		// Don't attach events to noData or text/comment nodes (allow plain objects tho)
-		if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
-			return;
-		}
-
-		// Caller can pass in an object of custom data in lieu of the handler
-		if ( handler.handler ) {
-			handleObjIn = handler;
-			handler = handleObjIn.handler;
-		}
-
-		// Make sure that the handler has a unique ID, used to find/remove it later
-		if ( !handler.guid ) {
-			handler.guid = jQuery.guid++;
-		}
-
-		// Init the element's event structure and main handler, if this is the first
-		events = elemData.events;
-		if ( !events ) {
-			elemData.events = events = {};
-		}
-		eventHandle = elemData.handle;
-		if ( !eventHandle ) {
-			elemData.handle = eventHandle = function( e ) {
-				// Discard the second event of a jQuery.event.trigger() and
-				// when an event is called after a page has unloaded
-				return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
-					jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
-					undefined;
-			};
-			// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
-			eventHandle.elem = elem;
-		}
-
-		// Handle multiple events separated by a space
-		// jQuery(...).bind("mouseover mouseout", fn);
-		types = jQuery.trim( hoverHack(types) ).split( " " );
-		for ( t = 0; t < types.length; t++ ) {
-
-			tns = rtypenamespace.exec( types[t] ) || [];
-			type = tns[1];
-			namespaces = ( tns[2] || "" ).split( "." ).sort();
-
-			// If event changes its type, use the special event handlers for the changed type
-			special = jQuery.event.special[ type ] || {};
-
-			// If selector defined, determine special event api type, otherwise given type
-			type = ( selector ? special.delegateType : special.bindType ) || type;
-
-			// Update special based on newly reset type
-			special = jQuery.event.special[ type ] || {};
-
-			// handleObj is passed to all event handlers
-			handleObj = jQuery.extend({
-				type: type,
-				origType: tns[1],
-				data: data,
-				handler: handler,
-				guid: handler.guid,
-				selector: selector,
-				quick: quickParse( selector ),
-				namespace: namespaces.join(".")
-			}, handleObjIn );
-
-			// Init the event handler queue if we're the first
-			handlers = events[ type ];
-			if ( !handlers ) {
-				handlers = events[ type ] = [];
-				handlers.delegateCount = 0;
-
-				// Only use addEventListener/attachEvent if the special events handler returns false
-				if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
-					// Bind the global event handler to the element
-					if ( elem.addEventListener ) {
-						elem.addEventListener( type, eventHandle, false );
-
-					} else if ( elem.attachEvent ) {
-						elem.attachEvent( "on" + type, eventHandle );
-					}
-				}
-			}
-
-			if ( special.add ) {
-				special.add.call( elem, handleObj );
-
-				if ( !handleObj.handler.guid ) {
-					handleObj.handler.guid = handler.guid;
-				}
-			}
-
-			// Add to the element's handler list, delegates in front
-			if ( selector ) {
-				handlers.splice( handlers.delegateCount++, 0, handleObj );
-			} else {
-				handlers.push( handleObj );
-			}
-
-			// Keep track of which events have ever been used, for event optimization
-			jQuery.event.global[ type ] = true;
-		}
-
-		// Nullify elem to prevent memory leaks in IE
-		elem = null;
-	},
-
-	global: {},
-
-	// Detach an event or set of events from an element
-	remove: function( elem, types, handler, selector, mappedTypes ) {
-
-		var elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
-			t, tns, type, origType, namespaces, origCount,
-			j, events, special, handle, eventType, handleObj;
-
-		if ( !elemData || !(events = elemData.events) ) {
-			return;
-		}
-
-		// Once for each type.namespace in types; type may be omitted
-		types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
-		for ( t = 0; t < types.length; t++ ) {
-			tns = rtypenamespace.exec( types[t] ) || [];
-			type = origType = tns[1];
-			namespaces = tns[2];
-
-			// Unbind all events (on this namespace, if provided) for the element
-			if ( !type ) {
-				for ( type in events ) {
-					jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
-				}
-				continue;
-			}
-
-			special = jQuery.event.special[ type ] || {};
-			type = ( selector? special.delegateType : special.bindType ) || type;
-			eventType = events[ type ] || [];
-			origCount = eventType.length;
-			namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
-
-			// Remove matching events
-			for ( j = 0; j < eventType.length; j++ ) {
-				handleObj = eventType[ j ];
-
-				if ( ( mappedTypes || origType === handleObj.origType ) &&
-					 ( !handler || handler.guid === handleObj.guid ) &&
-					 ( !namespaces || namespaces.test( handleObj.namespace ) ) &&
-					 ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
-					eventType.splice( j--, 1 );
-
-					if ( handleObj.selector ) {
-						eventType.delegateCount--;
-					}
-					if ( special.remove ) {
-						special.remove.call( elem, handleObj );
-					}
-				}
-			}
-
-			// Remove generic event handler if we removed something and no more handlers exist
-			// (avoids potential for endless recursion during removal of special event handlers)
-			if ( eventType.length === 0 && origCount !== eventType.length ) {
-				if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
-					jQuery.removeEvent( elem, type, elemData.handle );
-				}
-
-				delete events[ type ];
-			}
-		}
-
-		// Remove the expando if it's no longer used
-		if ( jQuery.isEmptyObject( events ) ) {
-			handle = elemData.handle;
-			if ( handle ) {
-				handle.elem = null;
-			}
-
-			// removeData also checks for emptiness and clears the expando if empty
-			// so use it instead of delete
-			jQuery.removeData( elem, [ "events", "handle" ], true );
-		}
-	},
-
-	// Events that are safe to short-circuit if no handlers are attached.
-	// Native DOM events should not be added, they may have inline handlers.
-	customEvent: {
-		"getData": true,
-		"setData": true,
-		"changeData": true
-	},
-
-	trigger: function( event, data, elem, onlyHandlers ) {
-		// Don't do events on text and comment nodes
-		if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
-			return;
-		}
-
-		// Event object or event type
-		var type = event.type || event,
-			namespaces = [],
-			cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType;
-
-		// focus/blur morphs to focusin/out; ensure we're not firing them right now
-		if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
-			return;
-		}
-
-		if ( type.indexOf( "!" ) >= 0 ) {
-			// Exclusive events trigger only for the exact event (no namespaces)
-			type = type.slice(0, -1);
-			exclusive = true;
-		}
-
-		if ( type.indexOf( "." ) >= 0 ) {
-			// Namespaced trigger; create a regexp to match event type in handle()
-			namespaces = type.split(".");
-			type = namespaces.shift();
-			namespaces.sort();
-		}
-
-		if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
-			// No jQuery handlers for this event type, and it can't have inline handlers
-			return;
-		}
-
-		// Caller can pass in an Event, Object, or just an event type string
-		event = typeof event === "object" ?
-			// jQuery.Event object
-			event[ jQuery.expando ] ? event :
-			// Object literal
-			new jQuery.Event( type, event ) :
-			// Just the event type (string)
-			new jQuery.Event( type );
-
-		event.type = type;
-		event.isTrigger = true;
-		event.exclusive = exclusive;
-		event.namespace = namespaces.join( "." );
-		event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
-		ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
-
-		// Handle a global trigger
-		if ( !elem ) {
-
-			// TODO: Stop taunting the data cache; remove global events and always attach to document
-			cache = jQuery.cache;
-			for ( i in cache ) {
-				if ( cache[ i ].events && cache[ i ].events[ type ] ) {
-					jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
-				}
-			}
-			return;
-		}
-
-		// Clean up the event in case it is being reused
-		event.result = undefined;
-		if ( !event.target ) {
-			event.target = elem;
-		}
-
-		// Clone any incoming data and prepend the event, creating the handler arg list
-		data = data != null ? jQuery.makeArray( data ) : [];
-		data.unshift( event );
-
-		// Allow special events to draw outside the lines
-		special = jQuery.event.special[ type ] || {};
-		if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
-			return;
-		}
-
-		// Determine event propagation path in advance, per W3C events spec (#9951)
-		// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
-		eventPath = [[ elem, special.bindType || type ]];
-		if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
-
-			bubbleType = special.delegateType || type;
-			cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
-			old = null;
-			for ( ; cur; cur = cur.parentNode ) {
-				eventPath.push([ cur, bubbleType ]);
-				old = cur;
-			}
-
-			// Only add window if we got to document (e.g., not plain obj or detached DOM)
-			if ( old && old === elem.ownerDocument ) {
-				eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
-			}
-		}
-
-		// Fire handlers on the event path
-		for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
-
-			cur = eventPath[i][0];
-			event.type = eventPath[i][1];
-
-			handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
-			if ( handle ) {
-				handle.apply( cur, data );
-			}
-			// Note that this is a bare JS function and not a jQuery handler
-			handle = ontype && cur[ ontype ];
-			if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) {
-				event.preventDefault();
-			}
-		}
-		event.type = type;
-
-		// If nobody prevented the default action, do it now
-		if ( !onlyHandlers && !event.isDefaultPrevented() ) {
-
-			if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
-				!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
-
-				// Call a native DOM method on the target with the same name name as the event.
-				// Can't use an .isFunction() check here because IE6/7 fails that test.
-				// Don't do default actions on window, that's where global variables be (#6170)
-				// IE<9 dies on focus/blur to hidden element (#1486)
-				if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
-
-					// Don't re-trigger an onFOO event when we call its FOO() method
-					old = elem[ ontype ];
-
-					if ( old ) {
-						elem[ ontype ] = null;
-					}
-
-					// Prevent re-triggering of the same event, since we already bubbled it above
-					jQuery.event.triggered = type;
-					elem[ type ]();
-					jQuery.event.triggered = undefined;
-
-					if ( old ) {
-						elem[ ontype ] = old;
-					}
-				}
-			}
-		}
-
-		return event.result;
-	},
-
-	dispatch: function( event ) {
-
-		// Make a writable jQuery.Event from the native event object
-		event = jQuery.event.fix( event || window.event );
-
-		var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
-			delegateCount = handlers.delegateCount,
-			args = [].slice.call( arguments, 0 ),
-			run_all = !event.exclusive && !event.namespace,
-			handlerQueue = [],
-			i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related;
-
-		// Use the fix-ed jQuery.Event rather than the (read-only) native event
-		args[0] = event;
-		event.delegateTarget = this;
-
-		// Determine handlers that should run if there are delegated events
-		// Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861)
-		if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) {
-
-			// Pregenerate a single jQuery object for reuse with .is()
-			jqcur = jQuery(this);
-			jqcur.context = this.ownerDocument || this;
-
-			for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
-				selMatch = {};
-				matches = [];
-				jqcur[0] = cur;
-				for ( i = 0; i < delegateCount; i++ ) {
-					handleObj = handlers[ i ];
-					sel = handleObj.selector;
-
-					if ( selMatch[ sel ] === undefined ) {
-						selMatch[ sel ] = (
-							handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel )
-						);
-					}
-					if ( selMatch[ sel ] ) {
-						matches.push( handleObj );
-					}
-				}
-				if ( matches.length ) {
-					handlerQueue.push({ elem: cur, matches: matches });
-				}
-			}
-		}
-
-		// Add the remaining (directly-bound) handlers
-		if ( handlers.length > delegateCount ) {
-			handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
-		}
-
-		// Run delegates first; they may want to stop propagation beneath us
-		for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
-			matched = handlerQueue[ i ];
-			event.currentTarget = matched.elem;
-
-			for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
-				handleObj = matched.matches[ j ];
-
-				// Triggered event must either 1) be non-exclusive and have no namespace, or
-				// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
-				if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
-
-					event.data = handleObj.data;
-					event.handleObj = handleObj;
-
-					ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
-							.apply( matched.elem, args );
-
-					if ( ret !== undefined ) {
-						event.result = ret;
-						if ( ret === false ) {
-							event.preventDefault();
-							event.stopPropagation();
-						}
-					}
-				}
-			}
-		}
-
-		return event.result;
-	},
-
-	// Includes some event props shared by KeyEvent and MouseEvent
-	// *** attrChange attrName relatedNode srcElement  are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
-	props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
-
-	fixHooks: {},
-
-	keyHooks: {
-		props: "char charCode key keyCode".split(" "),
-		filter: function( event, original ) {
-
-			// Add which for key events
-			if ( event.which == null ) {
-				event.which = original.charCode != null ? original.charCode : original.keyCode;
-			}
-
-			return event;
-		}
-	},
-
-	mouseHooks: {
-		props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
-		filter: function( event, original ) {
-			var eventDoc, doc, body,
-				button = original.button,
-				fromElement = original.fromElement;
-
-			// Calculate pageX/Y if missing and clientX/Y available
-			if ( event.pageX == null && original.clientX != null ) {
-				eventDoc = event.target.ownerDocument || document;
-				doc = eventDoc.documentElement;
-				body = eventDoc.body;
-
-				event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
-				event.pageY = original.clientY + ( doc && doc.scrollTop  || body && body.scrollTop  || 0 ) - ( doc && doc.clientTop  || body && body.clientTop  || 0 );
-			}
-
-			// Add relatedTarget, if necessary
-			if ( !event.relatedTarget && fromElement ) {
-				event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
-			}
-
-			// Add which for click: 1 === left; 2 === middle; 3 === right
-			// Note: button is not normalized, so don't use it
-			if ( !event.which && button !== undefined ) {
-				event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
-			}
-
-			return event;
-		}
-	},
-
-	fix: function( event ) {
-		if ( event[ jQuery.expando ] ) {
-			return event;
-		}
-
-		// Create a writable copy of the event object and normalize some properties
-		var i, prop,
-			originalEvent = event,
-			fixHook = jQuery.event.fixHooks[ event.type ] || {},
-			copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
-
-		event = jQuery.Event( originalEvent );
-
-		for ( i = copy.length; i; ) {
-			prop = copy[ --i ];
-			event[ prop ] = originalEvent[ prop ];
-		}
-
-		// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
-		if ( !event.target ) {
-			event.target = originalEvent.srcElement || document;
-		}
-
-		// Target should not be a text node (#504, Safari)
-		if ( event.target.nodeType === 3 ) {
-			event.target = event.target.parentNode;
-		}
-
-		// For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8)
-		if ( event.metaKey === undefined ) {
-			event.metaKey = event.ctrlKey;
-		}
-
-		return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
-	},
-
-	special: {
-		ready: {
-			// Make sure the ready event is setup
-			setup: jQuery.bindReady
-		},
-
-		load: {
-			// Prevent triggered image.load events from bubbling to window.load
-			noBubble: true
-		},
-
-		focus: {
-			delegateType: "focusin"
-		},
-		blur: {
-			delegateType: "focusout"
-		},
-
-		beforeunload: {
-			setup: function( data, namespaces, eventHandle ) {
-				// We only want to do this special case on windows
-				if ( jQuery.isWindow( this ) ) {
-					this.onbeforeunload = eventHandle;
-				}
-			},
-
-			teardown: function( namespaces, eventHandle ) {
-				if ( this.onbeforeunload === eventHandle ) {
-					this.onbeforeunload = null;
-				}
-			}
-		}
-	},
-
-	simulate: function( type, elem, event, bubble ) {
-		// Piggyback on a donor event to simulate a different one.
-		// Fake originalEvent to avoid donor's stopPropagation, but if the
-		// simulated event prevents default then we do the same on the donor.
-		var e = jQuery.extend(
-			new jQuery.Event(),
-			event,
-			{ type: type,
-				isSimulated: true,
-				originalEvent: {}
-			}
-		);
-		if ( bubble ) {
-			jQuery.event.trigger( e, null, elem );
-		} else {
-			jQuery.event.dispatch.call( elem, e );
-		}
-		if ( e.isDefaultPrevented() ) {
-			event.preventDefault();
-		}
-	}
-};
+    if (!jQuery.support.checkOn) {
+        jQuery.each([ "radio", "checkbox" ], function () {
+            jQuery.valHooks[ this ] = {
+                get: function (elem) {
+                    // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
+                    return elem.getAttribute("value") === null ? "on" : elem.value;
+                }
+            };
+        });
+    }
+    jQuery.each([ "radio", "checkbox" ], function () {
+        jQuery.valHooks[ this ] = jQuery.extend(jQuery.valHooks[ this ], {
+            set: function (elem, value) {
+                if (jQuery.isArray(value)) {
+                    return ( elem.checked = jQuery.inArray(jQuery(elem).val(), value) >= 0 );
+                }
+            }
+        });
+    });
+
+
+    var rformElems = /^(?:textarea|input|select)$/i,
+        rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/,
+        rhoverHack = /\bhover(\.\S+)?\b/,
+        rkeyEvent = /^key/,
+        rmouseEvent = /^(?:mouse|contextmenu)|click/,
+        rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
+        rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,
+        quickParse = function (selector) {
+            var quick = rquickIs.exec(selector);
+            if (quick) {
+                //   0  1    2   3
+                // [ _, tag, id, class ]
+                quick[1] = ( quick[1] || "" ).toLowerCase();
+                quick[3] = quick[3] && new RegExp("(?:^|\\s)" + quick[3] + "(?:\\s|$)");
+            }
+            return quick;
+        },
+        quickIs = function (elem, m) {
+            var attrs = elem.attributes || {};
+            return (
+                (!m[1] || elem.nodeName.toLowerCase() === m[1]) &&
+                    (!m[2] || (attrs.id || {}).value === m[2]) &&
+                    (!m[3] || m[3].test((attrs[ "class" ] || {}).value))
+                );
+        },
+        hoverHack = function (events) {
+            return jQuery.event.special.hover ? events : events.replace(rhoverHack, "mouseenter$1 mouseleave$1");
+        };
+
+    /*
+     * Helper functions for managing events -- not part of the public interface.
+     * Props to Dean Edwards' addEvent library for many of the ideas.
+     */
+    jQuery.event = {
+
+        add: function (elem, types, handler, data, selector) {
+
+            var elemData, eventHandle, events,
+                t, tns, type, namespaces, handleObj,
+                handleObjIn, quick, handlers, special;
+
+            // Don't attach events to noData or text/comment nodes (allow plain objects tho)
+            if (elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data(elem))) {
+                return;
+            }
+
+            // Caller can pass in an object of custom data in lieu of the handler
+            if (handler.handler) {
+                handleObjIn = handler;
+                handler = handleObjIn.handler;
+            }
+
+            // Make sure that the handler has a unique ID, used to find/remove it later
+            if (!handler.guid) {
+                handler.guid = jQuery.guid++;
+            }
+
+            // Init the element's event structure and main handler, if this is the first
+            events = elemData.events;
+            if (!events) {
+                elemData.events = events = {};
+            }
+            eventHandle = elemData.handle;
+            if (!eventHandle) {
+                elemData.handle = eventHandle = function (e) {
+                    // Discard the second event of a jQuery.event.trigger() and
+                    // when an event is called after a page has unloaded
+                    return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
+                        jQuery.event.dispatch.apply(eventHandle.elem, arguments) :
+                        undefined;
+                };
+                // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
+                eventHandle.elem = elem;
+            }
+
+            // Handle multiple events separated by a space
+            // jQuery(...).bind("mouseover mouseout", fn);
+            types = jQuery.trim(hoverHack(types)).split(" ");
+            for (t = 0; t < types.length; t++) {
+
+                tns = rtypenamespace.exec(types[t]) || [];
+                type = tns[1];
+                namespaces = ( tns[2] || "" ).split(".").sort();
+
+                // If event changes its type, use the special event handlers for the changed type
+                special = jQuery.event.special[ type ] || {};
+
+                // If selector defined, determine special event api type, otherwise given type
+                type = ( selector ? special.delegateType : special.bindType ) || type;
+
+                // Update special based on newly reset type
+                special = jQuery.event.special[ type ] || {};
+
+                // handleObj is passed to all event handlers
+                handleObj = jQuery.extend({
+                    type: type,
+                    origType: tns[1],
+                    data: data,
+                    handler: handler,
+                    guid: handler.guid,
+                    selector: selector,
+                    quick: quickParse(selector),
+                    namespace: namespaces.join(".")
+                }, handleObjIn);
+
+                // Init the event handler queue if we're the first
+                handlers = events[ type ];
+                if (!handlers) {
+                    handlers = events[ type ] = [];
+                    handlers.delegateCount = 0;
+
+                    // Only use addEventListener/attachEvent if the special events handler returns false
+                    if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) {
+                        // Bind the global event handler to the element
+                        if (elem.addEventListener) {
+                            elem.addEventListener(type, eventHandle, false);
+
+                        } else if (elem.attachEvent) {
+                            elem.attachEvent("on" + type, eventHandle);
+                        }
+                    }
+                }
+
+                if (special.add) {
+                    special.add.call(elem, handleObj);
+
+                    if (!handleObj.handler.guid) {
+                        handleObj.handler.guid = handler.guid;
+                    }
+                }
+
+                // Add to the element's handler list, delegates in front
+                if (selector) {
+                    handlers.splice(handlers.delegateCount++, 0, handleObj);
+                } else {
+                    handlers.push(handleObj);
+                }
+
+                // Keep track of which events have ever been used, for event optimization
+                jQuery.event.global[ type ] = true;
+            }
+
+            // Nullify elem to prevent memory leaks in IE
+            elem = null;
+        },
+
+        global: {},
+
+        // Detach an event or set of events from an element
+        remove: function (elem, types, handler, selector, mappedTypes) {
+
+            var elemData = jQuery.hasData(elem) && jQuery._data(elem),
+                t, tns, type, origType, namespaces, origCount,
+                j, events, special, handle, eventType, handleObj;
+
+            if (!elemData || !(events = elemData.events)) {
+                return;
+            }
+
+            // Once for each type.namespace in types; type may be omitted
+            types = jQuery.trim(hoverHack(types || "")).split(" ");
+            for (t = 0; t < types.length; t++) {
+                tns = rtypenamespace.exec(types[t]) || [];
+                type = origType = tns[1];
+                namespaces = tns[2];
+
+                // Unbind all events (on this namespace, if provided) for the element
+                if (!type) {
+                    for (type in events) {
+                        jQuery.event.remove(elem, type + types[ t ], handler, selector, true);
+                    }
+                    continue;
+                }
+
+                special = jQuery.event.special[ type ] || {};
+                type = ( selector ? special.delegateType : special.bindType ) || type;
+                eventType = events[ type ] || [];
+                origCount = eventType.length;
+                namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
+
+                // Remove matching events
+                for (j = 0; j < eventType.length; j++) {
+                    handleObj = eventType[ j ];
+
+                    if (( mappedTypes || origType === handleObj.origType ) &&
+                        ( !handler || handler.guid === handleObj.guid ) &&
+                        ( !namespaces || namespaces.test(handleObj.namespace) ) &&
+                        ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector )) {
+                        eventType.splice(j--, 1);
+
+                        if (handleObj.selector) {
+                            eventType.delegateCount--;
+                        }
+                        if (special.remove) {
+                            special.remove.call(elem, handleObj);
+                        }
+                    }
+                }
+
+                // Remove generic event handler if we removed something and no more handlers exist
+                // (avoids potential for endless recursion during removal of special event handlers)
+                if (eventType.length === 0 && origCount !== eventType.length) {
+                    if (!special.teardown || special.teardown.call(elem, namespaces) === false) {
+                        jQuery.removeEvent(elem, type, elemData.handle);
+                    }
+
+                    delete events[ type ];
+                }
+            }
+
+            // Remove the expando if it's no longer used
+            if (jQuery.isEmptyObject(events)) {
+                handle = elemData.handle;
+                if (handle) {
+                    handle.elem = null;
+                }
+
+                // removeData also checks for emptiness and clears the expando if empty
+                // so use it instead of delete
+                jQuery.removeData(elem, [ "events", "handle" ], true);
+            }
+        },
+
+        // Events that are safe to short-circuit if no handlers are attached.
+        // Native DOM events should not be added, they may have inline handlers.
+        customEvent: {
+            "getData": true,
+            "setData": true,
+            "changeData": true
+        },
+
+        trigger: function (event, data, elem, onlyHandlers) {
+            // Don't do events on text and comment nodes
+            if (elem && (elem.nodeType === 3 || elem.nodeType === 8)) {
+                return;
+            }
+
+            // Event object or event type
+            var type = event.type || event,
+                namespaces = [],
+                cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType;
+
+            // focus/blur morphs to focusin/out; ensure we're not firing them right now
+            if (rfocusMorph.test(type + jQuery.event.triggered)) {
+                return;
+            }
+
+            if (type.indexOf("!") >= 0) {
+                // Exclusive events trigger only for the exact event (no namespaces)
+                type = type.slice(0, -1);
+                exclusive = true;
+            }
+
+            if (type.indexOf(".") >= 0) {
+                // Namespaced trigger; create a regexp to match event type in handle()
+                namespaces = type.split(".");
+                type = namespaces.shift();
+                namespaces.sort();
+            }
+
+            if ((!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ]) {
+                // No jQuery handlers for this event type, and it can't have inline handlers
+                return;
+            }
+
+            // Caller can pass in an Event, Object, or just an event type string
+            event = typeof event === "object" ?
+                // jQuery.Event object
+                event[ jQuery.expando ] ? event :
+                    // Object literal
+                    new jQuery.Event(type, event) :
+                // Just the event type (string)
+                new jQuery.Event(type);
+
+            event.type = type;
+            event.isTrigger = true;
+            event.exclusive = exclusive;
+            event.namespace = namespaces.join(".");
+            event.namespace_re = event.namespace ? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
+            ontype = type.indexOf(":") < 0 ? "on" + type : "";
+
+            // Handle a global trigger
+            if (!elem) {
+
+                // TODO: Stop taunting the data cache; remove global events and always attach to document
+                cache = jQuery.cache;
+                for (i in cache) {
+                    if (cache[ i ].events && cache[ i ].events[ type ]) {
+                        jQuery.event.trigger(event, data, cache[ i ].handle.elem, true);
+                    }
+                }
+                return;
+            }
+
+            // Clean up the event in case it is being reused
+            event.result = undefined;
+            if (!event.target) {
+                event.target = elem;
+            }
+
+            // Clone any incoming data and prepend the event, creating the handler arg list
+            data = data != null ? jQuery.makeArray(data) : [];
+            data.unshift(event);
+
+            // Allow special events to draw outside the lines
+            special = jQuery.event.special[ type ] || {};
+            if (special.trigger && special.trigger.apply(elem, data) === false) {
+                return;
+            }
+
+            // Determine event propagation path in advance, per W3C events spec (#9951)
+            // Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
+            eventPath = [
+                [ elem, special.bindType || type ]
+            ];
+            if (!onlyHandlers && !special.noBubble && !jQuery.isWindow(elem)) {
+
+                bubbleType = special.delegateType || type;
+                cur = rfocusMorph.test(bubbleType + type) ? elem : elem.parentNode;
+                old = null;
+                for (; cur; cur = cur.parentNode) {
+                    eventPath.push([ cur, bubbleType ]);
+                    old = cur;
+                }
+
+                // Only add window if we got to document (e.g., not plain obj or detached DOM)
+                if (old && old === elem.ownerDocument) {
+                    eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
+                }
+            }
+
+            // Fire handlers on the event path
+            for (i = 0; i < eventPath.length && !event.isPropagationStopped(); i++) {
+
+                cur = eventPath[i][0];
+                event.type = eventPath[i][1];
+
+                handle = ( jQuery._data(cur, "events") || {} )[ event.type ] && jQuery._data(cur, "handle");
+                if (handle) {
+                    handle.apply(cur, data);
+                }
+                // Note that this is a bare JS function and not a jQuery handler
+                handle = ontype && cur[ ontype ];
+                if (handle && jQuery.acceptData(cur) && handle.apply(cur, data) === false) {
+                    event.preventDefault();
+                }
+            }
+            event.type = type;
+
+            // If nobody prevented the default action, do it now
+            if (!onlyHandlers && !event.isDefaultPrevented()) {
+
+                if ((!special._default || special._default.apply(elem.ownerDocument, data) === false) && !(type === "click" && jQuery.nodeName(elem, "a")) && jQuery.acceptData(elem)) {
+
+                    // Call a native DOM method on the target with the same name name as the event.
+                    // Can't use an .isFunction() check here because IE6/7 fails that test.
+                    // Don't do default actions on window, that's where global variables be (#6170)
+                    // IE<9 dies on focus/blur to hidden element (#1486)
+                    if (ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow(elem)) {
+
+                        // Don't re-trigger an onFOO event when we call its FOO() method
+                        old = elem[ ontype ];
+
+                        if (old) {
+                            elem[ ontype ] = null;
+                        }
+
+                        // Prevent re-triggering of the same event, since we already bubbled it above
+                        jQuery.event.triggered = type;
+                        elem[ type ]();
+                        jQuery.event.triggered = undefined;
+
+                        if (old) {
+                            elem[ ontype ] = old;
+                        }
+                    }
+                }
+            }
+
+            return event.result;
+        },
+
+        dispatch: function (event) {
+
+            // Make a writable jQuery.Event from the native event object
+            event = jQuery.event.fix(event || window.event);
+
+            var handlers = ( (jQuery._data(this, "events") || {} )[ event.type ] || []),
+                delegateCount = handlers.delegateCount,
+                args = [].slice.call(arguments, 0),
+                run_all = !event.exclusive && !event.namespace,
+                handlerQueue = [],
+                i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related;
+
+            // Use the fix-ed jQuery.Event rather than the (read-only) native event
+            args[0] = event;
+            event.delegateTarget = this;
+
+            // Determine handlers that should run if there are delegated events
+            // Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861)
+            if (delegateCount && !event.target.disabled && !(event.button && event.type === "click")) {
+
+                // Pregenerate a single jQuery object for reuse with .is()
+                jqcur = jQuery(this);
+                jqcur.context = this.ownerDocument || this;
+
+                for (cur = event.target; cur != this; cur = cur.parentNode || this) {
+                    selMatch = {};
+                    matches = [];
+                    jqcur[0] = cur;
+                    for (i = 0; i < delegateCount; i++) {
+                        handleObj = handlers[ i ];
+                        sel = handleObj.selector;
+
+                        if (selMatch[ sel ] === undefined) {
+                            selMatch[ sel ] = (
+                                handleObj.quick ? quickIs(cur, handleObj.quick) : jqcur.is(sel)
+                                );
+                        }
+                        if (selMatch[ sel ]) {
+                            matches.push(handleObj);
+                        }
+                    }
+                    if (matches.length) {
+                        handlerQueue.push({ elem: cur, matches: matches });
+                    }
+                }
+            }
+
+            // Add the remaining (directly-bound) handlers
+            if (handlers.length > delegateCount) {
+                handlerQueue.push({ elem: this, matches: handlers.slice(delegateCount) });
+            }
+
+            // Run delegates first; they may want to stop propagation beneath us
+            for (i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++) {
+                matched = handlerQueue[ i ];
+                event.currentTarget = matched.elem;
+
+                for (j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++) {
+                    handleObj = matched.matches[ j ];
+
+                    // Triggered event must either 1) be non-exclusive and have no namespace, or
+                    // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
+                    if (run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test(handleObj.namespace)) {
+
+                        event.data = handleObj.data;
+                        event.handleObj = handleObj;
+
+                        ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
+                            .apply(matched.elem, args);
+
+                        if (ret !== undefined) {
+                            event.result = ret;
+                            if (ret === false) {
+                                event.preventDefault();
+                                event.stopPropagation();
+                            }
+                        }
+                    }
+                }
+            }
+
+            return event.result;
+        },
+
+        // Includes some event props shared by KeyEvent and MouseEvent
+        // *** attrChange attrName relatedNode srcElement  are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
+        props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
+
+        fixHooks: {},
+
+        keyHooks: {
+            props: "char charCode key keyCode".split(" "),
+            filter: function (event, original) {
+
+                // Add which for key events
+                if (event.which == null) {
+                    event.which = original.charCode != null ? original.charCode : original.keyCode;
+                }
+
+                return event;
+            }
+        },
+
+        mouseHooks: {
+            props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
+            filter: function (event, original) {
+                var eventDoc, doc, body,
+                    button = original.button,
+                    fromElement = original.fromElement;
+
+                // Calculate pageX/Y if missing and clientX/Y available
+                if (event.pageX == null && original.clientX != null) {
+                    eventDoc = event.target.ownerDocument || document;
+                    doc = eventDoc.documentElement;
+                    body = eventDoc.body;
+
+                    event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
+                    event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
+                }
+
+                // Add relatedTarget, if necessary
+                if (!event.relatedTarget && fromElement) {
+                    event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
+                }
+
+                // Add which for click: 1 === left; 2 === middle; 3 === right
+                // Note: button is not normalized, so don't use it
+                if (!event.which && button !== undefined) {
+                    event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
+                }
+
+                return event;
+            }
+        },
+
+        fix: function (event) {
+            if (event[ jQuery.expando ]) {
+                return event;
+            }
+
+            // Create a writable copy of the event object and normalize some properties
+            var i, prop,
+                originalEvent = event,
+                fixHook = jQuery.event.fixHooks[ event.type ] || {},
+                copy = fixHook.props ? this.props.concat(fixHook.props) : this.props;
+
+            event = jQuery.Event(originalEvent);
+
+            for (i = copy.length; i;) {
+                prop = copy[ --i ];
+                event[ prop ] = originalEvent[ prop ];
+            }
+
+            // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
+            if (!event.target) {
+                event.target = originalEvent.srcElement || document;
+            }
+
+            // Target should not be a text node (#504, Safari)
+            if (event.target.nodeType === 3) {
+                event.target = event.target.parentNode;
+            }
+
+            // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8)
+            if (event.metaKey === undefined) {
+                event.metaKey = event.ctrlKey;
+            }
+
+            return fixHook.filter ? fixHook.filter(event, originalEvent) : event;
+        },
+
+        special: {
+            ready: {
+                // Make sure the ready event is setup
+                setup: jQuery.bindReady
+            },
+
+            load: {
+                // Prevent triggered image.load events from bubbling to window.load
+                noBubble: true
+            },
+
+            focus: {
+                delegateType: "focusin"
+            },
+            blur: {
+                delegateType: "focusout"
+            },
+
+            beforeunload: {
+                setup: function (data, namespaces, eventHandle) {
+                    // We only want to do this special case on windows
+                    if (jQuery.isWindow(this)) {
+                        this.onbeforeunload = eventHandle;
+                    }
+                },
+
+                teardown: function (namespaces, eventHandle) {
+                    if (this.onbeforeunload === eventHandle) {
+                        this.onbeforeunload = null;
+                    }
+                }
+            }
+        },
+
+        simulate: function (type, elem, event, bubble) {
+            // Piggyback on a donor event to simulate a different one.
+            // Fake originalEvent to avoid donor's stopPropagation, but if the
+            // simulated event prevents default then we do the same on the donor.
+            var e = jQuery.extend(
+                new jQuery.Event(),
+                event,
+                { type: type,
+                    isSimulated: true,
+                    originalEvent: {}
+                }
+            );
+            if (bubble) {
+                jQuery.event.trigger(e, null, elem);
+            } else {
+                jQuery.event.dispatch.call(elem, e);
+            }
+            if (e.isDefaultPrevented()) {
+                event.preventDefault();
+            }
+        }
+    };
 
 // Some plugins are using, but it's undocumented/deprecated and will be removed.
 // The 1.7 special event interface should provide all the hooks needed now.
-jQuery.event.handle = jQuery.event.dispatch;
-
-jQuery.removeEvent = document.removeEventListener ?
-	function( elem, type, handle ) {
-		if ( elem.removeEventListener ) {
-			elem.removeEventListener( type, handle, false );
-		}
-	} :
-	function( elem, type, handle ) {
-		if ( elem.detachEvent ) {
-			elem.detachEvent( "on" + type, handle );
-		}
-	};
-
-jQuery.Event = function( src, props ) {
-	// Allow instantiation without the 'new' keyword
-	if ( !(this instanceof jQuery.Event) ) {
-		return new jQuery.Event( src, props );
-	}
-
-	// Event object
-	if ( src && src.type ) {
-		this.originalEvent = src;
-		this.type = src.type;
-
-		// Events bubbling up the document may have been marked as prevented
-		// by a handler lower down the tree; reflect the correct value.
-		this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
-			src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
-
-	// Event type
-	} else {
-		this.type = src;
-	}
-
-	// Put explicitly provided properties onto the event object
-	if ( props ) {
-		jQuery.extend( this, props );
-	}
-
-	// Create a timestamp if incoming event doesn't have one
-	this.timeStamp = src && src.timeStamp || jQuery.now();
-
-	// Mark it as fixed
-	this[ jQuery.expando ] = true;
-};
-
-function returnFalse() {
-	return false;
-}
-function returnTrue() {
-	return true;
-}
+    jQuery.event.handle = jQuery.event.dispatch;
+
+    jQuery.removeEvent = document.removeEventListener ?
+        function (elem, type, handle) {
+            if (elem.removeEventListener) {
+                elem.removeEventListener(type, handle, false);
+            }
+        } :
+        function (elem, type, handle) {
+            if (elem.detachEvent) {
+                elem.detachEvent("on" + type, handle);
+            }
+        };
+
+    jQuery.Event = function (src, props) {
+        // Allow instantiation without the 'new' keyword
+        if (!(this instanceof jQuery.Event)) {
+            return new jQuery.Event(src, props);
+        }
+
+        // Event object
+        if (src && src.type) {
+            this.originalEvent = src;
+            this.type = src.type;
+
+            // Events bubbling up the document may have been marked as prevented
+            // by a handler lower down the tree; reflect the correct value.
+            this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
+                src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
+
+            // Event type
+        } else {
+            this.type = src;
+        }
+
+        // Put explicitly provided properties onto the event object
+        if (props) {
+            jQuery.extend(this, props);
+        }
+
+        // Create a timestamp if incoming event doesn't have one
+        this.timeStamp = src && src.timeStamp || jQuery.now();
+
+        // Mark it as fixed
+        this[ jQuery.expando ] = true;
+    };
+
+    function returnFalse() {
+        return false;
+    }
+
+    function returnTrue() {
+        return true;
+    }
 
 // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
 // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
-jQuery.Event.prototype = {
-	preventDefault: function() {
-		this.isDefaultPrevented = returnTrue;
-
-		var e = this.originalEvent;
-		if ( !e ) {
-			return;
-		}
-
-		// if preventDefault exists run it on the original event
-		if ( e.preventDefault ) {
-			e.preventDefault();
-
-		// otherwise set the returnValue property of the original event to false (IE)
-		} else {
-			e.returnValue = false;
-		}
-	},
-	stopPropagation: function() {
-		this.isPropagationStopped = returnTrue;
-
-		var e = this.originalEvent;
-		if ( !e ) {
-			return;
-		}
-		// if stopPropagation exists run it on the original event
-		if ( e.stopPropagation ) {
-			e.stopPropagation();
-		}
-		// otherwise set the cancelBubble property of the original event to true (IE)
-		e.cancelBubble = true;
-	},
-	stopImmediatePropagation: function() {
-		this.isImmediatePropagationStopped = returnTrue;
-		this.stopPropagation();
-	},
-	isDefaultPrevented: returnFalse,
-	isPropagationStopped: returnFalse,
-	isImmediatePropagationStopped: returnFalse
-};
+    jQuery.Event.prototype = {
+        preventDefault: function () {
+            this.isDefaultPrevented = returnTrue;
+
+            var e = this.originalEvent;
+            if (!e) {
+                return;
+            }
+
+            // if preventDefault exists run it on the original event
+            if (e.preventDefault) {
+                e.preventDefault();
+
+                // otherwise set the returnValue property of the original event to false (IE)
+            } else {
+                e.returnValue = false;
+            }
+        },
+        stopPropagation: function () {
+            this.isPropagationStopped = returnTrue;
+
+            var e = this.originalEvent;
+            if (!e) {
+                return;
+            }
+            // if stopPropagation exists run it on the original event
+            if (e.stopPropagation) {
+                e.stopPropagation();
+            }
+            // otherwise set the cancelBubble property of the original event to true (IE)
+            e.cancelBubble = true;
+        },
+        stopImmediatePropagation: function () {
+            this.isImmediatePropagationStopped = returnTrue;
+            this.stopPropagation();
+        },
+        isDefaultPrevented: returnFalse,
+        isPropagationStopped: returnFalse,
+        isImmediatePropagationStopped: returnFalse
+    };
 
 // Create mouseenter/leave events using mouseover/out and event-time checks
-jQuery.each({
-	mouseenter: "mouseover",
-	mouseleave: "mouseout"
-}, function( orig, fix ) {
-	jQuery.event.special[ orig ] = {
-		delegateType: fix,
-		bindType: fix,
-
-		handle: function( event ) {
-			var target = this,
-				related = event.relatedTarget,
-				handleObj = event.handleObj,
-				selector = handleObj.selector,
-				ret;
-
-			// For mousenter/leave call the handler if related is outside the target.
-			// NB: No relatedTarget if the mouse left/entered the browser window
-			if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
-				event.type = handleObj.origType;
-				ret = handleObj.handler.apply( this, arguments );
-				event.type = fix;
-			}
-			return ret;
-		}
-	};
-});
+    jQuery.each({
+        mouseenter: "mouseover",
+        mouseleave: "mouseout"
+    }, function (orig, fix) {
+        jQuery.event.special[ orig ] = {
+            delegateType: fix,
+            bindType: fix,
+
+            handle: function (event) {
+                var target = this,
+                    related = event.relatedTarget,
+                    handleObj = event.handleObj,
+                    selector = handleObj.selector,
+                    ret;
+
+                // For mousenter/leave call the handler if related is outside the target.
+                // NB: No relatedTarget if the mouse left/entered the browser window
+                if (!related || (related !== target && !jQuery.contains(target, related))) {
+                    event.type = handleObj.origType;
+                    ret = handleObj.handler.apply(this, arguments);
+                    event.type = fix;
+                }
+                return ret;
+            }
+        };
+    });
 
 // IE submit delegation
-if ( !jQuery.support.submitBubbles ) {
-
-	jQuery.event.special.submit = {
-		setup: function() {
-			// Only need this for delegated form submit events
-			if ( jQuery.nodeName( this, "form" ) ) {
-				return false;
-			}
-
-			// Lazy-add a submit handler when a descendant form may potentially be submitted
-			jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
-				// Node name check avoids a VML-related crash in IE (#9807)
-				var elem = e.target,
-					form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
-				if ( form && !form._submit_attached ) {
-					jQuery.event.add( form, "submit._submit", function( event ) {
-						// If form was submitted by the user, bubble the event up the tree
-						if ( this.parentNode && !event.isTrigger ) {
-							jQuery.event.simulate( "submit", this.parentNode, event, true );
-						}
-					});
-					form._submit_attached = true;
-				}
-			});
-			// return undefined since we don't need an event listener
-		},
-
-		teardown: function() {
-			// Only need this for delegated form submit events
-			if ( jQuery.nodeName( this, "form" ) ) {
-				return false;
-			}
-
-			// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
-			jQuery.event.remove( this, "._submit" );
-		}
-	};
-}
+    if (!jQuery.support.submitBubbles) {
+
+        jQuery.event.special.submit = {
+            setup: function () {
+                // Only need this for delegated form submit events
+                if (jQuery.nodeName(this, "form")) {
+                    return false;
+                }
+
+                // Lazy-add a submit handler when a descendant form may potentially be submitted
+                jQuery.event.add(this, "click._submit keypress._submit", function (e) {
+                    // Node name check avoids a VML-related crash in IE (#9807)
+                    var elem = e.target,
+                        form = jQuery.nodeName(elem, "input") || jQuery.nodeName(elem, "button") ? elem.form : undefined;
+                    if (form && !form._submit_attached) {
+                        jQuery.event.add(form, "submit._submit", function (event) {
+                            // If form was submitted by the user, bubble the event up the tree
+                            if (this.parentNode && !event.isTrigger) {
+                                jQuery.event.simulate("submit", this.parentNode, event, true);
+                            }
+                        });
+                        form._submit_attached = true;
+                    }
+                });
+                // return undefined since we don't need an event listener
+            },
+
+            teardown: function () {
+                // Only need this for delegated form submit events
+                if (jQuery.nodeName(this, "form")) {
+                    return false;
+                }
+
+                // Remove delegated handlers; cleanData eventually reaps submit handlers attached above
+                jQuery.event.remove(this, "._submit");
+            }
+        };
+    }
 
 // IE change delegation and checkbox/radio fix
-if ( !jQuery.support.changeBubbles ) {
-
-	jQuery.event.special.change = {
-
-		setup: function() {
-
-			if ( rformElems.test( this.nodeName ) ) {
-				// IE doesn't fire change on a check/radio until blur; trigger it on click
-				// after a propertychange. Eat the blur-change in special.change.handle.
-				// This still fires onchange a second time for check/radio after blur.
-				if ( this.type === "checkbox" || this.type === "radio" ) {
-					jQuery.event.add( this, "propertychange._change", function( event ) {
-						if ( event.originalEvent.propertyName === "checked" ) {
-							this._just_changed = true;
-						}
-					});
-					jQuery.event.add( this, "click._change", function( event ) {
-						if ( this._just_changed && !event.isTrigger ) {
-							this._just_changed = false;
-							jQuery.event.simulate( "change", this, event, true );
-						}
-					});
-				}
-				return false;
-			}
-			// Delegated event; lazy-add a change handler on descendant inputs
-			jQuery.event.add( this, "beforeactivate._change", function( e ) {
-				var elem = e.target;
-
-				if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) {
-					jQuery.event.add( elem, "change._change", function( event ) {
-						if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
-							jQuery.event.simulate( "change", this.parentNode, event, true );
-						}
-					});
-					elem._change_attached = true;
-				}
-			});
-		},
-
-		handle: function( event ) {
-			var elem = event.target;
-
-			// Swallow native change events from checkbox/radio, we already triggered them above
-			if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
-				return event.handleObj.handler.apply( this, arguments );
-			}
-		},
-
-		teardown: function() {
-			jQuery.event.remove( this, "._change" );
-
-			return rformElems.test( this.nodeName );
-		}
-	};
-}
+    if (!jQuery.support.changeBubbles) {
+
+        jQuery.event.special.change = {
+
+            setup: function () {
+
+                if (rformElems.test(this.nodeName)) {
+                    // IE doesn't fire change on a check/radio until blur; trigger it on click
+                    // after a propertychange. Eat the blur-change in special.change.handle.
+                    // This still fires onchange a second time for check/radio after blur.
+                    if (this.type === "checkbox" || this.type === "radio") {
+                        jQuery.event.add(this, "propertychange._change", function (event) {
+                            if (event.originalEvent.propertyName === "checked") {
+                                this._just_changed = true;
+                            }
+                        });
+                        jQuery.event.add(this, "click._change", function (event) {
+                            if (this._just_changed && !event.isTrigger) {
+                                this._just_changed = false;
+                                jQuery.event.simulate("change", this, event, true);
+                            }
+                        });
+                    }
+                    return false;
+                }
+                // Delegated event; lazy-add a change handler on descendant inputs
+                jQuery.event.add(this, "beforeactivate._change", function (e) {
+                    var elem = e.target;
+
+                    if (rformElems.test(elem.nodeName) && !elem._change_attached) {
+                        jQuery.event.add(elem, "change._change", function (event) {
+                            if (this.parentNode && !event.isSimulated && !event.isTrigger) {
+                                jQuery.event.simulate("change", this.parentNode, event, true);
+                            }
+                        });
+                        elem._change_attached = true;
+                    }
+                });
+            },
+
+            handle: function (event) {
+                var elem = event.target;
+
+                // Swallow native change events from checkbox/radio, we already triggered them above
+                if (this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox")) {
+                    return event.handleObj.handler.apply(this, arguments);
+                }
+            },
+
+            teardown: function () {
+                jQuery.event.remove(this, "._change");
+
+                return rformElems.test(this.nodeName);
+            }
+        };
+    }
 
 // Create "bubbling" focus and blur events
-if ( !jQuery.support.focusinBubbles ) {
-	jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
-
-		// Attach a single capturing handler while someone wants focusin/focusout
-		var attaches = 0,
-			handler = function( event ) {
-				jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
-			};
-
-		jQuery.event.special[ fix ] = {
-			setup: function() {
-				if ( attaches++ === 0 ) {
-					document.addEventListener( orig, handler, true );
-				}
-			},
-			teardown: function() {
-				if ( --attaches === 0 ) {
-					document.removeEventListener( orig, handler, true );
-				}
-			}
-		};
-	});
-}
-
-jQuery.fn.extend({
-
-	on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
-		var origFn, type;
-
-		// Types can be a map of types/handlers
-		if ( typeof types === "object" ) {
-			// ( types-Object, selector, data )
-			if ( typeof selector !== "string" ) {
-				// ( types-Object, data )
-				data = selector;
-				selector = undefined;
-			}
-			for ( type in types ) {
-				this.on( type, selector, data, types[ type ], one );
-			}
-			return this;
-		}
-
-		if ( data == null && fn == null ) {
-			// ( types, fn )
-			fn = selector;
-			data = selector = undefined;
-		} else if ( fn == null ) {
-			if ( typeof selector === "string" ) {
-				// ( types, selector, fn )
-				fn = data;
-				data = undefined;
-			} else {
-				// ( types, data, fn )
-				fn = data;
-				data = selector;
-				selector = undefined;
-			}
-		}
-		if ( fn === false ) {
-			fn = returnFalse;
-		} else if ( !fn ) {
-			return this;
-		}
-
-		if ( one === 1 ) {
-			origFn = fn;
-			fn = function( event ) {
-				// Can use an empty set, since event contains the info
-				jQuery().off( event );
-				return origFn.apply( this, arguments );
-			};
-			// Use same guid so caller can remove using origFn
-			fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
-		}
-		return this.each( function() {
-			jQuery.event.add( this, types, fn, data, selector );
-		});
-	},
-	one: function( types, selector, data, fn ) {
-		return this.on.call( this, types, selector, data, fn, 1 );
-	},
-	off: function( types, selector, fn ) {
-		if ( types && types.preventDefault && types.handleObj ) {
-			// ( event )  dispatched jQuery.Event
-			var handleObj = types.handleObj;
-			jQuery( types.delegateTarget ).off(
-				handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type,
-				handleObj.selector,
-				handleObj.handler
-			);
-			return this;
-		}
-		if ( typeof types === "object" ) {
-			// ( types-object [, selector] )
-			for ( var type in types ) {
-				this.off( type, selector, types[ type ] );
-			}
-			return this;
-		}
-		if ( selector === false || typeof selector === "function" ) {
-			// ( types [, fn] )
-			fn = selector;
-			selector = undefined;
-		}
-		if ( fn === false ) {
-			fn = returnFalse;
-		}
-		return this.each(function() {
-			jQuery.event.remove( this, types, fn, selector );
-		});
-	},
-
-	bind: function( types, data, fn ) {
-		return this.on( types, null, data, fn );
-	},
-	unbind: function( types, fn ) {
-		return this.off( types, null, fn );
-	},
-
-	live: function( types, data, fn ) {
-		jQuery( this.context ).on( types, this.selector, data, fn );
-		return this;
-	},
-	die: function( types, fn ) {
-		jQuery( this.context ).off( types, this.selector || "**", fn );
-		return this;
-	},
-
-	delegate: function( selector, types, data, fn ) {
-		return this.on( types, selector, data, fn );
-	},
-	undelegate: function( selector, types, fn ) {
-		// ( namespace ) or ( selector, types [, fn] )
-		return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn );
-	},
-
-	trigger: function( type, data ) {
-		return this.each(function() {
-			jQuery.event.trigger( type, data, this );
-		});
-	},
-	triggerHandler: function( type, data ) {
-		if ( this[0] ) {
-			return jQuery.event.trigger( type, data, this[0], true );
-		}
-	},
-
-	toggle: function( fn ) {
-		// Save reference to arguments for access in closure
-		var args = arguments,
-			guid = fn.guid || jQuery.guid++,
-			i = 0,
-			toggler = function( event ) {
-				// Figure out which function to execute
-				var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
-				jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
-
-				// Make sure that clicks stop
-				event.preventDefault();
-
-				// and execute the function
-				return args[ lastToggle ].apply( this, arguments ) || false;
-			};
-
-		// link all the functions, so any of them can unbind this click handler
-		toggler.guid = guid;
-		while ( i < args.length ) {
-			args[ i++ ].guid = guid;
-		}
-
-		return this.click( toggler );
-	},
-
-	hover: function( fnOver, fnOut ) {
-		return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
-	}
-});
-
-jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
-	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
-	"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
-
-	// Handle event binding
-	jQuery.fn[ name ] = function( data, fn ) {
-		if ( fn == null ) {
-			fn = data;
-			data = null;
-		}
-
-		return arguments.length > 0 ?
-			this.on( name, null, data, fn ) :
-			this.trigger( name );
-	};
-
-	if ( jQuery.attrFn ) {
-		jQuery.attrFn[ name ] = true;
-	}
-
-	if ( rkeyEvent.test( name ) ) {
-		jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
-	}
-
-	if ( rmouseEvent.test( name ) ) {
-		jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
-	}
-});
-
-
-
-/*!
- * Sizzle CSS Selector Engine
- *  Copyright 2011, The Dojo Foundation
- *  Released under the MIT, BSD, and GPL Licenses.
- *  More information: http://sizzlejs.com/
- */
-(function(){
-
-var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
-	expando = "sizcache" + (Math.random() + '').replace('.', ''),
-	done = 0,
-	toString = Object.prototype.toString,
-	hasDuplicate = false,
-	baseHasDuplicate = true,
-	rBackslash = /\\/g,
-	rReturn = /\r\n/g,
-	rNonWord = /\W/;
+    if (!jQuery.support.focusinBubbles) {
+        jQuery.each({ focus: "focusin", blur: "focusout" }, function (orig, fix) {
+
+            // Attach a single capturing handler while someone wants focusin/focusout
+            var attaches = 0,
+                handler = function (event) {
+                    jQuery.event.simulate(fix, event.target, jQuery.event.fix(event), true);
+                };
+
+            jQuery.event.special[ fix ] = {
+                setup: function () {
+                    if (attaches++ === 0) {
+                        document.addEventListener(orig, handler, true);
+                    }
+                },
+                teardown: function () {
+                    if (--attaches === 0) {
+                        document.removeEventListener(orig, handler, true);
+                    }
+                }
+            };
+        });
+    }
+
+    jQuery.fn.extend({
+
+        on: function (types, selector, data, fn, /*INTERNAL*/ one) {
+            var origFn, type;
+
+            // Types can be a map of types/handlers
+            if (typeof types === "object") {
+                // ( types-Object, selector, data )
+                if (typeof selector !== "string") {
+                    // ( types-Object, data )
+                    data = selector;
+                    selector = undefined;
+                }
+                for (type in types) {
+                    this.on(type, selector, data, types[ type ], one);
+                }
+                return this;
+            }
+
+            if (data == null && fn == null) {
+                // ( types, fn )
+                fn = selector;
+                data = selector = undefined;
+            } else if (fn == null) {
+                if (typeof selector === "string") {
+                    // ( types, selector, fn )
+                    fn = data;
+                    data = undefined;
+                } else {
+                    // ( types, data, fn )
+                    fn = data;
+                    data = selector;
+                    selector = undefined;
+                }
+            }
+            if (fn === false) {
+                fn = returnFalse;
+            } else if (!fn) {
+                return this;
+            }
+
+            if (one === 1) {
+                origFn = fn;
+                fn = function (event) {
+                    // Can use an empty set, since event contains the info
+                    jQuery().off(event);
+                    return origFn.apply(this, arguments);
+                };
+                // Use same guid so caller can remove using origFn
+                fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
+            }
+            return this.each(function () {
+                jQuery.event.add(this, types, fn, data, selector);
+            });
+        },
+        one: function (types, selector, data, fn) {
+            return this.on.call(this, types, selector, data, fn, 1);
+        },
+        off: function (types, selector, fn) {
+            if (types && types.preventDefault && types.handleObj) {
+                // ( event )  dispatched jQuery.Event
+                var handleObj = types.handleObj;
+                jQuery(types.delegateTarget).off(
+                    handleObj.namespace ? handleObj.type + "." + handleObj.namespace : handleObj.type,
+                    handleObj.selector,
+                    handleObj.handler
+                );
+                return this;
+            }
+            if (typeof types === "object") {
+                // ( types-object [, selector] )
+                for (var type in types) {
+                    this.off(type, selector, types[ type ]);
+                }
+                return this;
+            }
+            if (selector === false || typeof selector === "function") {
+                // ( types [, fn] )
+                fn = selector;
+                selector = undefined;
+            }
+            if (fn === false) {
+                fn = returnFalse;
+            }
+            return this.each(function () {
+                jQuery.event.remove(this, types, fn, selector);
+            });
+        },
+
+        bind: function (types, data, fn) {
+            return this.on(types, null, data, fn);
+        },
+        unbind: function (types, fn) {
+            return this.off(types, null, fn);
+        },
+
+        live: function (types, data, fn) {
+            jQuery(this.context).on(types, this.selector, data, fn);
+            return this;
+        },
+        die: function (types, fn) {
+            jQuery(this.context).off(types, this.selector || "**", fn);
+            return this;
+        },
+
+        delegate: function (selector, types, data, fn) {
+            return this.on(types, selector, data, fn);
+        },
+        undelegate: function (selector, types, fn) {
+            // ( namespace ) or ( selector, types [, fn] )
+            return arguments.length == 1 ? this.off(selector, "**") : this.off(types, selector, fn);
+        },
+
+        trigger: function (type, data) {
+            return this.each(function () {
+                jQuery.event.trigger(type, data, this);
+            });
+        },
+        triggerHandler: function (type, data) {
+            if (this[0]) {
+                return jQuery.event.trigger(type, data, this[0], true);
+            }
+        },
+
+        toggle: function (fn) {
+            // Save reference to arguments for access in closure
+            var args = arguments,
+                guid = fn.guid || jQuery.guid++,
+                i = 0,
+                toggler = function (event) {
+                    // Figure out which function to execute
+                    var lastToggle = ( jQuery._data(this, "lastToggle" + fn.guid) || 0 ) % i;
+                    jQuery._data(this, "lastToggle" + fn.guid, lastToggle + 1);
+
+                    // Make sure that clicks stop
+                    event.preventDefault();
+
+                    // and execute the function
+                    return args[ lastToggle ].apply(this, arguments) || false;
+                };
+
+            // link all the functions, so any of them can unbind this click handler
+            toggler.guid = guid;
+            while (i < args.length) {
+                args[ i++ ].guid = guid;
+            }
+
+            return this.click(toggler);
+        },
+
+        hover: function (fnOver, fnOut) {
+            return this.mouseenter(fnOver).mouseleave(fnOut || fnOver);
+        }
+    });
+
+    jQuery.each(("blur focus focusin focusout load resize scroll unload click dblclick " +
+        "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
+        "change select submit keydown keypress keyup error contextmenu").split(" "), function (i, name) {
+
+        // Handle event binding
+        jQuery.fn[ name ] = function (data, fn) {
+            if (fn == null) {
+                fn = data;
+                data = null;
+            }
+
+            return arguments.length > 0 ?
+                this.on(name, null, data, fn) :
+                this.trigger(name);
+        };
+
+        if (jQuery.attrFn) {
+            jQuery.attrFn[ name ] = true;
+        }
+
+        if (rkeyEvent.test(name)) {
+            jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
+        }
+
+        if (rmouseEvent.test(name)) {
+            jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
+        }
+    });
+
+
+    /*!
+     * Sizzle CSS Selector Engine
+     *  Copyright 2011, The Dojo Foundation
+     *  Released under the MIT, BSD, and GPL Licenses.
+     *  More information: http://sizzlejs.com/
+     */
+    (function () {
+
+        var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
+            expando = "sizcache" + (Math.random() + '').replace('.', ''),
+            done = 0,
+            toString = Object.prototype.toString,
+            hasDuplicate = false,
+            baseHasDuplicate = true,
+            rBackslash = /\\/g,
+            rReturn = /\r\n/g,
+            rNonWord = /\W/;
 
 // Here we check if the JavaScript engine is using some sort of
 // optimization where it does not always call our comparision
 // function. If that is the case, discard the hasDuplicate value.
 //   Thus far that includes Google Chrome.
-[0, 0].sort(function() {
-	baseHasDuplicate = false;
-	return 0;
-});
-
-var Sizzle = function( selector, context, results, seed ) {
-	results = results || [];
-	context = context || document;
-
-	var origContext = context;
-
-	if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
-		return [];
-	}
-	
-	if ( !selector || typeof selector !== "string" ) {
-		return results;
-	}
-
-	var m, set, checkSet, extra, ret, cur, pop, i,
-		prune = true,
-		contextXML = Sizzle.isXML( context ),
-		parts = [],
-		soFar = selector;
-	
-	// Reset the position of the chunker regexp (start from head)
-	do {
-		chunker.exec( "" );
-		m = chunker.exec( soFar );
-
-		if ( m ) {
-			soFar = m[3];
-		
-			parts.push( m[1] );
-		
-			if ( m[2] ) {
-				extra = m[3];
-				break;
-			}
-		}
-	} while ( m );
-
-	if ( parts.length > 1 && origPOS.exec( selector ) ) {
-
-		if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
-			set = posProcess( parts[0] + parts[1], context, seed );
-
-		} else {
-			set = Expr.relative[ parts[0] ] ?
-				[ context ] :
-				Sizzle( parts.shift(), context );
-
-			while ( parts.length ) {
-				selector = parts.shift();
-
-				if ( Expr.relative[ selector ] ) {
-					selector += parts.shift();
-				}
-				
-				set = posProcess( selector, set, seed );
-			}
-		}
-
-	} else {
-		// Take a shortcut and set the context if the root selector is an ID
-		// (but not if it'll be faster if the inner selector is an ID)
-		if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
-				Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
-
-			ret = Sizzle.find( parts.shift(), context, contextXML );
-			context = ret.expr ?
-				Sizzle.filter( ret.expr, ret.set )[0] :
-				ret.set[0];
-		}
-
-		if ( context ) {
-			ret = seed ?
-				{ expr: parts.pop(), set: makeArray(seed) } :
-				Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
-
-			set = ret.expr ?
-				Sizzle.filter( ret.expr, ret.set ) :
-				ret.set;
-
-			if ( parts.length > 0 ) {
-				checkSet = makeArray( set );
-
-			} else {
-				prune = false;
-			}
-
-			while ( parts.length ) {
-				cur = parts.pop();
-				pop = cur;
-
-				if ( !Expr.relative[ cur ] ) {
-					cur = "";
-				} else {
-					pop = parts.pop();
-				}
-
-				if ( pop == null ) {
-					pop = context;
-				}
-
-				Expr.relative[ cur ]( checkSet, pop, contextXML );
-			}
-
-		} else {
-			checkSet = parts = [];
-		}
-	}
-
-	if ( !checkSet ) {
-		checkSet = set;
-	}
-
-	if ( !checkSet ) {
-		Sizzle.error( cur || selector );
-	}
-
-	if ( toString.call(checkSet) === "[object Array]" ) {
-		if ( !prune ) {
-			results.push.apply( results, checkSet );
-
-		} else if ( context && context.nodeType === 1 ) {
-			for ( i = 0; checkSet[i] != null; i++ ) {
-				if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
-					results.push( set[i] );
-				}
-			}
-
-		} else {
-			for ( i = 0; checkSet[i] != null; i++ ) {
-				if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
-					results.push( set[i] );
-				}
-			}
-		}
-
-	} else {
-		makeArray( checkSet, results );
-	}
-
-	if ( extra ) {
-		Sizzle( extra, origContext, results, seed );
-		Sizzle.uniqueSort( results );
-	}
-
-	return results;
-};
-
-Sizzle.uniqueSort = function( results ) {
-	if ( sortOrder ) {
-		hasDuplicate = baseHasDuplicate;
-		results.sort( sortOrder );
-
-		if ( hasDuplicate ) {
-			for ( var i = 1; i < results.length; i++ ) {
-				if ( results[i] === results[ i - 1 ] ) {
-					results.splice( i--, 1 );
-				}
-			}
-		}
-	}
-
-	return results;
-};
-
-Sizzle.matches = function( expr, set ) {
-	return Sizzle( expr, null, null, set );
-};
-
-Sizzle.matchesSelector = function( node, expr ) {
-	return Sizzle( expr, null, null, [node] ).length > 0;
-};
-
-Sizzle.find = function( expr, context, isXML ) {
-	var set, i, len, match, type, left;
-
-	if ( !expr ) {
-		return [];
-	}
-
-	for ( i = 0, len = Expr.order.length; i < len; i++ ) {
-		type = Expr.order[i];
-		
-		if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
-			left = match[1];
-			match.splice( 1, 1 );
-
-			if ( left.substr( left.length - 1 ) !== "\\" ) {
-				match[1] = (match[1] || "").replace( rBackslash, "" );
-				set = Expr.find[ type ]( match, context, isXML );
-
-				if ( set != null ) {
-					expr = expr.replace( Expr.match[ type ], "" );
-					break;
-				}
-			}
-		}
-	}
-
-	if ( !set ) {
-		set = typeof context.getElementsByTagName !== "undefined" ?
-			context.getElementsByTagName( "*" ) :
-			[];
-	}
-
-	return { set: set, expr: expr };
-};
-
-Sizzle.filter = function( expr, set, inplace, not ) {
-	var match, anyFound,
-		type, found, item, filter, left,
-		i, pass,
-		old = expr,
-		result = [],
-		curLoop = set,
-		isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
-
-	while ( expr && set.length ) {
-		for ( type in Expr.filter ) {
-			if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
-				filter = Expr.filter[ type ];
-				left = match[1];
-
-				anyFound = false;
-
-				match.splice(1,1);
-
-				if ( left.substr( left.length - 1 ) === "\\" ) {
-					continue;
-				}
-
-				if ( curLoop === result ) {
-					result = [];
-				}
-
-				if ( Expr.preFilter[ type ] ) {
-					match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
-
-					if ( !match ) {
-						anyFound = found = true;
-
-					} else if ( match === true ) {
-						continue;
-					}
-				}
-
-				if ( match ) {
-					for ( i = 0; (item = curLoop[i]) != null; i++ ) {
-						if ( item ) {
-							found = filter( item, match, i, curLoop );
-							pass = not ^ found;
-
-							if ( inplace && found != null ) {
-								if ( pass ) {
-									anyFound = true;
-
-								} else {
-									curLoop[i] = false;
-								}
-
-							} else if ( pass ) {
-								result.push( item );
-								anyFound = true;
-							}
-						}
-					}
-				}
-
-				if ( found !== undefined ) {
-					if ( !inplace ) {
-						curLoop = result;
-					}
-
-					expr = expr.replace( Expr.match[ type ], "" );
-
-					if ( !anyFound ) {
-						return [];
-					}
-
-					break;
-				}
-			}
-		}
-
-		// Improper expression
-		if ( expr === old ) {
-			if ( anyFound == null ) {
-				Sizzle.error( expr );
-
-			} else {
-				break;
-			}
-		}
-
-		old = expr;
-	}
-
-	return curLoop;
-};
-
-Sizzle.error = function( msg ) {
-	throw new Error( "Syntax error, unrecognized expression: " + msg );
-};
-
-/**
- * Utility function for retreiving the text value of an array of DOM nodes
- * @param {Array|Element} elem
- */
-var getText = Sizzle.getText = function( elem ) {
-    var i, node,
-		nodeType = elem.nodeType,
-		ret = "";
-
-	if ( nodeType ) {
-		if ( nodeType === 1 || nodeType === 9 ) {
-			// Use textContent || innerText for elements
-			if ( typeof elem.textContent === 'string' ) {
-				return elem.textContent;
-			} else if ( typeof elem.innerText === 'string' ) {
-				// Replace IE's carriage returns
-				return elem.innerText.replace( rReturn, '' );
-			} else {
-				// Traverse it's children
-				for ( elem = elem.firstChild; elem; elem = elem.nextSibling) {
-					ret += getText( elem );
-				}
-			}
-		} else if ( nodeType === 3 || nodeType === 4 ) {
-			return elem.nodeValue;
-		}
-	} else {
-
-		// If no nodeType, this is expected to be an array
-		for ( i = 0; (node = elem[i]); i++ ) {
-			// Do not traverse comment nodes
-			if ( node.nodeType !== 8 ) {
-				ret += getText( node );
-			}
-		}
-	}
-	return ret;
-};
-
-var Expr = Sizzle.selectors = {
-	order: [ "ID", "NAME", "TAG" ],
-
-	match: {
-		ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
-		CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
-		NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
-		ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
-		TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
-		CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
-		POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
-		PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
-	},
-
-	leftMatch: {},
-
-	attrMap: {
-		"class": "className",
-		"for": "htmlFor"
-	},
-
-	attrHandle: {
-		href: function( elem ) {
-			return elem.getAttribute( "href" );
-		},
-		type: function( elem ) {
-			return elem.getAttribute( "type" );
-		}
-	},
-
-	relative: {
-		"+": function(checkSet, part){
-			var isPartStr = typeof part === "string",
-				isTag = isPartStr && !rNonWord.test( part ),
-				isPartStrNotTag = isPartStr && !isTag;
-
-			if ( isTag ) {
-				part = part.toLowerCase();
-			}
-
-			for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
-				if ( (elem = checkSet[i]) ) {
-					while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
-
-					checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
-						elem || false :
-						elem === part;
-				}
-			}
-
-			if ( isPartStrNotTag ) {
-				Sizzle.filter( part, checkSet, true );
-			}
-		},
-
-		">": function( checkSet, part ) {
-			var elem,
-				isPartStr = typeof part === "string",
-				i = 0,
-				l = checkSet.length;
-
-			if ( isPartStr && !rNonWord.test( part ) ) {
-				part = part.toLowerCase();
-
-				for ( ; i < l; i++ ) {
-					elem = checkSet[i];
-
-					if ( elem ) {
-						var parent = elem.parentNode;
-						checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
-					}
-				}
-
-			} else {
-				for ( ; i < l; i++ ) {
-					elem = checkSet[i];
-
-					if ( elem ) {
-						checkSet[i] = isPartStr ?
-							elem.parentNode :
-							elem.parentNode === part;
-					}
-				}
-
-				if ( isPartStr ) {
-					Sizzle.filter( part, checkSet, true );
-				}
-			}
-		},
-
-		"": function(checkSet, part, isXML){
-			var nodeCheck,
-				doneName = done++,
-				checkFn = dirCheck;
-
-			if ( typeof part === "string" && !rNonWord.test( part ) ) {
-				part = part.toLowerCase();
-				nodeCheck = part;
-				checkFn = dirNodeCheck;
-			}
-
-			checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
-		},
-
-		"~": function( checkSet, part, isXML ) {
-			var nodeCheck,
-				doneName = done++,
-				checkFn = dirCheck;
-
-			if ( typeof part === "string" && !rNonWord.test( part ) ) {
-				part = part.toLowerCase();
-				nodeCheck = part;
-				checkFn = dirNodeCheck;
-			}
-
-			checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
-		}
-	},
-
-	find: {
-		ID: function( match, context, isXML ) {
-			if ( typeof context.getElementById !== "undefined" && !isXML ) {
-				var m = context.getElementById(match[1]);
-				// Check parentNode to catch when Blackberry 4.6 returns
-				// nodes that are no longer in the document #6963
-				return m && m.parentNode ? [m] : [];
-			}
-		},
-
-		NAME: function( match, context ) {
-			if ( typeof context.getElementsByName !== "undefined" ) {
-				var ret = [],
-					results = context.getElementsByName( match[1] );
-
-				for ( var i = 0, l = results.length; i < l; i++ ) {
-					if ( results[i].getAttribute("name") === match[1] ) {
-						ret.push( results[i] );
-					}
-				}
-
-				return ret.length === 0 ? null : ret;
-			}
-		},
-
-		TAG: function( match, context ) {
-			if ( typeof context.getElementsByTagName !== "undefined" ) {
-				return context.getElementsByTagName( match[1] );
-			}
-		}
-	},
-	preFilter: {
-		CLASS: function( match, curLoop, inplace, result, not, isXML ) {
-			match = " " + match[1].replace( rBackslash, "" ) + " ";
-
-			if ( isXML ) {
-				return match;
-			}
-
-			for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
-				if ( elem ) {
-					if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
-						if ( !inplace ) {
-							result.push( elem );
-						}
-
-					} else if ( inplace ) {
-						curLoop[i] = false;
-					}
-				}
-			}
-
-			return false;
-		},
-
-		ID: function( match ) {
-			return match[1].replace( rBackslash, "" );
-		},
-
-		TAG: function( match, curLoop ) {
-			return match[1].replace( rBackslash, "" ).toLowerCase();
-		},
-
-		CHILD: function( match ) {
-			if ( match[1] === "nth" ) {
-				if ( !match[2] ) {
-					Sizzle.error( match[0] );
-				}
-
-				match[2] = match[2].replace(/^\+|\s*/g, '');
-
-				// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
-				var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
-					match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
-					!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
-
-				// calculate the numbers (first)n+(last) including if they are negative
-				match[2] = (test[1] + (test[2] || 1)) - 0;
-				match[3] = test[3] - 0;
-			}
-			else if ( match[2] ) {
-				Sizzle.error( match[0] );
-			}
-
-			// TODO: Move to normal caching system
-			match[0] = done++;
-
-			return match;
-		},
-
-		ATTR: function( match, curLoop, inplace, result, not, isXML ) {
-			var name = match[1] = match[1].replace( rBackslash, "" );
-			
-			if ( !isXML && Expr.attrMap[name] ) {
-				match[1] = Expr.attrMap[name];
-			}
-
-			// Handle if an un-quoted value was used
-			match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
-
-			if ( match[2] === "~=" ) {
-				match[4] = " " + match[4] + " ";
-			}
-
-			return match;
-		},
-
-		PSEUDO: function( match, curLoop, inplace, result, not ) {
-			if ( match[1] === "not" ) {
-				// If we're dealing with a complex expression, or a simple one
-				if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
-					match[3] = Sizzle(match[3], null, null, curLoop);
-
-				} else {
-					var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
-
-					if ( !inplace ) {
-						result.push.apply( result, ret );
-					}
-
-					return false;
-				}
-
-			} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
-				return true;
-			}
-			
-			return match;
-		},
-
-		POS: function( match ) {
-			match.unshift( true );
-
-			return match;
-		}
-	},
-	
-	filters: {
-		enabled: function( elem ) {
-			return elem.disabled === false && elem.type !== "hidden";
-		},
-
-		disabled: function( elem ) {
-			return elem.disabled === true;
-		},
-
-		checked: function( elem ) {
-			return elem.checked === true;
-		},
-		
-		selected: function( elem ) {
-			// Accessing this property makes selected-by-default
-			// options in Safari work properly
-			if ( elem.parentNode ) {
-				elem.parentNode.selectedIndex;
-			}
-			
-			return elem.selected === true;
-		},
-
-		parent: function( elem ) {
-			return !!elem.firstChild;
-		},
-
-		empty: function( elem ) {
-			return !elem.firstChild;
-		},
-
-		has: function( elem, i, match ) {
-			return !!Sizzle( match[3], elem ).length;
-		},
-
-		header: function( elem ) {
-			return (/h\d/i).test( elem.nodeName );
-		},
-
-		text: function( elem ) {
-			var attr = elem.getAttribute( "type" ), type = elem.type;
-			// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) 
-			// use getAttribute instead to test this case
-			return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
-		},
-
-		radio: function( elem ) {
-			return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
-		},
-
-		checkbox: function( elem ) {
-			return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
-		},
-
-		file: function( elem ) {
-			return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
-		},
-
-		password: function( elem ) {
-			return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
-		},
-
-		submit: function( elem ) {
-			var name = elem.nodeName.toLowerCase();
-			return (name === "input" || name === "button") && "submit" === elem.type;
-		},
-
-		image: function( elem ) {
-			return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
-		},
-
-		reset: function( elem ) {
-			var name = elem.nodeName.toLowerCase();
-			return (name === "input" || name === "button") && "reset" === elem.type;
-		},
-
-		button: function( elem ) {
-			var name = elem.nodeName.toLowerCase();
-			return name === "input" && "button" === elem.type || name === "button";
-		},
-
-		input: function( elem ) {
-			return (/input|select|textarea|button/i).test( elem.nodeName );
-		},
-
-		focus: function( elem ) {
-			return elem === elem.ownerDocument.activeElement;
-		}
-	},
-	setFilters: {
-		first: function( elem, i ) {
-			return i === 0;
-		},
-
-		last: function( elem, i, match, array ) {
-			return i === array.length - 1;
-		},
-
-		even: function( elem, i ) {
-			return i % 2 === 0;
-		},
-
-		odd: function( elem, i ) {
-			return i % 2 === 1;
-		},
-
-		lt: function( elem, i, match ) {
-			return i < match[3] - 0;
-		},
-
-		gt: function( elem, i, match ) {
-			return i > match[3] - 0;
-		},
-
-		nth: function( elem, i, match ) {
-			return match[3] - 0 === i;
-		},
-
-		eq: function( elem, i, match ) {
-			return match[3] - 0 === i;
-		}
-	},
-	filter: {
-		PSEUDO: function( elem, match, i, array ) {
-			var name = match[1],
-				filter = Expr.filters[ name ];
-
-			if ( filter ) {
-				return filter( elem, i, match, array );
-
-			} else if ( name === "contains" ) {
-				return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;
-
-			} else if ( name === "not" ) {
-				var not = match[3];
-
-				for ( var j = 0, l = not.length; j < l; j++ ) {
-					if ( not[j] === elem ) {
-						return false;
-					}
-				}
-
-				return true;
-
-			} else {
-				Sizzle.error( name );
-			}
-		},
-
-		CHILD: function( elem, match ) {
-			var first, last,
-				doneName, parent, cache,
-				count, diff,
-				type = match[1],
-				node = elem;
-
-			switch ( type ) {
-				case "only":
-				case "first":
-					while ( (node = node.previousSibling) )	 {
-						if ( node.nodeType === 1 ) { 
-							return false; 
-						}
-					}
-
-					if ( type === "first" ) { 
-						return true; 
-					}
-
-					node = elem;
-
-				case "last":
-					while ( (node = node.nextSibling) )	 {
-						if ( node.nodeType === 1 ) { 
-							return false; 
-						}
-					}
-
-					return true;
-
-				case "nth":
-					first = match[2];
-					last = match[3];
-
-					if ( first === 1 && last === 0 ) {
-						return true;
-					}
-					
-					doneName = match[0];
-					parent = elem.parentNode;
-	
-					if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
-						count = 0;
-						
-						for ( node = parent.firstChild; node; node = node.nextSibling ) {
-							if ( node.nodeType === 1 ) {
-								node.nodeIndex = ++count;
-							}
-						} 
-
-						parent[ expando ] = doneName;
-					}
-					
-					diff = elem.nodeIndex - last;
-
-					if ( first === 0 ) {
-						return diff === 0;
-
-					} else {
-						return ( diff % first === 0 && diff / first >= 0 );
-					}
-			}
-		},
-
-		ID: function( elem, match ) {
-			return elem.nodeType === 1 && elem.getAttribute("id") === match;
-		},
-
-		TAG: function( elem, match ) {
-			return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
-		},
-		
-		CLASS: function( elem, match ) {
-			return (" " + (elem.className || elem.getAttribute("class")) + " ")
-				.indexOf( match ) > -1;
-		},
-
-		ATTR: function( elem, match ) {
-			var name = match[1],
-				result = Sizzle.attr ?
-					Sizzle.attr( elem, name ) :
-					Expr.attrHandle[ name ] ?
-					Expr.attrHandle[ name ]( elem ) :
-					elem[ name ] != null ?
-						elem[ name ] :
-						elem.getAttribute( name ),
-				value = result + "",
-				type = match[2],
-				check = match[4];
-
-			return result == null ?
-				type === "!=" :
-				!type && Sizzle.attr ?
-				result != null :
-				type === "=" ?
-				value === check :
-				type === "*=" ?
-				value.indexOf(check) >= 0 :
-				type === "~=" ?
-				(" " + value + " ").indexOf(check) >= 0 :
-				!check ?
-				value && result !== false :
-				type === "!=" ?
-				value !== check :
-				type === "^=" ?
-				value.indexOf(check) === 0 :
-				type === "$=" ?
-				value.substr(value.length - check.length) === check :
-				type === "|=" ?
-				value === check || value.substr(0, check.length + 1) === check + "-" :
-				false;
-		},
-
-		POS: function( elem, match, i, array ) {
-			var name = match[2],
-				filter = Expr.setFilters[ name ];
-
-			if ( filter ) {
-				return filter( elem, i, match, array );
-			}
-		}
-	}
-};
-
-var origPOS = Expr.match.POS,
-	fescape = function(all, num){
-		return "\\" + (num - 0 + 1);
-	};
-
-for ( var type in Expr.match ) {
-	Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
-	Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
-}
-
-var makeArray = function( array, results ) {
-	array = Array.prototype.slice.call( array, 0 );
-
-	if ( results ) {
-		results.push.apply( results, array );
-		return results;
-	}
-	
-	return array;
-};
+        [0, 0].sort(function () {
+            baseHasDuplicate = false;
+            return 0;
+        });
+
+        var Sizzle = function (selector, context, results, seed) {
+            results = results || [];
+            context = context || document;
+
+            var origContext = context;
+
+            if (context.nodeType !== 1 && context.nodeType !== 9) {
+                return [];
+            }
+
+            if (!selector || typeof selector !== "string") {
+                return results;
+            }
+
+            var m, set, checkSet, extra, ret, cur, pop, i,
+                prune = true,
+                contextXML = Sizzle.isXML(context),
+                parts = [],
+                soFar = selector;
+
+            // Reset the position of the chunker regexp (start from head)
+            do {
+                chunker.exec("");
+                m = chunker.exec(soFar);
+
+                if (m) {
+                    soFar = m[3];
+
+                    parts.push(m[1]);
+
+                    if (m[2]) {
+                        extra = m[3];
+                        break;
+                    }
+                }
+            } while (m);
+
+            if (parts.length > 1 && origPOS.exec(selector)) {
+
+                if (parts.length === 2 && Expr.relative[ parts[0] ]) {
+                    set = posProcess(parts[0] + parts[1], context, seed);
+
+                } else {
+                    set = Expr.relative[ parts[0] ] ?
+                        [ context ] :
+                        Sizzle(parts.shift(), context);
+
+                    while (parts.length) {
+                        selector = parts.shift();
+
+                        if (Expr.relative[ selector ]) {
+                            selector += parts.shift();
+                        }
+
+                        set = posProcess(selector, set, seed);
+                    }
+                }
+
+            } else {
+                // Take a shortcut and set the context if the root selector is an ID
+                // (but not if it'll be faster if the inner selector is an ID)
+                if (!seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
+                    Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1])) {
+
+                    ret = Sizzle.find(parts.shift(), context, contextXML);
+                    context = ret.expr ?
+                        Sizzle.filter(ret.expr, ret.set)[0] :
+                        ret.set[0];
+                }
+
+                if (context) {
+                    ret = seed ?
+                    { expr: parts.pop(), set: makeArray(seed) } :
+                        Sizzle.find(parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML);
+
+                    set = ret.expr ?
+                        Sizzle.filter(ret.expr, ret.set) :
+                        ret.set;
+
+                    if (parts.length > 0) {
+                        checkSet = makeArray(set);
+
+                    } else {
+                        prune = false;
+                    }
+
+                    while (parts.length) {
+                        cur = parts.pop();
+                        pop = cur;
+
+                        if (!Expr.relative[ cur ]) {
+                            cur = "";
+                        } else {
+                            pop = parts.pop();
+                        }
+
+                        if (pop == null) {
+                            pop = context;
+                        }
+
+                        Expr.relative[ cur ](checkSet, pop, contextXML);
+                    }
+
+                } else {
+                    checkSet = parts = [];
+                }
+            }
+
+            if (!checkSet) {
+                checkSet = set;
+            }
+
+            if (!checkSet) {
+                Sizzle.error(cur || selector);
+            }
+
+            if (toString.call(checkSet) === "[object Array]") {
+                if (!prune) {
+                    results.push.apply(results, checkSet);
+
+                } else if (context && context.nodeType === 1) {
+                    for (i = 0; checkSet[i] != null; i++) {
+                        if (checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i]))) {
+                            results.push(set[i]);
+                        }
+                    }
+
+                } else {
+                    for (i = 0; checkSet[i] != null; i++) {
+                        if (checkSet[i] && checkSet[i].nodeType === 1) {
+                            results.push(set[i]);
+                        }
+                    }
+                }
+
+            } else {
+                makeArray(checkSet, results);
+            }
+
+            if (extra) {
+                Sizzle(extra, origContext, results, seed);
+                Sizzle.uniqueSort(results);
+            }
+
+            return results;
+        };
+
+        Sizzle.uniqueSort = function (results) {
+            if (sortOrder) {
+                hasDuplicate = baseHasDuplicate;
+                results.sort(sortOrder);
+
+                if (hasDuplicate) {
+                    for (var i = 1; i < results.length; i++) {
+                        if (results[i] === results[ i - 1 ]) {
+                            results.splice(i--, 1);
+                        }
+                    }
+                }
+            }
+
+            return results;
+        };
+
+        Sizzle.matches = function (expr, set) {
+            return Sizzle(expr, null, null, set);
+        };
+
+        Sizzle.matchesSelector = function (node, expr) {
+            return Sizzle(expr, null, null, [node]).length > 0;
+        };
+
+        Sizzle.find = function (expr, context, isXML) {
+            var set, i, len, match, type, left;
+
+            if (!expr) {
+                return [];
+            }
+
+            for (i = 0, len = Expr.order.length; i < len; i++) {
+                type = Expr.order[i];
+
+                if ((match = Expr.leftMatch[ type ].exec(expr))) {
+                    left = match[1];
+                    match.splice(1, 1);
+
+                    if (left.substr(left.length - 1) !== "\\") {
+                        match[1] = (match[1] || "").replace(rBackslash, "");
+                        set = Expr.find[ type ](match, context, isXML);
+
+                        if (set != null) {
+                            expr = expr.replace(Expr.match[ type ], "");
+                            break;
+                        }
+                    }
+                }
+            }
+
+            if (!set) {
+                set = typeof context.getElementsByTagName !== "undefined" ?
+                    context.getElementsByTagName("*") :
+                    [];
+            }
+
+            return { set: set, expr: expr };
+        };
+
+        Sizzle.filter = function (expr, set, inplace, not) {
+            var match, anyFound,
+                type, found, item, filter, left,
+                i, pass,
+                old = expr,
+                result = [],
+                curLoop = set,
+                isXMLFilter = set && set[0] && Sizzle.isXML(set[0]);
+
+            while (expr && set.length) {
+                for (type in Expr.filter) {
+                    if ((match = Expr.leftMatch[ type ].exec(expr)) != null && match[2]) {
+                        filter = Expr.filter[ type ];
+                        left = match[1];
+
+                        anyFound = false;
+
+                        match.splice(1, 1);
+
+                        if (left.substr(left.length - 1) === "\\") {
+                            continue;
+                        }
+
+                        if (curLoop === result) {
+                            result = [];
+                        }
+
+                        if (Expr.preFilter[ type ]) {
+                            match = Expr.preFilter[ type ](match, curLoop, inplace, result, not, isXMLFilter);
+
+                            if (!match) {
+                                anyFound = found = true;
+
+                            } else if (match === true) {
+                                continue;
+                            }
+                        }
+
+                        if (match) {
+                            for (i = 0; (item = curLoop[i]) != null; i++) {
+                                if (item) {
+                                    found = filter(item, match, i, curLoop);
+                                    pass = not ^ found;
+
+                                    if (inplace && found != null) {
+                                        if (pass) {
+                                            anyFound = true;
+
+                                        } else {
+                                            curLoop[i] = false;
+                                        }
+
+                                    } else if (pass) {
+                                        result.push(item);
+                                        anyFound = true;
+                                    }
+                                }
+                            }
+                        }
+
+                        if (found !== undefined) {
+                            if (!inplace) {
+                                curLoop = result;
+                            }
+
+                            expr = expr.replace(Expr.match[ type ], "");
+
+                            if (!anyFound) {
+                                return [];
+                            }
+
+                            break;
+                        }
+                    }
+                }
+
+                // Improper expression
+                if (expr === old) {
+                    if (anyFound == null) {
+                        Sizzle.error(expr);
+
+                    } else {
+                        break;
+                    }
+                }
+
+                old = expr;
+            }
+
+            return curLoop;
+        };
+
+        Sizzle.error = function (msg) {
+            throw new Error("Syntax error, unrecognized expression: " + msg);
+        };
+
+        /**
+         * Utility function for retreiving the text value of an array of DOM nodes
+         * @param {Array|Element} elem
+         */
+        var getText = Sizzle.getText = function (elem) {
+            var i, node,
+                nodeType = elem.nodeType,
+                ret = "";
+
+            if (nodeType) {
+                if (nodeType === 1 || nodeType === 9) {
+                    // Use textContent || innerText for elements
+                    if (typeof elem.textContent === 'string') {
+                        return elem.textContent;
+                    } else if (typeof elem.innerText === 'string') {
+                        // Replace IE's carriage returns
+                        return elem.innerText.replace(rReturn, '');
+                    } else {
+                        // Traverse it's children
+                        for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
+                            ret += getText(elem);
+                        }
+                    }
+                } else if (nodeType === 3 || nodeType === 4) {
+                    return elem.nodeValue;
+                }
+            } else {
+
+                // If no nodeType, this is expected to be an array
+                for (i = 0; (node = elem[i]); i++) {
+                    // Do not traverse comment nodes
+                    if (node.nodeType !== 8) {
+                        ret += getText(node);
+                    }
+                }
+            }
+            return ret;
+        };
+
+        var Expr = Sizzle.selectors = {
+            order: [ "ID", "NAME", "TAG" ],
+
+            match: {
+                ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
+                CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
+                NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
+                ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
+                TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
+                CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
+                POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
+                PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
+            },
+
+            leftMatch: {},
+
+            attrMap: {
+                "class": "className",
+                "for": "htmlFor"
+            },
+
+            attrHandle: {
+                href: function (elem) {
+                    return elem.getAttribute("href");
+                },
+                type: function (elem) {
+                    return elem.getAttribute("type");
+                }
+            },
+
+            relative: {
+                "+": function (checkSet, part) {
+                    var isPartStr = typeof part === "string",
+                        isTag = isPartStr && !rNonWord.test(part),
+                        isPartStrNotTag = isPartStr && !isTag;
+
+                    if (isTag) {
+                        part = part.toLowerCase();
+                    }
+
+                    for (var i = 0, l = checkSet.length, elem; i < l; i++) {
+                        if ((elem = checkSet[i])) {
+                            while ((elem = elem.previousSibling) && elem.nodeType !== 1) {
+                            }
+
+                            checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
+                                elem || false :
+                                elem === part;
+                        }
+                    }
+
+                    if (isPartStrNotTag) {
+                        Sizzle.filter(part, checkSet, true);
+                    }
+                },
+
+                ">": function (checkSet, part) {
+                    var elem,
+                        isPartStr = typeof part === "string",
+                        i = 0,
+                        l = checkSet.length;
+
+                    if (isPartStr && !rNonWord.test(part)) {
+                        part = part.toLowerCase();
+
+                        for (; i < l; i++) {
+                            elem = checkSet[i];
+
+                            if (elem) {
+                                var parent = elem.parentNode;
+                                checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
+                            }
+                        }
+
+                    } else {
+                        for (; i < l; i++) {
+                            elem = checkSet[i];
+
+                            if (elem) {
+                                checkSet[i] = isPartStr ?
+                                    elem.parentNode :
+                                    elem.parentNode === part;
+                            }
+                        }
+
+                        if (isPartStr) {
+                            Sizzle.filter(part, checkSet, true);
+                        }
+                    }
+                },
+
+                "": function (checkSet, part, isXML) {
+                    var nodeCheck,
+                        doneName = done++,
+                        checkFn = dirCheck;
+
+                    if (typeof part === "string" && !rNonWord.test(part)) {
+                        part = part.toLowerCase();
+                        nodeCheck = part;
+                        checkFn = dirNodeCheck;
+                    }
+
+                    checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
+                },
+
+                "~": function (checkSet, part, isXML) {
+                    var nodeCheck,
+                        doneName = done++,
+                        checkFn = dirCheck;
+
+                    if (typeof part === "string" && !rNonWord.test(part)) {
+                        part = part.toLowerCase();
+                        nodeCheck = part;
+                        checkFn = dirNodeCheck;
+                    }
+
+                    checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
+                }
+            },
+
+            find: {
+                ID: function (match, context, isXML) {
+                    if (typeof context.getElementById !== "undefined" && !isXML) {
+                        var m = context.getElementById(match[1]);
+                        // Check parentNode to catch when Blackberry 4.6 returns
+                        // nodes that are no longer in the document #6963
+                        return m && m.parentNode ? [m] : [];
+                    }
+                },
+
+                NAME: function (match, context) {
+                    if (typeof context.getElementsByName !== "undefined") {
+                        var ret = [],
+                            results = context.getElementsByName(match[1]);
+
+                        for (var i = 0, l = results.length; i < l; i++) {
+                            if (results[i].getAttribute("name") === match[1]) {
+                                ret.push(results[i]);
+                            }
+                        }
+
+                        return ret.length === 0 ? null : ret;
+                    }
+                },
+
+                TAG: function (match, context) {
+                    if (typeof context.getElementsByTagName !== "undefined") {
+                        return context.getElementsByTagName(match[1]);
+                    }
+                }
+            },
+            preFilter: {
+                CLASS: function (match, curLoop, inplace, result, not, isXML) {
+                    match = " " + match[1].replace(rBackslash, "") + " ";
+
+                    if (isXML) {
+                        return match;
+                    }
+
+                    for (var i = 0, elem; (elem = curLoop[i]) != null; i++) {
+                        if (elem) {
+                            if (not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0)) {
+                                if (!inplace) {
+                                    result.push(elem);
+                                }
+
+                            } else if (inplace) {
+                                curLoop[i] = false;
+                            }
+                        }
+                    }
+
+                    return false;
+                },
+
+                ID: function (match) {
+                    return match[1].replace(rBackslash, "");
+                },
+
+                TAG: function (match, curLoop) {
+                    return match[1].replace(rBackslash, "").toLowerCase();
+                },
+
+                CHILD: function (match) {
+                    if (match[1] === "nth") {
+                        if (!match[2]) {
+                            Sizzle.error(match[0]);
+                        }
+
+                        match[2] = match[2].replace(/^\+|\s*/g, '');
+
+                        // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
+                        var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
+                            match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
+                                !/\D/.test(match[2]) && "0n+" + match[2] || match[2]);
+
+                        // calculate the numbers (first)n+(last) including if they are negative
+                        match[2] = (test[1] + (test[2] || 1)) - 0;
+                        match[3] = test[3] - 0;
+                    }
+                    else if (match[2]) {
+                        Sizzle.error(match[0]);
+                    }
+
+                    // TODO: Move to normal caching system
+                    match[0] = done++;
+
+                    return match;
+                },
+
+                ATTR: function (match, curLoop, inplace, result, not, isXML) {
+                    var name = match[1] = match[1].replace(rBackslash, "");
+
+                    if (!isXML && Expr.attrMap[name]) {
+                        match[1] = Expr.attrMap[name];
+                    }
+
+                    // Handle if an un-quoted value was used
+                    match[4] = ( match[4] || match[5] || "" ).replace(rBackslash, "");
+
+                    if (match[2] === "~=") {
+                        match[4] = " " + match[4] + " ";
+                    }
+
+                    return match;
+                },
+
+                PSEUDO: function (match, curLoop, inplace, result, not) {
+                    if (match[1] === "not") {
+                        // If we're dealing with a complex expression, or a simple one
+                        if (( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3])) {
+                            match[3] = Sizzle(match[3], null, null, curLoop);
+
+                        } else {
+                            var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
+
+                            if (!inplace) {
+                                result.push.apply(result, ret);
+                            }
+
+                            return false;
+                        }
+
+                    } else if (Expr.match.POS.test(match[0]) || Expr.match.CHILD.test(match[0])) {
+                        return true;
+                    }
+
+                    return match;
+                },
+
+                POS: function (match) {
+                    match.unshift(true);
+
+                    return match;
+                }
+            },
+
+            filters: {
+                enabled: function (elem) {
+                    return elem.disabled === false && elem.type !== "hidden";
+                },
+
+                disabled: function (elem) {
+                    return elem.disabled === true;
+                },
+
+                checked: function (elem) {
+                    return elem.checked === true;
+                },
+
+                selected: function (elem) {
+                    // Accessing this property makes selected-by-default
+                    // options in Safari work properly
+                    if (elem.parentNode) {
+                        elem.parentNode.selectedIndex;
+                    }
+
+                    return elem.selected === true;
+                },
+
+                parent: function (elem) {
+                    return !!elem.firstChild;
+                },
+
+                empty: function (elem) {
+                    return !elem.firstChild;
+                },
+
+                has: function (elem, i, match) {
+                    return !!Sizzle(match[3], elem).length;
+                },
+
+                header: function (elem) {
+                    return (/h\d/i).test(elem.nodeName);
+                },
+
+                text: function (elem) {
+                    var attr = elem.getAttribute("type"), type = elem.type;
+                    // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) 
+                    // use getAttribute instead to test this case
+                    return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
+                },
+
+                radio: function (elem) {
+                    return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
+                },
+
+                checkbox: function (elem) {
+                    return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
+                },
+
+                file: function (elem) {
+                    return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
+                },
+
+                password: function (elem) {
+                    return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
+                },
+
+                submit: function (elem) {
+                    var name = elem.nodeName.toLowerCase();
+                    return (name === "input" || name === "button") && "submit" === elem.type;
+                },
+
+                image: function (elem) {
+                    return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
+                },
+
+                reset: function (elem) {
+                    var name = elem.nodeName.toLowerCase();
+                    return (name === "input" || name === "button") && "reset" === elem.type;
+                },
+
+                button: function (elem) {
+                    var name = elem.nodeName.toLowerCase();
+                    return name === "input" && "button" === elem.type || name === "button";
+                },
+
+                input: function (elem) {
+                    return (/input|select|textarea|button/i).test(elem.nodeName);
+                },
+
+                focus: function (elem) {
+                    return elem === elem.ownerDocument.activeElement;
+                }
+            },
+            setFilters: {
+                first: function (elem, i) {
+                    return i === 0;
+                },
+
+                last: function (elem, i, match, array) {
+                    return i === array.length - 1;
+                },
+
+                even: function (elem, i) {
+                    return i % 2 === 0;
+                },
+
+                odd: function (elem, i) {
+                    return i % 2 === 1;
+                },
+
+                lt: function (elem, i, match) {
+                    return i < match[3] - 0;
+                },
+
+                gt: function (elem, i, match) {
+                    return i > match[3] - 0;
+                },
+
+                nth: function (elem, i, match) {
+                    return match[3] - 0 === i;
+                },
+
+                eq: function (elem, i, match) {
+                    return match[3] - 0 === i;
+                }
+            },
+            filter: {
+                PSEUDO: function (elem, match, i, array) {
+                    var name = match[1],
+                        filter = Expr.filters[ name ];
+
+                    if (filter) {
+                        return filter(elem, i, match, array);
+
+                    } else if (name === "contains") {
+                        return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;
+
+                    } else if (name === "not") {
+                        var not = match[3];
+
+                        for (var j = 0, l = not.length; j < l; j++) {
+                            if (not[j] === elem) {
+                                return false;
+                            }
+                        }
+
+                        return true;
+
+                    } else {
+                        Sizzle.error(name);
+                    }
+                },
+
+                CHILD: function (elem, match) {
+                    var first, last,
+                        doneName, parent, cache,
+                        count, diff,
+                        type = match[1],
+                        node = elem;
+
+                    switch (type) {
+                        case "only":
+                        case "first":
+                            while ((node = node.previousSibling)) {
+                                if (node.nodeType === 1) {
+                                    return false;
+                                }
+                            }
+
+                            if (type === "first") {
+                                return true;
+                            }
+
+                            node = elem;
+
+                        case "last":
+                            while ((node = node.nextSibling)) {
+                                if (node.nodeType === 1) {
+                                    return false;
+                                }
+                            }
+
+                            return true;
+
+                        case "nth":
+                            first = match[2];
+                            last = match[3];
+
+                            if (first === 1 && last === 0) {
+                                return true;
+                            }
+
+                            doneName = match[0];
+                            parent = elem.parentNode;
+
+                            if (parent && (parent[ expando ] !== doneName || !elem.nodeIndex)) {
+                                count = 0;
+
+                                for (node = parent.firstChild; node; node = node.nextSibling) {
+                                    if (node.nodeType === 1) {
+                                        node.nodeIndex = ++count;
+                                    }
+                                }
+
+                                parent[ expando ] = doneName;
+                            }
+
+                            diff = elem.nodeIndex - last;
+
+                            if (first === 0) {
+                                return diff === 0;
+
+                            } else {
+                                return ( diff % first === 0 && diff / first >= 0 );
+                            }
+                    }
+                },
+
+                ID: function (elem, match) {
+                    return elem.nodeType === 1 && elem.getAttribute("id") === match;
+                },
+
+                TAG: function (elem, match) {
+                    return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
+                },
+
+                CLASS: function (elem, match) {
+                    return (" " + (elem.className || elem.getAttribute("class")) + " ")
+                        .indexOf(match) > -1;
+                },
+
+                ATTR: function (elem, match) {
+                    var name = match[1],
+                        result = Sizzle.attr ?
+                            Sizzle.attr(elem, name) :
+                            Expr.attrHandle[ name ] ?
+                                Expr.attrHandle[ name ](elem) :
+                                elem[ name ] != null ?
+                                    elem[ name ] :
+                                    elem.getAttribute(name),
+                        value = result + "",
+                        type = match[2],
+                        check = match[4];
+
+                    return result == null ?
+                        type === "!=" :
+                        !type && Sizzle.attr ?
+                            result != null :
+                            type === "=" ?
+                                value === check :
+                                type === "*=" ?
+                                    value.indexOf(check) >= 0 :
+                                    type === "~=" ?
+                                        (" " + value + " ").indexOf(check) >= 0 :
+                                        !check ?
+                                            value && result !== false :
+                                            type === "!=" ?
+                                                value !== check :
+                                                type === "^=" ?
+                                                    value.indexOf(check) === 0 :
+                                                    type === "$=" ?
+                                                        value.substr(value.length - check.length) === check :
+                                                        type === "|=" ?
+                                                            value === check || value.substr(0, check.length + 1) === check + "-" :
+                                                            false;
+                },
+
+                POS: function (elem, match, i, array) {
+                    var name = match[2],
+                        filter = Expr.setFilters[ name ];
+
+                    if (filter) {
+                        return filter(elem, i, match, array);
+                    }
+                }
+            }
+        };
+
+        var origPOS = Expr.match.POS,
+            fescape = function (all, num) {
+                return "\\" + (num - 0 + 1);
+            };
+
+        for (var type in Expr.match) {
+            Expr.match[ type ] = new RegExp(Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source));
+            Expr.leftMatch[ type ] = new RegExp(/(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape));
+        }
+
+        var makeArray = function (array, results) {
+            array = Array.prototype.slice.call(array, 0);
+
+            if (results) {
+                results.push.apply(results, array);
+                return results;
+            }
+
+            return array;
+        };
 
 // Perform a simple check to determine if the browser is capable of
 // converting a NodeList to an array using builtin methods.
 // Also verifies that the returned array holds DOM nodes
 // (which is not the case in the Blackberry browser)
-try {
-	Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
+        try {
+            Array.prototype.slice.call(document.documentElement.childNodes, 0)[0].nodeType;
 
 // Provide a fallback method if it does not work
-} catch( e ) {
-	makeArray = function( array, results ) {
-		var i = 0,
-			ret = results || [];
-
-		if ( toString.call(array) === "[object Array]" ) {
-			Array.prototype.push.apply( ret, array );
-
-		} else {
-			if ( typeof array.length === "number" ) {
-				for ( var l = array.length; i < l; i++ ) {
-					ret.push( array[i] );
-				}
-
-			} else {
-				for ( ; array[i]; i++ ) {
-					ret.push( array[i] );
-				}
-			}
-		}
-
-		return ret;
-	};
-}
-
-var sortOrder, siblingCheck;
-
-if ( document.documentElement.compareDocumentPosition ) {
-	sortOrder = function( a, b ) {
-		if ( a === b ) {
-			hasDuplicate = true;
-			return 0;
-		}
-
-		if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
-			return a.compareDocumentPosition ? -1 : 1;
-		}
-
-		return a.compareDocumentPosition(b) & 4 ? -1 : 1;
-	};
-
-} else {
-	sortOrder = function( a, b ) {
-		// The nodes are identical, we can exit early
-		if ( a === b ) {
-			hasDuplicate = true;
-			return 0;
-
-		// Fallback to using sourceIndex (in IE) if it's available on both nodes
-		} else if ( a.sourceIndex && b.sourceIndex ) {
-			return a.sourceIndex - b.sourceIndex;
-		}
-
-		var al, bl,
-			ap = [],
-			bp = [],
-			aup = a.parentNode,
-			bup = b.parentNode,
-			cur = aup;
-
-		// If the nodes are siblings (or identical) we can do a quick check
-		if ( aup === bup ) {
-			return siblingCheck( a, b );
-
-		// If no parents were found then the nodes are disconnected
-		} else if ( !aup ) {
-			return -1;
-
-		} else if ( !bup ) {
-			return 1;
-		}
-
-		// Otherwise they're somewhere else in the tree so we need
-		// to build up a full list of the parentNodes for comparison
-		while ( cur ) {
-			ap.unshift( cur );
-			cur = cur.parentNode;
-		}
-
-		cur = bup;
-
-		while ( cur ) {
-			bp.unshift( cur );
-			cur = cur.parentNode;
-		}
-
-		al = ap.length;
-		bl = bp.length;
-
-		// Start walking down the tree looking for a discrepancy
-		for ( var i = 0; i < al && i < bl; i++ ) {
-			if ( ap[i] !== bp[i] ) {
-				return siblingCheck( ap[i], bp[i] );
-			}
-		}
-
-		// We ended someplace up the tree so do a sibling check
-		return i === al ?
-			siblingCheck( a, bp[i], -1 ) :
-			siblingCheck( ap[i], b, 1 );
-	};
-
-	siblingCheck = function( a, b, ret ) {
-		if ( a === b ) {
-			return ret;
-		}
-
-		var cur = a.nextSibling;
-
-		while ( cur ) {
-			if ( cur === b ) {
-				return -1;
-			}
-
-			cur = cur.nextSibling;
-		}
-
-		return 1;
-	};
-}
+        } catch (e) {
+            makeArray = function (array, results) {
+                var i = 0,
+                    ret = results || [];
+
+                if (toString.call(array) === "[object Array]") {
+                    Array.prototype.push.apply(ret, array);
+
+                } else {
+                    if (typeof array.length === "number") {
+                        for (var l = array.length; i < l; i++) {
+                            ret.push(array[i]);
+                        }
+
+                    } else {
+                        for (; array[i]; i++) {
+                            ret.push(array[i]);
+                        }
+                    }
+                }
+
+                return ret;
+            };
+        }
+
+        var sortOrder, siblingCheck;
+
+        if (document.documentElement.compareDocumentPosition) {
+            sortOrder = function (a, b) {
+                if (a === b) {
+                    hasDuplicate = true;
+                    return 0;
+                }
+
+                if (!a.compareDocumentPosition || !b.compareDocumentPosition) {
+                    return a.compareDocumentPosition ? -1 : 1;
+                }
+
+                return a.compareDocumentPosition(b) & 4 ? -1 : 1;
+            };
+
+        } else {
+            sortOrder = function (a, b) {
+                // The nodes are identical, we can exit early
+                if (a === b) {
+                    hasDuplicate = true;
+                    return 0;
+
+                    // Fallback to using sourceIndex (in IE) if it's available on both nodes
+                } else if (a.sourceIndex && b.sourceIndex) {
+                    return a.sourceIndex - b.sourceIndex;
+                }
+
+                var al, bl,
+                    ap = [],
+                    bp = [],
+                    aup = a.parentNode,
+                    bup = b.parentNode,
+                    cur = aup;
+
+                // If the nodes are siblings (or identical) we can do a quick check
+                if (aup === bup) {
+                    return siblingCheck(a, b);
+
+                    // If no parents were found then the nodes are disconnected
+                } else if (!aup) {
+                    return -1;
+
+                } else if (!bup) {
+                    return 1;
+                }
+
+                // Otherwise they're somewhere else in the tree so we need
+                // to build up a full list of the parentNodes for comparison
+                while (cur) {
+                    ap.unshift(cur);
+                    cur = cur.parentNode;
+                }
+
+                cur = bup;
+
+                while (cur) {
+                    bp.unshift(cur);
+                    cur = cur.parentNode;
+                }
+
+                al = ap.length;
+                bl = bp.length;
+
+                // Start walking down the tree looking for a discrepancy
+                for (var i = 0; i < al && i < bl; i++) {
+                    if (ap[i] !== bp[i]) {
+                        return siblingCheck(ap[i], bp[i]);
+                    }
+                }
+
+                // We ended someplace up the tree so do a sibling check
+                return i === al ?
+                    siblingCheck(a, bp[i], -1) :
+                    siblingCheck(ap[i], b, 1);
+            };
+
+            siblingCheck = function (a, b, ret) {
+                if (a === b) {
+                    return ret;
+                }
+
+                var cur = a.nextSibling;
+
+                while (cur) {
+                    if (cur === b) {
+                        return -1;
+                    }
+
+                    cur = cur.nextSibling;
+                }
+
+                return 1;
+            };
+        }
 
 // Check to see if the browser returns elements by name when
 // querying by getElementById (and provide a workaround)
-(function(){
-	// We're going to inject a fake input element with a specified name
-	var form = document.createElement("div"),
-		id = "script" + (new Date()).getTime(),
-		root = document.documentElement;
-
-	form.innerHTML = "<a name='" + id + "'/>";
-
-	// Inject it into the root element, check its status, and remove it quickly
-	root.insertBefore( form, root.firstChild );
-
-	// The workaround has to do additional checks after a getElementById
-	// Which slows things down for other browsers (hence the branching)
-	if ( document.getElementById( id ) ) {
-		Expr.find.ID = function( match, context, isXML ) {
-			if ( typeof context.getElementById !== "undefined" && !isXML ) {
-				var m = context.getElementById(match[1]);
-
-				return m ?
-					m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
-						[m] :
-						undefined :
-					[];
-			}
-		};
-
-		Expr.filter.ID = function( elem, match ) {
-			var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
-
-			return elem.nodeType === 1 && node && node.nodeValue === match;
-		};
-	}
-
-	root.removeChild( form );
-
-	// release memory in IE
-	root = form = null;
-})();
-
-(function(){
-	// Check to see if the browser returns only elements
-	// when doing getElementsByTagName("*")
-
-	// Create a fake element
-	var div = document.createElement("div");
-	div.appendChild( document.createComment("") );
-
-	// Make sure no comments are found
-	if ( div.getElementsByTagName("*").length > 0 ) {
-		Expr.find.TAG = function( match, context ) {
-			var results = context.getElementsByTagName( match[1] );
-
-			// Filter out possible comments
-			if ( match[1] === "*" ) {
-				var tmp = [];
-
-				for ( var i = 0; results[i]; i++ ) {
-					if ( results[i].nodeType === 1 ) {
-						tmp.push( results[i] );
-					}
-				}
-
-				results = tmp;
-			}
-
-			return results;
-		};
-	}
-
-	// Check to see if an attribute returns normalized href attributes
-	div.innerHTML = "<a href='#'></a>";
-
-	if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
-			div.firstChild.getAttribute("href") !== "#" ) {
-
-		Expr.attrHandle.href = function( elem ) {
-			return elem.getAttribute( "href", 2 );
-		};
-	}
-
-	// release memory in IE
-	div = null;
-})();
-
-if ( document.querySelectorAll ) {
-	(function(){
-		var oldSizzle = Sizzle,
-			div = document.createElement("div"),
-			id = "__sizzle__";
-
-		div.innerHTML = "<p class='TEST'></p>";
-
-		// Safari can't handle uppercase or unicode characters when
-		// in quirks mode.
-		if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
-			return;
-		}
-	
-		Sizzle = function( query, context, extra, seed ) {
-			context = context || document;
-
-			// Only use querySelectorAll on non-XML documents
-			// (ID selectors don't work in non-HTML documents)
-			if ( !seed && !Sizzle.isXML(context) ) {
-				// See if we find a selector to speed up
-				var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
-				
-				if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
-					// Speed-up: Sizzle("TAG")
-					if ( match[1] ) {
-						return makeArray( context.getElementsByTagName( query ), extra );
-					
-					// Speed-up: Sizzle(".CLASS")
-					} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
-						return makeArray( context.getElementsByClassName( match[2] ), extra );
-					}
-				}
-				
-				if ( context.nodeType === 9 ) {
-					// Speed-up: Sizzle("body")
-					// The body element only exists once, optimize finding it
-					if ( query === "body" && context.body ) {
-						return makeArray( [ context.body ], extra );
-						
-					// Speed-up: Sizzle("#ID")
-					} else if ( match && match[3] ) {
-						var elem = context.getElementById( match[3] );
-
-						// Check parentNode to catch when Blackberry 4.6 returns
-						// nodes that are no longer in the document #6963
-						if ( elem && elem.parentNode ) {
-							// Handle the case where IE and Opera return items
-							// by name instead of ID
-							if ( elem.id === match[3] ) {
-								return makeArray( [ elem ], extra );
-							}
-							
-						} else {
-							return makeArray( [], extra );
-						}
-					}
-					
-					try {
-						return makeArray( context.querySelectorAll(query), extra );
-					} catch(qsaError) {}
-
-				// qSA works strangely on Element-rooted queries
-				// We can work around this by specifying an extra ID on the root
-				// and working up from there (Thanks to Andrew Dupont for the technique)
-				// IE 8 doesn't work on object elements
-				} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
-					var oldContext = context,
-						old = context.getAttribute( "id" ),
-						nid = old || id,
-						hasParent = context.parentNode,
-						relativeHierarchySelector = /^\s*[+~]/.test( query );
-
-					if ( !old ) {
-						context.setAttribute( "id", nid );
-					} else {
-						nid = nid.replace( /'/g, "\\$&" );
-					}
-					if ( relativeHierarchySelector && hasParent ) {
-						context = context.parentNode;
-					}
-
-					try {
-						if ( !relativeHierarchySelector || hasParent ) {
-							return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
-						}
-
-					} catch(pseudoError) {
-					} finally {
-						if ( !old ) {
-							oldContext.removeAttribute( "id" );
-						}
-					}
-				}
-			}
-		
-			return oldSizzle(query, context, extra, seed);
-		};
-
-		for ( var prop in oldSizzle ) {
-			Sizzle[ prop ] = oldSizzle[ prop ];
-		}
-
-		// release memory in IE
-		div = null;
-	})();
-}
-
-(function(){
-	var html = document.documentElement,
-		matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
-
-	if ( matches ) {
-		// Check to see if it's possible to do matchesSelector
-		// on a disconnected node (IE 9 fails this)
-		var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
-			pseudoWorks = false;
-
-		try {
-			// This should fail with an exception
-			// Gecko does not error, returns false instead
-			matches.call( document.documentElement, "[test!='']:sizzle" );
-	
-		} catch( pseudoError ) {
-			pseudoWorks = true;
-		}
-
-		Sizzle.matchesSelector = function( node, expr ) {
-			// Make sure that attribute selectors are quoted
-			expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
-
-			if ( !Sizzle.isXML( node ) ) {
-				try { 
-					if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
-						var ret = matches.call( node, expr );
-
-						// IE 9's matchesSelector returns false on disconnected nodes
-						if ( ret || !disconnectedMatch ||
-								// As well, disconnected nodes are said to be in a document
-								// fragment in IE 9, so check for that
-								node.document && node.document.nodeType !== 11 ) {
-							return ret;
-						}
-					}
-				} catch(e) {}
-			}
-
-			return Sizzle(expr, null, null, [node]).length > 0;
-		};
-	}
-})();
-
-(function(){
-	var div = document.createElement("div");
-
-	div.innerHTML = "<div class='test e'></div><div class='test'></div>";
-
-	// Opera can't find a second classname (in 9.6)
-	// Also, make sure that getElementsByClassName actually exists
-	if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
-		return;
-	}
-
-	// Safari caches class attributes, doesn't catch changes (in 3.2)
-	div.lastChild.className = "e";
-
-	if ( div.getElementsByClassName("e").length === 1 ) {
-		return;
-	}
-	
-	Expr.order.splice(1, 0, "CLASS");
-	Expr.find.CLASS = function( match, context, isXML ) {
-		if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
-			return context.getElementsByClassName(match[1]);
-		}
-	};
-
-	// release memory in IE
-	div = null;
-})();
-
-function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
-	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
-		var elem = checkSet[i];
-
-		if ( elem ) {
-			var match = false;
-
-			elem = elem[dir];
-
-			while ( elem ) {
-				if ( elem[ expando ] === doneName ) {
-					match = checkSet[elem.sizset];
-					break;
-				}
-
-				if ( elem.nodeType === 1 && !isXML ){
-					elem[ expando ] = doneName;
-					elem.sizset = i;
-				}
-
-				if ( elem.nodeName.toLowerCase() === cur ) {
-					match = elem;
-					break;
-				}
-
-				elem = elem[dir];
-			}
-
-			checkSet[i] = match;
-		}
-	}
-}
-
-function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
-	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
-		var elem = checkSet[i];
-
-		if ( elem ) {
-			var match = false;
-			
-			elem = elem[dir];
-
-			while ( elem ) {
-				if ( elem[ expando ] === doneName ) {
-					match = checkSet[elem.sizset];
-					break;
-				}
-
-				if ( elem.nodeType === 1 ) {
-					if ( !isXML ) {
-						elem[ expando ] = doneName;
-						elem.sizset = i;
-					}
-
-					if ( typeof cur !== "string" ) {
-						if ( elem === cur ) {
-							match = true;
-							break;
-						}
-
-					} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
-						match = elem;
-						break;
-					}
-				}
-
-				elem = elem[dir];
-			}
-
-			checkSet[i] = match;
-		}
-	}
-}
-
-if ( document.documentElement.contains ) {
-	Sizzle.contains = function( a, b ) {
-		return a !== b && (a.contains ? a.contains(b) : true);
-	};
-
-} else if ( document.documentElement.compareDocumentPosition ) {
-	Sizzle.contains = function( a, b ) {
-		return !!(a.compareDocumentPosition(b) & 16);
-	};
-
-} else {
-	Sizzle.contains = function() {
-		return false;
-	};
-}
-
-Sizzle.isXML = function( elem ) {
-	// documentElement is verified for cases where it doesn't yet exist
-	// (such as loading iframes in IE - #4833) 
-	var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
-
-	return documentElement ? documentElement.nodeName !== "HTML" : false;
-};
-
-var posProcess = function( selector, context, seed ) {
-	var match,
-		tmpSet = [],
-		later = "",
-		root = context.nodeType ? [context] : context;
-
-	// Position selectors must be done after the filter
-	// And so must :not(positional) so we move all PSEUDOs to the end
-	while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
-		later += match[0];
-		selector = selector.replace( Expr.match.PSEUDO, "" );
-	}
-
-	selector = Expr.relative[selector] ? selector + "*" : selector;
-
-	for ( var i = 0, l = root.length; i < l; i++ ) {
-		Sizzle( selector, root[i], tmpSet, seed );
-	}
-
-	return Sizzle.filter( later, tmpSet );
-};
+        (function () {
+            // We're going to inject a fake input element with a specified name
+            var form = document.createElement("div"),
+                id = "script" + (new Date()).getTime(),
+                root = document.documentElement;
+
+            form.innerHTML = "<a name='" + id + "'/>";
+
+            // Inject it into the root element, check its status, and remove it quickly
+            root.insertBefore(form, root.firstChild);
+
+            // The workaround has to do additional checks after a getElementById
+            // Which slows things down for other browsers (hence the branching)
+            if (document.getElementById(id)) {
+                Expr.find.ID = function (match, context, isXML) {
+                    if (typeof context.getElementById !== "undefined" && !isXML) {
+                        var m = context.getElementById(match[1]);
+
+                        return m ?
+                            m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
+                                [m] :
+                                undefined :
+                            [];
+                    }
+                };
+
+                Expr.filter.ID = function (elem, match) {
+                    var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
+
+                    return elem.nodeType === 1 && node && node.nodeValue === match;
+                };
+            }
+
+            root.removeChild(form);
+
+            // release memory in IE
+            root = form = null;
+        })();
+
+        (function () {
+            // Check to see if the browser returns only elements
+            // when doing getElementsByTagName("*")
+
+            // Create a fake element
+            var div = document.createElement("div");
+            div.appendChild(document.createComment(""));
+
+            // Make sure no comments are found
+            if (div.getElementsByTagName("*").length > 0) {
+                Expr.find.TAG = function (match, context) {
+                    var results = context.getElementsByTagName(match[1]);
+
+                    // Filter out possible comments
+                    if (match[1] === "*") {
+                        var tmp = [];
+
+                        for (var i = 0; results[i]; i++) {
+                            if (results[i].nodeType === 1) {
+                                tmp.push(results[i]);
+                            }
+                        }
+
+                        results = tmp;
+                    }
+
+                    return results;
+                };
+            }
+
+            // Check to see if an attribute returns normalized href attributes
+            div.innerHTML = "<a href='#'></a>";
+
+            if (div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
+                div.firstChild.getAttribute("href") !== "#") {
+
+                Expr.attrHandle.href = function (elem) {
+                    return elem.getAttribute("href", 2);
+                };
+            }
+
+            // release memory in IE
+            div = null;
+        })();
+
+        if (document.querySelectorAll) {
+            (function () {
+                var oldSizzle = Sizzle,
+                    div = document.createElement("div"),
+                    id = "__sizzle__";
+
+                div.innerHTML = "<p class='TEST'></p>";
+
+                // Safari can't handle uppercase or unicode characters when
+                // in quirks mode.
+                if (div.querySelectorAll && div.querySelectorAll(".TEST").length === 0) {
+                    return;
+                }
+
+                Sizzle = function (query, context, extra, seed) {
+                    context = context || document;
+
+                    // Only use querySelectorAll on non-XML documents
+                    // (ID selectors don't work in non-HTML documents)
+                    if (!seed && !Sizzle.isXML(context)) {
+                        // See if we find a selector to speed up
+                        var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(query);
+
+                        if (match && (context.nodeType === 1 || context.nodeType === 9)) {
+                            // Speed-up: Sizzle("TAG")
+                            if (match[1]) {
+                                return makeArray(context.getElementsByTagName(query), extra);
+
+                                // Speed-up: Sizzle(".CLASS")
+                            } else if (match[2] && Expr.find.CLASS && context.getElementsByClassName) {
+                                return makeArray(context.getElementsByClassName(match[2]), extra);
+                            }
+                        }
+
+                        if (context.nodeType === 9) {
+                            // Speed-up: Sizzle("body")
+                            // The body element only exists once, optimize finding it
+                            if (query === "body" && context.body) {
+                                return makeArray([ context.body ], extra);
+
+                                // Speed-up: Sizzle("#ID")
+                            } else if (match && match[3]) {
+                                var elem = context.getElementById(match[3]);
+
+                                // Check parentNode to catch when Blackberry 4.6 returns
+                                // nodes that are no longer in the document #6963
+                                if (elem && elem.parentNode) {
+                                    // Handle the case where IE and Opera return items
+                                    // by name instead of ID
+                                    if (elem.id === match[3]) {
+                                        return makeArray([ elem ], extra);
+                                    }
+
+                                } else {
+                                    return makeArray([], extra);
+                                }
+                            }
+
+                            try {
+                                return makeArray(context.querySelectorAll(query), extra);
+                            } catch (qsaError) {
+                            }
+
+                            // qSA works strangely on Element-rooted queries
+                            // We can work around this by specifying an extra ID on the root
+                            // and working up from there (Thanks to Andrew Dupont for the technique)
+                            // IE 8 doesn't work on object elements
+                        } else if (context.nodeType === 1 && context.nodeName.toLowerCase() !== "object") {
+                            var oldContext = context,
+                                old = context.getAttribute("id"),
+                                nid = old || id,
+                                hasParent = context.parentNode,
+                                relativeHierarchySelector = /^\s*[+~]/.test(query);
+
+                            if (!old) {
+                                context.setAttribute("id", nid);
+                            } else {
+                                nid = nid.replace(/'/g, "\\$&");
+                            }
+                            if (relativeHierarchySelector && hasParent) {
+                                context = context.parentNode;
+                            }
+
+                            try {
+                                if (!relativeHierarchySelector || hasParent) {
+                                    return makeArray(context.querySelectorAll("[id='" + nid + "'] " + query), extra);
+                                }
+
+                            } catch (pseudoError) {
+                            } finally {
+                                if (!old) {
+                                    oldContext.removeAttribute("id");
+                                }
+                            }
+                        }
+                    }
+
+                    return oldSizzle(query, context, extra, seed);
+                };
+
+                for (var prop in oldSizzle) {
+                    Sizzle[ prop ] = oldSizzle[ prop ];
+                }
+
+                // release memory in IE
+                div = null;
+            })();
+        }
+
+        (function () {
+            var html = document.documentElement,
+                matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
+
+            if (matches) {
+                // Check to see if it's possible to do matchesSelector
+                // on a disconnected node (IE 9 fails this)
+                var disconnectedMatch = !matches.call(document.createElement("div"), "div"),
+                    pseudoWorks = false;
+
+                try {
+                    // This should fail with an exception
+                    // Gecko does not error, returns false instead
+                    matches.call(document.documentElement, "[test!='']:sizzle");
+
+                } catch (pseudoError) {
+                    pseudoWorks = true;
+                }
+
+                Sizzle.matchesSelector = function (node, expr) {
+                    // Make sure that attribute selectors are quoted
+                    expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
+
+                    if (!Sizzle.isXML(node)) {
+                        try {
+                            if (pseudoWorks || !Expr.match.PSEUDO.test(expr) && !/!=/.test(expr)) {
+                                var ret = matches.call(node, expr);
+
+                                // IE 9's matchesSelector returns false on disconnected nodes
+                                if (ret || !disconnectedMatch ||
+                                    // As well, disconnected nodes are said to be in a document
+                                    // fragment in IE 9, so check for that
+                                    node.document && node.document.nodeType !== 11) {
+                                    return ret;
+                                }
+                            }
+                        } catch (e) {
+                        }
+                    }
+
+                    return Sizzle(expr, null, null, [node]).length > 0;
+                };
+            }
+        })();
+
+        (function () {
+            var div = document.createElement("div");
+
+            div.innerHTML = "<div class='test e'></div><div class='test'></div>";
+
+            // Opera can't find a second classname (in 9.6)
+            // Also, make sure that getElementsByClassName actually exists
+            if (!div.getElementsByClassName || div.getElementsByClassName("e").length === 0) {
+                return;
+            }
+
+            // Safari caches class attributes, doesn't catch changes (in 3.2)
+            div.lastChild.className = "e";
+
+            if (div.getElementsByClassName("e").length === 1) {
+                return;
+            }
+
+            Expr.order.splice(1, 0, "CLASS");
+            Expr.find.CLASS = function (match, context, isXML) {
+                if (typeof context.getElementsByClassName !== "undefined" && !isXML) {
+                    return context.getElementsByClassName(match[1]);
+                }
+            };
+
+            // release memory in IE
+            div = null;
+        })();
+
+        function dirNodeCheck(dir, cur, doneName, checkSet, nodeCheck, isXML) {
+            for (var i = 0, l = checkSet.length; i < l; i++) {
+                var elem = checkSet[i];
+
+                if (elem) {
+                    var match = false;
+
+                    elem = elem[dir];
+
+                    while (elem) {
+                        if (elem[ expando ] === doneName) {
+                            match = checkSet[elem.sizset];
+                            break;
+                        }
+
+                        if (elem.nodeType === 1 && !isXML) {
+                            elem[ expando ] = doneName;
+                            elem.sizset = i;
+                        }
+
+                        if (elem.nodeName.toLowerCase() === cur) {
+                            match = elem;
+                            break;
+                        }
+
+                        elem = elem[dir];
+                    }
+
+                    checkSet[i] = match;
+                }
+            }
+        }
+
+        function dirCheck(dir, cur, doneName, checkSet, nodeCheck, isXML) {
+            for (var i = 0, l = checkSet.length; i < l; i++) {
+                var elem = checkSet[i];
+
+                if (elem) {
+                    var match = false;
+
+                    elem = elem[dir];
+
+                    while (elem) {
+                        if (elem[ expando ] === doneName) {
+                            match = checkSet[elem.sizset];
+                            break;
+                        }
+
+                        if (elem.nodeType === 1) {
+                            if (!isXML) {
+                                elem[ expando ] = doneName;
+                                elem.sizset = i;
+                            }
+
+                            if (typeof cur !== "string") {
+                                if (elem === cur) {
+                                    match = true;
+                                    break;
+                                }
+
+                            } else if (Sizzle.filter(cur, [elem]).length > 0) {
+                                match = elem;
+                                break;
+                            }
+                        }
+
+                        elem = elem[dir];
+                    }
+
+                    checkSet[i] = match;
+                }
+            }
+        }
+
+        if (document.documentElement.contains) {
+            Sizzle.contains = function (a, b) {
+                return a !== b && (a.contains ? a.contains(b) : true);
+            };
+
+        } else if (document.documentElement.compareDocumentPosition) {
+            Sizzle.contains = function (a, b) {
+                return !!(a.compareDocumentPosition(b) & 16);
+            };
+
+        } else {
+            Sizzle.contains = function () {
+                return false;
+            };
+        }
+
+        Sizzle.isXML = function (elem) {
+            // documentElement is verified for cases where it doesn't yet exist
+            // (such as loading iframes in IE - #4833) 
+            var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
+
+            return documentElement ? documentElement.nodeName !== "HTML" : false;
+        };
+
+        var posProcess = function (selector, context, seed) {
+            var match,
+                tmpSet = [],
+                later = "",
+                root = context.nodeType ? [context] : context;
+
+            // Position selectors must be done after the filter
+            // And so must :not(positional) so we move all PSEUDOs to the end
+            while ((match = Expr.match.PSEUDO.exec(selector))) {
+                later += match[0];
+                selector = selector.replace(Expr.match.PSEUDO, "");
+            }
+
+            selector = Expr.relative[selector] ? selector + "*" : selector;
+
+            for (var i = 0, l = root.length; i < l; i++) {
+                Sizzle(selector, root[i], tmpSet, seed);
+            }
+
+            return Sizzle.filter(later, tmpSet);
+        };
 
 // EXPOSE
 // Override sizzle attribute retrieval
-Sizzle.attr = jQuery.attr;
-Sizzle.selectors.attrMap = {};
-jQuery.find = Sizzle;
-jQuery.expr = Sizzle.selectors;
-jQuery.expr[":"] = jQuery.expr.filters;
-jQuery.unique = Sizzle.uniqueSort;
-jQuery.text = Sizzle.getText;
-jQuery.isXMLDoc = Sizzle.isXML;
-jQuery.contains = Sizzle.contains;
-
-
-})();
-
-
-var runtil = /Until$/,
-	rparentsprev = /^(?:parents|prevUntil|prevAll)/,
-	// Note: This RegExp should be improved, or likely pulled from Sizzle
-	rmultiselector = /,/,
-	isSimple = /^.[^:#\[\.,]*$/,
-	slice = Array.prototype.slice,
-	POS = jQuery.expr.match.POS,
-	// methods guaranteed to produce a unique set when starting from a unique set
-	guaranteedUnique = {
-		children: true,
-		contents: true,
-		next: true,
-		prev: true
-	};
-
-jQuery.fn.extend({
-	find: function( selector ) {
-		var self = this,
-			i, l;
-
-		if ( typeof selector !== "string" ) {
-			return jQuery( selector ).filter(function() {
-				for ( i = 0, l = self.length; i < l; i++ ) {
-					if ( jQuery.contains( self[ i ], this ) ) {
-						return true;
-					}
-				}
-			});
-		}
-
-		var ret = this.pushStack( "", "find", selector ),
-			length, n, r;
-
-		for ( i = 0, l = this.length; i < l; i++ ) {
-			length = ret.length;
-			jQuery.find( selector, this[i], ret );
-
-			if ( i > 0 ) {
-				// Make sure that the results are unique
-				for ( n = length; n < ret.length; n++ ) {
-					for ( r = 0; r < length; r++ ) {
-						if ( ret[r] === ret[n] ) {
-							ret.splice(n--, 1);
-							break;
-						}
-					}
-				}
-			}
-		}
-
-		return ret;
-	},
-
-	has: function( target ) {
-		var targets = jQuery( target );
-		return this.filter(function() {
-			for ( var i = 0, l = targets.length; i < l; i++ ) {
-				if ( jQuery.contains( this, targets[i] ) ) {
-					return true;
-				}
-			}
-		});
-	},
-
-	not: function( selector ) {
-		return this.pushStack( winnow(this, selector, false), "not", selector);
-	},
-
-	filter: function( selector ) {
-		return this.pushStack( winnow(this, selector, true), "filter", selector );
-	},
-
-	is: function( selector ) {
-		return !!selector && ( 
-			typeof selector === "string" ?
-				// If this is a positional selector, check membership in the returned set
-				// so $("p:first").is("p:last") won't return true for a doc with two "p".
-				POS.test( selector ) ? 
-					jQuery( selector, this.context ).index( this[0] ) >= 0 :
-					jQuery.filter( selector, this ).length > 0 :
-				this.filter( selector ).length > 0 );
-	},
-
-	closest: function( selectors, context ) {
-		var ret = [], i, l, cur = this[0];
-		
-		// Array (deprecated as of jQuery 1.7)
-		if ( jQuery.isArray( selectors ) ) {
-			var level = 1;
-
-			while ( cur && cur.ownerDocument && cur !== context ) {
-				for ( i = 0; i < selectors.length; i++ ) {
-
-					if ( jQuery( cur ).is( selectors[ i ] ) ) {
-						ret.push({ selector: selectors[ i ], elem: cur, level: level });
-					}
-				}
-
-				cur = cur.parentNode;
-				level++;
-			}
-
-			return ret;
-		}
-
-		// String
-		var pos = POS.test( selectors ) || typeof selectors !== "string" ?
-				jQuery( selectors, context || this.context ) :
-				0;
-
-		for ( i = 0, l = this.length; i < l; i++ ) {
-			cur = this[i];
-
-			while ( cur ) {
-				if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
-					ret.push( cur );
-					break;
-
-				} else {
-					cur = cur.parentNode;
-					if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
-						break;
-					}
-				}
-			}
-		}
-
-		ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
-
-		return this.pushStack( ret, "closest", selectors );
-	},
-
-	// Determine the position of an element within
-	// the matched set of elements
-	index: function( elem ) {
-
-		// No argument, return index in parent
-		if ( !elem ) {
-			return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
-		}
-
-		// index in selector
-		if ( typeof elem === "string" ) {
-			return jQuery.inArray( this[0], jQuery( elem ) );
-		}
-
-		// Locate the position of the desired element
-		return jQuery.inArray(
-			// If it receives a jQuery object, the first element is used
-			elem.jquery ? elem[0] : elem, this );
-	},
-
-	add: function( selector, context ) {
-		var set = typeof selector === "string" ?
-				jQuery( selector, context ) :
-				jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
-			all = jQuery.merge( this.get(), set );
-
-		return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
-			all :
-			jQuery.unique( all ) );
-	},
-
-	andSelf: function() {
-		return this.add( this.prevObject );
-	}
-});
+        Sizzle.attr = jQuery.attr;
+        Sizzle.selectors.attrMap = {};
+        jQuery.find = Sizzle;
+        jQuery.expr = Sizzle.selectors;
+        jQuery.expr[":"] = jQuery.expr.filters;
+        jQuery.unique = Sizzle.uniqueSort;
+        jQuery.text = Sizzle.getText;
+        jQuery.isXMLDoc = Sizzle.isXML;
+        jQuery.contains = Sizzle.contains;
+
+
+    })();
+
+
+    var runtil = /Until$/,
+        rparentsprev = /^(?:parents|prevUntil|prevAll)/,
+    // Note: This RegExp should be improved, or likely pulled from Sizzle
+        rmultiselector = /,/,
+        isSimple = /^.[^:#\[\.,]*$/,
+        slice = Array.prototype.slice,
+        POS = jQuery.expr.match.POS,
+    // methods guaranteed to produce a unique set when starting from a unique set
+        guaranteedUnique = {
+            children: true,
+            contents: true,
+            next: true,
+            prev: true
+        };
+
+    jQuery.fn.extend({
+        find: function (selector) {
+            var self = this,
+                i, l;
+
+            if (typeof selector !== "string") {
+                return jQuery(selector).filter(function () {
+                    for (i = 0, l = self.length; i < l; i++) {
+                        if (jQuery.contains(self[ i ], this)) {
+                            return true;
+                        }
+                    }
+                });
+            }
+
+            var ret = this.pushStack("", "find", selector),
+                length, n, r;
+
+            for (i = 0, l = this.length; i < l; i++) {
+                length = ret.length;
+                jQuery.find(selector, this[i], ret);
+
+                if (i > 0) {
+                    // Make sure that the results are unique
+                    for (n = length; n < ret.length; n++) {
+                        for (r = 0; r < length; r++) {
+                            if (ret[r] === ret[n]) {
+                                ret.splice(n--, 1);
+                                break;
+                            }
+                        }
+                    }
+                }
+            }
+
+            return ret;
+        },
+
+        has: function (target) {
+            var targets = jQuery(target);
+            return this.filter(function () {
+                for (var i = 0, l = targets.length; i < l; i++) {
+                    if (jQuery.contains(this, targets[i])) {
+                        return true;
+                    }
+                }
+            });
+        },
+
+        not: function (selector) {
+            return this.pushStack(winnow(this, selector, false), "not", selector);
+        },
+
+        filter: function (selector) {
+            return this.pushStack(winnow(this, selector, true), "filter", selector);
+        },
+
+        is: function (selector) {
+            return !!selector && (
+                typeof selector === "string" ?
+                    // If this is a positional selector, check membership in the returned set
+                    // so $("p:first").is("p:last") won't return true for a doc with two "p".
+                    POS.test(selector) ?
+                        jQuery(selector, this.context).index(this[0]) >= 0 :
+                        jQuery.filter(selector, this).length > 0 :
+                    this.filter(selector).length > 0 );
+        },
+
+        closest: function (selectors, context) {
+            var ret = [], i, l, cur = this[0];
+
+            // Array (deprecated as of jQuery 1.7)
+            if (jQuery.isArray(selectors)) {
+                var level = 1;
+
+                while (cur && cur.ownerDocument && cur !== context) {
+                    for (i = 0; i < selectors.length; i++) {
+
+                        if (jQuery(cur).is(selectors[ i ])) {
+                            ret.push({ selector: selectors[ i ], elem: cur, level: level });
+                        }
+                    }
+
+                    cur = cur.parentNode;
+                    level++;
+                }
+
+                return ret;
+            }
+
+            // String
+            var pos = POS.test(selectors) || typeof selectors !== "string" ?
+                jQuery(selectors, context || this.context) :
+                0;
+
+            for (i = 0, l = this.length; i < l; i++) {
+                cur = this[i];
+
+                while (cur) {
+                    if (pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors)) {
+                        ret.push(cur);
+                        break;
+
+                    } else {
+                        cur = cur.parentNode;
+                        if (!cur || !cur.ownerDocument || cur === context || cur.nodeType === 11) {
+                            break;
+                        }
+                    }
+                }
+            }
+
+            ret = ret.length > 1 ? jQuery.unique(ret) : ret;
+
+            return this.pushStack(ret, "closest", selectors);
+        },
+
+        // Determine the position of an element within
+        // the matched set of elements
+        index: function (elem) {
+
+            // No argument, return index in parent
+            if (!elem) {
+                return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
+            }
+
+            // index in selector
+            if (typeof elem === "string") {
+                return jQuery.inArray(this[0], jQuery(elem));
+            }
+
+            // Locate the position of the desired element
+            return jQuery.inArray(
+                // If it receives a jQuery object, the first element is used
+                elem.jquery ? elem[0] : elem, this);
+        },
+
+        add: function (selector, context) {
+            var set = typeof selector === "string" ?
+                    jQuery(selector, context) :
+                    jQuery.makeArray(selector && selector.nodeType ? [ selector ] : selector),
+                all = jQuery.merge(this.get(), set);
+
+            return this.pushStack(isDisconnected(set[0]) || isDisconnected(all[0]) ?
+                all :
+                jQuery.unique(all));
+        },
+
+        andSelf: function () {
+            return this.add(this.prevObject);
+        }
+    });
 
 // A painfully simple check to see if an element is disconnected
 // from a document (should be improved, where feasible).
-function isDisconnected( node ) {
-	return !node || !node.parentNode || node.parentNode.nodeType === 11;
-}
-
-jQuery.each({
-	parent: function( elem ) {
-		var parent = elem.parentNode;
-		return parent && parent.nodeType !== 11 ? parent : null;
-	},
-	parents: function( elem ) {
-		return jQuery.dir( elem, "parentNode" );
-	},
-	parentsUntil: function( elem, i, until ) {
-		return jQuery.dir( elem, "parentNode", until );
-	},
-	next: function( elem ) {
-		return jQuery.nth( elem, 2, "nextSibling" );
-	},
-	prev: function( elem ) {
-		return jQuery.nth( elem, 2, "previousSibling" );
-	},
-	nextAll: function( elem ) {
-		return jQuery.dir( elem, "nextSibling" );
-	},
-	prevAll: function( elem ) {
-		return jQuery.dir( elem, "previousSibling" );
-	},
-	nextUntil: function( elem, i, until ) {
-		return jQuery.dir( elem, "nextSibling", until );
-	},
-	prevUntil: function( elem, i, until ) {
-		return jQuery.dir( elem, "previousSibling", until );
-	},
-	siblings: function( elem ) {
-		return jQuery.sibling( elem.parentNode.firstChild, elem );
-	},
-	children: function( elem ) {
-		return jQuery.sibling( elem.firstChild );
-	},
-	contents: function( elem ) {
-		return jQuery.nodeName( elem, "iframe" ) ?
-			elem.contentDocument || elem.contentWindow.document :
-			jQuery.makeArray( elem.childNodes );
-	}
-}, function( name, fn ) {
-	jQuery.fn[ name ] = function( until, selector ) {
-		var ret = jQuery.map( this, fn, until );
-
-		if ( !runtil.test( name ) ) {
-			selector = until;
-		}
-
-		if ( selector && typeof selector === "string" ) {
-			ret = jQuery.filter( selector, ret );
-		}
-
-		ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
-
-		if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
-			ret = ret.reverse();
-		}
-
-		return this.pushStack( ret, name, slice.call( arguments ).join(",") );
-	};
-});
-
-jQuery.extend({
-	filter: function( expr, elems, not ) {
-		if ( not ) {
-			expr = ":not(" + expr + ")";
-		}
-
-		return elems.length === 1 ?
-			jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
-			jQuery.find.matches(expr, elems);
-	},
-
-	dir: function( elem, dir, until ) {
-		var matched = [],
-			cur = elem[ dir ];
-
-		while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
-			if ( cur.nodeType === 1 ) {
-				matched.push( cur );
-			}
-			cur = cur[dir];
-		}
-		return matched;
-	},
-
-	nth: function( cur, result, dir, elem ) {
-		result = result || 1;
-		var num = 0;
-
-		for ( ; cur; cur = cur[dir] ) {
-			if ( cur.nodeType === 1 && ++num === result ) {
-				break;
-			}
-		}
-
-		return cur;
-	},
-
-	sibling: function( n, elem ) {
-		var r = [];
-
-		for ( ; n; n = n.nextSibling ) {
-			if ( n.nodeType === 1 && n !== elem ) {
-				r.push( n );
-			}
-		}
-
-		return r;
-	}
-});
+    function isDisconnected(node) {
+        return !node || !node.parentNode || node.parentNode.nodeType === 11;
+    }
+
+    jQuery.each({
+        parent: function (elem) {
+            var parent = elem.parentNode;
+            return parent && parent.nodeType !== 11 ? parent : null;
+        },
+        parents: function (elem) {
+            return jQuery.dir(elem, "parentNode");
+        },
+        parentsUntil: function (elem, i, until) {
+            return jQuery.dir(elem, "parentNode", until);
+        },
+        next: function (elem) {
+            return jQuery.nth(elem, 2, "nextSibling");
+        },
+        prev: function (elem) {
+            return jQuery.nth(elem, 2, "previousSibling");
+        },
+        nextAll: function (elem) {
+            return jQuery.dir(elem, "nextSibling");
+        },
+        prevAll: function (elem) {
+            return jQuery.dir(elem, "previousSibling");
+        },
+        nextUntil: function (elem, i, until) {
+            return jQuery.dir(elem, "nextSibling", until);
+        },
+        prevUntil: function (elem, i, until) {
+            return jQuery.dir(elem, "previousSibling", until);
+        },
+        siblings: function (elem) {
+            return jQuery.sibling(elem.parentNode.firstChild, elem);
+        },
+        children: function (elem) {
+            return jQuery.sibling(elem.firstChild);
+        },
+        contents: function (elem) {
+            return jQuery.nodeName(elem, "iframe") ?
+                elem.contentDocument || elem.contentWindow.document :
+                jQuery.makeArray(elem.childNodes);
+        }
+    }, function (name, fn) {
+        jQuery.fn[ name ] = function (until, selector) {
+            var ret = jQuery.map(this, fn, until);
+
+            if (!runtil.test(name)) {
+                selector = until;
+            }
+
+            if (selector && typeof selector === "string") {
+                ret = jQuery.filter(selector, ret);
+            }
+
+            ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique(ret) : ret;
+
+            if ((this.length > 1 || rmultiselector.test(selector)) && rparentsprev.test(name)) {
+                ret = ret.reverse();
+            }
+
+            return this.pushStack(ret, name, slice.call(arguments).join(","));
+        };
+    });
+
+    jQuery.extend({
+        filter: function (expr, elems, not) {
+            if (not) {
+                expr = ":not(" + expr + ")";
+            }
+
+            return elems.length === 1 ?
+                jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
+                jQuery.find.matches(expr, elems);
+        },
+
+        dir: function (elem, dir, until) {
+            var matched = [],
+                cur = elem[ dir ];
+
+            while (cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery(cur).is(until))) {
+                if (cur.nodeType === 1) {
+                    matched.push(cur);
+                }
+                cur = cur[dir];
+            }
+            return matched;
+        },
+
+        nth: function (cur, result, dir, elem) {
+            result = result || 1;
+            var num = 0;
+
+            for (; cur; cur = cur[dir]) {
+                if (cur.nodeType === 1 && ++num === result) {
+                    break;
+                }
+            }
+
+            return cur;
+        },
+
+        sibling: function (n, elem) {
+            var r = [];
+
+            for (; n; n = n.nextSibling) {
+                if (n.nodeType === 1 && n !== elem) {
+                    r.push(n);
+                }
+            }
+
+            return r;
+        }
+    });
 
 // Implement the identical functionality for filter and not
-function winnow( elements, qualifier, keep ) {
-
-	// Can't pass null or undefined to indexOf in Firefox 4
-	// Set to 0 to skip string check
-	qualifier = qualifier || 0;
-
-	if ( jQuery.isFunction( qualifier ) ) {
-		return jQuery.grep(elements, function( elem, i ) {
-			var retVal = !!qualifier.call( elem, i, elem );
-			return retVal === keep;
-		});
-
-	} else if ( qualifier.nodeType ) {
-		return jQuery.grep(elements, function( elem, i ) {
-			return ( elem === qualifier ) === keep;
-		});
-
-	} else if ( typeof qualifier === "string" ) {
-		var filtered = jQuery.grep(elements, function( elem ) {
-			return elem.nodeType === 1;
-		});
-
-		if ( isSimple.test( qualifier ) ) {
-			return jQuery.filter(qualifier, filtered, !keep);
-		} else {
-			qualifier = jQuery.filter( qualifier, filtered );
-		}
-	}
-
-	return jQuery.grep(elements, function( elem, i ) {
-		return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
-	});
-}
-
-
-
-
-function createSafeFragment( document ) {
-	var list = nodeNames.split( "|" ),
-	safeFrag = document.createDocumentFragment();
-
-	if ( safeFrag.createElement ) {
-		while ( list.length ) {
-			safeFrag.createElement(
-				list.pop()
-			);
-		}
-	}
-	return safeFrag;
-}
-
-var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" +
-		"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
-	rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
-	rleadingWhitespace = /^\s+/,
-	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
-	rtagName = /<([\w:]+)/,
-	rtbody = /<tbody/i,
-	rhtml = /<|&#?\w+;/,
-	rnoInnerhtml = /<(?:script|style)/i,
-	rnocache = /<(?:script|object|embed|option|style)/i,
-	rnoshimcache = new RegExp("<(?:" + nodeNames + ")", "i"),
-	// checked="checked" or checked
-	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
-	rscriptType = /\/(java|ecma)script/i,
-	rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/,
-	wrapMap = {
-		option: [ 1, "<select multiple='multiple'>", "</select>" ],
-		legend: [ 1, "<fieldset>", "</fieldset>" ],
-		thead: [ 1, "<table>", "</table>" ],
-		tr: [ 2, "<table><tbody>", "</tbody></table>" ],
-		td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
-		col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
-		area: [ 1, "<map>", "</map>" ],
-		_default: [ 0, "", "" ]
-	},
-	safeFragment = createSafeFragment( document );
-
-wrapMap.optgroup = wrapMap.option;
-wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
-wrapMap.th = wrapMap.td;
+    function winnow(elements, qualifier, keep) {
+
+        // Can't pass null or undefined to indexOf in Firefox 4
+        // Set to 0 to skip string check
+        qualifier = qualifier || 0;
+
+        if (jQuery.isFunction(qualifier)) {
+            return jQuery.grep(elements, function (elem, i) {
+                var retVal = !!qualifier.call(elem, i, elem);
+                return retVal === keep;
+            });
+
+        } else if (qualifier.nodeType) {
+            return jQuery.grep(elements, function (elem, i) {
+                return ( elem === qualifier ) === keep;
+            });
+
+        } else if (typeof qualifier === "string") {
+            var filtered = jQuery.grep(elements, function (elem) {
+                return elem.nodeType === 1;
+            });
+
+            if (isSimple.test(qualifier)) {
+                return jQuery.filter(qualifier, filtered, !keep);
+            } else {
+                qualifier = jQuery.filter(qualifier, filtered);
+            }
+        }
+
+        return jQuery.grep(elements, function (elem, i) {
+            return ( jQuery.inArray(elem, qualifier) >= 0 ) === keep;
+        });
+    }
+
+
+    function createSafeFragment(document) {
+        var list = nodeNames.split("|"),
+            safeFrag = document.createDocumentFragment();
+
+        if (safeFrag.createElement) {
+            while (list.length) {
+                safeFrag.createElement(
+                    list.pop()
+                );
+            }
+        }
+        return safeFrag;
+    }
+
+    var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" +
+            "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
+        rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
+        rleadingWhitespace = /^\s+/,
+        rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
+        rtagName = /<([\w:]+)/,
+        rtbody = /<tbody/i,
+        rhtml = /<|&#?\w+;/,
+        rnoInnerhtml = /<(?:script|style)/i,
+        rnocache = /<(?:script|object|embed|option|style)/i,
+        rnoshimcache = new RegExp("<(?:" + nodeNames + ")", "i"),
+    // checked="checked" or checked
+        rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
+        rscriptType = /\/(java|ecma)script/i,
+        rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/,
+        wrapMap = {
+            option: [ 1, "<select multiple='multiple'>", "</select>" ],
+            legend: [ 1, "<fieldset>", "</fieldset>" ],
+            thead: [ 1, "<table>", "</table>" ],
+            tr: [ 2, "<table><tbody>", "</tbody></table>" ],
+            td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
+            col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
+            area: [ 1, "<map>", "</map>" ],
+            _default: [ 0, "", "" ]
+        },
+        safeFragment = createSafeFragment(document);
+
+    wrapMap.optgroup = wrapMap.option;
+    wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
+    wrapMap.th = wrapMap.td;
 
 // IE can't serialize <link> and <script> tags normally
-if ( !jQuery.support.htmlSerialize ) {
-	wrapMap._default = [ 1, "div<div>", "</div>" ];
-}
-
-jQuery.fn.extend({
-	text: function( text ) {
-		if ( jQuery.isFunction(text) ) {
-			return this.each(function(i) {
-				var self = jQuery( this );
-
-				self.text( text.call(this, i, self.text()) );
-			});
-		}
-
-		if ( typeof text !== "object" && text !== undefined ) {
-			return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
-		}
-
-		return jQuery.text( this );
-	},
-
-	wrapAll: function( html ) {
-		if ( jQuery.isFunction( html ) ) {
-			return this.each(function(i) {
-				jQuery(this).wrapAll( html.call(this, i) );
-			});
-		}
-
-		if ( this[0] ) {
-			// The elements to wrap the target around
-			var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
-
-			if ( this[0].parentNode ) {
-				wrap.insertBefore( this[0] );
-			}
-
-			wrap.map(function() {
-				var elem = this;
-
-				while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
-					elem = elem.firstChild;
-				}
-
-				return elem;
-			}).append( this );
-		}
-
-		return this;
-	},
-
-	wrapInner: function( html ) {
-		if ( jQuery.isFunction( html ) ) {
-			return this.each(function(i) {
-				jQuery(this).wrapInner( html.call(this, i) );
-			});
-		}
-
-		return this.each(function() {
-			var self = jQuery( this ),
-				contents = self.contents();
-
-			if ( contents.length ) {
-				contents.wrapAll( html );
-
-			} else {
-				self.append( html );
-			}
-		});
-	},
-
-	wrap: function( html ) {
-		var isFunction = jQuery.isFunction( html );
-
-		return this.each(function(i) {
-			jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
-		});
-	},
-
-	unwrap: function() {
-		return this.parent().each(function() {
-			if ( !jQuery.nodeName( this, "body" ) ) {
-				jQuery( this ).replaceWith( this.childNodes );
-			}
-		}).end();
-	},
-
-	append: function() {
-		return this.domManip(arguments, true, function( elem ) {
-			if ( this.nodeType === 1 ) {
-				this.appendChild( elem );
-			}
-		});
-	},
-
-	prepend: function() {
-		return this.domManip(arguments, true, function( elem ) {
-			if ( this.nodeType === 1 ) {
-				this.insertBefore( elem, this.firstChild );
-			}
-		});
-	},
-
-	before: function() {
-		if ( this[0] && this[0].parentNode ) {
-			return this.domManip(arguments, false, function( elem ) {
-				this.parentNode.insertBefore( elem, this );
-			});
-		} else if ( arguments.length ) {
-			var set = jQuery.clean( arguments );
-			set.push.apply( set, this.toArray() );
-			return this.pushStack( set, "before", arguments );
-		}
-	},
-
-	after: function() {
-		if ( this[0] && this[0].parentNode ) {
-			return this.domManip(arguments, false, function( elem ) {
-				this.parentNode.insertBefore( elem, this.nextSibling );
-			});
-		} else if ( arguments.length ) {
-			var set = this.pushStack( this, "after", arguments );
-			set.push.apply( set, jQuery.clean(arguments) );
-			return set;
-		}
-	},
-
-	// keepData is for internal use only--do not document
-	remove: function( selector, keepData ) {
-		for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
-			if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
-				if ( !keepData && elem.nodeType === 1 ) {
-					jQuery.cleanData( elem.getElementsByTagName("*") );
-					jQuery.cleanData( [ elem ] );
-				}
-
-				if ( elem.parentNode ) {
-					elem.parentNode.removeChild( elem );
-				}
-			}
-		}
-
-		return this;
-	},
-
-	empty: function() {
-		for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
-			// Remove element nodes and prevent memory leaks
-			if ( elem.nodeType === 1 ) {
-				jQuery.cleanData( elem.getElementsByTagName("*") );
-			}
-
-			// Remove any remaining nodes
-			while ( elem.firstChild ) {
-				elem.removeChild( elem.firstChild );
-			}
-		}
-
-		return this;
-	},
-
-	clone: function( dataAndEvents, deepDataAndEvents ) {
-		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
-		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
-
-		return this.map( function () {
-			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
-		});
-	},
-
-	html: function( value ) {
-		if ( value === undefined ) {
-			return this[0] && this[0].nodeType === 1 ?
-				this[0].innerHTML.replace(rinlinejQuery, "") :
-				null;
-
-		// See if we can take a shortcut and just use innerHTML
-		} else if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
-			(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
-			!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
-
-			value = value.replace(rxhtmlTag, "<$1></$2>");
-
-			try {
-				for ( var i = 0, l = this.length; i < l; i++ ) {
-					// Remove element nodes and prevent memory leaks
-					if ( this[i].nodeType === 1 ) {
-						jQuery.cleanData( this[i].getElementsByTagName("*") );
-						this[i].innerHTML = value;
-					}
-				}
-
-			// If using innerHTML throws an exception, use the fallback method
-			} catch(e) {
-				this.empty().append( value );
-			}
-
-		} else if ( jQuery.isFunction( value ) ) {
-			this.each(function(i){
-				var self = jQuery( this );
-
-				self.html( value.call(this, i, self.html()) );
-			});
-
-		} else {
-			this.empty().append( value );
-		}
-
-		return this;
-	},
-
-	replaceWith: function( value ) {
-		if ( this[0] && this[0].parentNode ) {
-			// Make sure that the elements are removed from the DOM before they are inserted
-			// this can help fix replacing a parent with child elements
-			if ( jQuery.isFunction( value ) ) {
-				return this.each(function(i) {
-					var self = jQuery(this), old = self.html();
-					self.replaceWith( value.call( this, i, old ) );
-				});
-			}
-
-			if ( typeof value !== "string" ) {
-				value = jQuery( value ).detach();
-			}
-
-			return this.each(function() {
-				var next = this.nextSibling,
-					parent = this.parentNode;
-
-				jQuery( this ).remove();
-
-				if ( next ) {
-					jQuery(next).before( value );
-				} else {
-					jQuery(parent).append( value );
-				}
-			});
-		} else {
-			return this.length ?
-				this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
-				this;
-		}
-	},
-
-	detach: function( selector ) {
-		return this.remove( selector, true );
-	},
-
-	domManip: function( args, table, callback ) {
-		var results, first, fragment, parent,
-			value = args[0],
-			scripts = [];
-
-		// We can't cloneNode fragments that contain checked, in WebKit
-		if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
-			return this.each(function() {
-				jQuery(this).domManip( args, table, callback, true );
-			});
-		}
-
-		if ( jQuery.isFunction(value) ) {
-			return this.each(function(i) {
-				var self = jQuery(this);
-				args[0] = value.call(this, i, table ? self.html() : undefined);
-				self.domManip( args, table, callback );
-			});
-		}
-
-		if ( this[0] ) {
-			parent = value && value.parentNode;
-
-			// If we're in a fragment, just use that instead of building a new one
-			if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
-				results = { fragment: parent };
-
-			} else {
-				results = jQuery.buildFragment( args, this, scripts );
-			}
-
-			fragment = results.fragment;
-
-			if ( fragment.childNodes.length === 1 ) {
-				first = fragment = fragment.firstChild;
-			} else {
-				first = fragment.firstChild;
-			}
-
-			if ( first ) {
-				table = table && jQuery.nodeName( first, "tr" );
-
-				for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
-					callback.call(
-						table ?
-							root(this[i], first) :
-							this[i],
-						// Make sure that we do not leak memory by inadvertently discarding
-						// the original fragment (which might have attached data) instead of
-						// using it; in addition, use the original fragment object for the last
-						// item instead of first because it can end up being emptied incorrectly
-						// in certain situations (Bug #8070).
-						// Fragments from the fragment cache must always be cloned and never used
-						// in place.
-						results.cacheable || ( l > 1 && i < lastIndex ) ?
-							jQuery.clone( fragment, true, true ) :
-							fragment
-					);
-				}
-			}
-
-			if ( scripts.length ) {
-				jQuery.each( scripts, evalScript );
-			}
-		}
-
-		return this;
-	}
-});
-
-function root( elem, cur ) {
-	return jQuery.nodeName(elem, "table") ?
-		(elem.getElementsByTagName("tbody")[0] ||
-		elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
-		elem;
-}
-
-function cloneCopyEvent( src, dest ) {
-
-	if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
-		return;
-	}
-
-	var type, i, l,
-		oldData = jQuery._data( src ),
-		curData = jQuery._data( dest, oldData ),
-		events = oldData.events;
-
-	if ( events ) {
-		delete curData.handle;
-		curData.events = {};
-
-		for ( type in events ) {
-			for ( i = 0, l = events[ type ].length; i < l; i++ ) {
-				jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data );
-			}
-		}
-	}
-
-	// make the cloned public data object a copy from the original
-	if ( curData.data ) {
-		curData.data = jQuery.extend( {}, curData.data );
-	}
-}
-
-function cloneFixAttributes( src, dest ) {
-	var nodeName;
-
-	// We do not need to do anything for non-Elements
-	if ( dest.nodeType !== 1 ) {
-		return;
-	}
-
-	// clearAttributes removes the attributes, which we don't want,
-	// but also removes the attachEvent events, which we *do* want
-	if ( dest.clearAttributes ) {
-		dest.clearAttributes();
-	}
-
-	// mergeAttributes, in contrast, only merges back on the
-	// original attributes, not the events
-	if ( dest.mergeAttributes ) {
-		dest.mergeAttributes( src );
-	}
-
-	nodeName = dest.nodeName.toLowerCase();
-
-	// IE6-8 fail to clone children inside object elements that use
-	// the proprietary classid attribute value (rather than the type
-	// attribute) to identify the type of content to display
-	if ( nodeName === "object" ) {
-		dest.outerHTML = src.outerHTML;
-
-	} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
-		// IE6-8 fails to persist the checked state of a cloned checkbox
-		// or radio button. Worse, IE6-7 fail to give the cloned element
-		// a checked appearance if the defaultChecked value isn't also set
-		if ( src.checked ) {
-			dest.defaultChecked = dest.checked = src.checked;
-		}
-
-		// IE6-7 get confused and end up setting the value of a cloned
-		// checkbox/radio button to an empty string instead of "on"
-		if ( dest.value !== src.value ) {
-			dest.value = src.value;
-		}
-
-	// IE6-8 fails to return the selected option to the default selected
-	// state when cloning options
-	} else if ( nodeName === "option" ) {
-		dest.selected = src.defaultSelected;
-
-	// IE6-8 fails to set the defaultValue to the correct value when
-	// cloning other types of input fields
-	} else if ( nodeName === "input" || nodeName === "textarea" ) {
-		dest.defaultValue = src.defaultValue;
-	}
-
-	// Event data gets referenced instead of copied if the expando
-	// gets copied too
-	dest.removeAttribute( jQuery.expando );
-}
-
-jQuery.buildFragment = function( args, nodes, scripts ) {
-	var fragment, cacheable, cacheresults, doc,
-	first = args[ 0 ];
-
-	// nodes may contain either an explicit document object,
-	// a jQuery collection or context object.
-	// If nodes[0] contains a valid object to assign to doc
-	if ( nodes && nodes[0] ) {
-		doc = nodes[0].ownerDocument || nodes[0];
-	}
-
-	// Ensure that an attr object doesn't incorrectly stand in as a document object
-	// Chrome and Firefox seem to allow this to occur and will throw exception
-	// Fixes #8950
-	if ( !doc.createDocumentFragment ) {
-		doc = document;
-	}
-
-	// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
-	// Cloning options loses the selected state, so don't cache them
-	// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
-	// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
-	// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
-	if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document &&
-		first.charAt(0) === "<" && !rnocache.test( first ) &&
-		(jQuery.support.checkClone || !rchecked.test( first )) &&
-		(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
-
-		cacheable = true;
-
-		cacheresults = jQuery.fragments[ first ];
-		if ( cacheresults && cacheresults !== 1 ) {
-			fragment = cacheresults;
-		}
-	}
-
-	if ( !fragment ) {
-		fragment = doc.createDocumentFragment();
-		jQuery.clean( args, doc, fragment, scripts );
-	}
-
-	if ( cacheable ) {
-		jQuery.fragments[ first ] = cacheresults ? fragment : 1;
-	}
-
-	return { fragment: fragment, cacheable: cacheable };
-};
-
-jQuery.fragments = {};
-
-jQuery.each({
-	appendTo: "append",
-	prependTo: "prepend",
-	insertBefore: "before",
-	insertAfter: "after",
-	replaceAll: "replaceWith"
-}, function( name, original ) {
-	jQuery.fn[ name ] = function( selector ) {
-		var ret = [],
-			insert = jQuery( selector ),
-			parent = this.length === 1 && this[0].parentNode;
-
-		if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
-			insert[ original ]( this[0] );
-			return this;
-
-		} else {
-			for ( var i = 0, l = insert.length; i < l; i++ ) {
-				var elems = ( i > 0 ? this.clone(true) : this ).get();
-				jQuery( insert[i] )[ original ]( elems );
-				ret = ret.concat( elems );
-			}
-
-			return this.pushStack( ret, name, insert.selector );
-		}
-	};
-});
-
-function getAll( elem ) {
-	if ( typeof elem.getElementsByTagName !== "undefined" ) {
-		return elem.getElementsByTagName( "*" );
-
-	} else if ( typeof elem.querySelectorAll !== "undefined" ) {
-		return elem.querySelectorAll( "*" );
-
-	} else {
-		return [];
-	}
-}
+    if (!jQuery.support.htmlSerialize) {
+        wrapMap._default = [ 1, "div<div>", "</div>" ];
+    }
+
+    jQuery.fn.extend({
+        text: function (text) {
+            if (jQuery.isFunction(text)) {
+                return this.each(function (i) {
+                    var self = jQuery(this);
+
+                    self.text(text.call(this, i, self.text()));
+                });
+            }
+
+            if (typeof text !== "object" && text !== undefined) {
+                return this.empty().append((this[0] && this[0].ownerDocument || document).createTextNode(text));
+            }
+
+            return jQuery.text(this);
+        },
+
+        wrapAll: function (html) {
+            if (jQuery.isFunction(html)) {
+                return this.each(function (i) {
+                    jQuery(this).wrapAll(html.call(this, i));
+                });
+            }
+
+            if (this[0]) {
+                // The elements to wrap the target around
+                var wrap = jQuery(html, this[0].ownerDocument).eq(0).clone(true);
+
+                if (this[0].parentNode) {
+                    wrap.insertBefore(this[0]);
+                }
+
+                wrap.map(function () {
+                    var elem = this;
+
+                    while (elem.firstChild && elem.firstChild.nodeType === 1) {
+                        elem = elem.firstChild;
+                    }
+
+                    return elem;
+                }).append(this);
+            }
+
+            return this;
+        },
+
+        wrapInner: function (html) {
+            if (jQuery.isFunction(html)) {
+                return this.each(function (i) {
+                    jQuery(this).wrapInner(html.call(this, i));
+                });
+            }
+
+            return this.each(function () {
+                var self = jQuery(this),
+                    contents = self.contents();
+
+                if (contents.length) {
+                    contents.wrapAll(html);
+
+                } else {
+                    self.append(html);
+                }
+            });
+        },
+
+        wrap: function (html) {
+            var isFunction = jQuery.isFunction(html);
+
+            return this.each(function (i) {
+                jQuery(this).wrapAll(isFunction ? html.call(this, i) : html);
+            });
+        },
+
+        unwrap: function () {
+            return this.parent().each(function () {
+                if (!jQuery.nodeName(this, "body")) {
+                    jQuery(this).replaceWith(this.childNodes);
+                }
+            }).end();
+        },
+
+        append: function () {
+            return this.domManip(arguments, true, function (elem) {
+                if (this.nodeType === 1) {
+                    this.appendChild(elem);
+                }
+            });
+        },
+
+        prepend: function () {
+            return this.domManip(arguments, true, function (elem) {
+                if (this.nodeType === 1) {
+                    this.insertBefore(elem, this.firstChild);
+                }
+            });
+        },
+
+        before: function () {
+            if (this[0] && this[0].parentNode) {
+                return this.domManip(arguments, false, function (elem) {
+                    this.parentNode.insertBefore(elem, this);
+                });
+            } else if (arguments.length) {
+                var set = jQuery.clean(arguments);
+                set.push.apply(set, this.toArray());
+                return this.pushStack(set, "before", arguments);
+            }
+        },
+
+        after: function () {
+            if (this[0] && this[0].parentNode) {
+                return this.domManip(arguments, false, function (elem) {
+                    this.parentNode.insertBefore(elem, this.nextSibling);
+                });
+            } else if (arguments.length) {
+                var set = this.pushStack(this, "after", arguments);
+                set.push.apply(set, jQuery.clean(arguments));
+                return set;
+            }
+        },
+
+        // keepData is for internal use only--do not document
+        remove: function (selector, keepData) {
+            for (var i = 0, elem; (elem = this[i]) != null; i++) {
+                if (!selector || jQuery.filter(selector, [ elem ]).length) {
+                    if (!keepData && elem.nodeType === 1) {
+                        jQuery.cleanData(elem.getElementsByTagName("*"));
+                        jQuery.cleanData([ elem ]);
+                    }
+
+                    if (elem.parentNode) {
+                        elem.parentNode.removeChild(elem);
+                    }
+                }
+            }
+
+            return this;
+        },
+
+        empty: function () {
+            for (var i = 0, elem; (elem = this[i]) != null; i++) {
+                // Remove element nodes and prevent memory leaks
+                if (elem.nodeType === 1) {
+                    jQuery.cleanData(elem.getElementsByTagName("*"));
+                }
+
+                // Remove any remaining nodes
+                while (elem.firstChild) {
+                    elem.removeChild(elem.firstChild);
+                }
+            }
+
+            return this;
+        },
+
+        clone: function (dataAndEvents, deepDataAndEvents) {
+            dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
+            deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
+
+            return this.map(function () {
+                return jQuery.clone(this, dataAndEvents, deepDataAndEvents);
+            });
+        },
+
+        html: function (value) {
+            if (value === undefined) {
+                return this[0] && this[0].nodeType === 1 ?
+                    this[0].innerHTML.replace(rinlinejQuery, "") :
+                    null;
+
+                // See if we can take a shortcut and just use innerHTML
+            } else if (typeof value === "string" && !rnoInnerhtml.test(value) &&
+                (jQuery.support.leadingWhitespace || !rleadingWhitespace.test(value)) && !wrapMap[ (rtagName.exec(value) || ["", ""])[1].toLowerCase() ]) {
+
+                value = value.replace(rxhtmlTag, "<$1></$2>");
+
+                try {
+                    for (var i = 0, l = this.length; i < l; i++) {
+                        // Remove element nodes and prevent memory leaks
+                        if (this[i].nodeType === 1) {
+                            jQuery.cleanData(this[i].getElementsByTagName("*"));
+                            this[i].innerHTML = value;
+                        }
+                    }
+
+                    // If using innerHTML throws an exception, use the fallback method
+                } catch (e) {
+                    this.empty().append(value);
+                }
+
+            } else if (jQuery.isFunction(value)) {
+                this.each(function (i) {
+                    var self = jQuery(this);
+
+                    self.html(value.call(this, i, self.html()));
+                });
+
+            } else {
+                this.empty().append(value);
+            }
+
+            return this;
+        },
+
+        replaceWith: function (value) {
+            if (this[0] && this[0].parentNode) {
+                // Make sure that the elements are removed from the DOM before they are inserted
+                // this can help fix replacing a parent with child elements
+                if (jQuery.isFunction(value)) {
+                    return this.each(function (i) {
+                        var self = jQuery(this), old = self.html();
+                        self.replaceWith(value.call(this, i, old));
+                    });
+                }
+
+                if (typeof value !== "string") {
+                    value = jQuery(value).detach();
+                }
+
+                return this.each(function () {
+                    var next = this.nextSibling,
+                        parent = this.parentNode;
+
+                    jQuery(this).remove();
+
+                    if (next) {
+                        jQuery(next).before(value);
+                    } else {
+                        jQuery(parent).append(value);
+                    }
+                });
+            } else {
+                return this.length ?
+                    this.pushStack(jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value) :
+                    this;
+            }
+        },
+
+        detach: function (selector) {
+            return this.remove(selector, true);
+        },
+
+        domManip: function (args, table, callback) {
+            var results, first, fragment, parent,
+                value = args[0],
+                scripts = [];
+
+            // We can't cloneNode fragments that contain checked, in WebKit
+            if (!jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test(value)) {
+                return this.each(function () {
+                    jQuery(this).domManip(args, table, callback, true);
+                });
+            }
+
+            if (jQuery.isFunction(value)) {
+                return this.each(function (i) {
+                    var self = jQuery(this);
+                    args[0] = value.call(this, i, table ? self.html() : undefined);
+                    self.domManip(args, table, callback);
+                });
+            }
+
+            if (this[0]) {
+                parent = value && value.parentNode;
+
+                // If we're in a fragment, just use that instead of building a new one
+                if (jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length) {
+                    results = { fragment: parent };
+
+                } else {
+                    results = jQuery.buildFragment(args, this, scripts);
+                }
+
+                fragment = results.fragment;
+
+                if (fragment.childNodes.length === 1) {
+                    first = fragment = fragment.firstChild;
+                } else {
+                    first = fragment.firstChild;
+                }
+
+                if (first) {
+                    table = table && jQuery.nodeName(first, "tr");
+
+                    for (var i = 0, l = this.length, lastIndex = l - 1; i < l; i++) {
+                        callback.call(
+                            table ?
+                                root(this[i], first) :
+                                this[i],
+                            // Make sure that we do not leak memory by inadvertently discarding
+                            // the original fragment (which might have attached data) instead of
+                            // using it; in addition, use the original fragment object for the last
+                            // item instead of first because it can end up being emptied incorrectly
+                            // in certain situations (Bug #8070).
+                            // Fragments from the fragment cache must always be cloned and never used
+                            // in place.
+                            results.cacheable || ( l > 1 && i < lastIndex ) ?
+                                jQuery.clone(fragment, true, true) :
+                                fragment
+                        );
+                    }
+                }
+
+                if (scripts.length) {
+                    jQuery.each(scripts, evalScript);
+                }
+            }
+
+            return this;
+        }
+    });
+
+    function root(elem, cur) {
+        return jQuery.nodeName(elem, "table") ?
+            (elem.getElementsByTagName("tbody")[0] ||
+                elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
+            elem;
+    }
+
+    function cloneCopyEvent(src, dest) {
+
+        if (dest.nodeType !== 1 || !jQuery.hasData(src)) {
+            return;
+        }
+
+        var type, i, l,
+            oldData = jQuery._data(src),
+            curData = jQuery._data(dest, oldData),
+            events = oldData.events;
+
+        if (events) {
+            delete curData.handle;
+            curData.events = {};
+
+            for (type in events) {
+                for (i = 0, l = events[ type ].length; i < l; i++) {
+                    jQuery.event.add(dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data);
+                }
+            }
+        }
+
+        // make the cloned public data object a copy from the original
+        if (curData.data) {
+            curData.data = jQuery.extend({}, curData.data);
+        }
+    }
+
+    function cloneFixAttributes(src, dest) {
+        var nodeName;
+
+        // We do not need to do anything for non-Elements
+        if (dest.nodeType !== 1) {
+            return;
+        }
+
+        // clearAttributes removes the attributes, which we don't want,
+        // but also removes the attachEvent events, which we *do* want
+        if (dest.clearAttributes) {
+            dest.clearAttributes();
+        }
+
+        // mergeAttributes, in contrast, only merges back on the
+        // original attributes, not the events
+        if (dest.mergeAttributes) {
+            dest.mergeAttributes(src);
+        }
+
+        nodeName = dest.nodeName.toLowerCase();
+
+        // IE6-8 fail to clone children inside object elements that use
+        // the proprietary classid attribute value (rather than the type
+        // attribute) to identify the type of content to display
+        if (nodeName === "object") {
+            dest.outerHTML = src.outerHTML;
+
+        } else if (nodeName === "input" && (src.type === "checkbox" || src.type === "radio")) {
+            // IE6-8 fails to persist the checked state of a cloned checkbox
+            // or radio button. Worse, IE6-7 fail to give the cloned element
+            // a checked appearance if the defaultChecked value isn't also set
+            if (src.checked) {
+                dest.defaultChecked = dest.checked = src.checked;
+            }
+
+            // IE6-7 get confused and end up setting the value of a cloned
+            // checkbox/radio button to an empty string instead of "on"
+            if (dest.value !== src.value) {
+                dest.value = src.value;
+            }
+
+            // IE6-8 fails to return the selected option to the default selected
+            // state when cloning options
+        } else if (nodeName === "option") {
+            dest.selected = src.defaultSelected;
+
+            // IE6-8 fails to set the defaultValue to the correct value when
+            // cloning other types of input fields
+        } else if (nodeName === "input" || nodeName === "textarea") {
+            dest.defaultValue = src.defaultValue;
+        }
+
+        // Event data gets referenced instead of copied if the expando
+        // gets copied too
+        dest.removeAttribute(jQuery.expando);
+    }
+
+    jQuery.buildFragment = function (args, nodes, scripts) {
+        var fragment, cacheable, cacheresults, doc,
+            first = args[ 0 ];
+
+        // nodes may contain either an explicit document object,
+        // a jQuery collection or context object.
+        // If nodes[0] contains a valid object to assign to doc
+        if (nodes && nodes[0]) {
+            doc = nodes[0].ownerDocument || nodes[0];
+        }
+
+        // Ensure that an attr object doesn't incorrectly stand in as a document object
+        // Chrome and Firefox seem to allow this to occur and will throw exception
+        // Fixes #8950
+        if (!doc.createDocumentFragment) {
+            doc = document;
+        }
+
+        // Only cache "small" (1/2 KB) HTML strings that are associated with the main document
+        // Cloning options loses the selected state, so don't cache them
+        // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
+        // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
+        // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
+        if (args.length === 1 && typeof first === "string" && first.length < 512 && doc === document &&
+            first.charAt(0) === "<" && !rnocache.test(first) &&
+            (jQuery.support.checkClone || !rchecked.test(first)) &&
+            (jQuery.support.html5Clone || !rnoshimcache.test(first))) {
+
+            cacheable = true;
+
+            cacheresults = jQuery.fragments[ first ];
+            if (cacheresults && cacheresults !== 1) {
+                fragment = cacheresults;
+            }
+        }
+
+        if (!fragment) {
+            fragment = doc.createDocumentFragment();
+            jQuery.clean(args, doc, fragment, scripts);
+        }
+
+        if (cacheable) {
+            jQuery.fragments[ first ] = cacheresults ? fragment : 1;
+        }
+
+        return { fragment: fragment, cacheable: cacheable };
+    };
+
+    jQuery.fragments = {};
+
+    jQuery.each({
+        appendTo: "append",
+        prependTo: "prepend",
+        insertBefore: "before",
+        insertAfter: "after",
+        replaceAll: "replaceWith"
+    }, function (name, original) {
+        jQuery.fn[ name ] = function (selector) {
+            var ret = [],
+                insert = jQuery(selector),
+                parent = this.length === 1 && this[0].parentNode;
+
+            if (parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1) {
+                insert[ original ](this[0]);
+                return this;
+
+            } else {
+                for (var i = 0, l = insert.length; i < l; i++) {
+                    var elems = ( i > 0 ? this.clone(true) : this ).get();
+                    jQuery(insert[i])[ original ](elems);
+                    ret = ret.concat(elems);
+                }
+
+                return this.pushStack(ret, name, insert.selector);
+            }
+        };
+    });
+
+    function getAll(elem) {
+        if (typeof elem.getElementsByTagName !== "undefined") {
+            return elem.getElementsByTagName("*");
+
+        } else if (typeof elem.querySelectorAll !== "undefined") {
+            return elem.querySelectorAll("*");
+
+        } else {
+            return [];
+        }
+    }
 
 // Used in clean, fixes the defaultChecked property
-function fixDefaultChecked( elem ) {
-	if ( elem.type === "checkbox" || elem.type === "radio" ) {
-		elem.defaultChecked = elem.checked;
-	}
-}
+    function fixDefaultChecked(elem) {
+        if (elem.type === "checkbox" || elem.type === "radio") {
+            elem.defaultChecked = elem.checked;
+        }
+    }
+
 // Finds all inputs and passes them to fixDefaultChecked
-function findInputs( elem ) {
-	var nodeName = ( elem.nodeName || "" ).toLowerCase();
-	if ( nodeName === "input" ) {
-		fixDefaultChecked( elem );
-	// Skip scripts, get other children
-	} else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) {
-		jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
-	}
-}
+    function findInputs(elem) {
+        var nodeName = ( elem.nodeName || "" ).toLowerCase();
+        if (nodeName === "input") {
+            fixDefaultChecked(elem);
+            // Skip scripts, get other children
+        } else if (nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined") {
+            jQuery.grep(elem.getElementsByTagName("input"), fixDefaultChecked);
+        }
+    }
 
 // Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js
-function shimCloneNode( elem ) {
-	var div = document.createElement( "div" );
-	safeFragment.appendChild( div );
-
-	div.innerHTML = elem.outerHTML;
-	return div.firstChild;
-}
-
-jQuery.extend({
-	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
-		var srcElements,
-			destElements,
-			i,
-			// IE<=8 does not properly clone detached, unknown element nodes
-			clone = jQuery.support.html5Clone || !rnoshimcache.test( "<" + elem.nodeName ) ?
-				elem.cloneNode( true ) :
-				shimCloneNode( elem );
-
-		if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
-				(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
-			// IE copies events bound via attachEvent when using cloneNode.
-			// Calling detachEvent on the clone will also remove the events
-			// from the original. In order to get around this, we use some
-			// proprietary methods to clear the events. Thanks to MooTools
-			// guys for this hotness.
-
-			cloneFixAttributes( elem, clone );
-
-			// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
-			srcElements = getAll( elem );
-			destElements = getAll( clone );
-
-			// Weird iteration because IE will replace the length property
-			// with an element if you are cloning the body and one of the
-			// elements on the page has a name or id of "length"
-			for ( i = 0; srcElements[i]; ++i ) {
-				// Ensure that the destination node is not null; Fixes #9587
-				if ( destElements[i] ) {
-					cloneFixAttributes( srcElements[i], destElements[i] );
-				}
-			}
-		}
-
-		// Copy the events from the original to the clone
-		if ( dataAndEvents ) {
-			cloneCopyEvent( elem, clone );
-
-			if ( deepDataAndEvents ) {
-				srcElements = getAll( elem );
-				destElements = getAll( clone );
-
-				for ( i = 0; srcElements[i]; ++i ) {
-					cloneCopyEvent( srcElements[i], destElements[i] );
-				}
-			}
-		}
-
-		srcElements = destElements = null;
-
-		// Return the cloned set
-		return clone;
-	},
-
-	clean: function( elems, context, fragment, scripts ) {
-		var checkScriptType;
-
-		context = context || document;
-
-		// !context.createElement fails in IE with an error but returns typeof 'object'
-		if ( typeof context.createElement === "undefined" ) {
-			context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
-		}
-
-		var ret = [], j;
-
-		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
-			if ( typeof elem === "number" ) {
-				elem += "";
-			}
-
-			if ( !elem ) {
-				continue;
-			}
-
-			// Convert html string into DOM nodes
-			if ( typeof elem === "string" ) {
-				if ( !rhtml.test( elem ) ) {
-					elem = context.createTextNode( elem );
-				} else {
-					// Fix "XHTML"-style tags in all browsers
-					elem = elem.replace(rxhtmlTag, "<$1></$2>");
-
-					// Trim whitespace, otherwise indexOf won't work as expected
-					var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(),
-						wrap = wrapMap[ tag ] || wrapMap._default,
-						depth = wrap[0],
-						div = context.createElement("div");
-
-					// Append wrapper element to unknown element safe doc fragment
-					if ( context === document ) {
-						// Use the fragment we've already created for this document
-						safeFragment.appendChild( div );
-					} else {
-						// Use a fragment created with the owner document
-						createSafeFragment( context ).appendChild( div );
-					}
-
-					// Go to html and back, then peel off extra wrappers
-					div.innerHTML = wrap[1] + elem + wrap[2];
-
-					// Move to the right depth
-					while ( depth-- ) {
-						div = div.lastChild;
-					}
-
-					// Remove IE's autoinserted <tbody> from table fragments
-					if ( !jQuery.support.tbody ) {
-
-						// String was a <table>, *may* have spurious <tbody>
-						var hasBody = rtbody.test(elem),
-							tbody = tag === "table" && !hasBody ?
-								div.firstChild && div.firstChild.childNodes :
-
-								// String was a bare <thead> or <tfoot>
-								wrap[1] === "<table>" && !hasBody ?
-									div.childNodes :
-									[];
-
-						for ( j = tbody.length - 1; j >= 0 ; --j ) {
-							if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
-								tbody[ j ].parentNode.removeChild( tbody[ j ] );
-							}
-						}
-					}
-
-					// IE completely kills leading whitespace when innerHTML is used
-					if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
-						div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
-					}
-
-					elem = div.childNodes;
-				}
-			}
-
-			// Resets defaultChecked for any radios and checkboxes
-			// about to be appended to the DOM in IE 6/7 (#8060)
-			var len;
-			if ( !jQuery.support.appendChecked ) {
-				if ( elem[0] && typeof (len = elem.length) === "number" ) {
-					for ( j = 0; j < len; j++ ) {
-						findInputs( elem[j] );
-					}
-				} else {
-					findInputs( elem );
-				}
-			}
-
-			if ( elem.nodeType ) {
-				ret.push( elem );
-			} else {
-				ret = jQuery.merge( ret, elem );
-			}
-		}
-
-		if ( fragment ) {
-			checkScriptType = function( elem ) {
-				return !elem.type || rscriptType.test( elem.type );
-			};
-			for ( i = 0; ret[i]; i++ ) {
-				if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
-					scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
-
-				} else {
-					if ( ret[i].nodeType === 1 ) {
-						var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType );
-
-						ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
-					}
-					fragment.appendChild( ret[i] );
-				}
-			}
-		}
-
-		return ret;
-	},
-
-	cleanData: function( elems ) {
-		var data, id,
-			cache = jQuery.cache,
-			special = jQuery.event.special,
-			deleteExpando = jQuery.support.deleteExpando;
-
-		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
-			if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
-				continue;
-			}
-
-			id = elem[ jQuery.expando ];
-
-			if ( id ) {
-				data = cache[ id ];
-
-				if ( data && data.events ) {
-					for ( var type in data.events ) {
-						if ( special[ type ] ) {
-							jQuery.event.remove( elem, type );
-
-						// This is a shortcut to avoid jQuery.event.remove's overhead
-						} else {
-							jQuery.removeEvent( elem, type, data.handle );
-						}
-					}
-
-					// Null the DOM reference to avoid IE6/7/8 leak (#7054)
-					if ( data.handle ) {
-						data.handle.elem = null;
-					}
-				}
-
-				if ( deleteExpando ) {
-					delete elem[ jQuery.expando ];
-
-				} else if ( elem.removeAttribute ) {
-					elem.removeAttribute( jQuery.expando );
-				}
-
-				delete cache[ id ];
-			}
-		}
-	}
-});
-
-function evalScript( i, elem ) {
-	if ( elem.src ) {
-		jQuery.ajax({
-			url: elem.src,
-			async: false,
-			dataType: "script"
-		});
-	} else {
-		jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) );
-	}
-
-	if ( elem.parentNode ) {
-		elem.parentNode.removeChild( elem );
-	}
-}
-
-
-
-
-var ralpha = /alpha\([^)]*\)/i,
-	ropacity = /opacity=([^)]*)/,
-	// fixed for IE9, see #8346
-	rupper = /([A-Z]|^ms)/g,
-	rnumpx = /^-?\d+(?:px)?$/i,
-	rnum = /^-?\d/,
-	rrelNum = /^([\-+])=([\-+.\de]+)/,
-
-	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
-	cssWidth = [ "Left", "Right" ],
-	cssHeight = [ "Top", "Bottom" ],
-	curCSS,
-
-	getComputedStyle,
-	currentStyle;
-
-jQuery.fn.css = function( name, value ) {
-	// Setting 'undefined' is a no-op
-	if ( arguments.length === 2 && value === undefined ) {
-		return this;
-	}
-
-	return jQuery.access( this, name, value, true, function( elem, name, value ) {
-		return value !== undefined ?
-			jQuery.style( elem, name, value ) :
-			jQuery.css( elem, name );
-	});
-};
-
-jQuery.extend({
-	// Add in style property hooks for overriding the default
-	// behavior of getting and setting a style property
-	cssHooks: {
-		opacity: {
-			get: function( elem, computed ) {
-				if ( computed ) {
-					// We should always get a number back from opacity
-					var ret = curCSS( elem, "opacity", "opacity" );
-					return ret === "" ? "1" : ret;
-
-				} else {
-					return elem.style.opacity;
-				}
-			}
-		}
-	},
-
-	// Exclude the following css properties to add px
-	cssNumber: {
-		"fillOpacity": true,
-		"fontWeight": true,
-		"lineHeight": true,
-		"opacity": true,
-		"orphans": true,
-		"widows": true,
-		"zIndex": true,
-		"zoom": true
-	},
-
-	// Add in properties whose names you wish to fix before
-	// setting or getting the value
-	cssProps: {
-		// normalize float css property
-		"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
-	},
-
-	// Get and set the style property on a DOM Node
-	style: function( elem, name, value, extra ) {
-		// Don't set styles on text and comment nodes
-		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
-			return;
-		}
-
-		// Make sure that we're working with the right name
-		var ret, type, origName = jQuery.camelCase( name ),
-			style = elem.style, hooks = jQuery.cssHooks[ origName ];
-
-		name = jQuery.cssProps[ origName ] || origName;
-
-		// Check if we're setting a value
-		if ( value !== undefined ) {
-			type = typeof value;
-
-			// convert relative number strings (+= or -=) to relative numbers. #7345
-			if ( type === "string" && (ret = rrelNum.exec( value )) ) {
-				value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) );
-				// Fixes bug #9237
-				type = "number";
-			}
-
-			// Make sure that NaN and null values aren't set. See: #7116
-			if ( value == null || type === "number" && isNaN( value ) ) {
-				return;
-			}
-
-			// If a number was passed in, add 'px' to the (except for certain CSS properties)
-			if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
-				value += "px";
-			}
-
-			// If a hook was provided, use that value, otherwise just set the specified value
-			if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
-				// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
-				// Fixes bug #5509
-				try {
-					style[ name ] = value;
-				} catch(e) {}
-			}
-
-		} else {
-			// If a hook was provided get the non-computed value from there
-			if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
-				return ret;
-			}
-
-			// Otherwise just get the value from the style object
-			return style[ name ];
-		}
-	},
-
-	css: function( elem, name, extra ) {
-		var ret, hooks;
-
-		// Make sure that we're working with the right name
-		name = jQuery.camelCase( name );
-		hooks = jQuery.cssHooks[ name ];
-		name = jQuery.cssProps[ name ] || name;
-
-		// cssFloat needs a special treatment
-		if ( name === "cssFloat" ) {
-			name = "float";
-		}
-
-		// If a hook was provided get the computed value from there
-		if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
-			return ret;
-
-		// Otherwise, if a way to get the computed value exists, use that
-		} else if ( curCSS ) {
-			return curCSS( elem, name );
-		}
-	},
-
-	// A method for quickly swapping in/out CSS properties to get correct calculations
-	swap: function( elem, options, callback ) {
-		var old = {};
-
-		// Remember the old values, and insert the new ones
-		for ( var name in options ) {
-			old[ name ] = elem.style[ name ];
-			elem.style[ name ] = options[ name ];
-		}
-
-		callback.call( elem );
-
-		// Revert the old values
-		for ( name in options ) {
-			elem.style[ name ] = old[ name ];
-		}
-	}
-});
+    function shimCloneNode(elem) {
+        var div = document.createElement("div");
+        safeFragment.appendChild(div);
+
+        div.innerHTML = elem.outerHTML;
+        return div.firstChild;
+    }
+
+    jQuery.extend({
+        clone: function (elem, dataAndEvents, deepDataAndEvents) {
+            var srcElements,
+                destElements,
+                i,
+            // IE<=8 does not properly clone detached, unknown element nodes
+                clone = jQuery.support.html5Clone || !rnoshimcache.test("<" + elem.nodeName) ?
+                    elem.cloneNode(true) :
+                    shimCloneNode(elem);
+
+            if ((!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
+                (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem)) {
+                // IE copies events bound via attachEvent when using cloneNode.
+                // Calling detachEvent on the clone will also remove the events
+                // from the original. In order to get around this, we use some
+                // proprietary methods to clear the events. Thanks to MooTools
+                // guys for this hotness.
+
+                cloneFixAttributes(elem, clone);
+
+                // Using Sizzle here is crazy slow, so we use getElementsByTagName instead
+                srcElements = getAll(elem);
+                destElements = getAll(clone);
+
+                // Weird iteration because IE will replace the length property
+                // with an element if you are cloning the body and one of the
+                // elements on the page has a name or id of "length"
+                for (i = 0; srcElements[i]; ++i) {
+                    // Ensure that the destination node is not null; Fixes #9587
+                    if (destElements[i]) {
+                        cloneFixAttributes(srcElements[i], destElements[i]);
+                    }
+                }
+            }
+
+            // Copy the events from the original to the clone
+            if (dataAndEvents) {
+                cloneCopyEvent(elem, clone);
+
+                if (deepDataAndEvents) {
+                    srcElements = getAll(elem);
+                    destElements = getAll(clone);
+
+                    for (i = 0; srcElements[i]; ++i) {
+                        cloneCopyEvent(srcElements[i], destElements[i]);
+                    }
+                }
+            }
+
+            srcElements = destElements = null;
+
+            // Return the cloned set
+            return clone;
+        },
+
+        clean: function (elems, context, fragment, scripts) {
+            var checkScriptType;
+
+            context = context || document;
+
+            // !context.createElement fails in IE with an error but returns typeof 'object'
+            if (typeof context.createElement === "undefined") {
+                context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
+            }
+
+            var ret = [], j;
+
+            for (var i = 0, elem; (elem = elems[i]) != null; i++) {
+                if (typeof elem === "number") {
+                    elem += "";
+                }
+
+                if (!elem) {
+                    continue;
+                }
+
+                // Convert html string into DOM nodes
+                if (typeof elem === "string") {
+                    if (!rhtml.test(elem)) {
+                        elem = context.createTextNode(elem);
+                    } else {
+                        // Fix "XHTML"-style tags in all browsers
+                        elem = elem.replace(rxhtmlTag, "<$1></$2>");
+
+                        // Trim whitespace, otherwise indexOf won't work as expected
+                        var tag = ( rtagName.exec(elem) || ["", ""] )[1].toLowerCase(),
+                            wrap = wrapMap[ tag ] || wrapMap._default,
+                            depth = wrap[0],
+                            div = context.createElement("div");
+
+                        // Append wrapper element to unknown element safe doc fragment
+                        if (context === document) {
+                            // Use the fragment we've already created for this document
+                            safeFragment.appendChild(div);
+                        } else {
+                            // Use a fragment created with the owner document
+                            createSafeFragment(context).appendChild(div);
+                        }
+
+                        // Go to html and back, then peel off extra wrappers
+                        div.innerHTML = wrap[1] + elem + wrap[2];
+
+                        // Move to the right depth
+                        while (depth--) {
+                            div = div.lastChild;
+                        }
+
+                        // Remove IE's autoinserted <tbody> from table fragments
+                        if (!jQuery.support.tbody) {
+
+                            // String was a <table>, *may* have spurious <tbody>
+                            var hasBody = rtbody.test(elem),
+                                tbody = tag === "table" && !hasBody ?
+                                    div.firstChild && div.firstChild.childNodes :
+
+                                    // String was a bare <thead> or <tfoot>
+                                    wrap[1] === "<table>" && !hasBody ?
+                                        div.childNodes :
+                                        [];
+
+                            for (j = tbody.length - 1; j >= 0; --j) {
+                                if (jQuery.nodeName(tbody[ j ], "tbody") && !tbody[ j ].childNodes.length) {
+                                    tbody[ j ].parentNode.removeChild(tbody[ j ]);
+                                }
+                            }
+                        }
+
+                        // IE completely kills leading whitespace when innerHTML is used
+                        if (!jQuery.support.leadingWhitespace && rleadingWhitespace.test(elem)) {
+                            div.insertBefore(context.createTextNode(rleadingWhitespace.exec(elem)[0]), div.firstChild);
+                        }
+
+                        elem = div.childNodes;
+                    }
+                }
+
+                // Resets defaultChecked for any radios and checkboxes
+                // about to be appended to the DOM in IE 6/7 (#8060)
+                var len;
+                if (!jQuery.support.appendChecked) {
+                    if (elem[0] && typeof (len = elem.length) === "number") {
+                        for (j = 0; j < len; j++) {
+                            findInputs(elem[j]);
+                        }
+                    } else {
+                        findInputs(elem);
+                    }
+                }
+
+                if (elem.nodeType) {
+                    ret.push(elem);
+                } else {
+                    ret = jQuery.merge(ret, elem);
+                }
+            }
+
+            if (fragment) {
+                checkScriptType = function (elem) {
+                    return !elem.type || rscriptType.test(elem.type);
+                };
+                for (i = 0; ret[i]; i++) {
+                    if (scripts && jQuery.nodeName(ret[i], "script") && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript")) {
+                        scripts.push(ret[i].parentNode ? ret[i].parentNode.removeChild(ret[i]) : ret[i]);
+
+                    } else {
+                        if (ret[i].nodeType === 1) {
+                            var jsTags = jQuery.grep(ret[i].getElementsByTagName("script"), checkScriptType);
+
+                            ret.splice.apply(ret, [i + 1, 0].concat(jsTags));
+                        }
+                        fragment.appendChild(ret[i]);
+                    }
+                }
+            }
+
+            return ret;
+        },
+
+        cleanData: function (elems) {
+            var data, id,
+                cache = jQuery.cache,
+                special = jQuery.event.special,
+                deleteExpando = jQuery.support.deleteExpando;
+
+            for (var i = 0, elem; (elem = elems[i]) != null; i++) {
+                if (elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) {
+                    continue;
+                }
+
+                id = elem[ jQuery.expando ];
+
+                if (id) {
+                    data = cache[ id ];
+
+                    if (data && data.events) {
+                        for (var type in data.events) {
+                            if (special[ type ]) {
+                                jQuery.event.remove(elem, type);
+
+                                // This is a shortcut to avoid jQuery.event.remove's overhead
+                            } else {
+                                jQuery.removeEvent(elem, type, data.handle);
+                            }
+                        }
+
+                        // Null the DOM reference to avoid IE6/7/8 leak (#7054)
+                        if (data.handle) {
+                            data.handle.elem = null;
+                        }
+                    }
+
+                    if (deleteExpando) {
+                        delete elem[ jQuery.expando ];
+
+                    } else if (elem.removeAttribute) {
+                        elem.removeAttribute(jQuery.expando);
+                    }
+
+                    delete cache[ id ];
+                }
+            }
+        }
+    });
+
+    function evalScript(i, elem) {
+        if (elem.src) {
+            jQuery.ajax({
+                url: elem.src,
+                async: false,
+                dataType: "script"
+            });
+        } else {
+            jQuery.globalEval(( elem.text || elem.textContent || elem.innerHTML || "" ).replace(rcleanScript, "/*$0*/"));
+        }
+
+        if (elem.parentNode) {
+            elem.parentNode.removeChild(elem);
+        }
+    }
+
+
+    var ralpha = /alpha\([^)]*\)/i,
+        ropacity = /opacity=([^)]*)/,
+    // fixed for IE9, see #8346
+        rupper = /([A-Z]|^ms)/g,
+        rnumpx = /^-?\d+(?:px)?$/i,
+        rnum = /^-?\d/,
+        rrelNum = /^([\-+])=([\-+.\de]+)/,
+
+        cssShow = { position: "absolute", visibility: "hidden", display: "block" },
+        cssWidth = [ "Left", "Right" ],
+        cssHeight = [ "Top", "Bottom" ],
+        curCSS,
+
+        getComputedStyle,
+        currentStyle;
+
+    jQuery.fn.css = function (name, value) {
+        // Setting 'undefined' is a no-op
+        if (arguments.length === 2 && value === undefined) {
+            return this;
+        }
+
+        return jQuery.access(this, name, value, true, function (elem, name, value) {
+            return value !== undefined ?
+                jQuery.style(elem, name, value) :
+                jQuery.css(elem, name);
+        });
+    };
+
+    jQuery.extend({
+        // Add in style property hooks for overriding the default
+        // behavior of getting and setting a style property
+        cssHooks: {
+            opacity: {
+                get: function (elem, computed) {
+                    if (computed) {
+                        // We should always get a number back from opacity
+                        var ret = curCSS(elem, "opacity", "opacity");
+                        return ret === "" ? "1" : ret;
+
+                    } else {
+                        return elem.style.opacity;
+                    }
+                }
+            }
+        },
+
+        // Exclude the following css properties to add px
+        cssNumber: {
+            "fillOpacity": true,
+            "fontWeight": true,
+            "lineHeight": true,
+            "opacity": true,
+            "orphans": true,
+            "widows": true,
+            "zIndex": true,
+            "zoom": true
+        },
+
+        // Add in properties whose names you wish to fix before
+        // setting or getting the value
+        cssProps: {
+            // normalize float css property
+            "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
+        },
+
+        // Get and set the style property on a DOM Node
+        style: function (elem, name, value, extra) {
+            // Don't set styles on text and comment nodes
+            if (!elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style) {
+                return;
+            }
+
+            // Make sure that we're working with the right name
+            var ret, type, origName = jQuery.camelCase(name),
+                style = elem.style, hooks = jQuery.cssHooks[ origName ];
+
+            name = jQuery.cssProps[ origName ] || origName;
+
+            // Check if we're setting a value
+            if (value !== undefined) {
+                type = typeof value;
+
+                // convert relative number strings (+= or -=) to relative numbers. #7345
+                if (type === "string" && (ret = rrelNum.exec(value))) {
+                    value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat(jQuery.css(elem, name));
+                    // Fixes bug #9237
+                    type = "number";
+                }
+
+                // Make sure that NaN and null values aren't set. See: #7116
+                if (value == null || type === "number" && isNaN(value)) {
+                    return;
+                }
+
+                // If a number was passed in, add 'px' to the (except for certain CSS properties)
+                if (type === "number" && !jQuery.cssNumber[ origName ]) {
+                    value += "px";
+                }
+
+                // If a hook was provided, use that value, otherwise just set the specified value
+                if (!hooks || !("set" in hooks) || (value = hooks.set(elem, value)) !== undefined) {
+                    // Wrapped to prevent IE from throwing errors when 'invalid' values are provided
+                    // Fixes bug #5509
+                    try {
+                        style[ name ] = value;
+                    } catch (e) {
+                    }
+                }
+
+            } else {
+                // If a hook was provided get the non-computed value from there
+                if (hooks && "get" in hooks && (ret = hooks.get(elem, false, extra)) !== undefined) {
+                    return ret;
+                }
+
+                // Otherwise just get the value from the style object
+                return style[ name ];
+            }
+        },
+
+        css: function (elem, name, extra) {
+            var ret, hooks;
+
+            // Make sure that we're working with the right name
+            name = jQuery.camelCase(name);
+            hooks = jQuery.cssHooks[ name ];
+            name = jQuery.cssProps[ name ] || name;
+
+            // cssFloat needs a special treatment
+            if (name === "cssFloat") {
+                name = "float";
+            }
+
+            // If a hook was provided get the computed value from there
+            if (hooks && "get" in hooks && (ret = hooks.get(elem, true, extra)) !== undefined) {
+                return ret;
+
+                // Otherwise, if a way to get the computed value exists, use that
+            } else if (curCSS) {
+                return curCSS(elem, name);
+            }
+        },
+
+        // A method for quickly swapping in/out CSS properties to get correct calculations
+        swap: function (elem, options, callback) {
+            var old = {};
+
+            // Remember the old values, and insert the new ones
+            for (var name in options) {
+                old[ name ] = elem.style[ name ];
+                elem.style[ name ] = options[ name ];
+            }
+
+            callback.call(elem);
+
+            // Revert the old values
+            for (name in options) {
+                elem.style[ name ] = old[ name ];
+            }
+        }
+    });
 
 // DEPRECATED, Use jQuery.css() instead
-jQuery.curCSS = jQuery.css;
-
-jQuery.each(["height", "width"], function( i, name ) {
-	jQuery.cssHooks[ name ] = {
-		get: function( elem, computed, extra ) {
-			var val;
-
-			if ( computed ) {
-				if ( elem.offsetWidth !== 0 ) {
-					return getWH( elem, name, extra );
-				} else {
-					jQuery.swap( elem, cssShow, function() {
-						val = getWH( elem, name, extra );
-					});
-				}
-
-				return val;
-			}
-		},
-
-		set: function( elem, value ) {
-			if ( rnumpx.test( value ) ) {
-				// ignore negative width and height values #1599
-				value = parseFloat( value );
-
-				if ( value >= 0 ) {
-					return value + "px";
-				}
-
-			} else {
-				return value;
-			}
-		}
-	};
-});
-
-if ( !jQuery.support.opacity ) {
-	jQuery.cssHooks.opacity = {
-		get: function( elem, computed ) {
-			// IE uses filters for opacity
-			return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
-				( parseFloat( RegExp.$1 ) / 100 ) + "" :
-				computed ? "1" : "";
-		},
-
-		set: function( elem, value ) {
-			var style = elem.style,
-				currentStyle = elem.currentStyle,
-				opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
-				filter = currentStyle && currentStyle.filter || style.filter || "";
-
-			// IE has trouble with opacity if it does not have layout
-			// Force it by setting the zoom level
-			style.zoom = 1;
-
-			// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
-			if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {
-
-				// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
-				// if "filter:" is present at all, clearType is disabled, we want to avoid this
-				// style.removeAttribute is IE Only, but so apparently is this code path...
-				style.removeAttribute( "filter" );
-
-				// if there there is no filter style applied in a css rule, we are done
-				if ( currentStyle && !currentStyle.filter ) {
-					return;
-				}
-			}
-
-			// otherwise, set new filter values
-			style.filter = ralpha.test( filter ) ?
-				filter.replace( ralpha, opacity ) :
-				filter + " " + opacity;
-		}
-	};
-}
-
-jQuery(function() {
-	// This hook cannot be added until DOM ready because the support test
-	// for it is not run until after DOM ready
-	if ( !jQuery.support.reliableMarginRight ) {
-		jQuery.cssHooks.marginRight = {
-			get: function( elem, computed ) {
-				// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
-				// Work around by temporarily setting element display to inline-block
-				var ret;
-				jQuery.swap( elem, { "display": "inline-block" }, function() {
-					if ( computed ) {
-						ret = curCSS( elem, "margin-right", "marginRight" );
-					} else {
-						ret = elem.style.marginRight;
-					}
-				});
-				return ret;
-			}
-		};
-	}
-});
-
-if ( document.defaultView && document.defaultView.getComputedStyle ) {
-	getComputedStyle = function( elem, name ) {
-		var ret, defaultView, computedStyle;
-
-		name = name.replace( rupper, "-$1" ).toLowerCase();
-
-		if ( (defaultView = elem.ownerDocument.defaultView) &&
-				(computedStyle = defaultView.getComputedStyle( elem, null )) ) {
-			ret = computedStyle.getPropertyValue( name );
-			if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
-				ret = jQuery.style( elem, name );
-			}
-		}
-
-		return ret;
-	};
-}
-
-if ( document.documentElement.currentStyle ) {
-	currentStyle = function( elem, name ) {
-		var left, rsLeft, uncomputed,
-			ret = elem.currentStyle && elem.currentStyle[ name ],
-			style = elem.style;
-
-		// Avoid setting ret to empty string here
-		// so we don't default to auto
-		if ( ret === null && style && (uncomputed = style[ name ]) ) {
-			ret = uncomputed;
-		}
-
-		// From the awesome hack by Dean Edwards
-		// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
-
-		// If we're not dealing with a regular pixel number
-		// but a number that has a weird ending, we need to convert it to pixels
-		if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
-
-			// Remember the original values
-			left = style.left;
-			rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
-
-			// Put in the new values to get a computed value out
-			if ( rsLeft ) {
-				elem.runtimeStyle.left = elem.currentStyle.left;
-			}
-			style.left = name === "fontSize" ? "1em" : ( ret || 0 );
-			ret = style.pixelLeft + "px";
-
-			// Revert the changed values
-			style.left = left;
-			if ( rsLeft ) {
-				elem.runtimeStyle.left = rsLeft;
-			}
-		}
-
-		return ret === "" ? "auto" : ret;
-	};
-}
-
-curCSS = getComputedStyle || currentStyle;
-
-function getWH( elem, name, extra ) {
-
-	// Start with offset property
-	var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
-		which = name === "width" ? cssWidth : cssHeight,
-		i = 0,
-		len = which.length;
-
-	if ( val > 0 ) {
-		if ( extra !== "border" ) {
-			for ( ; i < len; i++ ) {
-				if ( !extra ) {
-					val -= parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0;
-				}
-				if ( extra === "margin" ) {
-					val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0;
-				} else {
-					val -= parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0;
-				}
-			}
-		}
-
-		return val + "px";
-	}
-
-	// Fall back to computed then uncomputed css if necessary
-	val = curCSS( elem, name, name );
-	if ( val < 0 || val == null ) {
-		val = elem.style[ name ] || 0;
-	}
-	// Normalize "", auto, and prepare for extra
-	val = parseFloat( val ) || 0;
-
-	// Add padding, border, margin
-	if ( extra ) {
-		for ( ; i < len; i++ ) {
-			val += parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0;
-			if ( extra !== "padding" ) {
-				val += parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0;
-			}
-			if ( extra === "margin" ) {
-				val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0;
-			}
-		}
-	}
-
-	return val + "px";
-}
-
-if ( jQuery.expr && jQuery.expr.filters ) {
-	jQuery.expr.filters.hidden = function( elem ) {
-		var width = elem.offsetWidth,
-			height = elem.offsetHeight;
-
-		return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
-	};
-
-	jQuery.expr.filters.visible = function( elem ) {
-		return !jQuery.expr.filters.hidden( elem );
-	};
-}
-
-
-
-
-var r20 = /%20/g,
-	rbracket = /\[\]$/,
-	rCRLF = /\r?\n/g,
-	rhash = /#.*$/,
-	rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
-	rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
-	// #7653, #8125, #8152: local protocol detection
-	rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
-	rnoContent = /^(?:GET|HEAD)$/,
-	rprotocol = /^\/\//,
-	rquery = /\?/,
-	rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
-	rselectTextarea = /^(?:select|textarea)/i,
-	rspacesAjax = /\s+/,
-	rts = /([?&])_=[^&]*/,
-	rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
-
-	// Keep a copy of the old load method
-	_load = jQuery.fn.load,
-
-	/* Prefilters
-	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
-	 * 2) These are called:
-	 *    - BEFORE asking for a transport
-	 *    - AFTER param serialization (s.data is a string if s.processData is true)
-	 * 3) key is the dataType
-	 * 4) the catchall symbol "*" can be used
-	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
-	 */
-	prefilters = {},
-
-	/* Transports bindings
-	 * 1) key is the dataType
-	 * 2) the catchall symbol "*" can be used
-	 * 3) selection will start with transport dataType and THEN go to "*" if needed
-	 */
-	transports = {},
-
-	// Document location
-	ajaxLocation,
-
-	// Document location segments
-	ajaxLocParts,
-
-	// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
-	allTypes = ["*/"] + ["*"];
+    jQuery.curCSS = jQuery.css;
+
+    jQuery.each(["height", "width"], function (i, name) {
+        jQuery.cssHooks[ name ] = {
+            get: function (elem, computed, extra) {
+                var val;
+
+                if (computed) {
+                    if (elem.offsetWidth !== 0) {
+                        return getWH(elem, name, extra);
+                    } else {
+                        jQuery.swap(elem, cssShow, function () {
+                            val = getWH(elem, name, extra);
+                        });
+                    }
+
+                    return val;
+                }
+            },
+
+            set: function (elem, value) {
+                if (rnumpx.test(value)) {
+                    // ignore negative width and height values #1599
+                    value = parseFloat(value);
+
+                    if (value >= 0) {
+                        return value + "px";
+                    }
+
+                } else {
+                    return value;
+                }
+            }
+        };
+    });
+
+    if (!jQuery.support.opacity) {
+        jQuery.cssHooks.opacity = {
+            get: function (elem, computed) {
+                // IE uses filters for opacity
+                return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ?
+                    ( parseFloat(RegExp.$1) / 100 ) + "" :
+                    computed ? "1" : "";
+            },
+
+            set: function (elem, value) {
+                var style = elem.style,
+                    currentStyle = elem.currentStyle,
+                    opacity = jQuery.isNumeric(value) ? "alpha(opacity=" + value * 100 + ")" : "",
+                    filter = currentStyle && currentStyle.filter || style.filter || "";
+
+                // IE has trouble with opacity if it does not have layout
+                // Force it by setting the zoom level
+                style.zoom = 1;
+
+                // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
+                if (value >= 1 && jQuery.trim(filter.replace(ralpha, "")) === "") {
+
+                    // Setting style.filter to null, "" & " " still leave "filter:" in the cssText
+                    // if "filter:" is present at all, clearType is disabled, we want to avoid this
+                    // style.removeAttribute is IE Only, but so apparently is this code path...
+                    style.removeAttribute("filter");
+
+                    // if there there is no filter style applied in a css rule, we are done
+                    if (currentStyle && !currentStyle.filter) {
+                        return;
+                    }
+                }
+
+                // otherwise, set new filter values
+                style.filter = ralpha.test(filter) ?
+                    filter.replace(ralpha, opacity) :
+                    filter + " " + opacity;
+            }
+        };
+    }
+
+    jQuery(function () {
+        // This hook cannot be added until DOM ready because the support test
+        // for it is not run until after DOM ready
+        if (!jQuery.support.reliableMarginRight) {
+            jQuery.cssHooks.marginRight = {
+                get: function (elem, computed) {
+                    // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
+                    // Work around by temporarily setting element display to inline-block
+                    var ret;
+                    jQuery.swap(elem, { "display": "inline-block" }, function () {
+                        if (computed) {
+                            ret = curCSS(elem, "margin-right", "marginRight");
+                        } else {
+                            ret = elem.style.marginRight;
+                        }
+                    });
+                    return ret;
+                }
+            };
+        }
+    });
+
+    if (document.defaultView && document.defaultView.getComputedStyle) {
+        getComputedStyle = function (elem, name) {
+            var ret, defaultView, computedStyle;
+
+            name = name.replace(rupper, "-$1").toLowerCase();
+
+            if ((defaultView = elem.ownerDocument.defaultView) &&
+                (computedStyle = defaultView.getComputedStyle(elem, null))) {
+                ret = computedStyle.getPropertyValue(name);
+                if (ret === "" && !jQuery.contains(elem.ownerDocument.documentElement, elem)) {
+                    ret = jQuery.style(elem, name);
+                }
+            }
+
+            return ret;
+        };
+    }
+
+    if (document.documentElement.currentStyle) {
+        currentStyle = function (elem, name) {
+            var left, rsLeft, uncomputed,
+                ret = elem.currentStyle && elem.currentStyle[ name ],
+                style = elem.style;
+
+            // Avoid setting ret to empty string here
+            // so we don't default to auto
+            if (ret === null && style && (uncomputed = style[ name ])) {
+                ret = uncomputed;
+            }
+
+            // From the awesome hack by Dean Edwards
+            // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
+
+            // If we're not dealing with a regular pixel number
+            // but a number that has a weird ending, we need to convert it to pixels
+            if (!rnumpx.test(ret) && rnum.test(ret)) {
+
+                // Remember the original values
+                left = style.left;
+                rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
+
+                // Put in the new values to get a computed value out
+                if (rsLeft) {
+                    elem.runtimeStyle.left = elem.currentStyle.left;
+                }
+                style.left = name === "fontSize" ? "1em" : ( ret || 0 );
+                ret = style.pixelLeft + "px";
+
+                // Revert the changed values
+                style.left = left;
+                if (rsLeft) {
+                    elem.runtimeStyle.left = rsLeft;
+                }
+            }
+
+            return ret === "" ? "auto" : ret;
+        };
+    }
+
+    curCSS = getComputedStyle || currentStyle;
+
+    function getWH(elem, name, extra) {
+
+        // Start with offset property
+        var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
+            which = name === "width" ? cssWidth : cssHeight,
+            i = 0,
+            len = which.length;
+
+        if (val > 0) {
+            if (extra !== "border") {
+                for (; i < len; i++) {
+                    if (!extra) {
+                        val -= parseFloat(jQuery.css(elem, "padding" + which[ i ])) || 0;
+                    }
+                    if (extra === "margin") {
+                        val += parseFloat(jQuery.css(elem, extra + which[ i ])) || 0;
+                    } else {
+                        val -= parseFloat(jQuery.css(elem, "border" + which[ i ] + "Width")) || 0;
+                    }
+                }
+            }
+
+            return val + "px";
+        }
+
+        // Fall back to computed then uncomputed css if necessary
+        val = curCSS(elem, name, name);
+        if (val < 0 || val == null) {
+            val = elem.style[ name ] || 0;
+        }
+        // Normalize "", auto, and prepare for extra
+        val = parseFloat(val) || 0;
+
+        // Add padding, border, margin
+        if (extra) {
+            for (; i < len; i++) {
+                val += parseFloat(jQuery.css(elem, "padding" + which[ i ])) || 0;
+                if (extra !== "padding") {
+                    val += parseFloat(jQuery.css(elem, "border" + which[ i ] + "Width")) || 0;
+                }
+                if (extra === "margin") {
+                    val += parseFloat(jQuery.css(elem, extra + which[ i ])) || 0;
+                }
+            }
+        }
+
+        return val + "px";
+    }
+
+    if (jQuery.expr && jQuery.expr.filters) {
+        jQuery.expr.filters.hidden = function (elem) {
+            var width = elem.offsetWidth,
+                height = elem.offsetHeight;
+
+            return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css(elem, "display")) === "none");
+        };
+
+        jQuery.expr.filters.visible = function (elem) {
+            return !jQuery.expr.filters.hidden(elem);
+        };
+    }
+
+
+    var r20 = /%20/g,
+        rbracket = /\[\]$/,
+        rCRLF = /\r?\n/g,
+        rhash = /#.*$/,
+        rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
+        rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
+    // #7653, #8125, #8152: local protocol detection
+        rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
+        rnoContent = /^(?:GET|HEAD)$/,
+        rprotocol = /^\/\//,
+        rquery = /\?/,
+        rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
+        rselectTextarea = /^(?:select|textarea)/i,
+        rspacesAjax = /\s+/,
+        rts = /([?&])_=[^&]*/,
+        rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
+
+    // Keep a copy of the old load method
+        _load = jQuery.fn.load,
+
+    /* Prefilters
+     * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
+     * 2) These are called:
+     *    - BEFORE asking for a transport
+     *    - AFTER param serialization (s.data is a string if s.processData is true)
+     * 3) key is the dataType
+     * 4) the catchall symbol "*" can be used
+     * 5) execution will start with transport dataType and THEN continue down to "*" if needed
+     */
+        prefilters = {},
+
+    /* Transports bindings
+     * 1) key is the dataType
+     * 2) the catchall symbol "*" can be used
+     * 3) selection will start with transport dataType and THEN go to "*" if needed
+     */
+        transports = {},
+
+    // Document location
+        ajaxLocation,
+
+    // Document location segments
+        ajaxLocParts,
+
+    // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
+        allTypes = ["*/"] + ["*"];
 
 // #8138, IE may throw an exception when accessing
 // a field from window.location if document.domain has been set
-try {
-	ajaxLocation = location.href;
-} catch( e ) {
-	// Use the href attribute of an A element
-	// since IE will modify it given document.location
-	ajaxLocation = document.createElement( "a" );
-	ajaxLocation.href = "";
-	ajaxLocation = ajaxLocation.href;
-}
+    try {
+        ajaxLocation = location.href;
+    } catch (e) {
+        // Use the href attribute of an A element
+        // since IE will modify it given document.location
+        ajaxLocation = document.createElement("a");
+        ajaxLocation.href = "";
+        ajaxLocation = ajaxLocation.href;
+    }
 
 // Segment location into parts
-ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
+    ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || [];
 
 // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
-function addToPrefiltersOrTransports( structure ) {
-
-	// dataTypeExpression is optional and defaults to "*"
-	return function( dataTypeExpression, func ) {
-
-		if ( typeof dataTypeExpression !== "string" ) {
-			func = dataTypeExpression;
-			dataTypeExpression = "*";
-		}
-
-		if ( jQuery.isFunction( func ) ) {
-			var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
-				i = 0,
-				length = dataTypes.length,
-				dataType,
-				list,
-				placeBefore;
-
-			// For each dataType in the dataTypeExpression
-			for ( ; i < length; i++ ) {
-				dataType = dataTypes[ i ];
-				// We control if we're asked to add before
-				// any existing element
-				placeBefore = /^\+/.test( dataType );
-				if ( placeBefore ) {
-					dataType = dataType.substr( 1 ) || "*";
-				}
-				list = structure[ dataType ] = structure[ dataType ] || [];
-				// then we add to the structure accordingly
-				list[ placeBefore ? "unshift" : "push" ]( func );
-			}
-		}
-	};
-}
+    function addToPrefiltersOrTransports(structure) {
+
+        // dataTypeExpression is optional and defaults to "*"
+        return function (dataTypeExpression, func) {
+
+            if (typeof dataTypeExpression !== "string") {
+                func = dataTypeExpression;
+                dataTypeExpression = "*";
+            }
+
+            if (jQuery.isFunction(func)) {
+                var dataTypes = dataTypeExpression.toLowerCase().split(rspacesAjax),
+                    i = 0,
+                    length = dataTypes.length,
+                    dataType,
+                    list,
+                    placeBefore;
+
+                // For each dataType in the dataTypeExpression
+                for (; i < length; i++) {
+                    dataType = dataTypes[ i ];
+                    // We control if we're asked to add before
+                    // any existing element
+                    placeBefore = /^\+/.test(dataType);
+                    if (placeBefore) {
+                        dataType = dataType.substr(1) || "*";
+                    }
+                    list = structure[ dataType ] = structure[ dataType ] || [];
+                    // then we add to the structure accordingly
+                    list[ placeBefore ? "unshift" : "push" ](func);
+                }
+            }
+        };
+    }
 
 // Base inspection function for prefilters and transports
-function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
-		dataType /* internal */, inspected /* internal */ ) {
-
-	dataType = dataType || options.dataTypes[ 0 ];
-	inspected = inspected || {};
-
-	inspected[ dataType ] = true;
-
-	var list = structure[ dataType ],
-		i = 0,
-		length = list ? list.length : 0,
-		executeOnly = ( structure === prefilters ),
-		selection;
-
-	for ( ; i < length && ( executeOnly || !selection ); i++ ) {
-		selection = list[ i ]( options, originalOptions, jqXHR );
-		// If we got redirected to another dataType
-		// we try there if executing only and not done already
-		if ( typeof selection === "string" ) {
-			if ( !executeOnly || inspected[ selection ] ) {
-				selection = undefined;
-			} else {
-				options.dataTypes.unshift( selection );
-				selection = inspectPrefiltersOrTransports(
-						structure, options, originalOptions, jqXHR, selection, inspected );
-			}
-		}
-	}
-	// If we're only executing or nothing was selected
-	// we try the catchall dataType if not done already
-	if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
-		selection = inspectPrefiltersOrTransports(
-				structure, options, originalOptions, jqXHR, "*", inspected );
-	}
-	// unnecessary when only executing (prefilters)
-	// but it'll be ignored by the caller in that case
-	return selection;
-}
+    function inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */) {
+
+        dataType = dataType || options.dataTypes[ 0 ];
+        inspected = inspected || {};
+
+        inspected[ dataType ] = true;
+
+        var list = structure[ dataType ],
+            i = 0,
+            length = list ? list.length : 0,
+            executeOnly = ( structure === prefilters ),
+            selection;
+
+        for (; i < length && ( executeOnly || !selection ); i++) {
+            selection = list[ i ](options, originalOptions, jqXHR);
+            // If we got redirected to another dataType
+            // we try there if executing only and not done already
+            if (typeof selection === "string") {
+                if (!executeOnly || inspected[ selection ]) {
+                    selection = undefined;
+                } else {
+                    options.dataTypes.unshift(selection);
+                    selection = inspectPrefiltersOrTransports(
+                        structure, options, originalOptions, jqXHR, selection, inspected);
+                }
+            }
+        }
+        // If we're only executing or nothing was selected
+        // we try the catchall dataType if not done already
+        if (( executeOnly || !selection ) && !inspected[ "*" ]) {
+            selection = inspectPrefiltersOrTransports(
+                structure, options, originalOptions, jqXHR, "*", inspected);
+        }
+        // unnecessary when only executing (prefilters)
+        // but it'll be ignored by the caller in that case
+        return selection;
+    }
 
 // A special extend for ajax options
 // that takes "flat" options (not to be deep extended)
 // Fixes #9887
-function ajaxExtend( target, src ) {
-	var key, deep,
-		flatOptions = jQuery.ajaxSettings.flatOptions || {};
-	for ( key in src ) {
-		if ( src[ key ] !== undefined ) {
-			( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
-		}
-	}
-	if ( deep ) {
-		jQuery.extend( true, target, deep );
-	}
-}
-
-jQuery.fn.extend({
-	load: function( url, params, callback ) {
-		if ( typeof url !== "string" && _load ) {
-			return _load.apply( this, arguments );
-
-		// Don't do a request if no elements are being requested
-		} else if ( !this.length ) {
-			return this;
-		}
-
-		var off = url.indexOf( " " );
-		if ( off >= 0 ) {
-			var selector = url.slice( off, url.length );
-			url = url.slice( 0, off );
-		}
-
-		// Default to a GET request
-		var type = "GET";
-
-		// If the second parameter was provided
-		if ( params ) {
-			// If it's a function
-			if ( jQuery.isFunction( params ) ) {
-				// We assume that it's the callback
-				callback = params;
-				params = undefined;
-
-			// Otherwise, build a param string
-			} else if ( typeof params === "object" ) {
-				params = jQuery.param( params, jQuery.ajaxSettings.traditional );
-				type = "POST";
-			}
-		}
-
-		var self = this;
-
-		// Request the remote document
-		jQuery.ajax({
-			url: url,
-			type: type,
-			dataType: "html",
-			data: params,
-			// Complete callback (responseText is used internally)
-			complete: function( jqXHR, status, responseText ) {
-				// Store the response as specified by the jqXHR object
-				responseText = jqXHR.responseText;
-				// If successful, inject the HTML into all the matched elements
-				if ( jqXHR.isResolved() ) {
-					// #4825: Get the actual response in case
-					// a dataFilter is present in ajaxSettings
-					jqXHR.done(function( r ) {
-						responseText = r;
-					});
-					// See if a selector was specified
-					self.html( selector ?
-						// Create a dummy div to hold the results
-						jQuery("<div>")
-							// inject the contents of the document in, removing the scripts
-							// to avoid any 'Permission Denied' errors in IE
-							.append(responseText.replace(rscript, ""))
-
-							// Locate the specified elements
-							.find(selector) :
-
-						// If not, just inject the full result
-						responseText );
-				}
-
-				if ( callback ) {
-					self.each( callback, [ responseText, status, jqXHR ] );
-				}
-			}
-		});
-
-		return this;
-	},
-
-	serialize: function() {
-		return jQuery.param( this.serializeArray() );
-	},
-
-	serializeArray: function() {
-		return this.map(function(){
-			return this.elements ? jQuery.makeArray( this.elements ) : this;
-		})
-		.filter(function(){
-			return this.name && !this.disabled &&
-				( this.checked || rselectTextarea.test( this.nodeName ) ||
-					rinput.test( this.type ) );
-		})
-		.map(function( i, elem ){
-			var val = jQuery( this ).val();
-
-			return val == null ?
-				null :
-				jQuery.isArray( val ) ?
-					jQuery.map( val, function( val, i ){
-						return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
-					}) :
-					{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
-		}).get();
-	}
-});
+    function ajaxExtend(target, src) {
+        var key, deep,
+            flatOptions = jQuery.ajaxSettings.flatOptions || {};
+        for (key in src) {
+            if (src[ key ] !== undefined) {
+                ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
+            }
+        }
+        if (deep) {
+            jQuery.extend(true, target, deep);
+        }
+    }
+
+    jQuery.fn.extend({
+        load: function (url, params, callback) {
+            if (typeof url !== "string" && _load) {
+                return _load.apply(this, arguments);
+
+                // Don't do a request if no elements are being requested
+            } else if (!this.length) {
+                return this;
+            }
+
+            var off = url.indexOf(" ");
+            if (off >= 0) {
+                var selector = url.slice(off, url.length);
+                url = url.slice(0, off);
+            }
+
+            // Default to a GET request
+            var type = "GET";
+
+            // If the second parameter was provided
+            if (params) {
+                // If it's a function
+                if (jQuery.isFunction(params)) {
+                    // We assume that it's the callback
+                    callback = params;
+                    params = undefined;
+
+                    // Otherwise, build a param string
+                } else if (typeof params === "object") {
+                    params = jQuery.param(params, jQuery.ajaxSettings.traditional);
+                    type = "POST";
+                }
+            }
+
+            var self = this;
+
+            // Request the remote document
+            jQuery.ajax({
+                url: url,
+                type: type,
+                dataType: "html",
+                data: params,
+                // Complete callback (responseText is used internally)
+                complete: function (jqXHR, status, responseText) {
+                    // Store the response as specified by the jqXHR object
+                    responseText = jqXHR.responseText;
+                    // If successful, inject the HTML into all the matched elements
+                    if (jqXHR.isResolved()) {
+                        // #4825: Get the actual response in case
+                        // a dataFilter is present in ajaxSettings
+                        jqXHR.done(function (r) {
+                            responseText = r;
+                        });
+                        // See if a selector was specified
+                        self.html(selector ?
+                            // Create a dummy div to hold the results
+                            jQuery("<div>")
+                                // inject the contents of the document in, removing the scripts
+                                // to avoid any 'Permission Denied' errors in IE
+                                .append(responseText.replace(rscript, ""))
+
+                                // Locate the specified elements
+                                .find(selector) :
+
+                            // If not, just inject the full result
+                            responseText);
+                    }
+
+                    if (callback) {
+                        self.each(callback, [ responseText, status, jqXHR ]);
+                    }
+                }
+            });
+
+            return this;
+        },
+
+        serialize: function () {
+            return jQuery.param(this.serializeArray());
+        },
+
+        serializeArray: function () {
+            return this.map(function () {
+                return this.elements ? jQuery.makeArray(this.elements) : this;
+            })
+                .filter(function () {
+                    return this.name && !this.disabled &&
+                        ( this.checked || rselectTextarea.test(this.nodeName) ||
+                            rinput.test(this.type) );
+                })
+                .map(function (i, elem) {
+                    var val = jQuery(this).val();
+
+                    return val == null ?
+                        null :
+                        jQuery.isArray(val) ?
+                            jQuery.map(val, function (val, i) {
+                                return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
+                            }) :
+                        { name: elem.name, value: val.replace(rCRLF, "\r\n") };
+                }).get();
+        }
+    });
 
 // Attach a bunch of functions for handling common AJAX events
-jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
-	jQuery.fn[ o ] = function( f ){
-		return this.on( o, f );
-	};
-});
-
-jQuery.each( [ "get", "post" ], function( i, method ) {
-	jQuery[ method ] = function( url, data, callback, type ) {
-		// shift arguments if data argument was omitted
-		if ( jQuery.isFunction( data ) ) {
-			type = type || callback;
-			callback = data;
-			data = undefined;
-		}
-
-		return jQuery.ajax({
-			type: method,
-			url: url,
-			data: data,
-			success: callback,
-			dataType: type
-		});
-	};
-});
-
-jQuery.extend({
-
-	getScript: function( url, callback ) {
-		return jQuery.get( url, undefined, callback, "script" );
-	},
-
-	getJSON: function( url, data, callback ) {
-		return jQuery.get( url, data, callback, "json" );
-	},
-
-	// Creates a full fledged settings object into target
-	// with both ajaxSettings and settings fields.
-	// If target is omitted, writes into ajaxSettings.
-	ajaxSetup: function( target, settings ) {
-		if ( settings ) {
-			// Building a settings object
-			ajaxExtend( target, jQuery.ajaxSettings );
-		} else {
-			// Extending ajaxSettings
-			settings = target;
-			target = jQuery.ajaxSettings;
-		}
-		ajaxExtend( target, settings );
-		return target;
-	},
-
-	ajaxSettings: {
-		url: ajaxLocation,
-		isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
-		global: true,
-		type: "GET",
-		contentType: "application/x-www-form-urlencoded",
-		processData: true,
-		async: true,
-		/*
-		timeout: 0,
-		data: null,
-		dataType: null,
-		username: null,
-		password: null,
-		cache: null,
-		traditional: false,
-		headers: {},
-		*/
-
-		accepts: {
-			xml: "application/xml, text/xml",
-			html: "text/html",
-			text: "text/plain",
-			json: "application/json, text/javascript",
-			"*": allTypes
-		},
-
-		contents: {
-			xml: /xml/,
-			html: /html/,
-			json: /json/
-		},
-
-		responseFields: {
-			xml: "responseXML",
-			text: "responseText"
-		},
-
-		// List of data converters
-		// 1) key format is "source_type destination_type" (a single space in-between)
-		// 2) the catchall symbol "*" can be used for source_type
-		converters: {
-
-			// Convert anything to text
-			"* text": window.String,
-
-			// Text to html (true = no transformation)
-			"text html": true,
-
-			// Evaluate text as a json expression
-			"text json": jQuery.parseJSON,
-
-			// Parse text as xml
-			"text xml": jQuery.parseXML
-		},
-
-		// For options that shouldn't be deep extended:
-		// you can add your own custom options here if
-		// and when you create one that shouldn't be
-		// deep extended (see ajaxExtend)
-		flatOptions: {
-			context: true,
-			url: true
-		}
-	},
-
-	ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
-	ajaxTransport: addToPrefiltersOrTransports( transports ),
-
-	// Main method
-	ajax: function( url, options ) {
-
-		// If url is an object, simulate pre-1.5 signature
-		if ( typeof url === "object" ) {
-			options = url;
-			url = undefined;
-		}
-
-		// Force options to be an object
-		options = options || {};
-
-		var // Create the final options object
-			s = jQuery.ajaxSetup( {}, options ),
-			// Callbacks context
-			callbackContext = s.context || s,
-			// Context for global events
-			// It's the callbackContext if one was provided in the options
-			// and if it's a DOM node or a jQuery collection
-			globalEventContext = callbackContext !== s &&
-				( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
-						jQuery( callbackContext ) : jQuery.event,
-			// Deferreds
-			deferred = jQuery.Deferred(),
-			completeDeferred = jQuery.Callbacks( "once memory" ),
-			// Status-dependent callbacks
-			statusCode = s.statusCode || {},
-			// ifModified key
-			ifModifiedKey,
-			// Headers (they are sent all at once)
-			requestHeaders = {},
-			requestHeadersNames = {},
-			// Response headers
-			responseHeadersString,
-			responseHeaders,
-			// transport
-			transport,
-			// timeout handle
-			timeoutTimer,
-			// Cross-domain detection vars
-			parts,
-			// The jqXHR state
-			state = 0,
-			// To know if global events are to be dispatched
-			fireGlobals,
-			// Loop variable
-			i,
-			// Fake xhr
-			jqXHR = {
-
-				readyState: 0,
-
-				// Caches the header
-				setRequestHeader: function( name, value ) {
-					if ( !state ) {
-						var lname = name.toLowerCase();
-						name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
-						requestHeaders[ name ] = value;
-					}
-					return this;
-				},
-
-				// Raw string
-				getAllResponseHeaders: function() {
-					return state === 2 ? responseHeadersString : null;
-				},
-
-				// Builds headers hashtable if needed
-				getResponseHeader: function( key ) {
-					var match;
-					if ( state === 2 ) {
-						if ( !responseHeaders ) {
-							responseHeaders = {};
-							while( ( match = rheaders.exec( responseHeadersString ) ) ) {
-								responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
-							}
-						}
-						match = responseHeaders[ key.toLowerCase() ];
-					}
-					return match === undefined ? null : match;
-				},
-
-				// Overrides response content-type header
-				overrideMimeType: function( type ) {
-					if ( !state ) {
-						s.mimeType = type;
-					}
-					return this;
-				},
-
-				// Cancel the request
-				abort: function( statusText ) {
-					statusText = statusText || "abort";
-					if ( transport ) {
-						transport.abort( statusText );
-					}
-					done( 0, statusText );
-					return this;
-				}
-			};
-
-		// Callback for when everything is done
-		// It is defined here because jslint complains if it is declared
-		// at the end of the function (which would be more logical and readable)
-		function done( status, nativeStatusText, responses, headers ) {
-
-			// Called once
-			if ( state === 2 ) {
-				return;
-			}
-
-			// State is "done" now
-			state = 2;
-
-			// Clear timeout if it exists
-			if ( timeoutTimer ) {
-				clearTimeout( timeoutTimer );
-			}
-
-			// Dereference transport for early garbage collection
-			// (no matter how long the jqXHR object will be used)
-			transport = undefined;
-
-			// Cache response headers
-			responseHeadersString = headers || "";
-
-			// Set readyState
-			jqXHR.readyState = status > 0 ? 4 : 0;
-
-			var isSuccess,
-				success,
-				error,
-				statusText = nativeStatusText,
-				response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
-				lastModified,
-				etag;
-
-			// If successful, handle type chaining
-			if ( status >= 200 && status < 300 || status === 304 ) {
-
-				// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
-				if ( s.ifModified ) {
-
-					if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
-						jQuery.lastModified[ ifModifiedKey ] = lastModified;
-					}
-					if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
-						jQuery.etag[ ifModifiedKey ] = etag;
-					}
-				}
-
-				// If not modified
-				if ( status === 304 ) {
-
-					statusText = "notmodified";
-					isSuccess = true;
-
-				// If we have data
-				} else {
-
-					try {
-						success = ajaxConvert( s, response );
-						statusText = "success";
-						isSuccess = true;
-					} catch(e) {
-						// We have a parsererror
-						statusText = "parsererror";
-						error = e;
-					}
-				}
-			} else {
-				// We extract error from statusText
-				// then normalize statusText and status for non-aborts
-				error = statusText;
-				if ( !statusText || status ) {
-					statusText = "error";
-					if ( status < 0 ) {
-						status = 0;
-					}
-				}
-			}
-
-			// Set data for the fake xhr object
-			jqXHR.status = status;
-			jqXHR.statusText = "" + ( nativeStatusText || statusText );
-
-			// Success/Error
-			if ( isSuccess ) {
-				deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
-			} else {
-				deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
-			}
-
-			// Status-dependent callbacks
-			jqXHR.statusCode( statusCode );
-			statusCode = undefined;
-
-			if ( fireGlobals ) {
-				globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
-						[ jqXHR, s, isSuccess ? success : error ] );
-			}
-
-			// Complete
-			completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
-
-			if ( fireGlobals ) {
-				globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
-				// Handle the global AJAX counter
-				if ( !( --jQuery.active ) ) {
-					jQuery.event.trigger( "ajaxStop" );
-				}
-			}
-		}
-
-		// Attach deferreds
-		deferred.promise( jqXHR );
-		jqXHR.success = jqXHR.done;
-		jqXHR.error = jqXHR.fail;
-		jqXHR.complete = completeDeferred.add;
-
-		// Status-dependent callbacks
-		jqXHR.statusCode = function( map ) {
-			if ( map ) {
-				var tmp;
-				if ( state < 2 ) {
-					for ( tmp in map ) {
-						statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
-					}
-				} else {
-					tmp = map[ jqXHR.status ];
-					jqXHR.then( tmp, tmp );
-				}
-			}
-			return this;
-		};
-
-		// Remove hash character (#7531: and string promotion)
-		// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
-		// We also use the url parameter if available
-		s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
-
-		// Extract dataTypes list
-		s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
-
-		// Determine if a cross-domain request is in order
-		if ( s.crossDomain == null ) {
-			parts = rurl.exec( s.url.toLowerCase() );
-			s.crossDomain = !!( parts &&
-				( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
-					( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
-						( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
-			);
-		}
-
-		// Convert data if not already a string
-		if ( s.data && s.processData && typeof s.data !== "string" ) {
-			s.data = jQuery.param( s.data, s.traditional );
-		}
-
-		// Apply prefilters
-		inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
-
-		// If request was aborted inside a prefiler, stop there
-		if ( state === 2 ) {
-			return false;
-		}
-
-		// We can fire global events as of now if asked to
-		fireGlobals = s.global;
-
-		// Uppercase the type
-		s.type = s.type.toUpperCase();
-
-		// Determine if request has content
-		s.hasContent = !rnoContent.test( s.type );
-
-		// Watch for a new set of requests
-		if ( fireGlobals && jQuery.active++ === 0 ) {
-			jQuery.event.trigger( "ajaxStart" );
-		}
-
-		// More options handling for requests with no content
-		if ( !s.hasContent ) {
-
-			// If data is available, append data to url
-			if ( s.data ) {
-				s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
-				// #9682: remove data so that it's not used in an eventual retry
-				delete s.data;
-			}
-
-			// Get ifModifiedKey before adding the anti-cache parameter
-			ifModifiedKey = s.url;
-
-			// Add anti-cache in url if needed
-			if ( s.cache === false ) {
-
-				var ts = jQuery.now(),
-					// try replacing _= if it is there
-					ret = s.url.replace( rts, "$1_=" + ts );
-
-				// if nothing was replaced, add timestamp to the end
-				s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
-			}
-		}
-
-		// Set the correct header, if data is being sent
-		if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
-			jqXHR.setRequestHeader( "Content-Type", s.contentType );
-		}
-
-		// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
-		if ( s.ifModified ) {
-			ifModifiedKey = ifModifiedKey || s.url;
-			if ( jQuery.lastModified[ ifModifiedKey ] ) {
-				jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
-			}
-			if ( jQuery.etag[ ifModifiedKey ] ) {
-				jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
-			}
-		}
-
-		// Set the Accepts header for the server, depending on the dataType
-		jqXHR.setRequestHeader(
-			"Accept",
-			s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
-				s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
-				s.accepts[ "*" ]
-		);
-
-		// Check for headers option
-		for ( i in s.headers ) {
-			jqXHR.setRequestHeader( i, s.headers[ i ] );
-		}
-
-		// Allow custom headers/mimetypes and early abort
-		if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
-				// Abort if not done already
-				jqXHR.abort();
-				return false;
-
-		}
-
-		// Install callbacks on deferreds
-		for ( i in { success: 1, error: 1, complete: 1 } ) {
-			jqXHR[ i ]( s[ i ] );
-		}
-
-		// Get transport
-		transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
-
-		// If no transport, we auto-abort
-		if ( !transport ) {
-			done( -1, "No Transport" );
-		} else {
-			jqXHR.readyState = 1;
-			// Send global event
-			if ( fireGlobals ) {
-				globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
-			}
-			// Timeout
-			if ( s.async && s.timeout > 0 ) {
-				timeoutTimer = setTimeout( function(){
-					jqXHR.abort( "timeout" );
-				}, s.timeout );
-			}
-
-			try {
-				state = 1;
-				transport.send( requestHeaders, done );
-			} catch (e) {
-				// Propagate exception as error if not done
-				if ( state < 2 ) {
-					done( -1, e );
-				// Simply rethrow otherwise
-				} else {
-					throw e;
-				}
-			}
-		}
-
-		return jqXHR;
-	},
-
-	// Serialize an array of form elements or a set of
-	// key/values into a query string
-	param: function( a, traditional ) {
-		var s = [],
-			add = function( key, value ) {
-				// If value is a function, invoke it and return its value
-				value = jQuery.isFunction( value ) ? value() : value;
-				s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
-			};
-
-		// Set traditional to true for jQuery <= 1.3.2 behavior.
-		if ( traditional === undefined ) {
-			traditional = jQuery.ajaxSettings.traditional;
-		}
-
-		// If an array was passed in, assume that it is an array of form elements.
-		if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
-			// Serialize the form elements
-			jQuery.each( a, function() {
-				add( this.name, this.value );
-			});
-
-		} else {
-			// If traditional, encode the "old" way (the way 1.3.2 or older
-			// did it), otherwise encode params recursively.
-			for ( var prefix in a ) {
-				buildParams( prefix, a[ prefix ], traditional, add );
-			}
-		}
-
-		// Return the resulting serialization
-		return s.join( "&" ).replace( r20, "+" );
-	}
-});
-
-function buildParams( prefix, obj, traditional, add ) {
-	if ( jQuery.isArray( obj ) ) {
-		// Serialize array item.
-		jQuery.each( obj, function( i, v ) {
-			if ( traditional || rbracket.test( prefix ) ) {
-				// Treat each array item as a scalar.
-				add( prefix, v );
-
-			} else {
-				// If array item is non-scalar (array or object), encode its
-				// numeric index to resolve deserialization ambiguity issues.
-				// Note that rack (as of 1.0.0) can't currently deserialize
-				// nested arrays properly, and attempting to do so may cause
-				// a server error. Possible fixes are to modify rack's
-				// deserialization algorithm or to provide an option or flag
-				// to force array serialization to be shallow.
-				buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
-			}
-		});
-
-	} else if ( !traditional && obj != null && typeof obj === "object" ) {
-		// Serialize object item.
-		for ( var name in obj ) {
-			buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
-		}
-
-	} else {
-		// Serialize scalar item.
-		add( prefix, obj );
-	}
-}
+    jQuery.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function (i, o) {
+        jQuery.fn[ o ] = function (f) {
+            return this.on(o, f);
+        };
+    });
+
+    jQuery.each([ "get", "post" ], function (i, method) {
+        jQuery[ method ] = function (url, data, callback, type) {
+            // shift arguments if data argument was omitted
+            if (jQuery.isFunction(data)) {
+                type = type || callback;
+                callback = data;
+                data = undefined;
+            }
+
+            return jQuery.ajax({
+                type: method,
+                url: url,
+                data: data,
+                success: callback,
+                dataType: type
+            });
+        };
+    });
+
+    jQuery.extend({
+
+        getScript: function (url, callback) {
+            return jQuery.get(url, undefined, callback, "script");
+        },
+
+        getJSON: function (url, data, callback) {
+            return jQuery.get(url, data, callback, "json");
+        },
+
+        // Creates a full fledged settings object into target
+        // with both ajaxSettings and settings fields.
+        // If target is omitted, writes into ajaxSettings.
+        ajaxSetup: function (target, settings) {
+            if (settings) {
+                // Building a settings object
+                ajaxExtend(target, jQuery.ajaxSettings);
+            } else {
+                // Extending ajaxSettings
+                settings = target;
+                target = jQuery.ajaxSettings;
+            }
+            ajaxExtend(target, settings);
+            return target;
+        },
+
+        ajaxSettings: {
+            url: ajaxLocation,
+            isLocal: rlocalProtocol.test(ajaxLocParts[ 1 ]),
+            global: true,
+            type: "GET",
+            contentType: "application/x-www-form-urlencoded",
+            processData: true,
+            async: true,
+            /*
+             timeout: 0,
+             data: null,
+             dataType: null,
+             username: null,
+             password: null,
+             cache: null,
+             traditional: false,
+             headers: {},
+             */
+
+            accepts: {
+                xml: "application/xml, text/xml",
+                html: "text/html",
+                text: "text/plain",
+                json: "application/json, text/javascript",
+                "*": allTypes
+            },
+
+            contents: {
+                xml: /xml/,
+                html: /html/,
+                json: /json/
+            },
+
+            responseFields: {
+                xml: "responseXML",
+                text: "responseText"
+            },
+
+            // List of data converters
+            // 1) key format is "source_type destination_type" (a single space in-between)
+            // 2) the catchall symbol "*" can be used for source_type
+            converters: {
+
+                // Convert anything to text
+                "* text": window.String,
+
+                // Text to html (true = no transformation)
+                "text html": true,
+
+                // Evaluate text as a json expression
+                "text json": jQuery.parseJSON,
+
+                // Parse text as xml
+                "text xml": jQuery.parseXML
+            },
+
+            // For options that shouldn't be deep extended:
+            // you can add your own custom options here if
+            // and when you create one that shouldn't be
+            // deep extended (see ajaxExtend)
+            flatOptions: {
+                context: true,
+                url: true
+            }
+        },
+
+        ajaxPrefilter: addToPrefiltersOrTransports(prefilters),
+        ajaxTransport: addToPrefiltersOrTransports(transports),
+
+        // Main method
+        ajax: function (url, options) {
+
+            // If url is an object, simulate pre-1.5 signature
+            if (typeof url === "object") {
+                options = url;
+                url = undefined;
+            }
+
+            // Force options to be an object
+            options = options || {};
+
+            var // Create the final options object
+                s = jQuery.ajaxSetup({}, options),
+            // Callbacks context
+                callbackContext = s.context || s,
+            // Context for global events
+            // It's the callbackContext if one was provided in the options
+            // and if it's a DOM node or a jQuery collection
+                globalEventContext = callbackContext !== s &&
+                    ( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
+                    jQuery(callbackContext) : jQuery.event,
+            // Deferreds
+                deferred = jQuery.Deferred(),
+                completeDeferred = jQuery.Callbacks("once memory"),
+            // Status-dependent callbacks
+                statusCode = s.statusCode || {},
+            // ifModified key
+                ifModifiedKey,
+            // Headers (they are sent all at once)
+                requestHeaders = {},
+                requestHeadersNames = {},
+            // Response headers
+                responseHeadersString,
+                responseHeaders,
+            // transport
+                transport,
+            // timeout handle
+                timeoutTimer,
+            // Cross-domain detection vars
+                parts,
+            // The jqXHR state
+                state = 0,
+            // To know if global events are to be dispatched
+                fireGlobals,
+            // Loop variable
+                i,
+            // Fake xhr
+                jqXHR = {
+
+                    readyState: 0,
+
+                    // Caches the header
+                    setRequestHeader: function (name, value) {
+                        if (!state) {
+                            var lname = name.toLowerCase();
+                            name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
+                            requestHeaders[ name ] = value;
+                        }
+                        return this;
+                    },
+
+                    // Raw string
+                    getAllResponseHeaders: function () {
+                        return state === 2 ? responseHeadersString : null;
+                    },
+
+                    // Builds headers hashtable if needed
+                    getResponseHeader: function (key) {
+                        var match;
+                        if (state === 2) {
+                            if (!responseHeaders) {
+                                responseHeaders = {};
+                                while (( match = rheaders.exec(responseHeadersString) )) {
+                                    responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
+                                }
+                            }
+                            match = responseHeaders[ key.toLowerCase() ];
+                        }
+                        return match === undefined ? null : match;
+                    },
+
+                    // Overrides response content-type header
+                    overrideMimeType: function (type) {
+                        if (!state) {
+                            s.mimeType = type;
+                        }
+                        return this;
+                    },
+
+                    // Cancel the request
+                    abort: function (statusText) {
+                        statusText = statusText || "abort";
+                        if (transport) {
+                            transport.abort(statusText);
+                        }
+                        done(0, statusText);
+                        return this;
+                    }
+                };
+
+            // Callback for when everything is done
+            // It is defined here because jslint complains if it is declared
+            // at the end of the function (which would be more logical and readable)
+            function done(status, nativeStatusText, responses, headers) {
+
+                // Called once
+                if (state === 2) {
+                    return;
+                }
+
+                // State is "done" now
+                state = 2;
+
+                // Clear timeout if it exists
+                if (timeoutTimer) {
+                    clearTimeout(timeoutTimer);
+                }
+
+                // Dereference transport for early garbage collection
+                // (no matter how long the jqXHR object will be used)
+                transport = undefined;
+
+                // Cache response headers
+                responseHeadersString = headers || "";
+
+                // Set readyState
+                jqXHR.readyState = status > 0 ? 4 : 0;
+
+                var isSuccess,
+                    success,
+                    error,
+                    statusText = nativeStatusText,
+                    response = responses ? ajaxHandleResponses(s, jqXHR, responses) : undefined,
+                    lastModified,
+                    etag;
+
+                // If successful, handle type chaining
+                if (status >= 200 && status < 300 || status === 304) {
+
+                    // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+                    if (s.ifModified) {
+
+                        if (( lastModified = jqXHR.getResponseHeader("Last-Modified") )) {
+                            jQuery.lastModified[ ifModifiedKey ] = lastModified;
+                        }
+                        if (( etag = jqXHR.getResponseHeader("Etag") )) {
+                            jQuery.etag[ ifModifiedKey ] = etag;
+                        }
+                    }
+
+                    // If not modified
+                    if (status === 304) {
+
+                        statusText = "notmodified";
+                        isSuccess = true;
+
+                        // If we have data
+                    } else {
+
+                        try {
+                            success = ajaxConvert(s, response);
+                            statusText = "success";
+                            isSuccess = true;
+                        } catch (e) {
+                            // We have a parsererror
+                            statusText = "parsererror";
+                            error = e;
+                        }
+                    }
+                } else {
+                    // We extract error from statusText
+                    // then normalize statusText and status for non-aborts
+                    error = statusText;
+                    if (!statusText || status) {
+                        statusText = "error";
+                        if (status < 0) {
+                            status = 0;
+                        }
+                    }
+                }
+
+                // Set data for the fake xhr object
+                jqXHR.status = status;
+                jqXHR.statusText = "" + ( nativeStatusText || statusText );
+
+                // Success/Error
+                if (isSuccess) {
+                    deferred.resolveWith(callbackContext, [ success, statusText, jqXHR ]);
+                } else {
+                    deferred.rejectWith(callbackContext, [ jqXHR, statusText, error ]);
+                }
+
+                // Status-dependent callbacks
+                jqXHR.statusCode(statusCode);
+                statusCode = undefined;
+
+                if (fireGlobals) {
+                    globalEventContext.trigger("ajax" + ( isSuccess ? "Success" : "Error" ),
+                        [ jqXHR, s, isSuccess ? success : error ]);
+                }
+
+                // Complete
+                completeDeferred.fireWith(callbackContext, [ jqXHR, statusText ]);
+
+                if (fireGlobals) {
+                    globalEventContext.trigger("ajaxComplete", [ jqXHR, s ]);
+                    // Handle the global AJAX counter
+                    if (!( --jQuery.active )) {
+                        jQuery.event.trigger("ajaxStop");
+                    }
+                }
+            }
+
+            // Attach deferreds
+            deferred.promise(jqXHR);
+            jqXHR.success = jqXHR.done;
+            jqXHR.error = jqXHR.fail;
+            jqXHR.complete = completeDeferred.add;
+
+            // Status-dependent callbacks
+            jqXHR.statusCode = function (map) {
+                if (map) {
+                    var tmp;
+                    if (state < 2) {
+                        for (tmp in map) {
+                            statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
+                        }
+                    } else {
+                        tmp = map[ jqXHR.status ];
+                        jqXHR.then(tmp, tmp);
+                    }
+                }
+                return this;
+            };
+
+            // Remove hash character (#7531: and string promotion)
+            // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
+            // We also use the url parameter if available
+            s.url = ( ( url || s.url ) + "" ).replace(rhash, "").replace(rprotocol, ajaxLocParts[ 1 ] + "//");
+
+            // Extract dataTypes list
+            s.dataTypes = jQuery.trim(s.dataType || "*").toLowerCase().split(rspacesAjax);
+
+            // Determine if a cross-domain request is in order
+            if (s.crossDomain == null) {
+                parts = rurl.exec(s.url.toLowerCase());
+                s.crossDomain = !!( parts &&
+                    ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
+                        ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
+                            ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
+                    );
+            }
+
+            // Convert data if not already a string
+            if (s.data && s.processData && typeof s.data !== "string") {
+                s.data = jQuery.param(s.data, s.traditional);
+            }
+
+            // Apply prefilters
+            inspectPrefiltersOrTransports(prefilters, s, options, jqXHR);
+
+            // If request was aborted inside a prefiler, stop there
+            if (state === 2) {
+                return false;
+            }
+
+            // We can fire global events as of now if asked to
+            fireGlobals = s.global;
+
+            // Uppercase the type
+            s.type = s.type.toUpperCase();
+
+            // Determine if request has content
+            s.hasContent = !rnoContent.test(s.type);
+
+            // Watch for a new set of requests
+            if (fireGlobals && jQuery.active++ === 0) {
+                jQuery.event.trigger("ajaxStart");
+            }
+
+            // More options handling for requests with no content
+            if (!s.hasContent) {
+
+                // If data is available, append data to url
+                if (s.data) {
+                    s.url += ( rquery.test(s.url) ? "&" : "?" ) + s.data;
+                    // #9682: remove data so that it's not used in an eventual retry
+                    delete s.data;
+                }
+
+                // Get ifModifiedKey before adding the anti-cache parameter
+                ifModifiedKey = s.url;
+
+                // Add anti-cache in url if needed
+                if (s.cache === false) {
+
+                    var ts = jQuery.now(),
+                    // try replacing _= if it is there
+                        ret = s.url.replace(rts, "$1_=" + ts);
+
+                    // if nothing was replaced, add timestamp to the end
+                    s.url = ret + ( ( ret === s.url ) ? ( rquery.test(s.url) ? "&" : "?" ) + "_=" + ts : "" );
+                }
+            }
+
+            // Set the correct header, if data is being sent
+            if (s.data && s.hasContent && s.contentType !== false || options.contentType) {
+                jqXHR.setRequestHeader("Content-Type", s.contentType);
+            }
+
+            // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+            if (s.ifModified) {
+                ifModifiedKey = ifModifiedKey || s.url;
+                if (jQuery.lastModified[ ifModifiedKey ]) {
+                    jqXHR.setRequestHeader("If-Modified-Since", jQuery.lastModified[ ifModifiedKey ]);
+                }
+                if (jQuery.etag[ ifModifiedKey ]) {
+                    jqXHR.setRequestHeader("If-None-Match", jQuery.etag[ ifModifiedKey ]);
+                }
+            }
+
+            // Set the Accepts header for the server, depending on the dataType
+            jqXHR.setRequestHeader(
+                "Accept",
+                s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
+                    s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
+                    s.accepts[ "*" ]
+            );
+
+            // Check for headers option
+            for (i in s.headers) {
+                jqXHR.setRequestHeader(i, s.headers[ i ]);
+            }
+
+            // Allow custom headers/mimetypes and early abort
+            if (s.beforeSend && ( s.beforeSend.call(callbackContext, jqXHR, s) === false || state === 2 )) {
+                // Abort if not done already
+                jqXHR.abort();
+                return false;
+
+            }
+
+            // Install callbacks on deferreds
+            for (i in { success: 1, error: 1, complete: 1 }) {
+                jqXHR[ i ](s[ i ]);
+            }
+
+            // Get transport
+            transport = inspectPrefiltersOrTransports(transports, s, options, jqXHR);
+
+            // If no transport, we auto-abort
+            if (!transport) {
+                done(-1, "No Transport");
+            } else {
+                jqXHR.readyState = 1;
+                // Send global event
+                if (fireGlobals) {
+                    globalEventContext.trigger("ajaxSend", [ jqXHR, s ]);
+                }
+                // Timeout
+                if (s.async && s.timeout > 0) {
+                    timeoutTimer = setTimeout(function () {
+                        jqXHR.abort("timeout");
+                    }, s.timeout);
+                }
+
+                try {
+                    state = 1;
+                    transport.send(requestHeaders, done);
+                } catch (e) {
+                    // Propagate exception as error if not done
+                    if (state < 2) {
+                        done(-1, e);
+                        // Simply rethrow otherwise
+                    } else {
+                        throw e;
+                    }
+                }
+            }
+
+            return jqXHR;
+        },
+
+        // Serialize an array of form elements or a set of
+        // key/values into a query string
+        param: function (a, traditional) {
+            var s = [],
+                add = function (key, value) {
+                    // If value is a function, invoke it and return its value
+                    value = jQuery.isFunction(value) ? value() : value;
+                    s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
+                };
+
+            // Set traditional to true for jQuery <= 1.3.2 behavior.
+            if (traditional === undefined) {
+                traditional = jQuery.ajaxSettings.traditional;
+            }
+
+            // If an array was passed in, assume that it is an array of form elements.
+            if (jQuery.isArray(a) || ( a.jquery && !jQuery.isPlainObject(a) )) {
+                // Serialize the form elements
+                jQuery.each(a, function () {
+                    add(this.name, this.value);
+                });
+
+            } else {
+                // If traditional, encode the "old" way (the way 1.3.2 or older
+                // did it), otherwise encode params recursively.
+                for (var prefix in a) {
+                    buildParams(prefix, a[ prefix ], traditional, add);
+                }
+            }
+
+            // Return the resulting serialization
+            return s.join("&").replace(r20, "+");
+        }
+    });
+
+    function buildParams(prefix, obj, traditional, add) {
+        if (jQuery.isArray(obj)) {
+            // Serialize array item.
+            jQuery.each(obj, function (i, v) {
+                if (traditional || rbracket.test(prefix)) {
+                    // Treat each array item as a scalar.
+                    add(prefix, v);
+
+                } else {
+                    // If array item is non-scalar (array or object), encode its
+                    // numeric index to resolve deserialization ambiguity issues.
+                    // Note that rack (as of 1.0.0) can't currently deserialize
+                    // nested arrays properly, and attempting to do so may cause
+                    // a server error. Possible fixes are to modify rack's
+                    // deserialization algorithm or to provide an option or flag
+                    // to force array serialization to be shallow.
+                    buildParams(prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add);
+                }
+            });
+
+        } else if (!traditional && obj != null && typeof obj === "object") {
+            // Serialize object item.
+            for (var name in obj) {
+                buildParams(prefix + "[" + name + "]", obj[ name ], traditional, add);
+            }
+
+        } else {
+            // Serialize scalar item.
+            add(prefix, obj);
+        }
+    }
 
 // This is still on the jQuery object... for now
 // Want to move this to jQuery.ajax some day
-jQuery.extend({
-
-	// Counter for holding the number of active queries
-	active: 0,
-
-	// Last-Modified header cache for next request
-	lastModified: {},
-	etag: {}
-
-});
-
-/* Handles responses to an ajax request:
- * - sets all responseXXX fields accordingly
- * - finds the right dataType (mediates between content-type and expected dataType)
- * - returns the corresponding response
- */
-function ajaxHandleResponses( s, jqXHR, responses ) {
-
-	var contents = s.contents,
-		dataTypes = s.dataTypes,
-		responseFields = s.responseFields,
-		ct,
-		type,
-		finalDataType,
-		firstDataType;
-
-	// Fill responseXXX fields
-	for ( type in responseFields ) {
-		if ( type in responses ) {
-			jqXHR[ responseFields[type] ] = responses[ type ];
-		}
-	}
-
-	// Remove auto dataType and get content-type in the process
-	while( dataTypes[ 0 ] === "*" ) {
-		dataTypes.shift();
-		if ( ct === undefined ) {
-			ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
-		}
-	}
-
-	// Check if we're dealing with a known content-type
-	if ( ct ) {
-		for ( type in contents ) {
-			if ( contents[ type ] && contents[ type ].test( ct ) ) {
-				dataTypes.unshift( type );
-				break;
-			}
-		}
-	}
-
-	// Check to see if we have a response for the expected dataType
-	if ( dataTypes[ 0 ] in responses ) {
-		finalDataType = dataTypes[ 0 ];
-	} else {
-		// Try convertible dataTypes
-		for ( type in responses ) {
-			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
-				finalDataType = type;
-				break;
-			}
-			if ( !firstDataType ) {
-				firstDataType = type;
-			}
-		}
-		// Or just use first one
-		finalDataType = finalDataType || firstDataType;
-	}
-
-	// If we found a dataType
-	// We add the dataType to the list if needed
-	// and return the corresponding response
-	if ( finalDataType ) {
-		if ( finalDataType !== dataTypes[ 0 ] ) {
-			dataTypes.unshift( finalDataType );
-		}
-		return responses[ finalDataType ];
-	}
-}
+    jQuery.extend({
+
+        // Counter for holding the number of active queries
+        active: 0,
+
+        // Last-Modified header cache for next request
+        lastModified: {},
+        etag: {}
+
+    });
+
+    /* Handles responses to an ajax request:
+     * - sets all responseXXX fields accordingly
+     * - finds the right dataType (mediates between content-type and expected dataType)
+     * - returns the corresponding response
+     */
+    function ajaxHandleResponses(s, jqXHR, responses) {
+
+        var contents = s.contents,
+            dataTypes = s.dataTypes,
+            responseFields = s.responseFields,
+            ct,
+            type,
+            finalDataType,
+            firstDataType;
+
+        // Fill responseXXX fields
+        for (type in responseFields) {
+            if (type in responses) {
+                jqXHR[ responseFields[type] ] = responses[ type ];
+            }
+        }
+
+        // Remove auto dataType and get content-type in the process
+        while (dataTypes[ 0 ] === "*") {
+            dataTypes.shift();
+            if (ct === undefined) {
+                ct = s.mimeType || jqXHR.getResponseHeader("content-type");
+            }
+        }
+
+        // Check if we're dealing with a known content-type
+        if (ct) {
+            for (type in contents) {
+                if (contents[ type ] && contents[ type ].test(ct)) {
+                    dataTypes.unshift(type);
+                    break;
+                }
+            }
+        }
+
+        // Check to see if we have a response for the expected dataType
+        if (dataTypes[ 0 ] in responses) {
+            finalDataType = dataTypes[ 0 ];
+        } else {
+            // Try convertible dataTypes
+            for (type in responses) {
+                if (!dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ]) {
+                    finalDataType = type;
+                    break;
+                }
+                if (!firstDataType) {
+                    firstDataType = type;
+                }
+            }
+            // Or just use first one
+            finalDataType = finalDataType || firstDataType;
+        }
+
+        // If we found a dataType
+        // We add the dataType to the list if needed
+        // and return the corresponding response
+        if (finalDataType) {
+            if (finalDataType !== dataTypes[ 0 ]) {
+                dataTypes.unshift(finalDataType);
+            }
+            return responses[ finalDataType ];
+        }
+    }
 
 // Chain conversions given the request and the original response
-function ajaxConvert( s, response ) {
-
-	// Apply the dataFilter if provided
-	if ( s.dataFilter ) {
-		response = s.dataFilter( response, s.dataType );
-	}
-
-	var dataTypes = s.dataTypes,
-		converters = {},
-		i,
-		key,
-		length = dataTypes.length,
-		tmp,
-		// Current and previous dataTypes
-		current = dataTypes[ 0 ],
-		prev,
-		// Conversion expression
-		conversion,
-		// Conversion function
-		conv,
-		// Conversion functions (transitive conversion)
-		conv1,
-		conv2;
-
-	// For each dataType in the chain
-	for ( i = 1; i < length; i++ ) {
-
-		// Create converters map
-		// with lowercased keys
-		if ( i === 1 ) {
-			for ( key in s.converters ) {
-				if ( typeof key === "string" ) {
-					converters[ key.toLowerCase() ] = s.converters[ key ];
-				}
-			}
-		}
-
-		// Get the dataTypes
-		prev = current;
-		current = dataTypes[ i ];
-
-		// If current is auto dataType, update it to prev
-		if ( current === "*" ) {
-			current = prev;
-		// If no auto and dataTypes are actually different
-		} else if ( prev !== "*" && prev !== current ) {
-
-			// Get the converter
-			conversion = prev + " " + current;
-			conv = converters[ conversion ] || converters[ "* " + current ];
-
-			// If there is no direct converter, search transitively
-			if ( !conv ) {
-				conv2 = undefined;
-				for ( conv1 in converters ) {
-					tmp = conv1.split( " " );
-					if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
-						conv2 = converters[ tmp[1] + " " + current ];
-						if ( conv2 ) {
-							conv1 = converters[ conv1 ];
-							if ( conv1 === true ) {
-								conv = conv2;
-							} else if ( conv2 === true ) {
-								conv = conv1;
-							}
-							break;
-						}
-					}
-				}
-			}
-			// If we found no converter, dispatch an error
-			if ( !( conv || conv2 ) ) {
-				jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
-			}
-			// If found converter is not an equivalence
-			if ( conv !== true ) {
-				// Convert with 1 or 2 converters accordingly
-				response = conv ? conv( response ) : conv2( conv1(response) );
-			}
-		}
-	}
-	return response;
-}
-
-
-
-
-var jsc = jQuery.now(),
-	jsre = /(\=)\?(&|$)|\?\?/i;
+    function ajaxConvert(s, response) {
+
+        // Apply the dataFilter if provided
+        if (s.dataFilter) {
+            response = s.dataFilter(response, s.dataType);
+        }
+
+        var dataTypes = s.dataTypes,
+            converters = {},
+            i,
+            key,
+            length = dataTypes.length,
+            tmp,
+        // Current and previous dataTypes
+            current = dataTypes[ 0 ],
+            prev,
+        // Conversion expression
+            conversion,
+        // Conversion function
+            conv,
+        // Conversion functions (transitive conversion)
+            conv1,
+            conv2;
+
+        // For each dataType in the chain
+        for (i = 1; i < length; i++) {
+
+            // Create converters map
+            // with lowercased keys
+            if (i === 1) {
+                for (key in s.converters) {
+                    if (typeof key === "string") {
+                        converters[ key.toLowerCase() ] = s.converters[ key ];
+                    }
+                }
+            }
+
+            // Get the dataTypes
+            prev = current;
+            current = dataTypes[ i ];
+
+            // If current is auto dataType, update it to prev
+            if (current === "*") {
+                current = prev;
+                // If no auto and dataTypes are actually different
+            } else if (prev !== "*" && prev !== current) {
+
+                // Get the converter
+                conversion = prev + " " + current;
+                conv = converters[ conversion ] || converters[ "* " + current ];
+
+                // If there is no direct converter, search transitively
+                if (!conv) {
+                    conv2 = undefined;
+                    for (conv1 in converters) {
+                        tmp = conv1.split(" ");
+                        if (tmp[ 0 ] === prev || tmp[ 0 ] === "*") {
+                            conv2 = converters[ tmp[1] + " " + current ];
+                            if (conv2) {
+                                conv1 = converters[ conv1 ];
+                                if (conv1 === true) {
+                                    conv = conv2;
+                                } else if (conv2 === true) {
+                                    conv = conv1;
+                                }
+                                break;
+                            }
+                        }
+                    }
+                }
+                // If we found no converter, dispatch an error
+                if (!( conv || conv2 )) {
+                    jQuery.error("No conversion from " + conversion.replace(" ", " to "));
+                }
+                // If found converter is not an equivalence
+                if (conv !== true) {
+                    // Convert with 1 or 2 converters accordingly
+                    response = conv ? conv(response) : conv2(conv1(response));
+                }
+            }
+        }
+        return response;
+    }
+
+
+    var jsc = jQuery.now(),
+        jsre = /(\=)\?(&|$)|\?\?/i;
 
 // Default jsonp settings
-jQuery.ajaxSetup({
-	jsonp: "callback",
-	jsonpCallback: function() {
-		return jQuery.expando + "_" + ( jsc++ );
-	}
-});
+    jQuery.ajaxSetup({
+        jsonp: "callback",
+        jsonpCallback: function () {
+            return jQuery.expando + "_" + ( jsc++ );
+        }
+    });
 
 // Detect, normalize options and install callbacks for jsonp requests
-jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
-
-	var inspectData = s.contentType === "application/x-www-form-urlencoded" &&
-		( typeof s.data === "string" );
-
-	if ( s.dataTypes[ 0 ] === "jsonp" ||
-		s.jsonp !== false && ( jsre.test( s.url ) ||
-				inspectData && jsre.test( s.data ) ) ) {
-
-		var responseContainer,
-			jsonpCallback = s.jsonpCallback =
-				jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
-			previous = window[ jsonpCallback ],
-			url = s.url,
-			data = s.data,
-			replace = "$1" + jsonpCallback + "$2";
-
-		if ( s.jsonp !== false ) {
-			url = url.replace( jsre, replace );
-			if ( s.url === url ) {
-				if ( inspectData ) {
-					data = data.replace( jsre, replace );
-				}
-				if ( s.data === data ) {
-					// Add callback manually
-					url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
-				}
-			}
-		}
-
-		s.url = url;
-		s.data = data;
-
-		// Install callback
-		window[ jsonpCallback ] = function( response ) {
-			responseContainer = [ response ];
-		};
-
-		// Clean-up function
-		jqXHR.always(function() {
-			// Set callback back to previous value
-			window[ jsonpCallback ] = previous;
-			// Call if it was a function and we have a response
-			if ( responseContainer && jQuery.isFunction( previous ) ) {
-				window[ jsonpCallback ]( responseContainer[ 0 ] );
-			}
-		});
-
-		// Use data converter to retrieve json after script execution
-		s.converters["script json"] = function() {
-			if ( !responseContainer ) {
-				jQuery.error( jsonpCallback + " was not called" );
-			}
-			return responseContainer[ 0 ];
-		};
-
-		// force json dataType
-		s.dataTypes[ 0 ] = "json";
-
-		// Delegate to script
-		return "script";
-	}
-});
-
-
+    jQuery.ajaxPrefilter("json jsonp", function (s, originalSettings, jqXHR) {
+
+        var inspectData = s.contentType === "application/x-www-form-urlencoded" &&
+            ( typeof s.data === "string" );
+
+        if (s.dataTypes[ 0 ] === "jsonp" ||
+            s.jsonp !== false && ( jsre.test(s.url) ||
+                inspectData && jsre.test(s.data) )) {
+
+            var responseContainer,
+                jsonpCallback = s.jsonpCallback =
+                    jQuery.isFunction(s.jsonpCallback) ? s.jsonpCallback() : s.jsonpCallback,
+                previous = window[ jsonpCallback ],
+                url = s.url,
+                data = s.data,
+                replace = "$1" + jsonpCallback + "$2";
+
+            if (s.jsonp !== false) {
+                url = url.replace(jsre, replace);
+                if (s.url === url) {
+                    if (inspectData) {
+                        data = data.replace(jsre, replace);
+                    }
+                    if (s.data === data) {
+                        // Add callback manually
+                        url += (/\?/.test(url) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
+                    }
+                }
+            }
+
+            s.url = url;
+            s.data = data;
+
+            // Install callback
+            window[ jsonpCallback ] = function (response) {
+                responseContainer = [ response ];
+            };
+
+            // Clean-up function
+            jqXHR.always(function () {
+                // Set callback back to previous value
+                window[ jsonpCallback ] = previous;
+                // Call if it was a function and we have a response
+                if (responseContainer && jQuery.isFunction(previous)) {
+                    window[ jsonpCallback ](responseContainer[ 0 ]);
+                }
+            });
+
+            // Use data converter to retrieve json after script execution
+            s.converters["script json"] = function () {
+                if (!responseContainer) {
+                    jQuery.error(jsonpCallback + " was not called");
+                }
+                return responseContainer[ 0 ];
+            };
+
+            // force json dataType
+            s.dataTypes[ 0 ] = "json";
+
+            // Delegate to script
+            return "script";
+        }
+    });
 
 
 // Install script dataType
-jQuery.ajaxSetup({
-	accepts: {
-		script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
-	},
-	contents: {
-		script: /javascript|ecmascript/
-	},
-	converters: {
-		"text script": function( text ) {
-			jQuery.globalEval( text );
-			return text;
-		}
-	}
-});
+    jQuery.ajaxSetup({
+        accepts: {
+            script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
+        },
+        contents: {
+            script: /javascript|ecmascript/
+        },
+        converters: {
+            "text script": function (text) {
+                jQuery.globalEval(text);
+                return text;
+            }
+        }
+    });
 
 // Handle cache's special case and global
-jQuery.ajaxPrefilter( "script", function( s ) {
-	if ( s.cache === undefined ) {
-		s.cache = false;
-	}
-	if ( s.crossDomain ) {
-		s.type = "GET";
-		s.global = false;
-	}
-});
+    jQuery.ajaxPrefilter("script", function (s) {
+        if (s.cache === undefined) {
+            s.cache = false;
+        }
+        if (s.crossDomain) {
+            s.type = "GET";
+            s.global = false;
+        }
+    });
 
 // Bind script tag hack transport
-jQuery.ajaxTransport( "script", function(s) {
+    jQuery.ajaxTransport("script", function (s) {
 
-	// This transport only deals with cross domain requests
-	if ( s.crossDomain ) {
+        // This transport only deals with cross domain requests
+        if (s.crossDomain) {
 
-		var script,
-			head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
+            var script,
+                head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
 
-		return {
+            return {
 
-			send: function( _, callback ) {
+                send: function (_, callback) {
 
-				script = document.createElement( "script" );
+                    script = document.createElement("script");
 
-				script.async = "async";
+                    script.async = "async";
 
-				if ( s.scriptCharset ) {
-					script.charset = s.scriptCharset;
-				}
+                    if (s.scriptCharset) {
+                        script.charset = s.scriptCharset;
+                    }
 
-				script.src = s.url;
+                    script.src = s.url;
 
-				// Attach handlers for all browsers
-				script.onload = script.onreadystatechange = function( _, isAbort ) {
+                    // Attach handlers for all browsers
+                    script.onload = script.onreadystatechange = function (_, isAbort) {
 
-					if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
+                        if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) {
 
-						// Handle memory leak in IE
-						script.onload = script.onreadystatechange = null;
+                            // Handle memory leak in IE
+                            script.onload = script.onreadystatechange = null;
 
-						// Remove the script
-						if ( head && script.parentNode ) {
-							head.removeChild( script );
-						}
+                            // Remove the script
+                            if (head && script.parentNode) {
+                                head.removeChild(script);
+                            }
 
-						// Dereference the script
-						script = undefined;
+                            // Dereference the script
+                            script = undefined;
 
-						// Callback if not abort
-						if ( !isAbort ) {
-							callback( 200, "success" );
-						}
-					}
-				};
-				// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
-				// This arises when a base node is used (#2709 and #4378).
-				head.insertBefore( script, head.firstChild );
-			},
+                            // Callback if not abort
+                            if (!isAbort) {
+                                callback(200, "success");
+                            }
+                        }
+                    };
+                    // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
+                    // This arises when a base node is used (#2709 and #4378).
+                    head.insertBefore(script, head.firstChild);
+                },
 
-			abort: function() {
-				if ( script ) {
-					script.onload( 0, 1 );
-				}
-			}
-		};
-	}
-});
+                abort: function () {
+                    if (script) {
+                        script.onload(0, 1);
+                    }
+                }
+            };
+        }
+    });
 
 
-
-
-var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
-	xhrOnUnloadAbort = window.ActiveXObject ? function() {
-		// Abort all pending requests
-		for ( var key in xhrCallbacks ) {
-			xhrCallbacks[ key ]( 0, 1 );
-		}
-	} : false,
-	xhrId = 0,
-	xhrCallbacks;
+    var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
+        xhrOnUnloadAbort = window.ActiveXObject ? function () {
+            // Abort all pending requests
+            for (var key in xhrCallbacks) {
+                xhrCallbacks[ key ](0, 1);
+            }
+        } : false,
+        xhrId = 0,
+        xhrCallbacks;
 
 // Functions to create xhrs
-function createStandardXHR() {
-	try {
-		return new window.XMLHttpRequest();
-	} catch( e ) {}
-}
-
-function createActiveXHR() {
-	try {
-		return new window.ActiveXObject( "Microsoft.XMLHTTP" );
-	} catch( e ) {}
-}
+    function createStandardXHR() {
+        try {
+            return new window.XMLHttpRequest();
+        } catch (e) {
+        }
+    }
+
+    function createActiveXHR() {
+        try {
+            return new window.ActiveXObject("Microsoft.XMLHTTP");
+        } catch (e) {
+        }
+    }
 
 // Create the request object
 // (This is still attached to ajaxSettings for backward compatibility)
-jQuery.ajaxSettings.xhr = window.ActiveXObject ?
-	/* Microsoft failed to properly
-	 * implement the XMLHttpRequest in IE7 (can't request local files),
-	 * so we use the ActiveXObject when it is available
-	 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
-	 * we need a fallback.
-	 */
-	function() {
-		return !this.isLocal && createStandardXHR() || createActiveXHR();
-	} :
-	// For all other browsers, use the standard XMLHttpRequest object
-	createStandardXHR;
+    jQuery.ajaxSettings.xhr = window.ActiveXObject ?
+        /* Microsoft failed to properly
+         * implement the XMLHttpRequest in IE7 (can't request local files),
+         * so we use the ActiveXObject when it is available
+         * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
+         * we need a fallback.
+         */
+        function () {
+            return !this.isLocal && createStandardXHR() || createActiveXHR();
+        } :
+        // For all other browsers, use the standard XMLHttpRequest object
+        createStandardXHR;
 
 // Determine support properties
-(function( xhr ) {
-	jQuery.extend( jQuery.support, {
-		ajax: !!xhr,
-		cors: !!xhr && ( "withCredentials" in xhr )
-	});
-})( jQuery.ajaxSettings.xhr() );
+    (function (xhr) {
+        jQuery.extend(jQuery.support, {
+            ajax: !!xhr,
+            cors: !!xhr && ( "withCredentials" in xhr )
+        });
+    })(jQuery.ajaxSettings.xhr());
 
 // Create transport if the browser can provide an xhr
-if ( jQuery.support.ajax ) {
-
-	jQuery.ajaxTransport(function( s ) {
-		// Cross domain only allowed if supported through XMLHttpRequest
-		if ( !s.crossDomain || jQuery.support.cors ) {
-
-			var callback;
-
-			return {
-				send: function( headers, complete ) {
-
-					// Get a new xhr
-					var xhr = s.xhr(),
-						handle,
-						i;
-
-					// Open the socket
-					// Passing null username, generates a login popup on Opera (#2865)
-					if ( s.username ) {
-						xhr.open( s.type, s.url, s.async, s.username, s.password );
-					} else {
-						xhr.open( s.type, s.url, s.async );
-					}
-
-					// Apply custom fields if provided
-					if ( s.xhrFields ) {
-						for ( i in s.xhrFields ) {
-							xhr[ i ] = s.xhrFields[ i ];
-						}
-					}
-
-					// Override mime type if needed
-					if ( s.mimeType && xhr.overrideMimeType ) {
-						xhr.overrideMimeType( s.mimeType );
-					}
-
-					// X-Requested-With header
-					// For cross-domain requests, seeing as conditions for a preflight are
-					// akin to a jigsaw puzzle, we simply never set it to be sure.
-					// (it can always be set on a per-request basis or even using ajaxSetup)
-					// For same-domain requests, won't change header if already provided.
-					if ( !s.crossDomain && !headers["X-Requested-With"] ) {
-						headers[ "X-Requested-With" ] = "XMLHttpRequest";
-					}
-
-					// Need an extra try/catch for cross domain requests in Firefox 3
-					try {
-						for ( i in headers ) {
-							xhr.setRequestHeader( i, headers[ i ] );
-						}
-					} catch( _ ) {}
-
-					// Do send the request
-					// This may raise an exception which is actually
-					// handled in jQuery.ajax (so no try/catch here)
-					xhr.send( ( s.hasContent && s.data ) || null );
-
-					// Listener
-					callback = function( _, isAbort ) {
-
-						var status,
-							statusText,
-							responseHeaders,
-							responses,
-							xml;
-
-						// Firefox throws exceptions when accessing properties
-						// of an xhr when a network error occured
-						// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
-						try {
-
-							// Was never called and is aborted or complete
-							if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
-
-								// Only called once
-								callback = undefined;
-
-								// Do not keep as active anymore
-								if ( handle ) {
-									xhr.onreadystatechange = jQuery.noop;
-									if ( xhrOnUnloadAbort ) {
-										delete xhrCallbacks[ handle ];
-									}
-								}
-
-								// If it's an abort
-								if ( isAbort ) {
-									// Abort it manually if needed
-									if ( xhr.readyState !== 4 ) {
-										xhr.abort();
-									}
-								} else {
-									status = xhr.status;
-									responseHeaders = xhr.getAllResponseHeaders();
-									responses = {};
-									xml = xhr.responseXML;
-
-									// Construct response list
-									if ( xml && xml.documentElement /* #4958 */ ) {
-										responses.xml = xml;
-									}
-									responses.text = xhr.responseText;
-
-									// Firefox throws an exception when accessing
-									// statusText for faulty cross-domain requests
-									try {
-										statusText = xhr.statusText;
-									} catch( e ) {
-										// We normalize with Webkit giving an empty statusText
-										statusText = "";
-									}
-
-									// Filter status for non standard behaviors
-
-									// If the request is local and we have data: assume a success
-									// (success with no data won't get notified, that's the best we
-									// can do given current implementations)
-									if ( !status && s.isLocal && !s.crossDomain ) {
-										status = responses.text ? 200 : 404;
-									// IE - #1450: sometimes returns 1223 when it should be 204
-									} else if ( status === 1223 ) {
-										status = 204;
-									}
-								}
-							}
-						} catch( firefoxAccessException ) {
-							if ( !isAbort ) {
-								complete( -1, firefoxAccessException );
-							}
-						}
-
-						// Call complete if needed
-						if ( responses ) {
-							complete( status, statusText, responses, responseHeaders );
-						}
-					};
-
-					// if we're in sync mode or it's in cache
-					// and has been retrieved directly (IE6 & IE7)
-					// we need to manually fire the callback
-					if ( !s.async || xhr.readyState === 4 ) {
-						callback();
-					} else {
-						handle = ++xhrId;
-						if ( xhrOnUnloadAbort ) {
-							// Create the active xhrs callbacks list if needed
-							// and attach the unload handler
-							if ( !xhrCallbacks ) {
-								xhrCallbacks = {};
-								jQuery( window ).unload( xhrOnUnloadAbort );
-							}
-							// Add to list of active xhrs callbacks
-							xhrCallbacks[ handle ] = callback;
-						}
-						xhr.onreadystatechange = callback;
-					}
-				},
-
-				abort: function() {
-					if ( callback ) {
-						callback(0,1);
-					}
-				}
-			};
-		}
-	});
-}
-
-
-
-
-var elemdisplay = {},
-	iframe, iframeDoc,
-	rfxtypes = /^(?:toggle|show|hide)$/,
-	rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
-	timerId,
-	fxAttrs = [
-		// height animations
-		[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
-		// width animations
-		[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
-		// opacity animations
-		[ "opacity" ]
-	],
-	fxNow;
-
-jQuery.fn.extend({
-	show: function( speed, easing, callback ) {
-		var elem, display;
-
-		if ( speed || speed === 0 ) {
-			return this.animate( genFx("show", 3), speed, easing, callback );
-
-		} else {
-			for ( var i = 0, j = this.length; i < j; i++ ) {
-				elem = this[ i ];
-
-				if ( elem.style ) {
-					display = elem.style.display;
-
-					// Reset the inline display of this element to learn if it is
-					// being hidden by cascaded rules or not
-					if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
-						display = elem.style.display = "";
-					}
-
-					// Set elements which have been overridden with display: none
-					// in a stylesheet to whatever the default browser style is
-					// for such an element
-					if ( display === "" && jQuery.css(elem, "display") === "none" ) {
-						jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
-					}
-				}
-			}
-
-			// Set the display of most of the elements in a second loop
-			// to avoid the constant reflow
-			for ( i = 0; i < j; i++ ) {
-				elem = this[ i ];
-
-				if ( elem.style ) {
-					display = elem.style.display;
-
-					if ( display === "" || display === "none" ) {
-						elem.style.display = jQuery._data( elem, "olddisplay" ) || "";
-					}
-				}
-			}
-
-			return this;
-		}
-	},
-
-	hide: function( speed, easing, callback ) {
-		if ( speed || speed === 0 ) {
-			return this.animate( genFx("hide", 3), speed, easing, callback);
-
-		} else {
-			var elem, display,
-				i = 0,
-				j = this.length;
-
-			for ( ; i < j; i++ ) {
-				elem = this[i];
-				if ( elem.style ) {
-					display = jQuery.css( elem, "display" );
-
-					if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) {
-						jQuery._data( elem, "olddisplay", display );
-					}
-				}
-			}
-
-			// Set the display of the elements in a second loop
-			// to avoid the constant reflow
-			for ( i = 0; i < j; i++ ) {
-				if ( this[i].style ) {
-					this[i].style.display = "none";
-				}
-			}
-
-			return this;
-		}
-	},
-
-	// Save the old toggle function
-	_toggle: jQuery.fn.toggle,
-
-	toggle: function( fn, fn2, callback ) {
-		var bool = typeof fn === "boolean";
-
-		if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
-			this._toggle.apply( this, arguments );
-
-		} else if ( fn == null || bool ) {
-			this.each(function() {
-				var state = bool ? fn : jQuery(this).is(":hidden");
-				jQuery(this)[ state ? "show" : "hide" ]();
-			});
-
-		} else {
-			this.animate(genFx("toggle", 3), fn, fn2, callback);
-		}
-
-		return this;
-	},
-
-	fadeTo: function( speed, to, easing, callback ) {
-		return this.filter(":hidden").css("opacity", 0).show().end()
-					.animate({opacity: to}, speed, easing, callback);
-	},
-
-	animate: function( prop, speed, easing, callback ) {
-		var optall = jQuery.speed( speed, easing, callback );
-
-		if ( jQuery.isEmptyObject( prop ) ) {
-			return this.each( optall.complete, [ false ] );
-		}
-
-		// Do not change referenced properties as per-property easing will be lost
-		prop = jQuery.extend( {}, prop );
-
-		function doAnimation() {
-			// XXX 'this' does not always have a nodeName when running the
-			// test suite
-
-			if ( optall.queue === false ) {
-				jQuery._mark( this );
-			}
-
-			var opt = jQuery.extend( {}, optall ),
-				isElement = this.nodeType === 1,
-				hidden = isElement && jQuery(this).is(":hidden"),
-				name, val, p, e,
-				parts, start, end, unit,
-				method;
-
-			// will store per property easing and be used to determine when an animation is complete
-			opt.animatedProperties = {};
-
-			for ( p in prop ) {
-
-				// property name normalization
-				name = jQuery.camelCase( p );
-				if ( p !== name ) {
-					prop[ name ] = prop[ p ];
-					delete prop[ p ];
-				}
-
-				val = prop[ name ];
-
-				// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
-				if ( jQuery.isArray( val ) ) {
-					opt.animatedProperties[ name ] = val[ 1 ];
-					val = prop[ name ] = val[ 0 ];
-				} else {
-					opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
-				}
-
-				if ( val === "hide" && hidden || val === "show" && !hidden ) {
-					return opt.complete.call( this );
-				}
-
-				if ( isElement && ( name === "height" || name === "width" ) ) {
-					// Make sure that nothing sneaks out
-					// Record all 3 overflow attributes because IE does not
-					// change the overflow attribute when overflowX and
-					// overflowY are set to the same value
-					opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
-
-					// Set display property to inline-block for height/width
-					// animations on inline elements that are having width/height animated
-					if ( jQuery.css( this, "display" ) === "inline" &&
-							jQuery.css( this, "float" ) === "none" ) {
-
-						// inline-level elements accept inline-block;
-						// block-level elements need to be inline with layout
-						if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) {
-							this.style.display = "inline-block";
-
-						} else {
-							this.style.zoom = 1;
-						}
-					}
-				}
-			}
-
-			if ( opt.overflow != null ) {
-				this.style.overflow = "hidden";
-			}
-
-			for ( p in prop ) {
-				e = new jQuery.fx( this, opt, p );
-				val = prop[ p ];
-
-				if ( rfxtypes.test( val ) ) {
-
-					// Tracks whether to show or hide based on private
-					// data attached to the element
-					method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 );
-					if ( method ) {
-						jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" );
-						e[ method ]();
-					} else {
-						e[ val ]();
-					}
-
-				} else {
-					parts = rfxnum.exec( val );
-					start = e.cur();
-
-					if ( parts ) {
-						end = parseFloat( parts[2] );
-						unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
-
-						// We need to compute starting value
-						if ( unit !== "px" ) {
-							jQuery.style( this, p, (end || 1) + unit);
-							start = ( (end || 1) / e.cur() ) * start;
-							jQuery.style( this, p, start + unit);
-						}
-
-						// If a +=/-= token was provided, we're doing a relative animation
-						if ( parts[1] ) {
-							end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
-						}
-
-						e.custom( start, end, unit );
-
-					} else {
-						e.custom( start, val, "" );
-					}
-				}
-			}
-
-			// For JS strict compliance
-			return true;
-		}
-
-		return optall.queue === false ?
-			this.each( doAnimation ) :
-			this.queue( optall.queue, doAnimation );
-	},
-
-	stop: function( type, clearQueue, gotoEnd ) {
-		if ( typeof type !== "string" ) {
-			gotoEnd = clearQueue;
-			clearQueue = type;
-			type = undefined;
-		}
-		if ( clearQueue && type !== false ) {
-			this.queue( type || "fx", [] );
-		}
-
-		return this.each(function() {
-			var index,
-				hadTimers = false,
-				timers = jQuery.timers,
-				data = jQuery._data( this );
-
-			// clear marker counters if we know they won't be
-			if ( !gotoEnd ) {
-				jQuery._unmark( true, this );
-			}
-
-			function stopQueue( elem, data, index ) {
-				var hooks = data[ index ];
-				jQuery.removeData( elem, index, true );
-				hooks.stop( gotoEnd );
-			}
-
-			if ( type == null ) {
-				for ( index in data ) {
-					if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) {
-						stopQueue( this, data, index );
-					}
-				}
-			} else if ( data[ index = type + ".run" ] && data[ index ].stop ){
-				stopQueue( this, data, index );
-			}
-
-			for ( index = timers.length; index--; ) {
-				if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
-					if ( gotoEnd ) {
-
-						// force the next step to be the last
-						timers[ index ]( true );
-					} else {
-						timers[ index ].saveState();
-					}
-					hadTimers = true;
-					timers.splice( index, 1 );
-				}
-			}
-
-			// start the next in the queue if the last step wasn't forced
-			// timers currently will call their complete callbacks, which will dequeue
-			// but only if they were gotoEnd
-			if ( !( gotoEnd && hadTimers ) ) {
-				jQuery.dequeue( this, type );
-			}
-		});
-	}
-
-});
+    if (jQuery.support.ajax) {
+
+        jQuery.ajaxTransport(function (s) {
+            // Cross domain only allowed if supported through XMLHttpRequest
+            if (!s.crossDomain || jQuery.support.cors) {
+
+                var callback;
+
+                return {
+                    send: function (headers, complete) {
+
+                        // Get a new xhr
+                        var xhr = s.xhr(),
+                            handle,
+                            i;
+
+                        // Open the socket
+                        // Passing null username, generates a login popup on Opera (#2865)
+                        if (s.username) {
+                            xhr.open(s.type, s.url, s.async, s.username, s.password);
+                        } else {
+                            xhr.open(s.type, s.url, s.async);
+                        }
+
+                        // Apply custom fields if provided
+                        if (s.xhrFields) {
+                            for (i in s.xhrFields) {
+                                xhr[ i ] = s.xhrFields[ i ];
+                            }
+                        }
+
+                        // Override mime type if needed
+                        if (s.mimeType && xhr.overrideMimeType) {
+                            xhr.overrideMimeType(s.mimeType);
+                        }
+
+                        // X-Requested-With header
+                        // For cross-domain requests, seeing as conditions for a preflight are
+                        // akin to a jigsaw puzzle, we simply never set it to be sure.
+                        // (it can always be set on a per-request basis or even using ajaxSetup)
+                        // For same-domain requests, won't change header if already provided.
+                        if (!s.crossDomain && !headers["X-Requested-With"]) {
+                            headers[ "X-Requested-With" ] = "XMLHttpRequest";
+                        }
+
+                        // Need an extra try/catch for cross domain requests in Firefox 3
+                        try {
+                            for (i in headers) {
+                                xhr.setRequestHeader(i, headers[ i ]);
+                            }
+                        } catch (_) {
+                        }
+
+                        // Do send the request
+                        // This may raise an exception which is actually
+                        // handled in jQuery.ajax (so no try/catch here)
+                        xhr.send(( s.hasContent && s.data ) || null);
+
+                        // Listener
+                        callback = function (_, isAbort) {
+
+                            var status,
+                                statusText,
+                                responseHeaders,
+                                responses,
+                                xml;
+
+                            // Firefox throws exceptions when accessing properties
+                            // of an xhr when a network error occured
+                            // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
+                            try {
+
+                                // Was never called and is aborted or complete
+                                if (callback && ( isAbort || xhr.readyState === 4 )) {
+
+                                    // Only called once
+                                    callback = undefined;
+
+                                    // Do not keep as active anymore
+                                    if (handle) {
+                                        xhr.onreadystatechange = jQuery.noop;
+                                        if (xhrOnUnloadAbort) {
+                                            delete xhrCallbacks[ handle ];
+                                        }
+                                    }
+
+                                    // If it's an abort
+                                    if (isAbort) {
+                                        // Abort it manually if needed
+                                        if (xhr.readyState !== 4) {
+                                            xhr.abort();
+                                        }
+                                    } else {
+                                        status = xhr.status;
+                                        responseHeaders = xhr.getAllResponseHeaders();
+                                        responses = {};
+                                        xml = xhr.responseXML;
+
+                                        // Construct response list
+                                        if (xml && xml.documentElement /* #4958 */) {
+                                            responses.xml = xml;
+                                        }
+                                        responses.text = xhr.responseText;
+
+                                        // Firefox throws an exception when accessing
+                                        // statusText for faulty cross-domain requests
+                                        try {
+                                            statusText = xhr.statusText;
+                                        } catch (e) {
+                                            // We normalize with Webkit giving an empty statusText
+                                            statusText = "";
+                                        }
+
+                                        // Filter status for non standard behaviors
+
+                                        // If the request is local and we have data: assume a success
+                                        // (success with no data won't get notified, that's the best we
+                                        // can do given current implementations)
+                                        if (!status && s.isLocal && !s.crossDomain) {
+                                            status = responses.text ? 200 : 404;
+                                            // IE - #1450: sometimes returns 1223 when it should be 204
+                                        } else if (status === 1223) {
+                                            status = 204;
+                                        }
+                                    }
+                                }
+                            } catch (firefoxAccessException) {
+                                if (!isAbort) {
+                                    complete(-1, firefoxAccessException);
+                                }
+                            }
+
+                            // Call complete if needed
+                            if (responses) {
+                                complete(status, statusText, responses, responseHeaders);
+                            }
+                        };
+
+                        // if we're in sync mode or it's in cache
+                        // and has been retrieved directly (IE6 & IE7)
+                        // we need to manually fire the callback
+                        if (!s.async || xhr.readyState === 4) {
+                            callback();
+                        } else {
+                            handle = ++xhrId;
+                            if (xhrOnUnloadAbort) {
+                                // Create the active xhrs callbacks list if needed
+                                // and attach the unload handler
+                                if (!xhrCallbacks) {
+                                    xhrCallbacks = {};
+                                    jQuery(window).unload(xhrOnUnloadAbort);
+                                }
+                                // Add to list of active xhrs callbacks
+                                xhrCallbacks[ handle ] = callback;
+                            }
+                            xhr.onreadystatechange = callback;
+                        }
+                    },
+
+                    abort: function () {
+                        if (callback) {
+                            callback(0, 1);
+                        }
+                    }
+                };
+            }
+        });
+    }
+
+
+    var elemdisplay = {},
+        iframe, iframeDoc,
+        rfxtypes = /^(?:toggle|show|hide)$/,
+        rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
+        timerId,
+        fxAttrs = [
+            // height animations
+            [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
+            // width animations
+            [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
+            // opacity animations
+            [ "opacity" ]
+        ],
+        fxNow;
+
+    jQuery.fn.extend({
+        show: function (speed, easing, callback) {
+            var elem, display;
+
+            if (speed || speed === 0) {
+                return this.animate(genFx("show", 3), speed, easing, callback);
+
+            } else {
+                for (var i = 0, j = this.length; i < j; i++) {
+                    elem = this[ i ];
+
+                    if (elem.style) {
+                        display = elem.style.display;
+
+                        // Reset the inline display of this element to learn if it is
+                        // being hidden by cascaded rules or not
+                        if (!jQuery._data(elem, "olddisplay") && display === "none") {
+                            display = elem.style.display = "";
+                        }
+
+                        // Set elements which have been overridden with display: none
+                        // in a stylesheet to whatever the default browser style is
+                        // for such an element
+                        if (display === "" && jQuery.css(elem, "display") === "none") {
+                            jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName));
+                        }
+                    }
+                }
+
+                // Set the display of most of the elements in a second loop
+                // to avoid the constant reflow
+                for (i = 0; i < j; i++) {
+                    elem = this[ i ];
+
+                    if (elem.style) {
+                        display = elem.style.display;
+
+                        if (display === "" || display === "none") {
+                            elem.style.display = jQuery._data(elem, "olddisplay") || "";
+                        }
+                    }
+                }
+
+                return this;
+            }
+        },
+
+        hide: function (speed, easing, callback) {
+            if (speed || speed === 0) {
+                return this.animate(genFx("hide", 3), speed, easing, callback);
+
+            } else {
+                var elem, display,
+                    i = 0,
+                    j = this.length;
+
+                for (; i < j; i++) {
+                    elem = this[i];
+                    if (elem.style) {
+                        display = jQuery.css(elem, "display");
+
+                        if (display !== "none" && !jQuery._data(elem, "olddisplay")) {
+                            jQuery._data(elem, "olddisplay", display);
+                        }
+                    }
+                }
+
+                // Set the display of the elements in a second loop
+                // to avoid the constant reflow
+                for (i = 0; i < j; i++) {
+                    if (this[i].style) {
+                        this[i].style.display = "none";
+                    }
+                }
+
+                return this;
+            }
+        },
+
+        // Save the old toggle function
+        _toggle: jQuery.fn.toggle,
+
+        toggle: function (fn, fn2, callback) {
+            var bool = typeof fn === "boolean";
+
+            if (jQuery.isFunction(fn) && jQuery.isFunction(fn2)) {
+                this._toggle.apply(this, arguments);
+
+            } else if (fn == null || bool) {
+                this.each(function () {
+                    var state = bool ? fn : jQuery(this).is(":hidden");
+                    jQuery(this)[ state ? "show" : "hide" ]();
+                });
+
+            } else {
+                this.animate(genFx("toggle", 3), fn, fn2, callback);
+            }
+
+            return this;
+        },
+
+        fadeTo: function (speed, to, easing, callback) {
+            return this.filter(":hidden").css("opacity", 0).show().end()
+                .animate({opacity: to}, speed, easing, callback);
+        },
+
+        animate: function (prop, speed, easing, callback) {
+            var optall = jQuery.speed(speed, easing, callback);
+
+            if (jQuery.isEmptyObject(prop)) {
+                return this.each(optall.complete, [ false ]);
+            }
+
+            // Do not change referenced properties as per-property easing will be lost
+            prop = jQuery.extend({}, prop);
+
+            function doAnimation() {
+                // XXX 'this' does not always have a nodeName when running the
+                // test suite
+
+                if (optall.queue === false) {
+                    jQuery._mark(this);
+                }
+
+                var opt = jQuery.extend({}, optall),
+                    isElement = this.nodeType === 1,
+                    hidden = isElement && jQuery(this).is(":hidden"),
+                    name, val, p, e,
+                    parts, start, end, unit,
+                    method;
+
+                // will store per property easing and be used to determine when an animation is complete
+                opt.animatedProperties = {};
+
+                for (p in prop) {
+
+                    // property name normalization
+                    name = jQuery.camelCase(p);
+                    if (p !== name) {
+                        prop[ name ] = prop[ p ];
+                        delete prop[ p ];
+                    }
+
+                    val = prop[ name ];
+
+                    // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
+                    if (jQuery.isArray(val)) {
+                        opt.animatedProperties[ name ] = val[ 1 ];
+                        val = prop[ name ] = val[ 0 ];
+                    } else {
+                        opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
+                    }
+
+                    if (val === "hide" && hidden || val === "show" && !hidden) {
+                        return opt.complete.call(this);
+                    }
+
+                    if (isElement && ( name === "height" || name === "width" )) {
+                        // Make sure that nothing sneaks out
+                        // Record all 3 overflow attributes because IE does not
+                        // change the overflow attribute when overflowX and
+                        // overflowY are set to the same value
+                        opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
+
+                        // Set display property to inline-block for height/width
+                        // animations on inline elements that are having width/height animated
+                        if (jQuery.css(this, "display") === "inline" &&
+                            jQuery.css(this, "float") === "none") {
+
+                            // inline-level elements accept inline-block;
+                            // block-level elements need to be inline with layout
+                            if (!jQuery.support.inlineBlockNeedsLayout || defaultDisplay(this.nodeName) === "inline") {
+                                this.style.display = "inline-block";
+
+                            } else {
+                                this.style.zoom = 1;
+                            }
+                        }
+                    }
+                }
+
+                if (opt.overflow != null) {
+                    this.style.overflow = "hidden";
+                }
+
+                for (p in prop) {
+                    e = new jQuery.fx(this, opt, p);
+                    val = prop[ p ];
+
+                    if (rfxtypes.test(val)) {
+
+                        // Tracks whether to show or hide based on private
+                        // data attached to the element
+                        method = jQuery._data(this, "toggle" + p) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 );
+                        if (method) {
+                            jQuery._data(this, "toggle" + p, method === "show" ? "hide" : "show");
+                            e[ method ]();
+                        } else {
+                            e[ val ]();
+                        }
+
+                    } else {
+                        parts = rfxnum.exec(val);
+                        start = e.cur();
+
+                        if (parts) {
+                            end = parseFloat(parts[2]);
+                            unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
+
+                            // We need to compute starting value
+                            if (unit !== "px") {
+                                jQuery.style(this, p, (end || 1) + unit);
+                                start = ( (end || 1) / e.cur() ) * start;
+                                jQuery.style(this, p, start + unit);
+                            }
+
+                            // If a +=/-= token was provided, we're doing a relative animation
+                            if (parts[1]) {
+                                end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
+                            }
+
+                            e.custom(start, end, unit);
+
+                        } else {
+                            e.custom(start, val, "");
+                        }
+                    }
+                }
+
+                // For JS strict compliance
+                return true;
+            }
+
+            return optall.queue === false ?
+                this.each(doAnimation) :
+                this.queue(optall.queue, doAnimation);
+        },
+
+        stop: function (type, clearQueue, gotoEnd) {
+            if (typeof type !== "string") {
+                gotoEnd = clearQueue;
+                clearQueue = type;
+                type = undefined;
+            }
+            if (clearQueue && type !== false) {
+                this.queue(type || "fx", []);
+            }
+
+            return this.each(function () {
+                var index,
+                    hadTimers = false,
+                    timers = jQuery.timers,
+                    data = jQuery._data(this);
+
+                // clear marker counters if we know they won't be
+                if (!gotoEnd) {
+                    jQuery._unmark(true, this);
+                }
+
+                function stopQueue(elem, data, index) {
+                    var hooks = data[ index ];
+                    jQuery.removeData(elem, index, true);
+                    hooks.stop(gotoEnd);
+                }
+
+                if (type == null) {
+                    for (index in data) {
+                        if (data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4) {
+                            stopQueue(this, data, index);
+                        }
+                    }
+                } else if (data[ index = type + ".run" ] && data[ index ].stop) {
+                    stopQueue(this, data, index);
+                }
+
+                for (index = timers.length; index--;) {
+                    if (timers[ index ].elem === this && (type == null || timers[ index ].queue === type)) {
+                        if (gotoEnd) {
+
+                            // force the next step to be the last
+                            timers[ index ](true);
+                        } else {
+                            timers[ index ].saveState();
+                        }
+                        hadTimers = true;
+                        timers.splice(index, 1);
+                    }
+                }
+
+                // start the next in the queue if the last step wasn't forced
+                // timers currently will call their complete callbacks, which will dequeue
+                // but only if they were gotoEnd
+                if (!( gotoEnd && hadTimers )) {
+                    jQuery.dequeue(this, type);
+                }
+            });
+        }
+
+    });
 
 // Animations created synchronously will run synchronously
-function createFxNow() {
-	setTimeout( clearFxNow, 0 );
-	return ( fxNow = jQuery.now() );
-}
+    function createFxNow() {
+        setTimeout(clearFxNow, 0);
+        return ( fxNow = jQuery.now() );
+    }
 
-function clearFxNow() {
-	fxNow = undefined;
-}
+    function clearFxNow() {
+        fxNow = undefined;
+    }
 
 // Generate parameters to create a standard animation
-function genFx( type, num ) {
-	var obj = {};
+    function genFx(type, num) {
+        var obj = {};
 
-	jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() {
-		obj[ this ] = type;
-	});
+        jQuery.each(fxAttrs.concat.apply([], fxAttrs.slice(0, num)), function () {
+            obj[ this ] = type;
+        });
 
-	return obj;
-}
+        return obj;
+    }
 
 // Generate shortcuts for custom animations
-jQuery.each({
-	slideDown: genFx( "show", 1 ),
-	slideUp: genFx( "hide", 1 ),
-	slideToggle: genFx( "toggle", 1 ),
-	fadeIn: { opacity: "show" },
-	fadeOut: { opacity: "hide" },
-	fadeToggle: { opacity: "toggle" }
-}, function( name, props ) {
-	jQuery.fn[ name ] = function( speed, easing, callback ) {
-		return this.animate( props, speed, easing, callback );
-	};
-});
-
-jQuery.extend({
-	speed: function( speed, easing, fn ) {
-		var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
-			complete: fn || !fn && easing ||
-				jQuery.isFunction( speed ) && speed,
-			duration: speed,
-			easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
-		};
-
-		opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
-			opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
-
-		// normalize opt.queue - true/undefined/null -> "fx"
-		if ( opt.queue == null || opt.queue === true ) {
-			opt.queue = "fx";
-		}
-
-		// Queueing
-		opt.old = opt.complete;
-
-		opt.complete = function( noUnmark ) {
-			if ( jQuery.isFunction( opt.old ) ) {
-				opt.old.call( this );
-			}
-
-			if ( opt.queue ) {
-				jQuery.dequeue( this, opt.queue );
-			} else if ( noUnmark !== false ) {
-				jQuery._unmark( this );
-			}
-		};
-
-		return opt;
-	},
-
-	easing: {
-		linear: function( p, n, firstNum, diff ) {
-			return firstNum + diff * p;
-		},
-		swing: function( p, n, firstNum, diff ) {
-			return ( ( -Math.cos( p*Math.PI ) / 2 ) + 0.5 ) * diff + firstNum;
-		}
-	},
-
-	timers: [],
-
-	fx: function( elem, options, prop ) {
-		this.options = options;
-		this.elem = elem;
-		this.prop = prop;
-
-		options.orig = options.orig || {};
-	}
-
-});
-
-jQuery.fx.prototype = {
-	// Simple function for setting a style value
-	update: function() {
-		if ( this.options.step ) {
-			this.options.step.call( this.elem, this.now, this );
-		}
-
-		( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this );
-	},
-
-	// Get the current size
-	cur: function() {
-		if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) {
-			return this.elem[ this.prop ];
-		}
-
-		var parsed,
-			r = jQuery.css( this.elem, this.prop );
-		// Empty strings, null, undefined and "auto" are converted to 0,
-		// complex values such as "rotate(1rad)" are returned as is,
-		// simple values such as "10px" are parsed to Float.
-		return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
-	},
-
-	// Start an animation from one number to another
-	custom: function( from, to, unit ) {
-		var self = this,
-			fx = jQuery.fx;
-
-		this.startTime = fxNow || createFxNow();
-		this.end = to;
-		this.now = this.start = from;
-		this.pos = this.state = 0;
-		this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
-
-		function t( gotoEnd ) {
-			return self.step( gotoEnd );
-		}
-
-		t.queue = this.options.queue;
-		t.elem = this.elem;
-		t.saveState = function() {
-			if ( self.options.hide && jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) {
-				jQuery._data( self.elem, "fxshow" + self.prop, self.start );
-			}
-		};
-
-		if ( t() && jQuery.timers.push(t) && !timerId ) {
-			timerId = setInterval( fx.tick, fx.interval );
-		}
-	},
-
-	// Simple 'show' function
-	show: function() {
-		var dataShow = jQuery._data( this.elem, "fxshow" + this.prop );
-
-		// Remember where we started, so that we can go back to it later
-		this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop );
-		this.options.show = true;
-
-		// Begin the animation
-		// Make sure that we start at a small width/height to avoid any flash of content
-		if ( dataShow !== undefined ) {
-			// This show is picking up where a previous hide or show left off
-			this.custom( this.cur(), dataShow );
-		} else {
-			this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() );
-		}
-
-		// Start by showing the element
-		jQuery( this.elem ).show();
-	},
-
-	// Simple 'hide' function
-	hide: function() {
-		// Remember where we started, so that we can go back to it later
-		this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop );
-		this.options.hide = true;
-
-		// Begin the animation
-		this.custom( this.cur(), 0 );
-	},
-
-	// Each step of an animation
-	step: function( gotoEnd ) {
-		var p, n, complete,
-			t = fxNow || createFxNow(),
-			done = true,
-			elem = this.elem,
-			options = this.options;
-
-		if ( gotoEnd || t >= options.duration + this.startTime ) {
-			this.now = this.end;
-			this.pos = this.state = 1;
-			this.update();
-
-			options.animatedProperties[ this.prop ] = true;
-
-			for ( p in options.animatedProperties ) {
-				if ( options.animatedProperties[ p ] !== true ) {
-					done = false;
-				}
-			}
-
-			if ( done ) {
-				// Reset the overflow
-				if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
-
-					jQuery.each( [ "", "X", "Y" ], function( index, value ) {
-						elem.style[ "overflow" + value ] = options.overflow[ index ];
-					});
-				}
-
-				// Hide the element if the "hide" operation was done
-				if ( options.hide ) {
-					jQuery( elem ).hide();
-				}
-
-				// Reset the properties, if the item has been hidden or shown
-				if ( options.hide || options.show ) {
-					for ( p in options.animatedProperties ) {
-						jQuery.style( elem, p, options.orig[ p ] );
-						jQuery.removeData( elem, "fxshow" + p, true );
-						// Toggle data is no longer needed
-						jQuery.removeData( elem, "toggle" + p, true );
-					}
-				}
-
-				// Execute the complete function
-				// in the event that the complete function throws an exception
-				// we must ensure it won't be called twice. #5684
-
-				complete = options.complete;
-				if ( complete ) {
-
-					options.complete = false;
-					complete.call( elem );
-				}
-			}
-
-			return false;
-
-		} else {
-			// classical easing cannot be used with an Infinity duration
-			if ( options.duration == Infinity ) {
-				this.now = t;
-			} else {
-				n = t - this.startTime;
-				this.state = n / options.duration;
-
-				// Perform the easing function, defaults to swing
-				this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration );
-				this.now = this.start + ( (this.end - this.start) * this.pos );
-			}
-			// Perform the next step of the animation
-			this.update();
-		}
-
-		return true;
-	}
-};
-
-jQuery.extend( jQuery.fx, {
-	tick: function() {
-		var timer,
-			timers = jQuery.timers,
-			i = 0;
-
-		for ( ; i < timers.length; i++ ) {
-			timer = timers[ i ];
-			// Checks the timer has not already been removed
-			if ( !timer() && timers[ i ] === timer ) {
-				timers.splice( i--, 1 );
-			}
-		}
-
-		if ( !timers.length ) {
-			jQuery.fx.stop();
-		}
-	},
-
-	interval: 13,
-
-	stop: function() {
-		clearInterval( timerId );
-		timerId = null;
-	},
-
-	speeds: {
-		slow: 600,
-		fast: 200,
-		// Default speed
-		_default: 400
-	},
-
-	step: {
-		opacity: function( fx ) {
-			jQuery.style( fx.elem, "opacity", fx.now );
-		},
-
-		_default: function( fx ) {
-			if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
-				fx.elem.style[ fx.prop ] = fx.now + fx.unit;
-			} else {
-				fx.elem[ fx.prop ] = fx.now;
-			}
-		}
-	}
-});
+    jQuery.each({
+        slideDown: genFx("show", 1),
+        slideUp: genFx("hide", 1),
+        slideToggle: genFx("toggle", 1),
+        fadeIn: { opacity: "show" },
+        fadeOut: { opacity: "hide" },
+        fadeToggle: { opacity: "toggle" }
+    }, function (name, props) {
+        jQuery.fn[ name ] = function (speed, easing, callback) {
+            return this.animate(props, speed, easing, callback);
+        };
+    });
+
+    jQuery.extend({
+        speed: function (speed, easing, fn) {
+            var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : {
+                complete: fn || !fn && easing ||
+                    jQuery.isFunction(speed) && speed,
+                duration: speed,
+                easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
+            };
+
+            opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
+                opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
+
+            // normalize opt.queue - true/undefined/null -> "fx"
+            if (opt.queue == null || opt.queue === true) {
+                opt.queue = "fx";
+            }
+
+            // Queueing
+            opt.old = opt.complete;
+
+            opt.complete = function (noUnmark) {
+                if (jQuery.isFunction(opt.old)) {
+                    opt.old.call(this);
+                }
+
+                if (opt.queue) {
+                    jQuery.dequeue(this, opt.queue);
+                } else if (noUnmark !== false) {
+                    jQuery._unmark(this);
+                }
+            };
+
+            return opt;
+        },
+
+        easing: {
+            linear: function (p, n, firstNum, diff) {
+                return firstNum + diff * p;
+            },
+            swing: function (p, n, firstNum, diff) {
+                return ( ( -Math.cos(p * Math.PI) / 2 ) + 0.5 ) * diff + firstNum;
+            }
+        },
+
+        timers: [],
+
+        fx: function (elem, options, prop) {
+            this.options = options;
+            this.elem = elem;
+            this.prop = prop;
+
+            options.orig = options.orig || {};
+        }
+
+    });
+
+    jQuery.fx.prototype = {
+        // Simple function for setting a style value
+        update: function () {
+            if (this.options.step) {
+                this.options.step.call(this.elem, this.now, this);
+            }
+
+            ( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )(this);
+        },
+
+        // Get the current size
+        cur: function () {
+            if (this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null)) {
+                return this.elem[ this.prop ];
+            }
+
+            var parsed,
+                r = jQuery.css(this.elem, this.prop);
+            // Empty strings, null, undefined and "auto" are converted to 0,
+            // complex values such as "rotate(1rad)" are returned as is,
+            // simple values such as "10px" are parsed to Float.
+            return isNaN(parsed = parseFloat(r)) ? !r || r === "auto" ? 0 : r : parsed;
+        },
+
+        // Start an animation from one number to another
+        custom: function (from, to, unit) {
+            var self = this,
+                fx = jQuery.fx;
+
+            this.startTime = fxNow || createFxNow();
+            this.end = to;
+            this.now = this.start = from;
+            this.pos = this.state = 0;
+            this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
+
+            function t(gotoEnd) {
+                return self.step(gotoEnd);
+            }
+
+            t.queue = this.options.queue;
+            t.elem = this.elem;
+            t.saveState = function () {
+                if (self.options.hide && jQuery._data(self.elem, "fxshow" + self.prop) === undefined) {
+                    jQuery._data(self.elem, "fxshow" + self.prop, self.start);
+                }
+            };
+
+            if (t() && jQuery.timers.push(t) && !timerId) {
+                timerId = setInterval(fx.tick, fx.interval);
+            }
+        },
+
+        // Simple 'show' function
+        show: function () {
+            var dataShow = jQuery._data(this.elem, "fxshow" + this.prop);
+
+            // Remember where we started, so that we can go back to it later
+            this.options.orig[ this.prop ] = dataShow || jQuery.style(this.elem, this.prop);
+            this.options.show = true;
+
+            // Begin the animation
+            // Make sure that we start at a small width/height to avoid any flash of content
+            if (dataShow !== undefined) {
+                // This show is picking up where a previous hide or show left off
+                this.custom(this.cur(), dataShow);
+            } else {
+                this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur());
+            }
+
+            // Start by showing the element
+            jQuery(this.elem).show();
+        },
+
+        // Simple 'hide' function
+        hide: function () {
+            // Remember where we started, so that we can go back to it later
+            this.options.orig[ this.prop ] = jQuery._data(this.elem, "fxshow" + this.prop) || jQuery.style(this.elem, this.prop);
+            this.options.hide = true;
+
+            // Begin the animation
+            this.custom(this.cur(), 0);
+        },
+
+        // Each step of an animation
+        step: function (gotoEnd) {
+            var p, n, complete,
+                t = fxNow || createFxNow(),
+                done = true,
+                elem = this.elem,
+                options = this.options;
+
+            if (gotoEnd || t >= options.duration + this.startTime) {
+                this.now = this.end;
+                this.pos = this.state = 1;
+                this.update();
+
+                options.animatedProperties[ this.prop ] = true;
+
+                for (p in options.animatedProperties) {
+                    if (options.animatedProperties[ p ] !== true) {
+                        done = false;
+                    }
+                }
+
+                if (done) {
+                    // Reset the overflow
+                    if (options.overflow != null && !jQuery.support.shrinkWrapBlocks) {
+
+                        jQuery.each([ "", "X", "Y" ], function (index, value) {
+                            elem.style[ "overflow" + value ] = options.overflow[ index ];
+                        });
+                    }
+
+                    // Hide the element if the "hide" operation was done
+                    if (options.hide) {
+                        jQuery(elem).hide();
+                    }
+
+                    // Reset the properties, if the item has been hidden or shown
+                    if (options.hide || options.show) {
+                        for (p in options.animatedProperties) {
+                            jQuery.style(elem, p, options.orig[ p ]);
+                            jQuery.removeData(elem, "fxshow" + p, true);
+                            // Toggle data is no longer needed
+                            jQuery.removeData(elem, "toggle" + p, true);
+                        }
+                    }
+
+                    // Execute the complete function
+                    // in the event that the complete function throws an exception
+                    // we must ensure it won't be called twice. #5684
+
+                    complete = options.complete;
+                    if (complete) {
+
+                        options.complete = false;
+                        complete.call(elem);
+                    }
+                }
+
+                return false;
+
+            } else {
+                // classical easing cannot be used with an Infinity duration
+                if (options.duration == Infinity) {
+                    this.now = t;
+                } else {
+                    n = t - this.startTime;
+                    this.state = n / options.duration;
+
+                    // Perform the easing function, defaults to swing
+                    this.pos = jQuery.easing[ options.animatedProperties[this.prop] ](this.state, n, 0, 1, options.duration);
+                    this.now = this.start + ( (this.end - this.start) * this.pos );
+                }
+                // Perform the next step of the animation
+                this.update();
+            }
+
+            return true;
+        }
+    };
+
+    jQuery.extend(jQuery.fx, {
+        tick: function () {
+            var timer,
+                timers = jQuery.timers,
+                i = 0;
+
+            for (; i < timers.length; i++) {
+                timer = timers[ i ];
+                // Checks the timer has not already been removed
+                if (!timer() && timers[ i ] === timer) {
+                    timers.splice(i--, 1);
+                }
+            }
+
+            if (!timers.length) {
+                jQuery.fx.stop();
+            }
+        },
+
+        interval: 13,
+
+        stop: function () {
+            clearInterval(timerId);
+            timerId = null;
+        },
+
+        speeds: {
+            slow: 600,
+            fast: 200,
+            // Default speed
+            _default: 400
+        },
+
+        step: {
+            opacity: function (fx) {
+                jQuery.style(fx.elem, "opacity", fx.now);
+            },
+
+            _default: function (fx) {
+                if (fx.elem.style && fx.elem.style[ fx.prop ] != null) {
+                    fx.elem.style[ fx.prop ] = fx.now + fx.unit;
+                } else {
+                    fx.elem[ fx.prop ] = fx.now;
+                }
+            }
+        }
+    });
 
 // Adds width/height step functions
 // Do not set anything below 0
-jQuery.each([ "width", "height" ], function( i, prop ) {
-	jQuery.fx.step[ prop ] = function( fx ) {
-		jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit );
-	};
-});
-
-if ( jQuery.expr && jQuery.expr.filters ) {
-	jQuery.expr.filters.animated = function( elem ) {
-		return jQuery.grep(jQuery.timers, function( fn ) {
-			return elem === fn.elem;
-		}).length;
-	};
-}
+    jQuery.each([ "width", "height" ], function (i, prop) {
+        jQuery.fx.step[ prop ] = function (fx) {
+            jQuery.style(fx.elem, prop, Math.max(0, fx.now) + fx.unit);
+        };
+    });
+
+    if (jQuery.expr && jQuery.expr.filters) {
+        jQuery.expr.filters.animated = function (elem) {
+            return jQuery.grep(jQuery.timers,function (fn) {
+                return elem === fn.elem;
+            }).length;
+        };
+    }
 
 // Try to restore the default display value of an element
-function defaultDisplay( nodeName ) {
-
-	if ( !elemdisplay[ nodeName ] ) {
-
-		var body = document.body,
-			elem = jQuery( "<" + nodeName + ">" ).appendTo( body ),
-			display = elem.css( "display" );
-		elem.remove();
-
-		// If the simple way fails,
-		// get element's real default display by attaching it to a temp iframe
-		if ( display === "none" || display === "" ) {
-			// No iframe to use yet, so create it
-			if ( !iframe ) {
-				iframe = document.createElement( "iframe" );
-				iframe.frameBorder = iframe.width = iframe.height = 0;
-			}
-
-			body.appendChild( iframe );
-
-			// Create a cacheable copy of the iframe document on first call.
-			// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
-			// document to it; WebKit & Firefox won't allow reusing the iframe document.
-			if ( !iframeDoc || !iframe.createElement ) {
-				iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
-				iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" );
-				iframeDoc.close();
-			}
-
-			elem = iframeDoc.createElement( nodeName );
-
-			iframeDoc.body.appendChild( elem );
-
-			display = jQuery.css( elem, "display" );
-			body.removeChild( iframe );
-		}
-
-		// Store the correct default display
-		elemdisplay[ nodeName ] = display;
-	}
-
-	return elemdisplay[ nodeName ];
-}
-
-
-
-
-var rtable = /^t(?:able|d|h)$/i,
-	rroot = /^(?:body|html)$/i;
-
-if ( "getBoundingClientRect" in document.documentElement ) {
-	jQuery.fn.offset = function( options ) {
-		var elem = this[0], box;
-
-		if ( options ) {
-			return this.each(function( i ) {
-				jQuery.offset.setOffset( this, options, i );
-			});
-		}
-
-		if ( !elem || !elem.ownerDocument ) {
-			return null;
-		}
-
-		if ( elem === elem.ownerDocument.body ) {
-			return jQuery.offset.bodyOffset( elem );
-		}
-
-		try {
-			box = elem.getBoundingClientRect();
-		} catch(e) {}
-
-		var doc = elem.ownerDocument,
-			docElem = doc.documentElement;
-
-		// Make sure we're not dealing with a disconnected DOM node
-		if ( !box || !jQuery.contains( docElem, elem ) ) {
-			return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
-		}
-
-		var body = doc.body,
-			win = getWindow(doc),
-			clientTop  = docElem.clientTop  || body.clientTop  || 0,
-			clientLeft = docElem.clientLeft || body.clientLeft || 0,
-			scrollTop  = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop  || body.scrollTop,
-			scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
-			top  = box.top  + scrollTop  - clientTop,
-			left = box.left + scrollLeft - clientLeft;
-
-		return { top: top, left: left };
-	};
-
-} else {
-	jQuery.fn.offset = function( options ) {
-		var elem = this[0];
-
-		if ( options ) {
-			return this.each(function( i ) {
-				jQuery.offset.setOffset( this, options, i );
-			});
-		}
-
-		if ( !elem || !elem.ownerDocument ) {
-			return null;
-		}
-
-		if ( elem === elem.ownerDocument.body ) {
-			return jQuery.offset.bodyOffset( elem );
-		}
-
-		var computedStyle,
-			offsetParent = elem.offsetParent,
-			prevOffsetParent = elem,
-			doc = elem.ownerDocument,
-			docElem = doc.documentElement,
-			body = doc.body,
-			defaultView = doc.defaultView,
-			prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
-			top = elem.offsetTop,
-			left = elem.offsetLeft;
-
-		while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
-			if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
-				break;
-			}
-
-			computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
-			top  -= elem.scrollTop;
-			left -= elem.scrollLeft;
-
-			if ( elem === offsetParent ) {
-				top  += elem.offsetTop;
-				left += elem.offsetLeft;
-
-				if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
-					top  += parseFloat( computedStyle.borderTopWidth  ) || 0;
-					left += parseFloat( computedStyle.borderLeftWidth ) || 0;
-				}
-
-				prevOffsetParent = offsetParent;
-				offsetParent = elem.offsetParent;
-			}
-
-			if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
-				top  += parseFloat( computedStyle.borderTopWidth  ) || 0;
-				left += parseFloat( computedStyle.borderLeftWidth ) || 0;
-			}
-
-			prevComputedStyle = computedStyle;
-		}
-
-		if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
-			top  += body.offsetTop;
-			left += body.offsetLeft;
-		}
-
-		if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
-			top  += Math.max( docElem.scrollTop, body.scrollTop );
-			left += Math.max( docElem.scrollLeft, body.scrollLeft );
-		}
-
-		return { top: top, left: left };
-	};
-}
-
-jQuery.offset = {
-
-	bodyOffset: function( body ) {
-		var top = body.offsetTop,
-			left = body.offsetLeft;
-
-		if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
-			top  += parseFloat( jQuery.css(body, "marginTop") ) || 0;
-			left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
-		}
-
-		return { top: top, left: left };
-	},
-
-	setOffset: function( elem, options, i ) {
-		var position = jQuery.css( elem, "position" );
-
-		// set position first, in-case top/left are set even on static elem
-		if ( position === "static" ) {
-			elem.style.position = "relative";
-		}
-
-		var curElem = jQuery( elem ),
-			curOffset = curElem.offset(),
-			curCSSTop = jQuery.css( elem, "top" ),
-			curCSSLeft = jQuery.css( elem, "left" ),
-			calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
-			props = {}, curPosition = {}, curTop, curLeft;
-
-		// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
-		if ( calculatePosition ) {
-			curPosition = curElem.position();
-			curTop = curPosition.top;
-			curLeft = curPosition.left;
-		} else {
-			curTop = parseFloat( curCSSTop ) || 0;
-			curLeft = parseFloat( curCSSLeft ) || 0;
-		}
-
-		if ( jQuery.isFunction( options ) ) {
-			options = options.call( elem, i, curOffset );
-		}
-
-		if ( options.top != null ) {
-			props.top = ( options.top - curOffset.top ) + curTop;
-		}
-		if ( options.left != null ) {
-			props.left = ( options.left - curOffset.left ) + curLeft;
-		}
-
-		if ( "using" in options ) {
-			options.using.call( elem, props );
-		} else {
-			curElem.css( props );
-		}
-	}
-};
-
-
-jQuery.fn.extend({
-
-	position: function() {
-		if ( !this[0] ) {
-			return null;
-		}
-
-		var elem = this[0],
-
-		// Get *real* offsetParent
-		offsetParent = this.offsetParent(),
-
-		// Get correct offsets
-		offset       = this.offset(),
-		parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
-
-		// Subtract element margins
-		// note: when an element has margin: auto the offsetLeft and marginLeft
-		// are the same in Safari causing offset.left to incorrectly be 0
-		offset.top  -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
-		offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
-
-		// Add offsetParent borders
-		parentOffset.top  += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
-		parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
-
-		// Subtract the two offsets
-		return {
-			top:  offset.top  - parentOffset.top,
-			left: offset.left - parentOffset.left
-		};
-	},
-
-	offsetParent: function() {
-		return this.map(function() {
-			var offsetParent = this.offsetParent || document.body;
-			while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
-				offsetParent = offsetParent.offsetParent;
-			}
-			return offsetParent;
-		});
-	}
-});
+    function defaultDisplay(nodeName) {
+
+        if (!elemdisplay[ nodeName ]) {
+
+            var body = document.body,
+                elem = jQuery("<" + nodeName + ">").appendTo(body),
+                display = elem.css("display");
+            elem.remove();
+
+            // If the simple way fails,
+            // get element's real default display by attaching it to a temp iframe
+            if (display === "none" || display === "") {
+                // No iframe to use yet, so create it
+                if (!iframe) {
+                    iframe = document.createElement("iframe");
+                    iframe.frameBorder = iframe.width = iframe.height = 0;
+                }
+
+                body.appendChild(iframe);
+
+                // Create a cacheable copy of the iframe document on first call.
+                // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
+                // document to it; WebKit & Firefox won't allow reusing the iframe document.
+                if (!iframeDoc || !iframe.createElement) {
+                    iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
+                    iframeDoc.write(( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>");
+                    iframeDoc.close();
+                }
+
+                elem = iframeDoc.createElement(nodeName);
+
+                iframeDoc.body.appendChild(elem);
+
+                display = jQuery.css(elem, "display");
+                body.removeChild(iframe);
+            }
+
+            // Store the correct default display
+            elemdisplay[ nodeName ] = display;
+        }
+
+        return elemdisplay[ nodeName ];
+    }
+
+
+    var rtable = /^t(?:able|d|h)$/i,
+        rroot = /^(?:body|html)$/i;
+
+    if ("getBoundingClientRect" in document.documentElement) {
+        jQuery.fn.offset = function (options) {
+            var elem = this[0], box;
+
+            if (options) {
+                return this.each(function (i) {
+                    jQuery.offset.setOffset(this, options, i);
+                });
+            }
+
+            if (!elem || !elem.ownerDocument) {
+                return null;
+            }
+
+            if (elem === elem.ownerDocument.body) {
+                return jQuery.offset.bodyOffset(elem);
+            }
+
+            try {
+                box = elem.getBoundingClientRect();
+            } catch (e) {
+            }
+
+            var doc = elem.ownerDocument,
+                docElem = doc.documentElement;
+
+            // Make sure we're not dealing with a disconnected DOM node
+            if (!box || !jQuery.contains(docElem, elem)) {
+                return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
+            }
+
+            var body = doc.body,
+                win = getWindow(doc),
+                clientTop = docElem.clientTop || body.clientTop || 0,
+                clientLeft = docElem.clientLeft || body.clientLeft || 0,
+                scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop,
+                scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
+                top = box.top + scrollTop - clientTop,
+                left = box.left + scrollLeft - clientLeft;
+
+            return { top: top, left: left };
+        };
+
+    } else {
+        jQuery.fn.offset = function (options) {
+            var elem = this[0];
+
+            if (options) {
+                return this.each(function (i) {
+                    jQuery.offset.setOffset(this, options, i);
+                });
+            }
+
+            if (!elem || !elem.ownerDocument) {
+                return null;
+            }
+
+            if (elem === elem.ownerDocument.body) {
+                return jQuery.offset.bodyOffset(elem);
+            }
+
+            var computedStyle,
+                offsetParent = elem.offsetParent,
+                prevOffsetParent = elem,
+                doc = elem.ownerDocument,
+                docElem = doc.documentElement,
+                body = doc.body,
+                defaultView = doc.defaultView,
+                prevComputedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle,
+                top = elem.offsetTop,
+                left = elem.offsetLeft;
+
+            while ((elem = elem.parentNode) && elem !== body && elem !== docElem) {
+                if (jQuery.support.fixedPosition && prevComputedStyle.position === "fixed") {
+                    break;
+                }
+
+                computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
+                top -= elem.scrollTop;
+                left -= elem.scrollLeft;
+
+                if (elem === offsetParent) {
+                    top += elem.offsetTop;
+                    left += elem.offsetLeft;
+
+                    if (jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName))) {
+                        top += parseFloat(computedStyle.borderTopWidth) || 0;
+                        left += parseFloat(computedStyle.borderLeftWidth) || 0;
+                    }
+
+                    prevOffsetParent = offsetParent;
+                    offsetParent = elem.offsetParent;
+                }
+
+                if (jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible") {
+                    top += parseFloat(computedStyle.borderTopWidth) || 0;
+                    left += parseFloat(computedStyle.borderLeftWidth) || 0;
+                }
+
+                prevComputedStyle = computedStyle;
+            }
+
+            if (prevComputedStyle.position === "relative" || prevComputedStyle.position === "static") {
+                top += body.offsetTop;
+                left += body.offsetLeft;
+            }
+
+            if (jQuery.support.fixedPosition && prevComputedStyle.position === "fixed") {
+                top += Math.max(docElem.scrollTop, body.scrollTop);
+                left += Math.max(docElem.scrollLeft, body.scrollLeft);
+            }
+
+            return { top: top, left: left };
+        };
+    }
+
+    jQuery.offset = {
+
+        bodyOffset: function (body) {
+            var top = body.offsetTop,
+                left = body.offsetLeft;
+
+            if (jQuery.support.doesNotIncludeMarginInBodyOffset) {
+                top += parseFloat(jQuery.css(body, "marginTop")) || 0;
+                left += parseFloat(jQuery.css(body, "marginLeft")) || 0;
+            }
+
+            return { top: top, left: left };
+        },
+
+        setOffset: function (elem, options, i) {
+            var position = jQuery.css(elem, "position");
+
+            // set position first, in-case top/left are set even on static elem
+            if (position === "static") {
+                elem.style.position = "relative";
+            }
+
+            var curElem = jQuery(elem),
+                curOffset = curElem.offset(),
+                curCSSTop = jQuery.css(elem, "top"),
+                curCSSLeft = jQuery.css(elem, "left"),
+                calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
+                props = {}, curPosition = {}, curTop, curLeft;
+
+            // need to be able to calculate position if either top or left is auto and position is either absolute or fixed
+            if (calculatePosition) {
+                curPosition = curElem.position();
+                curTop = curPosition.top;
+                curLeft = curPosition.left;
+            } else {
+                curTop = parseFloat(curCSSTop) || 0;
+                curLeft = parseFloat(curCSSLeft) || 0;
+            }
+
+            if (jQuery.isFunction(options)) {
+                options = options.call(elem, i, curOffset);
+            }
+
+            if (options.top != null) {
+                props.top = ( options.top - curOffset.top ) + curTop;
+            }
+            if (options.left != null) {
+                props.left = ( options.left - curOffset.left ) + curLeft;
+            }
+
+            if ("using" in options) {
+                options.using.call(elem, props);
+            } else {
+                curElem.css(props);
+            }
+        }
+    };
+
+
+    jQuery.fn.extend({
+
+        position: function () {
+            if (!this[0]) {
+                return null;
+            }
+
+            var elem = this[0],
+
+            // Get *real* offsetParent
+                offsetParent = this.offsetParent(),
+
+            // Get correct offsets
+                offset = this.offset(),
+                parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
+
+            // Subtract element margins
+            // note: when an element has margin: auto the offsetLeft and marginLeft
+            // are the same in Safari causing offset.left to incorrectly be 0
+            offset.top -= parseFloat(jQuery.css(elem, "marginTop")) || 0;
+            offset.left -= parseFloat(jQuery.css(elem, "marginLeft")) || 0;
+
+            // Add offsetParent borders
+            parentOffset.top += parseFloat(jQuery.css(offsetParent[0], "borderTopWidth")) || 0;
+            parentOffset.left += parseFloat(jQuery.css(offsetParent[0], "borderLeftWidth")) || 0;
+
+            // Subtract the two offsets
+            return {
+                top: offset.top - parentOffset.top,
+                left: offset.left - parentOffset.left
+            };
+        },
+
+        offsetParent: function () {
+            return this.map(function () {
+                var offsetParent = this.offsetParent || document.body;
+                while (offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static")) {
+                    offsetParent = offsetParent.offsetParent;
+                }
+                return offsetParent;
+            });
+        }
+    });
 
 
 // Create scrollLeft and scrollTop methods
-jQuery.each( ["Left", "Top"], function( i, name ) {
-	var method = "scroll" + name;
-
-	jQuery.fn[ method ] = function( val ) {
-		var elem, win;
-
-		if ( val === undefined ) {
-			elem = this[ 0 ];
-
-			if ( !elem ) {
-				return null;
-			}
-
-			win = getWindow( elem );
-
-			// Return the scroll offset
-			return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
-				jQuery.support.boxModel && win.document.documentElement[ method ] ||
-					win.document.body[ method ] :
-				elem[ method ];
-		}
-
-		// Set the scroll offset
-		return this.each(function() {
-			win = getWindow( this );
-
-			if ( win ) {
-				win.scrollTo(
-					!i ? val : jQuery( win ).scrollLeft(),
-					 i ? val : jQuery( win ).scrollTop()
-				);
-
-			} else {
-				this[ method ] = val;
-			}
-		});
-	};
-});
-
-function getWindow( elem ) {
-	return jQuery.isWindow( elem ) ?
-		elem :
-		elem.nodeType === 9 ?
-			elem.defaultView || elem.parentWindow :
-			false;
-}
-
-
+    jQuery.each(["Left", "Top"], function (i, name) {
+        var method = "scroll" + name;
+
+        jQuery.fn[ method ] = function (val) {
+            var elem, win;
+
+            if (val === undefined) {
+                elem = this[ 0 ];
+
+                if (!elem) {
+                    return null;
+                }
+
+                win = getWindow(elem);
+
+                // Return the scroll offset
+                return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
+                    jQuery.support.boxModel && win.document.documentElement[ method ] ||
+                        win.document.body[ method ] :
+                    elem[ method ];
+            }
+
+            // Set the scroll offset
+            return this.each(function () {
+                win = getWindow(this);
+
+                if (win) {
+                    win.scrollTo(
+                        !i ? val : jQuery(win).scrollLeft(),
+                        i ? val : jQuery(win).scrollTop()
+                    );
+
+                } else {
+                    this[ method ] = val;
+                }
+            });
+        };
+    });
+
+    function getWindow(elem) {
+        return jQuery.isWindow(elem) ?
+            elem :
+            elem.nodeType === 9 ?
+                elem.defaultView || elem.parentWindow :
+                false;
+    }
 
 
 // Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
-jQuery.each([ "Height", "Width" ], function( i, name ) {
-
-	var type = name.toLowerCase();
-
-	// innerHeight and innerWidth
-	jQuery.fn[ "inner" + name ] = function() {
-		var elem = this[0];
-		return elem ?
-			elem.style ?
-			parseFloat( jQuery.css( elem, type, "padding" ) ) :
-			this[ type ]() :
-			null;
-	};
-
-	// outerHeight and outerWidth
-	jQuery.fn[ "outer" + name ] = function( margin ) {
-		var elem = this[0];
-		return elem ?
-			elem.style ?
-			parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) :
-			this[ type ]() :
-			null;
-	};
-
-	jQuery.fn[ type ] = function( size ) {
-		// Get window width or height
-		var elem = this[0];
-		if ( !elem ) {
-			return size == null ? null : this;
-		}
-
-		if ( jQuery.isFunction( size ) ) {
-			return this.each(function( i ) {
-				var self = jQuery( this );
-				self[ type ]( size.call( this, i, self[ type ]() ) );
-			});
-		}
-
-		if ( jQuery.isWindow( elem ) ) {
-			// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
-			// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
-			var docElemProp = elem.document.documentElement[ "client" + name ],
-				body = elem.document.body;
-			return elem.document.compatMode === "CSS1Compat" && docElemProp ||
-				body && body[ "client" + name ] || docElemProp;
-
-		// Get document width or height
-		} else if ( elem.nodeType === 9 ) {
-			// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
-			return Math.max(
-				elem.documentElement["client" + name],
-				elem.body["scroll" + name], elem.documentElement["scroll" + name],
-				elem.body["offset" + name], elem.documentElement["offset" + name]
-			);
-
-		// Get or set width or height on the element
-		} else if ( size === undefined ) {
-			var orig = jQuery.css( elem, type ),
-				ret = parseFloat( orig );
-
-			return jQuery.isNumeric( ret ) ? ret : orig;
-
-		// Set the width or height on the element (default to pixels if value is unitless)
-		} else {
-			return this.css( type, typeof size === "string" ? size : size + "px" );
-		}
-	};
-
-});
-
-
+    jQuery.each([ "Height", "Width" ], function (i, name) {
+
+        var type = name.toLowerCase();
+
+        // innerHeight and innerWidth
+        jQuery.fn[ "inner" + name ] = function () {
+            var elem = this[0];
+            return elem ?
+                elem.style ?
+                    parseFloat(jQuery.css(elem, type, "padding")) :
+                    this[ type ]() :
+                null;
+        };
+
+        // outerHeight and outerWidth
+        jQuery.fn[ "outer" + name ] = function (margin) {
+            var elem = this[0];
+            return elem ?
+                elem.style ?
+                    parseFloat(jQuery.css(elem, type, margin ? "margin" : "border")) :
+                    this[ type ]() :
+                null;
+        };
+
+        jQuery.fn[ type ] = function (size) {
+            // Get window width or height
+            var elem = this[0];
+            if (!elem) {
+                return size == null ? null : this;
+            }
+
+            if (jQuery.isFunction(size)) {
+                return this.each(function (i) {
+                    var self = jQuery(this);
+                    self[ type ](size.call(this, i, self[ type ]()));
+                });
+            }
+
+            if (jQuery.isWindow(elem)) {
+                // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
+                // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
+                var docElemProp = elem.document.documentElement[ "client" + name ],
+                    body = elem.document.body;
+                return elem.document.compatMode === "CSS1Compat" && docElemProp ||
+                    body && body[ "client" + name ] || docElemProp;
+
+                // Get document width or height
+            } else if (elem.nodeType === 9) {
+                // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
+                return Math.max(
+                    elem.documentElement["client" + name],
+                    elem.body["scroll" + name], elem.documentElement["scroll" + name],
+                    elem.body["offset" + name], elem.documentElement["offset" + name]
+                );
+
+                // Get or set width or height on the element
+            } else if (size === undefined) {
+                var orig = jQuery.css(elem, type),
+                    ret = parseFloat(orig);
+
+                return jQuery.isNumeric(ret) ? ret : orig;
+
+                // Set the width or height on the element (default to pixels if value is unitless)
+            } else {
+                return this.css(type, typeof size === "string" ? size : size + "px");
+            }
+        };
+
+    });
 
 
 // Expose jQuery to the global object
-window.jQuery = window.$ = jQuery;
+    window.jQuery = window.$ = jQuery;
 
 // Expose jQuery as an AMD module, but only for AMD loaders that
 // understand the issues with loading multiple versions of jQuery
@@ -9257,10 +9241,11 @@ window.jQuery = window.$ = jQuery;
 // file names, and jQuery is normally delivered in a lowercase file name.
 // Do this after creating the global so that if an AMD module wants to call
 // noConflict to hide this version of jQuery, it will work.
-if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
-	define( "jquery", [], function () { return jQuery; } );
-}
-
+    if (typeof define === "function" && define.amd && define.amd.jQuery) {
+        define("jquery", [], function () {
+            return jQuery;
+        });
+    }
 
 
-})( window );
+})(window);
diff --git a/media/js/lib/jquery-1.7.1.min.js b/media/js/lib/jquery-1.7.1.min.js
index 198b3ff..9aba6bb 100644
--- a/media/js/lib/jquery-1.7.1.min.js
+++ b/media/js/lib/jquery-1.7.1.min.js
@@ -1,4 +1,2576 @@
 /*! jQuery v1.7.1 jquery.com | jquery.org/license */
-(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function cb(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function ca(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bE.test(a)?d(a,e):ca(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)ca(a+"["+e+"]",b[e],c,d);else d(a,b)}function b_(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function b$(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bT,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=b$(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=b$(a,c,d,e,"*",g));return l}function bZ(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bP),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bC(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bx:by,g=0,h=e.length;if(d>0){if(c!=="border")for(;g<h;g++)c||(d-=parseFloat(f.css(a,"padding"+e[g]))||0),c==="margin"?d+=parseFloat(f.css(a,c+e[g]))||0:d-=parseFloat(f.css(a,"border"+e[g]+"Width"))||0;return d+"px"}d=bz(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0;if(c)for(;g<h;g++)d+=parseFloat(f.css(a,"padding"+e[g]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+e[g]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+e[g]))||0);return d+"px"}function bp(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c+(i[c][d].namespace?".":"")+i[c][d].namespace,i[c][d],i[c][d].data)}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?m(g):h==="function"&&(!a.unique||!o.has(g))&&c.push(g)},n=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,l=j||0,j=0,k=c.length;for(;c&&l<k;l++)if(c[l].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}i=!1,c&&(a.once?e===!0?o.disable():c=[]:d&&d.length&&(e=d.shift(),o.fireWith(e[0],e[1])))},o={add:function(){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){i&&f<=k&&(k--,f<=l&&l--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&o.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(i?a.once||d.push([b,c]):(!a.once||!e)&&n(b,c));return this},fire:function(){o.fireWith(this,arguments);return this},fired:function(){return!!e}};return o};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p,q=c.createElement("div"),r=c.documentElement;q.setAttribute("className","t"),q.innerHTML="   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="<div style='width:4px;'></div>",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i++)g=e[i].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),l(this[0],g,h[g]));f._data(this[0],"parsedAttrs",!0)}}return h}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split("."),d[1]=d[1]?"."+d[1]:"";if(c===b){h=this.triggerHandler("getData"+d[1]+"!",[d[0]]),h===b&&this.length&&(h=f.data(this[0],a),h=l(this[0],a,h));return h===b&&d[1]?this.data(d[0]):h}return this.each(function(){var b=f(this),e=[d[0],c];b.triggerHandler("setData"+d[1]+"!",e),f.data(this,a,c),b.triggerHandler("changeData"+d[1]+"!",e)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise()}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h<g;h++)e=d[h],e&&(c=f.propFix[e]||e,f.attr(a,e,""),a.removeAttribute(v?e:c),u.test(e)&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};
-f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=[],j,k,l,m,n,o,p,q,r,s,t;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click")){m=f(this),m.context=this.ownerDocument||this;for(l=c.target;l!=this;l=l.parentNode||this){o={},q=[],m[0]=l;for(j=0;j<e;j++)r=d[j],s=r.selector,o[s]===b&&(o[s]=r.quick?H(l,r.quick):m.is(s)),o[s]&&q.push(r);q.length&&i.push({elem:l,matches:q})}}d.length>e&&i.push({elem:this,matches:d.slice(e)});for(j=0;j<i.length&&!c.isPropagationStopped();j++){p=i[j],c.currentTarget=p.elem;for(k=0;k<p.matches.length&&!c.isImmediatePropagationStopped();k++){r=p.matches[k];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=((f.event.special[r.origType]||{}).handle||r.handler).apply(p.elem,g),n!==b&&(c.result=n,n===!1&&(c.preventDefault(),c.stopPropagation()))}}return c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0)}),d._submit_attached=!0)})},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on.call(this,a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.type+"."+e.namespace:e.type,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.POS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function()
-{for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bp)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1></$2>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bn(k[i]);else bn(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||be.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bq=/alpha\([^)]*\)/i,br=/opacity=([^)]*)/,bs=/([A-Z]|^ms)/g,bt=/^-?\d+(?:px)?$/i,bu=/^-?\d/,bv=/^([\-+])=([\-+.\de]+)/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Left","Right"],by=["Top","Bottom"],bz,bA,bB;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bz(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bv.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bz)return bz(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bC(a,b,d);f.swap(a,bw,function(){e=bC(a,b,d)});return e}},set:function(a,b){if(!bt.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cv(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cu("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cu("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cv(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cn.test(h)?(o=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),o?(f._data(this,"toggle"+i,o==="show"?"hide":"show"),j[o]()):j[h]()):(k=co.exec(h),l=j.cur(),k?(m=parseFloat(k[2]),n=k[3]||(f.cssNumber[i]?"":"px"),n!=="px"&&(f.style(this,i,(m||1)+n),l=(m||1)/j.cur()*l,f.style(this,i,l+n)),k[1]&&(m=(k[1]==="-="?-1:1)*m+l),j.custom(l,m,n)):j.custom(l,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:cu("show",1),slideUp:cu("hide",1),slideToggle:cu("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cr||cs(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){e.options.hide&&f._data(e.elem,"fxshow"+e.prop)===b&&f._data(e.elem,"fxshow"+e.prop,e.start)},h()&&f.timers.push(h)&&!cp&&(cp=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cr||cs(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cp),cp=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(["width","height"],function(a,b){f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cy(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.support.fixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.support.fixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window);
\ No newline at end of file
+(function (a, b) {
+    function cy(a) {
+        return f.isWindow(a) ? a : a.nodeType === 9 ? a.defaultView || a.parentWindow : !1
+    }
+
+    function cv(a) {
+        if (!ck[a]) {
+            var b = c.body, d = f("<" + a + ">").appendTo(b), e = d.css("display");
+            d.remove();
+            if (e === "none" || e === "") {
+                cl || (cl = c.createElement("iframe"), cl.frameBorder = cl.width = cl.height = 0), b.appendChild(cl);
+                if (!cm || !cl.createElement)cm = (cl.contentWindow || cl.contentDocument).document, cm.write((c.compatMode === "CSS1Compat" ? "<!doctype html>" : "") + "<html><body>"), cm.close();
+                d = cm.createElement(a), cm.body.appendChild(d), e = f.css(d, "display"), b.removeChild(cl)
+            }
+            ck[a] = e
+        }
+        return ck[a]
+    }
+
+    function cu(a, b) {
+        var c = {};
+        f.each(cq.concat.apply([], cq.slice(0, b)), function () {
+            c[this] = a
+        });
+        return c
+    }
+
+    function ct() {
+        cr = b
+    }
+
+    function cs() {
+        setTimeout(ct, 0);
+        return cr = f.now()
+    }
+
+    function cj() {
+        try {
+            return new a.ActiveXObject("Microsoft.XMLHTTP")
+        } catch (b) {
+        }
+    }
+
+    function ci() {
+        try {
+            return new a.XMLHttpRequest
+        } catch (b) {
+        }
+    }
+
+    function cc(a, c) {
+        a.dataFilter && (c = a.dataFilter(c, a.dataType));
+        var d = a.dataTypes, e = {}, g, h, i = d.length, j, k = d[0], l, m, n, o, p;
+        for (g = 1; g < i; g++) {
+            if (g === 1)for (h in a.converters)typeof h == "string" && (e[h.toLowerCase()] = a.converters[h]);
+            l = k, k = d[g];
+            if (k === "*")k = l; else if (l !== "*" && l !== k) {
+                m = l + " " + k, n = e[m] || e["* " + k];
+                if (!n) {
+                    p = b;
+                    for (o in e) {
+                        j = o.split(" ");
+                        if (j[0] === l || j[0] === "*") {
+                            p = e[j[1] + " " + k];
+                            if (p) {
+                                o = e[o], o === !0 ? n = p : p === !0 && (n = o);
+                                break
+                            }
+                        }
+                    }
+                }
+                !n && !p && f.error("No conversion from " + m.replace(" ", " to ")), n !== !0 && (c = n ? n(c) : p(o(c)))
+            }
+        }
+        return c
+    }
+
+    function cb(a, c, d) {
+        var e = a.contents, f = a.dataTypes, g = a.responseFields, h, i, j, k;
+        for (i in g)i in d && (c[g[i]] = d[i]);
+        while (f[0] === "*")f.shift(), h === b && (h = a.mimeType || c.getResponseHeader("content-type"));
+        if (h)for (i in e)if (e[i] && e[i].test(h)) {
+            f.unshift(i);
+            break
+        }
+        if (f[0]in d)j = f[0]; else {
+            for (i in d) {
+                if (!f[0] || a.converters[i + " " + f[0]]) {
+                    j = i;
+                    break
+                }
+                k || (k = i)
+            }
+            j = j || k
+        }
+        if (j) {
+            j !== f[0] && f.unshift(j);
+            return d[j]
+        }
+    }
+
+    function ca(a, b, c, d) {
+        if (f.isArray(b))f.each(b, function (b, e) {
+            c || bE.test(a) ? d(a, e) : ca(a + "[" + (typeof e == "object" || f.isArray(e) ? b : "") + "]", e, c, d)
+        }); else if (!c && b != null && typeof b == "object")for (var e in b)ca(a + "[" + e + "]", b[e], c, d); else d(a, b)
+    }
+
+    function b_(a, c) {
+        var d, e, g = f.ajaxSettings.flatOptions || {};
+        for (d in c)c[d] !== b && ((g[d] ? a : e || (e = {}))[d] = c[d]);
+        e && f.extend(!0, a, e)
+    }
+
+    function b$(a, c, d, e, f, g) {
+        f = f || c.dataTypes[0], g = g || {}, g[f] = !0;
+        var h = a[f], i = 0, j = h ? h.length : 0, k = a === bT, l;
+        for (; i < j && (k || !l); i++)l = h[i](c, d, e), typeof l == "string" && (!k || g[l] ? l = b : (c.dataTypes.unshift(l), l = b$(a, c, d, e, l, g)));
+        (k || !l) && !g["*"] && (l = b$(a, c, d, e, "*", g));
+        return l
+    }
+
+    function bZ(a) {
+        return function (b, c) {
+            typeof b != "string" && (c = b, b = "*");
+            if (f.isFunction(c)) {
+                var d = b.toLowerCase().split(bP), e = 0, g = d.length, h, i, j;
+                for (; e < g; e++)h = d[e], j = /^\+/.test(h), j && (h = h.substr(1) || "*"), i = a[h] = a[h] || [], i[j ? "unshift" : "push"](c)
+            }
+        }
+    }
+
+    function bC(a, b, c) {
+        var d = b === "width" ? a.offsetWidth : a.offsetHeight, e = b === "width" ? bx : by, g = 0, h = e.length;
+        if (d > 0) {
+            if (c !== "border")for (; g < h; g++)c || (d -= parseFloat(f.css(a, "padding" + e[g])) || 0), c === "margin" ? d += parseFloat(f.css(a, c + e[g])) || 0 : d -= parseFloat(f.css(a, "border" + e[g] + "Width")) || 0;
+            return d + "px"
+        }
+        d = bz(a, b, b);
+        if (d < 0 || d == null)d = a.style[b] || 0;
+        d = parseFloat(d) || 0;
+        if (c)for (; g < h; g++)d += parseFloat(f.css(a, "padding" + e[g])) || 0, c !== "padding" && (d += parseFloat(f.css(a, "border" + e[g] + "Width")) || 0), c === "margin" && (d += parseFloat(f.css(a, c + e[g])) || 0);
+        return d + "px"
+    }
+
+    function bp(a, b) {
+        b.src ? f.ajax({url: b.src, async: !1, dataType: "script"}) : f.globalEval((b.text || b.textContent || b.innerHTML || "").replace(bf, "/*$0*/")), b.parentNode && b.parentNode.removeChild(b)
+    }
+
+    function bo(a) {
+        var b = c.createElement("div");
+        bh.appendChild(b), b.innerHTML = a.outerHTML;
+        return b.firstChild
+    }
+
+    function bn(a) {
+        var b = (a.nodeName || "").toLowerCase();
+        b === "input" ? bm(a) : b !== "script" && typeof a.getElementsByTagName != "undefined" && f.grep(a.getElementsByTagName("input"), bm)
+    }
+
+    function bm(a) {
+        if (a.type === "checkbox" || a.type === "radio")a.defaultChecked = a.checked
+    }
+
+    function bl(a) {
+        return typeof a.getElementsByTagName != "undefined" ? a.getElementsByTagName("*") : typeof a.querySelectorAll != "undefined" ? a.querySelectorAll("*") : []
+    }
+
+    function bk(a, b) {
+        var c;
+        if (b.nodeType === 1) {
+            b.clearAttributes && b.clearAttributes(), b.mergeAttributes && b.mergeAttributes(a), c = b.nodeName.toLowerCase();
+            if (c === "object")b.outerHTML = a.outerHTML; else if (c !== "input" || a.type !== "checkbox" && a.type !== "radio") {
+                if (c === "option")b.selected = a.defaultSelected; else if (c === "input" || c === "textarea")b.defaultValue = a.defaultValue
+            } else a.checked && (b.defaultChecked = b.checked = a.checked), b.value !== a.value && (b.value = a.value);
+            b.removeAttribute(f.expando)
+        }
+    }
+
+    function bj(a, b) {
+        if (b.nodeType === 1 && !!f.hasData(a)) {
+            var c, d, e, g = f._data(a), h = f._data(b, g), i = g.events;
+            if (i) {
+                delete h.handle, h.events = {};
+                for (c in i)for (d = 0, e = i[c].length; d < e; d++)f.event.add(b, c + (i[c][d].namespace ? "." : "") + i[c][d].namespace, i[c][d], i[c][d].data)
+            }
+            h.data && (h.data = f.extend({}, h.data))
+        }
+    }
+
+    function bi(a, b) {
+        return f.nodeName(a, "table") ? a.getElementsByTagName("tbody")[0] || a.appendChild(a.ownerDocument.createElement("tbody")) : a
+    }
+
+    function U(a) {
+        var b = V.split("|"), c = a.createDocumentFragment();
+        if (c.createElement)while (b.length)c.createElement(b.pop());
+        return c
+    }
+
+    function T(a, b, c) {
+        b = b || 0;
+        if (f.isFunction(b))return f.grep(a, function (a, d) {
+            var e = !!b.call(a, d, a);
+            return e === c
+        });
+        if (b.nodeType)return f.grep(a, function (a, d) {
+            return a === b === c
+        });
+        if (typeof b == "string") {
+            var d = f.grep(a, function (a) {
+                return a.nodeType === 1
+            });
+            if (O.test(b))return f.filter(b, d, !c);
+            b = f.filter(b, d)
+        }
+        return f.grep(a, function (a, d) {
+            return f.inArray(a, b) >= 0 === c
+        })
+    }
+
+    function S(a) {
+        return!a || !a.parentNode || a.parentNode.nodeType === 11
+    }
+
+    function K() {
+        return!0
+    }
+
+    function J() {
+        return!1
+    }
+
+    function n(a, b, c) {
+        var d = b + "defer", e = b + "queue", g = b + "mark", h = f._data(a, d);
+        h && (c === "queue" || !f._data(a, e)) && (c === "mark" || !f._data(a, g)) && setTimeout(function () {
+            !f._data(a, e) && !f._data(a, g) && (f.removeData(a, d, !0), h.fire())
+        }, 0)
+    }
+
+    function m(a) {
+        for (var b in a) {
+            if (b === "data" && f.isEmptyObject(a[b]))continue;
+            if (b !== "toJSON")return!1
+        }
+        return!0
+    }
+
+    function l(a, c, d) {
+        if (d === b && a.nodeType === 1) {
+            var e = "data-" + c.replace(k, "-$1").toLowerCase();
+            d = a.getAttribute(e);
+            if (typeof d == "string") {
+                try {
+                    d = d === "true" ? !0 : d === "false" ? !1 : d === "null" ? null : f.isNumeric(d) ? parseFloat(d) : j.test(d) ? f.parseJSON(d) : d
+                } catch (g) {
+                }
+                f.data(a, c, d)
+            } else d = b
+        }
+        return d
+    }
+
+    function h(a) {
+        var b = g[a] = {}, c, d;
+        a = a.split(/\s+/);
+        for (c = 0, d = a.length; c < d; c++)b[a[c]] = !0;
+        return b
+    }
+
+    var c = a.document, d = a.navigator, e = a.location, f = function () {
+        function J() {
+            if (!e.isReady) {
+                try {
+                    c.documentElement.doScroll("left")
+                } catch (a) {
+                    setTimeout(J, 1);
+                    return
+                }
+                e.ready()
+            }
+        }
+
+        var e = function (a, b) {
+            return new e.fn.init(a, b, h)
+        }, f = a.jQuery, g = a.$, h, i = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, j = /\S/, k = /^\s+/, l = /\s+$/, m = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, n = /^[\],:{}\s]*$/, o = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, p = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, q = /(?:^|:|,)(?:\s*\[)+/g, r = /(webkit)[ \/]([\w.]+)/, s = /(opera)(?:.*version)?[ \/]([\w.]+)/, t = /(msie) ([\w.]+)/, u = /(mozilla)(?:.*? rv:([\w.]+))?/, v = /-([a-z]|[0-9])/ig, w = /^-ms-/, x = function (a, b) {
+            return(b + "").toUpperCase()
+        }, y = d.userAgent, z, A, B, C = Object.prototype.toString, D = Object.prototype.hasOwnProperty, E = Array.prototype.push, F = Array.prototype.slice, G = String.prototype.trim, H = Array.prototype.indexOf, I = {};
+        e.fn = e.prototype = {constructor: e, init: function (a, d, f) {
+            var g, h, j, k;
+            if (!a)return this;
+            if (a.nodeType) {
+                this.context = this[0] = a, this.length = 1;
+                return this
+            }
+            if (a === "body" && !d && c.body) {
+                this.context = c, this[0] = c.body, this.selector = a, this.length = 1;
+                return this
+            }
+            if (typeof a == "string") {
+                a.charAt(0) !== "<" || a.charAt(a.length - 1) !== ">" || a.length < 3 ? g = i.exec(a) : g = [null, a, null];
+                if (g && (g[1] || !d)) {
+                    if (g[1]) {
+                        d = d instanceof e ? d[0] : d, k = d ? d.ownerDocument || d : c, j = m.exec(a), j ? e.isPlainObject(d) ? (a = [c.createElement(j[1])], e.fn.attr.call(a, d, !0)) : a = [k.createElement(j[1])] : (j = e.buildFragment([g[1]], [k]), a = (j.cacheable ? e.clone(j.fragment) : j.fragment).childNodes);
+                        return e.merge(this, a)
+                    }
+                    h = c.getElementById(g[2]);
+                    if (h && h.parentNode) {
+                        if (h.id !== g[2])return f.find(a);
+                        this.length = 1, this[0] = h
+                    }
+                    this.context = c, this.selector = a;
+                    return this
+                }
+                return!d || d.jquery ? (d || f).find(a) : this.constructor(d).find(a)
+            }
+            if (e.isFunction(a))return f.ready(a);
+            a.selector !== b && (this.selector = a.selector, this.context = a.context);
+            return e.makeArray(a, this)
+        }, selector: "", jquery: "1.7.1", length: 0, size: function () {
+            return this.length
+        }, toArray: function () {
+            return F.call(this, 0)
+        }, get: function (a) {
+            return a == null ? this.toArray() : a < 0 ? this[this.length + a] : this[a]
+        }, pushStack: function (a, b, c) {
+            var d = this.constructor();
+            e.isArray(a) ? E.apply(d, a) : e.merge(d, a), d.prevObject = this, d.context = this.context, b === "find" ? d.selector = this.selector + (this.selector ? " " : "") + c : b && (d.selector = this.selector + "." + b + "(" + c + ")");
+            return d
+        }, each: function (a, b) {
+            return e.each(this, a, b)
+        }, ready: function (a) {
+            e.bindReady(), A.add(a);
+            return this
+        }, eq: function (a) {
+            a = +a;
+            return a === -1 ? this.slice(a) : this.slice(a, a + 1)
+        }, first: function () {
+            return this.eq(0)
+        }, last: function () {
+            return this.eq(-1)
+        }, slice: function () {
+            return this.pushStack(F.apply(this, arguments), "slice", F.call(arguments).join(","))
+        }, map: function (a) {
+            return this.pushStack(e.map(this, function (b, c) {
+                return a.call(b, c, b)
+            }))
+        }, end: function () {
+            return this.prevObject || this.constructor(null)
+        }, push: E, sort: [].sort, splice: [].splice}, e.fn.init.prototype = e.fn, e.extend = e.fn.extend = function () {
+            var a, c, d, f, g, h, i = arguments[0] || {}, j = 1, k = arguments.length, l = !1;
+            typeof i == "boolean" && (l = i, i = arguments[1] || {}, j = 2), typeof i != "object" && !e.isFunction(i) && (i = {}), k === j && (i = this, --j);
+            for (; j < k; j++)if ((a = arguments[j]) != null)for (c in a) {
+                d = i[c], f = a[c];
+                if (i === f)continue;
+                l && f && (e.isPlainObject(f) || (g = e.isArray(f))) ? (g ? (g = !1, h = d && e.isArray(d) ? d : []) : h = d && e.isPlainObject(d) ? d : {}, i[c] = e.extend(l, h, f)) : f !== b && (i[c] = f)
+            }
+            return i
+        }, e.extend({noConflict: function (b) {
+            a.$ === e && (a.$ = g), b && a.jQuery === e && (a.jQuery = f);
+            return e
+        }, isReady: !1, readyWait: 1, holdReady: function (a) {
+            a ? e.readyWait++ : e.ready(!0)
+        }, ready: function (a) {
+            if (a === !0 && !--e.readyWait || a !== !0 && !e.isReady) {
+                if (!c.body)return setTimeout(e.ready, 1);
+                e.isReady = !0;
+                if (a !== !0 && --e.readyWait > 0)return;
+                A.fireWith(c, [e]), e.fn.trigger && e(c).trigger("ready").off("ready")
+            }
+        }, bindReady: function () {
+            if (!A) {
+                A = e.Callbacks("once memory");
+                if (c.readyState === "complete")return setTimeout(e.ready, 1);
+                if (c.addEventListener)c.addEventListener("DOMContentLoaded", B, !1), a.addEventListener("load", e.ready, !1); else if (c.attachEvent) {
+                    c.attachEvent("onreadystatechange", B), a.attachEvent("onload", e.ready);
+                    var b = !1;
+                    try {
+                        b = a.frameElement == null
+                    } catch (d) {
+                    }
+                    c.documentElement.doScroll && b && J()
+                }
+            }
+        }, isFunction: function (a) {
+            return e.type(a) === "function"
+        }, isArray: Array.isArray || function (a) {
+            return e.type(a) === "array"
+        }, isWindow: function (a) {
+            return a && typeof a == "object" && "setInterval"in a
+        }, isNumeric: function (a) {
+            return!isNaN(parseFloat(a)) && isFinite(a)
+        }, type: function (a) {
+            return a == null ? String(a) : I[C.call(a)] || "object"
+        }, isPlainObject: function (a) {
+            if (!a || e.type(a) !== "object" || a.nodeType || e.isWindow(a))return!1;
+            try {
+                if (a.constructor && !D.call(a, "constructor") && !D.call(a.constructor.prototype, "isPrototypeOf"))return!1
+            } catch (c) {
+                return!1
+            }
+            var d;
+            for (d in a);
+            return d === b || D.call(a, d)
+        }, isEmptyObject: function (a) {
+            for (var b in a)return!1;
+            return!0
+        }, error: function (a) {
+            throw new Error(a)
+        }, parseJSON: function (b) {
+            if (typeof b != "string" || !b)return null;
+            b = e.trim(b);
+            if (a.JSON && a.JSON.parse)return a.JSON.parse(b);
+            if (n.test(b.replace(o, "@").replace(p, "]").replace(q, "")))return(new Function("return " + b))();
+            e.error("Invalid JSON: " + b)
+        }, parseXML: function (c) {
+            var d, f;
+            try {
+                a.DOMParser ? (f = new DOMParser, d = f.parseFromString(c, "text/xml")) : (d = new ActiveXObject("Microsoft.XMLDOM"), d.async = "false", d.loadXML(c))
+            } catch (g) {
+                d = b
+            }
+            (!d || !d.documentElement || d.getElementsByTagName("parsererror").length) && e.error("Invalid XML: " + c);
+            return d
+        }, noop: function () {
+        }, globalEval: function (b) {
+            b && j.test(b) && (a.execScript || function (b) {
+                a.eval.call(a, b)
+            })(b)
+        }, camelCase: function (a) {
+            return a.replace(w, "ms-").replace(v, x)
+        }, nodeName: function (a, b) {
+            return a.nodeName && a.nodeName.toUpperCase() === b.toUpperCase()
+        }, each: function (a, c, d) {
+            var f, g = 0, h = a.length, i = h === b || e.isFunction(a);
+            if (d) {
+                if (i) {
+                    for (f in a)if (c.apply(a[f], d) === !1)break
+                } else for (; g < h;)if (c.apply(a[g++], d) === !1)break
+            } else if (i) {
+                for (f in a)if (c.call(a[f], f, a[f]) === !1)break
+            } else for (; g < h;)if (c.call(a[g], g, a[g++]) === !1)break;
+            return a
+        }, trim: G ? function (a) {
+            return a == null ? "" : G.call(a)
+        } : function (a) {
+            return a == null ? "" : (a + "").replace(k, "").replace(l, "")
+        }, makeArray: function (a, b) {
+            var c = b || [];
+            if (a != null) {
+                var d = e.type(a);
+                a.length == null || d === "string" || d === "function" || d === "regexp" || e.isWindow(a) ? E.call(c, a) : e.merge(c, a)
+            }
+            return c
+        }, inArray: function (a, b, c) {
+            var d;
+            if (b) {
+                if (H)return H.call(b, a, c);
+                d = b.length, c = c ? c < 0 ? Math.max(0, d + c) : c : 0;
+                for (; c < d; c++)if (c in b && b[c] === a)return c
+            }
+            return-1
+        }, merge: function (a, c) {
+            var d = a.length, e = 0;
+            if (typeof c.length == "number")for (var f = c.length; e < f; e++)a[d++] = c[e]; else while (c[e] !== b)a[d++] = c[e++];
+            a.length = d;
+            return a
+        }, grep: function (a, b, c) {
+            var d = [], e;
+            c = !!c;
+            for (var f = 0, g = a.length; f < g; f++)e = !!b(a[f], f), c !== e && d.push(a[f]);
+            return d
+        }, map: function (a, c, d) {
+            var f, g, h = [], i = 0, j = a.length, k = a instanceof e || j !== b && typeof j == "number" && (j > 0 && a[0] && a[j - 1] || j === 0 || e.isArray(a));
+            if (k)for (; i < j; i++)f = c(a[i], i, d), f != null && (h[h.length] = f); else for (g in a)f = c(a[g], g, d), f != null && (h[h.length] = f);
+            return h.concat.apply([], h)
+        }, guid: 1, proxy: function (a, c) {
+            if (typeof c == "string") {
+                var d = a[c];
+                c = a, a = d
+            }
+            if (!e.isFunction(a))return b;
+            var f = F.call(arguments, 2), g = function () {
+                return a.apply(c, f.concat(F.call(arguments)))
+            };
+            g.guid = a.guid = a.guid || g.guid || e.guid++;
+            return g
+        }, access: function (a, c, d, f, g, h) {
+            var i = a.length;
+            if (typeof c == "object") {
+                for (var j in c)e.access(a, j, c[j], f, g, d);
+                return a
+            }
+            if (d !== b) {
+                f = !h && f && e.isFunction(d);
+                for (var k = 0; k < i; k++)g(a[k], c, f ? d.call(a[k], k, g(a[k], c)) : d, h);
+                return a
+            }
+            return i ? g(a[0], c) : b
+        }, now: function () {
+            return(new Date).getTime()
+        }, uaMatch: function (a) {
+            a = a.toLowerCase();
+            var b = r.exec(a) || s.exec(a) || t.exec(a) || a.indexOf("compatible") < 0 && u.exec(a) || [];
+            return{browser: b[1] || "", version: b[2] || "0"}
+        }, sub: function () {
+            function a(b, c) {
+                return new a.fn.init(b, c)
+            }
+
+            e.extend(!0, a, this), a.superclass = this, a.fn = a.prototype = this(), a.fn.constructor = a, a.sub = this.sub, a.fn.init = function (d, f) {
+                f && f instanceof e && !(f instanceof a) && (f = a(f));
+                return e.fn.init.call(this, d, f, b)
+            }, a.fn.init.prototype = a.fn;
+            var b = a(c);
+            return a
+        }, browser: {}}), e.each("Boolean Number String Function Array Date RegExp Object".split(" "), function (a, b) {
+            I["[object " + b + "]"] = b.toLowerCase()
+        }), z = e.uaMatch(y), z.browser && (e.browser[z.browser] = !0, e.browser.version = z.version), e.browser.webkit && (e.browser.safari = !0), j.test(" ") && (k = /^[\s\xA0]+/, l = /[\s\xA0]+$/), h = e(c), c.addEventListener ? B = function () {
+            c.removeEventListener("DOMContentLoaded", B, !1), e.ready()
+        } : c.attachEvent && (B = function () {
+            c.readyState === "complete" && (c.detachEvent("onreadystatechange", B), e.ready())
+        });
+        return e
+    }(), g = {};
+    f.Callbacks = function (a) {
+        a = a ? g[a] || h(a) : {};
+        var c = [], d = [], e, i, j, k, l, m = function (b) {
+            var d, e, g, h, i;
+            for (d = 0, e = b.length; d < e; d++)g = b[d], h = f.type(g), h === "array" ? m(g) : h === "function" && (!a.unique || !o.has(g)) && c.push(g)
+        }, n = function (b, f) {
+            f = f || [], e = !a.memory || [b, f], i = !0, l = j || 0, j = 0, k = c.length;
+            for (; c && l < k; l++)if (c[l].apply(b, f) === !1 && a.stopOnFalse) {
+                e = !0;
+                break
+            }
+            i = !1, c && (a.once ? e === !0 ? o.disable() : c = [] : d && d.length && (e = d.shift(), o.fireWith(e[0], e[1])))
+        }, o = {add: function () {
+            if (c) {
+                var a = c.length;
+                m(arguments), i ? k = c.length : e && e !== !0 && (j = a, n(e[0], e[1]))
+            }
+            return this
+        }, remove: function () {
+            if (c) {
+                var b = arguments, d = 0, e = b.length;
+                for (; d < e; d++)for (var f = 0; f < c.length; f++)if (b[d] === c[f]) {
+                    i && f <= k && (k--, f <= l && l--), c.splice(f--, 1);
+                    if (a.unique)break
+                }
+            }
+            return this
+        }, has: function (a) {
+            if (c) {
+                var b = 0, d = c.length;
+                for (; b < d; b++)if (a === c[b])return!0
+            }
+            return!1
+        }, empty: function () {
+            c = [];
+            return this
+        }, disable: function () {
+            c = d = e = b;
+            return this
+        }, disabled: function () {
+            return!c
+        }, lock: function () {
+            d = b, (!e || e === !0) && o.disable();
+            return this
+        }, locked: function () {
+            return!d
+        }, fireWith: function (b, c) {
+            d && (i ? a.once || d.push([b, c]) : (!a.once || !e) && n(b, c));
+            return this
+        }, fire: function () {
+            o.fireWith(this, arguments);
+            return this
+        }, fired: function () {
+            return!!e
+        }};
+        return o
+    };
+    var i = [].slice;
+    f.extend({Deferred: function (a) {
+        var b = f.Callbacks("once memory"), c = f.Callbacks("once memory"), d = f.Callbacks("memory"), e = "pending", g = {resolve: b, reject: c, notify: d}, h = {done: b.add, fail: c.add, progress: d.add, state: function () {
+            return e
+        }, isResolved: b.fired, isRejected: c.fired, then: function (a, b, c) {
+            i.done(a).fail(b).progress(c);
+            return this
+        }, always: function () {
+            i.done.apply(i, arguments).fail.apply(i, arguments);
+            return this
+        }, pipe: function (a, b, c) {
+            return f.Deferred(function (d) {
+                f.each({done: [a, "resolve"], fail: [b, "reject"], progress: [c, "notify"]}, function (a, b) {
+                    var c = b[0], e = b[1], g;
+                    f.isFunction(c) ? i[a](function () {
+                        g = c.apply(this, arguments), g && f.isFunction(g.promise) ? g.promise().then(d.resolve, d.reject, d.notify) : d[e + "With"](this === i ? d : this, [g])
+                    }) : i[a](d[e])
+                })
+            }).promise()
+        }, promise: function (a) {
+            if (a == null)a = h; else for (var b in h)a[b] = h[b];
+            return a
+        }}, i = h.promise({}), j;
+        for (j in g)i[j] = g[j].fire, i[j + "With"] = g[j].fireWith;
+        i.done(function () {
+            e = "resolved"
+        }, c.disable, d.lock).fail(function () {
+            e = "rejected"
+        }, b.disable, d.lock), a && a.call(i, i);
+        return i
+    }, when: function (a) {
+        function m(a) {
+            return function (b) {
+                e[a] = arguments.length > 1 ? i.call(arguments, 0) : b, j.notifyWith(k, e)
+            }
+        }
+
+        function l(a) {
+            return function (c) {
+                b[a] = arguments.length > 1 ? i.call(arguments, 0) : c, --g || j.resolveWith(j, b)
+            }
+        }
+
+        var b = i.call(arguments, 0), c = 0, d = b.length, e = Array(d), g = d, h = d, j = d <= 1 && a && f.isFunction(a.promise) ? a : f.Deferred(), k = j.promise();
+        if (d > 1) {
+            for (; c < d; c++)b[c] && b[c].promise && f.isFunction(b[c].promise) ? b[c].promise().then(l(c), j.reject, m(c)) : --g;
+            g || j.resolveWith(j, b)
+        } else j !== a && j.resolveWith(j, d ? [a] : []);
+        return k
+    }}), f.support = function () {
+        var b, d, e, g, h, i, j, k, l, m, n, o, p, q = c.createElement("div"), r = c.documentElement;
+        q.setAttribute("className", "t"), q.innerHTML = "   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>", d = q.getElementsByTagName("*"), e = q.getElementsByTagName("a")[0];
+        if (!d || !d.length || !e)return{};
+        g = c.createElement("select"), h = g.appendChild(c.createElement("option")), i = q.getElementsByTagName("input")[0], b = {leadingWhitespace: q.firstChild.nodeType === 3, tbody: !q.getElementsByTagName("tbody").length, htmlSerialize: !!q.getElementsByTagName("link").length, style: /top/.test(e.getAttribute("style")), hrefNormalized: e.getAttribute("href") === "/a", opacity: /^0.55/.test(e.style.opacity), cssFloat: !!e.style.cssFloat, checkOn: i.value === "on", optSelected: h.selected, getSetAttribute: q.className !== "t", enctype: !!c.createElement("form").enctype, html5Clone: c.createElement("nav").cloneNode(!0).outerHTML !== "<:nav></:nav>", submitBubbles: !0, changeBubbles: !0, focusinBubbles: !1, deleteExpando: !0, noCloneEvent: !0, inlineBlockNeedsLayout: !1, shrinkWrapBlocks: !1, reliableMarginRight: !0}, i.checked = !0, b.noCloneChecked = i.cloneNode(!0).checked, g.disabled = !0, b.optDisabled = !h.disabled;
+        try {
+            delete q.test
+        } catch (s) {
+            b.deleteExpando = !1
+        }
+        !q.addEventListener && q.attachEvent && q.fireEvent && (q.attachEvent("onclick", function () {
+            b.noCloneEvent = !1
+        }), q.cloneNode(!0).fireEvent("onclick")), i = c.createElement("input"), i.value = "t", i.setAttribute("type", "radio"), b.radioValue = i.value === "t", i.setAttribute("checked", "checked"), q.appendChild(i), k = c.createDocumentFragment(), k.appendChild(q.lastChild), b.checkClone = k.cloneNode(!0).cloneNode(!0).lastChild.checked, b.appendChecked = i.checked, k.removeChild(i), k.appendChild(q), q.innerHTML = "", a.getComputedStyle && (j = c.createElement("div"), j.style.width = "0", j.style.marginRight = "0", q.style.width = "2px", q.appendChild(j), b.reliableMarginRight = (parseInt((a.getComputedStyle(j, null) || {marginRight: 0}).marginRight, 10) || 0) === 0);
+        if (q.attachEvent)for (o in{submit: 1, change: 1, focusin: 1})n = "on" + o, p = n in q, p || (q.setAttribute(n, "return;"), p = typeof q[n] == "function"), b[o + "Bubbles"] = p;
+        k.removeChild(q), k = g = h = j = q = i = null, f(function () {
+            var a, d, e, g, h, i, j, k, m, n, o, r = c.getElementsByTagName("body")[0];
+            !r || (j = 1, k = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;", m = "visibility:hidden;border:0;", n = "style='" + k + "border:5px solid #000;padding:0;'", o = "<div " + n + "><div></div></div>" + "<table " + n + " cellpadding='0' cellspacing='0'>" + "<tr><td></td></tr></table>", a = c.createElement("div"), a.style.cssText = m + "width:0;height:0;position:static;top:0;margin-top:" + j + "px", r.insertBefore(a, r.firstChild), q = c.createElement("div"), a.appendChild(q), q.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>", l = q.getElementsByTagName("td"), p = l[0].offsetHeight === 0, l[0].style.display = "", l[1].style.display = "none", b.reliableHiddenOffsets = p && l[0].offsetHeight === 0, q.innerHTML = "", q.style.width = q.style.paddingLeft = "1px", f.boxModel = b.boxModel = q.offsetWidth === 2, typeof q.style.zoom != "undefined" && (q.style.display = "inline", q.style.zoom = 1, b.inlineBlockNeedsLayout = q.offsetWidth === 2, q.style.display = "", q.innerHTML = "<div style='width:4px;'></div>", b.shrinkWrapBlocks = q.offsetWidth !== 2), q.style.cssText = k + m, q.innerHTML = o, d = q.firstChild, e = d.firstChild, h = d.nextSibling.firstChild.firstChild, i = {doesNotAddBorder: e.offsetTop !== 5, doesAddBorderForTableAndCells: h.offsetTop === 5}, e.style.position = "fixed", e.style.top = "20px", i.fixedPosition = e.offsetTop === 20 || e.offsetTop === 15, e.style.position = e.style.top = "", d.style.overflow = "hidden", d.style.position = "relative", i.subtractsBorderForOverflowNotVisible = e.offsetTop === -5, i.doesNotIncludeMarginInBodyOffset = r.offsetTop !== j, r.removeChild(a), q = a = null, f.extend(b, i))
+        });
+        return b
+    }();
+    var j = /^(?:\{.*\}|\[.*\])$/, k = /([A-Z])/g;
+    f.extend({cache: {}, uuid: 0, expando: "jQuery" + (f.fn.jquery + Math.random()).replace(/\D/g, ""), noData: {embed: !0, object: "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", applet: !0}, hasData: function (a) {
+        a = a.nodeType ? f.cache[a[f.expando]] : a[f.expando];
+        return!!a && !m(a)
+    }, data: function (a, c, d, e) {
+        if (!!f.acceptData(a)) {
+            var g, h, i, j = f.expando, k = typeof c == "string", l = a.nodeType, m = l ? f.cache : a, n = l ? a[j] : a[j] && j, o = c === "events";
+            if ((!n || !m[n] || !o && !e && !m[n].data) && k && d === b)return;
+            n || (l ? a[j] = n = ++f.uuid : n = j), m[n] || (m[n] = {}, l || (m[n].toJSON = f.noop));
+            if (typeof c == "object" || typeof c == "function")e ? m[n] = f.extend(m[n], c) : m[n].data = f.extend(m[n].data, c);
+            g = h = m[n], e || (h.data || (h.data = {}), h = h.data), d !== b && (h[f.camelCase(c)] = d);
+            if (o && !h[c])return g.events;
+            k ? (i = h[c], i == null && (i = h[f.camelCase(c)])) : i = h;
+            return i
+        }
+    }, removeData: function (a, b, c) {
+        if (!!f.acceptData(a)) {
+            var d, e, g, h = f.expando, i = a.nodeType, j = i ? f.cache : a, k = i ? a[h] : h;
+            if (!j[k])return;
+            if (b) {
+                d = c ? j[k] : j[k].data;
+                if (d) {
+                    f.isArray(b) || (b in d ? b = [b] : (b = f.camelCase(b), b in d ? b = [b] : b = b.split(" ")));
+                    for (e = 0, g = b.length; e < g; e++)delete d[b[e]];
+                    if (!(c ? m : f.isEmptyObject)(d))return
+                }
+            }
+            if (!c) {
+                delete j[k].data;
+                if (!m(j[k]))return
+            }
+            f.support.deleteExpando || !j.setInterval ? delete j[k] : j[k] = null, i && (f.support.deleteExpando ? delete a[h] : a.removeAttribute ? a.removeAttribute(h) : a[h] = null)
+        }
+    }, _data: function (a, b, c) {
+        return f.data(a, b, c, !0)
+    }, acceptData: function (a) {
+        if (a.nodeName) {
+            var b = f.noData[a.nodeName.toLowerCase()];
+            if (b)return b !== !0 && a.getAttribute("classid") === b
+        }
+        return!0
+    }}), f.fn.extend({data: function (a, c) {
+        var d, e, g, h = null;
+        if (typeof a == "undefined") {
+            if (this.length) {
+                h = f.data(this[0]);
+                if (this[0].nodeType === 1 && !f._data(this[0], "parsedAttrs")) {
+                    e = this[0].attributes;
+                    for (var i = 0, j = e.length; i < j; i++)g = e[i].name, g.indexOf("data-") === 0 && (g = f.camelCase(g.substring(5)), l(this[0], g, h[g]));
+                    f._data(this[0], "parsedAttrs", !0)
+                }
+            }
+            return h
+        }
+        if (typeof a == "object")return this.each(function () {
+            f.data(this, a)
+        });
+        d = a.split("."), d[1] = d[1] ? "." + d[1] : "";
+        if (c === b) {
+            h = this.triggerHandler("getData" + d[1] + "!", [d[0]]), h === b && this.length && (h = f.data(this[0], a), h = l(this[0], a, h));
+            return h === b && d[1] ? this.data(d[0]) : h
+        }
+        return this.each(function () {
+            var b = f(this), e = [d[0], c];
+            b.triggerHandler("setData" + d[1] + "!", e), f.data(this, a, c), b.triggerHandler("changeData" + d[1] + "!", e)
+        })
+    }, removeData: function (a) {
+        return this.each(function () {
+            f.removeData(this, a)
+        })
+    }}), f.extend({_mark: function (a, b) {
+        a && (b = (b || "fx") + "mark", f._data(a, b, (f._data(a, b) || 0) + 1))
+    }, _unmark: function (a, b, c) {
+        a !== !0 && (c = b, b = a, a = !1);
+        if (b) {
+            c = c || "fx";
+            var d = c + "mark", e = a ? 0 : (f._data(b, d) || 1) - 1;
+            e ? f._data(b, d, e) : (f.removeData(b, d, !0), n(b, c, "mark"))
+        }
+    }, queue: function (a, b, c) {
+        var d;
+        if (a) {
+            b = (b || "fx") + "queue", d = f._data(a, b), c && (!d || f.isArray(c) ? d = f._data(a, b, f.makeArray(c)) : d.push(c));
+            return d || []
+        }
+    }, dequeue: function (a, b) {
+        b = b || "fx";
+        var c = f.queue(a, b), d = c.shift(), e = {};
+        d === "inprogress" && (d = c.shift()), d && (b === "fx" && c.unshift("inprogress"), f._data(a, b + ".run", e), d.call(a, function () {
+            f.dequeue(a, b)
+        }, e)), c.length || (f.removeData(a, b + "queue " + b + ".run", !0), n(a, b, "queue"))
+    }}), f.fn.extend({queue: function (a, c) {
+        typeof a != "string" && (c = a, a = "fx");
+        if (c === b)return f.queue(this[0], a);
+        return this.each(function () {
+            var b = f.queue(this, a, c);
+            a === "fx" && b[0] !== "inprogress" && f.dequeue(this, a)
+        })
+    }, dequeue: function (a) {
+        return this.each(function () {
+            f.dequeue(this, a)
+        })
+    }, delay: function (a, b) {
+        a = f.fx ? f.fx.speeds[a] || a : a, b = b || "fx";
+        return this.queue(b, function (b, c) {
+            var d = setTimeout(b, a);
+            c.stop = function () {
+                clearTimeout(d)
+            }
+        })
+    }, clearQueue: function (a) {
+        return this.queue(a || "fx", [])
+    }, promise: function (a, c) {
+        function m() {
+            --h || d.resolveWith(e, [e])
+        }
+
+        typeof a != "string" && (c = a, a = b), a = a || "fx";
+        var d = f.Deferred(), e = this, g = e.length, h = 1, i = a + "defer", j = a + "queue", k = a + "mark", l;
+        while (g--)if (l = f.data(e[g], i, b, !0) || (f.data(e[g], j, b, !0) || f.data(e[g], k, b, !0)) && f.data(e[g], i, f.Callbacks("once memory"), !0))h++, l.add(m);
+        m();
+        return d.promise()
+    }});
+    var o = /[\n\t\r]/g, p = /\s+/, q = /\r/g, r = /^(?:button|input)$/i, s = /^(?:button|input|object|select|textarea)$/i, t = /^a(?:rea)?$/i, u = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, v = f.support.getSetAttribute, w, x, y;
+    f.fn.extend({attr: function (a, b) {
+        return f.access(this, a, b, !0, f.attr)
+    }, removeAttr: function (a) {
+        return this.each(function () {
+            f.removeAttr(this, a)
+        })
+    }, prop: function (a, b) {
+        return f.access(this, a, b, !0, f.prop)
+    }, removeProp: function (a) {
+        a = f.propFix[a] || a;
+        return this.each(function () {
+            try {
+                this[a] = b, delete this[a]
+            } catch (c) {
+            }
+        })
+    }, addClass: function (a) {
+        var b, c, d, e, g, h, i;
+        if (f.isFunction(a))return this.each(function (b) {
+            f(this).addClass(a.call(this, b, this.className))
+        });
+        if (a && typeof a == "string") {
+            b = a.split(p);
+            for (c = 0, d = this.length; c < d; c++) {
+                e = this[c];
+                if (e.nodeType === 1)if (!e.className && b.length === 1)e.className = a; else {
+                    g = " " + e.className + " ";
+                    for (h = 0, i = b.length; h < i; h++)~g.indexOf(" " + b[h] + " ") || (g += b[h] + " ");
+                    e.className = f.trim(g)
+                }
+            }
+        }
+        return this
+    }, removeClass: function (a) {
+        var c, d, e, g, h, i, j;
+        if (f.isFunction(a))return this.each(function (b) {
+            f(this).removeClass(a.call(this, b, this.className))
+        });
+        if (a && typeof a == "string" || a === b) {
+            c = (a || "").split(p);
+            for (d = 0, e = this.length; d < e; d++) {
+                g = this[d];
+                if (g.nodeType === 1 && g.className)if (a) {
+                    h = (" " + g.className + " ").replace(o, " ");
+                    for (i = 0, j = c.length; i < j; i++)h = h.replace(" " + c[i] + " ", " ");
+                    g.className = f.trim(h)
+                } else g.className = ""
+            }
+        }
+        return this
+    }, toggleClass: function (a, b) {
+        var c = typeof a, d = typeof b == "boolean";
+        if (f.isFunction(a))return this.each(function (c) {
+            f(this).toggleClass(a.call(this, c, this.className, b), b)
+        });
+        return this.each(function () {
+            if (c === "string") {
+                var e, g = 0, h = f(this), i = b, j = a.split(p);
+                while (e = j[g++])i = d ? i : !h.hasClass(e), h[i ? "addClass" : "removeClass"](e)
+            } else if (c === "undefined" || c === "boolean")this.className && f._data(this, "__className__", this.className), this.className = this.className || a === !1 ? "" : f._data(this, "__className__") || ""
+        })
+    }, hasClass: function (a) {
+        var b = " " + a + " ", c = 0, d = this.length;
+        for (; c < d; c++)if (this[c].nodeType === 1 && (" " + this[c].className + " ").replace(o, " ").indexOf(b) > -1)return!0;
+        return!1
+    }, val: function (a) {
+        var c, d, e, g = this[0];
+        {
+            if (!!arguments.length) {
+                e = f.isFunction(a);
+                return this.each(function (d) {
+                    var g = f(this), h;
+                    if (this.nodeType === 1) {
+                        e ? h = a.call(this, d, g.val()) : h = a, h == null ? h = "" : typeof h == "number" ? h += "" : f.isArray(h) && (h = f.map(h, function (a) {
+                            return a == null ? "" : a + ""
+                        })), c = f.valHooks[this.nodeName.toLowerCase()] || f.valHooks[this.type];
+                        if (!c || !("set"in c) || c.set(this, h, "value") === b)this.value = h
+                    }
+                })
+            }
+            if (g) {
+                c = f.valHooks[g.nodeName.toLowerCase()] || f.valHooks[g.type];
+                if (c && "get"in c && (d = c.get(g, "value")) !== b)return d;
+                d = g.value;
+                return typeof d == "string" ? d.replace(q, "") : d == null ? "" : d
+            }
+        }
+    }}), f.extend({valHooks: {option: {get: function (a) {
+        var b = a.attributes.value;
+        return!b || b.specified ? a.value : a.text
+    }}, select: {get: function (a) {
+        var b, c, d, e, g = a.selectedIndex, h = [], i = a.options, j = a.type === "select-one";
+        if (g < 0)return null;
+        c = j ? g : 0, d = j ? g + 1 : i.length;
+        for (; c < d; c++) {
+            e = i[c];
+            if (e.selected && (f.support.optDisabled ? !e.disabled : e.getAttribute("disabled") === null) && (!e.parentNode.disabled || !f.nodeName(e.parentNode, "optgroup"))) {
+                b = f(e).val();
+                if (j)return b;
+                h.push(b)
+            }
+        }
+        if (j && !h.length && i.length)return f(i[g]).val();
+        return h
+    }, set: function (a, b) {
+        var c = f.makeArray(b);
+        f(a).find("option").each(function () {
+            this.selected = f.inArray(f(this).val(), c) >= 0
+        }), c.length || (a.selectedIndex = -1);
+        return c
+    }}}, attrFn: {val: !0, css: !0, html: !0, text: !0, data: !0, width: !0, height: !0, offset: !0}, attr: function (a, c, d, e) {
+        var g, h, i, j = a.nodeType;
+        if (!!a && j !== 3 && j !== 8 && j !== 2) {
+            if (e && c in f.attrFn)return f(a)[c](d);
+            if (typeof a.getAttribute == "undefined")return f.prop(a, c, d);
+            i = j !== 1 || !f.isXMLDoc(a), i && (c = c.toLowerCase(), h = f.attrHooks[c] || (u.test(c) ? x : w));
+            if (d !== b) {
+                if (d === null) {
+                    f.removeAttr(a, c);
+                    return
+                }
+                if (h && "set"in h && i && (g = h.set(a, d, c)) !== b)return g;
+                a.setAttribute(c, "" + d);
+                return d
+            }
+            if (h && "get"in h && i && (g = h.get(a, c)) !== null)return g;
+            g = a.getAttribute(c);
+            return g === null ? b : g
+        }
+    }, removeAttr: function (a, b) {
+        var c, d, e, g, h = 0;
+        if (b && a.nodeType === 1) {
+            d = b.toLowerCase().split(p), g = d.length;
+            for (; h < g; h++)e = d[h], e && (c = f.propFix[e] || e, f.attr(a, e, ""), a.removeAttribute(v ? e : c), u.test(e) && c in a && (a[c] = !1))
+        }
+    }, attrHooks: {type: {set: function (a, b) {
+        if (r.test(a.nodeName) && a.parentNode)f.error("type property can't be changed"); else if (!f.support.radioValue && b === "radio" && f.nodeName(a, "input")) {
+            var c = a.value;
+            a.setAttribute("type", b), c && (a.value = c);
+            return b
+        }
+    }}, value: {get: function (a, b) {
+        if (w && f.nodeName(a, "button"))return w.get(a, b);
+        return b in a ? a.value : null
+    }, set: function (a, b, c) {
+        if (w && f.nodeName(a, "button"))return w.set(a, b, c);
+        a.value = b
+    }}}, propFix: {tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable"}, prop: function (a, c, d) {
+        var e, g, h, i = a.nodeType;
+        if (!!a && i !== 3 && i !== 8 && i !== 2) {
+            h = i !== 1 || !f.isXMLDoc(a), h && (c = f.propFix[c] || c, g = f.propHooks[c]);
+            return d !== b ? g && "set"in g && (e = g.set(a, d, c)) !== b ? e : a[c] = d : g && "get"in g && (e = g.get(a, c)) !== null ? e : a[c]
+        }
+    }, propHooks: {tabIndex: {get: function (a) {
+        var c = a.getAttributeNode("tabindex");
+        return c && c.specified ? parseInt(c.value, 10) : s.test(a.nodeName) || t.test(a.nodeName) && a.href ? 0 : b
+    }}}}), f.attrHooks.tabindex = f.propHooks.tabIndex, x = {get: function (a, c) {
+        var d, e = f.prop(a, c);
+        return e === !0 || typeof e != "boolean" && (d = a.getAttributeNode(c)) && d.nodeValue !== !1 ? c.toLowerCase() : b
+    }, set: function (a, b, c) {
+        var d;
+        b === !1 ? f.removeAttr(a, c) : (d = f.propFix[c] || c, d in a && (a[d] = !0), a.setAttribute(c, c.toLowerCase()));
+        return c
+    }}, v || (y = {name: !0, id: !0}, w = f.valHooks.button = {get: function (a, c) {
+        var d;
+        d = a.getAttributeNode(c);
+        return d && (y[c] ? d.nodeValue !== "" : d.specified) ? d.nodeValue : b
+    }, set: function (a, b, d) {
+        var e = a.getAttributeNode(d);
+        e || (e = c.createAttribute(d), a.setAttributeNode(e));
+        return e.nodeValue = b + ""
+    }}, f.attrHooks.tabindex.set = w.set, f.each(["width", "height"], function (a, b) {
+        f.attrHooks[b] = f.extend(f.attrHooks[b], {set: function (a, c) {
+            if (c === "") {
+                a.setAttribute(b, "auto");
+                return c
+            }
+        }})
+    }), f.attrHooks.contenteditable = {get: w.get, set: function (a, b, c) {
+        b === "" && (b = "false"), w.set(a, b, c)
+    }}), f.support.hrefNormalized || f.each(["href", "src", "width", "height"], function (a, c) {
+        f.attrHooks[c] = f.extend(f.attrHooks[c], {get: function (a) {
+            var d = a.getAttribute(c, 2);
+            return d === null ? b : d
+        }})
+    }), f.support.style || (f.attrHooks.style = {get: function (a) {
+        return a.style.cssText.toLowerCase() || b
+    }, set: function (a, b) {
+        return a.style.cssText = "" + b
+    }}), f.support.optSelected || (f.propHooks.selected = f.extend(f.propHooks.selected, {get: function (a) {
+        var b = a.parentNode;
+        b && (b.selectedIndex, b.parentNode && b.parentNode.selectedIndex);
+        return null
+    }})), f.support.enctype || (f.propFix.enctype = "encoding"), f.support.checkOn || f.each(["radio", "checkbox"], function () {
+        f.valHooks[this] = {get: function (a) {
+            return a.getAttribute("value") === null ? "on" : a.value
+        }}
+    }), f.each(["radio", "checkbox"], function () {
+        f.valHooks[this] = f.extend(f.valHooks[this], {set: function (a, b) {
+            if (f.isArray(b))return a.checked = f.inArray(f(a).val(), b) >= 0
+        }})
+    });
+    var z = /^(?:textarea|input|select)$/i, A = /^([^\.]*)?(?:\.(.+))?$/, B = /\bhover(\.\S+)?\b/, C = /^key/, D = /^(?:mouse|contextmenu)|click/, E = /^(?:focusinfocus|focusoutblur)$/, F = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, G = function (a) {
+        var b = F.exec(a);
+        b && (b[1] = (b[1] || "").toLowerCase(), b[3] = b[3] && new RegExp("(?:^|\\s)" + b[3] + "(?:\\s|$)"));
+        return b
+    }, H = function (a, b) {
+        var c = a.attributes || {};
+        return(!b[1] || a.nodeName.toLowerCase() === b[1]) && (!b[2] || (c.id || {}).value === b[2]) && (!b[3] || b[3].test((c["class"] || {}).value))
+    }, I = function (a) {
+        return f.event.special.hover ? a : a.replace(B, "mouseenter$1 mouseleave$1")
+    };
+    f.event = {add: function (a, c, d, e, g) {
+        var h, i, j, k, l, m, n, o, p, q, r, s;
+        if (!(a.nodeType === 3 || a.nodeType === 8 || !c || !d || !(h = f._data(a)))) {
+            d.handler && (p = d, d = p.handler), d.guid || (d.guid = f.guid++), j = h.events, j || (h.events = j = {}), i = h.handle, i || (h.handle = i = function (a) {
+                return typeof f != "undefined" && (!a || f.event.triggered !== a.type) ? f.event.dispatch.apply(i.elem, arguments) : b
+            }, i.elem = a), c = f.trim(I(c)).split(" ");
+            for (k = 0; k < c.length; k++) {
+                l = A.exec(c[k]) || [], m = l[1], n = (l[2] || "").split(".").sort(), s = f.event.special[m] || {}, m = (g ? s.delegateType : s.bindType) || m, s = f.event.special[m] || {}, o = f.extend({type: m, origType: l[1], data: e, handler: d, guid: d.guid, selector: g, quick: G(g), namespace: n.join(".")}, p), r = j[m];
+                if (!r) {
+                    r = j[m] = [], r.delegateCount = 0;
+                    if (!s.setup || s.setup.call(a, e, n, i) === !1)a.addEventListener ? a.addEventListener(m, i, !1) : a.attachEvent && a.attachEvent("on" + m, i)
+                }
+                s.add && (s.add.call(a, o), o.handler.guid || (o.handler.guid = d.guid)), g ? r.splice(r.delegateCount++, 0, o) : r.push(o), f.event.global[m] = !0
+            }
+            a = null
+        }
+    }, global: {}, remove: function (a, b, c, d, e) {
+        var g = f.hasData(a) && f._data(a), h, i, j, k, l, m, n, o, p, q, r, s;
+        if (!!g && !!(o = g.events)) {
+            b = f.trim(I(b || "")).split(" ");
+            for (h = 0; h < b.length; h++) {
+                i = A.exec(b[h]) || [], j = k = i[1], l = i[2];
+                if (!j) {
+                    for (j in o)f.event.remove(a, j + b[h], c, d, !0);
+                    continue
+                }
+                p = f.event.special[j] || {}, j = (d ? p.delegateType : p.bindType) || j, r = o[j] || [], m = r.length, l = l ? new RegExp("(^|\\.)" + l.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
+                for (n = 0; n < r.length; n++)s = r[n], (e || k === s.origType) && (!c || c.guid === s.guid) && (!l || l.test(s.namespace)) && (!d || d === s.selector || d === "**" && s.selector) && (r.splice(n--, 1), s.selector && r.delegateCount--, p.remove && p.remove.call(a, s));
+                r.length === 0 && m !== r.length && ((!p.teardown || p.teardown.call(a, l) === !1) && f.removeEvent(a, j, g.handle), delete o[j])
+            }
+            f.isEmptyObject(o) && (q = g.handle, q && (q.elem = null), f.removeData(a, ["events", "handle"], !0))
+        }
+    }, customEvent: {getData: !0, setData: !0, changeData: !0}, trigger: function (c, d, e, g) {
+        if (!e || e.nodeType !== 3 && e.nodeType !== 8) {
+            var h = c.type || c, i = [], j, k, l, m, n, o, p, q, r, s;
+            if (E.test(h + f.event.triggered))return;
+            h.indexOf("!") >= 0 && (h = h.slice(0, -1), k = !0), h.indexOf(".") >= 0 && (i = h.split("."), h = i.shift(), i.sort());
+            if ((!e || f.event.customEvent[h]) && !f.event.global[h])return;
+            c = typeof c == "object" ? c[f.expando] ? c : new f.Event(h, c) : new f.Event(h), c.type = h, c.isTrigger = !0, c.exclusive = k, c.namespace = i.join("."), c.namespace_re = c.namespace ? new RegExp("(^|\\.)" + i.join("\\.(?:.*\\.)?") + "(\\.|$)") : null, o = h.indexOf(":") < 0 ? "on" + h : "";
+            if (!e) {
+                j = f.cache;
+                for (l in j)j[l].events && j[l].events[h] && f.event.trigger(c, d, j[l].handle.elem, !0);
+                return
+            }
+            c.result = b, c.target || (c.target = e), d = d != null ? f.makeArray(d) : [], d.unshift(c), p = f.event.special[h] || {};
+            if (p.trigger && p.trigger.apply(e, d) === !1)return;
+            r = [
+                [e, p.bindType || h]
+            ];
+            if (!g && !p.noBubble && !f.isWindow(e)) {
+                s = p.delegateType || h, m = E.test(s + h) ? e : e.parentNode, n = null;
+                for (; m; m = m.parentNode)r.push([m, s]), n = m;
+                n && n === e.ownerDocument && r.push([n.defaultView || n.parentWindow || a, s])
+            }
+            for (l = 0; l < r.length && !c.isPropagationStopped(); l++)m = r[l][0], c.type = r[l][1], q = (f._data(m, "events") || {})[c.type] && f._data(m, "handle"), q && q.apply(m, d), q = o && m[o], q && f.acceptData(m) && q.apply(m, d) === !1 && c.preventDefault();
+            c.type = h, !g && !c.isDefaultPrevented() && (!p._default || p._default.apply(e.ownerDocument, d) === !1) && (h !== "click" || !f.nodeName(e, "a")) && f.acceptData(e) && o && e[h] && (h !== "focus" && h !== "blur" || c.target.offsetWidth !== 0) && !f.isWindow(e) && (n = e[o], n && (e[o] = null), f.event.triggered = h, e[h](), f.event.triggered = b, n && (e[o] = n));
+            return c.result
+        }
+    }, dispatch: function (c) {
+        c = f.event.fix(c || a.event);
+        var d = (f._data(this, "events") || {})[c.type] || [], e = d.delegateCount, g = [].slice.call(arguments, 0), h = !c.exclusive && !c.namespace, i = [], j, k, l, m, n, o, p, q, r, s, t;
+        g[0] = c, c.delegateTarget = this;
+        if (e && !c.target.disabled && (!c.button || c.type !== "click")) {
+            m = f(this), m.context = this.ownerDocument || this;
+            for (l = c.target; l != this; l = l.parentNode || this) {
+                o = {}, q = [], m[0] = l;
+                for (j = 0; j < e; j++)r = d[j], s = r.selector, o[s] === b && (o[s] = r.quick ? H(l, r.quick) : m.is(s)), o[s] && q.push(r);
+                q.length && i.push({elem: l, matches: q})
+            }
+        }
+        d.length > e && i.push({elem: this, matches: d.slice(e)});
+        for (j = 0; j < i.length && !c.isPropagationStopped(); j++) {
+            p = i[j], c.currentTarget = p.elem;
+            for (k = 0; k < p.matches.length && !c.isImmediatePropagationStopped(); k++) {
+                r = p.matches[k];
+                if (h || !c.namespace && !r.namespace || c.namespace_re && c.namespace_re.test(r.namespace))c.data = r.data, c.handleObj = r, n = ((f.event.special[r.origType] || {}).handle || r.handler).apply(p.elem, g), n !== b && (c.result = n, n === !1 && (c.preventDefault(), c.stopPropagation()))
+            }
+        }
+        return c.result
+    }, props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: {props: "char charCode key keyCode".split(" "), filter: function (a, b) {
+        a.which == null && (a.which = b.charCode != null ? b.charCode : b.keyCode);
+        return a
+    }}, mouseHooks: {props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function (a, d) {
+        var e, f, g, h = d.button, i = d.fromElement;
+        a.pageX == null && d.clientX != null && (e = a.target.ownerDocument || c, f = e.documentElement, g = e.body, a.pageX = d.clientX + (f && f.scrollLeft || g && g.scrollLeft || 0) - (f && f.clientLeft || g && g.clientLeft || 0), a.pageY = d.clientY + (f && f.scrollTop || g && g.scrollTop || 0) - (f && f.clientTop || g && g.clientTop || 0)), !a.relatedTarget && i && (a.relatedTarget = i === a.target ? d.toElement : i), !a.which && h !== b && (a.which = h & 1 ? 1 : h & 2 ? 3 : h & 4 ? 2 : 0);
+        return a
+    }}, fix: function (a) {
+        if (a[f.expando])return a;
+        var d, e, g = a, h = f.event.fixHooks[a.type] || {}, i = h.props ? this.props.concat(h.props) : this.props;
+        a = f.Event(g);
+        for (d = i.length; d;)e = i[--d], a[e] = g[e];
+        a.target || (a.target = g.srcElement || c), a.target.nodeType === 3 && (a.target = a.target.parentNode), a.metaKey === b && (a.metaKey = a.ctrlKey);
+        return h.filter ? h.filter(a, g) : a
+    }, special: {ready: {setup: f.bindReady}, load: {noBubble: !0}, focus: {delegateType: "focusin"}, blur: {delegateType: "focusout"}, beforeunload: {setup: function (a, b, c) {
+        f.isWindow(this) && (this.onbeforeunload = c)
+    }, teardown: function (a, b) {
+        this.onbeforeunload === b && (this.onbeforeunload = null)
+    }}}, simulate: function (a, b, c, d) {
+        var e = f.extend(new f.Event, c, {type: a, isSimulated: !0, originalEvent: {}});
+        d ? f.event.trigger(e, null, b) : f.event.dispatch.call(b, e), e.isDefaultPrevented() && c.preventDefault()
+    }}, f.event.handle = f.event.dispatch, f.removeEvent = c.removeEventListener ? function (a, b, c) {
+        a.removeEventListener && a.removeEventListener(b, c, !1)
+    } : function (a, b, c) {
+        a.detachEvent && a.detachEvent("on" + b, c)
+    }, f.Event = function (a, b) {
+        if (!(this instanceof f.Event))return new f.Event(a, b);
+        a && a.type ? (this.originalEvent = a, this.type = a.type, this.isDefaultPrevented = a.defaultPrevented || a.returnValue === !1 || a.getPreventDefault && a.getPreventDefault() ? K : J) : this.type = a, b && f.extend(this, b), this.timeStamp = a && a.timeStamp || f.now(), this[f.expando] = !0
+    }, f.Event.prototype = {preventDefault: function () {
+        this.isDefaultPrevented = K;
+        var a = this.originalEvent;
+        !a || (a.preventDefault ? a.preventDefault() : a.returnValue = !1)
+    }, stopPropagation: function () {
+        this.isPropagationStopped = K;
+        var a = this.originalEvent;
+        !a || (a.stopPropagation && a.stopPropagation(), a.cancelBubble = !0)
+    }, stopImmediatePropagation: function () {
+        this.isImmediatePropagationStopped = K, this.stopPropagation()
+    }, isDefaultPrevented: J, isPropagationStopped: J, isImmediatePropagationStopped: J}, f.each({mouseenter: "mouseover", mouseleave: "mouseout"}, function (a, b) {
+        f.event.special[a] = {delegateType: b, bindType: b, handle: function (a) {
+            var c = this, d = a.relatedTarget, e = a.handleObj, g = e.selector, h;
+            if (!d || d !== c && !f.contains(c, d))a.type = e.origType, h = e.handler.apply(this, arguments), a.type = b;
+            return h
+        }}
+    }), f.support.submitBubbles || (f.event.special.submit = {setup: function () {
+        if (f.nodeName(this, "form"))return!1;
+        f.event.add(this, "click._submit keypress._submit", function (a) {
+            var c = a.target, d = f.nodeName(c, "input") || f.nodeName(c, "button") ? c.form : b;
+            d && !d._submit_attached && (f.event.add(d, "submit._submit", function (a) {
+                this.parentNode && !a.isTrigger && f.event.simulate("submit", this.parentNode, a, !0)
+            }), d._submit_attached = !0)
+        })
+    }, teardown: function () {
+        if (f.nodeName(this, "form"))return!1;
+        f.event.remove(this, "._submit")
+    }}), f.support.changeBubbles || (f.event.special.change = {setup: function () {
+        if (z.test(this.nodeName)) {
+            if (this.type === "checkbox" || this.type === "radio")f.event.add(this, "propertychange._change", function (a) {
+                a.originalEvent.propertyName === "checked" && (this._just_changed = !0)
+            }), f.event.add(this, "click._change", function (a) {
+                this._just_changed && !a.isTrigger && (this._just_changed = !1, f.event.simulate("change", this, a, !0))
+            });
+            return!1
+        }
+        f.event.add(this, "beforeactivate._change", function (a) {
+            var b = a.target;
+            z.test(b.nodeName) && !b._change_attached && (f.event.add(b, "change._change", function (a) {
+                this.parentNode && !a.isSimulated && !a.isTrigger && f.event.simulate("change", this.parentNode, a, !0)
+            }), b._change_attached = !0)
+        })
+    }, handle: function (a) {
+        var b = a.target;
+        if (this !== b || a.isSimulated || a.isTrigger || b.type !== "radio" && b.type !== "checkbox")return a.handleObj.handler.apply(this, arguments)
+    }, teardown: function () {
+        f.event.remove(this, "._change");
+        return z.test(this.nodeName)
+    }}), f.support.focusinBubbles || f.each({focus: "focusin", blur: "focusout"}, function (a, b) {
+        var d = 0, e = function (a) {
+            f.event.simulate(b, a.target, f.event.fix(a), !0)
+        };
+        f.event.special[b] = {setup: function () {
+            d++ === 0 && c.addEventListener(a, e, !0)
+        }, teardown: function () {
+            --d === 0 && c.removeEventListener(a, e, !0)
+        }}
+    }), f.fn.extend({on: function (a, c, d, e, g) {
+        var h, i;
+        if (typeof a == "object") {
+            typeof c != "string" && (d = c, c = b);
+            for (i in a)this.on(i, c, d, a[i], g);
+            return this
+        }
+        d == null && e == null ? (e = c, d = c = b) : e == null && (typeof c == "string" ? (e = d, d = b) : (e = d, d = c, c = b));
+        if (e === !1)e = J; else if (!e)return this;
+        g === 1 && (h = e, e = function (a) {
+            f().off(a);
+            return h.apply(this, arguments)
+        }, e.guid = h.guid || (h.guid = f.guid++));
+        return this.each(function () {
+            f.event.add(this, a, e, d, c)
+        })
+    }, one: function (a, b, c, d) {
+        return this.on.call(this, a, b, c, d, 1)
+    }, off: function (a, c, d) {
+        if (a && a.preventDefault && a.handleObj) {
+            var e = a.handleObj;
+            f(a.delegateTarget).off(e.namespace ? e.type + "." + e.namespace : e.type, e.selector, e.handler);
+            return this
+        }
+        if (typeof a == "object") {
+            for (var g in a)this.off(g, c, a[g]);
+            return this
+        }
+        if (c === !1 || typeof c == "function")d = c, c = b;
+        d === !1 && (d = J);
+        return this.each(function () {
+            f.event.remove(this, a, d, c)
+        })
+    }, bind: function (a, b, c) {
+        return this.on(a, null, b, c)
+    }, unbind: function (a, b) {
+        return this.off(a, null, b)
+    }, live: function (a, b, c) {
+        f(this.context).on(a, this.selector, b, c);
+        return this
+    }, die: function (a, b) {
+        f(this.context).off(a, this.selector || "**", b);
+        return this
+    }, delegate: function (a, b, c, d) {
+        return this.on(b, a, c, d)
+    }, undelegate: function (a, b, c) {
+        return arguments.length == 1 ? this.off(a, "**") : this.off(b, a, c)
+    }, trigger: function (a, b) {
+        return this.each(function () {
+            f.event.trigger(a, b, this)
+        })
+    }, triggerHandler: function (a, b) {
+        if (this[0])return f.event.trigger(a, b, this[0], !0)
+    }, toggle: function (a) {
+        var b = arguments, c = a.guid || f.guid++, d = 0, e = function (c) {
+            var e = (f._data(this, "lastToggle" + a.guid) || 0) % d;
+            f._data(this, "lastToggle" + a.guid, e + 1), c.preventDefault();
+            return b[e].apply(this, arguments) || !1
+        };
+        e.guid = c;
+        while (d < b.length)b[d++].guid = c;
+        return this.click(e)
+    }, hover: function (a, b) {
+        return this.mouseenter(a).mouseleave(b || a)
+    }}), f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "), function (a, b) {
+        f.fn[b] = function (a, c) {
+            c == null && (c = a, a = null);
+            return arguments.length > 0 ? this.on(b, null, a, c) : this.trigger(b)
+        }, f.attrFn && (f.attrFn[b] = !0), C.test(b) && (f.event.fixHooks[b] = f.event.keyHooks), D.test(b) && (f.event.fixHooks[b] = f.event.mouseHooks)
+    }), function () {
+        function x(a, b, c, e, f, g) {
+            for (var h = 0, i = e.length; h < i; h++) {
+                var j = e[h];
+                if (j) {
+                    var k = !1;
+                    j = j[a];
+                    while (j) {
+                        if (j[d] === c) {
+                            k = e[j.sizset];
+                            break
+                        }
+                        if (j.nodeType === 1) {
+                            g || (j[d] = c, j.sizset = h);
+                            if (typeof b != "string") {
+                                if (j === b) {
+                                    k = !0;
+                                    break
+                                }
+                            } else if (m.filter(b, [j]).length > 0) {
+                                k = j;
+                                break
+                            }
+                        }
+                        j = j[a]
+                    }
+                    e[h] = k
+                }
+            }
+        }
+
+        function w(a, b, c, e, f, g) {
+            for (var h = 0, i = e.length; h < i; h++) {
+                var j = e[h];
+                if (j) {
+                    var k = !1;
+                    j = j[a];
+                    while (j) {
+                        if (j[d] === c) {
+                            k = e[j.sizset];
+                            break
+                        }
+                        j.nodeType === 1 && !g && (j[d] = c, j.sizset = h);
+                        if (j.nodeName.toLowerCase() === b) {
+                            k = j;
+                            break
+                        }
+                        j = j[a]
+                    }
+                    e[h] = k
+                }
+            }
+        }
+
+        var a = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, d = "sizcache" + (Math.random() + "").replace(".", ""), e = 0, g = Object.prototype.toString, h = !1, i = !0, j = /\\/g, k = /\r\n/g, l = /\W/;
+        [0, 0].sort(function () {
+            i = !1;
+            return 0
+        });
+        var m = function (b, d, e, f) {
+            e = e || [], d = d || c;
+            var h = d;
+            if (d.nodeType !== 1 && d.nodeType !== 9)return[];
+            if (!b || typeof b != "string")return e;
+            var i, j, k, l, n, q, r, t, u = !0, v = m.isXML(d), w = [], x = b;
+            do {
+                a.exec(""), i = a.exec(x);
+                if (i) {
+                    x = i[3], w.push(i[1]);
+                    if (i[2]) {
+                        l = i[3];
+                        break
+                    }
+                }
+            } while (i);
+            if (w.length > 1 && p.exec(b))if (w.length === 2 && o.relative[w[0]])j = y(w[0] + w[1], d, f); else {
+                j = o.relative[w[0]] ? [d] : m(w.shift(), d);
+                while (w.length)b = w.shift(), o.relative[b] && (b += w.shift()), j = y(b, j, f)
+            } else {
+                !f && w.length > 1 && d.nodeType === 9 && !v && o.match.ID.test(w[0]) && !o.match.ID.test(w[w.length - 1]) && (n = m.find(w.shift(), d, v), d = n.expr ? m.filter(n.expr, n.set)[0] : n.set[0]);
+                if (d) {
+                    n = f ? {expr: w.pop(), set: s(f)} : m.find(w.pop(), w.length === 1 && (w[0] === "~" || w[0] === "+") && d.parentNode ? d.parentNode : d, v), j = n.expr ? m.filter(n.expr, n.set) : n.set, w.length > 0 ? k = s(j) : u = !1;
+                    while (w.length)q = w.pop(), r = q, o.relative[q] ? r = w.pop() : q = "", r == null && (r = d), o.relative[q](k, r, v)
+                } else k = w = []
+            }
+            k || (k = j), k || m.error(q || b);
+            if (g.call(k) === "[object Array]")if (!u)e.push.apply(e, k); else if (d && d.nodeType === 1)for (t = 0; k[t] != null; t++)k[t] && (k[t] === !0 || k[t].nodeType === 1 && m.contains(d, k[t])) && e.push(j[t]); else for (t = 0; k[t] != null; t++)k[t] && k[t].nodeType === 1 && e.push(j[t]); else s(k, e);
+            l && (m(l, h, e, f), m.uniqueSort(e));
+            return e
+        };
+        m.uniqueSort = function (a) {
+            if (u) {
+                h = i, a.sort(u);
+                if (h)for (var b = 1; b < a.length; b++)a[b] === a[b - 1] && a.splice(b--, 1)
+            }
+            return a
+        }, m.matches = function (a, b) {
+            return m(a, null, null, b)
+        }, m.matchesSelector = function (a, b) {
+            return m(b, null, null, [a]).length > 0
+        }, m.find = function (a, b, c) {
+            var d, e, f, g, h, i;
+            if (!a)return[];
+            for (e = 0, f = o.order.length; e < f; e++) {
+                h = o.order[e];
+                if (g = o.leftMatch[h].exec(a)) {
+                    i = g[1], g.splice(1, 1);
+                    if (i.substr(i.length - 1) !== "\\") {
+                        g[1] = (g[1] || "").replace(j, ""), d = o.find[h](g, b, c);
+                        if (d != null) {
+                            a = a.replace(o.match[h], "");
+                            break
+                        }
+                    }
+                }
+            }
+            d || (d = typeof b.getElementsByTagName != "undefined" ? b.getElementsByTagName("*") : []);
+            return{set: d, expr: a}
+        }, m.filter = function (a, c, d, e) {
+            var f, g, h, i, j, k, l, n, p, q = a, r = [], s = c, t = c && c[0] && m.isXML(c[0]);
+            while (a && c.length) {
+                for (h in o.filter)if ((f = o.leftMatch[h].exec(a)) != null && f[2]) {
+                    k = o.filter[h], l = f[1], g = !1, f.splice(1, 1);
+                    if (l.substr(l.length - 1) === "\\")continue;
+                    s === r && (r = []);
+                    if (o.preFilter[h]) {
+                        f = o.preFilter[h](f, s, d, r, e, t);
+                        if (!f)g = i = !0; else if (f === !0)continue
+                    }
+                    if (f)for (n = 0; (j = s[n]) != null; n++)j && (i = k(j, f, n, s), p = e ^ i, d && i != null ? p ? g = !0 : s[n] = !1 : p && (r.push(j), g = !0));
+                    if (i !== b) {
+                        d || (s = r), a = a.replace(o.match[h], "");
+                        if (!g)return[];
+                        break
+                    }
+                }
+                if (a === q)if (g == null)m.error(a); else break;
+                q = a
+            }
+            return s
+        }, m.error = function (a) {
+            throw new Error("Syntax error, unrecognized expression: " + a)
+        };
+        var n = m.getText = function (a) {
+            var b, c, d = a.nodeType, e = "";
+            if (d) {
+                if (d === 1 || d === 9) {
+                    if (typeof a.textContent == "string")return a.textContent;
+                    if (typeof a.innerText == "string")return a.innerText.replace(k, "");
+                    for (a = a.firstChild; a; a = a.nextSibling)e += n(a)
+                } else if (d === 3 || d === 4)return a.nodeValue
+            } else for (b = 0; c = a[b]; b++)c.nodeType !== 8 && (e += n(c));
+            return e
+        }, o = m.selectors = {order: ["ID", "NAME", "TAG"], match: {ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/}, leftMatch: {}, attrMap: {"class": "className", "for": "htmlFor"}, attrHandle: {href: function (a) {
+            return a.getAttribute("href")
+        }, type: function (a) {
+            return a.getAttribute("type")
+        }}, relative: {"+": function (a, b) {
+            var c = typeof b == "string", d = c && !l.test(b), e = c && !d;
+            d && (b = b.toLowerCase());
+            for (var f = 0, g = a.length, h; f < g; f++)if (h = a[f]) {
+                while ((h = h.previousSibling) && h.nodeType !== 1);
+                a[f] = e || h && h.nodeName.toLowerCase() === b ? h || !1 : h === b
+            }
+            e && m.filter(b, a, !0)
+        }, ">": function (a, b) {
+            var c, d = typeof b == "string", e = 0, f = a.length;
+            if (d && !l.test(b)) {
+                b = b.toLowerCase();
+                for (; e < f; e++) {
+                    c = a[e];
+                    if (c) {
+                        var g = c.parentNode;
+                        a[e] = g.nodeName.toLowerCase() === b ? g : !1
+                    }
+                }
+            } else {
+                for (; e < f; e++)c = a[e], c && (a[e] = d ? c.parentNode : c.parentNode === b);
+                d && m.filter(b, a, !0)
+            }
+        }, "": function (a, b, c) {
+            var d, f = e++, g = x;
+            typeof b == "string" && !l.test(b) && (b = b.toLowerCase(), d = b, g = w), g("parentNode", b, f, a, d, c)
+        }, "~": function (a, b, c) {
+            var d, f = e++, g = x;
+            typeof b == "string" && !l.test(b) && (b = b.toLowerCase(), d = b, g = w), g("previousSibling", b, f, a, d, c)
+        }}, find: {ID: function (a, b, c) {
+            if (typeof b.getElementById != "undefined" && !c) {
+                var d = b.getElementById(a[1]);
+                return d && d.parentNode ? [d] : []
+            }
+        }, NAME: function (a, b) {
+            if (typeof b.getElementsByName != "undefined") {
+                var c = [], d = b.getElementsByName(a[1]);
+                for (var e = 0, f = d.length; e < f; e++)d[e].getAttribute("name") === a[1] && c.push(d[e]);
+                return c.length === 0 ? null : c
+            }
+        }, TAG: function (a, b) {
+            if (typeof b.getElementsByTagName != "undefined")return b.getElementsByTagName(a[1])
+        }}, preFilter: {CLASS: function (a, b, c, d, e, f) {
+            a = " " + a[1].replace(j, "") + " ";
+            if (f)return a;
+            for (var g = 0, h; (h = b[g]) != null; g++)h && (e ^ (h.className && (" " + h.className + " ").replace(/[\t\n\r]/g, " ").indexOf(a) >= 0) ? c || d.push(h) : c && (b[g] = !1));
+            return!1
+        }, ID: function (a) {
+            return a[1].replace(j, "")
+        }, TAG: function (a, b) {
+            return a[1].replace(j, "").toLowerCase()
+        }, CHILD: function (a) {
+            if (a[1] === "nth") {
+                a[2] || m.error(a[0]), a[2] = a[2].replace(/^\+|\s*/g, "");
+                var b = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2] === "even" && "2n" || a[2] === "odd" && "2n+1" || !/\D/.test(a[2]) && "0n+" + a[2] || a[2]);
+                a[2] = b[1] + (b[2] || 1) - 0, a[3] = b[3] - 0
+            } else a[2] && m.error(a[0]);
+            a[0] = e++;
+            return a
+        }, ATTR: function (a, b, c, d, e, f) {
+            var g = a[1] = a[1].replace(j, "");
+            !f && o.attrMap[g] && (a[1] = o.attrMap[g]), a[4] = (a[4] || a[5] || "").replace(j, ""), a[2] === "~=" && (a[4] = " " + a[4] + " ");
+            return a
+        }, PSEUDO: function (b, c, d, e, f) {
+            if (b[1] === "not")if ((a.exec(b[3]) || "").length > 1 || /^\w/.test(b[3]))b[3] = m(b[3], null, null, c); else {
+                var g = m.filter(b[3], c, d, !0 ^ f);
+                d || e.push.apply(e, g);
+                return!1
+            } else if (o.match.POS.test(b[0]) || o.match.CHILD.test(b[0]))return!0;
+            return b
+        }, POS: function (a) {
+            a.unshift(!0);
+            return a
+        }}, filters: {enabled: function (a) {
+            return a.disabled === !1 && a.type !== "hidden"
+        }, disabled: function (a) {
+            return a.disabled === !0
+        }, checked: function (a) {
+            return a.checked === !0
+        }, selected: function (a) {
+            a.parentNode && a.parentNode.selectedIndex;
+            return a.selected === !0
+        }, parent: function (a) {
+            return!!a.firstChild
+        }, empty: function (a) {
+            return!a.firstChild
+        }, has: function (a, b, c) {
+            return!!m(c[3], a).length
+        }, header: function (a) {
+            return/h\d/i.test(a.nodeName)
+        }, text: function (a) {
+            var b = a.getAttribute("type"), c = a.type;
+            return a.nodeName.toLowerCase() === "input" && "text" === c && (b === c || b === null)
+        }, radio: function (a) {
+            return a.nodeName.toLowerCase() === "input" && "radio" === a.type
+        }, checkbox: function (a) {
+            return a.nodeName.toLowerCase() === "input" && "checkbox" === a.type
+        }, file: function (a) {
+            return a.nodeName.toLowerCase() === "input" && "file" === a.type
+        }, password: function (a) {
+            return a.nodeName.toLowerCase() === "input" && "password" === a.type
+        }, submit: function (a) {
+            var b = a.nodeName.toLowerCase();
+            return(b === "input" || b === "button") && "submit" === a.type
+        }, image: function (a) {
+            return a.nodeName.toLowerCase() === "input" && "image" === a.type
+        }, reset: function (a) {
+            var b = a.nodeName.toLowerCase();
+            return(b === "input" || b === "button") && "reset" === a.type
+        }, button: function (a) {
+            var b = a.nodeName.toLowerCase();
+            return b === "input" && "button" === a.type || b === "button"
+        }, input: function (a) {
+            return/input|select|textarea|button/i.test(a.nodeName)
+        }, focus: function (a) {
+            return a === a.ownerDocument.activeElement
+        }}, setFilters: {first: function (a, b) {
+            return b === 0
+        }, last: function (a, b, c, d) {
+            return b === d.length - 1
+        }, even: function (a, b) {
+            return b % 2 === 0
+        }, odd: function (a, b) {
+            return b % 2 === 1
+        }, lt: function (a, b, c) {
+            return b < c[3] - 0
+        }, gt: function (a, b, c) {
+            return b > c[3] - 0
+        }, nth: function (a, b, c) {
+            return c[3] - 0 === b
+        }, eq: function (a, b, c) {
+            return c[3] - 0 === b
+        }}, filter: {PSEUDO: function (a, b, c, d) {
+            var e = b[1], f = o.filters[e];
+            if (f)return f(a, c, b, d);
+            if (e === "contains")return(a.textContent || a.innerText || n([a]) || "").indexOf(b[3]) >= 0;
+            if (e === "not") {
+                var g = b[3];
+                for (var h = 0, i = g.length; h < i; h++)if (g[h] === a)return!1;
+                return!0
+            }
+            m.error(e)
+        }, CHILD: function (a, b) {
+            var c, e, f, g, h, i, j, k = b[1], l = a;
+            switch (k) {
+                case"only":
+                case"first":
+                    while (l = l.previousSibling)if (l.nodeType === 1)return!1;
+                    if (k === "first")return!0;
+                    l = a;
+                case"last":
+                    while (l = l.nextSibling)if (l.nodeType === 1)return!1;
+                    return!0;
+                case"nth":
+                    c = b[2], e = b[3];
+                    if (c === 1 && e === 0)return!0;
+                    f = b[0], g = a.parentNode;
+                    if (g && (g[d] !== f || !a.nodeIndex)) {
+                        i = 0;
+                        for (l = g.firstChild; l; l = l.nextSibling)l.nodeType === 1 && (l.nodeIndex = ++i);
+                        g[d] = f
+                    }
+                    j = a.nodeIndex - e;
+                    return c === 0 ? j === 0 : j % c === 0 && j / c >= 0
+            }
+        }, ID: function (a, b) {
+            return a.nodeType === 1 && a.getAttribute("id") === b
+        }, TAG: function (a, b) {
+            return b === "*" && a.nodeType === 1 || !!a.nodeName && a.nodeName.toLowerCase() === b
+        }, CLASS: function (a, b) {
+            return(" " + (a.className || a.getAttribute("class")) + " ").indexOf(b) > -1
+        }, ATTR: function (a, b) {
+            var c = b[1], d = m.attr ? m.attr(a, c) : o.attrHandle[c] ? o.attrHandle[c](a) : a[c] != null ? a[c] : a.getAttribute(c), e = d + "", f = b[2], g = b[4];
+            return d == null ? f === "!=" : !f && m.attr ? d != null : f === "=" ? e === g : f === "*=" ? e.indexOf(g) >= 0 : f === "~=" ? (" " + e + " ").indexOf(g) >= 0 : g ? f === "!=" ? e !== g : f === "^=" ? e.indexOf(g) === 0 : f === "$=" ? e.substr(e.length - g.length) === g : f === "|=" ? e === g || e.substr(0, g.length + 1) === g + "-" : !1 : e && d !== !1
+        }, POS: function (a, b, c, d) {
+            var e = b[2], f = o.setFilters[e];
+            if (f)return f(a, c, b, d)
+        }}}, p = o.match.POS, q = function (a, b) {
+            return"\\" + (b - 0 + 1)
+        };
+        for (var r in o.match)o.match[r] = new RegExp(o.match[r].source + /(?![^\[]*\])(?![^\(]*\))/.source), o.leftMatch[r] = new RegExp(/(^(?:.|\r|\n)*?)/.source + o.match[r].source.replace(/\\(\d+)/g, q));
+        var s = function (a, b) {
+            a = Array.prototype.slice.call(a, 0);
+            if (b) {
+                b.push.apply(b, a);
+                return b
+            }
+            return a
+        };
+        try {
+            Array.prototype.slice.call(c.documentElement.childNodes, 0)[0].nodeType
+        } catch (t) {
+            s = function (a, b) {
+                var c = 0, d = b || [];
+                if (g.call(a) === "[object Array]")Array.prototype.push.apply(d, a); else if (typeof a.length == "number")for (var e = a.length; c < e; c++)d.push(a[c]); else for (; a[c]; c++)d.push(a[c]);
+                return d
+            }
+        }
+        var u, v;
+        c.documentElement.compareDocumentPosition ? u = function (a, b) {
+            if (a === b) {
+                h = !0;
+                return 0
+            }
+            if (!a.compareDocumentPosition || !b.compareDocumentPosition)return a.compareDocumentPosition ? -1 : 1;
+            return a.compareDocumentPosition(b) & 4 ? -1 : 1
+        } : (u = function (a, b) {
+            if (a === b) {
+                h = !0;
+                return 0
+            }
+            if (a.sourceIndex && b.sourceIndex)return a.sourceIndex - b.sourceIndex;
+            var c, d, e = [], f = [], g = a.parentNode, i = b.parentNode, j = g;
+            if (g === i)return v(a, b);
+            if (!g)return-1;
+            if (!i)return 1;
+            while (j)e.unshift(j), j = j.parentNode;
+            j = i;
+            while (j)f.unshift(j), j = j.parentNode;
+            c = e.length, d = f.length;
+            for (var k = 0; k < c && k < d; k++)if (e[k] !== f[k])return v(e[k], f[k]);
+            return k === c ? v(a, f[k], -1) : v(e[k], b, 1)
+        }, v = function (a, b, c) {
+            if (a === b)return c;
+            var d = a.nextSibling;
+            while (d) {
+                if (d === b)return-1;
+                d = d.nextSibling
+            }
+            return 1
+        }), function () {
+            var a = c.createElement("div"), d = "script" + (new Date).getTime(), e = c.documentElement;
+            a.innerHTML = "<a name='" + d + "'/>", e.insertBefore(a, e.firstChild), c.getElementById(d) && (o.find.ID = function (a, c, d) {
+                if (typeof c.getElementById != "undefined" && !d) {
+                    var e = c.getElementById(a[1]);
+                    return e ? e.id === a[1] || typeof e.getAttributeNode != "undefined" && e.getAttributeNode("id").nodeValue === a[1] ? [e] : b : []
+                }
+            }, o.filter.ID = function (a, b) {
+                var c = typeof a.getAttributeNode != "undefined" && a.getAttributeNode("id");
+                return a.nodeType === 1 && c && c.nodeValue === b
+            }), e.removeChild(a), e = a = null
+        }(), function () {
+            var a = c.createElement("div");
+            a.appendChild(c.createComment("")), a.getElementsByTagName("*").length > 0 && (o.find.TAG = function (a, b) {
+                var c = b.getElementsByTagName(a[1]);
+                if (a[1] === "*") {
+                    var d = [];
+                    for (var e = 0; c[e]; e++)c[e].nodeType === 1 && d.push(c[e]);
+                    c = d
+                }
+                return c
+            }), a.innerHTML = "<a href='#'></a>", a.firstChild && typeof a.firstChild.getAttribute != "undefined" && a.firstChild.getAttribute("href") !== "#" && (o.attrHandle.href = function (a) {
+                return a.getAttribute("href", 2)
+            }), a = null
+        }(), c.querySelectorAll && function () {
+            var a = m, b = c.createElement("div"), d = "__sizzle__";
+            b.innerHTML = "<p class='TEST'></p>";
+            if (!b.querySelectorAll || b.querySelectorAll(".TEST").length !== 0) {
+                m = function (b, e, f, g) {
+                    e = e || c;
+                    if (!g && !m.isXML(e)) {
+                        var h = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);
+                        if (h && (e.nodeType === 1 || e.nodeType === 9)) {
+                            if (h[1])return s(e.getElementsByTagName(b), f);
+                            if (h[2] && o.find.CLASS && e.getElementsByClassName)return s(e.getElementsByClassName(h[2]), f)
+                        }
+                        if (e.nodeType === 9) {
+                            if (b === "body" && e.body)return s([e.body], f);
+                            if (h && h[3]) {
+                                var i = e.getElementById(h[3]);
+                                if (!i || !i.parentNode)return s([], f);
+                                if (i.id === h[3])return s([i], f)
+                            }
+                            try {
+                                return s(e.querySelectorAll(b), f)
+                            } catch (j) {
+                            }
+                        } else if (e.nodeType === 1 && e.nodeName.toLowerCase() !== "object") {
+                            var k = e, l = e.getAttribute("id"), n = l || d, p = e.parentNode, q = /^\s*[+~]/.test(b);
+                            l ? n = n.replace(/'/g, "\\$&") : e.setAttribute("id", n), q && p && (e = e.parentNode);
+                            try {
+                                if (!q || p)return s(e.querySelectorAll("[id='" + n + "'] " + b), f)
+                            } catch (r) {
+                            } finally {
+                                l || k.removeAttribute("id")
+                            }
+                        }
+                    }
+                    return a(b, e, f, g)
+                };
+                for (var e in a)m[e] = a[e];
+                b = null
+            }
+        }(), function () {
+            var a = c.documentElement, b = a.matchesSelector || a.mozMatchesSelector || a.webkitMatchesSelector || a.msMatchesSelector;
+            if (b) {
+                var d = !b.call(c.createElement("div"), "div"), e = !1;
+                try {
+                    b.call(c.documentElement, "[test!='']:sizzle")
+                } catch (f) {
+                    e = !0
+                }
+                m.matchesSelector = function (a, c) {
+                    c = c.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
+                    if (!m.isXML(a))try {
+                        if (e || !o.match.PSEUDO.test(c) && !/!=/.test(c)) {
+                            var f = b.call(a, c);
+                            if (f || !d || a.document && a.document.nodeType !== 11)return f
+                        }
+                    } catch (g) {
+                    }
+                    return m(c, null, null, [a]).length > 0
+                }
+            }
+        }(), function () {
+            var a = c.createElement("div");
+            a.innerHTML = "<div class='test e'></div><div class='test'></div>";
+            if (!!a.getElementsByClassName && a.getElementsByClassName("e").length !== 0) {
+                a.lastChild.className = "e";
+                if (a.getElementsByClassName("e").length === 1)return;
+                o.order.splice(1, 0, "CLASS"), o.find.CLASS = function (a, b, c) {
+                    if (typeof b.getElementsByClassName != "undefined" && !c)return b.getElementsByClassName(a[1])
+                }, a = null
+            }
+        }(), c.documentElement.contains ? m.contains = function (a, b) {
+            return a !== b && (a.contains ? a.contains(b) : !0)
+        } : c.documentElement.compareDocumentPosition ? m.contains = function (a, b) {
+            return!!(a.compareDocumentPosition(b) & 16)
+        } : m.contains = function () {
+            return!1
+        }, m.isXML = function (a) {
+            var b = (a ? a.ownerDocument || a : 0).documentElement;
+            return b ? b.nodeName !== "HTML" : !1
+        };
+        var y = function (a, b, c) {
+            var d, e = [], f = "", g = b.nodeType ? [b] : b;
+            while (d = o.match.PSEUDO.exec(a))f += d[0], a = a.replace(o.match.PSEUDO, "");
+            a = o.relative[a] ? a + "*" : a;
+            for (var h = 0, i = g.length; h < i; h++)m(a, g[h], e, c);
+            return m.filter(f, e)
+        };
+        m.attr = f.attr, m.selectors.attrMap = {}, f.find = m, f.expr = m.selectors, f.expr[":"] = f.expr.filters, f.unique = m.uniqueSort, f.text = m.getText, f.isXMLDoc = m.isXML, f.contains = m.contains
+    }();
+    var L = /Until$/, M = /^(?:parents|prevUntil|prevAll)/, N = /,/, O = /^.[^:#\[\.,]*$/, P = Array.prototype.slice, Q = f.expr.match.POS, R = {children: !0, contents: !0, next: !0, prev: !0};
+    f.fn.extend({find: function (a) {
+        var b = this, c, d;
+        if (typeof a != "string")return f(a).filter(function () {
+            for (c = 0, d = b.length; c < d; c++)if (f.contains(b[c], this))return!0
+        });
+        var e = this.pushStack("", "find", a), g, h, i;
+        for (c = 0, d = this.length; c < d; c++) {
+            g = e.length, f.find(a, this[c], e);
+            if (c > 0)for (h = g; h < e.length; h++)for (i = 0; i < g; i++)if (e[i] === e[h]) {
+                e.splice(h--, 1);
+                break
+            }
+        }
+        return e
+    }, has: function (a) {
+        var b = f(a);
+        return this.filter(function () {
+            for (var a = 0, c = b.length; a < c; a++)if (f.contains(this, b[a]))return!0
+        })
+    }, not: function (a) {
+        return this.pushStack(T(this, a, !1), "not", a)
+    }, filter: function (a) {
+        return this.pushStack(T(this, a, !0), "filter", a)
+    }, is: function (a) {
+        return!!a && (typeof a == "string" ? Q.test(a) ? f(a, this.context).index(this[0]) >= 0 : f.filter(a, this).length > 0 : this.filter(a).length > 0)
+    }, closest: function (a, b) {
+        var c = [], d, e, g = this[0];
+        if (f.isArray(a)) {
+            var h = 1;
+            while (g && g.ownerDocument && g !== b) {
+                for (d = 0; d < a.length; d++)f(g).is(a[d]) && c.push({selector: a[d], elem: g, level: h});
+                g = g.parentNode, h++
+            }
+            return c
+        }
+        var i = Q.test(a) || typeof a != "string" ? f(a, b || this.context) : 0;
+        for (d = 0, e = this.length; d < e; d++) {
+            g = this[d];
+            while (g) {
+                if (i ? i.index(g) > -1 : f.find.matchesSelector(g, a)) {
+                    c.push(g);
+                    break
+                }
+                g = g.parentNode;
+                if (!g || !g.ownerDocument || g === b || g.nodeType === 11)break
+            }
+        }
+        c = c.length > 1 ? f.unique(c) : c;
+        return this.pushStack(c, "closest", a)
+    }, index: function (a) {
+        if (!a)return this[0] && this[0].parentNode ? this.prevAll().length : -1;
+        if (typeof a == "string")return f.inArray(this[0], f(a));
+        return f.inArray(a.jquery ? a[0] : a, this)
+    }, add: function (a, b) {
+        var c = typeof a == "string" ? f(a, b) : f.makeArray(a && a.nodeType ? [a] : a), d = f.merge(this.get(), c);
+        return this.pushStack(S(c[0]) || S(d[0]) ? d : f.unique(d))
+    }, andSelf: function () {
+        return this.add(this.prevObject)
+    }}), f.each({parent: function (a) {
+        var b = a.parentNode;
+        return b && b.nodeType !== 11 ? b : null
+    }, parents: function (a) {
+        return f.dir(a, "parentNode")
+    }, parentsUntil: function (a, b, c) {
+        return f.dir(a, "parentNode", c)
+    }, next: function (a) {
+        return f.nth(a, 2, "nextSibling")
+    }, prev: function (a) {
+        return f.nth(a, 2, "previousSibling")
+    }, nextAll: function (a) {
+        return f.dir(a, "nextSibling")
+    }, prevAll: function (a) {
+        return f.dir(a, "previousSibling")
+    }, nextUntil: function (a, b, c) {
+        return f.dir(a, "nextSibling", c)
+    }, prevUntil: function (a, b, c) {
+        return f.dir(a, "previousSibling", c)
+    }, siblings: function (a) {
+        return f.sibling(a.parentNode.firstChild, a)
+    }, children: function (a) {
+        return f.sibling(a.firstChild)
+    }, contents: function (a) {
+        return f.nodeName(a, "iframe") ? a.contentDocument || a.contentWindow.document : f.makeArray(a.childNodes)
+    }}, function (a, b) {
+        f.fn[a] = function (c, d) {
+            var e = f.map(this, b, c);
+            L.test(a) || (d = c), d && typeof d == "string" && (e = f.filter(d, e)), e = this.length > 1 && !R[a] ? f.unique(e) : e, (this.length > 1 || N.test(d)) && M.test(a) && (e = e.reverse());
+            return this.pushStack(e, a, P.call(arguments).join(","))
+        }
+    }), f.extend({filter: function (a, b, c) {
+        c && (a = ":not(" + a + ")");
+        return b.length === 1 ? f.find.matchesSelector(b[0], a) ? [b[0]] : [] : f.find.matches(a, b)
+    }, dir: function (a, c, d) {
+        var e = [], g = a[c];
+        while (g && g.nodeType !== 9 && (d === b || g.nodeType !== 1 || !f(g).is(d)))g.nodeType === 1 && e.push(g), g = g[c];
+        return e
+    }, nth: function (a, b, c, d) {
+        b = b || 1;
+        var e = 0;
+        for (; a; a = a[c])if (a.nodeType === 1 && ++e === b)break;
+        return a
+    }, sibling: function (a, b) {
+        var c = [];
+        for (; a; a = a.nextSibling)a.nodeType === 1 && a !== b && c.push(a);
+        return c
+    }});
+    var V = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", W = / jQuery\d+="(?:\d+|null)"/g, X = /^\s+/, Y = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, Z = /<([\w:]+)/, $ = /<tbody/i, _ = /<|&#?\w+;/, ba = /<(?:script|style)/i, bb = /<(?:script|object|embed|option|style)/i, bc = new RegExp("<(?:" + V + ")", "i"), bd = /checked\s*(?:[^=]|=\s*.checked.)/i, be = /\/(java|ecma)script/i, bf = /^\s*<!(?:\[CDATA\[|\-\-)/, bg = {option: [1, "<select multiple='multiple'>", "</select>"], legend: [1, "<fieldset>", "</fieldset>"], thead: [1, "<table>", "</table>"], tr: [2, "<table><tbody>", "</tbody></table>"], td: [3, "<table><tbody><tr>", "</tr></tbody></table>"], col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"], area: [1, "<map>", "</map>"], _default: [0, "", ""]}, bh = U(c);
+    bg.optgroup = bg.option, bg.tbody = bg.tfoot = bg.colgroup = bg.caption = bg.thead, bg.th = bg.td, f.support.htmlSerialize || (bg._default = [1, "div<div>", "</div>"]), f.fn.extend({text: function (a) {
+        if (f.isFunction(a))return this.each(function (b) {
+            var c = f(this);
+            c.text(a.call(this, b, c.text()))
+        });
+        if (typeof a != "object" && a !== b)return this.empty().append((this[0] && this[0].ownerDocument || c).createTextNode(a));
+        return f.text(this)
+    }, wrapAll: function (a) {
+        if (f.isFunction(a))return this.each(function (b) {
+            f(this).wrapAll(a.call(this, b))
+        });
+        if (this[0]) {
+            var b = f(a, this[0].ownerDocument).eq(0).clone(!0);
+            this[0].parentNode && b.insertBefore(this[0]), b.map(function () {
+                var a = this;
+                while (a.firstChild && a.firstChild.nodeType === 1)a = a.firstChild;
+                return a
+            }).append(this)
+        }
+        return this
+    }, wrapInner: function (a) {
+        if (f.isFunction(a))return this.each(function (b) {
+            f(this).wrapInner(a.call(this, b))
+        });
+        return this.each(function () {
+            var b = f(this), c = b.contents();
+            c.length ? c.wrapAll(a) : b.append(a)
+        })
+    }, wrap: function (a) {
+        var b = f.isFunction(a);
+        return this.each(function (c) {
+            f(this).wrapAll(b ? a.call(this, c) : a)
+        })
+    }, unwrap: function () {
+        return this.parent().each(function () {
+            f.nodeName(this, "body") || f(this).replaceWith(this.childNodes)
+        }).end()
+    }, append: function () {
+        return this.domManip(arguments, !0, function (a) {
+            this.nodeType === 1 && this.appendChild(a)
+        })
+    }, prepend: function () {
+        return this.domManip(arguments, !0, function (a) {
+            this.nodeType === 1 && this.insertBefore(a, this.firstChild)
+        })
+    }, before: function () {
+        if (this[0] && this[0].parentNode)return this.domManip(arguments, !1, function (a) {
+            this.parentNode.insertBefore(a, this)
+        });
+        if (arguments.length) {
+            var a = f.clean(arguments);
+            a.push.apply(a, this.toArray());
+            return this.pushStack(a, "before", arguments)
+        }
+    }, after: function () {
+        if (this[0] && this[0].parentNode)return this.domManip(arguments, !1, function (a) {
+            this.parentNode.insertBefore(a, this.nextSibling)
+        });
+        if (arguments.length) {
+            var a = this.pushStack(this, "after", arguments);
+            a.push.apply(a, f.clean(arguments));
+            return a
+        }
+    }, remove: function (a, b) {
+        for (var c = 0, d; (d = this[c]) != null; c++)if (!a || f.filter(a, [d]).length)!b && d.nodeType === 1 && (f.cleanData(d.getElementsByTagName("*")), f.cleanData([d])), d.parentNode && d.parentNode.removeChild(d);
+        return this
+    }, empty: function () {
+        for (var a = 0, b; (b = this[a]) != null; a++) {
+            b.nodeType === 1 && f.cleanData(b.getElementsByTagName("*"));
+            while (b.firstChild)b.removeChild(b.firstChild)
+        }
+        return this
+    }, clone: function (a, b) {
+        a = a == null ? !1 : a, b = b == null ? a : b;
+        return this.map(function () {
+            return f.clone(this, a, b)
+        })
+    }, html: function (a) {
+        if (a === b)return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(W, "") : null;
+        if (typeof a == "string" && !ba.test(a) && (f.support.leadingWhitespace || !X.test(a)) && !bg[(Z.exec(a) || ["", ""])[1].toLowerCase()]) {
+            a = a.replace(Y, "<$1></$2>");
+            try {
+                for (var c = 0, d = this.length; c < d; c++)this[c].nodeType === 1 && (f.cleanData(this[c].getElementsByTagName("*")), this[c].innerHTML = a)
+            } catch (e) {
+                this.empty().append(a)
+            }
+        } else f.isFunction(a) ? this.each(function (b) {
+            var c = f(this);
+            c.html(a.call(this, b, c.html()))
+        }) : this.empty().append(a);
+        return this
+    }, replaceWith: function (a) {
+        if (this[0] && this[0].parentNode) {
+            if (f.isFunction(a))return this.each(function (b) {
+                var c = f(this), d = c.html();
+                c.replaceWith(a.call(this, b, d))
+            });
+            typeof a != "string" && (a = f(a).detach());
+            return this.each(function () {
+                var b = this.nextSibling, c = this.parentNode;
+                f(this).remove(), b ? f(b).before(a) : f(c).append(a)
+            })
+        }
+        return this.length ? this.pushStack(f(f.isFunction(a) ? a() : a), "replaceWith", a) : this
+    }, detach: function (a) {
+        return this.remove(a, !0)
+    }, domManip: function (a, c, d) {
+        var e, g, h, i, j = a[0], k = [];
+        if (!f.support.checkClone && arguments.length === 3 && typeof j == "string" && bd.test(j))return this.each(function () {
+            f(this).domManip(a, c, d, !0)
+        });
+        if (f.isFunction(j))return this.each(function (e) {
+            var g = f(this);
+            a[0] = j.call(this, e, c ? g.html() : b), g.domManip(a, c, d)
+        });
+        if (this[0]) {
+            i = j && j.parentNode, f.support.parentNode && i && i.nodeType === 11 && i.childNodes.length === this.length ? e = {fragment: i} : e = f.buildFragment(a, this, k), h = e.fragment, h.childNodes.length === 1 ? g = h = h.firstChild : g = h.firstChild;
+            if (g) {
+                c = c && f.nodeName(g, "tr");
+                for (var l = 0, m = this.length, n = m - 1; l < m; l++)d.call(c ? bi(this[l], g) : this[l], e.cacheable || m > 1 && l < n ? f.clone(h, !0, !0) : h)
+            }
+            k.length && f.each(k, bp)
+        }
+        return this
+    }}), f.buildFragment = function (a, b, d) {
+        var e, g, h, i, j = a[0];
+        b && b[0] && (i = b[0].ownerDocument || b[0]), i.createDocumentFragment || (i = c), a.length === 1 && typeof j == "string" && j.length < 512 && i === c && j.charAt(0) === "<" && !bb.test(j) && (f.support.checkClone || !bd.test(j)) && (f.support.html5Clone || !bc.test(j)) && (g = !0, h = f.fragments[j], h && h !== 1 && (e = h)), e || (e = i.createDocumentFragment(), f.clean(a, i, e, d)), g && (f.fragments[j] = h ? e : 1);
+        return{fragment: e, cacheable: g}
+    }, f.fragments = {}, f.each({appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith"}, function (a, b) {
+        f.fn[a] = function (c) {
+            var d = [], e = f(c), g = this.length === 1 && this[0].parentNode;
+            if (g && g.nodeType === 11 && g.childNodes.length === 1 && e.length === 1) {
+                e[b](this[0]);
+                return this
+            }
+            for (var h = 0, i = e.length; h < i; h++) {
+                var j = (h > 0 ? this.clone(!0) : this).get();
+                f(e[h])[b](j), d = d.concat(j)
+            }
+            return this.pushStack(d, a, e.selector)
+        }
+    }), f.extend({clone: function (a, b, c) {
+        var d, e, g, h = f.support.html5Clone || !bc.test("<" + a.nodeName) ? a.cloneNode(!0) : bo(a);
+        if ((!f.support.noCloneEvent || !f.support.noCloneChecked) && (a.nodeType === 1 || a.nodeType === 11) && !f.isXMLDoc(a)) {
+            bk(a, h), d = bl(a), e = bl(h);
+            for (g = 0; d[g]; ++g)e[g] && bk(d[g], e[g])
+        }
+        if (b) {
+            bj(a, h);
+            if (c) {
+                d = bl(a), e = bl(h);
+                for (g = 0; d[g]; ++g)bj(d[g], e[g])
+            }
+        }
+        d = e = null;
+        return h
+    }, clean: function (a, b, d, e) {
+        var g;
+        b = b || c, typeof b.createElement == "undefined" && (b = b.ownerDocument || b[0] && b[0].ownerDocument || c);
+        var h = [], i;
+        for (var j = 0, k; (k = a[j]) != null; j++) {
+            typeof k == "number" && (k += "");
+            if (!k)continue;
+            if (typeof k == "string")if (!_.test(k))k = b.createTextNode(k); else {
+                k = k.replace(Y, "<$1></$2>");
+                var l = (Z.exec(k) || ["", ""])[1].toLowerCase(), m = bg[l] || bg._default, n = m[0], o = b.createElement("div");
+                b === c ? bh.appendChild(o) : U(b).appendChild(o), o.innerHTML = m[1] + k + m[2];
+                while (n--)o = o.lastChild;
+                if (!f.support.tbody) {
+                    var p = $.test(k), q = l === "table" && !p ? o.firstChild && o.firstChild.childNodes : m[1] === "<table>" && !p ? o.childNodes : [];
+                    for (i = q.length - 1; i >= 0; --i)f.nodeName(q[i], "tbody") && !q[i].childNodes.length && q[i].parentNode.removeChild(q[i])
+                }
+                !f.support.leadingWhitespace && X.test(k) && o.insertBefore(b.createTextNode(X.exec(k)[0]), o.firstChild), k = o.childNodes
+            }
+            var r;
+            if (!f.support.appendChecked)if (k[0] && typeof (r = k.length) == "number")for (i = 0; i < r; i++)bn(k[i]); else bn(k);
+            k.nodeType ? h.push(k) : h = f.merge(h, k)
+        }
+        if (d) {
+            g = function (a) {
+                return!a.type || be.test(a.type)
+            };
+            for (j = 0; h[j]; j++)if (e && f.nodeName(h[j], "script") && (!h[j].type || h[j].type.toLowerCase() === "text/javascript"))e.push(h[j].parentNode ? h[j].parentNode.removeChild(h[j]) : h[j]); else {
+                if (h[j].nodeType === 1) {
+                    var s = f.grep(h[j].getElementsByTagName("script"), g);
+                    h.splice.apply(h, [j + 1, 0].concat(s))
+                }
+                d.appendChild(h[j])
+            }
+        }
+        return h
+    }, cleanData: function (a) {
+        var b, c, d = f.cache, e = f.event.special, g = f.support.deleteExpando;
+        for (var h = 0, i; (i = a[h]) != null; h++) {
+            if (i.nodeName && f.noData[i.nodeName.toLowerCase()])continue;
+            c = i[f.expando];
+            if (c) {
+                b = d[c];
+                if (b && b.events) {
+                    for (var j in b.events)e[j] ? f.event.remove(i, j) : f.removeEvent(i, j, b.handle);
+                    b.handle && (b.handle.elem = null)
+                }
+                g ? delete i[f.expando] : i.removeAttribute && i.removeAttribute(f.expando), delete d[c]
+            }
+        }
+    }});
+    var bq = /alpha\([^)]*\)/i, br = /opacity=([^)]*)/, bs = /([A-Z]|^ms)/g, bt = /^-?\d+(?:px)?$/i, bu = /^-?\d/, bv = /^([\-+])=([\-+.\de]+)/, bw = {position: "absolute", visibility: "hidden", display: "block"}, bx = ["Left", "Right"], by = ["Top", "Bottom"], bz, bA, bB;
+    f.fn.css = function (a, c) {
+        if (arguments.length === 2 && c === b)return this;
+        return f.access(this, a, c, !0, function (a, c, d) {
+            return d !== b ? f.style(a, c, d) : f.css(a, c)
+        })
+    }, f.extend({cssHooks: {opacity: {get: function (a, b) {
+        if (b) {
+            var c = bz(a, "opacity", "opacity");
+            return c === "" ? "1" : c
+        }
+        return a.style.opacity
+    }}}, cssNumber: {fillOpacity: !0, fontWeight: !0, lineHeight: !0, opacity: !0, orphans: !0, widows: !0, zIndex: !0, zoom: !0}, cssProps: {"float": f.support.cssFloat ? "cssFloat" : "styleFloat"}, style: function (a, c, d, e) {
+        if (!!a && a.nodeType !== 3 && a.nodeType !== 8 && !!a.style) {
+            var g, h, i = f.camelCase(c), j = a.style, k = f.cssHooks[i];
+            c = f.cssProps[i] || i;
+            if (d === b) {
+                if (k && "get"in k && (g = k.get(a, !1, e)) !== b)return g;
+                return j[c]
+            }
+            h = typeof d, h === "string" && (g = bv.exec(d)) && (d = +(g[1] + 1) * +g[2] + parseFloat(f.css(a, c)), h = "number");
+            if (d == null || h === "number" && isNaN(d))return;
+            h === "number" && !f.cssNumber[i] && (d += "px");
+            if (!k || !("set"in k) || (d = k.set(a, d)) !== b)try {
+                j[c] = d
+            } catch (l) {
+            }
+        }
+    }, css: function (a, c, d) {
+        var e, g;
+        c = f.camelCase(c), g = f.cssHooks[c], c = f.cssProps[c] || c, c === "cssFloat" && (c = "float");
+        if (g && "get"in g && (e = g.get(a, !0, d)) !== b)return e;
+        if (bz)return bz(a, c)
+    }, swap: function (a, b, c) {
+        var d = {};
+        for (var e in b)d[e] = a.style[e], a.style[e] = b[e];
+        c.call(a);
+        for (e in b)a.style[e] = d[e]
+    }}), f.curCSS = f.css, f.each(["height", "width"], function (a, b) {
+        f.cssHooks[b] = {get: function (a, c, d) {
+            var e;
+            if (c) {
+                if (a.offsetWidth !== 0)return bC(a, b, d);
+                f.swap(a, bw, function () {
+                    e = bC(a, b, d)
+                });
+                return e
+            }
+        }, set: function (a, b) {
+            if (!bt.test(b))return b;
+            b = parseFloat(b);
+            if (b >= 0)return b + "px"
+        }}
+    }), f.support.opacity || (f.cssHooks.opacity = {get: function (a, b) {
+        return br.test((b && a.currentStyle ? a.currentStyle.filter : a.style.filter) || "") ? parseFloat(RegExp.$1) / 100 + "" : b ? "1" : ""
+    }, set: function (a, b) {
+        var c = a.style, d = a.currentStyle, e = f.isNumeric(b) ? "alpha(opacity=" + b * 100 + ")" : "", g = d && d.filter || c.filter || "";
+        c.zoom = 1;
+        if (b >= 1 && f.trim(g.replace(bq, "")) === "") {
+            c.removeAttribute("filter");
+            if (d && !d.filter)return
+        }
+        c.filter = bq.test(g) ? g.replace(bq, e) : g + " " + e
+    }}), f(function () {
+        f.support.reliableMarginRight || (f.cssHooks.marginRight = {get: function (a, b) {
+            var c;
+            f.swap(a, {display: "inline-block"}, function () {
+                b ? c = bz(a, "margin-right", "marginRight") : c = a.style.marginRight
+            });
+            return c
+        }})
+    }), c.defaultView && c.defaultView.getComputedStyle && (bA = function (a, b) {
+        var c, d, e;
+        b = b.replace(bs, "-$1").toLowerCase(), (d = a.ownerDocument.defaultView) && (e = d.getComputedStyle(a, null)) && (c = e.getPropertyValue(b), c === "" && !f.contains(a.ownerDocument.documentElement, a) && (c = f.style(a, b)));
+        return c
+    }), c.documentElement.currentStyle && (bB = function (a, b) {
+        var c, d, e, f = a.currentStyle && a.currentStyle[b], g = a.style;
+        f === null && g && (e = g[b]) && (f = e), !bt.test(f) && bu.test(f) && (c = g.left, d = a.runtimeStyle && a.runtimeStyle.left, d && (a.runtimeStyle.left = a.currentStyle.left), g.left = b === "fontSize" ? "1em" : f || 0, f = g.pixelLeft + "px", g.left = c, d && (a.runtimeStyle.left = d));
+        return f === "" ? "auto" : f
+    }), bz = bA || bB, f.expr && f.expr.filters && (f.expr.filters.hidden = function (a) {
+        var b = a.offsetWidth, c = a.offsetHeight;
+        return b === 0 && c === 0 || !f.support.reliableHiddenOffsets && (a.style && a.style.display || f.css(a, "display")) === "none"
+    }, f.expr.filters.visible = function (a) {
+        return!f.expr.filters.hidden(a)
+    });
+    var bD = /%20/g, bE = /\[\]$/, bF = /\r?\n/g, bG = /#.*$/, bH = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, bI = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, bJ = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, bK = /^(?:GET|HEAD)$/, bL = /^\/\//, bM = /\?/, bN = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, bO = /^(?:select|textarea)/i, bP = /\s+/, bQ = /([?&])_=[^&]*/, bR = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, bS = f.fn.load, bT = {}, bU = {}, bV, bW, bX = ["*/"] + ["*"];
+    try {
+        bV = e.href
+    } catch (bY) {
+        bV = c.createElement("a"), bV.href = "", bV = bV.href
+    }
+    bW = bR.exec(bV.toLowerCase()) || [], f.fn.extend({load: function (a, c, d) {
+        if (typeof a != "string" && bS)return bS.apply(this, arguments);
+        if (!this.length)return this;
+        var e = a.indexOf(" ");
+        if (e >= 0) {
+            var g = a.slice(e, a.length);
+            a = a.slice(0, e)
+        }
+        var h = "GET";
+        c && (f.isFunction(c) ? (d = c, c = b) : typeof c == "object" && (c = f.param(c, f.ajaxSettings.traditional), h = "POST"));
+        var i = this;
+        f.ajax({url: a, type: h, dataType: "html", data: c, complete: function (a, b, c) {
+            c = a.responseText, a.isResolved() && (a.done(function (a) {
+                c = a
+            }), i.html(g ? f("<div>").append(c.replace(bN, "")).find(g) : c)), d && i.each(d, [c, b, a])
+        }});
+        return this
+    }, serialize: function () {
+        return f.param(this.serializeArray())
+    }, serializeArray: function () {
+        return this.map(function () {
+            return this.elements ? f.makeArray(this.elements) : this
+        }).filter(function () {
+            return this.name && !this.disabled && (this.checked || bO.test(this.nodeName) || bI.test(this.type))
+        }).map(function (a, b) {
+            var c = f(this).val();
+            return c == null ? null : f.isArray(c) ? f.map(c, function (a, c) {
+                return{name: b.name, value: a.replace(bF, "\r\n")}
+            }) : {name: b.name, value: c.replace(bF, "\r\n")}
+        }).get()
+    }}), f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function (a, b) {
+        f.fn[b] = function (a) {
+            return this.on(b, a)
+        }
+    }), f.each(["get", "post"], function (a, c) {
+        f[c] = function (a, d, e, g) {
+            f.isFunction(d) && (g = g || e, e = d, d = b);
+            return f.ajax({type: c, url: a, data: d, success: e, dataType: g})
+        }
+    }), f.extend({getScript: function (a, c) {
+        return f.get(a, b, c, "script")
+    }, getJSON: function (a, b, c) {
+        return f.get(a, b, c, "json")
+    }, ajaxSetup: function (a, b) {
+        b ? b_(a, f.ajaxSettings) : (b = a, a = f.ajaxSettings), b_(a, b);
+        return a
+    }, ajaxSettings: {url: bV, isLocal: bJ.test(bW[1]), global: !0, type: "GET", contentType: "application/x-www-form-urlencoded", processData: !0, async: !0, accepts: {xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": bX}, contents: {xml: /xml/, html: /html/, json: /json/}, responseFields: {xml: "responseXML", text: "responseText"}, converters: {"* text": a.String, "text html": !0, "text json": f.parseJSON, "text xml": f.parseXML}, flatOptions: {context: !0, url: !0}}, ajaxPrefilter: bZ(bT), ajaxTransport: bZ(bU), ajax: function (a, c) {
+        function w(a, c, l, m) {
+            if (s !== 2) {
+                s = 2, q && clearTimeout(q), p = b, n = m || "", v.readyState = a > 0 ? 4 : 0;
+                var o, r, u, w = c, x = l ? cb(d, v, l) : b, y, z;
+                if (a >= 200 && a < 300 || a === 304) {
+                    if (d.ifModified) {
+                        if (y = v.getResponseHeader("Last-Modified"))f.lastModified[k] = y;
+                        if (z = v.getResponseHeader("Etag"))f.etag[k] = z
+                    }
+                    if (a === 304)w = "notmodified", o = !0; else try {
+                        r = cc(d, x), w = "success", o = !0
+                    } catch (A) {
+                        w = "parsererror", u = A
+                    }
+                } else {
+                    u = w;
+                    if (!w || a)w = "error", a < 0 && (a = 0)
+                }
+                v.status = a, v.statusText = "" + (c || w), o ? h.resolveWith(e, [r, w, v]) : h.rejectWith(e, [v, w, u]), v.statusCode(j), j = b, t && g.trigger("ajax" + (o ? "Success" : "Error"), [v, d, o ? r : u]), i.fireWith(e, [v, w]), t && (g.trigger("ajaxComplete", [v, d]), --f.active || f.event.trigger("ajaxStop"))
+            }
+        }
+
+        typeof a == "object" && (c = a, a = b), c = c || {};
+        var d = f.ajaxSetup({}, c), e = d.context || d, g = e !== d && (e.nodeType || e instanceof f) ? f(e) : f.event, h = f.Deferred(), i = f.Callbacks("once memory"), j = d.statusCode || {}, k, l = {}, m = {}, n, o, p, q, r, s = 0, t, u, v = {readyState: 0, setRequestHeader: function (a, b) {
+            if (!s) {
+                var c = a.toLowerCase();
+                a = m[c] = m[c] || a, l[a] = b
+            }
+            return this
+        }, getAllResponseHeaders: function () {
+            return s === 2 ? n : null
+        }, getResponseHeader: function (a) {
+            var c;
+            if (s === 2) {
+                if (!o) {
+                    o = {};
+                    while (c = bH.exec(n))o[c[1].toLowerCase()] = c[2]
+                }
+                c = o[a.toLowerCase()]
+            }
+            return c === b ? null : c
+        }, overrideMimeType: function (a) {
+            s || (d.mimeType = a);
+            return this
+        }, abort: function (a) {
+            a = a || "abort", p && p.abort(a), w(0, a);
+            return this
+        }};
+        h.promise(v), v.success = v.done, v.error = v.fail, v.complete = i.add, v.statusCode = function (a) {
+            if (a) {
+                var b;
+                if (s < 2)for (b in a)j[b] = [j[b], a[b]]; else b = a[v.status], v.then(b, b)
+            }
+            return this
+        }, d.url = ((a || d.url) + "").replace(bG, "").replace(bL, bW[1] + "//"), d.dataTypes = f.trim(d.dataType || "*").toLowerCase().split(bP), d.crossDomain == null && (r = bR.exec(d.url.toLowerCase()), d.crossDomain = !(!r || r[1] == bW[1] && r[2] == bW[2] && (r[3] || (r[1] === "http:" ? 80 : 443)) == (bW[3] || (bW[1] === "http:" ? 80 : 443)))), d.data && d.processData && typeof d.data != "string" && (d.data = f.param(d.data, d.traditional)), b$(bT, d, c, v);
+        if (s === 2)return!1;
+        t = d.global, d.type = d.type.toUpperCase(), d.hasContent = !bK.test(d.type), t && f.active++ === 0 && f.event.trigger("ajaxStart");
+        if (!d.hasContent) {
+            d.data && (d.url += (bM.test(d.url) ? "&" : "?") + d.data, delete d.data), k = d.url;
+            if (d.cache === !1) {
+                var x = f.now(), y = d.url.replace(bQ, "$1_=" + x);
+                d.url = y + (y === d.url ? (bM.test(d.url) ? "&" : "?") + "_=" + x : "")
+            }
+        }
+        (d.data && d.hasContent && d.contentType !== !1 || c.contentType) && v.setRequestHeader("Content-Type", d.contentType), d.ifModified && (k = k || d.url, f.lastModified[k] && v.setRequestHeader("If-Modified-Since", f.lastModified[k]), f.etag[k] && v.setRequestHeader("If-None-Match", f.etag[k])), v.setRequestHeader("Accept", d.dataTypes[0] && d.accepts[d.dataTypes[0]] ? d.accepts[d.dataTypes[0]] + (d.dataTypes[0] !== "*" ? ", " + bX + "; q=0.01" : "") : d.accepts["*"]);
+        for (u in d.headers)v.setRequestHeader(u, d.headers[u]);
+        if (d.beforeSend && (d.beforeSend.call(e, v, d) === !1 || s === 2)) {
+            v.abort();
+            return!1
+        }
+        for (u in{success: 1, error: 1, complete: 1})v[u](d[u]);
+        p = b$(bU, d, c, v);
+        if (!p)w(-1, "No Transport"); else {
+            v.readyState = 1, t && g.trigger("ajaxSend", [v, d]), d.async && d.timeout > 0 && (q = setTimeout(function () {
+                v.abort("timeout")
+            }, d.timeout));
+            try {
+                s = 1, p.send(l, w)
+            } catch (z) {
+                if (s < 2)w(-1, z); else throw z
+            }
+        }
+        return v
+    }, param: function (a, c) {
+        var d = [], e = function (a, b) {
+            b = f.isFunction(b) ? b() : b, d[d.length] = encodeURIComponent(a) + "=" + encodeURIComponent(b)
+        };
+        c === b && (c = f.ajaxSettings.traditional);
+        if (f.isArray(a) || a.jquery && !f.isPlainObject(a))f.each(a, function () {
+            e(this.name, this.value)
+        }); else for (var g in a)ca(g, a[g], c, e);
+        return d.join("&").replace(bD, "+")
+    }}), f.extend({active: 0, lastModified: {}, etag: {}});
+    var cd = f.now(), ce = /(\=)\?(&|$)|\?\?/i;
+    f.ajaxSetup({jsonp: "callback", jsonpCallback: function () {
+        return f.expando + "_" + cd++
+    }}), f.ajaxPrefilter("json jsonp", function (b, c, d) {
+        var e = b.contentType === "application/x-www-form-urlencoded" && typeof b.data == "string";
+        if (b.dataTypes[0] === "jsonp" || b.jsonp !== !1 && (ce.test(b.url) || e && ce.test(b.data))) {
+            var g, h = b.jsonpCallback = f.isFunction(b.jsonpCallback) ? b.jsonpCallback() : b.jsonpCallback, i = a[h], j = b.url, k = b.data, l = "$1" + h + "$2";
+            b.jsonp !== !1 && (j = j.replace(ce, l), b.url === j && (e && (k = k.replace(ce, l)), b.data === k && (j += (/\?/.test(j) ? "&" : "?") + b.jsonp + "=" + h))), b.url = j, b.data = k, a[h] = function (a) {
+                g = [a]
+            }, d.always(function () {
+                a[h] = i, g && f.isFunction(i) && a[h](g[0])
+            }), b.converters["script json"] = function () {
+                g || f.error(h + " was not called");
+                return g[0]
+            }, b.dataTypes[0] = "json";
+            return"script"
+        }
+    }), f.ajaxSetup({accepts: {script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"}, contents: {script: /javascript|ecmascript/}, converters: {"text script": function (a) {
+        f.globalEval(a);
+        return a
+    }}}), f.ajaxPrefilter("script", function (a) {
+        a.cache === b && (a.cache = !1), a.crossDomain && (a.type = "GET", a.global = !1)
+    }), f.ajaxTransport("script", function (a) {
+        if (a.crossDomain) {
+            var d, e = c.head || c.getElementsByTagName("head")[0] || c.documentElement;
+            return{send: function (f, g) {
+                d = c.createElement("script"), d.async = "async", a.scriptCharset && (d.charset = a.scriptCharset), d.src = a.url, d.onload = d.onreadystatechange = function (a, c) {
+                    if (c || !d.readyState || /loaded|complete/.test(d.readyState))d.onload = d.onreadystatechange = null, e && d.parentNode && e.removeChild(d), d = b, c || g(200, "success")
+                }, e.insertBefore(d, e.firstChild)
+            }, abort: function () {
+                d && d.onload(0, 1)
+            }}
+        }
+    });
+    var cf = a.ActiveXObject ? function () {
+        for (var a in ch)ch[a](0, 1)
+    } : !1, cg = 0, ch;
+    f.ajaxSettings.xhr = a.ActiveXObject ? function () {
+        return!this.isLocal && ci() || cj()
+    } : ci, function (a) {
+        f.extend(f.support, {ajax: !!a, cors: !!a && "withCredentials"in a})
+    }(f.ajaxSettings.xhr()), f.support.ajax && f.ajaxTransport(function (c) {
+        if (!c.crossDomain || f.support.cors) {
+            var d;
+            return{send: function (e, g) {
+                var h = c.xhr(), i, j;
+                c.username ? h.open(c.type, c.url, c.async, c.username, c.password) : h.open(c.type, c.url, c.async);
+                if (c.xhrFields)for (j in c.xhrFields)h[j] = c.xhrFields[j];
+                c.mimeType && h.overrideMimeType && h.overrideMimeType(c.mimeType), !c.crossDomain && !e["X-Requested-With"] && (e["X-Requested-With"] = "XMLHttpRequest");
+                try {
+                    for (j in e)h.setRequestHeader(j, e[j])
+                } catch (k) {
+                }
+                h.send(c.hasContent && c.data || null), d = function (a, e) {
+                    var j, k, l, m, n;
+                    try {
+                        if (d && (e || h.readyState === 4)) {
+                            d = b, i && (h.onreadystatechange = f.noop, cf && delete ch[i]);
+                            if (e)h.readyState !== 4 && h.abort(); else {
+                                j = h.status, l = h.getAllResponseHeaders(), m = {}, n = h.responseXML, n && n.documentElement && (m.xml = n), m.text = h.responseText;
+                                try {
+                                    k = h.statusText
+                                } catch (o) {
+                                    k = ""
+                                }
+                                !j && c.isLocal && !c.crossDomain ? j = m.text ? 200 : 404 : j === 1223 && (j = 204)
+                            }
+                        }
+                    } catch (p) {
+                        e || g(-1, p)
+                    }
+                    m && g(j, k, m, l)
+                }, !c.async || h.readyState === 4 ? d() : (i = ++cg, cf && (ch || (ch = {}, f(a).unload(cf)), ch[i] = d), h.onreadystatechange = d)
+            }, abort: function () {
+                d && d(0, 1)
+            }}
+        }
+    });
+    var ck = {}, cl, cm, cn = /^(?:toggle|show|hide)$/, co = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, cp, cq = [
+        ["height", "marginTop", "marginBottom", "paddingTop", "paddingBottom"],
+        ["width", "marginLeft", "marginRight", "paddingLeft", "paddingRight"],
+        ["opacity"]
+    ], cr;
+    f.fn.extend({show: function (a, b, c) {
+        var d, e;
+        if (a || a === 0)return this.animate(cu("show", 3), a, b, c);
+        for (var g = 0, h = this.length; g < h; g++)d = this[g], d.style && (e = d.style.display, !f._data(d, "olddisplay") && e === "none" && (e = d.style.display = ""), e === "" && f.css(d, "display") === "none" && f._data(d, "olddisplay", cv(d.nodeName)));
+        for (g = 0; g < h; g++) {
+            d = this[g];
+            if (d.style) {
+                e = d.style.display;
+                if (e === "" || e === "none")d.style.display = f._data(d, "olddisplay") || ""
+            }
+        }
+        return this
+    }, hide: function (a, b, c) {
+        if (a || a === 0)return this.animate(cu("hide", 3), a, b, c);
+        var d, e, g = 0, h = this.length;
+        for (; g < h; g++)d = this[g], d.style && (e = f.css(d, "display"), e !== "none" && !f._data(d, "olddisplay") && f._data(d, "olddisplay", e));
+        for (g = 0; g < h; g++)this[g].style && (this[g].style.display = "none");
+        return this
+    }, _toggle: f.fn.toggle, toggle: function (a, b, c) {
+        var d = typeof a == "boolean";
+        f.isFunction(a) && f.isFunction(b) ? this._toggle.apply(this, arguments) : a == null || d ? this.each(function () {
+            var b = d ? a : f(this).is(":hidden");
+            f(this)[b ? "show" : "hide"]()
+        }) : this.animate(cu("toggle", 3), a, b, c);
+        return this
+    }, fadeTo: function (a, b, c, d) {
+        return this.filter(":hidden").css("opacity", 0).show().end().animate({opacity: b}, a, c, d)
+    }, animate: function (a, b, c, d) {
+        function g() {
+            e.queue === !1 && f._mark(this);
+            var b = f.extend({}, e), c = this.nodeType === 1, d = c && f(this).is(":hidden"), g, h, i, j, k, l, m, n, o;
+            b.animatedProperties = {};
+            for (i in a) {
+                g = f.camelCase(i), i !== g && (a[g] = a[i], delete a[i]), h = a[g], f.isArray(h) ? (b.animatedProperties[g] = h[1], h = a[g] = h[0]) : b.animatedProperties[g] = b.specialEasing && b.specialEasing[g] || b.easing || "swing";
+                if (h === "hide" && d || h === "show" && !d)return b.complete.call(this);
+                c && (g === "height" || g === "width") && (b.overflow = [this.style.overflow, this.style.overflowX, this.style.overflowY], f.css(this, "display") === "inline" && f.css(this, "float") === "none" && (!f.support.inlineBlockNeedsLayout || cv(this.nodeName) === "inline" ? this.style.display = "inline-block" : this.style.zoom = 1))
+            }
+            b.overflow != null && (this.style.overflow = "hidden");
+            for (i in a)j = new f.fx(this, b, i), h = a[i], cn.test(h) ? (o = f._data(this, "toggle" + i) || (h === "toggle" ? d ? "show" : "hide" : 0), o ? (f._data(this, "toggle" + i, o === "show" ? "hide" : "show"), j[o]()) : j[h]()) : (k = co.exec(h), l = j.cur(), k ? (m = parseFloat(k[2]), n = k[3] || (f.cssNumber[i] ? "" : "px"), n !== "px" && (f.style(this, i, (m || 1) + n), l = (m || 1) / j.cur() * l, f.style(this, i, l + n)), k[1] && (m = (k[1] === "-=" ? -1 : 1) * m + l), j.custom(l, m, n)) : j.custom(l, h, ""));
+            return!0
+        }
+
+        var e = f.speed(b, c, d);
+        if (f.isEmptyObject(a))return this.each(e.complete, [!1]);
+        a = f.extend({}, a);
+        return e.queue === !1 ? this.each(g) : this.queue(e.queue, g)
+    }, stop: function (a, c, d) {
+        typeof a != "string" && (d = c, c = a, a = b), c && a !== !1 && this.queue(a || "fx", []);
+        return this.each(function () {
+            function h(a, b, c) {
+                var e = b[c];
+                f.removeData(a, c, !0), e.stop(d)
+            }
+
+            var b, c = !1, e = f.timers, g = f._data(this);
+            d || f._unmark(!0, this);
+            if (a == null)for (b in g)g[b] && g[b].stop && b.indexOf(".run") === b.length - 4 && h(this, g, b); else g[b = a + ".run"] && g[b].stop && h(this, g, b);
+            for (b = e.length; b--;)e[b].elem === this && (a == null || e[b].queue === a) && (d ? e[b](!0) : e[b].saveState(), c = !0, e.splice(b, 1));
+            (!d || !c) && f.dequeue(this, a)
+        })
+    }}), f.each({slideDown: cu("show", 1), slideUp: cu("hide", 1), slideToggle: cu("toggle", 1), fadeIn: {opacity: "show"}, fadeOut: {opacity: "hide"}, fadeToggle: {opacity: "toggle"}}, function (a, b) {
+        f.fn[a] = function (a, c, d) {
+            return this.animate(b, a, c, d)
+        }
+    }), f.extend({speed: function (a, b, c) {
+        var d = a && typeof a == "object" ? f.extend({}, a) : {complete: c || !c && b || f.isFunction(a) && a, duration: a, easing: c && b || b && !f.isFunction(b) && b};
+        d.duration = f.fx.off ? 0 : typeof d.duration == "number" ? d.duration : d.duration in f.fx.speeds ? f.fx.speeds[d.duration] : f.fx.speeds._default;
+        if (d.queue == null || d.queue === !0)d.queue = "fx";
+        d.old = d.complete, d.complete = function (a) {
+            f.isFunction(d.old) && d.old.call(this), d.queue ? f.dequeue(this, d.queue) : a !== !1 && f._unmark(this)
+        };
+        return d
+    }, easing: {linear: function (a, b, c, d) {
+        return c + d * a
+    }, swing: function (a, b, c, d) {
+        return(-Math.cos(a * Math.PI) / 2 + .5) * d + c
+    }}, timers: [], fx: function (a, b, c) {
+        this.options = b, this.elem = a, this.prop = c, b.orig = b.orig || {}
+    }}), f.fx.prototype = {update: function () {
+        this.options.step && this.options.step.call(this.elem, this.now, this), (f.fx.step[this.prop] || f.fx.step._default)(this)
+    }, cur: function () {
+        if (this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null))return this.elem[this.prop];
+        var a, b = f.css(this.elem, this.prop);
+        return isNaN(a = parseFloat(b)) ? !b || b === "auto" ? 0 : b : a
+    }, custom: function (a, c, d) {
+        function h(a) {
+            return e.step(a)
+        }
+
+        var e = this, g = f.fx;
+        this.startTime = cr || cs(), this.end = c, this.now = this.start = a, this.pos = this.state = 0, this.unit = d || this.unit || (f.cssNumber[this.prop] ? "" : "px"), h.queue = this.options.queue, h.elem = this.elem, h.saveState = function () {
+            e.options.hide && f._data(e.elem, "fxshow" + e.prop) === b && f._data(e.elem, "fxshow" + e.prop, e.start)
+        }, h() && f.timers.push(h) && !cp && (cp = setInterval(g.tick, g.interval))
+    }, show: function () {
+        var a = f._data(this.elem, "fxshow" + this.prop);
+        this.options.orig[this.prop] = a || f.style(this.elem, this.prop), this.options.show = !0, a !== b ? this.custom(this.cur(), a) : this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()), f(this.elem).show()
+    }, hide: function () {
+        this.options.orig[this.prop] = f._data(this.elem, "fxshow" + this.prop) || f.style(this.elem, this.prop), this.options.hide = !0, this.custom(this.cur(), 0)
+    }, step: function (a) {
+        var b, c, d, e = cr || cs(), g = !0, h = this.elem, i = this.options;
+        if (a || e >= i.duration + this.startTime) {
+            this.now = this.end, this.pos = this.state = 1, this.update(), i.animatedProperties[this.prop] = !0;
+            for (b in i.animatedProperties)i.animatedProperties[b] !== !0 && (g = !1);
+            if (g) {
+                i.overflow != null && !f.support.shrinkWrapBlocks && f.each(["", "X", "Y"], function (a, b) {
+                    h.style["overflow" + b] = i.overflow[a]
+                }), i.hide && f(h).hide();
+                if (i.hide || i.show)for (b in i.animatedProperties)f.style(h, b, i.orig[b]), f.removeData(h, "fxshow" + b, !0), f.removeData(h, "toggle" + b, !0);
+                d = i.complete, d && (i.complete = !1, d.call(h))
+            }
+            return!1
+        }
+        i.duration == Infinity ? this.now = e : (c = e - this.startTime, this.state = c / i.duration, this.pos = f.easing[i.animatedProperties[this.prop]](this.state, c, 0, 1, i.duration), this.now = this.start + (this.end - this.start) * this.pos), this.update();
+        return!0
+    }}, f.extend(f.fx, {tick: function () {
+        var a, b = f.timers, c = 0;
+        for (; c < b.length; c++)a = b[c], !a() && b[c] === a && b.splice(c--, 1);
+        b.length || f.fx.stop()
+    }, interval: 13, stop: function () {
+        clearInterval(cp), cp = null
+    }, speeds: {slow: 600, fast: 200, _default: 400}, step: {opacity: function (a) {
+        f.style(a.elem, "opacity", a.now)
+    }, _default: function (a) {
+        a.elem.style && a.elem.style[a.prop] != null ? a.elem.style[a.prop] = a.now + a.unit : a.elem[a.prop] = a.now
+    }}}), f.each(["width", "height"], function (a, b) {
+        f.fx.step[b] = function (a) {
+            f.style(a.elem, b, Math.max(0, a.now) + a.unit)
+        }
+    }), f.expr && f.expr.filters && (f.expr.filters.animated = function (a) {
+        return f.grep(f.timers,function (b) {
+            return a === b.elem
+        }).length
+    });
+    var cw = /^t(?:able|d|h)$/i, cx = /^(?:body|html)$/i;
+    "getBoundingClientRect"in c.documentElement ? f.fn.offset = function (a) {
+        var b = this[0], c;
+        if (a)return this.each(function (b) {
+            f.offset.setOffset(this, a, b)
+        });
+        if (!b || !b.ownerDocument)return null;
+        if (b === b.ownerDocument.body)return f.offset.bodyOffset(b);
+        try {
+            c = b.getBoundingClientRect()
+        } catch (d) {
+        }
+        var e = b.ownerDocument, g = e.documentElement;
+        if (!c || !f.contains(g, b))return c ? {top: c.top, left: c.left} : {top: 0, left: 0};
+        var h = e.body, i = cy(e), j = g.clientTop || h.clientTop || 0, k = g.clientLeft || h.clientLeft || 0, l = i.pageYOffset || f.support.boxModel && g.scrollTop || h.scrollTop, m = i.pageXOffset || f.support.boxModel && g.scrollLeft || h.scrollLeft, n = c.top + l - j, o = c.left + m - k;
+        return{top: n, left: o}
+    } : f.fn.offset = function (a) {
+        var b = this[0];
+        if (a)return this.each(function (b) {
+            f.offset.setOffset(this, a, b)
+        });
+        if (!b || !b.ownerDocument)return null;
+        if (b === b.ownerDocument.body)return f.offset.bodyOffset(b);
+        var c, d = b.offsetParent, e = b, g = b.ownerDocument, h = g.documentElement, i = g.body, j = g.defaultView, k = j ? j.getComputedStyle(b, null) : b.currentStyle, l = b.offsetTop, m = b.offsetLeft;
+        while ((b = b.parentNode) && b !== i && b !== h) {
+            if (f.support.fixedPosition && k.position === "fixed")break;
+            c = j ? j.getComputedStyle(b, null) : b.currentStyle, l -= b.scrollTop, m -= b.scrollLeft, b === d && (l += b.offsetTop, m += b.offsetLeft, f.support.doesNotAddBorder && (!f.support.doesAddBorderForTableAndCells || !cw.test(b.nodeName)) && (l += parseFloat(c.borderTopWidth) || 0, m += parseFloat(c.borderLeftWidth) || 0), e = d, d = b.offsetParent), f.support.subtractsBorderForOverflowNotVisible && c.overflow !== "visible" && (l += parseFloat(c.borderTopWidth) || 0, m += parseFloat(c.borderLeftWidth) || 0), k = c
+        }
+        if (k.position === "relative" || k.position === "static")l += i.offsetTop, m += i.offsetLeft;
+        f.support.fixedPosition && k.position === "fixed" && (l += Math.max(h.scrollTop, i.scrollTop), m += Math.max(h.scrollLeft, i.scrollLeft));
+        return{top: l, left: m}
+    }, f.offset = {bodyOffset: function (a) {
+        var b = a.offsetTop, c = a.offsetLeft;
+        f.support.doesNotIncludeMarginInBodyOffset && (b += parseFloat(f.css(a, "marginTop")) || 0, c += parseFloat(f.css(a, "marginLeft")) || 0);
+        return{top: b, left: c}
+    }, setOffset: function (a, b, c) {
+        var d = f.css(a, "position");
+        d === "static" && (a.style.position = "relative");
+        var e = f(a), g = e.offset(), h = f.css(a, "top"), i = f.css(a, "left"), j = (d === "absolute" || d === "fixed") && f.inArray("auto", [h, i]) > -1, k = {}, l = {}, m, n;
+        j ? (l = e.position(), m = l.top, n = l.left) : (m = parseFloat(h) || 0, n = parseFloat(i) || 0), f.isFunction(b) && (b = b.call(a, c, g)), b.top != null && (k.top = b.top - g.top + m), b.left != null && (k.left = b.left - g.left + n), "using"in b ? b.using.call(a, k) : e.css(k)
+    }}, f.fn.extend({position: function () {
+        if (!this[0])return null;
+        var a = this[0], b = this.offsetParent(), c = this.offset(), d = cx.test(b[0].nodeName) ? {top: 0, left: 0} : b.offset();
+        c.top -= parseFloat(f.css(a, "marginTop")) || 0, c.left -= parseFloat(f.css(a, "marginLeft")) || 0, d.top += parseFloat(f.css(b[0], "borderTopWidth")) || 0, d.left += parseFloat(f.css(b[0], "borderLeftWidth")) || 0;
+        return{top: c.top - d.top, left: c.left - d.left}
+    }, offsetParent: function () {
+        return this.map(function () {
+            var a = this.offsetParent || c.body;
+            while (a && !cx.test(a.nodeName) && f.css(a, "position") === "static")a = a.offsetParent;
+            return a
+        })
+    }}), f.each(["Left", "Top"], function (a, c) {
+        var d = "scroll" + c;
+        f.fn[d] = function (c) {
+            var e, g;
+            if (c === b) {
+                e = this[0];
+                if (!e)return null;
+                g = cy(e);
+                return g ? "pageXOffset"in g ? g[a ? "pageYOffset" : "pageXOffset"] : f.support.boxModel && g.document.documentElement[d] || g.document.body[d] : e[d]
+            }
+            return this.each(function () {
+                g = cy(this), g ? g.scrollTo(a ? f(g).scrollLeft() : c, a ? c : f(g).scrollTop()) : this[d] = c
+            })
+        }
+    }), f.each(["Height", "Width"], function (a, c) {
+        var d = c.toLowerCase();
+        f.fn["inner" + c] = function () {
+            var a = this[0];
+            return a ? a.style ? parseFloat(f.css(a, d, "padding")) : this[d]() : null
+        }, f.fn["outer" + c] = function (a) {
+            var b = this[0];
+            return b ? b.style ? parseFloat(f.css(b, d, a ? "margin" : "border")) : this[d]() : null
+        }, f.fn[d] = function (a) {
+            var e = this[0];
+            if (!e)return a == null ? null : this;
+            if (f.isFunction(a))return this.each(function (b) {
+                var c = f(this);
+                c[d](a.call(this, b, c[d]()))
+            });
+            if (f.isWindow(e)) {
+                var g = e.document.documentElement["client" + c], h = e.document.body;
+                return e.document.compatMode === "CSS1Compat" && g || h && h["client" + c] || g
+            }
+            if (e.nodeType === 9)return Math.max(e.documentElement["client" + c], e.body["scroll" + c], e.documentElement["scroll" + c], e.body["offset" + c], e.documentElement["offset" + c]);
+            if (a === b) {
+                var i = f.css(e, d), j = parseFloat(i);
+                return f.isNumeric(j) ? j : i
+            }
+            return this.css(d, typeof a == "string" ? a : a + "px")
+        }
+    }), a.jQuery = a.$ = f, typeof define == "function" && define.amd && define.amd.jQuery && define("jquery", [], function () {
+        return f
+    })
+})(window);
\ No newline at end of file
diff --git a/media/js/lib/jquery-ui-1.8.21.custom.min.js b/media/js/lib/jquery-ui-1.8.21.custom.min.js
index 0bed21c..2ab7ebe 100644
--- a/media/js/lib/jquery-ui-1.8.21.custom.min.js
+++ b/media/js/lib/jquery-ui-1.8.21.custom.min.js
@@ -1,49 +1,2360 @@
 /*! jQuery UI - v1.8.21 - 2012-06-05
-* https://github.com/jquery/jquery-ui
-* Includes: jquery.ui.core.js
-* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
-(function(a,b){function c(b,c){var e=b.nodeName.toLowerCase();if("area"===e){var f=b.parentNode,g=f.name,h;return!b.href||!g||f.nodeName.toLowerCase()!=="map"?!1:(h=a("img[usemap=#"+g+"]")[0],!!h&&d(h))}return(/input|select|textarea|button|object/.test(e)?!b.disabled:"a"==e?b.href||c:c)&&d(b)}function d(b){return!a(b).parents().andSelf().filter(function(){return a.curCSS(this,"visibility")==="hidden"||a.expr.filters.hidden(this)}).length}a.ui=a.ui||{};if(a.ui.version)return;a.extend(a.ui,{version:"1.8.21",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}}),a.fn.extend({propAttr:a.fn.prop||a.fn.attr,_focus:a.fn.focus,focus:function(b,c){return typeof b=="number"?this.each(function(){var d=this;setTimeout(function(){a(d).focus(),c&&c.call(d)},b)}):this._focus.apply(this,arguments)},scrollParent:function(){var b;return a.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?b=this.parents().filter(function(){return/(relative|absolute|fixed)/.test(a.curCSS(this,"position",1))&&/(auto|scroll)/.test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0):b=this.parents().filter(function(){return/(auto|scroll)/.test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0),/fixed/.test(this.css("position"))||!b.length?a(document):b},zIndex:function(c){if(c!==b)return this.css("zIndex",c);if(this.length){var d=a(this[0]),e,f;while(d.length&&d[0]!==document){e=d.css("position");if(e==="absolute"||e==="relative"||e==="fixed"){f=parseInt(d.css("zIndex"),10);if(!isNaN(f)&&f!==0)return f}d=d.parent()}}return 0},disableSelection:function(){return this.bind((a.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),a.each(["Width","Height"],function(c,d){function h(b,c,d,f){return a.each(e,function(){c-=parseFloat(a.curCSS(b,"padding"+this,!0))||0,d&&(c-=parseFloat(a.curCSS(b,"border"+this+"Width",!0))||0),f&&(c-=parseFloat(a.curCSS(b,"margin"+this,!0))||0)}),c}var e=d==="Width"?["Left","Right"]:["Top","Bottom"],f=d.toLowerCase(),g={innerWidth:a.fn.innerWidth,innerHeight:a.fn.innerHeight,outerWidth:a.fn.outerWidth,outerHeight:a.fn.outerHeight};a.fn["inner"+d]=function(c){return c===b?g["inner"+d].call(this):this.each(function(){a(this).css(f,h(this,c)+"px")})},a.fn["outer"+d]=function(b,c){return typeof b!="number"?g["outer"+d].call(this,b):this.each(function(){a(this).css(f,h(this,b,!0,c)+"px")})}}),a.extend(a.expr[":"],{data:function(b,c,d){return!!a.data(b,d[3])},focusable:function(b){return c(b,!isNaN(a.attr(b,"tabindex")))},tabbable:function(b){var d=a.attr(b,"tabindex"),e=isNaN(d);return(e||d>=0)&&c(b,!e)}}),a(function(){var b=document.body,c=b.appendChild(c=document.createElement("div"));c.offsetHeight,a.extend(c.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0}),a.support.minHeight=c.offsetHeight===100,a.support.selectstart="onselectstart"in c,b.removeChild(c).style.display="none"}),a.extend(a.ui,{plugin:{add:function(b,c,d){var e=a.ui[b].prototype;for(var f in d)e.plugins[f]=e.plugins[f]||[],e.plugins[f].push([c,d[f]])},call:function(a,b,c){var d=a.plugins[b];if(!d||!a.element[0].parentNode)return;for(var e=0;e<d.length;e++)a.options[d[e][0]]&&d[e][1].apply(a.element,c)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(b,c){if(a(b).css("overflow")==="hidden")return!1;var d=c&&c==="left"?"scrollLeft":"scrollTop",e=!1;return b[d]>0?!0:(b[d]=1,e=b[d]>0,b[d]=0,e)},isOverAxis:function(a,b,c){return a>b&&a<b+c},isOver:function(b,c,d,e,f,g){return a.ui.isOverAxis(b,d,f)&&a.ui.isOverAxis(c,e,g)}})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
-* https://github.com/jquery/jquery-ui
-* Includes: jquery.ui.widget.js
-* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
-(function(a,b){if(a.cleanData){var c=a.cleanData;a.cleanData=function(b){for(var d=0,e;(e=b[d])!=null;d++)try{a(e).triggerHandler("remove")}catch(f){}c(b)}}else{var d=a.fn.remove;a.fn.remove=function(b,c){return this.each(function(){return c||(!b||a.filter(b,[this]).length)&&a("*",this).add([this]).each(function(){try{a(this).triggerHandler("remove")}catch(b){}}),d.call(a(this),b,c)})}}a.widget=function(b,c,d){var e=b.split(".")[0],f;b=b.split(".")[1],f=e+"-"+b,d||(d=c,c=a.Widget),a.expr[":"][f]=function(c){return!!a.data(c,b)},a[e]=a[e]||{},a[e][b]=function(a,b){arguments.length&&this._createWidget(a,b)};var g=new c;g.options=a.extend(!0,{},g.options),a[e][b].prototype=a.extend(!0,g,{namespace:e,widgetName:b,widgetEventPrefix:a[e][b].prototype.widgetEventPrefix||b,widgetBaseClass:f},d),a.widget.bridge(b,a[e][b])},a.widget.bridge=function(c,d){a.fn[c]=function(e){var f=typeof e=="string",g=Array.prototype.slice.call(arguments,1),h=this;return e=!f&&g.length?a.extend.apply(null,[!0,e].concat(g)):e,f&&e.charAt(0)==="_"?h:(f?this.each(function(){var d=a.data(this,c),f=d&&a.isFunction(d[e])?d[e].apply(d,g):d;if(f!==d&&f!==b)return h=f,!1}):this.each(function(){var b=a.data(this,c);b?b.option(e||{})._init():a.data(this,c,new d(e,this))}),h)}},a.Widget=function(a,b){arguments.length&&this._createWidget(a,b)},a.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:!1},_createWidget:function(b,c){a.data(c,this.widgetName,this),this.element=a(c),this.options=a.extend(!0,{},this.options,this._getCreateOptions(),b);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()}),this._create(),this._trigger("create"),this._init()},_getCreateOptions:function(){return a.metadata&&a.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName),this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled "+"ui-state-disabled")},widget:function(){return this.element},option:function(c,d){var e=c;if(arguments.length===0)return a.extend({},this.options);if(typeof c=="string"){if(d===b)return this.options[c];e={},e[c]=d}return this._setOptions(e),this},_setOptions:function(b){var c=this;return a.each(b,function(a,b){c._setOption(a,b)}),this},_setOption:function(a,b){return this.options[a]=b,a==="disabled"&&this.widget()[b?"addClass":"removeClass"](this.widgetBaseClass+"-disabled"+" "+"ui-state-disabled").attr("aria-disabled",b),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_trigger:function(b,c,d){var e,f,g=this.options[b];d=d||{},c=a.Event(c),c.type=(b===this.widgetEventPrefix?b:this.widgetEventPrefix+b).toLowerCase(),c.target=this.element[0],f=c.originalEvent;if(f)for(e in f)e in c||(c[e]=f[e]);return this.element.trigger(c,d),!(a.isFunction(g)&&g.call(this.element[0],c,d)===!1||c.isDefaultPrevented())}}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
-* https://github.com/jquery/jquery-ui
-* Includes: jquery.ui.mouse.js
-* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
-(function(a,b){var c=!1;a(document).mouseup(function(a){c=!1}),a.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var b=this;this.element.bind("mousedown."+this.widgetName,function(a){return b._mouseDown(a)}).bind("click."+this.widgetName,function(c){if(!0===a.data(c.target,b.widgetName+".preventClickEvent"))return a.removeData(c.target,b.widgetName+".preventClickEvent"),c.stopImmediatePropagation(),!1}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),a(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(b){if(c)return;this._mouseStarted&&this._mouseUp(b),this._mouseDownEvent=b;var d=this,e=b.which==1,f=typeof this.options.cancel=="string"&&b.target.nodeName?a(b.target).closest(this.options.cancel).length:!1;if(!e||f||!this._mouseCapture(b))return!0;this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){d.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(b)&&this._mouseDelayMet(b)){this._mouseStarted=this._mouseStart(b)!==!1;if(!this._mouseStarted)return b.preventDefault(),!0}return!0===a.data(b.target,this.widgetName+".preventClickEvent")&&a.removeData(b.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(a){return d._mouseMove(a)},this._mouseUpDelegate=function(a){return d._mouseUp(a)},a(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),b.preventDefault(),c=!0,!0},_mouseMove:function(b){return!a.browser.msie||document.documentMode>=9||!!b.button?this._mouseStarted?(this._mouseDrag(b),b.preventDefault()):(this._mouseDistanceMet(b)&&this._mouseDelayMet(b)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,b)!==!1,this._mouseStarted?this._mouseDrag(b):this._mouseUp(b)),!this._mouseStarted):this._mouseUp(b)},_mouseUp:function(b){return a(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,b.target==this._mouseDownEvent.target&&a.data(b.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(b)),!1},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(a){return this.mouseDelayMet},_mouseStart:function(a){},_mouseDrag:function(a){},_mouseStop:function(a){},_mouseCapture:function(a){return!0}})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
-* https://github.com/jquery/jquery-ui
-* Includes: jquery.ui.position.js
-* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
-(function(a,b){a.ui=a.ui||{};var c=/left|center|right/,d=/top|center|bottom/,e="center",f={},g=a.fn.position,h=a.fn.offset;a.fn.position=function(b){if(!b||!b.of)return g.apply(this,arguments);b=a.extend({},b);var h=a(b.of),i=h[0],j=(b.collision||"flip").split(" "),k=b.offset?b.offset.split(" "):[0,0],l,m,n;return i.nodeType===9?(l=h.width(),m=h.height(),n={top:0,left:0}):i.setTimeout?(l=h.width(),m=h.height(),n={top:h.scrollTop(),left:h.scrollLeft()}):i.preventDefault?(b.at="left top",l=m=0,n={top:b.of.pageY,left:b.of.pageX}):(l=h.outerWidth(),m=h.outerHeight(),n=h.offset()),a.each(["my","at"],function(){var a=(b[this]||"").split(" ");a.length===1&&(a=c.test(a[0])?a.concat([e]):d.test(a[0])?[e].concat(a):[e,e]),a[0]=c.test(a[0])?a[0]:e,a[1]=d.test(a[1])?a[1]:e,b[this]=a}),j.length===1&&(j[1]=j[0]),k[0]=parseInt(k[0],10)||0,k.length===1&&(k[1]=k[0]),k[1]=parseInt(k[1],10)||0,b.at[0]==="right"?n.left+=l:b.at[0]===e&&(n.left+=l/2),b.at[1]==="bottom"?n.top+=m:b.at[1]===e&&(n.top+=m/2),n.left+=k[0],n.top+=k[1],this.each(function(){var c=a(this),d=c.outerWidth(),g=c.outerHeight(),h=parseInt(a.curCSS(this,"marginLeft",!0))||0,i=parseInt(a.curCSS(this,"marginTop",!0))||0,o=d+h+(parseInt(a.curCSS(this,"marginRight",!0))||0),p=g+i+(parseInt(a.curCSS(this,"marginBottom",!0))||0),q=a.extend({},n),r;b.my[0]==="right"?q.left-=d:b.my[0]===e&&(q.left-=d/2),b.my[1]==="bottom"?q.top-=g:b.my[1]===e&&(q.top-=g/2),f.fractions||(q.left=Math.round(q.left),q.top=Math.round(q.top)),r={left:q.left-h,top:q.top-i},a.each(["left","top"],function(c,e){a.ui.position[j[c]]&&a.ui.position[j[c]][e](q,{targetWidth:l,targetHeight:m,elemWidth:d,elemHeight:g,collisionPosition:r,collisionWidth:o,collisionHeight:p,offset:k,my:b.my,at:b.at})}),a.fn.bgiframe&&c.bgiframe(),c.offset(a.extend(q,{using:b.using}))})},a.ui.position={fit:{left:function(b,c){var d=a(window),e=c.collisionPosition.left+c.collisionWidth-d.width()-d.scrollLeft();b.left=e>0?b.left-e:Math.max(b.left-c.collisionPosition.left,b.left)},top:function(b,c){var d=a(window),e=c.collisionPosition.top+c.collisionHeight-d.height()-d.scrollTop();b.top=e>0?b.top-e:Math.max(b.top-c.collisionPosition.top,b.top)}},flip:{left:function(b,c){if(c.at[0]===e)return;var d=a(window),f=c.collisionPosition.left+c.collisionWidth-d.width()-d.scrollLeft(),g=c.my[0]==="left"?-c.elemWidth:c.my[0]==="right"?c.elemWidth:0,h=c.at[0]==="left"?c.targetWidth:-c.targetWidth,i=-2*c.offset[0];b.left+=c.collisionPosition.left<0?g+h+i:f>0?g+h+i:0},top:function(b,c){if(c.at[1]===e)return;var d=a(window),f=c.collisionPosition.top+c.collisionHeight-d.height()-d.scrollTop(),g=c.my[1]==="top"?-c.elemHeight:c.my[1]==="bottom"?c.elemHeight:0,h=c.at[1]==="top"?c.targetHeight:-c.targetHeight,i=-2*c.offset[1];b.top+=c.collisionPosition.top<0?g+h+i:f>0?g+h+i:0}}},a.offset.setOffset||(a.offset.setOffset=function(b,c){/static/.test(a.curCSS(b,"position"))&&(b.style.position="relative");var d=a(b),e=d.offset(),f=parseInt(a.curCSS(b,"top",!0),10)||0,g=parseInt(a.curCSS(b,"left",!0),10)||0,h={top:c.top-e.top+f,left:c.left-e.left+g};"using"in c?c.using.call(b,h):d.css(h)},a.fn.offset=function(b){var c=this[0];return!c||!c.ownerDocument?null:b?a.isFunction(b)?this.each(function(c){a(this).offset(b.call(this,c,a(this).offset()))}):this.each(function(){a.offset.setOffset(this,b)}):h.call(this)}),function(){var b=document.getElementsByTagName("body")[0],c=document.createElement("div"),d,e,g,h,i;d=document.createElement(b?"div":"body"),g={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},b&&a.extend(g,{position:"absolute",left:"-1000px",top:"-1000px"});for(var j in g)d.style[j]=g[j];d.appendChild(c),e=b||document.documentElement,e.insertBefore(d,e.firstChild),c.style.cssText="position: absolute; left: 10.7432222px; top: 10.432325px; height: 30px; width: 201px;",h=a(c).offset(function(a,b){return b}).offset(),d.innerHTML="",e.removeChild(d),i=h.top+h.left+(b?2e3:0),f.fractions=i>21&&i<22}()})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
-* https://github.com/jquery/jquery-ui
-* Includes: jquery.ui.draggable.js
-* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
-(function(a,b){a.widget("ui.draggable",a.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1},_create:function(){this.options.helper=="original"&&!/^(?:r|a|f)/.test(this.element.css("position"))&&(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},destroy:function(){if(!this.element.data("draggable"))return;return this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy(),this},_mouseCapture:function(b){var c=this.options;return this.helper||c.disabled||a(b.target).is(".ui-resizable-handle")?!1:(this.handle=this._getHandle(b),this.handle?(c.iframeFix&&a(c.iframeFix===!0?"iframe":c.iframeFix).each(function(){a('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(a(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(b){var c=this.options;return this.helper=this._createHelper(b),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),a.ui.ddmanager&&(a.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(b),this.originalPageX=b.pageX,this.originalPageY=b.pageY,c.cursorAt&&this._adjustOffsetFromHelper(c.cursorAt),c.containment&&this._setContainment(),this._trigger("start",b)===!1?(this._clear(),!1):(this._cacheHelperProportions(),a.ui.ddmanager&&!c.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b),this._mouseDrag(b,!0),a.ui.ddmanager&&a.ui.ddmanager.dragStart(this,b),!0)},_mouseDrag:function(b,c){this.position=this._generatePosition(b),this.positionAbs=this._convertPositionTo("absolute");if(!c){var d=this._uiHash();if(this._trigger("drag",b,d)===!1)return this._mouseUp({}),!1;this.position=d.position}if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";return a.ui.ddmanager&&a.ui.ddmanager.drag(this,b),!1},_mouseStop:function(b){var c=!1;a.ui.ddmanager&&!this.options.dropBehaviour&&(c=a.ui.ddmanager.drop(this,b)),this.dropped&&(c=this.dropped,this.dropped=!1);var d=this.element[0],e=!1;while(d&&(d=d.parentNode))d==document&&(e=!0);if(!e&&this.options.helper==="original")return!1;if(this.options.revert=="invalid"&&!c||this.options.revert=="valid"&&c||this.options.revert===!0||a.isFunction(this.options.revert)&&this.options.revert.call(this.element,c)){var f=this;a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){f._trigger("stop",b)!==!1&&f._clear()})}else this._trigger("stop",b)!==!1&&this._clear();return!1},_mouseUp:function(b){return this.options.iframeFix===!0&&a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),a.ui.ddmanager&&a.ui.ddmanager.dragStop(this,b),a.ui.mouse.prototype._mouseUp.call(this,b)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(b){var c=!this.options.handle||!a(this.options.handle,this.element).length?!0:!1;return a(this.options.handle,this.element).find("*").andSelf().each(function(){this==b.target&&(c=!0)}),c},_createHelper:function(b){var c=this.options,d=a.isFunction(c.helper)?a(c.helper.apply(this.element[0],[b])):c.helper=="clone"?this.element.clone().removeAttr("id"):this.element;return d.parents("body").length||d.appendTo(c.appendTo=="parent"?this.element[0].parentNode:c.appendTo),d[0]!=this.element[0]&&!/(fixed|absolute)/.test(d.css("position"))&&d.css("position","absolute"),d},_adjustOffsetFromHelper:function(b){typeof b=="string"&&(b=b.split(" ")),a.isArray(b)&&(b={left:+b[0],top:+b[1]||0}),"left"in b&&(this.offset.click.left=b.left+this.margins.left),"right"in b&&(this.offset.click.left=this.helperProportions.width-b.right+this.margins.left),"top"in b&&(this.offset.click.top=b.top+this.margins.top),"bottom"in b&&(this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])&&(b.left+=this.scrollParent.scrollLeft(),b.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)b={top:0,left:0};return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.element.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var b=this.options;b.containment=="parent"&&(b.containment=this.helper[0].parentNode);if(b.containment=="document"||b.containment=="window")this.containment=[b.containment=="document"?0:a(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,b.containment=="document"?0:a(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(b.containment=="document"?0:a(window).scrollLeft())+a(b.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(b.containment=="document"?0:a(window).scrollTop())+(a(b.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(b.containment)&&b.containment.constructor!=Array){var c=a(b.containment),d=c[0];if(!d)return;var e=c.offset(),f=a(d).css("overflow")!="hidden";this.containment=[(parseInt(a(d).css("borderLeftWidth"),10)||0)+(parseInt(a(d).css("paddingLeft"),10)||0),(parseInt(a(d).css("borderTopWidth"),10)||0)+(parseInt(a(d).css("paddingTop"),10)||0),(f?Math.max(d.scrollWidth,d.offsetWidth):d.offsetWidth)-(parseInt(a(d).css("borderLeftWidth"),10)||0)-(parseInt(a(d).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(f?Math.max(d.scrollHeight,d.offsetHeight):d.offsetHeight)-(parseInt(a(d).css("borderTopWidth"),10)||0)-(parseInt(a(d).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=c}else b.containment.constructor==Array&&(this.containment=b.containment)},_convertPositionTo:function(b,c){c||(c=this.position);var d=b=="absolute"?1:-1,e=this.options,f=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=/(html|body)/i.test(f[0].tagName);return{top:c.top+this.offset.relative.top*d+this.offset.parent.top*d-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():g?0:f.scrollTop())*d),left:c.left+this.offset.relative.left*d+this.offset.parent.left*d-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:f.scrollLeft())*d)}},_generatePosition:function(b){var c=this.options,d=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(d[0].tagName),f=b.pageX,g=b.pageY;if(this.originalPosition){var h;if(this.containment){if(this.relative_container){var i=this.relative_container.offset();h=[this.containment[0]+i.left,this.containment[1]+i.top,this.containment[2]+i.left,this.containment[3]+i.top]}else h=this.containment;b.pageX-this.offset.click.left<h[0]&&(f=h[0]+this.offset.click.left),b.pageY-this.offset.click.top<h[1]&&(g=h[1]+this.offset.click.top),b.pageX-this.offset.click.left>h[2]&&(f=h[2]+this.offset.click.left),b.pageY-this.offset.click.top>h[3]&&(g=h[3]+this.offset.click.top)}if(c.grid){var j=c.grid[1]?this.originalPageY+Math.round((g-this.originalPageY)/c.grid[1])*c.grid[1]:this.originalPageY;g=h?j-this.offset.click.top<h[1]||j-this.offset.click.top>h[3]?j-this.offset.click.top<h[1]?j+c.grid[1]:j-c.grid[1]:j:j;var k=c.grid[0]?this.originalPageX+Math.round((f-this.originalPageX)/c.grid[0])*c.grid[0]:this.originalPageX;f=h?k-this.offset.click.left<h[0]||k-this.offset.click.left>h[2]?k-this.offset.click.left<h[0]?k+c.grid[0]:k-c.grid[0]:k:k}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:d.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:d.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(b,c,d){return d=d||this._uiHash(),a.ui.plugin.call(this,b,[c,d]),b=="drag"&&(this.positionAbs=this._convertPositionTo("absolute")),a.Widget.prototype._trigger.call(this,b,c,d)},plugins:{},_uiHash:function(a){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),a.extend(a.ui.draggable,{version:"1.8.21"}),a.ui.plugin.add("draggable","connectToSortable",{start:function(b,c){var d=a(this).data("draggable"),e=d.options,f=a.extend({},c,{item:d.element});d.sortables=[],a(e.connectToSortable).each(function(){var c=a.data(this,"sortable");c&&!c.options.disabled&&(d.sortables.push({instance:c,shouldRevert:c.options.revert}),c.refreshPositions(),c._trigger("activate",b,f))})},stop:function(b,c){var d=a(this).data("draggable"),e=a.extend({},c,{item:d.element});a.each(d.sortables,function(){this.instance.isOver?(this.instance.isOver=0,d.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=!0),this.instance._mouseStop(b),this.instance.options.helper=this.instance.options._helper,d.options.helper=="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",b,e))})},drag:function(b,c){var d=a(this).data("draggable"),e=this,f=function(b){var c=this.offset.click.top,d=this.offset.click.left,e=this.positionAbs.top,f=this.positionAbs.left,g=b.height,h=b.width,i=b.top,j=b.left;return a.ui.isOver(e+c,f+d,i,j,g,h)};a.each(d.sortables,function(f){this.instance.positionAbs=d.positionAbs,this.instance.helperProportions=d.helperProportions,this.instance.offset.click=d.offset.click,this.instance._intersectsWith(this.instance.containerCache)?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=a(e).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return c.helper[0]},b.target=this.instance.currentItem[0],this.instance._mouseCapture(b,!0),this.instance._mouseStart(b,!0,!0),this.instance.offset.click.top=d.offset.click.top,this.instance.offset.click.left=d.offset.click.left,this.instance.offset.parent.left-=d.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=d.offset.parent.top-this.instance.offset.parent.top,d._trigger("toSortable",b),d.dropped=this.instance.element,d.currentItem=d.element,this.instance.fromOutside=d),this.instance.currentItem&&this.instance._mouseDrag(b)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",b,this.instance._uiHash(this.instance)),this.instance._mouseStop(b,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),d._trigger("fromSortable",b),d.dropped=!1)})}}),a.ui.plugin.add("draggable","cursor",{start:function(b,c){var d=a("body"),e=a(this).data("draggable").options;d.css("cursor")&&(e._cursor=d.css("cursor")),d.css("cursor",e.cursor)},stop:function(b,c){var d=a(this).data("draggable").options;d._cursor&&a("body").css("cursor",d._cursor)}}),a.ui.plugin.add("draggable","opacity",{start:function(b,c){var d=a(c.helper),e=a(this).data("draggable").options;d.css("opacity")&&(e._opacity=d.css("opacity")),d.css("opacity",e.opacity)},stop:function(b,c){var d=a(this).data("draggable").options;d._opacity&&a(c.helper).css("opacity",d._opacity)}}),a.ui.plugin.add("draggable","scroll",{start:function(b,c){var d=a(this).data("draggable");d.scrollParent[0]!=document&&d.scrollParent[0].tagName!="HTML"&&(d.overflowOffset=d.scrollParent.offset())},drag:function(b,c){var d=a(this).data("draggable"),e=d.options,f=!1;if(d.scrollParent[0]!=document&&d.scrollParent[0].tagName!="HTML"){if(!e.axis||e.axis!="x")d.overflowOffset.top+d.scrollParent[0].offsetHeight-b.pageY<e.scrollSensitivity?d.scrollParent[0].scrollTop=f=d.scrollParent[0].scrollTop+e.scrollSpeed:b.pageY-d.overflowOffset.top<e.scrollSensitivity&&(d.scrollParent[0].scrollTop=f=d.scrollParent[0].scrollTop-e.scrollSpeed);if(!e.axis||e.axis!="y")d.overflowOffset.left+d.scrollParent[0].offsetWidth-b.pageX<e.scrollSensitivity?d.scrollParent[0].scrollLeft=f=d.scrollParent[0].scrollLeft+e.scrollSpeed:b.pageX-d.overflowOffset.left<e.scrollSensitivity&&(d.scrollParent[0].scrollLeft=f=d.scrollParent[0].scrollLeft-e.scrollSpeed)}else{if(!e.axis||e.axis!="x")b.pageY-a(document).scrollTop()<e.scrollSensitivity?f=a(document).scrollTop(a(document).scrollTop()-e.scrollSpeed):a(window).height()-(b.pageY-a(document).scrollTop())<e.scrollSensitivity&&(f=a(document).scrollTop(a(document).scrollTop()+e.scrollSpeed));if(!e.axis||e.axis!="y")b.pageX-a(document).scrollLeft()<e.scrollSensitivity?f=a(document).scrollLeft(a(document).scrollLeft()-e.scrollSpeed):a(window).width()-(b.pageX-a(document).scrollLeft())<e.scrollSensitivity&&(f=a(document).scrollLeft(a(document).scrollLeft()+e.scrollSpeed))}f!==!1&&a.ui.ddmanager&&!e.dropBehaviour&&a.ui.ddmanager.prepareOffsets(d,b)}}),a.ui.plugin.add("draggable","snap",{start:function(b,c){var d=a(this).data("draggable"),e=d.options;d.snapElements=[],a(e.snap.constructor!=String?e.snap.items||":data(draggable)":e.snap).each(function(){var b=a(this),c=b.offset();this!=d.element[0]&&d.snapElements.push({item:this,width:b.outerWidth(),height:b.outerHeight(),top:c.top,left:c.left})})},drag:function(b,c){var d=a(this).data("draggable"),e=d.options,f=e.snapTolerance,g=c.offset.left,h=g+d.helperProportions.width,i=c.offset.top,j=i+d.helperProportions.height;for(var k=d.snapElements.length-1;k>=0;k--){var l=d.snapElements[k].left,m=l+d.snapElements[k].width,n=d.snapElements[k].top,o=n+d.snapElements[k].height;if(!(l-f<g&&g<m+f&&n-f<i&&i<o+f||l-f<g&&g<m+f&&n-f<j&&j<o+f||l-f<h&&h<m+f&&n-f<i&&i<o+f||l-f<h&&h<m+f&&n-f<j&&j<o+f)){d.snapElements[k].snapping&&d.options.snap.release&&d.options.snap.release.call(d.element,b,a.extend(d._uiHash(),{snapItem:d.snapElements[k].item})),d.snapElements[k].snapping=!1;continue}if(e.snapMode!="inner"){var p=Math.abs(n-j)<=f,q=Math.abs(o-i)<=f,r=Math.abs(l-h)<=f,s=Math.abs(m-g)<=f;p&&(c.position.top=d._convertPositionTo("relative",{top:n-d.helperProportions.height,left:0}).top-d.margins.top),q&&(c.position.top=d._convertPositionTo("relative",{top:o,left:0}).top-d.margins.top),r&&(c.position.left=d._convertPositionTo("relative",{top:0,left:l-d.helperProportions.width}).left-d.margins.left),s&&(c.position.left=d._convertPositionTo("relative",{top:0,left:m}).left-d.margins.left)}var t=p||q||r||s;if(e.snapMode!="outer"){var p=Math.abs(n-i)<=f,q=Math.abs(o-j)<=f,r=Math.abs(l-g)<=f,s=Math.abs(m-h)<=f;p&&(c.position.top=d._convertPositionTo("relative",{top:n,left:0}).top-d.margins.top),q&&(c.position.top=d._convertPositionTo("relative",{top:o-d.helperProportions.height,left:0}).top-d.margins.top),r&&(c.position.left=d._convertPositionTo("relative",{top:0,left:l}).left-d.margins.left),s&&(c.position.left=d._convertPositionTo("relative",{top:0,left:m-d.helperProportions.width}).left-d.margins.left)}!d.snapElements[k].snapping&&(p||q||r||s||t)&&d.options.snap.snap&&d.options.snap.snap.call(d.element,b,a.extend(d._uiHash(),{snapItem:d.snapElements[k].item})),d.snapElements[k].snapping=p||q||r||s||t}}}),a.ui.plugin.add("draggable","stack",{start:function(b,c){var d=a(this).data("draggable").options,e=a.makeArray(a(d.stack)).sort(function(b,c){return(parseInt(a(b).css("zIndex"),10)||0)-(parseInt(a(c).css("zIndex"),10)||0)});if(!e.length)return;var f=parseInt(e[0].style.zIndex)||0;a(e).each(function(a){this.style.zIndex=f+a}),this[0].style.zIndex=f+e.length}}),a.ui.plugin.add("draggable","zIndex",{start:function(b,c){var d=a(c.helper),e=a(this).data("draggable").options;d.css("zIndex")&&(e._zIndex=d.css("zIndex")),d.css("zIndex",e.zIndex)},stop:function(b,c){var d=a(this).data("draggable").options;d._zIndex&&a(c.helper).css("zIndex",d._zIndex)}})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
-* https://github.com/jquery/jquery-ui
-* Includes: jquery.ui.resizable.js
-* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
-(function(a,b){a.widget("ui.resizable",a.ui.mouse,{widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1e3},_create:function(){var b=this,c=this.options;this.element.addClass("ui-resizable"),a.extend(this,{_aspectRatio:!!c.aspectRatio,aspectRatio:c.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:c.helper||c.ghost||c.animate?c.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)&&(this.element.wrap(a('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("resizable",this.element.data("resizable")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=c.handles||(a(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se");if(this.handles.constructor==String){this.handles=="all"&&(this.handles="n,e,s,w,se,sw,ne,nw");var d=this.handles.split(",");this.handles={};for(var e=0;e<d.length;e++){var f=a.trim(d[e]),g="ui-resizable-"+f,h=a('<div class="ui-resizable-handle '+g+'"></div>');h.css({zIndex:c.zIndex}),"se"==f&&h.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[f]=".ui-resizable-"+f,this.element.append(h)}}this._renderAxis=function(b){b=b||this.element;for(var c in this.handles){this.handles[c].constructor==String&&(this.handles[c]=a(this.handles[c],this.element).show());if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var d=a(this.handles[c],this.element),e=0;e=/sw|ne|nw|se|n|s/.test(c)?d.outerHeight():d.outerWidth();var f=["padding",/ne|nw|n/.test(c)?"Top":/se|sw|s/.test(c)?"Bottom":/^e$/.test(c)?"Right":"Left"].join("");b.css(f,e),this._proportionallyResize()}if(!a(this.handles[c]).length)continue}},this._renderAxis(this.element),this._handles=a(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){if(!b.resizing){if(this.className)var a=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);b.axis=a&&a[1]?a[1]:"se"}}),c.autoHide&&(this._handles.hide(),a(this.element).addClass("ui-resizable-autohide").hover(function(){if(c.disabled)return;a(this).removeClass("ui-resizable-autohide"),b._handles.show()},function(){if(c.disabled)return;b.resizing||(a(this).addClass("ui-resizable-autohide"),b._handles.hide())})),this._mouseInit()},destroy:function(){this._mouseDestroy();var b=function(b){a(b).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};if(this.elementIsWrapper){b(this.element);var c=this.element;c.after(this.originalElement.css({position:c.css("position"),width:c.outerWidth(),height:c.outerHeight(),top:c.css("top"),left:c.css("left")})).remove()}return this.originalElement.css("resize",this.originalResizeStyle),b(this.originalElement),this},_mouseCapture:function(b){var c=!1;for(var d in this.handles)a(this.handles[d])[0]==b.target&&(c=!0);return!this.options.disabled&&c},_mouseStart:function(b){var d=this.options,e=this.element.position(),f=this.element;this.resizing=!0,this.documentScroll={top:a(document).scrollTop(),left:a(document).scrollLeft()},(f.is(".ui-draggable")||/absolute/.test(f.css("position")))&&f.css({position:"absolute",top:e.top,left:e.left}),this._renderProxy();var g=c(this.helper.css("left")),h=c(this.helper.css("top"));d.containment&&(g+=a(d.containment).scrollLeft()||0,h+=a(d.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:g,top:h},this.size=this._helper?{width:f.outerWidth(),height:f.outerHeight()}:{width:f.width(),height:f.height()},this.originalSize=this._helper?{width:f.outerWidth(),height:f.outerHeight()}:{width:f.width(),height:f.height()},this.originalPosition={left:g,top:h},this.sizeDiff={width:f.outerWidth()-f.width(),height:f.outerHeight()-f.height()},this.originalMousePosition={left:b.pageX,top:b.pageY},this.aspectRatio=typeof d.aspectRatio=="number"?d.aspectRatio:this.originalSize.width/this.originalSize.height||1;var i=a(".ui-resizable-"+this.axis).css("cursor");return a("body").css("cursor",i=="auto"?this.axis+"-resize":i),f.addClass("ui-resizable-resizing"),this._propagate("start",b),!0},_mouseDrag:function(b){var c=this.helper,d=this.options,e={},f=this,g=this.originalMousePosition,h=this.axis,i=b.pageX-g.left||0,j=b.pageY-g.top||0,k=this._change[h];if(!k)return!1;var l=k.apply(this,[b,i,j]),m=a.browser.msie&&a.browser.version<7,n=this.sizeDiff;this._updateVirtualBoundaries(b.shiftKey);if(this._aspectRatio||b.shiftKey)l=this._updateRatio(l,b);return l=this._respectSize(l,b),this._propagate("resize",b),c.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"}),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),this._updateCache(l),this._trigger("resize",b,this.ui()),!1},_mouseStop:function(b){this.resizing=!1;var c=this.options,d=this;if(this._helper){var e=this._proportionallyResizeElements,f=e.length&&/textarea/i.test(e[0].nodeName),g=f&&a.ui.hasScroll(e[0],"left")?0:d.sizeDiff.height,h=f?0:d.sizeDiff.width,i={width:d.helper.width()-h,height:d.helper.height()-g},j=parseInt(d.element.css("left"),10)+(d.position.left-d.originalPosition.left)||null,k=parseInt(d.element.css("top"),10)+(d.position.top-d.originalPosition.top)||null;c.animate||this.element.css(a.extend(i,{top:k,left:j})),d.helper.height(d.size.height),d.helper.width(d.size.width),this._helper&&!c.animate&&this._proportionallyResize()}return a("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",b),this._helper&&this.helper.remove(),!1},_updateVirtualBoundaries:function(a){var b=this.options,c,e,f,g,h;h={minWidth:d(b.minWidth)?b.minWidth:0,maxWidth:d(b.maxWidth)?b.maxWidth:Infinity,minHeight:d(b.minHeight)?b.minHeight:0,maxHeight:d(b.maxHeight)?b.maxHeight:Infinity};if(this._aspectRatio||a)c=h.minHeight*this.aspectRatio,f=h.minWidth/this.aspectRatio,e=h.maxHeight*this.aspectRatio,g=h.maxWidth/this.aspectRatio,c>h.minWidth&&(h.minWidth=c),f>h.minHeight&&(h.minHeight=f),e<h.maxWidth&&(h.maxWidth=e),g<h.maxHeight&&(h.maxHeight=g);this._vBoundaries=h},_updateCache:function(a){var b=this.options;this.offset=this.helper.offset(),d(a.left)&&(this.position.left=a.left),d(a.top)&&(this.position.top=a.top),d(a.height)&&(this.size.height=a.height),d(a.width)&&(this.size.width=a.width)},_updateRatio:function(a,b){var c=this.options,e=this.position,f=this.size,g=this.axis;return d(a.height)?a.width=a.height*this.aspectRatio:d(a.width)&&(a.height=a.width/this.aspectRatio),g=="sw"&&(a.left=e.left+(f.width-a.width),a.top=null),g=="nw"&&(a.top=e.top+(f.height-a.height),a.left=e.left+(f.width-a.width)),a},_respectSize:function(a,b){var c=this.helper,e=this._vBoundaries,f=this._aspectRatio||b.shiftKey,g=this.axis,h=d(a.width)&&e.maxWidth&&e.maxWidth<a.width,i=d(a.height)&&e.maxHeight&&e.maxHeight<a.height,j=d(a.width)&&e.minWidth&&e.minWidth>a.width,k=d(a.height)&&e.minHeight&&e.minHeight>a.height;j&&(a.width=e.minWidth),k&&(a.height=e.minHeight),h&&(a.width=e.maxWidth),i&&(a.height=e.maxHeight);var l=this.originalPosition.left+this.originalSize.width,m=this.position.top+this.size.height,n=/sw|nw|w/.test(g),o=/nw|ne|n/.test(g);j&&n&&(a.left=l-e.minWidth),h&&n&&(a.left=l-e.maxWidth),k&&o&&(a.top=m-e.minHeight),i&&o&&(a.top=m-e.maxHeight);var p=!a.width&&!a.height;return p&&!a.left&&a.top?a.top=null:p&&!a.top&&a.left&&(a.left=null),a},_proportionallyResize:function(){var b=this.options;if(!this._proportionallyResizeElements.length)return;var c=this.helper||this.element;for(var d=0;d<this._proportionallyResizeElements.length;d++){var e=this._proportionallyResizeElements[d];if(!this.borderDif){var f=[e.css("borderTopWidth"),e.css("borderRightWidth"),e.css("borderBottomWidth"),e.css("borderLeftWidth")],g=[e.css("paddingTop"),e.css("paddingRight"),e.css("paddingBottom"),e.css("paddingLeft")];this.borderDif=a.map(f,function(a,b){var c=parseInt(a,10)||0,d=parseInt(g[b],10)||0;return c+d})}if(!a.browser.msie||!a(c).is(":hidden")&&!a(c).parents(":hidden").length)e.css({height:c.height()-this.borderDif[0]-this.borderDif[2]||0,width:c.width()-this.borderDif[1]-this.borderDif[3]||0});else continue}},_renderProxy:function(){var b=this.element,c=this.options;this.elementOffset=b.offset();if(this._helper){this.helper=this.helper||a('<div style="overflow:hidden;"></div>');var d=a.browser.msie&&a.browser.version<7,e=d?1:0,f=d?2:-1;this.helper.addClass(this._helper).css({width:this.element.outerWidth()+f,height:this.element.outerHeight()+f,position:"absolute",left:this.elementOffset.left-e+"px",top:this.elementOffset.top-e+"px",zIndex:++c.zIndex}),this.helper.appendTo("body").disableSelection()}else this.helper=this.element},_change:{e:function(a,b,c){return{width:this.originalSize.width+b}},w:function(a,b,c){var d=this.options,e=this.originalSize,f=this.originalPosition;return{left:f.left+b,width:e.width-b}},n:function(a,b,c){var d=this.options,e=this.originalSize,f=this.originalPosition;return{top:f.top+c,height:e.height-c}},s:function(a,b,c){return{height:this.originalSize.height+c}},se:function(b,c,d){return a.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[b,c,d]))},sw:function(b,c,d){return a.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[b,c,d]))},ne:function(b,c,d){return a.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[b,c,d]))},nw:function(b,c,d){return a.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[b,c,d]))}},_propagate:function(b,c){a.ui.plugin.call(this,b,[c,this.ui()]),b!="resize"&&this._trigger(b,c,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),a.extend(a.ui.resizable,{version:"1.8.21"}),a.ui.plugin.add("resizable","alsoResize",{start:function(b,c){var d=a(this).data("resizable"),e=d.options,f=function(b){a(b).each(function(){var b=a(this);b.data("resizable-alsoresize",{width:parseInt(b.width(),10),height:parseInt(b.height(),10),left:parseInt(b.css("left"),10),top:parseInt(b.css("top"),10)})})};typeof e.alsoResize=="object"&&!e.alsoResize.parentNode?e.alsoResize.length?(e.alsoResize=e.alsoResize[0],f(e.alsoResize)):a.each(e.alsoResize,function(a){f(a)}):f(e.alsoResize)},resize:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.originalSize,g=d.originalPosition,h={height:d.size.height-f.height||0,width:d.size.width-f.width||0,top:d.position.top-g.top||0,left:d.position.left-g.left||0},i=function(b,d){a(b).each(function(){var b=a(this),e=a(this).data("resizable-alsoresize"),f={},g=d&&d.length?d:b.parents(c.originalElement[0]).length?["width","height"]:["width","height","top","left"];a.each(g,function(a,b){var c=(e[b]||0)+(h[b]||0);c&&c>=0&&(f[b]=c||null)}),b.css(f)})};typeof e.alsoResize=="object"&&!e.alsoResize.nodeType?a.each(e.alsoResize,function(a,b){i(a,b)}):i(e.alsoResize)},stop:function(b,c){a(this).removeData("resizable-alsoresize")}}),a.ui.plugin.add("resizable","animate",{stop:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d._proportionallyResizeElements,g=f.length&&/textarea/i.test(f[0].nodeName),h=g&&a.ui.hasScroll(f[0],"left")?0:d.sizeDiff.height,i=g?0:d.sizeDiff.width,j={width:d.size.width-i,height:d.size.height-h},k=parseInt(d.element.css("left"),10)+(d.position.left-d.originalPosition.left)||null,l=parseInt(d.element.css("top"),10)+(d.position.top-d.originalPosition.top)||null;d.element.animate(a.extend(j,l&&k?{top:l,left:k}:{}),{duration:e.animateDuration,easing:e.animateEasing,step:function(){var c={width:parseInt(d.element.css("width"),10),height:parseInt(d.element.css("height"),10),top:parseInt(d.element.css("top"),10),left:parseInt(d.element.css("left"),10)};f&&f.length&&a(f[0]).css({width:c.width,height:c.height}),d._updateCache(c),d._propagate("resize",b)}})}}),a.ui.plugin.add("resizable","containment",{start:function(b,d){var e=a(this).data("resizable"),f=e.options,g=e.element,h=f.containment,i=h instanceof a?h.get(0):/parent/.test(h)?g.parent().get(0):h;if(!i)return;e.containerElement=a(i);if(/document/.test(h)||h==document)e.containerOffset={left:0,top:0},e.containerPosition={left:0,top:0},e.parentData={element:a(document),left:0,top:0,width:a(document).width(),height:a(document).height()||document.body.parentNode.scrollHeight};else{var j=a(i),k=[];a(["Top","Right","Left","Bottom"]).each(function(a,b){k[a]=c(j.css("padding"+b))}),e.containerOffset=j.offset(),e.containerPosition=j.position(),e.containerSize={height:j.innerHeight()-k[3],width:j.innerWidth()-k[1]};var l=e.containerOffset,m=e.containerSize.height,n=e.containerSize.width,o=a.ui.hasScroll(i,"left")?i.scrollWidth:n,p=a.ui.hasScroll(i)?i.scrollHeight:m;e.parentData={element:i,left:l.left,top:l.top,width:o,height:p}}},resize:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.containerSize,g=d.containerOffset,h=d.size,i=d.position,j=d._aspectRatio||b.shiftKey,k={top:0,left:0},l=d.containerElement;l[0]!=document&&/static/.test(l.css("position"))&&(k=g),i.left<(d._helper?g.left:0)&&(d.size.width=d.size.width+(d._helper?d.position.left-g.left:d.position.left-k.left),j&&(d.size.height=d.size.width/d.aspectRatio),d.position.left=e.helper?g.left:0),i.top<(d._helper?g.top:0)&&(d.size.height=d.size.height+(d._helper?d.position.top-g.top:d.position.top),j&&(d.size.width=d.size.height*d.aspectRatio),d.position.top=d._helper?g.top:0),d.offset.left=d.parentData.left+d.position.left,d.offset.top=d.parentData.top+d.position.top;var m=Math.abs((d._helper?d.offset.left-k.left:d.offset.left-k.left)+d.sizeDiff.width),n=Math.abs((d._helper?d.offset.top-k.top:d.offset.top-g.top)+d.sizeDiff.height),o=d.containerElement.get(0)==d.element.parent().get(0),p=/relative|absolute/.test(d.containerElement.css("position"));o&&p&&(m-=d.parentData.left),m+d.size.width>=d.parentData.width&&(d.size.width=d.parentData.width-m,j&&(d.size.height=d.size.width/d.aspectRatio)),n+d.size.height>=d.parentData.height&&(d.size.height=d.parentData.height-n,j&&(d.size.width=d.size.height*d.aspectRatio))},stop:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.position,g=d.containerOffset,h=d.containerPosition,i=d.containerElement,j=a(d.helper),k=j.offset(),l=j.outerWidth()-d.sizeDiff.width,m=j.outerHeight()-d.sizeDiff.height;d._helper&&!e.animate&&/relative/.test(i.css("position"))&&a(this).css({left:k.left-h.left-g.left,width:l,height:m}),d._helper&&!e.animate&&/static/.test(i.css("position"))&&a(this).css({left:k.left-h.left-g.left,width:l,height:m})}}),a.ui.plugin.add("resizable","ghost",{start:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.size;d.ghost=d.originalElement.clone(),d.ghost.css({opacity:.25,display:"block",position:"relative",height:f.height,width:f.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof e.ghost=="string"?e.ghost:""),d.ghost.appendTo(d.helper)},resize:function(b,c){var d=a(this).data("resizable"),e=d.options;d.ghost&&d.ghost.css({position:"relative",height:d.size.height,width:d.size.width})},stop:function(b,c){var d=a(this).data("resizable"),e=d.options;d.ghost&&d.helper&&d.helper.get(0).removeChild(d.ghost.get(0))}}),a.ui.plugin.add("resizable","grid",{resize:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.size,g=d.originalSize,h=d.originalPosition,i=d.axis,j=e._aspectRatio||b.shiftKey;e.grid=typeof e.grid=="number"?[e.grid,e.grid]:e.grid;var k=Math.round((f.width-g.width)/(e.grid[0]||1))*(e.grid[0]||1),l=Math.round((f.height-g.height)/(e.grid[1]||1))*(e.grid[1]||1);/^(se|s|e)$/.test(i)?(d.size.width=g.width+k,d.size.height=g.height+l):/^(ne)$/.test(i)?(d.size.width=g.width+k,d.size.height=g.height+l,d.position.top=h.top-l):/^(sw)$/.test(i)?(d.size.width=g.width+k,d.size.height=g.height+l,d.position.left=h.left-k):(d.size.width=g.width+k,d.size.height=g.height+l,d.position.top=h.top-l,d.position.left=h.left-k)}});var c=function(a){return parseInt(a,10)||0},d=function(a){return!isNaN(parseInt(a,10))}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
-* https://github.com/jquery/jquery-ui
-* Includes: jquery.ui.sortable.js
-* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
-(function(a,b){a.widget("ui.sortable",a.ui.mouse,{widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3},_create:function(){var a=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?a.axis==="x"||/left|right/.test(this.items[0].item.css("float"))||/inline|table-cell/.test(this.items[0].item.css("display")):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},destroy:function(){a.Widget.prototype.destroy.call(this),this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var b=this.items.length-1;b>=0;b--)this.items[b].item.removeData(this.widgetName+"-item");return this},_setOption:function(b,c){b==="disabled"?(this.options[b]=c,this.widget()[c?"addClass":"removeClass"]("ui-sortable-disabled")):a.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(b,c){var d=this;if(this.reverting)return!1;if(this.options.disabled||this.options.type=="static")return!1;this._refreshItems(b);var e=null,f=this,g=a(b.target).parents().each(function(){if(a.data(this,d.widgetName+"-item")==f)return e=a(this),!1});a.data(b.target,d.widgetName+"-item")==f&&(e=a(b.target));if(!e)return!1;if(this.options.handle&&!c){var h=!1;a(this.options.handle,e).find("*").andSelf().each(function(){this==b.target&&(h=!0)});if(!h)return!1}return this.currentItem=e,this._removeCurrentsFromItems(),!0},_mouseStart:function(b,c,d){var e=this.options,f=this;this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(b),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(b),this.originalPageX=b.pageX,this.originalPageY=b.pageY,e.cursorAt&&this._adjustOffsetFromHelper(e.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!=this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),e.containment&&this._setContainment(),e.cursor&&(a("body").css("cursor")&&(this._storedCursor=a("body").css("cursor")),a("body").css("cursor",e.cursor)),e.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",e.opacity)),e.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",e.zIndex)),this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",b,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions();if(!d)for(var g=this.containers.length-1;g>=0;g--)this.containers[g]._trigger("activate",b,f._uiHash(this));return a.ui.ddmanager&&(a.ui.ddmanager.current=this),a.ui.ddmanager&&!e.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(b),!0},_mouseDrag:function(b){this.position=this._generatePosition(b),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs);if(this.options.scroll){var c=this.options,d=!1;this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-b.pageY<c.scrollSensitivity?this.scrollParent[0].scrollTop=d=this.scrollParent[0].scrollTop+c.scrollSpeed:b.pageY-this.overflowOffset.top<c.scrollSensitivity&&(this.scrollParent[0].scrollTop=d=this.scrollParent[0].scrollTop-c.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-b.pageX<c.scrollSensitivity?this.scrollParent[0].scrollLeft=d=this.scrollParent[0].scrollLeft+c.scrollSpeed:b.pageX-this.overflowOffset.left<c.scrollSensitivity&&(this.scrollParent[0].scrollLeft=d=this.scrollParent[0].scrollLeft-c.scrollSpeed)):(b.pageY-a(document).scrollTop()<c.scrollSensitivity?d=a(document).scrollTop(a(document).scrollTop()-c.scrollSpeed):a(window).height()-(b.pageY-a(document).scrollTop())<c.scrollSensitivity&&(d=a(document).scrollTop(a(document).scrollTop()+c.scrollSpeed)),b.pageX-a(document).scrollLeft()<c.scrollSensitivity?d=a(document).scrollLeft(a(document).scrollLeft()-c.scrollSpeed):a(window).width()-(b.pageX-a(document).scrollLeft())<c.scrollSensitivity&&(d=a(document).scrollLeft(a(document).scrollLeft()+c.scrollSpeed))),d!==!1&&a.ui.ddmanager&&!c.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b)}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";for(var e=this.items.length-1;e>=0;e--){var f=this.items[e],g=f.item[0],h=this._intersectsWithPointer(f);if(!h)continue;if(g!=this.currentItem[0]&&this.placeholder[h==1?"next":"prev"]()[0]!=g&&!a.ui.contains(this.placeholder[0],g)&&(this.options.type=="semi-dynamic"?!a.ui.contains(this.element[0],g):!0)){this.direction=h==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(f))this._rearrange(b,f);else break;this._trigger("change",b,this._uiHash());break}}return this._contactContainers(b),a.ui.ddmanager&&a.ui.ddmanager.drag(this,b),this._trigger("sort",b,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(b,c){if(!b)return;a.ui.ddmanager&&!this.options.dropBehaviour&&a.ui.ddmanager.drop(this,b);if(this.options.revert){var d=this,e=d.placeholder.offset();d.reverting=!0,a(this.helper).animate({left:e.left-this.offset.parent.left-d.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:e.top-this.offset.parent.top-d.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){d._clear(b)})}else this._clear(b,c);return!1},cancel:function(){var b=this;if(this.dragging){this._mouseUp({target:null}),this.options.helper=="original"?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var c=this.containers.length-1;c>=0;c--)this.containers[c]._trigger("deactivate",null,b._uiHash(this)),this.containers[c].containerCache.over&&(this.containers[c]._trigger("out",null,b._uiHash(this)),this.containers[c].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.options.helper!="original"&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),a.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?a(this.domPosition.prev).after(this.currentItem):a(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(b){var c=this._getItemsAsjQuery(b&&b.connected),d=[];return b=b||{},a(c).each(function(){var c=(a(b.item||this).attr(b.attribute||"id")||"").match(b.expression||/(.+)[-=_](.+)/);c&&d.push((b.key||c[1]+"[]")+"="+(b.key&&b.expression?c[1]:c[2]))}),!d.length&&b.key&&d.push(b.key+"="),d.join("&")},toArray:function(b){var c=this._getItemsAsjQuery(b&&b.connected),d=[];return b=b||{},c.each(function(){d.push(a(b.item||this).attr(b.attribute||"id")||"")}),d},_intersectsWith:function(a){var b=this.positionAbs.left,c=b+this.helperProportions.width,d=this.positionAbs.top,e=d+this.helperProportions.height,f=a.left,g=f+a.width,h=a.top,i=h+a.height,j=this.offset.click.top,k=this.offset.click.left,l=d+j>h&&d+j<i&&b+k>f&&b+k<g;return this.options.tolerance=="pointer"||this.options.forcePointerForContainers||this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>a[this.floating?"width":"height"]?l:f<b+this.helperProportions.width/2&&c-this.helperProportions.width/2<g&&h<d+this.helperProportions.height/2&&e-this.helperProportions.height/2<i},_intersectsWithPointer:function(b){var c=this.options.axis==="x"||a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,b.top,b.height),d=this.options.axis==="y"||a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,b.left,b.width),e=c&&d,f=this._getDragVerticalDirection(),g=this._getDragHorizontalDirection();return e?this.floating?g&&g=="right"||f=="down"?2:1:f&&(f=="down"?2:1):!1},_intersectsWithSides:function(b){var c=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,b.top+b.height/2,b.height),d=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,b.left+b.width/2,b.width),e=this._getDragVerticalDirection(),f=this._getDragHorizontalDirection();return this.floating&&f?f=="right"&&d||f=="left"&&!d:e&&(e=="down"&&c||e=="up"&&!c)},_getDragVerticalDirection:function(){var a=this.positionAbs.top-this.lastPositionAbs.top;return a!=0&&(a>0?"down":"up")},_getDragHorizontalDirection:function(){var a=this.positionAbs.left-this.lastPositionAbs.left;return a!=0&&(a>0?"right":"left")},refresh:function(a){return this._refreshItems(a),this.refreshPositions(),this},_connectWith:function(){var a=this.options;return a.connectWith.constructor==String?[a.connectWith]:a.connectWith},_getItemsAsjQuery:function(b){var c=this,d=[],e=[],f=this._connectWith();if(f&&b)for(var g=f.length-1;g>=0;g--){var h=a(f[g]);for(var i=h.length-1;i>=0;i--){var j=a.data(h[i],this.widgetName);j&&j!=this&&!j.options.disabled&&e.push([a.isFunction(j.options.items)?j.options.items.call(j.element):a(j.options.items,j.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),j])}}e.push([a.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):a(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(var g=e.length-1;g>=0;g--)e[g][0].each(function(){d.push(this)});return a(d)},_removeCurrentsFromItems:function(){var a=this.currentItem.find(":data("+this.widgetName+"-item)");for(var b=0;b<this.items.length;b++)for(var c=0;c<a.length;c++)a[c]==this.items[b].item[0]&&this.items.splice(b,1)},_refreshItems:function(b){this.items=[],this.containers=[this];var c=this.items,d=this,e=[[a.isFunction(this.options.items)?this.options.items.call(this.element[0],b,{item:this.currentItem}):a(this.options.items,this.element),this]],f=this._connectWith();if(f&&this.ready)for(var g=f.length-1;g>=0;g--){var h=a(f[g]);for(var i=h.length-1;i>=0;i--){var j=a.data(h[i],this.widgetName);j&&j!=this&&!j.options.disabled&&(e.push([a.isFunction(j.options.items)?j.options.items.call(j.element[0],b,{item:this.currentItem}):a(j.options.items,j.element),j]),this.containers.push(j))}}for(var g=e.length-1;g>=0;g--){var k=e[g][1],l=e[g][0];for(var i=0,m=l.length;i<m;i++){var n=a(l[i]);n.data(this.widgetName+"-item",k),c.push({item:n,instance:k,width:0,height:0,left:0,top:0})}}},refreshPositions:function(b){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());for(var c=this.items.length-1;c>=0;c--){var d=this.items[c];if(d.instance!=this.currentContainer&&this.currentContainer&&d.item[0]!=this.currentItem[0])continue;var e=this.options.toleranceElement?a(this.options.toleranceElement,d.item):d.item;b||(d.width=e.outerWidth(),d.height=e.outerHeight());var f=e.offset();d.left=f.left,d.top=f.top}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(var c=this.containers.length-1;c>=0;c--){var f=this.containers[c].element.offset();this.containers[c].containerCache.left=f.left,this.containers[c].containerCache.top=f.top,this.containers[c].containerCache.width=this.containers[c].element.outerWidth(),this.containers[c].containerCache.height=this.containers[c].element.outerHeight()}return this},_createPlaceholder:function(b){var c=b||this,d=c.options;if(!d.placeholder||d.placeholder.constructor==String){var e=d.placeholder;d.placeholder={element:function(){var b=a(document.createElement(c.currentItem[0].nodeName)).addClass(e||c.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];return e||(b.style.visibility="hidden"),b},update:function(a,b){if(e&&!d.forcePlaceholderSize)return;b.height()||b.height(c.currentItem.innerHeight()-parseInt(c.currentItem.css("paddingTop")||0,10)-parseInt(c.currentItem.css("paddingBottom")||0,10)),b.width()||b.width(c.currentItem.innerWidth()-parseInt(c.currentItem.css("paddingLeft")||0,10)-parseInt(c.currentItem.css("paddingRight")||0,10))}}}c.placeholder=a(d.placeholder.element.call(c.element,c.currentItem)),c.currentItem.after(c.placeholder),d.placeholder.update(c,c.placeholder)},_contactContainers:function(b){var c=null,d=null;for(var e=this.containers.length-1;e>=0;e--){if(a.ui.contains(this.currentItem[0],this.containers[e].element[0]))continue;if(this._intersectsWith(this.containers[e].containerCache)){if(c&&a.ui.contains(this.containers[e].element[0],c.element[0]))continue;c=this.containers[e],d=e}else this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",b,this._uiHash(this)),this.containers[e].containerCache.over=0)}if(!c)return;if(this.containers.length===1)this.containers[d]._trigger("over",b,this._uiHash(this)),this.containers[d].containerCache.over=1;else if(this.currentContainer!=this.containers[d]){var f=1e4,g=null,h=this.positionAbs[this.containers[d].floating?"left":"top"];for(var i=this.items.length-1;i>=0;i--){if(!a.ui.contains(this.containers[d].element[0],this.items[i].item[0]))continue;var j=this.containers[d].floating?this.items[i].item.offset().left:this.items[i].item.offset().top;Math.abs(j-h)<f&&(f=Math.abs(j-h),g=this.items[i],this.direction=j-h>0?"down":"up")}if(!g&&!this.options.dropOnEmpty)return;this.currentContainer=this.containers[d],g?this._rearrange(b,g,null,!0):this._rearrange(b,null,this.containers[d].element,!0),this._trigger("change",b,this._uiHash()),this.containers[d]._trigger("change",b,this._uiHash(this)),this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[d]._trigger("over",b,this._uiHash(this)),this.containers[d].containerCache.over=1}},_createHelper:function(b){var c=this.options,d=a.isFunction(c.helper)?a(c.helper.apply(this.element[0],[b,this.currentItem])):c.helper=="clone"?this.currentItem.clone():this.currentItem;return d.parents("body").length||a(c.appendTo!="parent"?c.appendTo:this.currentItem[0].parentNode)[0].appendChild(d[0]),d[0]==this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(d[0].style.width==""||c.forceHelperSize)&&d.width(this.currentItem.width()),(d[0].style.height==""||c.forceHelperSize)&&d.height(this.currentItem.height()),d},_adjustOffsetFromHelper:function(b){typeof b=="string"&&(b=b.split(" ")),a.isArray(b)&&(b={left:+b[0],top:+b[1]||0}),"left"in b&&(this.offset.click.left=b.left+this.margins.left),"right"in b&&(this.offset.click.left=this.helperProportions.width-b.right+this.margins.left),"top"in b&&(this.offset.click.top=b.top+this.margins.top),"bottom"in b&&(this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])&&(b.left+=this.scrollParent.scrollLeft(),b.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)b={top:0,left:0};return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.currentItem.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var b=this.options;b.containment=="parent"&&(b.containment=this.helper[0].parentNode);if(b.containment=="document"||b.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(b.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(b.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(b.containment)){var c=a(b.containment)[0],d=a(b.containment).offset(),e=a(c).css("overflow")!="hidden";this.containment=[d.left+(parseInt(a(c).css("borderLeftWidth"),10)||0)+(parseInt(a(c).css("paddingLeft"),10)||0)-this.margins.left,d.top+(parseInt(a(c).css("borderTopWidth"),10)||0)+(parseInt(a(c).css("paddingTop"),10)||0)-this.margins.top,d.left+(e?Math.max(c.scrollWidth,c.offsetWidth):c.offsetWidth)-(parseInt(a(c).css("borderLeftWidth"),10)||0)-(parseInt(a(c).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,d.top+(e?Math.max(c.scrollHeight,c.offsetHeight):c.offsetHeight)-(parseInt(a(c).css("borderTopWidth"),10)||0)-(parseInt(a(c).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(b,c){c||(c=this.position);var d=b=="absolute"?1:-1,e=this.options,f=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=/(html|body)/i.test(f[0].tagName);return{top:c.top+this.offset.relative.top*d+this.offset.parent.top*d-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():g?0:f.scrollTop())*d),left:c.left+this.offset.relative.left*d+this.offset.parent.left*d-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:f.scrollLeft())*d)}},_generatePosition:function(b){var c=this.options,d=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(d[0].tagName);this.cssPosition=="relative"&&(this.scrollParent[0]==document||this.scrollParent[0]==this.offsetParent[0])&&(this.offset.relative=this._getRelativeOffset());var f=b.pageX,g=b.pageY;if(this.originalPosition){this.containment&&(b.pageX-this.offset.click.left<this.containment[0]&&(f=this.containment[0]+this.offset.click.left),b.pageY-this.offset.click.top<this.containment[1]&&(g=this.containment[1]+this.offset.click.top),b.pageX-this.offset.click.left>this.containment[2]&&(f=this.containment[2]+this.offset.click.left),b.pageY-this.offset.click.top>this.containment[3]&&(g=this.containment[3]+this.offset.click.top));if(c.grid){var h=this.originalPageY+Math.round((g-this.originalPageY)/c.grid[1])*c.grid[1];g=this.containment?h-this.offset.click.top<this.containment[1]||h-this.offset.click.top>this.containment[3]?h-this.offset.click.top<this.containment[1]?h+c.grid[1]:h-c.grid[1]:h:h;var i=this.originalPageX+Math.round((f-this.originalPageX)/c.grid[0])*c.grid[0];f=this.containment?i-this.offset.click.left<this.containment[0]||i-this.offset.click.left>this.containment[2]?i-this.offset.click.left<this.containment[0]?i+c.grid[0]:i-c.grid[0]:i:i}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:d.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:d.scrollLeft())}},_rearrange:function(a,b,c,d){c?c[0].appendChild(this.placeholder[0]):b.item[0].parentNode.insertBefore(this.placeholder[0],this.direction=="down"?b.item[0]:b.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var e=this,f=this.counter;window.setTimeout(function(){f==e.counter&&e.refreshPositions(!d)},0)},_clear:function(b,c){this.reverting=!1;var d=[],e=this;!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var f in this._storedCSS)if(this._storedCSS[f]=="auto"||this._storedCSS[f]=="static")this._storedCSS[f]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!c&&d.push(function(a){this._trigger("receive",a,this._uiHash(this.fromOutside))}),(this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!c&&d.push(function(a){this._trigger("update",a,this._uiHash())});if(!a.ui.contains(this.element[0],this.currentItem[0])){c||d.push(function(a){this._trigger("remove",a,this._uiHash())});for(var f=this.containers.length-1;f>=0;f--)a.ui.contains(this.containers[f].element[0],this.currentItem[0])&&!c&&(d.push(function(a){return function(b){a._trigger("receive",b,this._uiHash(this))}}.call(this,this.containers[f])),d.push(function(a){return function(b){a._trigger("update",b,this._uiHash(this))}}.call(this,this.containers[f])))}for(var f=this.containers.length-1;f>=0;f--)c||d.push(function(a){return function(b){a._trigger("deactivate",b,this._uiHash(this))}}.call(this,this.containers[f])),this.containers[f].containerCache.over&&(d.push(function(a){return function(b){a._trigger("out",b,this._uiHash(this))}}.call(this,this.containers[f])),this.containers[f].containerCache.over=0);this._storedCursor&&a("body").css("cursor",this._storedCursor),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex),this.dragging=!1;if(this.cancelHelperRemoval){if(!c){this._trigger("beforeStop",b,this._uiHash());for(var f=0;f<d.length;f++)d[f].call(this,b);this._trigger("stop",b,this._uiHash())}return!1}c||this._trigger("beforeStop",b,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!=this.currentItem[0]&&this.helper.remove(),this.helper=null;if(!c){for(var f=0;f<d.length;f++)d[f].call(this,b);this._trigger("stop",b,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){a.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(b){var c=b||this;return{helper:c.helper,placeholder:c.placeholder||a([]),position:c.position,originalPosition:c.originalPosition,offset:c.positionAbs,item:c.currentItem,sender:b?b.element:null}}}),a.extend(a.ui.sortable,{version:"1.8.21"})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
-* https://github.com/jquery/jquery-ui
-* Includes: jquery.ui.accordion.js
-* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
-(function(a,b){a.widget("ui.accordion",{options:{active:0,animated:"slide",autoHeight:!0,clearStyle:!1,collapsible:!1,event:"click",fillSpace:!1,header:"> li > :first-child,> :not(li):even",icons:{header:"ui-icon-triangle-1-e",headerSelected:"ui-icon-triangle-1-s"},navigation:!1,navigationFilter:function(){return this.href.toLowerCase()===location.href.toLowerCase()}},_create:function(){var b=this,c=b.options;b.running=0,b.element.addClass("ui-accordion ui-widget ui-helper-reset").children("li").addClass("ui-accordion-li-fix"),b.headers=b.element.find(c.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function(){if(c.disabled)return;a(this).addClass("ui-state-hover")}).bind("mouseleave.accordion",function(){if(c.disabled)return;a(this).removeClass("ui-state-hover")}).bind("focus.accordion",function(){if(c.disabled)return;a(this).addClass("ui-state-focus")}).bind("blur.accordion",function(){if(c.disabled)return;a(this).removeClass("ui-state-focus")}),b.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");if(c.navigation){var d=b.element.find("a").filter(c.navigationFilter).eq(0);if(d.length){var e=d.closest(".ui-accordion-header");e.length?b.active=e:b.active=d.closest(".ui-accordion-content").prev()}}b.active=b._findActive(b.active||c.active).addClass("ui-state-default ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top"),b.active.next().addClass("ui-accordion-content-active"),b._createIcons(),b.resize(),b.element.attr("role","tablist"),b.headers.attr("role","tab").bind("keydown.accordion",function(a){return b._keydown(a)}).next().attr("role","tabpanel"),b.headers.not(b.active||"").attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).next().hide(),b.active.length?b.active.attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}):b.headers.eq(0).attr("tabIndex",0),a.browser.safari||b.headers.find("a").attr("tabIndex",-1),c.event&&b.headers.bind(c.event.split(" ").join(".accordion ")+".accordion",function(a){b._clickHandler.call(b,a,this),a.preventDefault()})},_createIcons:function(){var b=this.options;b.icons&&(a("<span></span>").addClass("ui-icon "+b.icons.header).prependTo(this.headers),this.active.children(".ui-icon").toggleClass(b.icons.header).toggleClass(b.icons.headerSelected),this.element.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.children(".ui-icon").remove(),this.element.removeClass("ui-accordion-icons")},destroy:function(){var b=this.options;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-accordion-disabled ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-selected").removeAttr("tabIndex"),this.headers.find("a").removeAttr("tabIndex"),this._destroyIcons();var c=this.headers.next().css("display","").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-accordion-disabled ui-state-disabled");return(b.autoHeight||b.fillHeight)&&c.css("height",""),a.Widget.prototype.destroy.call(this)},_setOption:function(b,c){a.Widget.prototype._setOption.apply(this,arguments),b=="active"&&this.activate(c),b=="icons"&&(this._destroyIcons(),c&&this._createIcons()),b=="disabled"&&this.headers.add(this.headers.next())[c?"addClass":"removeClass"]("ui-accordion-disabled ui-state-disabled")},_keydown:function(b){if(this.options.disabled||b.altKey||b.ctrlKey)return;var c=a.ui.keyCode,d=this.headers.length,e=this.headers.index(b.target),f=!1;switch(b.keyCode){case c.RIGHT:case c.DOWN:f=this.headers[(e+1)%d];break;case c.LEFT:case c.UP:f=this.headers[(e-1+d)%d];break;case c.SPACE:case c.ENTER:this._clickHandler({target:b.target},b.target),b.preventDefault()}return f?(a(b.target).attr("tabIndex",-1),a(f).attr("tabIndex",0),f.focus(),!1):!0},resize:function(){var b=this.options,c;if(b.fillSpace){if(a.browser.msie){var d=this.element.parent().css("overflow");this.element.parent().css("overflow","hidden")}c=this.element.parent().height(),a.browser.msie&&this.element.parent().css("overflow",d),this.headers.each(function(){c-=a(this).outerHeight(!0)}),this.headers.next().each(function(){a(this).height(Math.max(0,c-a(this).innerHeight()+a(this).height()))}).css("overflow","auto")}else b.autoHeight&&(c=0,this.headers.next().each(function(){c=Math.max(c,a(this).height("").height())}).height(c));return this},activate:function(a){this.options.active=a;var b=this._findActive(a)[0];return this._clickHandler({target:b},b),this},_findActive:function(b){return b?typeof b=="number"?this.headers.filter(":eq("+b+")"):this.headers.not(this.headers.not(b)):b===!1?a([]):this.headers.filter(":eq(0)")},_clickHandler:function(b,c){var d=this.options;if(d.disabled)return;if(!b.target){if(!d.collapsible)return;this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header),this.active.next().addClass("ui-accordion-content-active");var e=this.active.next(),f={options:d,newHeader:a([]),oldHeader:d.active,newContent:a([]),oldContent:e},g=this.active=a([]);this._toggle(g,e,f);return}var h=a(b.currentTarget||c),i=h[0]===this.active[0];d.active=d.collapsible&&i?!1:this.headers.index(h);if(this.running||!d.collapsible&&i)return;var j=this.active,g=h.next(),e=this.active.next(),f={options:d,newHeader:i&&d.collapsible?a([]):h,oldHeader:this.active,newContent:i&&d.collapsible?a([]):g,oldContent:e},k=this.headers.index(this.active[0])>this.headers.index(h[0]);this.active=i?a([]):h,this._toggle(g,e,f,i,k),j.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header),i||(h.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").children(".ui-icon").removeClass(d.icons.header).addClass(d.icons.headerSelected),h.next().addClass("ui-accordion-content-active"));return},_toggle:function(b,c,d,e,f){var g=this,h=g.options;g.toShow=b,g.toHide=c,g.data=d;var i=function(){if(!g)return;return g._completed.apply(g,arguments)};g._trigger("changestart",null,g.data),g.running=c.size()===0?b.size():c.size();if(h.animated){var j={};h.collapsible&&e?j={toShow:a([]),toHide:c,complete:i,down:f,autoHeight:h.autoHeight||h.fillSpace}:j={toShow:b,toHide:c,complete:i,down:f,autoHeight:h.autoHeight||h.fillSpace},h.proxied||(h.proxied=h.animated),h.proxiedDuration||(h.proxiedDuration=h.duration),h.animated=a.isFunction(h.proxied)?h.proxied(j):h.proxied,h.duration=a.isFunction(h.proxiedDuration)?h.proxiedDuration(j):h.proxiedDuration;var k=a.ui.accordion.animations,l=h.duration,m=h.animated;m&&!k[m]&&!a.easing[m]&&(m="slide"),k[m]||(k[m]=function(a){this.slide(a,{easing:m,duration:l||700})}),k[m](j)}else h.collapsible&&e?b.toggle():(c.hide(),b.show()),i(!0);c.prev().attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).blur(),b.prev().attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}).focus()},_completed:function(a){this.running=a?0:--this.running;if(this.running)return;this.options.clearStyle&&this.toShow.add(this.toHide).css({height:"",overflow:""}),this.toHide.removeClass("ui-accordion-content-active"),this.toHide.length&&(this.toHide.parent()[0].className=this.toHide.parent()[0].className),this._trigger("change",null,this.data)}}),a.extend(a.ui.accordion,{version:"1.8.21",animations:{slide:function(b,c){b=a.extend({easing:"swing",duration:300},b,c);if(!b.toHide.size()){b.toShow.animate({height:"show",paddingTop:"show",paddingBottom:"show"},b);return}if(!b.toShow.size()){b.toHide.animate({height:"hide",paddingTop:"hide",paddingBottom:"hide"},b);return}var d=b.toShow.css("overflow"),e=0,f={},g={},h=["height","paddingTop","paddingBottom"],i,j=b.toShow;i=j[0].style.width,j.width(j.parent().width()-parseFloat(j.css("paddingLeft"))-parseFloat(j.css("paddingRight"))-(parseFloat(j.css("borderLeftWidth"))||0)-(parseFloat(j.css("borderRightWidth"))||0)),a.each(h,function(c,d){g[d]="hide";var e=(""+a.css(b.toShow[0],d)).match(/^([\d+-.]+)(.*)$/);f[d]={value:e[1],unit:e[2]||"px"}}),b.toShow.css({height:0,overflow:"hidden"}).show(),b.toHide.filter(":hidden").each(b.complete).end().filter(":visible").animate(g,{step:function(a,c){c.prop=="height"&&(e=c.end-c.start===0?0:(c.now-c.start)/(c.end-c.start)),b.toShow[0].style[c.prop]=e*f[c.prop].value+f[c.prop].unit},duration:b.duration,easing:b.easing,complete:function(){b.autoHeight||b.toShow.css("height",""),b.toShow.css({width:i,overflow:d}),b.complete()}})},bounceslide:function(a){this.slide(a,{easing:a.down?"easeOutBounce":"swing",duration:a.down?1e3:200})}}})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
-* https://github.com/jquery/jquery-ui
-* Includes: jquery.ui.button.js
-* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
-(function(a,b){var c,d,e,f,g="ui-button ui-widget ui-state-default ui-corner-all",h="ui-state-hover ui-state-active ",i="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",j=function(){var b=a(this).find(":ui-button");setTimeout(function(){b.button("refresh")},1)},k=function(b){var c=b.name,d=b.form,e=a([]);return c&&(d?e=a(d).find("[name='"+c+"']"):e=a("[name='"+c+"']",b.ownerDocument).filter(function(){return!this.form})),e};a.widget("ui.button",{options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset.button").bind("reset.button",j),typeof this.options.disabled!="boolean"?this.options.disabled=!!this.element.propAttr("disabled"):this.element.propAttr("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var b=this,h=this.options,i=this.type==="checkbox"||this.type==="radio",l="ui-state-hover"+(i?"":" ui-state-active"),m="ui-state-focus";h.label===null&&(h.label=this.buttonElement.html()),this.buttonElement.addClass(g).attr("role","button").bind("mouseenter.button",function(){if(h.disabled)return;a(this).addClass("ui-state-hover"),this===c&&a(this).addClass("ui-state-active")}).bind("mouseleave.button",function(){if(h.disabled)return;a(this).removeClass(l)}).bind("click.button",function(a){h.disabled&&(a.preventDefault(),a.stopImmediatePropagation())}),this.element.bind("focus.button",function(){b.buttonElement.addClass(m)}).bind("blur.button",function(){b.buttonElement.removeClass(m)}),i&&(this.element.bind("change.button",function(){if(f)return;b.refresh()}),this.buttonElement.bind("mousedown.button",function(a){if(h.disabled)return;f=!1,d=a.pageX,e=a.pageY}).bind("mouseup.button",function(a){if(h.disabled)return;if(d!==a.pageX||e!==a.pageY)f=!0})),this.type==="checkbox"?this.buttonElement.bind("click.button",function(){if(h.disabled||f)return!1;a(this).toggleClass("ui-state-active"),b.buttonElement.attr("aria-pressed",b.element[0].checked)}):this.type==="radio"?this.buttonElement.bind("click.button",function(){if(h.disabled||f)return!1;a(this).addClass("ui-state-active"),b.buttonElement.attr("aria-pressed","true");var c=b.element[0];k(c).not(c).map(function(){return a(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown.button",function(){if(h.disabled)return!1;a(this).addClass("ui-state-active"),c=this,a(document).one("mouseup",function(){c=null})}).bind("mouseup.button",function(){if(h.disabled)return!1;a(this).removeClass("ui-state-active")}).bind("keydown.button",function(b){if(h.disabled)return!1;(b.keyCode==a.ui.keyCode.SPACE||b.keyCode==a.ui.keyCode.ENTER)&&a(this).addClass("ui-state-active")}).bind("keyup.button",function(){a(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(b){b.keyCode===a.ui.keyCode.SPACE&&a(this).click()})),this._setOption("disabled",h.disabled),this._resetButton()},_determineButtonType:function(){this.element.is(":checkbox")?this.type="checkbox":this.element.is(":radio")?this.type="radio":this.element.is("input")?this.type="input":this.type="button";if(this.type==="checkbox"||this.type==="radio"){var a=this.element.parents().filter(":last"),b="label[for='"+this.element.attr("id")+"']";this.buttonElement=a.find(b),this.buttonElement.length||(a=a.length?a.siblings():this.element.siblings(),this.buttonElement=a.filter(b),this.buttonElement.length||(this.buttonElement=a.find(b))),this.element.addClass("ui-helper-hidden-accessible");var c=this.element.is(":checked");c&&this.buttonElement.addClass("ui-state-active"),this.buttonElement.attr("aria-pressed",c)}else this.buttonElement=this.element},widget:function(){return this.buttonElement},destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(g+" "+h+" "+i).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title"),a.Widget.prototype.destroy.call(this)},_setOption:function(b,c){a.Widget.prototype._setOption.apply(this,arguments);if(b==="disabled"){c?this.element.propAttr("disabled",!0):this.element.propAttr("disabled",!1);return}this._resetButton()},refresh:function(){var b=this.element.is(":disabled");b!==this.options.disabled&&this._setOption("disabled",b),this.type==="radio"?k(this.element[0]).each(function(){a(this).is(":checked")?a(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):a(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):this.type==="checkbox"&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if(this.type==="input"){this.options.label&&this.element.val(this.options.label);return}var b=this.buttonElement.removeClass(i),c=a("<span></span>",this.element[0].ownerDocument).addClass("ui-button-text").html(this.options.label).appendTo(b.empty()).text(),d=this.options.icons,e=d.primary&&d.secondary,f=[];d.primary||d.secondary?(this.options.text&&f.push("ui-button-text-icon"+(e?"s":d.primary?"-primary":"-secondary")),d.primary&&b.prepend("<span class='ui-button-icon-primary ui-icon "+d.primary+"'></span>"),d.secondary&&b.append("<span class='ui-button-icon-secondary ui-icon "+d.secondary+"'></span>"),this.options.text||(f.push(e?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||b.attr("title",c))):f.push("ui-button-text-only"),b.addClass(f.join(" "))}}),a.widget("ui.buttonset",{options:{items:":button, :submit, :reset, :checkbox, :radio, a, :data(button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(b,c){b==="disabled"&&this.buttons.button("option",b,c),a.Widget.prototype._setOption.apply(this,arguments)},refresh:function(){var b=this.element.css("direction")==="rtl";this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(b?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(b?"ui-corner-left":"ui-corner-right").end().end()},destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy"),a.Widget.prototype.destroy.call(this)}})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
-* https://github.com/jquery/jquery-ui
-* Includes: jquery.ui.dialog.js
-* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
-(function(a,b){var c="ui-dialog ui-widget ui-widget-content ui-corner-all ",d={buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},e={maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},f=a.attrFn||{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0,click:!0};a.widget("ui.dialog",{options:{autoOpen:!0,buttons:{},closeOnEscape:!0,closeText:"close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:!1,maxWidth:!1,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",collision:"fit",using:function(b){var c=a(this).css(b).offset().top;c<0&&a(this).css("top",b.top-c)}},resizable:!0,show:null,stack:!0,title:"",width:300,zIndex:1e3},_create:function(){this.originalTitle=this.element.attr("title"),typeof this.originalTitle!="string"&&(this.originalTitle=""),this.options.title=this.options.title||this.originalTitle;var b=this,d=b.options,e=d.title||"&#160;",f=a.ui.dialog.getTitleId(b.element),g=(b.uiDialog=a("<div></div>")).appendTo(document.body).hide().addClass(c+d.dialogClass).css({zIndex:d.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(c){d.closeOnEscape&&!c.isDefaultPrevented()&&c.keyCode&&c.keyCode===a.ui.keyCode.ESCAPE&&(b.close(c),c.preventDefault())}).attr({role:"dialog","aria-labelledby":f}).mousedown(function(a){b.moveToTop(!1,a)}),h=b.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(g),i=(b.uiDialogTitlebar=a("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(g),j=a('<a href="#"></a>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){j.addClass("ui-state-hover")},function(){j.removeClass("ui-state-hover")}).focus(function(){j.addClass("ui-state-focus")}).blur(function(){j.removeClass("ui-state-focus")}).click(function(a){return b.close(a),!1}).appendTo(i),k=(b.uiDialogTitlebarCloseText=a("<span></span>")).addClass("ui-icon ui-icon-closethick").text(d.closeText).appendTo(j),l=a("<span></span>").addClass("ui-dialog-title").attr("id",f).html(e).prependTo(i);a.isFunction(d.beforeclose)&&!a.isFunction(d.beforeClose)&&(d.beforeClose=d.beforeclose),i.find("*").add(i).disableSelection(),d.draggable&&a.fn.draggable&&b._makeDraggable(),d.resizable&&a.fn.resizable&&b._makeResizable(),b._createButtons(d.buttons),b._isOpen=!1,a.fn.bgiframe&&g.bgiframe()},_init:function(){this.options.autoOpen&&this.open()},destroy:function(){var a=this;return a.overlay&&a.overlay.destroy(),a.uiDialog.hide(),a.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body"),a.uiDialog.remove(),a.originalTitle&&a.element.attr("title",a.originalTitle),a},widget:function(){return this.uiDialog},close:function(b){var c=this,d,e;if(!1===c._trigger("beforeClose",b))return;return c.overlay&&c.overlay.destroy(),c.uiDialog.unbind("keypress.ui-dialog"),c._isOpen=!1,c.options.hide?c.uiDialog.hide(c.options.hide,function(){c._trigger("close",b)}):(c.uiDialog.hide(),c._trigger("close",b)),a.ui.dialog.overlay.resize(),c.options.modal&&(d=0,a(".ui-dialog").each(function(){this!==c.uiDialog[0]&&(e=a(this).css("z-index"),isNaN(e)||(d=Math.max(d,e)))}),a.ui.dialog.maxZ=d),c},isOpen:function(){return this._isOpen},moveToTop:function(b,c){var d=this,e=d.options,f;return e.modal&&!b||!e.stack&&!e.modal?d._trigger("focus",c):(e.zIndex>a.ui.dialog.maxZ&&(a.ui.dialog.maxZ=e.zIndex),d.overlay&&(a.ui.dialog.maxZ+=1,d.overlay.$el.css("z-index",a.ui.dialog.overlay.maxZ=a.ui.dialog.maxZ)),f={scrollTop:d.element.scrollTop(),scrollLeft:d.element.scrollLeft()},a.ui.dialog.maxZ+=1,d.uiDialog.css("z-index",a.ui.dialog.maxZ),d.element.attr(f),d._trigger("focus",c),d)},open:function(){if(this._isOpen)return;var b=this,c=b.options,d=b.uiDialog;return b.overlay=c.modal?new a.ui.dialog.overlay(b):null,b._size(),b._position(c.position),d.show(c.show),b.moveToTop(!0),c.modal&&d.bind("keydown.ui-dialog",function(b){if(b.keyCode!==a.ui.keyCode.TAB)return;var c=a(":tabbable",this),d=c.filter(":first"),e=c.filter(":last");if(b.target===e[0]&&!b.shiftKey)return d.focus(1),!1;if(b.target===d[0]&&b.shiftKey)return e.focus(1),!1}),a(b.element.find(":tabbable").get().concat(d.find(".ui-dialog-buttonpane :tabbable").get().concat(d.get()))).eq(0).focus(),b._isOpen=!0,b._trigger("open"),b},_createButtons:function(b){var c=this,d=!1,e=a("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),g=a("<div></div>").addClass("ui-dialog-buttonset").appendTo(e);c.uiDialog.find(".ui-dialog-buttonpane").remove(),typeof b=="object"&&b!==null&&a.each(b,function(){return!(d=!0)}),d&&(a.each(b,function(b,d){d=a.isFunction(d)?{click:d,text:b}:d;var e=a('<button type="button"></button>').click(function(){d.click.apply(c.element[0],arguments)}).appendTo(g);a.each(d,function(a,b){if(a==="click")return;a in f?e[a](b):e.attr(a,b)}),a.fn.button&&e.button()}),e.appendTo(c.uiDialog))},_makeDraggable:function(){function f(a){return{position:a.position,offset:a.offset}}var b=this,c=b.options,d=a(document),e;b.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(d,g){e=c.height==="auto"?"auto":a(this).height(),a(this).height(a(this).height()).addClass("ui-dialog-dragging"),b._trigger("dragStart",d,f(g))},drag:function(a,c){b._trigger("drag",a,f(c))},stop:function(g,h){c.position=[h.position.left-d.scrollLeft(),h.position.top-d.scrollTop()],a(this).removeClass("ui-dialog-dragging").height(e),b._trigger("dragStop",g,f(h)),a.ui.dialog.overlay.resize()}})},_makeResizable:function(c){function h(a){return{originalPosition:a.originalPosition,originalSize:a.originalSize,position:a.position,size:a.size}}c=c===b?this.options.resizable:c;var d=this,e=d.options,f=d.uiDialog.css("position"),g=typeof c=="string"?c:"n,e,s,w,se,sw,ne,nw";d.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:d.element,maxWidth:e.maxWidth,maxHeight:e.maxHeight,minWidth:e.minWidth,minHeight:d._minHeight(),handles:g,start:function(b,c){a(this).addClass("ui-dialog-resizing"),d._trigger("resizeStart",b,h(c))},resize:function(a,b){d._trigger("resize",a,h(b))},stop:function(b,c){a(this).removeClass("ui-dialog-resizing"),e.height=a(this).height(),e.width=a(this).width(),d._trigger("resizeStop",b,h(c)),a.ui.dialog.overlay.resize()}}).css("position",f).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var a=this.options;return a.height==="auto"?a.minHeight:Math.min(a.minHeight,a.height)},_position:function(b){var c=[],d=[0,0],e;if(b){if(typeof b=="string"||typeof b=="object"&&"0"in b)c=b.split?b.split(" "):[b[0],b[1]],c.length===1&&(c[1]=c[0]),a.each(["left","top"],function(a,b){+c[a]===c[a]&&(d[a]=c[a],c[a]=b)}),b={my:c.join(" "),at:c.join(" "),offset:d.join(" ")};b=a.extend({},a.ui.dialog.prototype.options.position,b)}else b=a.ui.dialog.prototype.options.position;e=this.uiDialog.is(":visible"),e||this.uiDialog.show(),this.uiDialog.css({top:0,left:0}).position(a.extend({of:window},b)),e||this.uiDialog.hide()},_setOptions:function(b){var c=this,f={},g=!1;a.each(b,function(a,b){c._setOption(a,b),a in d&&(g=!0),a in e&&(f[a]=b)}),g&&this._size(),this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option",f)},_setOption:function(b,d){var e=this,f=e.uiDialog;switch(b){case"beforeclose":b="beforeClose";break;case"buttons":e._createButtons(d);break;case"closeText":e.uiDialogTitlebarCloseText.text(""+d);break;case"dialogClass":f.removeClass(e.options.dialogClass).addClass(c+d);break;case"disabled":d?f.addClass("ui-dialog-disabled"):f.removeClass("ui-dialog-disabled");break;case"draggable":var g=f.is(":data(draggable)");g&&!d&&f.draggable("destroy"),!g&&d&&e._makeDraggable();break;case"position":e._position(d);break;case"resizable":var h=f.is(":data(resizable)");h&&!d&&f.resizable("destroy"),h&&typeof d=="string"&&f.resizable("option","handles",d),!h&&d!==!1&&e._makeResizable(d);break;case"title":a(".ui-dialog-title",e.uiDialogTitlebar).html(""+(d||"&#160;"))}a.Widget.prototype._setOption.apply(e,arguments)},_size:function(){var b=this.options,c,d,e=this.uiDialog.is(":visible");this.element.show().css({width:"auto",minHeight:0,height:0}),b.minWidth>b.width&&(b.width=b.minWidth),c=this.uiDialog.css({height:"auto",width:b.width}).height(),d=Math.max(0,b.minHeight-c);if(b.height==="auto")if(a.support.minHeight)this.element.css({minHeight:d,height:"auto"});else{this.uiDialog.show();var f=this.element.css("height","auto").height();e||this.uiDialog.hide(),this.element.height(Math.max(f,d))}else this.element.height(Math.max(b.height-c,0));this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())}}),a.extend(a.ui.dialog,{version:"1.8.21",uuid:0,maxZ:0,getTitleId:function(a){var b=a.attr("id");return b||(this.uuid+=1,b=this.uuid),"ui-dialog-title-"+b},overlay:function(b){this.$el=a.ui.dialog.overlay.create(b)}}),a.extend(a.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:a.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(a){return a+".dialog-overlay"}).join(" "),create:function(b){this.instances.length===0&&(setTimeout(function(){a.ui.dialog.overlay.instances.length&&a(document).bind(a.ui.dialog.overlay.events,function(b){if(a(b.target).zIndex()<a.ui.dialog.overlay.maxZ)return!1})},1),a(document).bind("keydown.dialog-overlay",function(c){b.options.closeOnEscape&&!c.isDefaultPrevented()&&c.keyCode&&c.keyCode===a.ui.keyCode.ESCAPE&&(b.close(c),c.preventDefault())}),a(window).bind("resize.dialog-overlay",a.ui.dialog.overlay.resize));var c=(this.oldInstances.pop()||a("<div></div>").addClass("ui-widget-overlay")).appendTo(document.body).css({width:this.width(),height:this.height()});return a.fn.bgiframe&&c.bgiframe(),this.instances.push(c),c},destroy:function(b){var c=a.inArray(b,this.instances);c!=-1&&this.oldInstances.push(this.instances.splice(c,1)[0]),this.instances.length===0&&a([document,window]).unbind(".dialog-overlay"),b.remove();var d=0;a.each(this.instances,function(){d=Math.max(d,this.css("z-index"))}),this.maxZ=d},height:function(){var b,c;return a.browser.msie&&a.browser.version<7?(b=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight),c=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight),b<c?a(window).height()+"px":b+"px"):a(document).height()+"px"},width:function(){var b,c;return a.browser.msie?(b=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth),c=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth),b<c?a(window).width()+"px":b+"px"):a(document).width()+"px"},resize:function(){var b=a([]);a.each(a.ui.dialog.overlay.instances,function(){b=b.add(this)}),b.css({width:0,height:0}).css({width:a.ui.dialog.overlay.width(),height:a.ui.dialog.overlay.height()})}}),a.extend(a.ui.dialog.overlay.prototype,{destroy:function(){a.ui.dialog.overlay.destroy(this.$el)}})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
-* https://github.com/jquery/jquery-ui
-* Includes: jquery.ui.tabs.js
-* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
-(function(a,b){function e(){return++c}function f(){return++d}var c=0,d=0;a.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:!1,cookie:null,collapsible:!1,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"<div></div>",remove:null,select:null,show:null,spinner:"<em>Loading&#8230;</em>",tabTemplate:"<li><a href='#{href}'><span>#{label}</span></a></li>"},_create:function(){this._tabify(!0)},_setOption:function(a,b){if(a=="selected"){if(this.options.collapsible&&b==this.options.selected)return;this.select(b)}else this.options[a]=b,this._tabify()},_tabId:function(a){return a.title&&a.title.replace(/\s/g,"_").replace(/[^\w\u00c0-\uFFFF-]/g,"")||this.options.idPrefix+e()},_sanitizeSelector:function(a){return a.replace(/:/g,"\\:")},_cookie:function(){var b=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+f());return a.cookie.apply(null,[b].concat(a.makeArray(arguments)))},_ui:function(a,b){return{tab:a,panel:b,index:this.anchors.index(a)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var b=a(this);b.html(b.data("label.tabs")).removeData("label.tabs")})},_tabify:function(c){function m(b,c){b.css("display",""),!a.support.opacity&&c.opacity&&b[0].style.removeAttribute("filter")}var d=this,e=this.options,f=/^#.+/;this.list=this.element.find("ol,ul").eq(0),this.lis=a(" > li:has(a[href])",this.list),this.anchors=this.lis.map(function(){return a("a",this)[0]}),this.panels=a([]),this.anchors.each(function(b,c){var g=a(c).attr("href"),h=g.split("#")[0],i;h&&(h===location.toString().split("#")[0]||(i=a("base")[0])&&h===i.href)&&(g=c.hash,c.href=g);if(f.test(g))d.panels=d.panels.add(d.element.find(d._sanitizeSelector(g)));else if(g&&g!=="#"){a.data(c,"href.tabs",g),a.data(c,"load.tabs",g.replace(/#.*$/,""));var j=d._tabId(c);c.href="#"+j;var k=d.element.find("#"+j);k.length||(k=a(e.panelTemplate).attr("id",j).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(d.panels[b-1]||d.list),k.data("destroy.tabs",!0)),d.panels=d.panels.add(k)}else e.disabled.push(b)}),c?(this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all"),this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"),this.lis.addClass("ui-state-default ui-corner-top"),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom"),e.selected===b?(location.hash&&this.anchors.each(function(a,b){if(b.hash==location.hash)return e.selected=a,!1}),typeof e.selected!="number"&&e.cookie&&(e.selected=parseInt(d._cookie(),10)),typeof e.selected!="number"&&this.lis.filter(".ui-tabs-selected").length&&(e.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))),e.selected=e.selected||(this.lis.length?0:-1)):e.selected===null&&(e.selected=-1),e.selected=e.selected>=0&&this.anchors[e.selected]||e.selected<0?e.selected:0,e.disabled=a.unique(e.disabled.concat(a.map(this.lis.filter(".ui-state-disabled"),function(a,b){return d.lis.index(a)}))).sort(),a.inArray(e.selected,e.disabled)!=-1&&e.disabled.splice(a.inArray(e.selected,e.disabled),1),this.panels.addClass("ui-tabs-hide"),this.lis.removeClass("ui-tabs-selected ui-state-active"),e.selected>=0&&this.anchors.length&&(d.element.find(d._sanitizeSelector(d.anchors[e.selected].hash)).removeClass("ui-tabs-hide"),this.lis.eq(e.selected).addClass("ui-tabs-selected ui-state-active"),d.element.queue("tabs",function(){d._trigger("show",null,d._ui(d.anchors[e.selected],d.element.find(d._sanitizeSelector(d.anchors[e.selected].hash))[0]))}),this.load(e.selected)),a(window).bind("unload",function(){d.lis.add(d.anchors).unbind(".tabs"),d.lis=d.anchors=d.panels=null})):e.selected=this.lis.index(this.lis.filter(".ui-tabs-selected")),this.element[e.collapsible?"addClass":"removeClass"]("ui-tabs-collapsible"),e.cookie&&this._cookie(e.selected,e.cookie);for(var g=0,h;h=this.lis[g];g++)a(h)[a.inArray(g,e.disabled)!=-1&&!a(h).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled");e.cache===!1&&this.anchors.removeData("cache.tabs"),this.lis.add(this.anchors).unbind(".tabs");if(e.event!=="mouseover"){var i=function(a,b){b.is(":not(.ui-state-disabled)")&&b.addClass("ui-state-"+a)},j=function(a,b){b.removeClass("ui-state-"+a)};this.lis.bind("mouseover.tabs",function(){i("hover",a(this))}),this.lis.bind("mouseout.tabs",function(){j("hover",a(this))}),this.anchors.bind("focus.tabs",function(){i("focus",a(this).closest("li"))}),this.anchors.bind("blur.tabs",function(){j("focus",a(this).closest("li"))})}var k,l;e.fx&&(a.isArray(e.fx)?(k=e.fx[0],l=e.fx[1]):k=l=e.fx);var n=l?function(b,c){a(b).closest("li").addClass("ui-tabs-selected ui-state-active"),c.hide().removeClass("ui-tabs-hide").animate(l,l.duration||"normal",function(){m(c,l),d._trigger("show",null,d._ui(b,c[0]))})}:function(b,c){a(b).closest("li").addClass("ui-tabs-selected ui-state-active"),c.removeClass("ui-tabs-hide"),d._trigger("show",null,d._ui(b,c[0]))},o=k?function(a,b){b.animate(k,k.duration||"normal",function(){d.lis.removeClass("ui-tabs-selected ui-state-active"),b.addClass("ui-tabs-hide"),m(b,k),d.element.dequeue("tabs")})}:function(a,b,c){d.lis.removeClass("ui-tabs-selected ui-state-active"),b.addClass("ui-tabs-hide"),d.element.dequeue("tabs")};this.anchors.bind(e.event+".tabs",function(){var b=this,c=a(b).closest("li"),f=d.panels.filter(":not(.ui-tabs-hide)"),g=d.element.find(d._sanitizeSelector(b.hash));if(c.hasClass("ui-tabs-selected")&&!e.collapsible||c.hasClass("ui-state-disabled")||c.hasClass("ui-state-processing")||d.panels.filter(":animated").length||d._trigger("select",null,d._ui(this,g[0]))===!1)return this.blur(),!1;e.selected=d.anchors.index(this),d.abort();if(e.collapsible){if(c.hasClass("ui-tabs-selected"))return e.selected=-1,e.cookie&&d._cookie(e.selected,e.cookie),d.element.queue("tabs",function(){o(b,f)}).dequeue("tabs"),this.blur(),!1;if(!f.length)return e.cookie&&d._cookie(e.selected,e.cookie),d.element.queue("tabs",function(){n(b,g)}),d.load(d.anchors.index(this)),this.blur(),!1}e.cookie&&d._cookie(e.selected,e.cookie);if(g.length)f.length&&d.element.queue("tabs",function(){o(b,f)}),d.element.queue("tabs",function(){n(b,g)}),d.load(d.anchors.index(this));else throw"jQuery UI Tabs: Mismatching fragment identifier.";a.browser.msie&&this.blur()}),this.anchors.bind("click.tabs",function(){return!1})},_getIndex:function(a){return typeof a=="string"&&(a=this.anchors.index(this.anchors.filter("[href$='"+a+"']"))),a},destroy:function(){var b=this.options;return this.abort(),this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs"),this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"),this.anchors.each(function(){var b=a.data(this,"href.tabs");b&&(this.href=b);var c=a(this).unbind(".tabs");a.each(["href","load","cache"],function(a,b){c.removeData(b+".tabs")})}),this.lis.unbind(".tabs").add(this.panels).each(function(){a.data(this,"destroy.tabs")?a(this).remove():a(this).removeClass(["ui-state-default","ui-corner-top","ui-tabs-selected","ui-state-active","ui-state-hover","ui-state-focus","ui-state-disabled","ui-tabs-panel","ui-widget-content","ui-corner-bottom","ui-tabs-hide"].join(" "))}),b.cookie&&this._cookie(null,b.cookie),this},add:function(c,d,e){e===b&&(e=this.anchors.length);var f=this,g=this.options,h=a(g.tabTemplate.replace(/#\{href\}/g,c).replace(/#\{label\}/g,d)),i=c.indexOf("#")?this._tabId(a("a",h)[0]):c.replace("#","");h.addClass("ui-state-default ui-corner-top").data("destroy.tabs",!0);var j=f.element.find("#"+i);return j.length||(j=a(g.panelTemplate).attr("id",i).data("destroy.tabs",!0)),j.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide"),e>=this.lis.length?(h.appendTo(this.list),j.appendTo(this.list[0].parentNode)):(h.insertBefore(this.lis[e]),j.insertBefore(this.panels[e])),g.disabled=a.map(g.disabled,function(a,b){return a>=e?++a:a}),this._tabify(),this.anchors.length==1&&(g.selected=0,h.addClass("ui-tabs-selected ui-state-active"),j.removeClass("ui-tabs-hide"),this.element.queue("tabs",function(){f._trigger("show",null,f._ui(f.anchors[0],f.panels[0]))}),this.load(0)),this._trigger("add",null,this._ui(this.anchors[e],this.panels[e])),this},remove:function(b){b=this._getIndex(b);var c=this.options,d=this.lis.eq(b).remove(),e=this.panels.eq(b).remove();return d.hasClass("ui-tabs-selected")&&this.anchors.length>1&&this.select(b+(b+1<this.anchors.length?1:-1)),c.disabled=a.map(a.grep(c.disabled,function(a,c){return a!=b}),function(a,c){return a>=b?--a:a}),this._tabify(),this._trigger("remove",null,this._ui(d.find("a")[0],e[0])),this},enable:function(b){b=this._getIndex(b);var c=this.options;if(a.inArray(b,c.disabled)==-1)return;return this.lis.eq(b).removeClass("ui-state-disabled"),c.disabled=a.grep(c.disabled,function(a,c){return a!=b}),this._trigger("enable",null,this._ui(this.anchors[b],this.panels[b])),this},disable:function(a){a=this._getIndex(a);var b=this,c=this.options;return a!=c.selected&&(this.lis.eq(a).addClass("ui-state-disabled"),c.disabled.push(a),c.disabled.sort(),this._trigger("disable",null,this._ui(this.anchors[a],this.panels[a]))),this},select:function(a){a=this._getIndex(a);if(a==-1)if(this.options.collapsible&&this.options.selected!=-1)a=this.options.selected;else return this;return this.anchors.eq(a).trigger(this.options.event+".tabs"),this},load:function(b){b=this._getIndex(b);var c=this,d=this.options,e=this.anchors.eq(b)[0],f=a.data(e,"load.tabs");this.abort();if(!f||this.element.queue("tabs").length!==0&&a.data(e,"cache.tabs")){this.element.dequeue("tabs");return}this.lis.eq(b).addClass("ui-state-processing");if(d.spinner){var g=a("span",e);g.data("label.tabs",g.html()).html(d.spinner)}return this.xhr=a.ajax(a.extend({},d.ajaxOptions,{url:f,success:function(f,g){c.element.find(c._sanitizeSelector(e.hash)).html(f),c._cleanup(),d.cache&&a.data(e,"cache.tabs",!0),c._trigger("load",null,c._ui(c.anchors[b],c.panels[b]));try{d.ajaxOptions.success(f,g)}catch(h){}},error:function(a,f,g){c._cleanup(),c._trigger("load",null,c._ui(c.anchors[b],c.panels[b]));try{d.ajaxOptions.error(a,f,b,e)}catch(g){}}})),c.element.dequeue("tabs"),this},abort:function(){return this.element.queue([]),this.panels.stop(!1,!0),this.element.queue("tabs",this.element.queue("tabs").splice(-2,2)),this.xhr&&(this.xhr.abort(),delete this.xhr),this._cleanup(),this},url:function(a,b){return this.anchors.eq(a).removeData("cache.tabs").data("load.tabs",b),this},length:function(){return this.anchors.length}}),a.extend(a.ui.tabs,{version:"1.8.21"}),a.extend(a.ui.tabs.prototype,{rotation:null,rotate:function(a,b){var c=this,d=this.options,e=c._rotate||(c._rotate=function(b){clearTimeout(c.rotation),c.rotation=setTimeout(function(){var a=d.selected;c.select(++a<c.anchors.length?a:0)},a),b&&b.stopPropagation()}),f=c._unrotate||(c._unrotate=b?function(a){e()}:function(a){a.clientX&&c.rotate(null)});return a?(this.element.bind("tabsshow",e),this.anchors.bind(d.event+".tabs",f),e()):(clearTimeout(c.rotation),this.element.unbind("tabsshow",e),this.anchors.unbind(d.event+".tabs",f),delete this._rotate,delete this._unrotate),this}})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
-* https://github.com/jquery/jquery-ui
-* Includes: jquery.ui.datepicker.js
-* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
-(function($,undefined){function Datepicker(){this.debug=!1,this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},$.extend(this._defaults,this.regional[""]),this.dpDiv=bindHover($('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}function bindHover(a){var b="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return a.bind("mouseout",function(a){var c=$(a.target).closest(b);if(!c.length)return;c.removeClass("ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover")}).bind("mouseover",function(c){var d=$(c.target).closest(b);if($.datepicker._isDisabledDatepicker(instActive.inline?a.parent()[0]:instActive.input[0])||!d.length)return;d.parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),d.addClass("ui-state-hover"),d.hasClass("ui-datepicker-prev")&&d.addClass("ui-datepicker-prev-hover"),d.hasClass("ui-datepicker-next")&&d.addClass("ui-datepicker-next-hover")})}function extendRemove(a,b){$.extend(a,b);for(var c in b)if(b[c]==null||b[c]==undefined)a[c]=b[c];return a}function isArray(a){return a&&($.browser.safari&&typeof a=="object"&&a.length||a.constructor&&a.constructor.toString().match(/\Array\(\)/))}$.extend($.ui,{datepicker:{version:"1.8.21"}});var PROP_NAME="datepicker",dpuuid=(new Date).getTime(),instActive;$.extend(Datepicker.prototype,{markerClassName:"hasDatepicker",maxRows:4,log:function(){this.debug&&console.log.apply("",arguments)},_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(a){return extendRemove(this._defaults,a||{}),this},_attachDatepicker:function(target,settings){var inlineSettings=null;for(var attrName in this._defaults){var attrValue=target.getAttribute("date:"+attrName);if(attrValue){inlineSettings=inlineSettings||{};try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}}var nodeName=target.nodeName.toLowerCase(),inline=nodeName=="div"||nodeName=="span";target.id||(this.uuid+=1,target.id="dp"+this.uuid);var inst=this._newInst($(target),inline);inst.settings=$.extend({},settings||{},inlineSettings||{}),nodeName=="input"?this._connectDatepicker(target,inst):inline&&this._inlineDatepicker(target,inst)},_newInst:function(a,b){var c=a[0].id.replace(/([^A-Za-z0-9_-])/g,"\\\\$1");return{id:c,input:a,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:b,dpDiv:b?bindHover($('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')):this.dpDiv}},_connectDatepicker:function(a,b){var c=$(a);b.append=$([]),b.trigger=$([]);if(c.hasClass(this.markerClassName))return;this._attachments(c,b),c.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(a,c,d){b.settings[c]=d}).bind("getData.datepicker",function(a,c){return this._get(b,c)}),this._autoSize(b),$.data(a,PROP_NAME,b),b.settings.disabled&&this._disableDatepicker(a)},_attachments:function(a,b){var c=this._get(b,"appendText"),d=this._get(b,"isRTL");b.append&&b.append.remove(),c&&(b.append=$('<span class="'+this._appendClass+'">'+c+"</span>"),a[d?"before":"after"](b.append)),a.unbind("focus",this._showDatepicker),b.trigger&&b.trigger.remove();var e=this._get(b,"showOn");(e=="focus"||e=="both")&&a.focus(this._showDatepicker);if(e=="button"||e=="both"){var f=this._get(b,"buttonText"),g=this._get(b,"buttonImage");b.trigger=$(this._get(b,"buttonImageOnly")?$("<img/>").addClass(this._triggerClass).attr({src:g,alt:f,title:f}):$('<button type="button"></button>').addClass(this._triggerClass).html(g==""?f:$("<img/>").attr({src:g,alt:f,title:f}))),a[d?"before":"after"](b.trigger),b.trigger.click(function(){return $.datepicker._datepickerShowing&&$.datepicker._lastInput==a[0]?$.datepicker._hideDatepicker():$.datepicker._datepickerShowing&&$.datepicker._lastInput!=a[0]?($.datepicker._hideDatepicker(),$.datepicker._showDatepicker(a[0])):$.datepicker._showDatepicker(a[0]),!1})}},_autoSize:function(a){if(this._get(a,"autoSize")&&!a.inline){var b=new Date(2009,11,20),c=this._get(a,"dateFormat");if(c.match(/[DM]/)){var d=function(a){var b=0,c=0;for(var d=0;d<a.length;d++)a[d].length>b&&(b=a[d].length,c=d);return c};b.setMonth(d(this._get(a,c.match(/MM/)?"monthNames":"monthNamesShort"))),b.setDate(d(this._get(a,c.match(/DD/)?"dayNames":"dayNamesShort"))+20-b.getDay())}a.input.attr("size",this._formatDate(a,b).length)}},_inlineDatepicker:function(a,b){var c=$(a);if(c.hasClass(this.markerClassName))return;c.addClass(this.markerClassName).append(b.dpDiv).bind("setData.datepicker",function(a,c,d){b.settings[c]=d}).bind("getData.datepicker",function(a,c){return this._get(b,c)}),$.data(a,PROP_NAME,b),this._setDate(b,this._getDefaultDate(b),!0),this._updateDatepicker(b),this._updateAlternate(b),b.settings.disabled&&this._disableDatepicker(a),b.dpDiv.css("display","block")},_dialogDatepicker:function(a,b,c,d,e){var f=this._dialogInst;if(!f){this.uuid+=1;var g="dp"+this.uuid;this._dialogInput=$('<input type="text" id="'+g+'" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>'),this._dialogInput.keydown(this._doKeyDown),$("body").append(this._dialogInput),f=this._dialogInst=this._newInst(this._dialogInput,!1),f.settings={},$.data(this._dialogInput[0],PROP_NAME,f)}extendRemove(f.settings,d||{}),b=b&&b.constructor==Date?this._formatDate(f,b):b,this._dialogInput.val(b),this._pos=e?e.length?e:[e.pageX,e.pageY]:null;if(!this._pos){var h=document.documentElement.clientWidth,i=document.documentElement.clientHeight,j=document.documentElement.scrollLeft||document.body.scrollLeft,k=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[h/2-100+j,i/2-150+k]}return this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),f.settings.onSelect=c,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),$.blockUI&&$.blockUI(this.dpDiv),$.data(this._dialogInput[0],PROP_NAME,f),this},_destroyDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!b.hasClass(this.markerClassName))return;var d=a.nodeName.toLowerCase();$.removeData(a,PROP_NAME),d=="input"?(c.append.remove(),c.trigger.remove(),b.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):(d=="div"||d=="span")&&b.removeClass(this.markerClassName).empty()},_enableDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!b.hasClass(this.markerClassName))return;var d=a.nodeName.toLowerCase();if(d=="input")a.disabled=!1,c.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""});else if(d=="div"||d=="span"){var e=b.children("."+this._inlineClass);e.children().removeClass("ui-state-disabled"),e.find("select.ui-datepicker-month, select.ui-datepicker-year").removeAttr("disabled")}this._disabledInputs=$.map(this._disabledInputs,function(b){return b==a?null:b})},_disableDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!b.hasClass(this.markerClassName))return;var d=a.nodeName.toLowerCase();if(d=="input")a.disabled=!0,c.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"});else if(d=="div"||d=="span"){var e=b.children("."+this._inlineClass);e.children().addClass("ui-state-disabled"),e.find("select.ui-datepicker-month, select.ui-datepicker-year").attr("disabled","disabled")}this._disabledInputs=$.map(this._disabledInputs,function(b){return b==a?null:b}),this._disabledInputs[this._disabledInputs.length]=a},_isDisabledDatepicker:function(a){if(!a)return!1;for(var b=0;b<this._disabledInputs.length;b++)if(this._disabledInputs[b]==a)return!0;return!1},_getInst:function(a){try{return $.data(a,PROP_NAME)}catch(b){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(a,b,c){var d=this._getInst(a);if(arguments.length==2&&typeof b=="string")return b=="defaults"?$.extend({},$.datepicker._defaults):d?b=="all"?$.extend({},d.settings):this._get(d,b):null;var e=b||{};typeof b=="string"&&(e={},e[b]=c);if(d){this._curInst==d&&this._hideDatepicker();var f=this._getDateDatepicker(a,!0),g=this._getMinMaxDate(d,"min"),h=this._getMinMaxDate(d,"max");extendRemove(d.settings,e),g!==null&&e.dateFormat!==undefined&&e.minDate===undefined&&(d.settings.minDate=this._formatDate(d,g)),h!==null&&e.dateFormat!==undefined&&e.maxDate===undefined&&(d.settings.maxDate=this._formatDate(d,h)),this._attachments($(a),d),this._autoSize(d),this._setDate(d,f),this._updateAlternate(d),this._updateDatepicker(d)}},_changeDatepicker:function(a,b,c){this._optionDatepicker(a,b,c)},_refreshDatepicker:function(a){var b=this._getInst(a);b&&this._updateDatepicker(b)},_setDateDatepicker:function(a,b){var c=this._getInst(a);c&&(this._setDate(c,b),this._updateDatepicker(c),this._updateAlternate(c))},_getDateDatepicker:function(a,b){var c=this._getInst(a);return c&&!c.inline&&this._setDateFromField(c,b),c?this._getDate(c):null},_doKeyDown:function(a){var b=$.datepicker._getInst(a.target),c=!0,d=b.dpDiv.is(".ui-datepicker-rtl");b._keyEvent=!0;if($.datepicker._datepickerShowing)switch(a.keyCode){case 9:$.datepicker._hideDatepicker(),c=!1;break;case 13:var e=$("td."+$.datepicker._dayOverClass+":not(."+$.datepicker._currentClass+")",b.dpDiv);e[0]&&$.datepicker._selectDay(a.target,b.selectedMonth,b.selectedYear,e[0]);var f=$.datepicker._get(b,"onSelect");if(f){var g=$.datepicker._formatDate(b);f.apply(b.input?b.input[0]:null,[g,b])}else $.datepicker._hideDatepicker();return!1;case 27:$.datepicker._hideDatepicker();break;case 33:$.datepicker._adjustDate(a.target,a.ctrlKey?-$.datepicker._get(b,"stepBigMonths"):-$.datepicker._get(b,"stepMonths"),"M");break;case 34:$.datepicker._adjustDate(a.target,a.ctrlKey?+$.datepicker._get(b,"stepBigMonths"):+$.datepicker._get(b,"stepMonths"),"M");break;case 35:(a.ctrlKey||a.metaKey)&&$.datepicker._clearDate(a.target),c=a.ctrlKey||a.metaKey;break;case 36:(a.ctrlKey||a.metaKey)&&$.datepicker._gotoToday(a.target),c=a.ctrlKey||a.metaKey;break;case 37:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,d?1:-1,"D"),c=a.ctrlKey||a.metaKey,a.originalEvent.altKey&&$.datepicker._adjustDate(a.target,a.ctrlKey?-$.datepicker._get(b,"stepBigMonths"):-$.datepicker._get(b,"stepMonths"),"M");break;case 38:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,-7,"D"),c=a.ctrlKey||a.metaKey;break;case 39:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,d?-1:1,"D"),c=a.ctrlKey||a.metaKey,a.originalEvent.altKey&&$.datepicker._adjustDate(a.target,a.ctrlKey?+$.datepicker._get(b,"stepBigMonths"):+$.datepicker._get(b,"stepMonths"),"M");break;case 40:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,7,"D"),c=a.ctrlKey||a.metaKey;break;default:c=!1}else a.keyCode==36&&a.ctrlKey?$.datepicker._showDatepicker(this):c=!1;c&&(a.preventDefault(),a.stopPropagation())},_doKeyPress:function(a){var b=$.datepicker._getInst(a.target);if($.datepicker._get(b,"constrainInput")){var c=$.datepicker._possibleChars($.datepicker._get(b,"dateFormat")),d=String.fromCharCode(a.charCode==undefined?a.keyCode:a.charCode);return a.ctrlKey||a.metaKey||d<" "||!c||c.indexOf(d)>-1}},_doKeyUp:function(a){var b=$.datepicker._getInst(a.target);if(b.input.val()!=b.lastVal)try{var c=$.datepicker.parseDate($.datepicker._get(b,"dateFormat"),b.input?b.input.val():null,$.datepicker._getFormatConfig(b));c&&($.datepicker._setDateFromField(b),$.datepicker._updateAlternate(b),$.datepicker._updateDatepicker(b))}catch(d){$.datepicker.log(d)}return!0},_showDatepicker:function(a){a=a.target||a,a.nodeName.toLowerCase()!="input"&&(a=$("input",a.parentNode)[0]);if($.datepicker._isDisabledDatepicker(a)||$.datepicker._lastInput==a)return;var b=$.datepicker._getInst(a);$.datepicker._curInst&&$.datepicker._curInst!=b&&($.datepicker._curInst.dpDiv.stop(!0,!0),b&&$.datepicker._datepickerShowing&&$.datepicker._hideDatepicker($.datepicker._curInst.input[0]));var c=$.datepicker._get(b,"beforeShow"),d=c?c.apply(a,[a,b]):{};if(d===!1)return;extendRemove(b.settings,d),b.lastVal=null,$.datepicker._lastInput=a,$.datepicker._setDateFromField(b),$.datepicker._inDialog&&(a.value=""),$.datepicker._pos||($.datepicker._pos=$.datepicker._findPos(a),$.datepicker._pos[1]+=a.offsetHeight);var e=!1;$(a).parents().each(function(){return e|=$(this).css("position")=="fixed",!e}),e&&$.browser.opera&&($.datepicker._pos[0]-=document.documentElement.scrollLeft,$.datepicker._pos[1]-=document.documentElement.scrollTop);var f={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null,b.dpDiv.empty(),b.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),$.datepicker._updateDatepicker(b),f=$.datepicker._checkOffset(b,f,e),b.dpDiv.css({position:$.datepicker._inDialog&&$.blockUI?"static":e?"fixed":"absolute",display:"none",left:f.left+"px",top:f.top+"px"});if(!b.inline){var g=$.datepicker._get(b,"showAnim"),h=$.datepicker._get(b,"duration"),i=function(){var a=b.dpDiv.find("iframe.ui-datepicker-cover");if(!!a.length){var c=$.datepicker._getBorders(b.dpDiv);a.css({left:-c[0],top:-c[1],width:b.dpDiv.outerWidth(),height:b.dpDiv.outerHeight()})}};b.dpDiv.zIndex($(a).zIndex()+1),$.datepicker._datepickerShowing=!0,$.effects&&$.effects[g]?b.dpDiv.show(g,$.datepicker._get(b,"showOptions"),h,i):b.dpDiv[g||"show"](g?h:null,i),(!g||!h)&&i(),b.input.is(":visible")&&!b.input.is(":disabled")&&b.input.focus(),$.datepicker._curInst=b}},_updateDatepicker:function(a){var b=this;b.maxRows=4;var c=$.datepicker._getBorders(a.dpDiv);instActive=a,a.dpDiv.empty().append(this._generateHTML(a));var d=a.dpDiv.find("iframe.ui-datepicker-cover");!d.length||d.css({left:-c[0],top:-c[1],width:a.dpDiv.outerWidth(),height:a.dpDiv.outerHeight()}),a.dpDiv.find("."+this._dayOverClass+" a").mouseover();var e=this._getNumberOfMonths(a),f=e[1],g=17;a.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),f>1&&a.dpDiv.addClass("ui-datepicker-multi-"+f).css("width",g*f+"em"),a.dpDiv[(e[0]!=1||e[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi"),a.dpDiv[(this._get(a,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),a==$.datepicker._curInst&&$.datepicker._datepickerShowing&&a.input&&a.input.is(":visible")&&!a.input.is(":disabled")&&a.input[0]!=document.activeElement&&a.input.focus();if(a.yearshtml){var h=a.yearshtml;setTimeout(function(){h===a.yearshtml&&a.yearshtml&&a.dpDiv.find("select.ui-datepicker-year:first").replaceWith(a.yearshtml),h=a.yearshtml=null},0)}},_getBorders:function(a){var b=function(a){return{thin:1,medium:2,thick:3}[a]||a};return[parseFloat(b(a.css("border-left-width"))),parseFloat(b(a.css("border-top-width")))]},_checkOffset:function(a,b,c){var d=a.dpDiv.outerWidth(),e=a.dpDiv.outerHeight(),f=a.input?a.input.outerWidth():0,g=a.input?a.input.outerHeight():0,h=document.documentElement.clientWidth+$(document).scrollLeft(),i=document.documentElement.clientHeight+$(document).scrollTop();return b.left-=this._get(a,"isRTL")?d-f:0,b.left-=c&&b.left==a.input.offset().left?$(document).scrollLeft():0,b.top-=c&&b.top==a.input.offset().top+g?$(document).scrollTop():0,b.left-=Math.min(b.left,b.left+d>h&&h>d?Math.abs(b.left+d-h):0),b.top-=Math.min(b.top,b.top+e>i&&i>e?Math.abs(e+g):0),b},_findPos:function(a){var b=this._getInst(a),c=this._get(b,"isRTL");while(a&&(a.type=="hidden"||a.nodeType!=1||$.expr.filters.hidden(a)))a=a[c?"previousSibling":"nextSibling"];var d=$(a).offset();return[d.left,d.top]},_hideDatepicker:function(a){var b=this._curInst;if(!b||a&&b!=$.data(a,PROP_NAME))return;if(this._datepickerShowing){var c=this._get(b,"showAnim"),d=this._get(b,"duration"),e=function(){$.datepicker._tidyDialog(b)};$.effects&&$.effects[c]?b.dpDiv.hide(c,$.datepicker._get(b,"showOptions"),d,e):b.dpDiv[c=="slideDown"?"slideUp":c=="fadeIn"?"fadeOut":"hide"](c?d:null,e),c||e(),this._datepickerShowing=!1;var f=this._get(b,"onClose");f&&f.apply(b.input?b.input[0]:null,[b.input?b.input.val():"",b]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),$.blockUI&&($.unblockUI(),$("body").append(this.dpDiv))),this._inDialog=!1}},_tidyDialog:function(a){a.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(a){if(!$.datepicker._curInst)return;var b=$(a.target),c=$.datepicker._getInst(b[0]);(b[0].id!=$.datepicker._mainDivId&&b.parents("#"+$.datepicker._mainDivId).length==0&&!b.hasClass($.datepicker.markerClassName)&&!b.closest("."+$.datepicker._triggerClass).length&&$.datepicker._datepickerShowing&&(!$.datepicker._inDialog||!$.blockUI)||b.hasClass($.datepicker.markerClassName)&&$.datepicker._curInst!=c)&&$.datepicker._hideDatepicker()},_adjustDate:function(a,b,c){var d=$(a),e=this._getInst(d[0]);if(this._isDisabledDatepicker(d[0]))return;this._adjustInstDate(e,b+(c=="M"?this._get(e,"showCurrentAtPos"):0),c),this._updateDatepicker(e)},_gotoToday:function(a){var b=$(a),c=this._getInst(b[0]);if(this._get(c,"gotoCurrent")&&c.currentDay)c.selectedDay=c.currentDay,c.drawMonth=c.selectedMonth=c.currentMonth,c.drawYear=c.selectedYear=c.currentYear;else{var d=new Date;c.selectedDay=d.getDate(),c.drawMonth=c.selectedMonth=d.getMonth(),c.drawYear=c.selectedYear=d.getFullYear()}this._notifyChange(c),this._adjustDate(b)},_selectMonthYear:function(a,b,c){var d=$(a),e=this._getInst(d[0]);e["selected"+(c=="M"?"Month":"Year")]=e["draw"+(c=="M"?"Month":"Year")]=parseInt(b.options[b.selectedIndex].value,10),this._notifyChange(e),this._adjustDate(d)},_selectDay:function(a,b,c,d){var e=$(a);if($(d).hasClass(this._unselectableClass)||this._isDisabledDatepicker(e[0]))return;var f=this._getInst(e[0]);f.selectedDay=f.currentDay=$("a",d).html(),f.selectedMonth=f.currentMonth=b,f.selectedYear=f.currentYear=c,this._selectDate(a,this._formatDate(f,f.currentDay,f.currentMonth,f.currentYear))},_clearDate:function(a){var b=$(a),c=this._getInst(b[0]);this._selectDate(b,"")},_selectDate:function(a,b){var c=$(a),d=this._getInst(c[0]);b=b!=null?b:this._formatDate(d),d.input&&d.input.val(b),this._updateAlternate(d);var e=this._get(d,"onSelect");e?e.apply(d.input?d.input[0]:null,[b,d]):d.input&&d.input.trigger("change"),d.inline?this._updateDatepicker(d):(this._hideDatepicker(),this._lastInput=d.input[0],typeof d.input[0]!="object"&&d.input.focus(),this._lastInput=null)},_updateAlternate:function(a){var b=this._get(a,"altField");if(b){var c=this._get(a,"altFormat")||this._get(a,"dateFormat"),d=this._getDate(a),e=this.formatDate(c,d,this._getFormatConfig(a));$(b).each(function(){$(this).val(e)})}},noWeekends:function(a){var b=a.getDay();return[b>0&&b<6,""]},iso8601Week:function(a){var b=new Date(a.getTime());b.setDate(b.getDate()+4-(b.getDay()||7));var c=b.getTime();return b.setMonth(0),b.setDate(1),Math.floor(Math.round((c-b)/864e5)/7)+1},parseDate:function(a,b,c){if(a==null||b==null)throw"Invalid arguments";b=typeof b=="object"?b.toString():b+"";if(b=="")return null;var d=(c?c.shortYearCutoff:null)||this._defaults.shortYearCutoff;d=typeof d!="string"?d:(new Date).getFullYear()%100+parseInt(d,10);var e=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,f=(c?c.dayNames:null)||this._defaults.dayNames,g=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort,h=(c?c.monthNames:null)||this._defaults.monthNames,i=-1,j=-1,k=-1,l=-1,m=!1,n=function(b){var c=s+1<a.length&&a.charAt(s+1)==b;return c&&s++,c},o=function(a){var c=n(a),d=a=="@"?14:a=="!"?20:a=="y"&&c?4:a=="o"?3:2,e=new RegExp("^\\d{1,"+d+"}"),f=b.substring(r).match(e);if(!f)throw"Missing number at position "+r;return r+=f[0].length,parseInt(f[0],10)},p=function(a,c,d){var e=$.map(n(a)?d:c,function(a,b){return[[b,a]]}).sort(function(a,b){return-(a[1].length-b[1].length)}),f=-1;$.each(e,function(a,c){var d=c[1];if(b.substr(r,d.length).toLowerCase()==d.toLowerCase())return f=c[0],r+=d.length,!1});if(f!=-1)return f+1;throw"Unknown name at position "+r},q=function(){if(b.charAt(r)!=a.charAt(s))throw"Unexpected literal at position "+r;r++},r=0;for(var s=0;s<a.length;s++)if(m)a.charAt(s)=="'"&&!n("'")?m=!1:q();else switch(a.charAt(s)){case"d":k=o("d");break;case"D":p("D",e,f);break;case"o":l=o("o");break;case"m":j=o("m");break;case"M":j=p("M",g,h);break;case"y":i=o("y");break;case"@":var t=new Date(o("@"));i=t.getFullYear(),j=t.getMonth()+1,k=t.getDate();break;case"!":var t=new Date((o("!")-this._ticksTo1970)/1e4);i=t.getFullYear(),j=t.getMonth()+1,k=t.getDate();break;case"'":n("'")?q():m=!0;break;default:q()}if(r<b.length)throw"Extra/unparsed characters found in date: "+b.substring(r);i==-1?i=(new Date).getFullYear():i<100&&(i+=(new Date).getFullYear()-(new Date).getFullYear()%100+(i<=d?0:-100));if(l>-1){j=1,k=l;do{var u=this._getDaysInMonth(i,j-1);if(k<=u)break;j++,k-=u}while(!0)}var t=this._daylightSavingAdjust(new Date(i,j-1,k));if(t.getFullYear()!=i||t.getMonth()+1!=j||t.getDate()!=k)throw"Invalid date";return t},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*24*60*60*1e7,formatDate:function(a,b,c){if(!b)return"";var d=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,e=(c?c.dayNames:null)||this._defaults.dayNames,f=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort,g=(c?c.monthNames:null)||this._defaults.monthNames,h=function(b){var c=m+1<a.length&&a.charAt(m+1)==b;return c&&m++,c},i=function(a,b,c){var d=""+b;if(h(a))while(d.length<c)d="0"+d;return d},j=function(a,b,c,d){return h(a)?d[b]:c[b]},k="",l=!1;if(b)for(var m=0;m<a.length;m++)if(l)a.charAt(m)=="'"&&!h("'")?l=!1:k+=a.charAt(m);else switch(a.charAt(m)){case"d":k+=i("d",b.getDate(),2);break;case"D":k+=j("D",b.getDay(),d,e);break;case"o":k+=i("o",Math.round(((new Date(b.getFullYear(),b.getMonth(),b.getDate())).getTime()-(new Date(b.getFullYear(),0,0)).getTime())/864e5),3);break;case"m":k+=i("m",b.getMonth()+1,2);break;case"M":k+=j("M",b.getMonth(),f,g);break;case"y":k+=h("y")?b.getFullYear():(b.getYear()%100<10?"0":"")+b.getYear()%100;break;case"@":k+=b.getTime();break;case"!":k+=b.getTime()*1e4+this._ticksTo1970;break;case"'":h("'")?k+="'":l=!0;break;default:k+=a.charAt(m)}return k},_possibleChars:function(a){var b="",c=!1,d=function(b){var c=e+1<a.length&&a.charAt(e+1)==b;return c&&e++,c};for(var e=0;e<a.length;e++)if(c)a.charAt(e)=="'"&&!d("'")?c=!1:b+=a.charAt(e);else switch(a.charAt(e)){case"d":case"m":case"y":case"@":b+="0123456789";break;case"D":case"M":return null;case"'":d("'")?b+="'":c=!0;break;default:b+=a.charAt(e)}return b},_get:function(a,b){return a.settings[b]!==undefined?a.settings[b]:this._defaults[b]},_setDateFromField:function(a,b){if(a.input.val()==a.lastVal)return;var c=this._get(a,"dateFormat"),d=a.lastVal=a.input?a.input.val():null,e,f;e=f=this._getDefaultDate(a);var g=this._getFormatConfig(a);try{e=this.parseDate(c,d,g)||f}catch(h){this.log(h),d=b?"":d}a.selectedDay=e.getDate(),a.drawMonth=a.selectedMonth=e.getMonth(),a.drawYear=a.selectedYear=e.getFullYear(),a.currentDay=d?e.getDate():0,a.currentMonth=d?e.getMonth():0,a.currentYear=d?e.getFullYear():0,this._adjustInstDate(a)},_getDefaultDate:function(a){return this._restrictMinMax(a,this._determineDate(a,this._get(a,"defaultDate"),new Date))},_determineDate:function(a,b,c){var d=function(a){var b=new Date;return b.setDate(b.getDate()+a),b},e=function(b){try{return $.datepicker.parseDate($.datepicker._get(a,"dateFormat"),b,$.datepicker._getFormatConfig(a))}catch(c){}var d=(b.toLowerCase().match(/^c/)?$.datepicker._getDate(a):null)||new Date,e=d.getFullYear(),f=d.getMonth(),g=d.getDate(),h=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,i=h.exec(b);while(i){switch(i[2]||"d"){case"d":case"D":g+=parseInt(i[1],10);break;case"w":case"W":g+=parseInt(i[1],10)*7;break;case"m":case"M":f+=parseInt(i[1],10),g=Math.min(g,$.datepicker._getDaysInMonth(e,f));break;case"y":case"Y":e+=parseInt(i[1],10),g=Math.min(g,$.datepicker._getDaysInMonth(e,f))}i=h.exec(b)}return new Date(e,f,g)},f=b==null||b===""?c:typeof b=="string"?e(b):typeof b=="number"?isNaN(b)?c:d(b):new Date(b.getTime());return f=f&&f.toString()=="Invalid Date"?c:f,f&&(f.setHours(0),f.setMinutes(0),f.setSeconds(0),f.setMilliseconds(0)),this._daylightSavingAdjust(f)},_daylightSavingAdjust:function(a){return a?(a.setHours(a.getHours()>12?a.getHours()+2:0),a):null},_setDate:function(a,b,c){var d=!b,e=a.selectedMonth,f=a.selectedYear,g=this._restrictMinMax(a,this._determineDate(a,b,new Date));a.selectedDay=a.currentDay=g.getDate(),a.drawMonth=a.selectedMonth=a.currentMonth=g.getMonth(),a.drawYear=a.selectedYear=a.currentYear=g.getFullYear(),(e!=a.selectedMonth||f!=a.selectedYear)&&!c&&this._notifyChange(a),this._adjustInstDate(a),a.input&&a.input.val(d?"":this._formatDate(a))},_getDate:function(a){var b=!a.currentYear||a.input&&a.input.val()==""?null:this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return b},_generateHTML:function(a){var b=new Date;b=this._daylightSavingAdjust(new Date(b.getFullYear(),b.getMonth(),b.getDate()));var c=this._get(a,"isRTL"),d=this._get(a,"showButtonPanel"),e=this._get(a,"hideIfNoPrevNext"),f=this._get(a,"navigationAsDateFormat"),g=this._getNumberOfMonths(a),h=this._get(a,"showCurrentAtPos"),i=this._get(a,"stepMonths"),j=g[0]!=1||g[1]!=1,k=this._daylightSavingAdjust(a.currentDay?new Date(a.currentYear,a.currentMonth,a.currentDay):new Date(9999,9,9)),l=this._getMinMaxDate(a,"min"),m=this._getMinMaxDate(a,"max"),n=a.drawMonth-h,o=a.drawYear;n<0&&(n+=12,o--);if(m){var p=this._daylightSavingAdjust(new Date(m.getFullYear(),m.getMonth()-g[0]*g[1]+1,m.getDate()));p=l&&p<l?l:p;while(this._daylightSavingAdjust(new Date(o,n,1))>p)n--,n<0&&(n=11,o--)}a.drawMonth=n,a.drawYear=o;var q=this._get(a,"prevText");q=f?this.formatDate(q,this._daylightSavingAdjust(new Date(o,n-i,1)),this._getFormatConfig(a)):q;var r=this._canAdjustMonth(a,-1,o,n)?'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._adjustDate('#"+a.id+"', -"+i+", 'M');\""+' title="'+q+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+q+"</span></a>":e?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+q+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+q+"</span></a>",s=this._get(a,"nextText");s=f?this.formatDate(s,this._daylightSavingAdjust(new Date(o,n+i,1)),this._getFormatConfig(a)):s;var t=this._canAdjustMonth(a,1,o,n)?'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._adjustDate('#"+a.id+"', +"+i+", 'M');\""+' title="'+s+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+s+"</span></a>":e?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+s+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+s+"</span></a>",u=this._get(a,"currentText"),v=this._get(a,"gotoCurrent")&&a.currentDay?k:b;u=f?this.formatDate(u,v,this._getFormatConfig(a)):u;var w=a.inline?"":'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_'+dpuuid+'.datepicker._hideDatepicker();">'+this._get(a,"closeText")+"</button>",x=d?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(c?w:"")+(this._isInRange(a,v)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._gotoToday('#"+a.id+"');\""+">"+u+"</button>":"")+(c?"":w)+"</div>":"",y=parseInt(this._get(a,"firstDay"),10);y=isNaN(y)?0:y;var z=this._get(a,"showWeek"),A=this._get(a,"dayNames"),B=this._get(a,"dayNamesShort"),C=this._get(a,"dayNamesMin"),D=this._get(a,"monthNames"),E=this._get(a,"monthNamesShort"),F=this._get(a,"beforeShowDay"),G=this._get(a,"showOtherMonths"),H=this._get(a,"selectOtherMonths"),I=this._get(a,"calculateWeek")||this.iso8601Week,J=this._getDefaultDate(a),K="";for(var L=0;L<g[0];L++){var M="";this.maxRows=4;for(var N=0;N<g[1];N++){var O=this._daylightSavingAdjust(new Date(o,n,a.selectedDay)),P=" ui-corner-all",Q="";if(j){Q+='<div class="ui-datepicker-group';if(g[1]>1)switch(N){case 0:Q+=" ui-datepicker-group-first",P=" ui-corner-"+(c?"right":"left");break;case g[1]-1:Q+=" ui-datepicker-group-last",P=" ui-corner-"+(c?"left":"right");break;default:Q+=" ui-datepicker-group-middle",P=""}Q+='">'}Q+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+P+'">'+(/all|left/.test(P)&&L==0?c?t:r:"")+(/all|right/.test(P)&&L==0?c?r:t:"")+this._generateMonthYearHeader(a,n,o,l,m,L>0||N>0,D,E)+'</div><table class="ui-datepicker-calendar"><thead>'+"<tr>";var R=z?'<th class="ui-datepicker-week-col">'+this._get(a,"weekHeader")+"</th>":"";for(var S=0;S<7;S++){var T=(S+y)%7;R+="<th"+((S+y+6)%7>=5?' class="ui-datepicker-week-end"':"")+">"+'<span title="'+A[T]+'">'+C[T]+"</span></th>"}Q+=R+"</tr></thead><tbody>";var U=this._getDaysInMonth(o,n);o==a.selectedYear&&n==a.selectedMonth&&(a.selectedDay=Math.min(a.selectedDay,U));var V=(this._getFirstDayOfMonth(o,n)-y+7)%7,W=Math.ceil((V+U)/7),X=j?this.maxRows>W?this.maxRows:W:W;this.maxRows=X;var Y=this._daylightSavingAdjust(new Date(o,n,1-V));for(var Z=0;Z<X;Z++){Q+="<tr>";var _=z?'<td class="ui-datepicker-week-col">'+this._get(a,"calculateWeek")(Y)+"</td>":"";for(var S=0;S<7;S++){var ba=F?F.apply(a.input?a.input[0]:null,[Y]):[!0,""],bb=Y.getMonth()!=n,bc=bb&&!H||!ba[0]||l&&Y<l||m&&Y>m;_+='<td class="'+((S+y+6)%7>=5?" ui-datepicker-week-end":"")+(bb?" ui-datepicker-other-month":"")+(Y.getTime()==O.getTime()&&n==a.selectedMonth&&a._keyEvent||J.getTime()==Y.getTime()&&J.getTime()==O.getTime()?" "+this._dayOverClass:"")+(bc?" "+this._unselectableClass+" ui-state-disabled":"")+(bb&&!G?"":" "+ba[1]+(Y.getTime()==k.getTime()?" "+this._currentClass:"")+(Y.getTime()==b.getTime()?" ui-datepicker-today":""))+'"'+((!bb||G)&&ba[2]?' title="'+ba[2]+'"':"")+(bc?"":' onclick="DP_jQuery_'+dpuuid+".datepicker._selectDay('#"+a.id+"',"+Y.getMonth()+","+Y.getFullYear()+', this);return false;"')+">"+(bb&&!G?"&#xa0;":bc?'<span class="ui-state-default">'+Y.getDate()+"</span>":'<a class="ui-state-default'+(Y.getTime()==b.getTime()?" ui-state-highlight":"")+(Y.getTime()==k.getTime()?" ui-state-active":"")+(bb?" ui-priority-secondary":"")+'" href="#">'+Y.getDate()+"</a>")+"</td>",Y.setDate(Y.getDate()+1),Y=this._daylightSavingAdjust(Y)}Q+=_+"</tr>"}n++,n>11&&(n=0,o++),Q+="</tbody></table>"+(j?"</div>"+(g[0]>0&&N==g[1]-1?'<div class="ui-datepicker-row-break"></div>':""):""),M+=Q}K+=M}return K+=x+($.browser.msie&&parseInt($.browser.version,10)<7&&!a.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>':""),a._keyEvent=!1,K},_generateMonthYearHeader:function(a,b,c,d,e,f,g,h){var i=this._get(a,"changeMonth"),j=this._get(a,"changeYear"),k=this._get(a,"showMonthAfterYear"),l='<div class="ui-datepicker-title">',m="";if(f||!i)m+='<span class="ui-datepicker-month">'+g[b]+"</span>";else{var n=d&&d.getFullYear()==c,o=e&&e.getFullYear()==c;m+='<select class="ui-datepicker-month" onchange="DP_jQuery_'+dpuuid+".datepicker._selectMonthYear('#"+a.id+"', this, 'M');\" "+">";for(var p=0;p<12;p++)(!n||p>=d.getMonth())&&(!o||p<=e.getMonth())&&(m+='<option value="'+p+'"'+(p==b?' selected="selected"':"")+">"+h[p]+"</option>");m+="</select>"}k||(l+=m+(f||!i||!j?"&#xa0;":""));if(!a.yearshtml){a.yearshtml="";if(f||!j)l+='<span class="ui-datepicker-year">'+c+"</span>";else{var q=this._get(a,"yearRange").split(":"),r=(new Date).getFullYear(),s=function(a){var b=a.match(/c[+-].*/)?c+parseInt(a.substring(1),10):a.match(/[+-].*/)?r+parseInt(a,10):parseInt(a,10);return isNaN(b)?r:b},t=s(q[0]),u=Math.max(t,s(q[1]||""));t=d?Math.max(t,d.getFullYear()):t,u=e?Math.min(u,e.getFullYear()):u,a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+dpuuid+".datepicker._selectMonthYear('#"+a.id+"', this, 'Y');\" "+">";for(;t<=u;t++)a.yearshtml+='<option value="'+t+'"'+(t==c?' selected="selected"':"")+">"+t+"</option>";a.yearshtml+="</select>",l+=a.yearshtml,a.yearshtml=null}}return l+=this._get(a,"yearSuffix"),k&&(l+=(f||!i||!j?"&#xa0;":"")+m),l+="</div>",l},_adjustInstDate:function(a,b,c){var d=a.drawYear+(c=="Y"?b:0),e=a.drawMonth+(c=="M"?b:0),f=Math.min(a.selectedDay,this._getDaysInMonth(d,e))+(c=="D"?b:0),g=this._restrictMinMax(a,this._daylightSavingAdjust(new Date(d,e,f)));a.selectedDay=g.getDate(),a.drawMonth=a.selectedMonth=g.getMonth(),a.drawYear=a.selectedYear=g.getFullYear(),(c=="M"||c=="Y")&&this._notifyChange(a)},_restrictMinMax:function(a,b){var c=this._getMinMaxDate(a,"min"),d=this._getMinMaxDate(a,"max"),e=c&&b<c?c:b;return e=d&&e>d?d:e,e},_notifyChange:function(a){var b=this._get(a,"onChangeMonthYear");b&&b.apply(a.input?a.input[0]:null,[a.selectedYear,a.selectedMonth+1,a])},_getNumberOfMonths:function(a){var b=this._get(a,"numberOfMonths");return b==null?[1,1]:typeof b=="number"?[1,b]:b},_getMinMaxDate:function(a,b){return this._determineDate(a,this._get(a,b+"Date"),null)},_getDaysInMonth:function(a,b){return 32-this._daylightSavingAdjust(new Date(a,b,32)).getDate()},_getFirstDayOfMonth:function(a,b){return(new Date(a,b,1)).getDay()},_canAdjustMonth:function(a,b,c,d){var e=this._getNumberOfMonths(a),f=this._daylightSavingAdjust(new Date(c,d+(b<0?b:e[0]*e[1]),1));return b<0&&f.setDate(this._getDaysInMonth(f.getFullYear(),f.getMonth())),this._isInRange(a,f)},_isInRange:function(a,b){var c=this._getMinMaxDate(a,"min"),d=this._getMinMaxDate(a,"max");return(!c||b.getTime()>=c.getTime())&&(!d||b.getTime()<=d.getTime())},_getFormatConfig:function(a){var b=this._get(a,"shortYearCutoff");return b=typeof b!="string"?b:(new Date).getFullYear()%100+parseInt(b,10),{shortYearCutoff:b,dayNamesShort:this._get(a,"dayNamesShort"),dayNames:this._get(a,"dayNames"),monthNamesShort:this._get(a,"monthNamesShort"),monthNames:this._get(a,"monthNames")}},_formatDate:function(a,b,c,d){b||(a.currentDay=a.selectedDay,a.currentMonth=a.selectedMonth,a.currentYear=a.selectedYear);var e=b?typeof b=="object"?b:this._daylightSavingAdjust(new Date(d,c,b)):this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return this.formatDate(this._get(a,"dateFormat"),e,this._getFormatConfig(a))}}),$.fn.datepicker=function(a){if(!this.length)return this;$.datepicker.initialized||($(document).mousedown($.datepicker._checkExternalClick).find("body").append($.datepicker.dpDiv),$.datepicker.initialized=!0);var b=Array.prototype.slice.call(arguments,1);return typeof a!="string"||a!="isDisabled"&&a!="getDate"&&a!="widget"?a=="option"&&arguments.length==2&&typeof arguments[1]=="string"?$.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this[0]].concat(b)):this.each(function(){typeof a=="string"?$.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this].concat(b)):$.datepicker._attachDatepicker(this,a)}):$.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this[0]].concat(b))},$.datepicker=new Datepicker,$.datepicker.initialized=!1,$.datepicker.uuid=(new Date).getTime(),$.datepicker.version="1.8.21",window["DP_jQuery_"+dpuuid]=$})(jQuery);;
\ No newline at end of file
+ * https://github.com/jquery/jquery-ui
+ * Includes: jquery.ui.core.js
+ * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
+(function (a, b) {
+    function c(b, c) {
+        var e = b.nodeName.toLowerCase();
+        if ("area" === e) {
+            var f = b.parentNode, g = f.name, h;
+            return!b.href || !g || f.nodeName.toLowerCase() !== "map" ? !1 : (h = a("img[usemap=#" + g + "]")[0], !!h && d(h))
+        }
+        return(/input|select|textarea|button|object/.test(e) ? !b.disabled : "a" == e ? b.href || c : c) && d(b)
+    }
+
+    function d(b) {
+        return!a(b).parents().andSelf().filter(function () {
+            return a.curCSS(this, "visibility") === "hidden" || a.expr.filters.hidden(this)
+        }).length
+    }
+
+    a.ui = a.ui || {};
+    if (a.ui.version)return;
+    a.extend(a.ui, {version: "1.8.21", keyCode: {ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91}}), a.fn.extend({propAttr: a.fn.prop || a.fn.attr, _focus: a.fn.focus, focus: function (b, c) {
+        return typeof b == "number" ? this.each(function () {
+            var d = this;
+            setTimeout(function () {
+                a(d).focus(), c && c.call(d)
+            }, b)
+        }) : this._focus.apply(this, arguments)
+    }, scrollParent: function () {
+        var b;
+        return a.browser.msie && /(static|relative)/.test(this.css("position")) || /absolute/.test(this.css("position")) ? b = this.parents().filter(function () {
+            return/(relative|absolute|fixed)/.test(a.curCSS(this, "position", 1)) && /(auto|scroll)/.test(a.curCSS(this, "overflow", 1) + a.curCSS(this, "overflow-y", 1) + a.curCSS(this, "overflow-x", 1))
+        }).eq(0) : b = this.parents().filter(function () {
+            return/(auto|scroll)/.test(a.curCSS(this, "overflow", 1) + a.curCSS(this, "overflow-y", 1) + a.curCSS(this, "overflow-x", 1))
+        }).eq(0), /fixed/.test(this.css("position")) || !b.length ? a(document) : b
+    }, zIndex: function (c) {
+        if (c !== b)return this.css("zIndex", c);
+        if (this.length) {
+            var d = a(this[0]), e, f;
+            while (d.length && d[0] !== document) {
+                e = d.css("position");
+                if (e === "absolute" || e === "relative" || e === "fixed") {
+                    f = parseInt(d.css("zIndex"), 10);
+                    if (!isNaN(f) && f !== 0)return f
+                }
+                d = d.parent()
+            }
+        }
+        return 0
+    }, disableSelection: function () {
+        return this.bind((a.support.selectstart ? "selectstart" : "mousedown") + ".ui-disableSelection", function (a) {
+            a.preventDefault()
+        })
+    }, enableSelection: function () {
+        return this.unbind(".ui-disableSelection")
+    }}), a.each(["Width", "Height"], function (c, d) {
+        function h(b, c, d, f) {
+            return a.each(e, function () {
+                c -= parseFloat(a.curCSS(b, "padding" + this, !0)) || 0, d && (c -= parseFloat(a.curCSS(b, "border" + this + "Width", !0)) || 0), f && (c -= parseFloat(a.curCSS(b, "margin" + this, !0)) || 0)
+            }), c
+        }
+
+        var e = d === "Width" ? ["Left", "Right"] : ["Top", "Bottom"], f = d.toLowerCase(), g = {innerWidth: a.fn.innerWidth, innerHeight: a.fn.innerHeight, outerWidth: a.fn.outerWidth, outerHeight: a.fn.outerHeight};
+        a.fn["inner" + d] = function (c) {
+            return c === b ? g["inner" + d].call(this) : this.each(function () {
+                a(this).css(f, h(this, c) + "px")
+            })
+        }, a.fn["outer" + d] = function (b, c) {
+            return typeof b != "number" ? g["outer" + d].call(this, b) : this.each(function () {
+                a(this).css(f, h(this, b, !0, c) + "px")
+            })
+        }
+    }), a.extend(a.expr[":"], {data: function (b, c, d) {
+        return!!a.data(b, d[3])
+    }, focusable: function (b) {
+        return c(b, !isNaN(a.attr(b, "tabindex")))
+    }, tabbable: function (b) {
+        var d = a.attr(b, "tabindex"), e = isNaN(d);
+        return(e || d >= 0) && c(b, !e)
+    }}), a(function () {
+        var b = document.body, c = b.appendChild(c = document.createElement("div"));
+        c.offsetHeight, a.extend(c.style, {minHeight: "100px", height: "auto", padding: 0, borderWidth: 0}), a.support.minHeight = c.offsetHeight === 100, a.support.selectstart = "onselectstart"in c, b.removeChild(c).style.display = "none"
+    }), a.extend(a.ui, {plugin: {add: function (b, c, d) {
+        var e = a.ui[b].prototype;
+        for (var f in d)e.plugins[f] = e.plugins[f] || [], e.plugins[f].push([c, d[f]])
+    }, call: function (a, b, c) {
+        var d = a.plugins[b];
+        if (!d || !a.element[0].parentNode)return;
+        for (var e = 0; e < d.length; e++)a.options[d[e][0]] && d[e][1].apply(a.element, c)
+    }}, contains: function (a, b) {
+        return document.compareDocumentPosition ? a.compareDocumentPosition(b) & 16 : a !== b && a.contains(b)
+    }, hasScroll: function (b, c) {
+        if (a(b).css("overflow") === "hidden")return!1;
+        var d = c && c === "left" ? "scrollLeft" : "scrollTop", e = !1;
+        return b[d] > 0 ? !0 : (b[d] = 1, e = b[d] > 0, b[d] = 0, e)
+    }, isOverAxis: function (a, b, c) {
+        return a > b && a < b + c
+    }, isOver: function (b, c, d, e, f, g) {
+        return a.ui.isOverAxis(b, d, f) && a.ui.isOverAxis(c, e, g)
+    }})
+})(jQuery);
+;
+/*! jQuery UI - v1.8.21 - 2012-06-05
+ * https://github.com/jquery/jquery-ui
+ * Includes: jquery.ui.widget.js
+ * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
+(function (a, b) {
+    if (a.cleanData) {
+        var c = a.cleanData;
+        a.cleanData = function (b) {
+            for (var d = 0, e; (e = b[d]) != null; d++)try {
+                a(e).triggerHandler("remove")
+            } catch (f) {
+            }
+            c(b)
+        }
+    } else {
+        var d = a.fn.remove;
+        a.fn.remove = function (b, c) {
+            return this.each(function () {
+                return c || (!b || a.filter(b, [this]).length) && a("*", this).add([this]).each(function () {
+                    try {
+                        a(this).triggerHandler("remove")
+                    } catch (b) {
+                    }
+                }), d.call(a(this), b, c)
+            })
+        }
+    }
+    a.widget = function (b, c, d) {
+        var e = b.split(".")[0], f;
+        b = b.split(".")[1], f = e + "-" + b, d || (d = c, c = a.Widget), a.expr[":"][f] = function (c) {
+            return!!a.data(c, b)
+        }, a[e] = a[e] || {}, a[e][b] = function (a, b) {
+            arguments.length && this._createWidget(a, b)
+        };
+        var g = new c;
+        g.options = a.extend(!0, {}, g.options), a[e][b].prototype = a.extend(!0, g, {namespace: e, widgetName: b, widgetEventPrefix: a[e][b].prototype.widgetEventPrefix || b, widgetBaseClass: f}, d), a.widget.bridge(b, a[e][b])
+    }, a.widget.bridge = function (c, d) {
+        a.fn[c] = function (e) {
+            var f = typeof e == "string", g = Array.prototype.slice.call(arguments, 1), h = this;
+            return e = !f && g.length ? a.extend.apply(null, [!0, e].concat(g)) : e, f && e.charAt(0) === "_" ? h : (f ? this.each(function () {
+                var d = a.data(this, c), f = d && a.isFunction(d[e]) ? d[e].apply(d, g) : d;
+                if (f !== d && f !== b)return h = f, !1
+            }) : this.each(function () {
+                var b = a.data(this, c);
+                b ? b.option(e || {})._init() : a.data(this, c, new d(e, this))
+            }), h)
+        }
+    }, a.Widget = function (a, b) {
+        arguments.length && this._createWidget(a, b)
+    }, a.Widget.prototype = {widgetName: "widget", widgetEventPrefix: "", options: {disabled: !1}, _createWidget: function (b, c) {
+        a.data(c, this.widgetName, this), this.element = a(c), this.options = a.extend(!0, {}, this.options, this._getCreateOptions(), b);
+        var d = this;
+        this.element.bind("remove." + this.widgetName, function () {
+            d.destroy()
+        }), this._create(), this._trigger("create"), this._init()
+    }, _getCreateOptions: function () {
+        return a.metadata && a.metadata.get(this.element[0])[this.widgetName]
+    }, _create: function () {
+    }, _init: function () {
+    }, destroy: function () {
+        this.element.unbind("." + this.widgetName).removeData(this.widgetName), this.widget().unbind("." + this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass + "-disabled " + "ui-state-disabled")
+    }, widget: function () {
+        return this.element
+    }, option: function (c, d) {
+        var e = c;
+        if (arguments.length === 0)return a.extend({}, this.options);
+        if (typeof c == "string") {
+            if (d === b)return this.options[c];
+            e = {}, e[c] = d
+        }
+        return this._setOptions(e), this
+    }, _setOptions: function (b) {
+        var c = this;
+        return a.each(b, function (a, b) {
+            c._setOption(a, b)
+        }), this
+    }, _setOption: function (a, b) {
+        return this.options[a] = b, a === "disabled" && this.widget()[b ? "addClass" : "removeClass"](this.widgetBaseClass + "-disabled" + " " + "ui-state-disabled").attr("aria-disabled", b), this
+    }, enable: function () {
+        return this._setOption("disabled", !1)
+    }, disable: function () {
+        return this._setOption("disabled", !0)
+    }, _trigger: function (b, c, d) {
+        var e, f, g = this.options[b];
+        d = d || {}, c = a.Event(c), c.type = (b === this.widgetEventPrefix ? b : this.widgetEventPrefix + b).toLowerCase(), c.target = this.element[0], f = c.originalEvent;
+        if (f)for (e in f)e in c || (c[e] = f[e]);
+        return this.element.trigger(c, d), !(a.isFunction(g) && g.call(this.element[0], c, d) === !1 || c.isDefaultPrevented())
+    }}
+})(jQuery);
+;
+/*! jQuery UI - v1.8.21 - 2012-06-05
+ * https://github.com/jquery/jquery-ui
+ * Includes: jquery.ui.mouse.js
+ * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
+(function (a, b) {
+    var c = !1;
+    a(document).mouseup(function (a) {
+        c = !1
+    }), a.widget("ui.mouse", {options: {cancel: ":input,option", distance: 1, delay: 0}, _mouseInit: function () {
+        var b = this;
+        this.element.bind("mousedown." + this.widgetName,function (a) {
+            return b._mouseDown(a)
+        }).bind("click." + this.widgetName, function (c) {
+            if (!0 === a.data(c.target, b.widgetName + ".preventClickEvent"))return a.removeData(c.target, b.widgetName + ".preventClickEvent"), c.stopImmediatePropagation(), !1
+        }), this.started = !1
+    }, _mouseDestroy: function () {
+        this.element.unbind("." + this.widgetName), a(document).unbind("mousemove." + this.widgetName, this._mouseMoveDelegate).unbind("mouseup." + this.widgetName, this._mouseUpDelegate)
+    }, _mouseDown: function (b) {
+        if (c)return;
+        this._mouseStarted && this._mouseUp(b), this._mouseDownEvent = b;
+        var d = this, e = b.which == 1, f = typeof this.options.cancel == "string" && b.target.nodeName ? a(b.target).closest(this.options.cancel).length : !1;
+        if (!e || f || !this._mouseCapture(b))return!0;
+        this.mouseDelayMet = !this.options.delay, this.mouseDelayMet || (this._mouseDelayTimer = setTimeout(function () {
+            d.mouseDelayMet = !0
+        }, this.options.delay));
+        if (this._mouseDistanceMet(b) && this._mouseDelayMet(b)) {
+            this._mouseStarted = this._mouseStart(b) !== !1;
+            if (!this._mouseStarted)return b.preventDefault(), !0
+        }
+        return!0 === a.data(b.target, this.widgetName + ".preventClickEvent") && a.removeData(b.target, this.widgetName + ".preventClickEvent"), this._mouseMoveDelegate = function (a) {
+            return d._mouseMove(a)
+        }, this._mouseUpDelegate = function (a) {
+            return d._mouseUp(a)
+        }, a(document).bind("mousemove." + this.widgetName, this._mouseMoveDelegate).bind("mouseup." + this.widgetName, this._mouseUpDelegate), b.preventDefault(), c = !0, !0
+    }, _mouseMove: function (b) {
+        return!a.browser.msie || document.documentMode >= 9 || !!b.button ? this._mouseStarted ? (this._mouseDrag(b), b.preventDefault()) : (this._mouseDistanceMet(b) && this._mouseDelayMet(b) && (this._mouseStarted = this._mouseStart(this._mouseDownEvent, b) !== !1, this._mouseStarted ? this._mouseDrag(b) : this._mouseUp(b)), !this._mouseStarted) : this._mouseUp(b)
+    }, _mouseUp: function (b) {
+        return a(document).unbind("mousemove." + this.widgetName, this._mouseMoveDelegate).unbind("mouseup." + this.widgetName, this._mouseUpDelegate), this._mouseStarted && (this._mouseStarted = !1, b.target == this._mouseDownEvent.target && a.data(b.target, this.widgetName + ".preventClickEvent", !0), this._mouseStop(b)), !1
+    }, _mouseDistanceMet: function (a) {
+        return Math.max(Math.abs(this._mouseDownEvent.pageX - a.pageX), Math.abs(this._mouseDownEvent.pageY - a.pageY)) >= this.options.distance
+    }, _mouseDelayMet: function (a) {
+        return this.mouseDelayMet
+    }, _mouseStart: function (a) {
+    }, _mouseDrag: function (a) {
+    }, _mouseStop: function (a) {
+    }, _mouseCapture: function (a) {
+        return!0
+    }})
+})(jQuery);
+;
+/*! jQuery UI - v1.8.21 - 2012-06-05
+ * https://github.com/jquery/jquery-ui
+ * Includes: jquery.ui.position.js
+ * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
+(function (a, b) {
+    a.ui = a.ui || {};
+    var c = /left|center|right/, d = /top|center|bottom/, e = "center", f = {}, g = a.fn.position, h = a.fn.offset;
+    a.fn.position = function (b) {
+        if (!b || !b.of)return g.apply(this, arguments);
+        b = a.extend({}, b);
+        var h = a(b.of), i = h[0], j = (b.collision || "flip").split(" "), k = b.offset ? b.offset.split(" ") : [0, 0], l, m, n;
+        return i.nodeType === 9 ? (l = h.width(), m = h.height(), n = {top: 0, left: 0}) : i.setTimeout ? (l = h.width(), m = h.height(), n = {top: h.scrollTop(), left: h.scrollLeft()}) : i.preventDefault ? (b.at = "left top", l = m = 0, n = {top: b.of.pageY, left: b.of.pageX}) : (l = h.outerWidth(), m = h.outerHeight(), n = h.offset()), a.each(["my", "at"], function () {
+            var a = (b[this] || "").split(" ");
+            a.length === 1 && (a = c.test(a[0]) ? a.concat([e]) : d.test(a[0]) ? [e].concat(a) : [e, e]), a[0] = c.test(a[0]) ? a[0] : e, a[1] = d.test(a[1]) ? a[1] : e, b[this] = a
+        }), j.length === 1 && (j[1] = j[0]), k[0] = parseInt(k[0], 10) || 0, k.length === 1 && (k[1] = k[0]), k[1] = parseInt(k[1], 10) || 0, b.at[0] === "right" ? n.left += l : b.at[0] === e && (n.left += l / 2), b.at[1] === "bottom" ? n.top += m : b.at[1] === e && (n.top += m / 2), n.left += k[0], n.top += k[1], this.each(function () {
+            var c = a(this), d = c.outerWidth(), g = c.outerHeight(), h = parseInt(a.curCSS(this, "marginLeft", !0)) || 0, i = parseInt(a.curCSS(this, "marginTop", !0)) || 0, o = d + h + (parseInt(a.curCSS(this, "marginRight", !0)) || 0), p = g + i + (parseInt(a.curCSS(this, "marginBottom", !0)) || 0), q = a.extend({}, n), r;
+            b.my[0] === "right" ? q.left -= d : b.my[0] === e && (q.left -= d / 2), b.my[1] === "bottom" ? q.top -= g : b.my[1] === e && (q.top -= g / 2), f.fractions || (q.left = Math.round(q.left), q.top = Math.round(q.top)), r = {left: q.left - h, top: q.top - i}, a.each(["left", "top"], function (c, e) {
+                a.ui.position[j[c]] && a.ui.position[j[c]][e](q, {targetWidth: l, targetHeight: m, elemWidth: d, elemHeight: g, collisionPosition: r, collisionWidth: o, collisionHeight: p, offset: k, my: b.my, at: b.at})
+            }), a.fn.bgiframe && c.bgiframe(), c.offset(a.extend(q, {using: b.using}))
+        })
+    }, a.ui.position = {fit: {left: function (b, c) {
+        var d = a(window), e = c.collisionPosition.left + c.collisionWidth - d.width() - d.scrollLeft();
+        b.left = e > 0 ? b.left - e : Math.max(b.left - c.collisionPosition.left, b.left)
+    }, top: function (b, c) {
+        var d = a(window), e = c.collisionPosition.top + c.collisionHeight - d.height() - d.scrollTop();
+        b.top = e > 0 ? b.top - e : Math.max(b.top - c.collisionPosition.top, b.top)
+    }}, flip: {left: function (b, c) {
+        if (c.at[0] === e)return;
+        var d = a(window), f = c.collisionPosition.left + c.collisionWidth - d.width() - d.scrollLeft(), g = c.my[0] === "left" ? -c.elemWidth : c.my[0] === "right" ? c.elemWidth : 0, h = c.at[0] === "left" ? c.targetWidth : -c.targetWidth, i = -2 * c.offset[0];
+        b.left += c.collisionPosition.left < 0 ? g + h + i : f > 0 ? g + h + i : 0
+    }, top: function (b, c) {
+        if (c.at[1] === e)return;
+        var d = a(window), f = c.collisionPosition.top + c.collisionHeight - d.height() - d.scrollTop(), g = c.my[1] === "top" ? -c.elemHeight : c.my[1] === "bottom" ? c.elemHeight : 0, h = c.at[1] === "top" ? c.targetHeight : -c.targetHeight, i = -2 * c.offset[1];
+        b.top += c.collisionPosition.top < 0 ? g + h + i : f > 0 ? g + h + i : 0
+    }}}, a.offset.setOffset || (a.offset.setOffset = function (b, c) {
+        /static/.test(a.curCSS(b, "position")) && (b.style.position = "relative");
+        var d = a(b), e = d.offset(), f = parseInt(a.curCSS(b, "top", !0), 10) || 0, g = parseInt(a.curCSS(b, "left", !0), 10) || 0, h = {top: c.top - e.top + f, left: c.left - e.left + g};
+        "using"in c ? c.using.call(b, h) : d.css(h)
+    }, a.fn.offset = function (b) {
+        var c = this[0];
+        return!c || !c.ownerDocument ? null : b ? a.isFunction(b) ? this.each(function (c) {
+            a(this).offset(b.call(this, c, a(this).offset()))
+        }) : this.each(function () {
+            a.offset.setOffset(this, b)
+        }) : h.call(this)
+    }), function () {
+        var b = document.getElementsByTagName("body")[0], c = document.createElement("div"), d, e, g, h, i;
+        d = document.createElement(b ? "div" : "body"), g = {visibility: "hidden", width: 0, height: 0, border: 0, margin: 0, background: "none"}, b && a.extend(g, {position: "absolute", left: "-1000px", top: "-1000px"});
+        for (var j in g)d.style[j] = g[j];
+        d.appendChild(c), e = b || document.documentElement, e.insertBefore(d, e.firstChild), c.style.cssText = "position: absolute; left: 10.7432222px; top: 10.432325px; height: 30px; width: 201px;", h = a(c).offset(function (a, b) {
+            return b
+        }).offset(), d.innerHTML = "", e.removeChild(d), i = h.top + h.left + (b ? 2e3 : 0), f.fractions = i > 21 && i < 22
+    }()
+})(jQuery);
+;
+/*! jQuery UI - v1.8.21 - 2012-06-05
+ * https://github.com/jquery/jquery-ui
+ * Includes: jquery.ui.draggable.js
+ * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
+(function (a, b) {
+    a.widget("ui.draggable", a.ui.mouse, {widgetEventPrefix: "drag", options: {addClasses: !0, appendTo: "parent", axis: !1, connectToSortable: !1, containment: !1, cursor: "auto", cursorAt: !1, grid: !1, handle: !1, helper: "original", iframeFix: !1, opacity: !1, refreshPositions: !1, revert: !1, revertDuration: 500, scope: "default", scroll: !0, scrollSensitivity: 20, scrollSpeed: 20, snap: !1, snapMode: "both", snapTolerance: 20, stack: !1, zIndex: !1}, _create: function () {
+        this.options.helper == "original" && !/^(?:r|a|f)/.test(this.element.css("position")) && (this.element[0].style.position = "relative"), this.options.addClasses && this.element.addClass("ui-draggable"), this.options.disabled && this.element.addClass("ui-draggable-disabled"), this._mouseInit()
+    }, destroy: function () {
+        if (!this.element.data("draggable"))return;
+        return this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"), this._mouseDestroy(), this
+    }, _mouseCapture: function (b) {
+        var c = this.options;
+        return this.helper || c.disabled || a(b.target).is(".ui-resizable-handle") ? !1 : (this.handle = this._getHandle(b), this.handle ? (c.iframeFix && a(c.iframeFix === !0 ? "iframe" : c.iframeFix).each(function () {
+            a('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width: this.offsetWidth + "px", height: this.offsetHeight + "px", position: "absolute", opacity: "0.001", zIndex: 1e3}).css(a(this).offset()).appendTo("body")
+        }), !0) : !1)
+    }, _mouseStart: function (b) {
+        var c = this.options;
+        return this.helper = this._createHelper(b), this.helper.addClass("ui-draggable-dragging"), this._cacheHelperProportions(), a.ui.ddmanager && (a.ui.ddmanager.current = this), this._cacheMargins(), this.cssPosition = this.helper.css("position"), this.scrollParent = this.helper.scrollParent(), this.offset = this.positionAbs = this.element.offset(), this.offset = {top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left}, a.extend(this.offset, {click: {left: b.pageX - this.offset.left, top: b.pageY - this.offset.top}, parent: this._getParentOffset(), relative: this._getRelativeOffset()}), this.originalPosition = this.position = this._generatePosition(b), this.originalPageX = b.pageX, this.originalPageY = b.pageY, c.cursorAt && this._adjustOffsetFromHelper(c.cursorAt), c.containment && this._setContainment(), this._trigger("start", b) === !1 ? (this._clear(), !1) : (this._cacheHelperProportions(), a.ui.ddmanager && !c.dropBehaviour && a.ui.ddmanager.prepareOffsets(this, b), this._mouseDrag(b, !0), a.ui.ddmanager && a.ui.ddmanager.dragStart(this, b), !0)
+    }, _mouseDrag: function (b, c) {
+        this.position = this._generatePosition(b), this.positionAbs = this._convertPositionTo("absolute");
+        if (!c) {
+            var d = this._uiHash();
+            if (this._trigger("drag", b, d) === !1)return this._mouseUp({}), !1;
+            this.position = d.position
+        }
+        if (!this.options.axis || this.options.axis != "y")this.helper[0].style.left = this.position.left + "px";
+        if (!this.options.axis || this.options.axis != "x")this.helper[0].style.top = this.position.top + "px";
+        return a.ui.ddmanager && a.ui.ddmanager.drag(this, b), !1
+    }, _mouseStop: function (b) {
+        var c = !1;
+        a.ui.ddmanager && !this.options.dropBehaviour && (c = a.ui.ddmanager.drop(this, b)), this.dropped && (c = this.dropped, this.dropped = !1);
+        var d = this.element[0], e = !1;
+        while (d && (d = d.parentNode))d == document && (e = !0);
+        if (!e && this.options.helper === "original")return!1;
+        if (this.options.revert == "invalid" && !c || this.options.revert == "valid" && c || this.options.revert === !0 || a.isFunction(this.options.revert) && this.options.revert.call(this.element, c)) {
+            var f = this;
+            a(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function () {
+                f._trigger("stop", b) !== !1 && f._clear()
+            })
+        } else this._trigger("stop", b) !== !1 && this._clear();
+        return!1
+    }, _mouseUp: function (b) {
+        return this.options.iframeFix === !0 && a("div.ui-draggable-iframeFix").each(function () {
+            this.parentNode.removeChild(this)
+        }), a.ui.ddmanager && a.ui.ddmanager.dragStop(this, b), a.ui.mouse.prototype._mouseUp.call(this, b)
+    }, cancel: function () {
+        return this.helper.is(".ui-draggable-dragging") ? this._mouseUp({}) : this._clear(), this
+    }, _getHandle: function (b) {
+        var c = !this.options.handle || !a(this.options.handle, this.element).length ? !0 : !1;
+        return a(this.options.handle, this.element).find("*").andSelf().each(function () {
+            this == b.target && (c = !0)
+        }), c
+    }, _createHelper: function (b) {
+        var c = this.options, d = a.isFunction(c.helper) ? a(c.helper.apply(this.element[0], [b])) : c.helper == "clone" ? this.element.clone().removeAttr("id") : this.element;
+        return d.parents("body").length || d.appendTo(c.appendTo == "parent" ? this.element[0].parentNode : c.appendTo), d[0] != this.element[0] && !/(fixed|absolute)/.test(d.css("position")) && d.css("position", "absolute"), d
+    }, _adjustOffsetFromHelper: function (b) {
+        typeof b == "string" && (b = b.split(" ")), a.isArray(b) && (b = {left: +b[0], top: +b[1] || 0}), "left"in b && (this.offset.click.left = b.left + this.margins.left), "right"in b && (this.offset.click.left = this.helperProportions.width - b.right + this.margins.left), "top"in b && (this.offset.click.top = b.top + this.margins.top), "bottom"in b && (this.offset.click.top = this.helperProportions.height - b.bottom + this.margins.top)
+    }, _getParentOffset: function () {
+        this.offsetParent = this.helper.offsetParent();
+        var b = this.offsetParent.offset();
+        this.cssPosition == "absolute" && this.scrollParent[0] != document && a.ui.contains(this.scrollParent[0], this.offsetParent[0]) && (b.left += this.scrollParent.scrollLeft(), b.top += this.scrollParent.scrollTop());
+        if (this.offsetParent[0] == document.body || this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == "html" && a.browser.msie)b = {top: 0, left: 0};
+        return{top: b.top + (parseInt(this.offsetParent.css("borderTopWidth"), 10) || 0), left: b.left + (parseInt(this.offsetParent.css("borderLeftWidth"), 10) || 0)}
+    }, _getRelativeOffset: function () {
+        if (this.cssPosition == "relative") {
+            var a = this.element.position();
+            return{top: a.top - (parseInt(this.helper.css("top"), 10) || 0) + this.scrollParent.scrollTop(), left: a.left - (parseInt(this.helper.css("left"), 10) || 0) + this.scrollParent.scrollLeft()}
+        }
+        return{top: 0, left: 0}
+    }, _cacheMargins: function () {
+        this.margins = {left: parseInt(this.element.css("marginLeft"), 10) || 0, top: parseInt(this.element.css("marginTop"), 10) || 0, right: parseInt(this.element.css("marginRight"), 10) || 0, bottom: parseInt(this.element.css("marginBottom"), 10) || 0}
+    }, _cacheHelperProportions: function () {
+        this.helperProportions = {width: this.helper.outerWidth(), height: this.helper.outerHeight()}
+    }, _setContainment: function () {
+        var b = this.options;
+        b.containment == "parent" && (b.containment = this.helper[0].parentNode);
+        if (b.containment == "document" || b.containment == "window")this.containment = [b.containment == "document" ? 0 : a(window).scrollLeft() - this.offset.relative.left - this.offset.parent.left, b.containment == "document" ? 0 : a(window).scrollTop() - this.offset.relative.top - this.offset.parent.top, (b.containment == "document" ? 0 : a(window).scrollLeft()) + a(b.containment == "document" ? document : window).width() - this.helperProportions.width - this.margins.left, (b.containment == "document" ? 0 : a(window).scrollTop()) + (a(b.containment == "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top];
+        if (!/^(document|window|parent)$/.test(b.containment) && b.containment.constructor != Array) {
+            var c = a(b.containment), d = c[0];
+            if (!d)return;
+            var e = c.offset(), f = a(d).css("overflow") != "hidden";
+            this.containment = [(parseInt(a(d).css("borderLeftWidth"), 10) || 0) + (parseInt(a(d).css("paddingLeft"), 10) || 0), (parseInt(a(d).css("borderTopWidth"), 10) || 0) + (parseInt(a(d).css("paddingTop"), 10) || 0), (f ? Math.max(d.scrollWidth, d.offsetWidth) : d.offsetWidth) - (parseInt(a(d).css("borderLeftWidth"), 10) || 0) - (parseInt(a(d).css("paddingRight"), 10) || 0) - this.helperProportions.width - this.margins.left - this.margins.right, (f ? Math.max(d.scrollHeight, d.offsetHeight) : d.offsetHeight) - (parseInt(a(d).css("borderTopWidth"), 10) || 0) - (parseInt(a(d).css("paddingBottom"), 10) || 0) - this.helperProportions.height - this.margins.top - this.margins.bottom], this.relative_container = c
+        } else b.containment.constructor == Array && (this.containment = b.containment)
+    }, _convertPositionTo: function (b, c) {
+        c || (c = this.position);
+        var d = b == "absolute" ? 1 : -1, e = this.options, f = this.cssPosition == "absolute" && (this.scrollParent[0] == document || !a.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, g = /(html|body)/i.test(f[0].tagName);
+        return{top: c.top + this.offset.relative.top * d + this.offset.parent.top * d - (a.browser.safari && a.browser.version < 526 && this.cssPosition == "fixed" ? 0 : (this.cssPosition == "fixed" ? -this.scrollParent.scrollTop() : g ? 0 : f.scrollTop()) * d), left: c.left + this.offset.relative.left * d + this.offset.parent.left * d - (a.browser.safari && a.browser.version < 526 && this.cssPosition == "fixed" ? 0 : (this.cssPosition == "fixed" ? -this.scrollParent.scrollLeft() : g ? 0 : f.scrollLeft()) * d)}
+    }, _generatePosition: function (b) {
+        var c = this.options, d = this.cssPosition == "absolute" && (this.scrollParent[0] == document || !a.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, e = /(html|body)/i.test(d[0].tagName), f = b.pageX, g = b.pageY;
+        if (this.originalPosition) {
+            var h;
+            if (this.containment) {
+                if (this.relative_container) {
+                    var i = this.relative_container.offset();
+                    h = [this.containment[0] + i.left, this.containment[1] + i.top, this.containment[2] + i.left, this.containment[3] + i.top]
+                } else h = this.containment;
+                b.pageX - this.offset.click.left < h[0] && (f = h[0] + this.offset.click.left), b.pageY - this.offset.click.top < h[1] && (g = h[1] + this.offset.click.top), b.pageX - this.offset.click.left > h[2] && (f = h[2] + this.offset.click.left), b.pageY - this.offset.click.top > h[3] && (g = h[3] + this.offset.click.top)
+            }
+            if (c.grid) {
+                var j = c.grid[1] ? this.originalPageY + Math.round((g - this.originalPageY) / c.grid[1]) * c.grid[1] : this.originalPageY;
+                g = h ? j - this.offset.click.top < h[1] || j - this.offset.click.top > h[3] ? j - this.offset.click.top < h[1] ? j + c.grid[1] : j - c.grid[1] : j : j;
+                var k = c.grid[0] ? this.originalPageX + Math.round((f - this.originalPageX) / c.grid[0]) * c.grid[0] : this.originalPageX;
+                f = h ? k - this.offset.click.left < h[0] || k - this.offset.click.left > h[2] ? k - this.offset.click.left < h[0] ? k + c.grid[0] : k - c.grid[0] : k : k
+            }
+        }
+        return{top: g - this.offset.click.top - this.offset.relative.top - this.offset.parent.top + (a.browser.safari && a.browser.version < 526 && this.cssPosition == "fixed" ? 0 : this.cssPosition == "fixed" ? -this.scrollParent.scrollTop() : e ? 0 : d.scrollTop()), left: f - this.offset.click.left - this.offset.relative.left - this.offset.parent.left + (a.browser.safari && a.browser.version < 526 && this.cssPosition == "fixed" ? 0 : this.cssPosition == "fixed" ? -this.scrollParent.scrollLeft() : e ? 0 : d.scrollLeft())}
+    }, _clear: function () {
+        this.helper.removeClass("ui-draggable-dragging"), this.helper[0] != this.element[0] && !this.cancelHelperRemoval && this.helper.remove(), this.helper = null, this.cancelHelperRemoval = !1
+    }, _trigger: function (b, c, d) {
+        return d = d || this._uiHash(), a.ui.plugin.call(this, b, [c, d]), b == "drag" && (this.positionAbs = this._convertPositionTo("absolute")), a.Widget.prototype._trigger.call(this, b, c, d)
+    }, plugins: {}, _uiHash: function (a) {
+        return{helper: this.helper, position: this.position, originalPosition: this.originalPosition, offset: this.positionAbs}
+    }}), a.extend(a.ui.draggable, {version: "1.8.21"}), a.ui.plugin.add("draggable", "connectToSortable", {start: function (b, c) {
+        var d = a(this).data("draggable"), e = d.options, f = a.extend({}, c, {item: d.element});
+        d.sortables = [], a(e.connectToSortable).each(function () {
+            var c = a.data(this, "sortable");
+            c && !c.options.disabled && (d.sortables.push({instance: c, shouldRevert: c.options.revert}), c.refreshPositions(), c._trigger("activate", b, f))
+        })
+    }, stop: function (b, c) {
+        var d = a(this).data("draggable"), e = a.extend({}, c, {item: d.element});
+        a.each(d.sortables, function () {
+            this.instance.isOver ? (this.instance.isOver = 0, d.cancelHelperRemoval = !0, this.instance.cancelHelperRemoval = !1, this.shouldRevert && (this.instance.options.revert = !0), this.instance._mouseStop(b), this.instance.options.helper = this.instance.options._helper, d.options.helper == "original" && this.instance.currentItem.css({top: "auto", left: "auto"})) : (this.instance.cancelHelperRemoval = !1, this.instance._trigger("deactivate", b, e))
+        })
+    }, drag: function (b, c) {
+        var d = a(this).data("draggable"), e = this, f = function (b) {
+            var c = this.offset.click.top, d = this.offset.click.left, e = this.positionAbs.top, f = this.positionAbs.left, g = b.height, h = b.width, i = b.top, j = b.left;
+            return a.ui.isOver(e + c, f + d, i, j, g, h)
+        };
+        a.each(d.sortables, function (f) {
+            this.instance.positionAbs = d.positionAbs, this.instance.helperProportions = d.helperProportions, this.instance.offset.click = d.offset.click, this.instance._intersectsWith(this.instance.containerCache) ? (this.instance.isOver || (this.instance.isOver = 1, this.instance.currentItem = a(e).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item", !0), this.instance.options._helper = this.instance.options.helper, this.instance.options.helper = function () {
+                return c.helper[0]
+            }, b.target = this.instance.currentItem[0], this.instance._mouseCapture(b, !0), this.instance._mouseStart(b, !0, !0), this.instance.offset.click.top = d.offset.click.top, this.instance.offset.click.left = d.offset.click.left, this.instance.offset.parent.left -= d.offset.parent.left - this.instance.offset.parent.left, this.instance.offset.parent.top -= d.offset.parent.top - this.instance.offset.parent.top, d._trigger("toSortable", b), d.dropped = this.instance.element, d.currentItem = d.element, this.instance.fromOutside = d), this.instance.currentItem && this.instance._mouseDrag(b)) : this.instance.isOver && (this.instance.isOver = 0, this.instance.cancelHelperRemoval = !0, this.instance.options.revert = !1, this.instance._trigger("out", b, this.instance._uiHash(this.instance)), this.instance._mouseStop(b, !0), this.instance.options.helper = this.instance.options._helper, this.instance.currentItem.remove(), this.instance.placeholder && this.instance.placeholder.remove(), d._trigger("fromSortable", b), d.dropped = !1)
+        })
+    }}), a.ui.plugin.add("draggable", "cursor", {start: function (b, c) {
+        var d = a("body"), e = a(this).data("draggable").options;
+        d.css("cursor") && (e._cursor = d.css("cursor")), d.css("cursor", e.cursor)
+    }, stop: function (b, c) {
+        var d = a(this).data("draggable").options;
+        d._cursor && a("body").css("cursor", d._cursor)
+    }}), a.ui.plugin.add("draggable", "opacity", {start: function (b, c) {
+        var d = a(c.helper), e = a(this).data("draggable").options;
+        d.css("opacity") && (e._opacity = d.css("opacity")), d.css("opacity", e.opacity)
+    }, stop: function (b, c) {
+        var d = a(this).data("draggable").options;
+        d._opacity && a(c.helper).css("opacity", d._opacity)
+    }}), a.ui.plugin.add("draggable", "scroll", {start: function (b, c) {
+        var d = a(this).data("draggable");
+        d.scrollParent[0] != document && d.scrollParent[0].tagName != "HTML" && (d.overflowOffset = d.scrollParent.offset())
+    }, drag: function (b, c) {
+        var d = a(this).data("draggable"), e = d.options, f = !1;
+        if (d.scrollParent[0] != document && d.scrollParent[0].tagName != "HTML") {
+            if (!e.axis || e.axis != "x")d.overflowOffset.top + d.scrollParent[0].offsetHeight - b.pageY < e.scrollSensitivity ? d.scrollParent[0].scrollTop = f = d.scrollParent[0].scrollTop + e.scrollSpeed : b.pageY - d.overflowOffset.top < e.scrollSensitivity && (d.scrollParent[0].scrollTop = f = d.scrollParent[0].scrollTop - e.scrollSpeed);
+            if (!e.axis || e.axis != "y")d.overflowOffset.left + d.scrollParent[0].offsetWidth - b.pageX < e.scrollSensitivity ? d.scrollParent[0].scrollLeft = f = d.scrollParent[0].scrollLeft + e.scrollSpeed : b.pageX - d.overflowOffset.left < e.scrollSensitivity && (d.scrollParent[0].scrollLeft = f = d.scrollParent[0].scrollLeft - e.scrollSpeed)
+        } else {
+            if (!e.axis || e.axis != "x")b.pageY - a(document).scrollTop() < e.scrollSensitivity ? f = a(document).scrollTop(a(document).scrollTop() - e.scrollSpeed) : a(window).height() - (b.pageY - a(document).scrollTop()) < e.scrollSensitivity && (f = a(document).scrollTop(a(document).scrollTop() + e.scrollSpeed));
+            if (!e.axis || e.axis != "y")b.pageX - a(document).scrollLeft() < e.scrollSensitivity ? f = a(document).scrollLeft(a(document).scrollLeft() - e.scrollSpeed) : a(window).width() - (b.pageX - a(document).scrollLeft()) < e.scrollSensitivity && (f = a(document).scrollLeft(a(document).scrollLeft() + e.scrollSpeed))
+        }
+        f !== !1 && a.ui.ddmanager && !e.dropBehaviour && a.ui.ddmanager.prepareOffsets(d, b)
+    }}), a.ui.plugin.add("draggable", "snap", {start: function (b, c) {
+        var d = a(this).data("draggable"), e = d.options;
+        d.snapElements = [], a(e.snap.constructor != String ? e.snap.items || ":data(draggable)" : e.snap).each(function () {
+            var b = a(this), c = b.offset();
+            this != d.element[0] && d.snapElements.push({item: this, width: b.outerWidth(), height: b.outerHeight(), top: c.top, left: c.left})
+        })
+    }, drag: function (b, c) {
+        var d = a(this).data("draggable"), e = d.options, f = e.snapTolerance, g = c.offset.left, h = g + d.helperProportions.width, i = c.offset.top, j = i + d.helperProportions.height;
+        for (var k = d.snapElements.length - 1; k >= 0; k--) {
+            var l = d.snapElements[k].left, m = l + d.snapElements[k].width, n = d.snapElements[k].top, o = n + d.snapElements[k].height;
+            if (!(l - f < g && g < m + f && n - f < i && i < o + f || l - f < g && g < m + f && n - f < j && j < o + f || l - f < h && h < m + f && n - f < i && i < o + f || l - f < h && h < m + f && n - f < j && j < o + f)) {
+                d.snapElements[k].snapping && d.options.snap.release && d.options.snap.release.call(d.element, b, a.extend(d._uiHash(), {snapItem: d.snapElements[k].item})), d.snapElements[k].snapping = !1;
+                continue
+            }
+            if (e.snapMode != "inner") {
+                var p = Math.abs(n - j) <= f, q = Math.abs(o - i) <= f, r = Math.abs(l - h) <= f, s = Math.abs(m - g) <= f;
+                p && (c.position.top = d._convertPositionTo("relative", {top: n - d.helperProportions.height, left: 0}).top - d.margins.top), q && (c.position.top = d._convertPositionTo("relative", {top: o, left: 0}).top - d.margins.top), r && (c.position.left = d._convertPositionTo("relative", {top: 0, left: l - d.helperProportions.width}).left - d.margins.left), s && (c.position.left = d._convertPositionTo("relative", {top: 0, left: m}).left - d.margins.left)
+            }
+            var t = p || q || r || s;
+            if (e.snapMode != "outer") {
+                var p = Math.abs(n - i) <= f, q = Math.abs(o - j) <= f, r = Math.abs(l - g) <= f, s = Math.abs(m - h) <= f;
+                p && (c.position.top = d._convertPositionTo("relative", {top: n, left: 0}).top - d.margins.top), q && (c.position.top = d._convertPositionTo("relative", {top: o - d.helperProportions.height, left: 0}).top - d.margins.top), r && (c.position.left = d._convertPositionTo("relative", {top: 0, left: l}).left - d.margins.left), s && (c.position.left = d._convertPositionTo("relative", {top: 0, left: m - d.helperProportions.width}).left - d.margins.left)
+            }
+            !d.snapElements[k].snapping && (p || q || r || s || t) && d.options.snap.snap && d.options.snap.snap.call(d.element, b, a.extend(d._uiHash(), {snapItem: d.snapElements[k].item})), d.snapElements[k].snapping = p || q || r || s || t
+        }
+    }}), a.ui.plugin.add("draggable", "stack", {start: function (b, c) {
+        var d = a(this).data("draggable").options, e = a.makeArray(a(d.stack)).sort(function (b, c) {
+            return(parseInt(a(b).css("zIndex"), 10) || 0) - (parseInt(a(c).css("zIndex"), 10) || 0)
+        });
+        if (!e.length)return;
+        var f = parseInt(e[0].style.zIndex) || 0;
+        a(e).each(function (a) {
+            this.style.zIndex = f + a
+        }), this[0].style.zIndex = f + e.length
+    }}), a.ui.plugin.add("draggable", "zIndex", {start: function (b, c) {
+        var d = a(c.helper), e = a(this).data("draggable").options;
+        d.css("zIndex") && (e._zIndex = d.css("zIndex")), d.css("zIndex", e.zIndex)
+    }, stop: function (b, c) {
+        var d = a(this).data("draggable").options;
+        d._zIndex && a(c.helper).css("zIndex", d._zIndex)
+    }})
+})(jQuery);
+;
+/*! jQuery UI - v1.8.21 - 2012-06-05
+ * https://github.com/jquery/jquery-ui
+ * Includes: jquery.ui.resizable.js
+ * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
+(function (a, b) {
+    a.widget("ui.resizable", a.ui.mouse, {widgetEventPrefix: "resize", options: {alsoResize: !1, animate: !1, animateDuration: "slow", animateEasing: "swing", aspectRatio: !1, autoHide: !1, containment: !1, ghost: !1, grid: !1, handles: "e,s,se", helper: !1, maxHeight: null, maxWidth: null, minHeight: 10, minWidth: 10, zIndex: 1e3}, _create: function () {
+        var b = this, c = this.options;
+        this.element.addClass("ui-resizable"), a.extend(this, {_aspectRatio: !!c.aspectRatio, aspectRatio: c.aspectRatio, originalElement: this.element, _proportionallyResizeElements: [], _helper: c.helper || c.ghost || c.animate ? c.helper || "ui-resizable-helper" : null}), this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i) && (this.element.wrap(a('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position: this.element.css("position"), width: this.element.outerWidth(), height: this.element.outerHeight(), top: this.element.css("top"), left: this.element.css("left")})), this.element = this.element.parent().data("resizable", this.element.data("resizable")), this.elementIsWrapper = !0, this.element.css({marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom")}), this.originalElement.css({marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0}), this.originalResizeStyle = this.originalElement.css("resize"), this.originalElement.css("resize", "none"), this._proportionallyResizeElements.push(this.originalElement.css({position: "static", zoom: 1, display: "block"})), this.originalElement.css({margin: this.originalElement.css("margin")}), this._proportionallyResize()), this.handles = c.handles || (a(".ui-resizable-handle", this.element).length ? {n: ".ui-resizable-n", e: ".ui-resizable-e", s: ".ui-resizable-s", w: ".ui-resizable-w", se: ".ui-resizable-se", sw: ".ui-resizable-sw", ne: ".ui-resizable-ne", nw: ".ui-resizable-nw"} : "e,s,se");
+        if (this.handles.constructor == String) {
+            this.handles == "all" && (this.handles = "n,e,s,w,se,sw,ne,nw");
+            var d = this.handles.split(",");
+            this.handles = {};
+            for (var e = 0; e < d.length; e++) {
+                var f = a.trim(d[e]), g = "ui-resizable-" + f, h = a('<div class="ui-resizable-handle ' + g + '"></div>');
+                h.css({zIndex: c.zIndex}), "se" == f && h.addClass("ui-icon ui-icon-gripsmall-diagonal-se"), this.handles[f] = ".ui-resizable-" + f, this.element.append(h)
+            }
+        }
+        this._renderAxis = function (b) {
+            b = b || this.element;
+            for (var c in this.handles) {
+                this.handles[c].constructor == String && (this.handles[c] = a(this.handles[c], this.element).show());
+                if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) {
+                    var d = a(this.handles[c], this.element), e = 0;
+                    e = /sw|ne|nw|se|n|s/.test(c) ? d.outerHeight() : d.outerWidth();
+                    var f = ["padding", /ne|nw|n/.test(c) ? "Top" : /se|sw|s/.test(c) ? "Bottom" : /^e$/.test(c) ? "Right" : "Left"].join("");
+                    b.css(f, e), this._proportionallyResize()
+                }
+                if (!a(this.handles[c]).length)continue
+            }
+        }, this._renderAxis(this.element), this._handles = a(".ui-resizable-handle", this.element).disableSelection(), this._handles.mouseover(function () {
+            if (!b.resizing) {
+                if (this.className)var a = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
+                b.axis = a && a[1] ? a[1] : "se"
+            }
+        }), c.autoHide && (this._handles.hide(), a(this.element).addClass("ui-resizable-autohide").hover(function () {
+            if (c.disabled)return;
+            a(this).removeClass("ui-resizable-autohide"), b._handles.show()
+        }, function () {
+            if (c.disabled)return;
+            b.resizing || (a(this).addClass("ui-resizable-autohide"), b._handles.hide())
+        })), this._mouseInit()
+    }, destroy: function () {
+        this._mouseDestroy();
+        var b = function (b) {
+            a(b).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove()
+        };
+        if (this.elementIsWrapper) {
+            b(this.element);
+            var c = this.element;
+            c.after(this.originalElement.css({position: c.css("position"), width: c.outerWidth(), height: c.outerHeight(), top: c.css("top"), left: c.css("left")})).remove()
+        }
+        return this.originalElement.css("resize", this.originalResizeStyle), b(this.originalElement), this
+    }, _mouseCapture: function (b) {
+        var c = !1;
+        for (var d in this.handles)a(this.handles[d])[0] == b.target && (c = !0);
+        return!this.options.disabled && c
+    }, _mouseStart: function (b) {
+        var d = this.options, e = this.element.position(), f = this.element;
+        this.resizing = !0, this.documentScroll = {top: a(document).scrollTop(), left: a(document).scrollLeft()}, (f.is(".ui-draggable") || /absolute/.test(f.css("position"))) && f.css({position: "absolute", top: e.top, left: e.left}), this._renderProxy();
+        var g = c(this.helper.css("left")), h = c(this.helper.css("top"));
+        d.containment && (g += a(d.containment).scrollLeft() || 0, h += a(d.containment).scrollTop() || 0), this.offset = this.helper.offset(), this.position = {left: g, top: h}, this.size = this._helper ? {width: f.outerWidth(), height: f.outerHeight()} : {width: f.width(), height: f.height()}, this.originalSize = this._helper ? {width: f.outerWidth(), height: f.outerHeight()} : {width: f.width(), height: f.height()}, this.originalPosition = {left: g, top: h}, this.sizeDiff = {width: f.outerWidth() - f.width(), height: f.outerHeight() - f.height()}, this.originalMousePosition = {left: b.pageX, top: b.pageY}, this.aspectRatio = typeof d.aspectRatio == "number" ? d.aspectRatio : this.originalSize.width / this.originalSize.height || 1;
+        var i = a(".ui-resizable-" + this.axis).css("cursor");
+        return a("body").css("cursor", i == "auto" ? this.axis + "-resize" : i), f.addClass("ui-resizable-resizing"), this._propagate("start", b), !0
+    }, _mouseDrag: function (b) {
+        var c = this.helper, d = this.options, e = {}, f = this, g = this.originalMousePosition, h = this.axis, i = b.pageX - g.left || 0, j = b.pageY - g.top || 0, k = this._change[h];
+        if (!k)return!1;
+        var l = k.apply(this, [b, i, j]), m = a.browser.msie && a.browser.version < 7, n = this.sizeDiff;
+        this._updateVirtualBoundaries(b.shiftKey);
+        if (this._aspectRatio || b.shiftKey)l = this._updateRatio(l, b);
+        return l = this._respectSize(l, b), this._propagate("resize", b), c.css({top: this.position.top + "px", left: this.position.left + "px", width: this.size.width + "px", height: this.size.height + "px"}), !this._helper && this._proportionallyResizeElements.length && this._proportionallyResize(), this._updateCache(l), this._trigger("resize", b, this.ui()), !1
+    }, _mouseStop: function (b) {
+        this.resizing = !1;
+        var c = this.options, d = this;
+        if (this._helper) {
+            var e = this._proportionallyResizeElements, f = e.length && /textarea/i.test(e[0].nodeName), g = f && a.ui.hasScroll(e[0], "left") ? 0 : d.sizeDiff.height, h = f ? 0 : d.sizeDiff.width, i = {width: d.helper.width() - h, height: d.helper.height() - g}, j = parseInt(d.element.css("left"), 10) + (d.position.left - d.originalPosition.left) || null, k = parseInt(d.element.css("top"), 10) + (d.position.top - d.originalPosition.top) || null;
+            c.animate || this.element.css(a.extend(i, {top: k, left: j})), d.helper.height(d.size.height), d.helper.width(d.size.width), this._helper && !c.animate && this._proportionallyResize()
+        }
+        return a("body").css("cursor", "auto"), this.element.removeClass("ui-resizable-resizing"), this._propagate("stop", b), this._helper && this.helper.remove(), !1
+    }, _updateVirtualBoundaries: function (a) {
+        var b = this.options, c, e, f, g, h;
+        h = {minWidth: d(b.minWidth) ? b.minWidth : 0, maxWidth: d(b.maxWidth) ? b.maxWidth : Infinity, minHeight: d(b.minHeight) ? b.minHeight : 0, maxHeight: d(b.maxHeight) ? b.maxHeight : Infinity};
+        if (this._aspectRatio || a)c = h.minHeight * this.aspectRatio, f = h.minWidth / this.aspectRatio, e = h.maxHeight * this.aspectRatio, g = h.maxWidth / this.aspectRatio, c > h.minWidth && (h.minWidth = c), f > h.minHeight && (h.minHeight = f), e < h.maxWidth && (h.maxWidth = e), g < h.maxHeight && (h.maxHeight = g);
+        this._vBoundaries = h
+    }, _updateCache: function (a) {
+        var b = this.options;
+        this.offset = this.helper.offset(), d(a.left) && (this.position.left = a.left), d(a.top) && (this.position.top = a.top), d(a.height) && (this.size.height = a.height), d(a.width) && (this.size.width = a.width)
+    }, _updateRatio: function (a, b) {
+        var c = this.options, e = this.position, f = this.size, g = this.axis;
+        return d(a.height) ? a.width = a.height * this.aspectRatio : d(a.width) && (a.height = a.width / this.aspectRatio), g == "sw" && (a.left = e.left + (f.width - a.width), a.top = null), g == "nw" && (a.top = e.top + (f.height - a.height), a.left = e.left + (f.width - a.width)), a
+    }, _respectSize: function (a, b) {
+        var c = this.helper, e = this._vBoundaries, f = this._aspectRatio || b.shiftKey, g = this.axis, h = d(a.width) && e.maxWidth && e.maxWidth < a.width, i = d(a.height) && e.maxHeight && e.maxHeight < a.height, j = d(a.width) && e.minWidth && e.minWidth > a.width, k = d(a.height) && e.minHeight && e.minHeight > a.height;
+        j && (a.width = e.minWidth), k && (a.height = e.minHeight), h && (a.width = e.maxWidth), i && (a.height = e.maxHeight);
+        var l = this.originalPosition.left + this.originalSize.width, m = this.position.top + this.size.height, n = /sw|nw|w/.test(g), o = /nw|ne|n/.test(g);
+        j && n && (a.left = l - e.minWidth), h && n && (a.left = l - e.maxWidth), k && o && (a.top = m - e.minHeight), i && o && (a.top = m - e.maxHeight);
+        var p = !a.width && !a.height;
+        return p && !a.left && a.top ? a.top = null : p && !a.top && a.left && (a.left = null), a
+    }, _proportionallyResize: function () {
+        var b = this.options;
+        if (!this._proportionallyResizeElements.length)return;
+        var c = this.helper || this.element;
+        for (var d = 0; d < this._proportionallyResizeElements.length; d++) {
+            var e = this._proportionallyResizeElements[d];
+            if (!this.borderDif) {
+                var f = [e.css("borderTopWidth"), e.css("borderRightWidth"), e.css("borderBottomWidth"), e.css("borderLeftWidth")], g = [e.css("paddingTop"), e.css("paddingRight"), e.css("paddingBottom"), e.css("paddingLeft")];
+                this.borderDif = a.map(f, function (a, b) {
+                    var c = parseInt(a, 10) || 0, d = parseInt(g[b], 10) || 0;
+                    return c + d
+                })
+            }
+            if (!a.browser.msie || !a(c).is(":hidden") && !a(c).parents(":hidden").length)e.css({height: c.height() - this.borderDif[0] - this.borderDif[2] || 0, width: c.width() - this.borderDif[1] - this.borderDif[3] || 0}); else continue
+        }
+    }, _renderProxy: function () {
+        var b = this.element, c = this.options;
+        this.elementOffset = b.offset();
+        if (this._helper) {
+            this.helper = this.helper || a('<div style="overflow:hidden;"></div>');
+            var d = a.browser.msie && a.browser.version < 7, e = d ? 1 : 0, f = d ? 2 : -1;
+            this.helper.addClass(this._helper).css({width: this.element.outerWidth() + f, height: this.element.outerHeight() + f, position: "absolute", left: this.elementOffset.left - e + "px", top: this.elementOffset.top - e + "px", zIndex: ++c.zIndex}), this.helper.appendTo("body").disableSelection()
+        } else this.helper = this.element
+    }, _change: {e: function (a, b, c) {
+        return{width: this.originalSize.width + b}
+    }, w: function (a, b, c) {
+        var d = this.options, e = this.originalSize, f = this.originalPosition;
+        return{left: f.left + b, width: e.width - b}
+    }, n: function (a, b, c) {
+        var d = this.options, e = this.originalSize, f = this.originalPosition;
+        return{top: f.top + c, height: e.height - c}
+    }, s: function (a, b, c) {
+        return{height: this.originalSize.height + c}
+    }, se: function (b, c, d) {
+        return a.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [b, c, d]))
+    }, sw: function (b, c, d) {
+        return a.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [b, c, d]))
+    }, ne: function (b, c, d) {
+        return a.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [b, c, d]))
+    }, nw: function (b, c, d) {
+        return a.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [b, c, d]))
+    }}, _propagate: function (b, c) {
+        a.ui.plugin.call(this, b, [c, this.ui()]), b != "resize" && this._trigger(b, c, this.ui())
+    }, plugins: {}, ui: function () {
+        return{originalElement: this.originalElement, element: this.element, helper: this.helper, position: this.position, size: this.size, originalSize: this.originalSize, originalPosition: this.originalPosition}
+    }}), a.extend(a.ui.resizable, {version: "1.8.21"}), a.ui.plugin.add("resizable", "alsoResize", {start: function (b, c) {
+        var d = a(this).data("resizable"), e = d.options, f = function (b) {
+            a(b).each(function () {
+                var b = a(this);
+                b.data("resizable-alsoresize", {width: parseInt(b.width(), 10), height: parseInt(b.height(), 10), left: parseInt(b.css("left"), 10), top: parseInt(b.css("top"), 10)})
+            })
+        };
+        typeof e.alsoResize == "object" && !e.alsoResize.parentNode ? e.alsoResize.length ? (e.alsoResize = e.alsoResize[0], f(e.alsoResize)) : a.each(e.alsoResize, function (a) {
+            f(a)
+        }) : f(e.alsoResize)
+    }, resize: function (b, c) {
+        var d = a(this).data("resizable"), e = d.options, f = d.originalSize, g = d.originalPosition, h = {height: d.size.height - f.height || 0, width: d.size.width - f.width || 0, top: d.position.top - g.top || 0, left: d.position.left - g.left || 0}, i = function (b, d) {
+            a(b).each(function () {
+                var b = a(this), e = a(this).data("resizable-alsoresize"), f = {}, g = d && d.length ? d : b.parents(c.originalElement[0]).length ? ["width", "height"] : ["width", "height", "top", "left"];
+                a.each(g, function (a, b) {
+                    var c = (e[b] || 0) + (h[b] || 0);
+                    c && c >= 0 && (f[b] = c || null)
+                }), b.css(f)
+            })
+        };
+        typeof e.alsoResize == "object" && !e.alsoResize.nodeType ? a.each(e.alsoResize, function (a, b) {
+            i(a, b)
+        }) : i(e.alsoResize)
+    }, stop: function (b, c) {
+        a(this).removeData("resizable-alsoresize")
+    }}), a.ui.plugin.add("resizable", "animate", {stop: function (b, c) {
+        var d = a(this).data("resizable"), e = d.options, f = d._proportionallyResizeElements, g = f.length && /textarea/i.test(f[0].nodeName), h = g && a.ui.hasScroll(f[0], "left") ? 0 : d.sizeDiff.height, i = g ? 0 : d.sizeDiff.width, j = {width: d.size.width - i, height: d.size.height - h}, k = parseInt(d.element.css("left"), 10) + (d.position.left - d.originalPosition.left) || null, l = parseInt(d.element.css("top"), 10) + (d.position.top - d.originalPosition.top) || null;
+        d.element.animate(a.extend(j, l && k ? {top: l, left: k} : {}), {duration: e.animateDuration, easing: e.animateEasing, step: function () {
+            var c = {width: parseInt(d.element.css("width"), 10), height: parseInt(d.element.css("height"), 10), top: parseInt(d.element.css("top"), 10), left: parseInt(d.element.css("left"), 10)};
+            f && f.length && a(f[0]).css({width: c.width, height: c.height}), d._updateCache(c), d._propagate("resize", b)
+        }})
+    }}), a.ui.plugin.add("resizable", "containment", {start: function (b, d) {
+        var e = a(this).data("resizable"), f = e.options, g = e.element, h = f.containment, i = h instanceof a ? h.get(0) : /parent/.test(h) ? g.parent().get(0) : h;
+        if (!i)return;
+        e.containerElement = a(i);
+        if (/document/.test(h) || h == document)e.containerOffset = {left: 0, top: 0}, e.containerPosition = {left: 0, top: 0}, e.parentData = {element: a(document), left: 0, top: 0, width: a(document).width(), height: a(document).height() || document.body.parentNode.scrollHeight}; else {
+            var j = a(i), k = [];
+            a(["Top", "Right", "Left", "Bottom"]).each(function (a, b) {
+                k[a] = c(j.css("padding" + b))
+            }), e.containerOffset = j.offset(), e.containerPosition = j.position(), e.containerSize = {height: j.innerHeight() - k[3], width: j.innerWidth() - k[1]};
+            var l = e.containerOffset, m = e.containerSize.height, n = e.containerSize.width, o = a.ui.hasScroll(i, "left") ? i.scrollWidth : n, p = a.ui.hasScroll(i) ? i.scrollHeight : m;
+            e.parentData = {element: i, left: l.left, top: l.top, width: o, height: p}
+        }
+    }, resize: function (b, c) {
+        var d = a(this).data("resizable"), e = d.options, f = d.containerSize, g = d.containerOffset, h = d.size, i = d.position, j = d._aspectRatio || b.shiftKey, k = {top: 0, left: 0}, l = d.containerElement;
+        l[0] != document && /static/.test(l.css("position")) && (k = g), i.left < (d._helper ? g.left : 0) && (d.size.width = d.size.width + (d._helper ? d.position.left - g.left : d.position.left - k.left), j && (d.size.height = d.size.width / d.aspectRatio), d.position.left = e.helper ? g.left : 0), i.top < (d._helper ? g.top : 0) && (d.size.height = d.size.height + (d._helper ? d.position.top - g.top : d.position.top), j && (d.size.width = d.size.height * d.aspectRatio), d.position.top = d._helper ? g.top : 0), d.offset.left = d.parentData.left + d.position.left, d.offset.top = d.parentData.top + d.position.top;
+        var m = Math.abs((d._helper ? d.offset.left - k.left : d.offset.left - k.left) + d.sizeDiff.width), n = Math.abs((d._helper ? d.offset.top - k.top : d.offset.top - g.top) + d.sizeDiff.height), o = d.containerElement.get(0) == d.element.parent().get(0), p = /relative|absolute/.test(d.containerElement.css("position"));
+        o && p && (m -= d.parentData.left), m + d.size.width >= d.parentData.width && (d.size.width = d.parentData.width - m, j && (d.size.height = d.size.width / d.aspectRatio)), n + d.size.height >= d.parentData.height && (d.size.height = d.parentData.height - n, j && (d.size.width = d.size.height * d.aspectRatio))
+    }, stop: function (b, c) {
+        var d = a(this).data("resizable"), e = d.options, f = d.position, g = d.containerOffset, h = d.containerPosition, i = d.containerElement, j = a(d.helper), k = j.offset(), l = j.outerWidth() - d.sizeDiff.width, m = j.outerHeight() - d.sizeDiff.height;
+        d._helper && !e.animate && /relative/.test(i.css("position")) && a(this).css({left: k.left - h.left - g.left, width: l, height: m}), d._helper && !e.animate && /static/.test(i.css("position")) && a(this).css({left: k.left - h.left - g.left, width: l, height: m})
+    }}), a.ui.plugin.add("resizable", "ghost", {start: function (b, c) {
+        var d = a(this).data("resizable"), e = d.options, f = d.size;
+        d.ghost = d.originalElement.clone(), d.ghost.css({opacity: .25, display: "block", position: "relative", height: f.height, width: f.width, margin: 0, left: 0, top: 0}).addClass("ui-resizable-ghost").addClass(typeof e.ghost == "string" ? e.ghost : ""), d.ghost.appendTo(d.helper)
+    }, resize: function (b, c) {
+        var d = a(this).data("resizable"), e = d.options;
+        d.ghost && d.ghost.css({position: "relative", height: d.size.height, width: d.size.width})
+    }, stop: function (b, c) {
+        var d = a(this).data("resizable"), e = d.options;
+        d.ghost && d.helper && d.helper.get(0).removeChild(d.ghost.get(0))
+    }}), a.ui.plugin.add("resizable", "grid", {resize: function (b, c) {
+        var d = a(this).data("resizable"), e = d.options, f = d.size, g = d.originalSize, h = d.originalPosition, i = d.axis, j = e._aspectRatio || b.shiftKey;
+        e.grid = typeof e.grid == "number" ? [e.grid, e.grid] : e.grid;
+        var k = Math.round((f.width - g.width) / (e.grid[0] || 1)) * (e.grid[0] || 1), l = Math.round((f.height - g.height) / (e.grid[1] || 1)) * (e.grid[1] || 1);
+        /^(se|s|e)$/.test(i) ? (d.size.width = g.width + k, d.size.height = g.height + l) : /^(ne)$/.test(i) ? (d.size.width = g.width + k, d.size.height = g.height + l, d.position.top = h.top - l) : /^(sw)$/.test(i) ? (d.size.width = g.width + k, d.size.height = g.height + l, d.position.left = h.left - k) : (d.size.width = g.width + k, d.size.height = g.height + l, d.position.top = h.top - l, d.position.left = h.left - k)
+    }});
+    var c = function (a) {
+        return parseInt(a, 10) || 0
+    }, d = function (a) {
+        return!isNaN(parseInt(a, 10))
+    }
+})(jQuery);
+;
+/*! jQuery UI - v1.8.21 - 2012-06-05
+ * https://github.com/jquery/jquery-ui
+ * Includes: jquery.ui.sortable.js
+ * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
+(function (a, b) {
+    a.widget("ui.sortable", a.ui.mouse, {widgetEventPrefix: "sort", ready: !1, options: {appendTo: "parent", axis: !1, connectWith: !1, containment: !1, cursor: "auto", cursorAt: !1, dropOnEmpty: !0, forcePlaceholderSize: !1, forceHelperSize: !1, grid: !1, handle: !1, helper: "original", items: "> *", opacity: !1, placeholder: !1, revert: !1, scroll: !0, scrollSensitivity: 20, scrollSpeed: 20, scope: "default", tolerance: "intersect", zIndex: 1e3}, _create: function () {
+        var a = this.options;
+        this.containerCache = {}, this.element.addClass("ui-sortable"), this.refresh(), this.floating = this.items.length ? a.axis === "x" || /left|right/.test(this.items[0].item.css("float")) || /inline|table-cell/.test(this.items[0].item.css("display")) : !1, this.offset = this.element.offset(), this._mouseInit(), this.ready = !0
+    }, destroy: function () {
+        a.Widget.prototype.destroy.call(this), this.element.removeClass("ui-sortable ui-sortable-disabled"), this._mouseDestroy();
+        for (var b = this.items.length - 1; b >= 0; b--)this.items[b].item.removeData(this.widgetName + "-item");
+        return this
+    }, _setOption: function (b, c) {
+        b === "disabled" ? (this.options[b] = c, this.widget()[c ? "addClass" : "removeClass"]("ui-sortable-disabled")) : a.Widget.prototype._setOption.apply(this, arguments)
+    }, _mouseCapture: function (b, c) {
+        var d = this;
+        if (this.reverting)return!1;
+        if (this.options.disabled || this.options.type == "static")return!1;
+        this._refreshItems(b);
+        var e = null, f = this, g = a(b.target).parents().each(function () {
+            if (a.data(this, d.widgetName + "-item") == f)return e = a(this), !1
+        });
+        a.data(b.target, d.widgetName + "-item") == f && (e = a(b.target));
+        if (!e)return!1;
+        if (this.options.handle && !c) {
+            var h = !1;
+            a(this.options.handle, e).find("*").andSelf().each(function () {
+                this == b.target && (h = !0)
+            });
+            if (!h)return!1
+        }
+        return this.currentItem = e, this._removeCurrentsFromItems(), !0
+    }, _mouseStart: function (b, c, d) {
+        var e = this.options, f = this;
+        this.currentContainer = this, this.refreshPositions(), this.helper = this._createHelper(b), this._cacheHelperProportions(), this._cacheMargins(), this.scrollParent = this.helper.scrollParent(), this.offset = this.currentItem.offset(), this.offset = {top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left}, a.extend(this.offset, {click: {left: b.pageX - this.offset.left, top: b.pageY - this.offset.top}, parent: this._getParentOffset(), relative: this._getRelativeOffset()}), this.helper.css("position", "absolute"), this.cssPosition = this.helper.css("position"), this.originalPosition = this._generatePosition(b), this.originalPageX = b.pageX, this.originalPageY = b.pageY, e.cursorAt && this._adjustOffsetFromHelper(e.cursorAt), this.domPosition = {prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0]}, this.helper[0] != this.currentItem[0] && this.currentItem.hide(), this._createPlaceholder(), e.containment && this._setContainment(), e.cursor && (a("body").css("cursor") && (this._storedCursor = a("body").css("cursor")), a("body").css("cursor", e.cursor)), e.opacity && (this.helper.css("opacity") && (this._storedOpacity = this.helper.css("opacity")), this.helper.css("opacity", e.opacity)), e.zIndex && (this.helper.css("zIndex") && (this._storedZIndex = this.helper.css("zIndex")), this.helper.css("zIndex", e.zIndex)), this.scrollParent[0] != document && this.scrollParent[0].tagName != "HTML" && (this.overflowOffset = this.scrollParent.offset()), this._trigger("start", b, this._uiHash()), this._preserveHelperProportions || this._cacheHelperProportions();
+        if (!d)for (var g = this.containers.length - 1; g >= 0; g--)this.containers[g]._trigger("activate", b, f._uiHash(this));
+        return a.ui.ddmanager && (a.ui.ddmanager.current = this), a.ui.ddmanager && !e.dropBehaviour && a.ui.ddmanager.prepareOffsets(this, b), this.dragging = !0, this.helper.addClass("ui-sortable-helper"), this._mouseDrag(b), !0
+    }, _mouseDrag: function (b) {
+        this.position = this._generatePosition(b), this.positionAbs = this._convertPositionTo("absolute"), this.lastPositionAbs || (this.lastPositionAbs = this.positionAbs);
+        if (this.options.scroll) {
+            var c = this.options, d = !1;
+            this.scrollParent[0] != document && this.scrollParent[0].tagName != "HTML" ? (this.overflowOffset.top + this.scrollParent[0].offsetHeight - b.pageY < c.scrollSensitivity ? this.scrollParent[0].scrollTop = d = this.scrollParent[0].scrollTop + c.scrollSpeed : b.pageY - this.overflowOffset.top < c.scrollSensitivity && (this.scrollParent[0].scrollTop = d = this.scrollParent[0].scrollTop - c.scrollSpeed), this.overflowOffset.left + this.scrollParent[0].offsetWidth - b.pageX < c.scrollSensitivity ? this.scrollParent[0].scrollLeft = d = this.scrollParent[0].scrollLeft + c.scrollSpeed : b.pageX - this.overflowOffset.left < c.scrollSensitivity && (this.scrollParent[0].scrollLeft = d = this.scrollParent[0].scrollLeft - c.scrollSpeed)) : (b.pageY - a(document).scrollTop() < c.scrollSensitivity ? d = a(document).scrollTop(a(document).scrollTop() - c.scrollSpeed) : a(window).height() - (b.pageY - a(document).scrollTop()) < c.scrollSensitivity && (d = a(document).scrollTop(a(document).scrollTop() + c.scrollSpeed)), b.pageX - a(document).scrollLeft() < c.scrollSensitivity ? d = a(document).scrollLeft(a(document).scrollLeft() - c.scrollSpeed) : a(window).width() - (b.pageX - a(document).scrollLeft()) < c.scrollSensitivity && (d = a(document).scrollLeft(a(document).scrollLeft() + c.scrollSpeed))), d !== !1 && a.ui.ddmanager && !c.dropBehaviour && a.ui.ddmanager.prepareOffsets(this, b)
+        }
+        this.positionAbs = this._convertPositionTo("absolute");
+        if (!this.options.axis || this.options.axis != "y")this.helper[0].style.left = this.position.left + "px";
+        if (!this.options.axis || this.options.axis != "x")this.helper[0].style.top = this.position.top + "px";
+        for (var e = this.items.length - 1; e >= 0; e--) {
+            var f = this.items[e], g = f.item[0], h = this._intersectsWithPointer(f);
+            if (!h)continue;
+            if (g != this.currentItem[0] && this.placeholder[h == 1 ? "next" : "prev"]()[0] != g && !a.ui.contains(this.placeholder[0], g) && (this.options.type == "semi-dynamic" ? !a.ui.contains(this.element[0], g) : !0)) {
+                this.direction = h == 1 ? "down" : "up";
+                if (this.options.tolerance == "pointer" || this._intersectsWithSides(f))this._rearrange(b, f); else break;
+                this._trigger("change", b, this._uiHash());
+                break
+            }
+        }
+        return this._contactContainers(b), a.ui.ddmanager && a.ui.ddmanager.drag(this, b), this._trigger("sort", b, this._uiHash()), this.lastPositionAbs = this.positionAbs, !1
+    }, _mouseStop: function (b, c) {
+        if (!b)return;
+        a.ui.ddmanager && !this.options.dropBehaviour && a.ui.ddmanager.drop(this, b);
+        if (this.options.revert) {
+            var d = this, e = d.placeholder.offset();
+            d.reverting = !0, a(this.helper).animate({left: e.left - this.offset.parent.left - d.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft), top: e.top - this.offset.parent.top - d.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)}, parseInt(this.options.revert, 10) || 500, function () {
+                d._clear(b)
+            })
+        } else this._clear(b, c);
+        return!1
+    }, cancel: function () {
+        var b = this;
+        if (this.dragging) {
+            this._mouseUp({target: null}), this.options.helper == "original" ? this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper") : this.currentItem.show();
+            for (var c = this.containers.length - 1; c >= 0; c--)this.containers[c]._trigger("deactivate", null, b._uiHash(this)), this.containers[c].containerCache.over && (this.containers[c]._trigger("out", null, b._uiHash(this)), this.containers[c].containerCache.over = 0)
+        }
+        return this.placeholder && (this.placeholder[0].parentNode && this.placeholder[0].parentNode.removeChild(this.placeholder[0]), this.options.helper != "original" && this.helper && this.helper[0].parentNode && this.helper.remove(), a.extend(this, {helper: null, dragging: !1, reverting: !1, _noFinalSort: null}), this.domPosition.prev ? a(this.domPosition.prev).after(this.currentItem) : a(this.domPosition.parent).prepend(this.currentItem)), this
+    }, serialize: function (b) {
+        var c = this._getItemsAsjQuery(b && b.connected), d = [];
+        return b = b || {}, a(c).each(function () {
+            var c = (a(b.item || this).attr(b.attribute || "id") || "").match(b.expression || /(.+)[-=_](.+)/);
+            c && d.push((b.key || c[1] + "[]") + "=" + (b.key && b.expression ? c[1] : c[2]))
+        }), !d.length && b.key && d.push(b.key + "="), d.join("&")
+    }, toArray: function (b) {
+        var c = this._getItemsAsjQuery(b && b.connected), d = [];
+        return b = b || {}, c.each(function () {
+            d.push(a(b.item || this).attr(b.attribute || "id") || "")
+        }), d
+    }, _intersectsWith: function (a) {
+        var b = this.positionAbs.left, c = b + this.helperProportions.width, d = this.positionAbs.top, e = d + this.helperProportions.height, f = a.left, g = f + a.width, h = a.top, i = h + a.height, j = this.offset.click.top, k = this.offset.click.left, l = d + j > h && d + j < i && b + k > f && b + k < g;
+        return this.options.tolerance == "pointer" || this.options.forcePointerForContainers || this.options.tolerance != "pointer" && this.helperProportions[this.floating ? "width" : "height"] > a[this.floating ? "width" : "height"] ? l : f < b + this.helperProportions.width / 2 && c - this.helperProportions.width / 2 < g && h < d + this.helperProportions.height / 2 && e - this.helperProportions.height / 2 < i
+    }, _intersectsWithPointer: function (b) {
+        var c = this.options.axis === "x" || a.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, b.top, b.height), d = this.options.axis === "y" || a.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, b.left, b.width), e = c && d, f = this._getDragVerticalDirection(), g = this._getDragHorizontalDirection();
+        return e ? this.floating ? g && g == "right" || f == "down" ? 2 : 1 : f && (f == "down" ? 2 : 1) : !1
+    }, _intersectsWithSides: function (b) {
+        var c = a.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, b.top + b.height / 2, b.height), d = a.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, b.left + b.width / 2, b.width), e = this._getDragVerticalDirection(), f = this._getDragHorizontalDirection();
+        return this.floating && f ? f == "right" && d || f == "left" && !d : e && (e == "down" && c || e == "up" && !c)
+    }, _getDragVerticalDirection: function () {
+        var a = this.positionAbs.top - this.lastPositionAbs.top;
+        return a != 0 && (a > 0 ? "down" : "up")
+    }, _getDragHorizontalDirection: function () {
+        var a = this.positionAbs.left - this.lastPositionAbs.left;
+        return a != 0 && (a > 0 ? "right" : "left")
+    }, refresh: function (a) {
+        return this._refreshItems(a), this.refreshPositions(), this
+    }, _connectWith: function () {
+        var a = this.options;
+        return a.connectWith.constructor == String ? [a.connectWith] : a.connectWith
+    }, _getItemsAsjQuery: function (b) {
+        var c = this, d = [], e = [], f = this._connectWith();
+        if (f && b)for (var g = f.length - 1; g >= 0; g--) {
+            var h = a(f[g]);
+            for (var i = h.length - 1; i >= 0; i--) {
+                var j = a.data(h[i], this.widgetName);
+                j && j != this && !j.options.disabled && e.push([a.isFunction(j.options.items) ? j.options.items.call(j.element) : a(j.options.items, j.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), j])
+            }
+        }
+        e.push([a.isFunction(this.options.items) ? this.options.items.call(this.element, null, {options: this.options, item: this.currentItem}) : a(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]);
+        for (var g = e.length - 1; g >= 0; g--)e[g][0].each(function () {
+            d.push(this)
+        });
+        return a(d)
+    }, _removeCurrentsFromItems: function () {
+        var a = this.currentItem.find(":data(" + this.widgetName + "-item)");
+        for (var b = 0; b < this.items.length; b++)for (var c = 0; c < a.length; c++)a[c] == this.items[b].item[0] && this.items.splice(b, 1)
+    }, _refreshItems: function (b) {
+        this.items = [], this.containers = [this];
+        var c = this.items, d = this, e = [
+            [a.isFunction(this.options.items) ? this.options.items.call(this.element[0], b, {item: this.currentItem}) : a(this.options.items, this.element), this]
+        ], f = this._connectWith();
+        if (f && this.ready)for (var g = f.length - 1; g >= 0; g--) {
+            var h = a(f[g]);
+            for (var i = h.length - 1; i >= 0; i--) {
+                var j = a.data(h[i], this.widgetName);
+                j && j != this && !j.options.disabled && (e.push([a.isFunction(j.options.items) ? j.options.items.call(j.element[0], b, {item: this.currentItem}) : a(j.options.items, j.element), j]), this.containers.push(j))
+            }
+        }
+        for (var g = e.length - 1; g >= 0; g--) {
+            var k = e[g][1], l = e[g][0];
+            for (var i = 0, m = l.length; i < m; i++) {
+                var n = a(l[i]);
+                n.data(this.widgetName + "-item", k), c.push({item: n, instance: k, width: 0, height: 0, left: 0, top: 0})
+            }
+        }
+    }, refreshPositions: function (b) {
+        this.offsetParent && this.helper && (this.offset.parent = this._getParentOffset());
+        for (var c = this.items.length - 1; c >= 0; c--) {
+            var d = this.items[c];
+            if (d.instance != this.currentContainer && this.currentContainer && d.item[0] != this.currentItem[0])continue;
+            var e = this.options.toleranceElement ? a(this.options.toleranceElement, d.item) : d.item;
+            b || (d.width = e.outerWidth(), d.height = e.outerHeight());
+            var f = e.offset();
+            d.left = f.left, d.top = f.top
+        }
+        if (this.options.custom && this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this); else for (var c = this.containers.length - 1; c >= 0; c--) {
+            var f = this.containers[c].element.offset();
+            this.containers[c].containerCache.left = f.left, this.containers[c].containerCache.top = f.top, this.containers[c].containerCache.width = this.containers[c].element.outerWidth(), this.containers[c].containerCache.height = this.containers[c].element.outerHeight()
+        }
+        return this
+    }, _createPlaceholder: function (b) {
+        var c = b || this, d = c.options;
+        if (!d.placeholder || d.placeholder.constructor == String) {
+            var e = d.placeholder;
+            d.placeholder = {element: function () {
+                var b = a(document.createElement(c.currentItem[0].nodeName)).addClass(e || c.currentItem[0].className + " ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];
+                return e || (b.style.visibility = "hidden"), b
+            }, update: function (a, b) {
+                if (e && !d.forcePlaceholderSize)return;
+                b.height() || b.height(c.currentItem.innerHeight() - parseInt(c.currentItem.css("paddingTop") || 0, 10) - parseInt(c.currentItem.css("paddingBottom") || 0, 10)), b.width() || b.width(c.currentItem.innerWidth() - parseInt(c.currentItem.css("paddingLeft") || 0, 10) - parseInt(c.currentItem.css("paddingRight") || 0, 10))
+            }}
+        }
+        c.placeholder = a(d.placeholder.element.call(c.element, c.currentItem)), c.currentItem.after(c.placeholder), d.placeholder.update(c, c.placeholder)
+    }, _contactContainers: function (b) {
+        var c = null, d = null;
+        for (var e = this.containers.length - 1; e >= 0; e--) {
+            if (a.ui.contains(this.currentItem[0], this.containers[e].element[0]))continue;
+            if (this._intersectsWith(this.containers[e].containerCache)) {
+                if (c && a.ui.contains(this.containers[e].element[0], c.element[0]))continue;
+                c = this.containers[e], d = e
+            } else this.containers[e].containerCache.over && (this.containers[e]._trigger("out", b, this._uiHash(this)), this.containers[e].containerCache.over = 0)
+        }
+        if (!c)return;
+        if (this.containers.length === 1)this.containers[d]._trigger("over", b, this._uiHash(this)), this.containers[d].containerCache.over = 1; else if (this.currentContainer != this.containers[d]) {
+            var f = 1e4, g = null, h = this.positionAbs[this.containers[d].floating ? "left" : "top"];
+            for (var i = this.items.length - 1; i >= 0; i--) {
+                if (!a.ui.contains(this.containers[d].element[0], this.items[i].item[0]))continue;
+                var j = this.containers[d].floating ? this.items[i].item.offset().left : this.items[i].item.offset().top;
+                Math.abs(j - h) < f && (f = Math.abs(j - h), g = this.items[i], this.direction = j - h > 0 ? "down" : "up")
+            }
+            if (!g && !this.options.dropOnEmpty)return;
+            this.currentContainer = this.containers[d], g ? this._rearrange(b, g, null, !0) : this._rearrange(b, null, this.containers[d].element, !0), this._trigger("change", b, this._uiHash()), this.containers[d]._trigger("change", b, this._uiHash(this)), this.options.placeholder.update(this.currentContainer, this.placeholder), this.containers[d]._trigger("over", b, this._uiHash(this)), this.containers[d].containerCache.over = 1
+        }
+    }, _createHelper: function (b) {
+        var c = this.options, d = a.isFunction(c.helper) ? a(c.helper.apply(this.element[0], [b, this.currentItem])) : c.helper == "clone" ? this.currentItem.clone() : this.currentItem;
+        return d.parents("body").length || a(c.appendTo != "parent" ? c.appendTo : this.currentItem[0].parentNode)[0].appendChild(d[0]), d[0] == this.currentItem[0] && (this._storedCSS = {width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left")}), (d[0].style.width == "" || c.forceHelperSize) && d.width(this.currentItem.width()), (d[0].style.height == "" || c.forceHelperSize) && d.height(this.currentItem.height()), d
+    }, _adjustOffsetFromHelper: function (b) {
+        typeof b == "string" && (b = b.split(" ")), a.isArray(b) && (b = {left: +b[0], top: +b[1] || 0}), "left"in b && (this.offset.click.left = b.left + this.margins.left), "right"in b && (this.offset.click.left = this.helperProportions.width - b.right + this.margins.left), "top"in b && (this.offset.click.top = b.top + this.margins.top), "bottom"in b && (this.offset.click.top = this.helperProportions.height - b.bottom + this.margins.top)
+    }, _getParentOffset: function () {
+        this.offsetParent = this.helper.offsetParent();
+        var b = this.offsetParent.offset();
+        this.cssPosition == "absolute" && this.scrollParent[0] != document && a.ui.contains(this.scrollParent[0], this.offsetParent[0]) && (b.left += this.scrollParent.scrollLeft(), b.top += this.scrollParent.scrollTop());
+        if (this.offsetParent[0] == document.body || this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == "html" && a.browser.msie)b = {top: 0, left: 0};
+        return{top: b.top + (parseInt(this.offsetParent.css("borderTopWidth"), 10) || 0), left: b.left + (parseInt(this.offsetParent.css("borderLeftWidth"), 10) || 0)}
+    }, _getRelativeOffset: function () {
+        if (this.cssPosition == "relative") {
+            var a = this.currentItem.position();
+            return{top: a.top - (parseInt(this.helper.css("top"), 10) || 0) + this.scrollParent.scrollTop(), left: a.left - (parseInt(this.helper.css("left"), 10) || 0) + this.scrollParent.scrollLeft()}
+        }
+        return{top: 0, left: 0}
+    }, _cacheMargins: function () {
+        this.margins = {left: parseInt(this.currentItem.css("marginLeft"), 10) || 0, top: parseInt(this.currentItem.css("marginTop"), 10) || 0}
+    }, _cacheHelperProportions: function () {
+        this.helperProportions = {width: this.helper.outerWidth(), height: this.helper.outerHeight()}
+    }, _setContainment: function () {
+        var b = this.options;
+        b.containment == "parent" && (b.containment = this.helper[0].parentNode);
+        if (b.containment == "document" || b.containment == "window")this.containment = [0 - this.offset.relative.left - this.offset.parent.left, 0 - this.offset.relative.top - this.offset.parent.top, a(b.containment == "document" ? document : window).width() - this.helperProportions.width - this.margins.left, (a(b.containment == "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top];
+        if (!/^(document|window|parent)$/.test(b.containment)) {
+            var c = a(b.containment)[0], d = a(b.containment).offset(), e = a(c).css("overflow") != "hidden";
+            this.containment = [d.left + (parseInt(a(c).css("borderLeftWidth"), 10) || 0) + (parseInt(a(c).css("paddingLeft"), 10) || 0) - this.margins.left, d.top + (parseInt(a(c).css("borderTopWidth"), 10) || 0) + (parseInt(a(c).css("paddingTop"), 10) || 0) - this.margins.top, d.left + (e ? Math.max(c.scrollWidth, c.offsetWidth) : c.offsetWidth) - (parseInt(a(c).css("borderLeftWidth"), 10) || 0) - (parseInt(a(c).css("paddingRight"), 10) || 0) - this.helperProportions.width - this.margins.left, d.top + (e ? Math.max(c.scrollHeight, c.offsetHeight) : c.offsetHeight) - (parseInt(a(c).css("borderTopWidth"), 10) || 0) - (parseInt(a(c).css("paddingBottom"), 10) || 0) - this.helperProportions.height - this.margins.top]
+        }
+    }, _convertPositionTo: function (b, c) {
+        c || (c = this.position);
+        var d = b == "absolute" ? 1 : -1, e = this.options, f = this.cssPosition == "absolute" && (this.scrollParent[0] == document || !a.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, g = /(html|body)/i.test(f[0].tagName);
+        return{top: c.top + this.offset.relative.top * d + this.offset.parent.top * d - (a.browser.safari && this.cssPosition == "fixed" ? 0 : (this.cssPosition == "fixed" ? -this.scrollParent.scrollTop() : g ? 0 : f.scrollTop()) * d), left: c.left + this.offset.relative.left * d + this.offset.parent.left * d - (a.browser.safari && this.cssPosition == "fixed" ? 0 : (this.cssPosition == "fixed" ? -this.scrollParent.scrollLeft() : g ? 0 : f.scrollLeft()) * d)}
+    }, _generatePosition: function (b) {
+        var c = this.options, d = this.cssPosition == "absolute" && (this.scrollParent[0] == document || !a.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, e = /(html|body)/i.test(d[0].tagName);
+        this.cssPosition == "relative" && (this.scrollParent[0] == document || this.scrollParent[0] == this.offsetParent[0]) && (this.offset.relative = this._getRelativeOffset());
+        var f = b.pageX, g = b.pageY;
+        if (this.originalPosition) {
+            this.containment && (b.pageX - this.offset.click.left < this.containment[0] && (f = this.containment[0] + this.offset.click.left), b.pageY - this.offset.click.top < this.containment[1] && (g = this.containment[1] + this.offset.click.top), b.pageX - this.offset.click.left > this.containment[2] && (f = this.containment[2] + this.offset.click.left), b.pageY - this.offset.click.top > this.containment[3] && (g = this.containment[3] + this.offset.click.top));
+            if (c.grid) {
+                var h = this.originalPageY + Math.round((g - this.originalPageY) / c.grid[1]) * c.grid[1];
+                g = this.containment ? h - this.offset.click.top < this.containment[1] || h - this.offset.click.top > this.containment[3] ? h - this.offset.click.top < this.containment[1] ? h + c.grid[1] : h - c.grid[1] : h : h;
+                var i = this.originalPageX + Math.round((f - this.originalPageX) / c.grid[0]) * c.grid[0];
+                f = this.containment ? i - this.offset.click.left < this.containment[0] || i - this.offset.click.left > this.containment[2] ? i - this.offset.click.left < this.containment[0] ? i + c.grid[0] : i - c.grid[0] : i : i
+            }
+        }
+        return{top: g - this.offset.click.top - this.offset.relative.top - this.offset.parent.top + (a.browser.safari && this.cssPosition == "fixed" ? 0 : this.cssPosition == "fixed" ? -this.scrollParent.scrollTop() : e ? 0 : d.scrollTop()), left: f - this.offset.click.left - this.offset.relative.left - this.offset.parent.left + (a.browser.safari && this.cssPosition == "fixed" ? 0 : this.cssPosition == "fixed" ? -this.scrollParent.scrollLeft() : e ? 0 : d.scrollLeft())}
+    }, _rearrange: function (a, b, c, d) {
+        c ? c[0].appendChild(this.placeholder[0]) : b.item[0].parentNode.insertBefore(this.placeholder[0], this.direction == "down" ? b.item[0] : b.item[0].nextSibling), this.counter = this.counter ? ++this.counter : 1;
+        var e = this, f = this.counter;
+        window.setTimeout(function () {
+            f == e.counter && e.refreshPositions(!d)
+        }, 0)
+    }, _clear: function (b, c) {
+        this.reverting = !1;
+        var d = [], e = this;
+        !this._noFinalSort && this.currentItem.parent().length && this.placeholder.before(this.currentItem), this._noFinalSort = null;
+        if (this.helper[0] == this.currentItem[0]) {
+            for (var f in this._storedCSS)if (this._storedCSS[f] == "auto" || this._storedCSS[f] == "static")this._storedCSS[f] = "";
+            this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")
+        } else this.currentItem.show();
+        this.fromOutside && !c && d.push(function (a) {
+            this._trigger("receive", a, this._uiHash(this.fromOutside))
+        }), (this.fromOutside || this.domPosition.prev != this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent != this.currentItem.parent()[0]) && !c && d.push(function (a) {
+            this._trigger("update", a, this._uiHash())
+        });
+        if (!a.ui.contains(this.element[0], this.currentItem[0])) {
+            c || d.push(function (a) {
+                this._trigger("remove", a, this._uiHash())
+            });
+            for (var f = this.containers.length - 1; f >= 0; f--)a.ui.contains(this.containers[f].element[0], this.currentItem[0]) && !c && (d.push(function (a) {
+                return function (b) {
+                    a._trigger("receive", b, this._uiHash(this))
+                }
+            }.call(this, this.containers[f])), d.push(function (a) {
+                return function (b) {
+                    a._trigger("update", b, this._uiHash(this))
+                }
+            }.call(this, this.containers[f])))
+        }
+        for (var f = this.containers.length - 1; f >= 0; f--)c || d.push(function (a) {
+            return function (b) {
+                a._trigger("deactivate", b, this._uiHash(this))
+            }
+        }.call(this, this.containers[f])), this.containers[f].containerCache.over && (d.push(function (a) {
+            return function (b) {
+                a._trigger("out", b, this._uiHash(this))
+            }
+        }.call(this, this.containers[f])), this.containers[f].containerCache.over = 0);
+        this._storedCursor && a("body").css("cursor", this._storedCursor), this._storedOpacity && this.helper.css("opacity", this._storedOpacity), this._storedZIndex && this.helper.css("zIndex", this._storedZIndex == "auto" ? "" : this._storedZIndex), this.dragging = !1;
+        if (this.cancelHelperRemoval) {
+            if (!c) {
+                this._trigger("beforeStop", b, this._uiHash());
+                for (var f = 0; f < d.length; f++)d[f].call(this, b);
+                this._trigger("stop", b, this._uiHash())
+            }
+            return!1
+        }
+        c || this._trigger("beforeStop", b, this._uiHash()), this.placeholder[0].parentNode.removeChild(this.placeholder[0]), this.helper[0] != this.currentItem[0] && this.helper.remove(), this.helper = null;
+        if (!c) {
+            for (var f = 0; f < d.length; f++)d[f].call(this, b);
+            this._trigger("stop", b, this._uiHash())
+        }
+        return this.fromOutside = !1, !0
+    }, _trigger: function () {
+        a.Widget.prototype._trigger.apply(this, arguments) === !1 && this.cancel()
+    }, _uiHash: function (b) {
+        var c = b || this;
+        return{helper: c.helper, placeholder: c.placeholder || a([]), position: c.position, originalPosition: c.originalPosition, offset: c.positionAbs, item: c.currentItem, sender: b ? b.element : null}
+    }}), a.extend(a.ui.sortable, {version: "1.8.21"})
+})(jQuery);
+;
+/*! jQuery UI - v1.8.21 - 2012-06-05
+ * https://github.com/jquery/jquery-ui
+ * Includes: jquery.ui.accordion.js
+ * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
+(function (a, b) {
+    a.widget("ui.accordion", {options: {active: 0, animated: "slide", autoHeight: !0, clearStyle: !1, collapsible: !1, event: "click", fillSpace: !1, header: "> li > :first-child,> :not(li):even", icons: {header: "ui-icon-triangle-1-e", headerSelected: "ui-icon-triangle-1-s"}, navigation: !1, navigationFilter: function () {
+        return this.href.toLowerCase() === location.href.toLowerCase()
+    }}, _create: function () {
+        var b = this, c = b.options;
+        b.running = 0, b.element.addClass("ui-accordion ui-widget ui-helper-reset").children("li").addClass("ui-accordion-li-fix"), b.headers = b.element.find(c.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function () {
+            if (c.disabled)return;
+            a(this).addClass("ui-state-hover")
+        }).bind("mouseleave.accordion",function () {
+            if (c.disabled)return;
+            a(this).removeClass("ui-state-hover")
+        }).bind("focus.accordion",function () {
+            if (c.disabled)return;
+            a(this).addClass("ui-state-focus")
+        }).bind("blur.accordion", function () {
+            if (c.disabled)return;
+            a(this).removeClass("ui-state-focus")
+        }), b.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");
+        if (c.navigation) {
+            var d = b.element.find("a").filter(c.navigationFilter).eq(0);
+            if (d.length) {
+                var e = d.closest(".ui-accordion-header");
+                e.length ? b.active = e : b.active = d.closest(".ui-accordion-content").prev()
+            }
+        }
+        b.active = b._findActive(b.active || c.active).addClass("ui-state-default ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top"), b.active.next().addClass("ui-accordion-content-active"), b._createIcons(), b.resize(), b.element.attr("role", "tablist"), b.headers.attr("role", "tab").bind("keydown.accordion",function (a) {
+            return b._keydown(a)
+        }).next().attr("role", "tabpanel"), b.headers.not(b.active || "").attr({"aria-expanded": "false", "aria-selected": "false", tabIndex: -1}).next().hide(), b.active.length ? b.active.attr({"aria-expanded": "true", "aria-selected": "true", tabIndex: 0}) : b.headers.eq(0).attr("tabIndex", 0), a.browser.safari || b.headers.find("a").attr("tabIndex", -1), c.event && b.headers.bind(c.event.split(" ").join(".accordion ") + ".accordion", function (a) {
+            b._clickHandler.call(b, a, this), a.preventDefault()
+        })
+    }, _createIcons: function () {
+        var b = this.options;
+        b.icons && (a("<span></span>").addClass("ui-icon " + b.icons.header).prependTo(this.headers), this.active.children(".ui-icon").toggleClass(b.icons.header).toggleClass(b.icons.headerSelected), this.element.addClass("ui-accordion-icons"))
+    }, _destroyIcons: function () {
+        this.headers.children(".ui-icon").remove(), this.element.removeClass("ui-accordion-icons")
+    }, destroy: function () {
+        var b = this.options;
+        this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"), this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-accordion-disabled ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-selected").removeAttr("tabIndex"), this.headers.find("a").removeAttr("tabIndex"), this._destroyIcons();
+        var c = this.headers.next().css("display", "").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-accordion-disabled ui-state-disabled");
+        return(b.autoHeight || b.fillHeight) && c.css("height", ""), a.Widget.prototype.destroy.call(this)
+    }, _setOption: function (b, c) {
+        a.Widget.prototype._setOption.apply(this, arguments), b == "active" && this.activate(c), b == "icons" && (this._destroyIcons(), c && this._createIcons()), b == "disabled" && this.headers.add(this.headers.next())[c ? "addClass" : "removeClass"]("ui-accordion-disabled ui-state-disabled")
+    }, _keydown: function (b) {
+        if (this.options.disabled || b.altKey || b.ctrlKey)return;
+        var c = a.ui.keyCode, d = this.headers.length, e = this.headers.index(b.target), f = !1;
+        switch (b.keyCode) {
+            case c.RIGHT:
+            case c.DOWN:
+                f = this.headers[(e + 1) % d];
+                break;
+            case c.LEFT:
+            case c.UP:
+                f = this.headers[(e - 1 + d) % d];
+                break;
+            case c.SPACE:
+            case c.ENTER:
+                this._clickHandler({target: b.target}, b.target), b.preventDefault()
+        }
+        return f ? (a(b.target).attr("tabIndex", -1), a(f).attr("tabIndex", 0), f.focus(), !1) : !0
+    }, resize: function () {
+        var b = this.options, c;
+        if (b.fillSpace) {
+            if (a.browser.msie) {
+                var d = this.element.parent().css("overflow");
+                this.element.parent().css("overflow", "hidden")
+            }
+            c = this.element.parent().height(), a.browser.msie && this.element.parent().css("overflow", d), this.headers.each(function () {
+                c -= a(this).outerHeight(!0)
+            }), this.headers.next().each(function () {
+                a(this).height(Math.max(0, c - a(this).innerHeight() + a(this).height()))
+            }).css("overflow", "auto")
+        } else b.autoHeight && (c = 0, this.headers.next().each(function () {
+            c = Math.max(c, a(this).height("").height())
+        }).height(c));
+        return this
+    }, activate: function (a) {
+        this.options.active = a;
+        var b = this._findActive(a)[0];
+        return this._clickHandler({target: b}, b), this
+    }, _findActive: function (b) {
+        return b ? typeof b == "number" ? this.headers.filter(":eq(" + b + ")") : this.headers.not(this.headers.not(b)) : b === !1 ? a([]) : this.headers.filter(":eq(0)")
+    }, _clickHandler: function (b, c) {
+        var d = this.options;
+        if (d.disabled)return;
+        if (!b.target) {
+            if (!d.collapsible)return;
+            this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header), this.active.next().addClass("ui-accordion-content-active");
+            var e = this.active.next(), f = {options: d, newHeader: a([]), oldHeader: d.active, newContent: a([]), oldContent: e}, g = this.active = a([]);
+            this._toggle(g, e, f);
+            return
+        }
+        var h = a(b.currentTarget || c), i = h[0] === this.active[0];
+        d.active = d.collapsible && i ? !1 : this.headers.index(h);
+        if (this.running || !d.collapsible && i)return;
+        var j = this.active, g = h.next(), e = this.active.next(), f = {options: d, newHeader: i && d.collapsible ? a([]) : h, oldHeader: this.active, newContent: i && d.collapsible ? a([]) : g, oldContent: e}, k = this.headers.index(this.active[0]) > this.headers.index(h[0]);
+        this.active = i ? a([]) : h, this._toggle(g, e, f, i, k), j.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header), i || (h.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").children(".ui-icon").removeClass(d.icons.header).addClass(d.icons.headerSelected), h.next().addClass("ui-accordion-content-active"));
+        return
+    }, _toggle: function (b, c, d, e, f) {
+        var g = this, h = g.options;
+        g.toShow = b, g.toHide = c, g.data = d;
+        var i = function () {
+            if (!g)return;
+            return g._completed.apply(g, arguments)
+        };
+        g._trigger("changestart", null, g.data), g.running = c.size() === 0 ? b.size() : c.size();
+        if (h.animated) {
+            var j = {};
+            h.collapsible && e ? j = {toShow: a([]), toHide: c, complete: i, down: f, autoHeight: h.autoHeight || h.fillSpace} : j = {toShow: b, toHide: c, complete: i, down: f, autoHeight: h.autoHeight || h.fillSpace}, h.proxied || (h.proxied = h.animated), h.proxiedDuration || (h.proxiedDuration = h.duration), h.animated = a.isFunction(h.proxied) ? h.proxied(j) : h.proxied, h.duration = a.isFunction(h.proxiedDuration) ? h.proxiedDuration(j) : h.proxiedDuration;
+            var k = a.ui.accordion.animations, l = h.duration, m = h.animated;
+            m && !k[m] && !a.easing[m] && (m = "slide"), k[m] || (k[m] = function (a) {
+                this.slide(a, {easing: m, duration: l || 700})
+            }), k[m](j)
+        } else h.collapsible && e ? b.toggle() : (c.hide(), b.show()), i(!0);
+        c.prev().attr({"aria-expanded": "false", "aria-selected": "false", tabIndex: -1}).blur(), b.prev().attr({"aria-expanded": "true", "aria-selected": "true", tabIndex: 0}).focus()
+    }, _completed: function (a) {
+        this.running = a ? 0 : --this.running;
+        if (this.running)return;
+        this.options.clearStyle && this.toShow.add(this.toHide).css({height: "", overflow: ""}), this.toHide.removeClass("ui-accordion-content-active"), this.toHide.length && (this.toHide.parent()[0].className = this.toHide.parent()[0].className), this._trigger("change", null, this.data)
+    }}), a.extend(a.ui.accordion, {version: "1.8.21", animations: {slide: function (b, c) {
+        b = a.extend({easing: "swing", duration: 300}, b, c);
+        if (!b.toHide.size()) {
+            b.toShow.animate({height: "show", paddingTop: "show", paddingBottom: "show"}, b);
+            return
+        }
+        if (!b.toShow.size()) {
+            b.toHide.animate({height: "hide", paddingTop: "hide", paddingBottom: "hide"}, b);
+            return
+        }
+        var d = b.toShow.css("overflow"), e = 0, f = {}, g = {}, h = ["height", "paddingTop", "paddingBottom"], i, j = b.toShow;
+        i = j[0].style.width, j.width(j.parent().width() - parseFloat(j.css("paddingLeft")) - parseFloat(j.css("paddingRight")) - (parseFloat(j.css("borderLeftWidth")) || 0) - (parseFloat(j.css("borderRightWidth")) || 0)), a.each(h, function (c, d) {
+            g[d] = "hide";
+            var e = ("" + a.css(b.toShow[0], d)).match(/^([\d+-.]+)(.*)$/);
+            f[d] = {value: e[1], unit: e[2] || "px"}
+        }), b.toShow.css({height: 0, overflow: "hidden"}).show(), b.toHide.filter(":hidden").each(b.complete).end().filter(":visible").animate(g, {step: function (a, c) {
+            c.prop == "height" && (e = c.end - c.start === 0 ? 0 : (c.now - c.start) / (c.end - c.start)), b.toShow[0].style[c.prop] = e * f[c.prop].value + f[c.prop].unit
+        }, duration: b.duration, easing: b.easing, complete: function () {
+            b.autoHeight || b.toShow.css("height", ""), b.toShow.css({width: i, overflow: d}), b.complete()
+        }})
+    }, bounceslide: function (a) {
+        this.slide(a, {easing: a.down ? "easeOutBounce" : "swing", duration: a.down ? 1e3 : 200})
+    }}})
+})(jQuery);
+;
+/*! jQuery UI - v1.8.21 - 2012-06-05
+ * https://github.com/jquery/jquery-ui
+ * Includes: jquery.ui.button.js
+ * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
+(function (a, b) {
+    var c, d, e, f, g = "ui-button ui-widget ui-state-default ui-corner-all", h = "ui-state-hover ui-state-active ", i = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only", j = function () {
+        var b = a(this).find(":ui-button");
+        setTimeout(function () {
+            b.button("refresh")
+        }, 1)
+    }, k = function (b) {
+        var c = b.name, d = b.form, e = a([]);
+        return c && (d ? e = a(d).find("[name='" + c + "']") : e = a("[name='" + c + "']", b.ownerDocument).filter(function () {
+            return!this.form
+        })), e
+    };
+    a.widget("ui.button", {options: {disabled: null, text: !0, label: null, icons: {primary: null, secondary: null}}, _create: function () {
+        this.element.closest("form").unbind("reset.button").bind("reset.button", j), typeof this.options.disabled != "boolean" ? this.options.disabled = !!this.element.propAttr("disabled") : this.element.propAttr("disabled", this.options.disabled), this._determineButtonType(), this.hasTitle = !!this.buttonElement.attr("title");
+        var b = this, h = this.options, i = this.type === "checkbox" || this.type === "radio", l = "ui-state-hover" + (i ? "" : " ui-state-active"), m = "ui-state-focus";
+        h.label === null && (h.label = this.buttonElement.html()), this.buttonElement.addClass(g).attr("role", "button").bind("mouseenter.button",function () {
+            if (h.disabled)return;
+            a(this).addClass("ui-state-hover"), this === c && a(this).addClass("ui-state-active")
+        }).bind("mouseleave.button",function () {
+            if (h.disabled)return;
+            a(this).removeClass(l)
+        }).bind("click.button", function (a) {
+            h.disabled && (a.preventDefault(), a.stopImmediatePropagation())
+        }), this.element.bind("focus.button",function () {
+            b.buttonElement.addClass(m)
+        }).bind("blur.button", function () {
+            b.buttonElement.removeClass(m)
+        }), i && (this.element.bind("change.button", function () {
+            if (f)return;
+            b.refresh()
+        }), this.buttonElement.bind("mousedown.button",function (a) {
+            if (h.disabled)return;
+            f = !1, d = a.pageX, e = a.pageY
+        }).bind("mouseup.button", function (a) {
+            if (h.disabled)return;
+            if (d !== a.pageX || e !== a.pageY)f = !0
+        })), this.type === "checkbox" ? this.buttonElement.bind("click.button", function () {
+            if (h.disabled || f)return!1;
+            a(this).toggleClass("ui-state-active"), b.buttonElement.attr("aria-pressed", b.element[0].checked)
+        }) : this.type === "radio" ? this.buttonElement.bind("click.button", function () {
+            if (h.disabled || f)return!1;
+            a(this).addClass("ui-state-active"), b.buttonElement.attr("aria-pressed", "true");
+            var c = b.element[0];
+            k(c).not(c).map(function () {
+                return a(this).button("widget")[0]
+            }).removeClass("ui-state-active").attr("aria-pressed", "false")
+        }) : (this.buttonElement.bind("mousedown.button",function () {
+            if (h.disabled)return!1;
+            a(this).addClass("ui-state-active"), c = this, a(document).one("mouseup", function () {
+                c = null
+            })
+        }).bind("mouseup.button",function () {
+            if (h.disabled)return!1;
+            a(this).removeClass("ui-state-active")
+        }).bind("keydown.button",function (b) {
+            if (h.disabled)return!1;
+            (b.keyCode == a.ui.keyCode.SPACE || b.keyCode == a.ui.keyCode.ENTER) && a(this).addClass("ui-state-active")
+        }).bind("keyup.button", function () {
+            a(this).removeClass("ui-state-active")
+        }), this.buttonElement.is("a") && this.buttonElement.keyup(function (b) {
+            b.keyCode === a.ui.keyCode.SPACE && a(this).click()
+        })), this._setOption("disabled", h.disabled), this._resetButton()
+    }, _determineButtonType: function () {
+        this.element.is(":checkbox") ? this.type = "checkbox" : this.element.is(":radio") ? this.type = "radio" : this.element.is("input") ? this.type = "input" : this.type = "button";
+        if (this.type === "checkbox" || this.type === "radio") {
+            var a = this.element.parents().filter(":last"), b = "label[for='" + this.element.attr("id") + "']";
+            this.buttonElement = a.find(b), this.buttonElement.length || (a = a.length ? a.siblings() : this.element.siblings(), this.buttonElement = a.filter(b), this.buttonElement.length || (this.buttonElement = a.find(b))), this.element.addClass("ui-helper-hidden-accessible");
+            var c = this.element.is(":checked");
+            c && this.buttonElement.addClass("ui-state-active"), this.buttonElement.attr("aria-pressed", c)
+        } else this.buttonElement = this.element
+    }, widget: function () {
+        return this.buttonElement
+    }, destroy: function () {
+        this.element.removeClass("ui-helper-hidden-accessible"), this.buttonElement.removeClass(g + " " + h + " " + i).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()), this.hasTitle || this.buttonElement.removeAttr("title"), a.Widget.prototype.destroy.call(this)
+    }, _setOption: function (b, c) {
+        a.Widget.prototype._setOption.apply(this, arguments);
+        if (b === "disabled") {
+            c ? this.element.propAttr("disabled", !0) : this.element.propAttr("disabled", !1);
+            return
+        }
+        this._resetButton()
+    }, refresh: function () {
+        var b = this.element.is(":disabled");
+        b !== this.options.disabled && this._setOption("disabled", b), this.type === "radio" ? k(this.element[0]).each(function () {
+            a(this).is(":checked") ? a(this).button("widget").addClass("ui-state-active").attr("aria-pressed", "true") : a(this).button("widget").removeClass("ui-state-active").attr("aria-pressed", "false")
+        }) : this.type === "checkbox" && (this.element.is(":checked") ? this.buttonElement.addClass("ui-state-active").attr("aria-pressed", "true") : this.buttonElement.removeClass("ui-state-active").attr("aria-pressed", "false"))
+    }, _resetButton: function () {
+        if (this.type === "input") {
+            this.options.label && this.element.val(this.options.label);
+            return
+        }
+        var b = this.buttonElement.removeClass(i), c = a("<span></span>", this.element[0].ownerDocument).addClass("ui-button-text").html(this.options.label).appendTo(b.empty()).text(), d = this.options.icons, e = d.primary && d.secondary, f = [];
+        d.primary || d.secondary ? (this.options.text && f.push("ui-button-text-icon" + (e ? "s" : d.primary ? "-primary" : "-secondary")), d.primary && b.prepend("<span class='ui-button-icon-primary ui-icon " + d.primary + "'></span>"), d.secondary && b.append("<span class='ui-button-icon-secondary ui-icon " + d.secondary + "'></span>"), this.options.text || (f.push(e ? "ui-button-icons-only" : "ui-button-icon-only"), this.hasTitle || b.attr("title", c))) : f.push("ui-button-text-only"), b.addClass(f.join(" "))
+    }}), a.widget("ui.buttonset", {options: {items: ":button, :submit, :reset, :checkbox, :radio, a, :data(button)"}, _create: function () {
+        this.element.addClass("ui-buttonset")
+    }, _init: function () {
+        this.refresh()
+    }, _setOption: function (b, c) {
+        b === "disabled" && this.buttons.button("option", b, c), a.Widget.prototype._setOption.apply(this, arguments)
+    }, refresh: function () {
+        var b = this.element.css("direction") === "rtl";
+        this.buttons = this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function () {
+            return a(this).button("widget")[0]
+        }).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(b ? "ui-corner-right" : "ui-corner-left").end().filter(":last").addClass(b ? "ui-corner-left" : "ui-corner-right").end().end()
+    }, destroy: function () {
+        this.element.removeClass("ui-buttonset"), this.buttons.map(function () {
+            return a(this).button("widget")[0]
+        }).removeClass("ui-corner-left ui-corner-right").end().button("destroy"), a.Widget.prototype.destroy.call(this)
+    }})
+})(jQuery);
+;
+/*! jQuery UI - v1.8.21 - 2012-06-05
+ * https://github.com/jquery/jquery-ui
+ * Includes: jquery.ui.dialog.js
+ * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
+(function (a, b) {
+    var c = "ui-dialog ui-widget ui-widget-content ui-corner-all ", d = {buttons: !0, height: !0, maxHeight: !0, maxWidth: !0, minHeight: !0, minWidth: !0, width: !0}, e = {maxHeight: !0, maxWidth: !0, minHeight: !0, minWidth: !0}, f = a.attrFn || {val: !0, css: !0, html: !0, text: !0, data: !0, width: !0, height: !0, offset: !0, click: !0};
+    a.widget("ui.dialog", {options: {autoOpen: !0, buttons: {}, closeOnEscape: !0, closeText: "close", dialogClass: "", draggable: !0, hide: null, height: "auto", maxHeight: !1, maxWidth: !1, minHeight: 150, minWidth: 150, modal: !1, position: {my: "center", at: "center", collision: "fit", using: function (b) {
+        var c = a(this).css(b).offset().top;
+        c < 0 && a(this).css("top", b.top - c)
+    }}, resizable: !0, show: null, stack: !0, title: "", width: 300, zIndex: 1e3}, _create: function () {
+        this.originalTitle = this.element.attr("title"), typeof this.originalTitle != "string" && (this.originalTitle = ""), this.options.title = this.options.title || this.originalTitle;
+        var b = this, d = b.options, e = d.title || "&#160;", f = a.ui.dialog.getTitleId(b.element), g = (b.uiDialog = a("<div></div>")).appendTo(document.body).hide().addClass(c + d.dialogClass).css({zIndex: d.zIndex}).attr("tabIndex", -1).css("outline", 0).keydown(function (c) {
+            d.closeOnEscape && !c.isDefaultPrevented() && c.keyCode && c.keyCode === a.ui.keyCode.ESCAPE && (b.close(c), c.preventDefault())
+        }).attr({role: "dialog", "aria-labelledby": f}).mousedown(function (a) {
+            b.moveToTop(!1, a)
+        }), h = b.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(g), i = (b.uiDialogTitlebar = a("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(g), j = a('<a href="#"></a>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role", "button").hover(function () {
+            j.addClass("ui-state-hover")
+        },function () {
+            j.removeClass("ui-state-hover")
+        }).focus(function () {
+            j.addClass("ui-state-focus")
+        }).blur(function () {
+            j.removeClass("ui-state-focus")
+        }).click(function (a) {
+            return b.close(a), !1
+        }).appendTo(i), k = (b.uiDialogTitlebarCloseText = a("<span></span>")).addClass("ui-icon ui-icon-closethick").text(d.closeText).appendTo(j), l = a("<span></span>").addClass("ui-dialog-title").attr("id", f).html(e).prependTo(i);
+        a.isFunction(d.beforeclose) && !a.isFunction(d.beforeClose) && (d.beforeClose = d.beforeclose), i.find("*").add(i).disableSelection(), d.draggable && a.fn.draggable && b._makeDraggable(), d.resizable && a.fn.resizable && b._makeResizable(), b._createButtons(d.buttons), b._isOpen = !1, a.fn.bgiframe && g.bgiframe()
+    }, _init: function () {
+        this.options.autoOpen && this.open()
+    }, destroy: function () {
+        var a = this;
+        return a.overlay && a.overlay.destroy(), a.uiDialog.hide(), a.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body"), a.uiDialog.remove(), a.originalTitle && a.element.attr("title", a.originalTitle), a
+    }, widget: function () {
+        return this.uiDialog
+    }, close: function (b) {
+        var c = this, d, e;
+        if (!1 === c._trigger("beforeClose", b))return;
+        return c.overlay && c.overlay.destroy(), c.uiDialog.unbind("keypress.ui-dialog"), c._isOpen = !1, c.options.hide ? c.uiDialog.hide(c.options.hide, function () {
+            c._trigger("close", b)
+        }) : (c.uiDialog.hide(), c._trigger("close", b)), a.ui.dialog.overlay.resize(), c.options.modal && (d = 0, a(".ui-dialog").each(function () {
+            this !== c.uiDialog[0] && (e = a(this).css("z-index"), isNaN(e) || (d = Math.max(d, e)))
+        }), a.ui.dialog.maxZ = d), c
+    }, isOpen: function () {
+        return this._isOpen
+    }, moveToTop: function (b, c) {
+        var d = this, e = d.options, f;
+        return e.modal && !b || !e.stack && !e.modal ? d._trigger("focus", c) : (e.zIndex > a.ui.dialog.maxZ && (a.ui.dialog.maxZ = e.zIndex), d.overlay && (a.ui.dialog.maxZ += 1, d.overlay.$el.css("z-index", a.ui.dialog.overlay.maxZ = a.ui.dialog.maxZ)), f = {scrollTop: d.element.scrollTop(), scrollLeft: d.element.scrollLeft()}, a.ui.dialog.maxZ += 1, d.uiDialog.css("z-index", a.ui.dialog.maxZ), d.element.attr(f), d._trigger("focus", c), d)
+    }, open: function () {
+        if (this._isOpen)return;
+        var b = this, c = b.options, d = b.uiDialog;
+        return b.overlay = c.modal ? new a.ui.dialog.overlay(b) : null, b._size(), b._position(c.position), d.show(c.show), b.moveToTop(!0), c.modal && d.bind("keydown.ui-dialog", function (b) {
+            if (b.keyCode !== a.ui.keyCode.TAB)return;
+            var c = a(":tabbable", this), d = c.filter(":first"), e = c.filter(":last");
+            if (b.target === e[0] && !b.shiftKey)return d.focus(1), !1;
+            if (b.target === d[0] && b.shiftKey)return e.focus(1), !1
+        }), a(b.element.find(":tabbable").get().concat(d.find(".ui-dialog-buttonpane :tabbable").get().concat(d.get()))).eq(0).focus(), b._isOpen = !0, b._trigger("open"), b
+    }, _createButtons: function (b) {
+        var c = this, d = !1, e = a("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"), g = a("<div></div>").addClass("ui-dialog-buttonset").appendTo(e);
+        c.uiDialog.find(".ui-dialog-buttonpane").remove(), typeof b == "object" && b !== null && a.each(b, function () {
+            return!(d = !0)
+        }), d && (a.each(b, function (b, d) {
+            d = a.isFunction(d) ? {click: d, text: b} : d;
+            var e = a('<button type="button"></button>').click(function () {
+                d.click.apply(c.element[0], arguments)
+            }).appendTo(g);
+            a.each(d, function (a, b) {
+                if (a === "click")return;
+                a in f ? e[a](b) : e.attr(a, b)
+            }), a.fn.button && e.button()
+        }), e.appendTo(c.uiDialog))
+    }, _makeDraggable: function () {
+        function f(a) {
+            return{position: a.position, offset: a.offset}
+        }
+
+        var b = this, c = b.options, d = a(document), e;
+        b.uiDialog.draggable({cancel: ".ui-dialog-content, .ui-dialog-titlebar-close", handle: ".ui-dialog-titlebar", containment: "document", start: function (d, g) {
+            e = c.height === "auto" ? "auto" : a(this).height(), a(this).height(a(this).height()).addClass("ui-dialog-dragging"), b._trigger("dragStart", d, f(g))
+        }, drag: function (a, c) {
+            b._trigger("drag", a, f(c))
+        }, stop: function (g, h) {
+            c.position = [h.position.left - d.scrollLeft(), h.position.top - d.scrollTop()], a(this).removeClass("ui-dialog-dragging").height(e), b._trigger("dragStop", g, f(h)), a.ui.dialog.overlay.resize()
+        }})
+    }, _makeResizable: function (c) {
+        function h(a) {
+            return{originalPosition: a.originalPosition, originalSize: a.originalSize, position: a.position, size: a.size}
+        }
+
+        c = c === b ? this.options.resizable : c;
+        var d = this, e = d.options, f = d.uiDialog.css("position"), g = typeof c == "string" ? c : "n,e,s,w,se,sw,ne,nw";
+        d.uiDialog.resizable({cancel: ".ui-dialog-content", containment: "document", alsoResize: d.element, maxWidth: e.maxWidth, maxHeight: e.maxHeight, minWidth: e.minWidth, minHeight: d._minHeight(), handles: g, start: function (b, c) {
+            a(this).addClass("ui-dialog-resizing"), d._trigger("resizeStart", b, h(c))
+        }, resize: function (a, b) {
+            d._trigger("resize", a, h(b))
+        }, stop: function (b, c) {
+            a(this).removeClass("ui-dialog-resizing"), e.height = a(this).height(), e.width = a(this).width(), d._trigger("resizeStop", b, h(c)), a.ui.dialog.overlay.resize()
+        }}).css("position", f).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")
+    }, _minHeight: function () {
+        var a = this.options;
+        return a.height === "auto" ? a.minHeight : Math.min(a.minHeight, a.height)
+    }, _position: function (b) {
+        var c = [], d = [0, 0], e;
+        if (b) {
+            if (typeof b == "string" || typeof b == "object" && "0"in b)c = b.split ? b.split(" ") : [b[0], b[1]], c.length === 1 && (c[1] = c[0]), a.each(["left", "top"], function (a, b) {
+                +c[a] === c[a] && (d[a] = c[a], c[a] = b)
+            }), b = {my: c.join(" "), at: c.join(" "), offset: d.join(" ")};
+            b = a.extend({}, a.ui.dialog.prototype.options.position, b)
+        } else b = a.ui.dialog.prototype.options.position;
+        e = this.uiDialog.is(":visible"), e || this.uiDialog.show(), this.uiDialog.css({top: 0, left: 0}).position(a.extend({of: window}, b)), e || this.uiDialog.hide()
+    }, _setOptions: function (b) {
+        var c = this, f = {}, g = !1;
+        a.each(b, function (a, b) {
+            c._setOption(a, b), a in d && (g = !0), a in e && (f[a] = b)
+        }), g && this._size(), this.uiDialog.is(":data(resizable)") && this.uiDialog.resizable("option", f)
+    }, _setOption: function (b, d) {
+        var e = this, f = e.uiDialog;
+        switch (b) {
+            case"beforeclose":
+                b = "beforeClose";
+                break;
+            case"buttons":
+                e._createButtons(d);
+                break;
+            case"closeText":
+                e.uiDialogTitlebarCloseText.text("" + d);
+                break;
+            case"dialogClass":
+                f.removeClass(e.options.dialogClass).addClass(c + d);
+                break;
+            case"disabled":
+                d ? f.addClass("ui-dialog-disabled") : f.removeClass("ui-dialog-disabled");
+                break;
+            case"draggable":
+                var g = f.is(":data(draggable)");
+                g && !d && f.draggable("destroy"), !g && d && e._makeDraggable();
+                break;
+            case"position":
+                e._position(d);
+                break;
+            case"resizable":
+                var h = f.is(":data(resizable)");
+                h && !d && f.resizable("destroy"), h && typeof d == "string" && f.resizable("option", "handles", d), !h && d !== !1 && e._makeResizable(d);
+                break;
+            case"title":
+                a(".ui-dialog-title", e.uiDialogTitlebar).html("" + (d || "&#160;"))
+        }
+        a.Widget.prototype._setOption.apply(e, arguments)
+    }, _size: function () {
+        var b = this.options, c, d, e = this.uiDialog.is(":visible");
+        this.element.show().css({width: "auto", minHeight: 0, height: 0}), b.minWidth > b.width && (b.width = b.minWidth), c = this.uiDialog.css({height: "auto", width: b.width}).height(), d = Math.max(0, b.minHeight - c);
+        if (b.height === "auto")if (a.support.minHeight)this.element.css({minHeight: d, height: "auto"}); else {
+            this.uiDialog.show();
+            var f = this.element.css("height", "auto").height();
+            e || this.uiDialog.hide(), this.element.height(Math.max(f, d))
+        } else this.element.height(Math.max(b.height - c, 0));
+        this.uiDialog.is(":data(resizable)") && this.uiDialog.resizable("option", "minHeight", this._minHeight())
+    }}), a.extend(a.ui.dialog, {version: "1.8.21", uuid: 0, maxZ: 0, getTitleId: function (a) {
+        var b = a.attr("id");
+        return b || (this.uuid += 1, b = this.uuid), "ui-dialog-title-" + b
+    }, overlay: function (b) {
+        this.$el = a.ui.dialog.overlay.create(b)
+    }}), a.extend(a.ui.dialog.overlay, {instances: [], oldInstances: [], maxZ: 0, events: a.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function (a) {
+        return a + ".dialog-overlay"
+    }).join(" "), create: function (b) {
+        this.instances.length === 0 && (setTimeout(function () {
+            a.ui.dialog.overlay.instances.length && a(document).bind(a.ui.dialog.overlay.events, function (b) {
+                if (a(b.target).zIndex() < a.ui.dialog.overlay.maxZ)return!1
+            })
+        }, 1), a(document).bind("keydown.dialog-overlay", function (c) {
+            b.options.closeOnEscape && !c.isDefaultPrevented() && c.keyCode && c.keyCode === a.ui.keyCode.ESCAPE && (b.close(c), c.preventDefault())
+        }), a(window).bind("resize.dialog-overlay", a.ui.dialog.overlay.resize));
+        var c = (this.oldInstances.pop() || a("<div></div>").addClass("ui-widget-overlay")).appendTo(document.body).css({width: this.width(), height: this.height()});
+        return a.fn.bgiframe && c.bgiframe(), this.instances.push(c), c
+    }, destroy: function (b) {
+        var c = a.inArray(b, this.instances);
+        c != -1 && this.oldInstances.push(this.instances.splice(c, 1)[0]), this.instances.length === 0 && a([document, window]).unbind(".dialog-overlay"), b.remove();
+        var d = 0;
+        a.each(this.instances, function () {
+            d = Math.max(d, this.css("z-index"))
+        }), this.maxZ = d
+    }, height: function () {
+        var b, c;
+        return a.browser.msie && a.browser.version < 7 ? (b = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight), c = Math.max(document.documentElement.offsetHeight, document.body.offsetHeight), b < c ? a(window).height() + "px" : b + "px") : a(document).height() + "px"
+    }, width: function () {
+        var b, c;
+        return a.browser.msie ? (b = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth), c = Math.max(document.documentElement.offsetWidth, document.body.offsetWidth), b < c ? a(window).width() + "px" : b + "px") : a(document).width() + "px"
+    }, resize: function () {
+        var b = a([]);
+        a.each(a.ui.dialog.overlay.instances, function () {
+            b = b.add(this)
+        }), b.css({width: 0, height: 0}).css({width: a.ui.dialog.overlay.width(), height: a.ui.dialog.overlay.height()})
+    }}), a.extend(a.ui.dialog.overlay.prototype, {destroy: function () {
+        a.ui.dialog.overlay.destroy(this.$el)
+    }})
+})(jQuery);
+;
+/*! jQuery UI - v1.8.21 - 2012-06-05
+ * https://github.com/jquery/jquery-ui
+ * Includes: jquery.ui.tabs.js
+ * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
+(function (a, b) {
+    function e() {
+        return++c
+    }
+
+    function f() {
+        return++d
+    }
+
+    var c = 0, d = 0;
+    a.widget("ui.tabs", {options: {add: null, ajaxOptions: null, cache: !1, cookie: null, collapsible: !1, disable: null, disabled: [], enable: null, event: "click", fx: null, idPrefix: "ui-tabs-", load: null, panelTemplate: "<div></div>", remove: null, select: null, show: null, spinner: "<em>Loading&#8230;</em>", tabTemplate: "<li><a href='#{href}'><span>#{label}</span></a></li>"}, _create: function () {
+        this._tabify(!0)
+    }, _setOption: function (a, b) {
+        if (a == "selected") {
+            if (this.options.collapsible && b == this.options.selected)return;
+            this.select(b)
+        } else this.options[a] = b, this._tabify()
+    }, _tabId: function (a) {
+        return a.title && a.title.replace(/\s/g, "_").replace(/[^\w\u00c0-\uFFFF-]/g, "") || this.options.idPrefix + e()
+    }, _sanitizeSelector: function (a) {
+        return a.replace(/:/g, "\\:")
+    }, _cookie: function () {
+        var b = this.cookie || (this.cookie = this.options.cookie.name || "ui-tabs-" + f());
+        return a.cookie.apply(null, [b].concat(a.makeArray(arguments)))
+    }, _ui: function (a, b) {
+        return{tab: a, panel: b, index: this.anchors.index(a)}
+    }, _cleanup: function () {
+        this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function () {
+            var b = a(this);
+            b.html(b.data("label.tabs")).removeData("label.tabs")
+        })
+    }, _tabify: function (c) {
+        function m(b, c) {
+            b.css("display", ""), !a.support.opacity && c.opacity && b[0].style.removeAttribute("filter")
+        }
+
+        var d = this, e = this.options, f = /^#.+/;
+        this.list = this.element.find("ol,ul").eq(0), this.lis = a(" > li:has(a[href])", this.list), this.anchors = this.lis.map(function () {
+            return a("a", this)[0]
+        }), this.panels = a([]), this.anchors.each(function (b, c) {
+            var g = a(c).attr("href"), h = g.split("#")[0], i;
+            h && (h === location.toString().split("#")[0] || (i = a("base")[0]) && h === i.href) && (g = c.hash, c.href = g);
+            if (f.test(g))d.panels = d.panels.add(d.element.find(d._sanitizeSelector(g))); else if (g && g !== "#") {
+                a.data(c, "href.tabs", g), a.data(c, "load.tabs", g.replace(/#.*$/, ""));
+                var j = d._tabId(c);
+                c.href = "#" + j;
+                var k = d.element.find("#" + j);
+                k.length || (k = a(e.panelTemplate).attr("id", j).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(d.panels[b - 1] || d.list), k.data("destroy.tabs", !0)), d.panels = d.panels.add(k)
+            } else e.disabled.push(b)
+        }), c ? (this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all"), this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"), this.lis.addClass("ui-state-default ui-corner-top"), this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom"), e.selected === b ? (location.hash && this.anchors.each(function (a, b) {
+            if (b.hash == location.hash)return e.selected = a, !1
+        }), typeof e.selected != "number" && e.cookie && (e.selected = parseInt(d._cookie(), 10)), typeof e.selected != "number" && this.lis.filter(".ui-tabs-selected").length && (e.selected = this.lis.index(this.lis.filter(".ui-tabs-selected"))), e.selected = e.selected || (this.lis.length ? 0 : -1)) : e.selected === null && (e.selected = -1), e.selected = e.selected >= 0 && this.anchors[e.selected] || e.selected < 0 ? e.selected : 0, e.disabled = a.unique(e.disabled.concat(a.map(this.lis.filter(".ui-state-disabled"), function (a, b) {
+            return d.lis.index(a)
+        }))).sort(), a.inArray(e.selected, e.disabled) != -1 && e.disabled.splice(a.inArray(e.selected, e.disabled), 1), this.panels.addClass("ui-tabs-hide"), this.lis.removeClass("ui-tabs-selected ui-state-active"), e.selected >= 0 && this.anchors.length && (d.element.find(d._sanitizeSelector(d.anchors[e.selected].hash)).removeClass("ui-tabs-hide"), this.lis.eq(e.selected).addClass("ui-tabs-selected ui-state-active"), d.element.queue("tabs", function () {
+            d._trigger("show", null, d._ui(d.anchors[e.selected], d.element.find(d._sanitizeSelector(d.anchors[e.selected].hash))[0]))
+        }), this.load(e.selected)), a(window).bind("unload", function () {
+            d.lis.add(d.anchors).unbind(".tabs"), d.lis = d.anchors = d.panels = null
+        })) : e.selected = this.lis.index(this.lis.filter(".ui-tabs-selected")), this.element[e.collapsible ? "addClass" : "removeClass"]("ui-tabs-collapsible"), e.cookie && this._cookie(e.selected, e.cookie);
+        for (var g = 0, h; h = this.lis[g]; g++)a(h)[a.inArray(g, e.disabled) != -1 && !a(h).hasClass("ui-tabs-selected") ? "addClass" : "removeClass"]("ui-state-disabled");
+        e.cache === !1 && this.anchors.removeData("cache.tabs"), this.lis.add(this.anchors).unbind(".tabs");
+        if (e.event !== "mouseover") {
+            var i = function (a, b) {
+                b.is(":not(.ui-state-disabled)") && b.addClass("ui-state-" + a)
+            }, j = function (a, b) {
+                b.removeClass("ui-state-" + a)
+            };
+            this.lis.bind("mouseover.tabs", function () {
+                i("hover", a(this))
+            }), this.lis.bind("mouseout.tabs", function () {
+                j("hover", a(this))
+            }), this.anchors.bind("focus.tabs", function () {
+                i("focus", a(this).closest("li"))
+            }), this.anchors.bind("blur.tabs", function () {
+                j("focus", a(this).closest("li"))
+            })
+        }
+        var k, l;
+        e.fx && (a.isArray(e.fx) ? (k = e.fx[0], l = e.fx[1]) : k = l = e.fx);
+        var n = l ? function (b, c) {
+            a(b).closest("li").addClass("ui-tabs-selected ui-state-active"), c.hide().removeClass("ui-tabs-hide").animate(l, l.duration || "normal", function () {
+                m(c, l), d._trigger("show", null, d._ui(b, c[0]))
+            })
+        } : function (b, c) {
+            a(b).closest("li").addClass("ui-tabs-selected ui-state-active"), c.removeClass("ui-tabs-hide"), d._trigger("show", null, d._ui(b, c[0]))
+        }, o = k ? function (a, b) {
+            b.animate(k, k.duration || "normal", function () {
+                d.lis.removeClass("ui-tabs-selected ui-state-active"), b.addClass("ui-tabs-hide"), m(b, k), d.element.dequeue("tabs")
+            })
+        } : function (a, b, c) {
+            d.lis.removeClass("ui-tabs-selected ui-state-active"), b.addClass("ui-tabs-hide"), d.element.dequeue("tabs")
+        };
+        this.anchors.bind(e.event + ".tabs", function () {
+            var b = this, c = a(b).closest("li"), f = d.panels.filter(":not(.ui-tabs-hide)"), g = d.element.find(d._sanitizeSelector(b.hash));
+            if (c.hasClass("ui-tabs-selected") && !e.collapsible || c.hasClass("ui-state-disabled") || c.hasClass("ui-state-processing") || d.panels.filter(":animated").length || d._trigger("select", null, d._ui(this, g[0])) === !1)return this.blur(), !1;
+            e.selected = d.anchors.index(this), d.abort();
+            if (e.collapsible) {
+                if (c.hasClass("ui-tabs-selected"))return e.selected = -1, e.cookie && d._cookie(e.selected, e.cookie), d.element.queue("tabs",function () {
+                    o(b, f)
+                }).dequeue("tabs"), this.blur(), !1;
+                if (!f.length)return e.cookie && d._cookie(e.selected, e.cookie), d.element.queue("tabs", function () {
+                    n(b, g)
+                }), d.load(d.anchors.index(this)), this.blur(), !1
+            }
+            e.cookie && d._cookie(e.selected, e.cookie);
+            if (g.length)f.length && d.element.queue("tabs", function () {
+                o(b, f)
+            }), d.element.queue("tabs", function () {
+                n(b, g)
+            }), d.load(d.anchors.index(this)); else throw"jQuery UI Tabs: Mismatching fragment identifier.";
+            a.browser.msie && this.blur()
+        }), this.anchors.bind("click.tabs", function () {
+            return!1
+        })
+    }, _getIndex: function (a) {
+        return typeof a == "string" && (a = this.anchors.index(this.anchors.filter("[href$='" + a + "']"))), a
+    }, destroy: function () {
+        var b = this.options;
+        return this.abort(), this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs"), this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"), this.anchors.each(function () {
+            var b = a.data(this, "href.tabs");
+            b && (this.href = b);
+            var c = a(this).unbind(".tabs");
+            a.each(["href", "load", "cache"], function (a, b) {
+                c.removeData(b + ".tabs")
+            })
+        }), this.lis.unbind(".tabs").add(this.panels).each(function () {
+            a.data(this, "destroy.tabs") ? a(this).remove() : a(this).removeClass(["ui-state-default", "ui-corner-top", "ui-tabs-selected", "ui-state-active", "ui-state-hover", "ui-state-focus", "ui-state-disabled", "ui-tabs-panel", "ui-widget-content", "ui-corner-bottom", "ui-tabs-hide"].join(" "))
+        }), b.cookie && this._cookie(null, b.cookie), this
+    }, add: function (c, d, e) {
+        e === b && (e = this.anchors.length);
+        var f = this, g = this.options, h = a(g.tabTemplate.replace(/#\{href\}/g, c).replace(/#\{label\}/g, d)), i = c.indexOf("#") ? this._tabId(a("a", h)[0]) : c.replace("#", "");
+        h.addClass("ui-state-default ui-corner-top").data("destroy.tabs", !0);
+        var j = f.element.find("#" + i);
+        return j.length || (j = a(g.panelTemplate).attr("id", i).data("destroy.tabs", !0)), j.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide"), e >= this.lis.length ? (h.appendTo(this.list), j.appendTo(this.list[0].parentNode)) : (h.insertBefore(this.lis[e]), j.insertBefore(this.panels[e])), g.disabled = a.map(g.disabled, function (a, b) {
+            return a >= e ? ++a : a
+        }), this._tabify(), this.anchors.length == 1 && (g.selected = 0, h.addClass("ui-tabs-selected ui-state-active"), j.removeClass("ui-tabs-hide"), this.element.queue("tabs", function () {
+            f._trigger("show", null, f._ui(f.anchors[0], f.panels[0]))
+        }), this.load(0)), this._trigger("add", null, this._ui(this.anchors[e], this.panels[e])), this
+    }, remove: function (b) {
+        b = this._getIndex(b);
+        var c = this.options, d = this.lis.eq(b).remove(), e = this.panels.eq(b).remove();
+        return d.hasClass("ui-tabs-selected") && this.anchors.length > 1 && this.select(b + (b + 1 < this.anchors.length ? 1 : -1)), c.disabled = a.map(a.grep(c.disabled, function (a, c) {
+            return a != b
+        }), function (a, c) {
+            return a >= b ? --a : a
+        }), this._tabify(), this._trigger("remove", null, this._ui(d.find("a")[0], e[0])), this
+    }, enable: function (b) {
+        b = this._getIndex(b);
+        var c = this.options;
+        if (a.inArray(b, c.disabled) == -1)return;
+        return this.lis.eq(b).removeClass("ui-state-disabled"), c.disabled = a.grep(c.disabled, function (a, c) {
+            return a != b
+        }), this._trigger("enable", null, this._ui(this.anchors[b], this.panels[b])), this
+    }, disable: function (a) {
+        a = this._getIndex(a);
+        var b = this, c = this.options;
+        return a != c.selected && (this.lis.eq(a).addClass("ui-state-disabled"), c.disabled.push(a), c.disabled.sort(), this._trigger("disable", null, this._ui(this.anchors[a], this.panels[a]))), this
+    }, select: function (a) {
+        a = this._getIndex(a);
+        if (a == -1)if (this.options.collapsible && this.options.selected != -1)a = this.options.selected; else return this;
+        return this.anchors.eq(a).trigger(this.options.event + ".tabs"), this
+    }, load: function (b) {
+        b = this._getIndex(b);
+        var c = this, d = this.options, e = this.anchors.eq(b)[0], f = a.data(e, "load.tabs");
+        this.abort();
+        if (!f || this.element.queue("tabs").length !== 0 && a.data(e, "cache.tabs")) {
+            this.element.dequeue("tabs");
+            return
+        }
+        this.lis.eq(b).addClass("ui-state-processing");
+        if (d.spinner) {
+            var g = a("span", e);
+            g.data("label.tabs", g.html()).html(d.spinner)
+        }
+        return this.xhr = a.ajax(a.extend({}, d.ajaxOptions, {url: f, success: function (f, g) {
+            c.element.find(c._sanitizeSelector(e.hash)).html(f), c._cleanup(), d.cache && a.data(e, "cache.tabs", !0), c._trigger("load", null, c._ui(c.anchors[b], c.panels[b]));
+            try {
+                d.ajaxOptions.success(f, g)
+            } catch (h) {
+            }
+        }, error: function (a, f, g) {
+            c._cleanup(), c._trigger("load", null, c._ui(c.anchors[b], c.panels[b]));
+            try {
+                d.ajaxOptions.error(a, f, b, e)
+            } catch (g) {
+            }
+        }})), c.element.dequeue("tabs"), this
+    }, abort: function () {
+        return this.element.queue([]), this.panels.stop(!1, !0), this.element.queue("tabs", this.element.queue("tabs").splice(-2, 2)), this.xhr && (this.xhr.abort(), delete this.xhr), this._cleanup(), this
+    }, url: function (a, b) {
+        return this.anchors.eq(a).removeData("cache.tabs").data("load.tabs", b), this
+    }, length: function () {
+        return this.anchors.length
+    }}), a.extend(a.ui.tabs, {version: "1.8.21"}), a.extend(a.ui.tabs.prototype, {rotation: null, rotate: function (a, b) {
+        var c = this, d = this.options, e = c._rotate || (c._rotate = function (b) {
+            clearTimeout(c.rotation), c.rotation = setTimeout(function () {
+                var a = d.selected;
+                c.select(++a < c.anchors.length ? a : 0)
+            }, a), b && b.stopPropagation()
+        }), f = c._unrotate || (c._unrotate = b ? function (a) {
+            e()
+        } : function (a) {
+            a.clientX && c.rotate(null)
+        });
+        return a ? (this.element.bind("tabsshow", e), this.anchors.bind(d.event + ".tabs", f), e()) : (clearTimeout(c.rotation), this.element.unbind("tabsshow", e), this.anchors.unbind(d.event + ".tabs", f), delete this._rotate, delete this._unrotate), this
+    }})
+})(jQuery);
+;
+/*! jQuery UI - v1.8.21 - 2012-06-05
+ * https://github.com/jquery/jquery-ui
+ * Includes: jquery.ui.datepicker.js
+ * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
+(function ($, undefined) {
+    function Datepicker() {
+        this.debug = !1, this._curInst = null, this._keyEvent = !1, this._disabledInputs = [], this._datepickerShowing = !1, this._inDialog = !1, this._mainDivId = "ui-datepicker-div", this._inlineClass = "ui-datepicker-inline", this._appendClass = "ui-datepicker-append", this._triggerClass = "ui-datepicker-trigger", this._dialogClass = "ui-datepicker-dialog", this._disableClass = "ui-datepicker-disabled", this._unselectableClass = "ui-datepicker-unselectable", this._currentClass = "ui-datepicker-current-day", this._dayOverClass = "ui-datepicker-days-cell-over", this.regional = [], this.regional[""] = {closeText: "Done", prevText: "Prev", nextText: "Next", currentText: "Today", monthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], dayNamesMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], weekHeader: "Wk", dateFormat: "mm/dd/yy", firstDay: 0, isRTL: !1, showMonthAfterYear: !1, yearSuffix: ""}, this._defaults = {showOn: "focus", showAnim: "fadeIn", showOptions: {}, defaultDate: null, appendText: "", buttonText: "...", buttonImage: "", buttonImageOnly: !1, hideIfNoPrevNext: !1, navigationAsDateFormat: !1, gotoCurrent: !1, changeMonth: !1, changeYear: !1, yearRange: "c-10:c+10", showOtherMonths: !1, selectOtherMonths: !1, showWeek: !1, calculateWeek: this.iso8601Week, shortYearCutoff: "+10", minDate: null, maxDate: null, duration: "fast", beforeShowDay: null, beforeShow: null, onSelect: null, onChangeMonthYear: null, onClose: null, numberOfMonths: 1, showCurrentAtPos: 0, stepMonths: 1, stepBigMonths: 12, altField: "", altFormat: "", constrainInput: !0, showButtonPanel: !1, autoSize: !1, disabled: !1}, $.extend(this._defaults, this.regional[""]), this.dpDiv = bindHover($('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))
+    }
+
+    function bindHover(a) {
+        var b = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
+        return a.bind("mouseout",function (a) {
+            var c = $(a.target).closest(b);
+            if (!c.length)return;
+            c.removeClass("ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover")
+        }).bind("mouseover", function (c) {
+            var d = $(c.target).closest(b);
+            if ($.datepicker._isDisabledDatepicker(instActive.inline ? a.parent()[0] : instActive.input[0]) || !d.length)return;
+            d.parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"), d.addClass("ui-state-hover"), d.hasClass("ui-datepicker-prev") && d.addClass("ui-datepicker-prev-hover"), d.hasClass("ui-datepicker-next") && d.addClass("ui-datepicker-next-hover")
+        })
+    }
+
+    function extendRemove(a, b) {
+        $.extend(a, b);
+        for (var c in b)if (b[c] == null || b[c] == undefined)a[c] = b[c];
+        return a
+    }
+
+    function isArray(a) {
+        return a && ($.browser.safari && typeof a == "object" && a.length || a.constructor && a.constructor.toString().match(/\Array\(\)/))
+    }
+
+    $.extend($.ui, {datepicker: {version: "1.8.21"}});
+    var PROP_NAME = "datepicker", dpuuid = (new Date).getTime(), instActive;
+    $.extend(Datepicker.prototype, {markerClassName: "hasDatepicker", maxRows: 4, log: function () {
+        this.debug && console.log.apply("", arguments)
+    }, _widgetDatepicker: function () {
+        return this.dpDiv
+    }, setDefaults: function (a) {
+        return extendRemove(this._defaults, a || {}), this
+    }, _attachDatepicker: function (target, settings) {
+        var inlineSettings = null;
+        for (var attrName in this._defaults) {
+            var attrValue = target.getAttribute("date:" + attrName);
+            if (attrValue) {
+                inlineSettings = inlineSettings || {};
+                try {
+                    inlineSettings[attrName] = eval(attrValue)
+                } catch (err) {
+                    inlineSettings[attrName] = attrValue
+                }
+            }
+        }
+        var nodeName = target.nodeName.toLowerCase(), inline = nodeName == "div" || nodeName == "span";
+        target.id || (this.uuid += 1, target.id = "dp" + this.uuid);
+        var inst = this._newInst($(target), inline);
+        inst.settings = $.extend({}, settings || {}, inlineSettings || {}), nodeName == "input" ? this._connectDatepicker(target, inst) : inline && this._inlineDatepicker(target, inst)
+    }, _newInst: function (a, b) {
+        var c = a[0].id.replace(/([^A-Za-z0-9_-])/g, "\\\\$1");
+        return{id: c, input: a, selectedDay: 0, selectedMonth: 0, selectedYear: 0, drawMonth: 0, drawYear: 0, inline: b, dpDiv: b ? bindHover($('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')) : this.dpDiv}
+    }, _connectDatepicker: function (a, b) {
+        var c = $(a);
+        b.append = $([]), b.trigger = $([]);
+        if (c.hasClass(this.markerClassName))return;
+        this._attachments(c, b), c.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function (a, c, d) {
+            b.settings[c] = d
+        }).bind("getData.datepicker", function (a, c) {
+            return this._get(b, c)
+        }), this._autoSize(b), $.data(a, PROP_NAME, b), b.settings.disabled && this._disableDatepicker(a)
+    }, _attachments: function (a, b) {
+        var c = this._get(b, "appendText"), d = this._get(b, "isRTL");
+        b.append && b.append.remove(), c && (b.append = $('<span class="' + this._appendClass + '">' + c + "</span>"), a[d ? "before" : "after"](b.append)), a.unbind("focus", this._showDatepicker), b.trigger && b.trigger.remove();
+        var e = this._get(b, "showOn");
+        (e == "focus" || e == "both") && a.focus(this._showDatepicker);
+        if (e == "button" || e == "both") {
+            var f = this._get(b, "buttonText"), g = this._get(b, "buttonImage");
+            b.trigger = $(this._get(b, "buttonImageOnly") ? $("<img/>").addClass(this._triggerClass).attr({src: g, alt: f, title: f}) : $('<button type="button"></button>').addClass(this._triggerClass).html(g == "" ? f : $("<img/>").attr({src: g, alt: f, title: f}))), a[d ? "before" : "after"](b.trigger), b.trigger.click(function () {
+                return $.datepicker._datepickerShowing && $.datepicker._lastInput == a[0] ? $.datepicker._hideDatepicker() : $.datepicker._datepickerShowing && $.datepicker._lastInput != a[0] ? ($.datepicker._hideDatepicker(), $.datepicker._showDatepicker(a[0])) : $.datepicker._showDatepicker(a[0]), !1
+            })
+        }
+    }, _autoSize: function (a) {
+        if (this._get(a, "autoSize") && !a.inline) {
+            var b = new Date(2009, 11, 20), c = this._get(a, "dateFormat");
+            if (c.match(/[DM]/)) {
+                var d = function (a) {
+                    var b = 0, c = 0;
+                    for (var d = 0; d < a.length; d++)a[d].length > b && (b = a[d].length, c = d);
+                    return c
+                };
+                b.setMonth(d(this._get(a, c.match(/MM/) ? "monthNames" : "monthNamesShort"))), b.setDate(d(this._get(a, c.match(/DD/) ? "dayNames" : "dayNamesShort")) + 20 - b.getDay())
+            }
+            a.input.attr("size", this._formatDate(a, b).length)
+        }
+    }, _inlineDatepicker: function (a, b) {
+        var c = $(a);
+        if (c.hasClass(this.markerClassName))return;
+        c.addClass(this.markerClassName).append(b.dpDiv).bind("setData.datepicker",function (a, c, d) {
+            b.settings[c] = d
+        }).bind("getData.datepicker", function (a, c) {
+            return this._get(b, c)
+        }), $.data(a, PROP_NAME, b), this._setDate(b, this._getDefaultDate(b), !0), this._updateDatepicker(b), this._updateAlternate(b), b.settings.disabled && this._disableDatepicker(a), b.dpDiv.css("display", "block")
+    }, _dialogDatepicker: function (a, b, c, d, e) {
+        var f = this._dialogInst;
+        if (!f) {
+            this.uuid += 1;
+            var g = "dp" + this.uuid;
+            this._dialogInput = $('<input type="text" id="' + g + '" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>'), this._dialogInput.keydown(this._doKeyDown), $("body").append(this._dialogInput), f = this._dialogInst = this._newInst(this._dialogInput, !1), f.settings = {}, $.data(this._dialogInput[0], PROP_NAME, f)
+        }
+        extendRemove(f.settings, d || {}), b = b && b.constructor == Date ? this._formatDate(f, b) : b, this._dialogInput.val(b), this._pos = e ? e.length ? e : [e.pageX, e.pageY] : null;
+        if (!this._pos) {
+            var h = document.documentElement.clientWidth, i = document.documentElement.clientHeight, j = document.documentElement.scrollLeft || document.body.scrollLeft, k = document.documentElement.scrollTop || document.body.scrollTop;
+            this._pos = [h / 2 - 100 + j, i / 2 - 150 + k]
+        }
+        return this._dialogInput.css("left", this._pos[0] + 20 + "px").css("top", this._pos[1] + "px"), f.settings.onSelect = c, this._inDialog = !0, this.dpDiv.addClass(this._dialogClass), this._showDatepicker(this._dialogInput[0]), $.blockUI && $.blockUI(this.dpDiv), $.data(this._dialogInput[0], PROP_NAME, f), this
+    }, _destroyDatepicker: function (a) {
+        var b = $(a), c = $.data(a, PROP_NAME);
+        if (!b.hasClass(this.markerClassName))return;
+        var d = a.nodeName.toLowerCase();
+        $.removeData(a, PROP_NAME), d == "input" ? (c.append.remove(), c.trigger.remove(), b.removeClass(this.markerClassName).unbind("focus", this._showDatepicker).unbind("keydown", this._doKeyDown).unbind("keypress", this._doKeyPress).unbind("keyup", this._doKeyUp)) : (d == "div" || d == "span") && b.removeClass(this.markerClassName).empty()
+    }, _enableDatepicker: function (a) {
+        var b = $(a), c = $.data(a, PROP_NAME);
+        if (!b.hasClass(this.markerClassName))return;
+        var d = a.nodeName.toLowerCase();
+        if (d == "input")a.disabled = !1, c.trigger.filter("button").each(function () {
+            this.disabled = !1
+        }).end().filter("img").css({opacity: "1.0", cursor: ""}); else if (d == "div" || d == "span") {
+            var e = b.children("." + this._inlineClass);
+            e.children().removeClass("ui-state-disabled"), e.find("select.ui-datepicker-month, select.ui-datepicker-year").removeAttr("disabled")
+        }
+        this._disabledInputs = $.map(this._disabledInputs, function (b) {
+            return b == a ? null : b
+        })
+    }, _disableDatepicker: function (a) {
+        var b = $(a), c = $.data(a, PROP_NAME);
+        if (!b.hasClass(this.markerClassName))return;
+        var d = a.nodeName.toLowerCase();
+        if (d == "input")a.disabled = !0, c.trigger.filter("button").each(function () {
+            this.disabled = !0
+        }).end().filter("img").css({opacity: "0.5", cursor: "default"}); else if (d == "div" || d == "span") {
+            var e = b.children("." + this._inlineClass);
+            e.children().addClass("ui-state-disabled"), e.find("select.ui-datepicker-month, select.ui-datepicker-year").attr("disabled", "disabled")
+        }
+        this._disabledInputs = $.map(this._disabledInputs, function (b) {
+            return b == a ? null : b
+        }), this._disabledInputs[this._disabledInputs.length] = a
+    }, _isDisabledDatepicker: function (a) {
+        if (!a)return!1;
+        for (var b = 0; b < this._disabledInputs.length; b++)if (this._disabledInputs[b] == a)return!0;
+        return!1
+    }, _getInst: function (a) {
+        try {
+            return $.data(a, PROP_NAME)
+        } catch (b) {
+            throw"Missing instance data for this datepicker"
+        }
+    }, _optionDatepicker: function (a, b, c) {
+        var d = this._getInst(a);
+        if (arguments.length == 2 && typeof b == "string")return b == "defaults" ? $.extend({}, $.datepicker._defaults) : d ? b == "all" ? $.extend({}, d.settings) : this._get(d, b) : null;
+        var e = b || {};
+        typeof b == "string" && (e = {}, e[b] = c);
+        if (d) {
+            this._curInst == d && this._hideDatepicker();
+            var f = this._getDateDatepicker(a, !0), g = this._getMinMaxDate(d, "min"), h = this._getMinMaxDate(d, "max");
+            extendRemove(d.settings, e), g !== null && e.dateFormat !== undefined && e.minDate === undefined && (d.settings.minDate = this._formatDate(d, g)), h !== null && e.dateFormat !== undefined && e.maxDate === undefined && (d.settings.maxDate = this._formatDate(d, h)), this._attachments($(a), d), this._autoSize(d), this._setDate(d, f), this._updateAlternate(d), this._updateDatepicker(d)
+        }
+    }, _changeDatepicker: function (a, b, c) {
+        this._optionDatepicker(a, b, c)
+    }, _refreshDatepicker: function (a) {
+        var b = this._getInst(a);
+        b && this._updateDatepicker(b)
+    }, _setDateDatepicker: function (a, b) {
+        var c = this._getInst(a);
+        c && (this._setDate(c, b), this._updateDatepicker(c), this._updateAlternate(c))
+    }, _getDateDatepicker: function (a, b) {
+        var c = this._getInst(a);
+        return c && !c.inline && this._setDateFromField(c, b), c ? this._getDate(c) : null
+    }, _doKeyDown: function (a) {
+        var b = $.datepicker._getInst(a.target), c = !0, d = b.dpDiv.is(".ui-datepicker-rtl");
+        b._keyEvent = !0;
+        if ($.datepicker._datepickerShowing)switch (a.keyCode) {
+            case 9:
+                $.datepicker._hideDatepicker(), c = !1;
+                break;
+            case 13:
+                var e = $("td." + $.datepicker._dayOverClass + ":not(." + $.datepicker._currentClass + ")", b.dpDiv);
+                e[0] && $.datepicker._selectDay(a.target, b.selectedMonth, b.selectedYear, e[0]);
+                var f = $.datepicker._get(b, "onSelect");
+                if (f) {
+                    var g = $.datepicker._formatDate(b);
+                    f.apply(b.input ? b.input[0] : null, [g, b])
+                } else $.datepicker._hideDatepicker();
+                return!1;
+            case 27:
+                $.datepicker._hideDatepicker();
+                break;
+            case 33:
+                $.datepicker._adjustDate(a.target, a.ctrlKey ? -$.datepicker._get(b, "stepBigMonths") : -$.datepicker._get(b, "stepMonths"), "M");
+                break;
+            case 34:
+                $.datepicker._adjustDate(a.target, a.ctrlKey ? +$.datepicker._get(b, "stepBigMonths") : +$.datepicker._get(b, "stepMonths"), "M");
+                break;
+            case 35:
+                (a.ctrlKey || a.metaKey) && $.datepicker._clearDate(a.target), c = a.ctrlKey || a.metaKey;
+                break;
+            case 36:
+                (a.ctrlKey || a.metaKey) && $.datepicker._gotoToday(a.target), c = a.ctrlKey || a.metaKey;
+                break;
+            case 37:
+                (a.ctrlKey || a.metaKey) && $.datepicker._adjustDate(a.target, d ? 1 : -1, "D"), c = a.ctrlKey || a.metaKey, a.originalEvent.altKey && $.datepicker._adjustDate(a.target, a.ctrlKey ? -$.datepicker._get(b, "stepBigMonths") : -$.datepicker._get(b, "stepMonths"), "M");
+                break;
+            case 38:
+                (a.ctrlKey || a.metaKey) && $.datepicker._adjustDate(a.target, -7, "D"), c = a.ctrlKey || a.metaKey;
+                break;
+            case 39:
+                (a.ctrlKey || a.metaKey) && $.datepicker._adjustDate(a.target, d ? -1 : 1, "D"), c = a.ctrlKey || a.metaKey, a.originalEvent.altKey && $.datepicker._adjustDate(a.target, a.ctrlKey ? +$.datepicker._get(b, "stepBigMonths") : +$.datepicker._get(b, "stepMonths"), "M");
+                break;
+            case 40:
+                (a.ctrlKey || a.metaKey) && $.datepicker._adjustDate(a.target, 7, "D"), c = a.ctrlKey || a.metaKey;
+                break;
+            default:
+                c = !1
+        } else a.keyCode == 36 && a.ctrlKey ? $.datepicker._showDatepicker(this) : c = !1;
+        c && (a.preventDefault(), a.stopPropagation())
+    }, _doKeyPress: function (a) {
+        var b = $.datepicker._getInst(a.target);
+        if ($.datepicker._get(b, "constrainInput")) {
+            var c = $.datepicker._possibleChars($.datepicker._get(b, "dateFormat")), d = String.fromCharCode(a.charCode == undefined ? a.keyCode : a.charCode);
+            return a.ctrlKey || a.metaKey || d < " " || !c || c.indexOf(d) > -1
+        }
+    }, _doKeyUp: function (a) {
+        var b = $.datepicker._getInst(a.target);
+        if (b.input.val() != b.lastVal)try {
+            var c = $.datepicker.parseDate($.datepicker._get(b, "dateFormat"), b.input ? b.input.val() : null, $.datepicker._getFormatConfig(b));
+            c && ($.datepicker._setDateFromField(b), $.datepicker._updateAlternate(b), $.datepicker._updateDatepicker(b))
+        } catch (d) {
+            $.datepicker.log(d)
+        }
+        return!0
+    }, _showDatepicker: function (a) {
+        a = a.target || a, a.nodeName.toLowerCase() != "input" && (a = $("input", a.parentNode)[0]);
+        if ($.datepicker._isDisabledDatepicker(a) || $.datepicker._lastInput == a)return;
+        var b = $.datepicker._getInst(a);
+        $.datepicker._curInst && $.datepicker._curInst != b && ($.datepicker._curInst.dpDiv.stop(!0, !0), b && $.datepicker._datepickerShowing && $.datepicker._hideDatepicker($.datepicker._curInst.input[0]));
+        var c = $.datepicker._get(b, "beforeShow"), d = c ? c.apply(a, [a, b]) : {};
+        if (d === !1)return;
+        extendRemove(b.settings, d), b.lastVal = null, $.datepicker._lastInput = a, $.datepicker._setDateFromField(b), $.datepicker._inDialog && (a.value = ""), $.datepicker._pos || ($.datepicker._pos = $.datepicker._findPos(a), $.datepicker._pos[1] += a.offsetHeight);
+        var e = !1;
+        $(a).parents().each(function () {
+            return e |= $(this).css("position") == "fixed", !e
+        }), e && $.browser.opera && ($.datepicker._pos[0] -= document.documentElement.scrollLeft, $.datepicker._pos[1] -= document.documentElement.scrollTop);
+        var f = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
+        $.datepicker._pos = null, b.dpDiv.empty(), b.dpDiv.css({position: "absolute", display: "block", top: "-1000px"}), $.datepicker._updateDatepicker(b), f = $.datepicker._checkOffset(b, f, e), b.dpDiv.css({position: $.datepicker._inDialog && $.blockUI ? "static" : e ? "fixed" : "absolute", display: "none", left: f.left + "px", top: f.top + "px"});
+        if (!b.inline) {
+            var g = $.datepicker._get(b, "showAnim"), h = $.datepicker._get(b, "duration"), i = function () {
+                var a = b.dpDiv.find("iframe.ui-datepicker-cover");
+                if (!!a.length) {
+                    var c = $.datepicker._getBorders(b.dpDiv);
+                    a.css({left: -c[0], top: -c[1], width: b.dpDiv.outerWidth(), height: b.dpDiv.outerHeight()})
+                }
+            };
+            b.dpDiv.zIndex($(a).zIndex() + 1), $.datepicker._datepickerShowing = !0, $.effects && $.effects[g] ? b.dpDiv.show(g, $.datepicker._get(b, "showOptions"), h, i) : b.dpDiv[g || "show"](g ? h : null, i), (!g || !h) && i(), b.input.is(":visible") && !b.input.is(":disabled") && b.input.focus(), $.datepicker._curInst = b
+        }
+    }, _updateDatepicker: function (a) {
+        var b = this;
+        b.maxRows = 4;
+        var c = $.datepicker._getBorders(a.dpDiv);
+        instActive = a, a.dpDiv.empty().append(this._generateHTML(a));
+        var d = a.dpDiv.find("iframe.ui-datepicker-cover");
+        !d.length || d.css({left: -c[0], top: -c[1], width: a.dpDiv.outerWidth(), height: a.dpDiv.outerHeight()}), a.dpDiv.find("." + this._dayOverClass + " a").mouseover();
+        var e = this._getNumberOfMonths(a), f = e[1], g = 17;
+        a.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""), f > 1 && a.dpDiv.addClass("ui-datepicker-multi-" + f).css("width", g * f + "em"), a.dpDiv[(e[0] != 1 || e[1] != 1 ? "add" : "remove") + "Class"]("ui-datepicker-multi"), a.dpDiv[(this._get(a, "isRTL") ? "add" : "remove") + "Class"]("ui-datepicker-rtl"), a == $.datepicker._curInst && $.datepicker._datepickerShowing && a.input && a.input.is(":visible") && !a.input.is(":disabled") && a.input[0] != document.activeElement && a.input.focus();
+        if (a.yearshtml) {
+            var h = a.yearshtml;
+            setTimeout(function () {
+                h === a.yearshtml && a.yearshtml && a.dpDiv.find("select.ui-datepicker-year:first").replaceWith(a.yearshtml), h = a.yearshtml = null
+            }, 0)
+        }
+    }, _getBorders: function (a) {
+        var b = function (a) {
+            return{thin: 1, medium: 2, thick: 3}[a] || a
+        };
+        return[parseFloat(b(a.css("border-left-width"))), parseFloat(b(a.css("border-top-width")))]
+    }, _checkOffset: function (a, b, c) {
+        var d = a.dpDiv.outerWidth(), e = a.dpDiv.outerHeight(), f = a.input ? a.input.outerWidth() : 0, g = a.input ? a.input.outerHeight() : 0, h = document.documentElement.clientWidth + $(document).scrollLeft(), i = document.documentElement.clientHeight + $(document).scrollTop();
+        return b.left -= this._get(a, "isRTL") ? d - f : 0, b.left -= c && b.left == a.input.offset().left ? $(document).scrollLeft() : 0, b.top -= c && b.top == a.input.offset().top + g ? $(document).scrollTop() : 0, b.left -= Math.min(b.left, b.left + d > h && h > d ? Math.abs(b.left + d - h) : 0), b.top -= Math.min(b.top, b.top + e > i && i > e ? Math.abs(e + g) : 0), b
+    }, _findPos: function (a) {
+        var b = this._getInst(a), c = this._get(b, "isRTL");
+        while (a && (a.type == "hidden" || a.nodeType != 1 || $.expr.filters.hidden(a)))a = a[c ? "previousSibling" : "nextSibling"];
+        var d = $(a).offset();
+        return[d.left, d.top]
+    }, _hideDatepicker: function (a) {
+        var b = this._curInst;
+        if (!b || a && b != $.data(a, PROP_NAME))return;
+        if (this._datepickerShowing) {
+            var c = this._get(b, "showAnim"), d = this._get(b, "duration"), e = function () {
+                $.datepicker._tidyDialog(b)
+            };
+            $.effects && $.effects[c] ? b.dpDiv.hide(c, $.datepicker._get(b, "showOptions"), d, e) : b.dpDiv[c == "slideDown" ? "slideUp" : c == "fadeIn" ? "fadeOut" : "hide"](c ? d : null, e), c || e(), this._datepickerShowing = !1;
+            var f = this._get(b, "onClose");
+            f && f.apply(b.input ? b.input[0] : null, [b.input ? b.input.val() : "", b]), this._lastInput = null, this._inDialog && (this._dialogInput.css({position: "absolute", left: "0", top: "-100px"}), $.blockUI && ($.unblockUI(), $("body").append(this.dpDiv))), this._inDialog = !1
+        }
+    }, _tidyDialog: function (a) {
+        a.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")
+    }, _checkExternalClick: function (a) {
+        if (!$.datepicker._curInst)return;
+        var b = $(a.target), c = $.datepicker._getInst(b[0]);
+        (b[0].id != $.datepicker._mainDivId && b.parents("#" + $.datepicker._mainDivId).length == 0 && !b.hasClass($.datepicker.markerClassName) && !b.closest("." + $.datepicker._triggerClass).length && $.datepicker._datepickerShowing && (!$.datepicker._inDialog || !$.blockUI) || b.hasClass($.datepicker.markerClassName) && $.datepicker._curInst != c) && $.datepicker._hideDatepicker()
+    }, _adjustDate: function (a, b, c) {
+        var d = $(a), e = this._getInst(d[0]);
+        if (this._isDisabledDatepicker(d[0]))return;
+        this._adjustInstDate(e, b + (c == "M" ? this._get(e, "showCurrentAtPos") : 0), c), this._updateDatepicker(e)
+    }, _gotoToday: function (a) {
+        var b = $(a), c = this._getInst(b[0]);
+        if (this._get(c, "gotoCurrent") && c.currentDay)c.selectedDay = c.currentDay, c.drawMonth = c.selectedMonth = c.currentMonth, c.drawYear = c.selectedYear = c.currentYear; else {
+            var d = new Date;
+            c.selectedDay = d.getDate(), c.drawMonth = c.selectedMonth = d.getMonth(), c.drawYear = c.selectedYear = d.getFullYear()
+        }
+        this._notifyChange(c), this._adjustDate(b)
+    }, _selectMonthYear: function (a, b, c) {
+        var d = $(a), e = this._getInst(d[0]);
+        e["selected" + (c == "M" ? "Month" : "Year")] = e["draw" + (c == "M" ? "Month" : "Year")] = parseInt(b.options[b.selectedIndex].value, 10), this._notifyChange(e), this._adjustDate(d)
+    }, _selectDay: function (a, b, c, d) {
+        var e = $(a);
+        if ($(d).hasClass(this._unselectableClass) || this._isDisabledDatepicker(e[0]))return;
+        var f = this._getInst(e[0]);
+        f.selectedDay = f.currentDay = $("a", d).html(), f.selectedMonth = f.currentMonth = b, f.selectedYear = f.currentYear = c, this._selectDate(a, this._formatDate(f, f.currentDay, f.currentMonth, f.currentYear))
+    }, _clearDate: function (a) {
+        var b = $(a), c = this._getInst(b[0]);
+        this._selectDate(b, "")
+    }, _selectDate: function (a, b) {
+        var c = $(a), d = this._getInst(c[0]);
+        b = b != null ? b : this._formatDate(d), d.input && d.input.val(b), this._updateAlternate(d);
+        var e = this._get(d, "onSelect");
+        e ? e.apply(d.input ? d.input[0] : null, [b, d]) : d.input && d.input.trigger("change"), d.inline ? this._updateDatepicker(d) : (this._hideDatepicker(), this._lastInput = d.input[0], typeof d.input[0] != "object" && d.input.focus(), this._lastInput = null)
+    }, _updateAlternate: function (a) {
+        var b = this._get(a, "altField");
+        if (b) {
+            var c = this._get(a, "altFormat") || this._get(a, "dateFormat"), d = this._getDate(a), e = this.formatDate(c, d, this._getFormatConfig(a));
+            $(b).each(function () {
+                $(this).val(e)
+            })
+        }
+    }, noWeekends: function (a) {
+        var b = a.getDay();
+        return[b > 0 && b < 6, ""]
+    }, iso8601Week: function (a) {
+        var b = new Date(a.getTime());
+        b.setDate(b.getDate() + 4 - (b.getDay() || 7));
+        var c = b.getTime();
+        return b.setMonth(0), b.setDate(1), Math.floor(Math.round((c - b) / 864e5) / 7) + 1
+    }, parseDate: function (a, b, c) {
+        if (a == null || b == null)throw"Invalid arguments";
+        b = typeof b == "object" ? b.toString() : b + "";
+        if (b == "")return null;
+        var d = (c ? c.shortYearCutoff : null) || this._defaults.shortYearCutoff;
+        d = typeof d != "string" ? d : (new Date).getFullYear() % 100 + parseInt(d, 10);
+        var e = (c ? c.dayNamesShort : null) || this._defaults.dayNamesShort, f = (c ? c.dayNames : null) || this._defaults.dayNames, g = (c ? c.monthNamesShort : null) || this._defaults.monthNamesShort, h = (c ? c.monthNames : null) || this._defaults.monthNames, i = -1, j = -1, k = -1, l = -1, m = !1, n = function (b) {
+            var c = s + 1 < a.length && a.charAt(s + 1) == b;
+            return c && s++, c
+        }, o = function (a) {
+            var c = n(a), d = a == "@" ? 14 : a == "!" ? 20 : a == "y" && c ? 4 : a == "o" ? 3 : 2, e = new RegExp("^\\d{1," + d + "}"), f = b.substring(r).match(e);
+            if (!f)throw"Missing number at position " + r;
+            return r += f[0].length, parseInt(f[0], 10)
+        }, p = function (a, c, d) {
+            var e = $.map(n(a) ? d : c,function (a, b) {
+                return[
+                    [b, a]
+                ]
+            }).sort(function (a, b) {
+                return-(a[1].length - b[1].length)
+            }), f = -1;
+            $.each(e, function (a, c) {
+                var d = c[1];
+                if (b.substr(r, d.length).toLowerCase() == d.toLowerCase())return f = c[0], r += d.length, !1
+            });
+            if (f != -1)return f + 1;
+            throw"Unknown name at position " + r
+        }, q = function () {
+            if (b.charAt(r) != a.charAt(s))throw"Unexpected literal at position " + r;
+            r++
+        }, r = 0;
+        for (var s = 0; s < a.length; s++)if (m)a.charAt(s) == "'" && !n("'") ? m = !1 : q(); else switch (a.charAt(s)) {
+            case"d":
+                k = o("d");
+                break;
+            case"D":
+                p("D", e, f);
+                break;
+            case"o":
+                l = o("o");
+                break;
+            case"m":
+                j = o("m");
+                break;
+            case"M":
+                j = p("M", g, h);
+                break;
+            case"y":
+                i = o("y");
+                break;
+            case"@":
+                var t = new Date(o("@"));
+                i = t.getFullYear(), j = t.getMonth() + 1, k = t.getDate();
+                break;
+            case"!":
+                var t = new Date((o("!") - this._ticksTo1970) / 1e4);
+                i = t.getFullYear(), j = t.getMonth() + 1, k = t.getDate();
+                break;
+            case"'":
+                n("'") ? q() : m = !0;
+                break;
+            default:
+                q()
+        }
+        if (r < b.length)throw"Extra/unparsed characters found in date: " + b.substring(r);
+        i == -1 ? i = (new Date).getFullYear() : i < 100 && (i += (new Date).getFullYear() - (new Date).getFullYear() % 100 + (i <= d ? 0 : -100));
+        if (l > -1) {
+            j = 1, k = l;
+            do {
+                var u = this._getDaysInMonth(i, j - 1);
+                if (k <= u)break;
+                j++, k -= u
+            } while (!0)
+        }
+        var t = this._daylightSavingAdjust(new Date(i, j - 1, k));
+        if (t.getFullYear() != i || t.getMonth() + 1 != j || t.getDate() != k)throw"Invalid date";
+        return t
+    }, ATOM: "yy-mm-dd", COOKIE: "D, dd M yy", ISO_8601: "yy-mm-dd", RFC_822: "D, d M y", RFC_850: "DD, dd-M-y", RFC_1036: "D, d M y", RFC_1123: "D, d M yy", RFC_2822: "D, d M yy", RSS: "D, d M y", TICKS: "!", TIMESTAMP: "@", W3C: "yy-mm-dd", _ticksTo1970: (718685 + Math.floor(492.5) - Math.floor(19.7) + Math.floor(4.925)) * 24 * 60 * 60 * 1e7, formatDate: function (a, b, c) {
+        if (!b)return"";
+        var d = (c ? c.dayNamesShort : null) || this._defaults.dayNamesShort, e = (c ? c.dayNames : null) || this._defaults.dayNames, f = (c ? c.monthNamesShort : null) || this._defaults.monthNamesShort, g = (c ? c.monthNames : null) || this._defaults.monthNames, h = function (b) {
+            var c = m + 1 < a.length && a.charAt(m + 1) == b;
+            return c && m++, c
+        }, i = function (a, b, c) {
+            var d = "" + b;
+            if (h(a))while (d.length < c)d = "0" + d;
+            return d
+        }, j = function (a, b, c, d) {
+            return h(a) ? d[b] : c[b]
+        }, k = "", l = !1;
+        if (b)for (var m = 0; m < a.length; m++)if (l)a.charAt(m) == "'" && !h("'") ? l = !1 : k += a.charAt(m); else switch (a.charAt(m)) {
+            case"d":
+                k += i("d", b.getDate(), 2);
+                break;
+            case"D":
+                k += j("D", b.getDay(), d, e);
+                break;
+            case"o":
+                k += i("o", Math.round(((new Date(b.getFullYear(), b.getMonth(), b.getDate())).getTime() - (new Date(b.getFullYear(), 0, 0)).getTime()) / 864e5), 3);
+                break;
+            case"m":
+                k += i("m", b.getMonth() + 1, 2);
+                break;
+            case"M":
+                k += j("M", b.getMonth(), f, g);
+                break;
+            case"y":
+                k += h("y") ? b.getFullYear() : (b.getYear() % 100 < 10 ? "0" : "") + b.getYear() % 100;
+                break;
+            case"@":
+                k += b.getTime();
+                break;
+            case"!":
+                k += b.getTime() * 1e4 + this._ticksTo1970;
+                break;
+            case"'":
+                h("'") ? k += "'" : l = !0;
+                break;
+            default:
+                k += a.charAt(m)
+        }
+        return k
+    }, _possibleChars: function (a) {
+        var b = "", c = !1, d = function (b) {
+            var c = e + 1 < a.length && a.charAt(e + 1) == b;
+            return c && e++, c
+        };
+        for (var e = 0; e < a.length; e++)if (c)a.charAt(e) == "'" && !d("'") ? c = !1 : b += a.charAt(e); else switch (a.charAt(e)) {
+            case"d":
+            case"m":
+            case"y":
+            case"@":
+                b += "0123456789";
+                break;
+            case"D":
+            case"M":
+                return null;
+            case"'":
+                d("'") ? b += "'" : c = !0;
+                break;
+            default:
+                b += a.charAt(e)
+        }
+        return b
+    }, _get: function (a, b) {
+        return a.settings[b] !== undefined ? a.settings[b] : this._defaults[b]
+    }, _setDateFromField: function (a, b) {
+        if (a.input.val() == a.lastVal)return;
+        var c = this._get(a, "dateFormat"), d = a.lastVal = a.input ? a.input.val() : null, e, f;
+        e = f = this._getDefaultDate(a);
+        var g = this._getFormatConfig(a);
+        try {
+            e = this.parseDate(c, d, g) || f
+        } catch (h) {
+            this.log(h), d = b ? "" : d
+        }
+        a.selectedDay = e.getDate(), a.drawMonth = a.selectedMonth = e.getMonth(), a.drawYear = a.selectedYear = e.getFullYear(), a.currentDay = d ? e.getDate() : 0, a.currentMonth = d ? e.getMonth() : 0, a.currentYear = d ? e.getFullYear() : 0, this._adjustInstDate(a)
+    }, _getDefaultDate: function (a) {
+        return this._restrictMinMax(a, this._determineDate(a, this._get(a, "defaultDate"), new Date))
+    }, _determineDate: function (a, b, c) {
+        var d = function (a) {
+            var b = new Date;
+            return b.setDate(b.getDate() + a), b
+        }, e = function (b) {
+            try {
+                return $.datepicker.parseDate($.datepicker._get(a, "dateFormat"), b, $.datepicker._getFormatConfig(a))
+            } catch (c) {
+            }
+            var d = (b.toLowerCase().match(/^c/) ? $.datepicker._getDate(a) : null) || new Date, e = d.getFullYear(), f = d.getMonth(), g = d.getDate(), h = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g, i = h.exec(b);
+            while (i) {
+                switch (i[2] || "d") {
+                    case"d":
+                    case"D":
+                        g += parseInt(i[1], 10);
+                        break;
+                    case"w":
+                    case"W":
+                        g += parseInt(i[1], 10) * 7;
+                        break;
+                    case"m":
+                    case"M":
+                        f += parseInt(i[1], 10), g = Math.min(g, $.datepicker._getDaysInMonth(e, f));
+                        break;
+                    case"y":
+                    case"Y":
+                        e += parseInt(i[1], 10), g = Math.min(g, $.datepicker._getDaysInMonth(e, f))
+                }
+                i = h.exec(b)
+            }
+            return new Date(e, f, g)
+        }, f = b == null || b === "" ? c : typeof b == "string" ? e(b) : typeof b == "number" ? isNaN(b) ? c : d(b) : new Date(b.getTime());
+        return f = f && f.toString() == "Invalid Date" ? c : f, f && (f.setHours(0), f.setMinutes(0), f.setSeconds(0), f.setMilliseconds(0)), this._daylightSavingAdjust(f)
+    }, _daylightSavingAdjust: function (a) {
+        return a ? (a.setHours(a.getHours() > 12 ? a.getHours() + 2 : 0), a) : null
+    }, _setDate: function (a, b, c) {
+        var d = !b, e = a.selectedMonth, f = a.selectedYear, g = this._restrictMinMax(a, this._determineDate(a, b, new Date));
+        a.selectedDay = a.currentDay = g.getDate(), a.drawMonth = a.selectedMonth = a.currentMonth = g.getMonth(), a.drawYear = a.selectedYear = a.currentYear = g.getFullYear(), (e != a.selectedMonth || f != a.selectedYear) && !c && this._notifyChange(a), this._adjustInstDate(a), a.input && a.input.val(d ? "" : this._formatDate(a))
+    }, _getDate: function (a) {
+        var b = !a.currentYear || a.input && a.input.val() == "" ? null : this._daylightSavingAdjust(new Date(a.currentYear, a.currentMonth, a.currentDay));
+        return b
+    }, _generateHTML: function (a) {
+        var b = new Date;
+        b = this._daylightSavingAdjust(new Date(b.getFullYear(), b.getMonth(), b.getDate()));
+        var c = this._get(a, "isRTL"), d = this._get(a, "showButtonPanel"), e = this._get(a, "hideIfNoPrevNext"), f = this._get(a, "navigationAsDateFormat"), g = this._getNumberOfMonths(a), h = this._get(a, "showCurrentAtPos"), i = this._get(a, "stepMonths"), j = g[0] != 1 || g[1] != 1, k = this._daylightSavingAdjust(a.currentDay ? new Date(a.currentYear, a.currentMonth, a.currentDay) : new Date(9999, 9, 9)), l = this._getMinMaxDate(a, "min"), m = this._getMinMaxDate(a, "max"), n = a.drawMonth - h, o = a.drawYear;
+        n < 0 && (n += 12, o--);
+        if (m) {
+            var p = this._daylightSavingAdjust(new Date(m.getFullYear(), m.getMonth() - g[0] * g[1] + 1, m.getDate()));
+            p = l && p < l ? l : p;
+            while (this._daylightSavingAdjust(new Date(o, n, 1)) > p)n--, n < 0 && (n = 11, o--)
+        }
+        a.drawMonth = n, a.drawYear = o;
+        var q = this._get(a, "prevText");
+        q = f ? this.formatDate(q, this._daylightSavingAdjust(new Date(o, n - i, 1)), this._getFormatConfig(a)) : q;
+        var r = this._canAdjustMonth(a, -1, o, n) ? '<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_' + dpuuid + ".datepicker._adjustDate('#" + a.id + "', -" + i + ", 'M');\"" + ' title="' + q + '"><span class="ui-icon ui-icon-circle-triangle-' + (c ? "e" : "w") + '">' + q + "</span></a>" : e ? "" : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="' + q + '"><span class="ui-icon ui-icon-circle-triangle-' + (c ? "e" : "w") + '">' + q + "</span></a>", s = this._get(a, "nextText");
+        s = f ? this.formatDate(s, this._daylightSavingAdjust(new Date(o, n + i, 1)), this._getFormatConfig(a)) : s;
+        var t = this._canAdjustMonth(a, 1, o, n) ? '<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_' + dpuuid + ".datepicker._adjustDate('#" + a.id + "', +" + i + ", 'M');\"" + ' title="' + s + '"><span class="ui-icon ui-icon-circle-triangle-' + (c ? "w" : "e") + '">' + s + "</span></a>" : e ? "" : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="' + s + '"><span class="ui-icon ui-icon-circle-triangle-' + (c ? "w" : "e") + '">' + s + "</span></a>", u = this._get(a, "currentText"), v = this._get(a, "gotoCurrent") && a.currentDay ? k : b;
+        u = f ? this.formatDate(u, v, this._getFormatConfig(a)) : u;
+        var w = a.inline ? "" : '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_' + dpuuid + '.datepicker._hideDatepicker();">' + this._get(a, "closeText") + "</button>", x = d ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (c ? w : "") + (this._isInRange(a, v) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_' + dpuuid + ".datepicker._gotoToday('#" + a.id + "');\"" + ">" + u + "</button>" : "") + (c ? "" : w) + "</div>" : "", y = parseInt(this._get(a, "firstDay"), 10);
+        y = isNaN(y) ? 0 : y;
+        var z = this._get(a, "showWeek"), A = this._get(a, "dayNames"), B = this._get(a, "dayNamesShort"), C = this._get(a, "dayNamesMin"), D = this._get(a, "monthNames"), E = this._get(a, "monthNamesShort"), F = this._get(a, "beforeShowDay"), G = this._get(a, "showOtherMonths"), H = this._get(a, "selectOtherMonths"), I = this._get(a, "calculateWeek") || this.iso8601Week, J = this._getDefaultDate(a), K = "";
+        for (var L = 0; L < g[0]; L++) {
+            var M = "";
+            this.maxRows = 4;
+            for (var N = 0; N < g[1]; N++) {
+                var O = this._daylightSavingAdjust(new Date(o, n, a.selectedDay)), P = " ui-corner-all", Q = "";
+                if (j) {
+                    Q += '<div class="ui-datepicker-group';
+                    if (g[1] > 1)switch (N) {
+                        case 0:
+                            Q += " ui-datepicker-group-first", P = " ui-corner-" + (c ? "right" : "left");
+                            break;
+                        case g[1] - 1:
+                            Q += " ui-datepicker-group-last", P = " ui-corner-" + (c ? "left" : "right");
+                            break;
+                        default:
+                            Q += " ui-datepicker-group-middle", P = ""
+                    }
+                    Q += '">'
+                }
+                Q += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + P + '">' + (/all|left/.test(P) && L == 0 ? c ? t : r : "") + (/all|right/.test(P) && L == 0 ? c ? r : t : "") + this._generateMonthYearHeader(a, n, o, l, m, L > 0 || N > 0, D, E) + '</div><table class="ui-datepicker-calendar"><thead>' + "<tr>";
+                var R = z ? '<th class="ui-datepicker-week-col">' + this._get(a, "weekHeader") + "</th>" : "";
+                for (var S = 0; S < 7; S++) {
+                    var T = (S + y) % 7;
+                    R += "<th" + ((S + y + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : "") + ">" + '<span title="' + A[T] + '">' + C[T] + "</span></th>"
+                }
+                Q += R + "</tr></thead><tbody>";
+                var U = this._getDaysInMonth(o, n);
+                o == a.selectedYear && n == a.selectedMonth && (a.selectedDay = Math.min(a.selectedDay, U));
+                var V = (this._getFirstDayOfMonth(o, n) - y + 7) % 7, W = Math.ceil((V + U) / 7), X = j ? this.maxRows > W ? this.maxRows : W : W;
+                this.maxRows = X;
+                var Y = this._daylightSavingAdjust(new Date(o, n, 1 - V));
+                for (var Z = 0; Z < X; Z++) {
+                    Q += "<tr>";
+                    var _ = z ? '<td class="ui-datepicker-week-col">' + this._get(a, "calculateWeek")(Y) + "</td>" : "";
+                    for (var S = 0; S < 7; S++) {
+                        var ba = F ? F.apply(a.input ? a.input[0] : null, [Y]) : [!0, ""], bb = Y.getMonth() != n, bc = bb && !H || !ba[0] || l && Y < l || m && Y > m;
+                        _ += '<td class="' + ((S + y + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + (bb ? " ui-datepicker-other-month" : "") + (Y.getTime() == O.getTime() && n == a.selectedMonth && a._keyEvent || J.getTime() == Y.getTime() && J.getTime() == O.getTime() ? " " + this._dayOverClass : "") + (bc ? " " + this._unselectableClass + " ui-state-disabled" : "") + (bb && !G ? "" : " " + ba[1] + (Y.getTime() == k.getTime() ? " " + this._currentClass : "") + (Y.getTime() == b.getTime() ? " ui-datepicker-today" : "")) + '"' + ((!bb || G) && ba[2] ? ' title="' + ba[2] + '"' : "") + (bc ? "" : ' onclick="DP_jQuery_' + dpuuid + ".datepicker._selectDay('#" + a.id + "'," + Y.getMonth() + "," + Y.getFullYear() + ', this);return false;"') + ">" + (bb && !G ? "&#xa0;" : bc ? '<span class="ui-state-default">' + Y.getDate() + "</span>" : '<a class="ui-state-default' + (Y.getTime() == b.getTime() ? " ui-state-highlight" : "") + (Y.getTime() == k.getTime() ? " ui-state-active" : "") + (bb ? " ui-priority-secondary" : "") + '" href="#">' + Y.getDate() + "</a>") + "</td>", Y.setDate(Y.getDate() + 1), Y = this._daylightSavingAdjust(Y)
+                    }
+                    Q += _ + "</tr>"
+                }
+                n++, n > 11 && (n = 0, o++), Q += "</tbody></table>" + (j ? "</div>" + (g[0] > 0 && N == g[1] - 1 ? '<div class="ui-datepicker-row-break"></div>' : "") : ""), M += Q
+            }
+            K += M
+        }
+        return K += x + ($.browser.msie && parseInt($.browser.version, 10) < 7 && !a.inline ? '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : ""), a._keyEvent = !1, K
+    }, _generateMonthYearHeader: function (a, b, c, d, e, f, g, h) {
+        var i = this._get(a, "changeMonth"), j = this._get(a, "changeYear"), k = this._get(a, "showMonthAfterYear"), l = '<div class="ui-datepicker-title">', m = "";
+        if (f || !i)m += '<span class="ui-datepicker-month">' + g[b] + "</span>"; else {
+            var n = d && d.getFullYear() == c, o = e && e.getFullYear() == c;
+            m += '<select class="ui-datepicker-month" onchange="DP_jQuery_' + dpuuid + ".datepicker._selectMonthYear('#" + a.id + "', this, 'M');\" " + ">";
+            for (var p = 0; p < 12; p++)(!n || p >= d.getMonth()) && (!o || p <= e.getMonth()) && (m += '<option value="' + p + '"' + (p == b ? ' selected="selected"' : "") + ">" + h[p] + "</option>");
+            m += "</select>"
+        }
+        k || (l += m + (f || !i || !j ? "&#xa0;" : ""));
+        if (!a.yearshtml) {
+            a.yearshtml = "";
+            if (f || !j)l += '<span class="ui-datepicker-year">' + c + "</span>"; else {
+                var q = this._get(a, "yearRange").split(":"), r = (new Date).getFullYear(), s = function (a) {
+                    var b = a.match(/c[+-].*/) ? c + parseInt(a.substring(1), 10) : a.match(/[+-].*/) ? r + parseInt(a, 10) : parseInt(a, 10);
+                    return isNaN(b) ? r : b
+                }, t = s(q[0]), u = Math.max(t, s(q[1] || ""));
+                t = d ? Math.max(t, d.getFullYear()) : t, u = e ? Math.min(u, e.getFullYear()) : u, a.yearshtml += '<select class="ui-datepicker-year" onchange="DP_jQuery_' + dpuuid + ".datepicker._selectMonthYear('#" + a.id + "', this, 'Y');\" " + ">";
+                for (; t <= u; t++)a.yearshtml += '<option value="' + t + '"' + (t == c ? ' selected="selected"' : "") + ">" + t + "</option>";
+                a.yearshtml += "</select>", l += a.yearshtml, a.yearshtml = null
+            }
+        }
+        return l += this._get(a, "yearSuffix"), k && (l += (f || !i || !j ? "&#xa0;" : "") + m), l += "</div>", l
+    }, _adjustInstDate: function (a, b, c) {
+        var d = a.drawYear + (c == "Y" ? b : 0), e = a.drawMonth + (c == "M" ? b : 0), f = Math.min(a.selectedDay, this._getDaysInMonth(d, e)) + (c == "D" ? b : 0), g = this._restrictMinMax(a, this._daylightSavingAdjust(new Date(d, e, f)));
+        a.selectedDay = g.getDate(), a.drawMonth = a.selectedMonth = g.getMonth(), a.drawYear = a.selectedYear = g.getFullYear(), (c == "M" || c == "Y") && this._notifyChange(a)
+    }, _restrictMinMax: function (a, b) {
+        var c = this._getMinMaxDate(a, "min"), d = this._getMinMaxDate(a, "max"), e = c && b < c ? c : b;
+        return e = d && e > d ? d : e, e
+    }, _notifyChange: function (a) {
+        var b = this._get(a, "onChangeMonthYear");
+        b && b.apply(a.input ? a.input[0] : null, [a.selectedYear, a.selectedMonth + 1, a])
+    }, _getNumberOfMonths: function (a) {
+        var b = this._get(a, "numberOfMonths");
+        return b == null ? [1, 1] : typeof b == "number" ? [1, b] : b
+    }, _getMinMaxDate: function (a, b) {
+        return this._determineDate(a, this._get(a, b + "Date"), null)
+    }, _getDaysInMonth: function (a, b) {
+        return 32 - this._daylightSavingAdjust(new Date(a, b, 32)).getDate()
+    }, _getFirstDayOfMonth: function (a, b) {
+        return(new Date(a, b, 1)).getDay()
+    }, _canAdjustMonth: function (a, b, c, d) {
+        var e = this._getNumberOfMonths(a), f = this._daylightSavingAdjust(new Date(c, d + (b < 0 ? b : e[0] * e[1]), 1));
+        return b < 0 && f.setDate(this._getDaysInMonth(f.getFullYear(), f.getMonth())), this._isInRange(a, f)
+    }, _isInRange: function (a, b) {
+        var c = this._getMinMaxDate(a, "min"), d = this._getMinMaxDate(a, "max");
+        return(!c || b.getTime() >= c.getTime()) && (!d || b.getTime() <= d.getTime())
+    }, _getFormatConfig: function (a) {
+        var b = this._get(a, "shortYearCutoff");
+        return b = typeof b != "string" ? b : (new Date).getFullYear() % 100 + parseInt(b, 10), {shortYearCutoff: b, dayNamesShort: this._get(a, "dayNamesShort"), dayNames: this._get(a, "dayNames"), monthNamesShort: this._get(a, "monthNamesShort"), monthNames: this._get(a, "monthNames")}
+    }, _formatDate: function (a, b, c, d) {
+        b || (a.currentDay = a.selectedDay, a.currentMonth = a.selectedMonth, a.currentYear = a.selectedYear);
+        var e = b ? typeof b == "object" ? b : this._daylightSavingAdjust(new Date(d, c, b)) : this._daylightSavingAdjust(new Date(a.currentYear, a.currentMonth, a.currentDay));
+        return this.formatDate(this._get(a, "dateFormat"), e, this._getFormatConfig(a))
+    }}), $.fn.datepicker = function (a) {
+        if (!this.length)return this;
+        $.datepicker.initialized || ($(document).mousedown($.datepicker._checkExternalClick).find("body").append($.datepicker.dpDiv), $.datepicker.initialized = !0);
+        var b = Array.prototype.slice.call(arguments, 1);
+        return typeof a != "string" || a != "isDisabled" && a != "getDate" && a != "widget" ? a == "option" && arguments.length == 2 && typeof arguments[1] == "string" ? $.datepicker["_" + a + "Datepicker"].apply($.datepicker, [this[0]].concat(b)) : this.each(function () {
+            typeof a == "string" ? $.datepicker["_" + a + "Datepicker"].apply($.datepicker, [this].concat(b)) : $.datepicker._attachDatepicker(this, a)
+        }) : $.datepicker["_" + a + "Datepicker"].apply($.datepicker, [this[0]].concat(b))
+    }, $.datepicker = new Datepicker, $.datepicker.initialized = !1, $.datepicker.uuid = (new Date).getTime(), $.datepicker.version = "1.8.21", window["DP_jQuery_" + dpuuid] = $
+})(jQuery);
+;
\ No newline at end of file
diff --git a/media/js/lib/jquery.event.drag.custom.js b/media/js/lib/jquery.event.drag.custom.js
index c012ae0..7b940c4 100644
--- a/media/js/lib/jquery.event.drag.custom.js
+++ b/media/js/lib/jquery.event.drag.custom.js
@@ -3,140 +3,149 @@
  * jquery.event.drag.js ~ v1.5 ~ Copyright (c) 2008, Three Dub Media (http://threedubmedia.com)
  * Licensed under the MIT License ~ http://threedubmedia.googlecode.com/files/MIT-LICENSE.txt
  */
-;(function($){ // secure $ jQuery alias
-/*******************************************************************************************/
+;
+(function ($) { // secure $ jQuery alias
+    /*******************************************************************************************/
 // Created: 2008-06-04 | Updated: 2009-03-24
-/*******************************************************************************************/
+    /*******************************************************************************************/
 // Events: drag, dragstart, dragend
-/*******************************************************************************************/
+    /*******************************************************************************************/
 
 // jquery method
-$.fn.drag = function( fn1, fn2, fn3 ){
-	if ( fn2 ) this.bind('dragstart', fn1 ); // 2+ args
-	if ( fn3 ) this.bind('dragend', fn3 ); // 3 args
-	return !fn1 ? this.trigger('drag') // 0 args
-		: this.bind('drag', fn2 ? fn2 : fn1 ); // 1+ args
-	};
+    $.fn.drag = function (fn1, fn2, fn3) {
+        if (fn2) this.bind('dragstart', fn1); // 2+ args
+        if (fn3) this.bind('dragend', fn3); // 3 args
+        return !fn1 ? this.trigger('drag') // 0 args
+            : this.bind('drag', fn2 ? fn2 : fn1); // 1+ args
+    };
 
 // local refs
-var $event = $.event, $special = $event.special,
+    var $event = $.event, $special = $event.special,
 
 // special event configuration
-drag = $special.drag = {
-	not: ':input', // don't begin to drag on event.targets that match this selector
-	distance: 0, // distance dragged before dragstart
-	which: 1, // mouse button pressed to start drag sequence
-	dragging: false, // hold the active target element
-	setup: function( data ){
-		data = $.extend({
-			distance: drag.distance,
-			which: drag.which,
-			not: drag.not
-			}, data || {});
-		data.distance = squared( data.distance ); //  xІ + yІ = distanceІ
-		$event.add( this, "mousedown", handler, data );
-		if ( this.attachEvent ) this.attachEvent("ondragstart", dontStart ); // prevent image dragging in IE...
-		},
-	teardown: function(){
-		$event.remove( this, "mousedown", handler );
-		if ( this === drag.dragging ) drag.dragging = drag.proxy = false; // deactivate element
-		selectable( this, true ); // enable text selection
-		if ( this.detachEvent ) this.detachEvent("ondragstart", dontStart ); // prevent image dragging in IE...
-		}
-	};
+        drag = $special.drag = {
+            not: ':input', // don't begin to drag on event.targets that match this selector
+            distance: 0, // distance dragged before dragstart
+            which: 1, // mouse button pressed to start drag sequence
+            dragging: false, // hold the active target element
+            setup: function (data) {
+                data = $.extend({
+                    distance: drag.distance,
+                    which: drag.which,
+                    not: drag.not
+                }, data || {});
+                data.distance = squared(data.distance); //  xІ + yІ = distanceІ
+                $event.add(this, "mousedown", handler, data);
+                if (this.attachEvent) this.attachEvent("ondragstart", dontStart); // prevent image dragging in IE...
+            },
+            teardown: function () {
+                $event.remove(this, "mousedown", handler);
+                if (this === drag.dragging) drag.dragging = drag.proxy = false; // deactivate element
+                selectable(this, true); // enable text selection
+                if (this.detachEvent) this.detachEvent("ondragstart", dontStart); // prevent image dragging in IE...
+            }
+        };
 
 // prevent normal event binding...
-$special.dragstart = $special.dragend = { setup:function(){}, teardown:function(){} };
+    $special.dragstart = $special.dragend = { setup: function () {
+    }, teardown: function () {
+    } };
 
 // handle drag-releatd DOM events
-function handler ( event ){
-	var elem = this, returned, data = event.data || {};
-	// mousemove or mouseup
-	if ( data.elem ){
-		// update event properties...
-		elem = event.dragTarget = data.elem; // drag source element
-		event.dragProxy = drag.proxy || elem; // proxy element or source
-		event.cursorOffsetX = data.pageX - data.left; // mousedown offset
-		event.cursorOffsetY = data.pageY - data.top; // mousedown offset
-		event.offsetX = event.pageX - event.cursorOffsetX; // element offset
-		event.offsetY = event.pageY - event.cursorOffsetY; // element offset
-		}
-	// mousedown, check some initial props to avoid the switch statement
-	else if ( drag.dragging || ( data.which>0 && event.which!=data.which ) ||
-		$( event.target ).is( data.not ) ) return;
-	// handle various events
-	switch ( event.type ){
-		// mousedown, left click, event.target is not restricted, init dragging
-		case 'mousedown':
-			returned = hijack(event, "beforedragstart", elem);
-			if (returned === false)
-				return true;
-			$.extend( data, $( elem ).offset(), {
-				elem: elem, target: event.target,
-				pageX: event.pageX, pageY: event.pageY
-				}); // store some initial attributes
-			$event.add( document, "mousemove mouseup", handler, data );
-			selectable( elem, false ); // disable text selection
-			drag.dragging = null; // pending state
-			return false; // prevents text selection in safari
-		// mousemove, check distance, start dragging
-		case !drag.dragging && 'mousemove':
-			if ( squared( event.pageX-data.pageX )
-				+ squared( event.pageY-data.pageY ) //  xІ + yІ = distanceІ
-				< data.distance ) break; // distance tolerance not reached
-			event.target = data.target; // force target from "mousedown" event (fix distance issue)
-			returned = hijack( event, "dragstart", elem ); // trigger "dragstart", return proxy element
-			if ( returned !== false ){ // "dragstart" not rejected
-				drag.dragging = elem; // activate element
-				drag.proxy = event.dragProxy = $( returned || elem )[0]; // set proxy
-				}
-		// mousemove, dragging
-		case 'mousemove':
-			if ( drag.dragging ){
-				returned = hijack( event, "drag", elem ); // trigger "drag"
-				if ( $special.drop ){ // manage drop events
-					$special.drop.allowed = ( returned !== false ); // prevent drop
-					$special.drop.handler( event ); // "dropstart", "dropend"
-					}
-				if ( returned !== false ) break; // "drag" not rejected, stop
-				event.type = "mouseup"; // helps "drop" handler behave
-				}
-		// mouseup, stop dragging
-		case 'mouseup':
-			if (drag.dragging === false) break;
-			$event.remove( document, "mousemove mouseup", handler ); // remove page events
-			if ( drag.dragging ){
-				if ( $special.drop ) $special.drop.handler( event ); // "drop"
-				hijack( event, "dragend", elem ); // trigger "dragend"
-				}
-			selectable( elem, true ); // enable text selection
-			drag.dragging = drag.proxy = data.elem = false; // deactivate element
-			break;
-		}
-	return true;
-	};
+    function handler(event) {
+        var elem = this, returned, data = event.data || {};
+        // mousemove or mouseup
+        if (data.elem) {
+            // update event properties...
+            elem = event.dragTarget = data.elem; // drag source element
+            event.dragProxy = drag.proxy || elem; // proxy element or source
+            event.cursorOffsetX = data.pageX - data.left; // mousedown offset
+            event.cursorOffsetY = data.pageY - data.top; // mousedown offset
+            event.offsetX = event.pageX - event.cursorOffsetX; // element offset
+            event.offsetY = event.pageY - event.cursorOffsetY; // element offset
+        }
+        // mousedown, check some initial props to avoid the switch statement
+        else if (drag.dragging || ( data.which > 0 && event.which != data.which ) ||
+            $(event.target).is(data.not)) return;
+        // handle various events
+        switch (event.type) {
+            // mousedown, left click, event.target is not restricted, init dragging
+            case 'mousedown':
+                returned = hijack(event, "beforedragstart", elem);
+                if (returned === false)
+                    return true;
+                $.extend(data, $(elem).offset(), {
+                    elem: elem, target: event.target,
+                    pageX: event.pageX, pageY: event.pageY
+                }); // store some initial attributes
+                $event.add(document, "mousemove mouseup", handler, data);
+                selectable(elem, false); // disable text selection
+                drag.dragging = null; // pending state
+                return false; // prevents text selection in safari
+            // mousemove, check distance, start dragging
+            case !drag.dragging && 'mousemove':
+                if (squared(event.pageX - data.pageX)
+                    + squared(event.pageY - data.pageY) //  xІ + yІ = distanceІ
+                    < data.distance) break; // distance tolerance not reached
+                event.target = data.target; // force target from "mousedown" event (fix distance issue)
+                returned = hijack(event, "dragstart", elem); // trigger "dragstart", return proxy element
+                if (returned !== false) { // "dragstart" not rejected
+                    drag.dragging = elem; // activate element
+                    drag.proxy = event.dragProxy = $(returned || elem)[0]; // set proxy
+                }
+            // mousemove, dragging
+            case 'mousemove':
+                if (drag.dragging) {
+                    returned = hijack(event, "drag", elem); // trigger "drag"
+                    if ($special.drop) { // manage drop events
+                        $special.drop.allowed = ( returned !== false ); // prevent drop
+                        $special.drop.handler(event); // "dropstart", "dropend"
+                    }
+                    if (returned !== false) break; // "drag" not rejected, stop
+                    event.type = "mouseup"; // helps "drop" handler behave
+                }
+            // mouseup, stop dragging
+            case 'mouseup':
+                if (drag.dragging === false) break;
+                $event.remove(document, "mousemove mouseup", handler); // remove page events
+                if (drag.dragging) {
+                    if ($special.drop) $special.drop.handler(event); // "drop"
+                    hijack(event, "dragend", elem); // trigger "dragend"
+                }
+                selectable(elem, true); // enable text selection
+                drag.dragging = drag.proxy = data.elem = false; // deactivate element
+                break;
+        }
+        return true;
+    };
 
 // set event type to custom value, and handle it
-function hijack ( event, type, elem ){
-	event.type = type; // force the event type
-	var result = $.event.handle.call( elem, event );
-	return result===false ? false : result || event.result;
-	};
+    function hijack(event, type, elem) {
+        event.type = type; // force the event type
+        var result = $.event.handle.call(elem, event);
+        return result === false ? false : result || event.result;
+    };
 
 // return the value squared
-function squared ( value ){ return Math.pow( value, 2 ); };
+    function squared(value) {
+        return Math.pow(value, 2);
+    };
 
 // suppress default dragstart IE events...
-function dontStart(){ return ( drag.dragging === false ); };
+    function dontStart() {
+        return ( drag.dragging === false );
+    };
 
 // toggles text selection attributes
-function selectable ( elem, bool ){
-	if ( !elem ) return; // maybe element was removed ?
-	elem.unselectable = bool ? "off" : "on"; // IE
-	elem.onselectstart = function(){ return bool; }; // IE
-	//if ( document.selection && document.selection.empty ) document.selection.empty(); // IE
-	if ( elem.style ) elem.style.MozUserSelect = bool ? "" : "none"; // FF
-	};
+    function selectable(elem, bool) {
+        if (!elem) return; // maybe element was removed ?
+        elem.unselectable = bool ? "off" : "on"; // IE
+        elem.onselectstart = function () {
+            return bool;
+        }; // IE
+        //if ( document.selection && document.selection.empty ) document.selection.empty(); // IE
+        if (elem.style) elem.style.MozUserSelect = bool ? "" : "none"; // FF
+    };
 
-/*******************************************************************************************/
-})( jQuery ); // confine scope
\ No newline at end of file
+    /*******************************************************************************************/
+})(jQuery); // confine scope
\ No newline at end of file
diff --git a/media/js/lib/jquery.jqGrid.min.js b/media/js/lib/jquery.jqGrid.min.js
index 3659e1b..bc0b66d 100644
--- a/media/js/lib/jquery.jqGrid.min.js
+++ b/media/js/lib/jquery.jqGrid.min.js
@@ -1,333 +1,4561 @@
 /* 
-* jqGrid  4.4.0 - jQuery Grid 
-* Copyright (c) 2008, Tony Tomov, tony@trirand.com 
-* Dual licensed under the MIT and GPL licenses 
-* http://www.opensource.org/licenses/mit-license.php 
-* http://www.gnu.org/licenses/gpl-2.0.html 
-* Date:2012-06-14 
-* Modules: grid.base.js; grid.common.js; grid.formedit.js; grid.filter.js; grid.jqueryui.js; 
-*/
-(function(b){b.jgrid=b.jgrid||{};b.extend(b.jgrid,{version:"4.4.0",htmlDecode:function(b){return b&&("&nbsp;"==b||"&#160;"==b||1===b.length&&160===b.charCodeAt(0))?"":!b?b:(""+b).replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&quot;/g,'"').replace(/&amp;/g,"&")},htmlEncode:function(b){return!b?b:(""+b).replace(/&/g,"&amp;").replace(/\"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")},format:function(f){var e=b.makeArray(arguments).slice(1);void 0===f&&(f="");return f.replace(/\{(\d+)\}/g,
-function(b,d){return e[d]})},getCellIndex:function(f){f=b(f);if(f.is("tr"))return-1;f=(!f.is("td")&&!f.is("th")?f.closest("td,th"):f)[0];return b.browser.msie?b.inArray(f,f.parentNode.cells):f.cellIndex},stripHtml:function(b){var b=b+"",e=/<("[^"]*"|'[^']*'|[^'">])*>/gi;return b?(b=b.replace(e,""))&&"&nbsp;"!==b&&"&#160;"!==b?b.replace(/\"/g,"'"):"":b},stripPref:function(f,e){var c=b.type(f);if("string"==c||"number"==c)f=""+f,e=""!==f?(""+e).replace(""+f,""):e;return e},stringToDoc:function(b){var e;
-if("string"!==typeof b)return b;try{e=(new DOMParser).parseFromString(b,"text/xml")}catch(c){e=new ActiveXObject("Microsoft.XMLDOM"),e.async=!1,e.loadXML(b)}return e&&e.documentElement&&"parsererror"!=e.documentElement.tagName?e:null},parse:function(f){"while(1);"==f.substr(0,9)&&(f=f.substr(9));"/*"==f.substr(0,2)&&(f=f.substr(2,f.length-4));f||(f="{}");return!0===b.jgrid.useJSON&&"object"===typeof JSON&&"function"===typeof JSON.parse?JSON.parse(f):eval("("+f+")")},parseDate:function(f,e){var c=
-{m:1,d:1,y:1970,h:0,i:0,s:0,u:0},d,a,h;d=/[\\\/:_;.,\t\T\s-]/;if(e&&null!==e&&void 0!==e){e=b.trim(e);e=e.split(d);void 0!==b.jgrid.formatter.date.masks[f]&&(f=b.jgrid.formatter.date.masks[f]);var f=f.split(d),g=b.jgrid.formatter.date.monthNames,i=b.jgrid.formatter.date.AmPm,j=function(a,b){0===a?12===b&&(b=0):12!==b&&(b+=12);return b};d=0;for(a=f.length;d<a;d++)"M"==f[d]&&(h=b.inArray(e[d],g),-1!==h&&12>h&&(e[d]=h+1,c.m=e[d])),"F"==f[d]&&(h=b.inArray(e[d],g),-1!==h&&11<h&&(e[d]=h+1-12,c.m=e[d])),
-"a"==f[d]&&(h=b.inArray(e[d],i),-1!==h&&2>h&&e[d]==i[h]&&(e[d]=h,c.h=j(e[d],c.h))),"A"==f[d]&&(h=b.inArray(e[d],i),-1!==h&&1<h&&e[d]==i[h]&&(e[d]=h-2,c.h=j(e[d],c.h))),void 0!==e[d]&&(c[f[d].toLowerCase()]=parseInt(e[d],10));c.m=parseInt(c.m,10)-1;d=c.y;70<=d&&99>=d?c.y=1900+c.y:0<=d&&69>=d&&(c.y=2E3+c.y);void 0!==c.j&&(c.d=c.j);void 0!==c.n&&(c.m=parseInt(c.n,10)-1)}return new Date(c.y,c.m,c.d,c.h,c.i,c.s,c.u)},jqID:function(b){return(""+b).replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g,"\\$&")},
-guid:1,uidPref:"jqg",randId:function(f){return(f?f:b.jgrid.uidPref)+b.jgrid.guid++},getAccessor:function(b,e){var c,d,a=[],h;if("function"===typeof e)return e(b);c=b[e];if(void 0===c)try{if("string"===typeof e&&(a=e.split(".")),h=a.length)for(c=b;c&&h--;)d=a.shift(),c=c[d]}catch(g){}return c},getXmlData:function(f,e,c){var d="string"===typeof e?e.match(/^(.*)\[(\w+)\]$/):null;if("function"===typeof e)return e(f);if(d&&d[2])return d[1]?b(d[1],f).attr(d[2]):b(f).attr(d[2]);f=b(e,f);return c?f:0<f.length?
-b(f).text():void 0},cellWidth:function(){var f=b("<div class='ui-jqgrid' style='left:10000px'><table class='ui-jqgrid-btable' style='width:5px;'><tr class='jqgrow'><td style='width:5px;'></td></tr></table></div>"),e=f.appendTo("body").find("td").width();f.remove();return 5!==e},ajaxOptions:{},from:function(f){return new function(e,c){"string"==typeof e&&(e=b.data(e));var d=this,a=e,h=!0,f=!1,i=c,j=/[\$,%]/g,l=null,k=null,m=0,o=!1,p="",v=[],u=!0;if("object"==typeof e&&e.push)0<e.length&&(u="object"!=
-typeof e[0]?!1:!0);else throw"data provides is not an array";this._hasData=function(){return null===a?!1:0===a.length?!1:!0};this._getStr=function(a){var b=[];f&&b.push("jQuery.trim(");b.push("String("+a+")");f&&b.push(")");h||b.push(".toLowerCase()");return b.join("")};this._strComp=function(a){return"string"==typeof a?".toString()":""};this._group=function(a,b){return{field:a.toString(),unique:b,items:[]}};this._toStr=function(a){f&&(a=b.trim(a));a=a.toString().replace(/\\/g,"\\\\").replace(/\"/g,
-'\\"');return h?a:a.toLowerCase()};this._funcLoop=function(d){var c=[];b.each(a,function(a,b){c.push(d(b))});return c};this._append=function(a){var b;i=null===i?"":i+(""===p?" && ":p);for(b=0;b<m;b++)i+="(";o&&(i+="!");i+="("+a+")";o=!1;p="";m=0};this._setCommand=function(a,b){l=a;k=b};this._resetNegate=function(){o=!1};this._repeatCommand=function(a,b){return null===l?d:null!==a&&null!==b?l(a,b):null===k||!u?l(a):l(k,a)};this._equals=function(a,b){return 0===d._compare(a,b,1)};this._compare=function(a,
-b,d){var c=Object.prototype.toString;void 0===d&&(d=1);void 0===a&&(a=null);void 0===b&&(b=null);if(null===a&&null===b)return 0;if(null===a&&null!==b)return 1;if(null!==a&&null===b)return-1;if("[object Date]"===c.call(a)&&"[object Date]"===c.call(b))return a<b?-d:a>b?d:0;!h&&"number"!==typeof a&&"number"!==typeof b&&(a=(""+a).toLowerCase(),b=(""+b).toLowerCase());return a<b?-d:a>b?d:0};this._performSort=function(){0!==v.length&&(a=d._doSort(a,0))};this._doSort=function(a,b){var c=v[b].by,f=v[b].dir,
-h=v[b].type,e=v[b].datefmt;if(b==v.length-1)return d._getOrder(a,c,f,h,e);b++;c=d._getGroup(a,c,f,h,e);f=[];for(h=0;h<c.length;h++)for(var e=d._doSort(c[h].items,b),g=0;g<e.length;g++)f.push(e[g]);return f};this._getOrder=function(a,c,h,f,e){var g=[],i=[],l="a"==h?1:-1,k,m;void 0===f&&(f="text");m="float"==f||"number"==f||"currency"==f||"numeric"==f?function(a){a=parseFloat((""+a).replace(j,""));return isNaN(a)?0:a}:"int"==f||"integer"==f?function(a){return a?parseFloat((""+a).replace(j,"")):0}:"date"==
-f||"datetime"==f?function(a){return b.jgrid.parseDate(e,a).getTime()}:b.isFunction(f)?f:function(a){a||(a="");return b.trim((""+a).toUpperCase())};b.each(a,function(a,d){k=""!==c?b.jgrid.getAccessor(d,c):d;void 0===k&&(k="");k=m(k,d);i.push({vSort:k,index:a})});i.sort(function(a,b){a=a.vSort;b=b.vSort;return d._compare(a,b,l)});for(var f=0,o=a.length;f<o;)h=i[f].index,g.push(a[h]),f++;return g};this._getGroup=function(a,c,f,h,e){var g=[],i=null,j=null,k;b.each(d._getOrder(a,c,f,h,e),function(a,f){k=
-b.jgrid.getAccessor(f,c);void 0===k&&(k="");d._equals(j,k)||(j=k,null!==i&&g.push(i),i=d._group(c,k));i.items.push(f)});null!==i&&g.push(i);return g};this.ignoreCase=function(){h=!1;return d};this.useCase=function(){h=!0;return d};this.trim=function(){f=!0;return d};this.noTrim=function(){f=!1;return d};this.execute=function(){var c=i,f=[];if(null===c)return d;b.each(a,function(){eval(c)&&f.push(this)});a=f;return d};this.data=function(){return a};this.select=function(c){d._performSort();if(!d._hasData())return[];
-d.execute();if(b.isFunction(c)){var f=[];b.each(a,function(a,b){f.push(c(b))});return f}return a};this.hasMatch=function(){if(!d._hasData())return!1;d.execute();return 0<a.length};this.andNot=function(a,b,c){o=!o;return d.and(a,b,c)};this.orNot=function(a,b,c){o=!o;return d.or(a,b,c)};this.not=function(a,b,c){return d.andNot(a,b,c)};this.and=function(a,b,c){p=" && ";return void 0===a?d:d._repeatCommand(a,b,c)};this.or=function(a,b,c){p=" || ";return void 0===a?d:d._repeatCommand(a,b,c)};this.orBegin=
-function(){m++;return d};this.orEnd=function(){null!==i&&(i+=")");return d};this.isNot=function(a){o=!o;return d.is(a)};this.is=function(a){d._append("this."+a);d._resetNegate();return d};this._compareValues=function(a,c,f,h,e){var g;g=u?"jQuery.jgrid.getAccessor(this,'"+c+"')":"this";void 0===f&&(f=null);var i=f,k=void 0===e.stype?"text":e.stype;if(null!==f)switch(k){case "int":case "integer":i=isNaN(Number(i))||""===i?"0":i;g="parseInt("+g+",10)";i="parseInt("+i+",10)";break;case "float":case "number":case "numeric":i=
-(""+i).replace(j,"");i=isNaN(Number(i))||""===i?"0":i;g="parseFloat("+g+")";i="parseFloat("+i+")";break;case "date":case "datetime":i=""+b.jgrid.parseDate(e.newfmt||"Y-m-d",i).getTime();g='jQuery.jgrid.parseDate("'+e.srcfmt+'",'+g+").getTime()";break;default:g=d._getStr(g),i=d._getStr('"'+d._toStr(i)+'"')}d._append(g+" "+h+" "+i);d._setCommand(a,c);d._resetNegate();return d};this.equals=function(a,b,c){return d._compareValues(d.equals,a,b,"==",c)};this.notEquals=function(a,b,c){return d._compareValues(d.equals,
-a,b,"!==",c)};this.isNull=function(a,b,c){return d._compareValues(d.equals,a,null,"===",c)};this.greater=function(a,b,c){return d._compareValues(d.greater,a,b,">",c)};this.less=function(a,b,c){return d._compareValues(d.less,a,b,"<",c)};this.greaterOrEquals=function(a,b,c){return d._compareValues(d.greaterOrEquals,a,b,">=",c)};this.lessOrEquals=function(a,b,c){return d._compareValues(d.lessOrEquals,a,b,"<=",c)};this.startsWith=function(a,c){var h=void 0===c||null===c?a:c,h=f?b.trim(h.toString()).length:
-h.toString().length;u?d._append(d._getStr("jQuery.jgrid.getAccessor(this,'"+a+"')")+".substr(0,"+h+") == "+d._getStr('"'+d._toStr(c)+'"')):(h=f?b.trim(c.toString()).length:c.toString().length,d._append(d._getStr("this")+".substr(0,"+h+") == "+d._getStr('"'+d._toStr(a)+'"')));d._setCommand(d.startsWith,a);d._resetNegate();return d};this.endsWith=function(a,c){var h=void 0===c||null===c?a:c,h=f?b.trim(h.toString()).length:h.toString().length;u?d._append(d._getStr("jQuery.jgrid.getAccessor(this,'"+a+
-"')")+".substr("+d._getStr("jQuery.jgrid.getAccessor(this,'"+a+"')")+".length-"+h+","+h+') == "'+d._toStr(c)+'"'):d._append(d._getStr("this")+".substr("+d._getStr("this")+'.length-"'+d._toStr(a)+'".length,"'+d._toStr(a)+'".length) == "'+d._toStr(a)+'"');d._setCommand(d.endsWith,a);d._resetNegate();return d};this.contains=function(a,b){u?d._append(d._getStr("jQuery.jgrid.getAccessor(this,'"+a+"')")+'.indexOf("'+d._toStr(b)+'",0) > -1'):d._append(d._getStr("this")+'.indexOf("'+d._toStr(a)+'",0) > -1');
-d._setCommand(d.contains,a);d._resetNegate();return d};this.groupBy=function(b,c,f,h){return!d._hasData()?null:d._getGroup(a,b,c,f,h)};this.orderBy=function(a,c,f,h){c=void 0===c||null===c?"a":b.trim(c.toString().toLowerCase());if(null===f||void 0===f)f="text";if(null===h||void 0===h)h="Y-m-d";if("desc"==c||"descending"==c)c="d";if("asc"==c||"ascending"==c)c="a";v.push({by:a,dir:c,type:f,datefmt:h});return d};return d}(f,null)},extend:function(f){b.extend(b.fn.jqGrid,f);this.no_legacy_api||b.fn.extend(f)}});
-b.fn.jqGrid=function(f){if("string"==typeof f){var e=b.jgrid.getAccessor(b.fn.jqGrid,f);if(!e)throw"jqGrid - No such method: "+f;var c=b.makeArray(arguments).slice(1);return e.apply(this,c)}return this.each(function(){if(!this.grid){var d=b.extend(!0,{url:"",height:150,page:1,rowNum:20,rowTotal:null,records:0,pager:"",pgbuttons:!0,pginput:!0,colModel:[],rowList:[],colNames:[],sortorder:"asc",sortname:"",datatype:"xml",mtype:"GET",altRows:!1,selarrrow:[],savedRow:[],shrinkToFit:!0,xmlReader:{},jsonReader:{},
-subGrid:!1,subGridModel:[],reccount:0,lastpage:0,lastsort:0,selrow:null,beforeSelectRow:null,onSelectRow:null,onSortCol:null,ondblClickRow:null,onRightClickRow:null,onPaging:null,onSelectAll:null,loadComplete:null,gridComplete:null,loadError:null,loadBeforeSend:null,afterInsertRow:null,beforeRequest:null,beforeProcessing:null,onHeaderClick:null,viewrecords:!1,loadonce:!1,multiselect:!1,multikey:!1,editurl:null,search:!1,caption:"",hidegrid:!0,hiddengrid:!1,postData:{},userData:{},treeGrid:!1,treeGridModel:"nested",
-treeReader:{},treeANode:-1,ExpandColumn:null,tree_root_level:0,prmNames:{page:"page",rows:"rows",sort:"sidx",order:"sord",search:"_search",nd:"nd",id:"id",oper:"oper",editoper:"edit",addoper:"add",deloper:"del",subgridid:"id",npage:null,totalrows:"totalrows"},forceFit:!1,gridstate:"visible",cellEdit:!1,cellsubmit:"remote",nv:0,loadui:"enable",toolbar:[!1,""],scroll:!1,multiboxonly:!1,deselectAfterSort:!0,scrollrows:!1,autowidth:!1,scrollOffset:18,cellLayout:5,subGridWidth:20,multiselectWidth:20,gridview:!1,
-rownumWidth:25,rownumbers:!1,pagerpos:"center",recordpos:"right",footerrow:!1,userDataOnFooter:!1,hoverrows:!0,altclass:"ui-priority-secondary",viewsortcols:[!1,"vertical",!0],resizeclass:"",autoencode:!1,remapColumns:[],ajaxGridOptions:{},direction:"ltr",toppager:!1,headertitles:!1,scrollTimeout:40,data:[],_index:{},grouping:!1,groupingView:{groupField:[],groupOrder:[],groupText:[],groupColumnShow:[],groupSummary:[],showSummaryOnHide:!1,sortitems:[],sortnames:[],summary:[],summaryval:[],plusicon:"ui-icon-circlesmall-plus",
-minusicon:"ui-icon-circlesmall-minus"},ignoreCase:!1,cmTemplate:{},idPrefix:""},b.jgrid.defaults,f||{}),a=this,c={headers:[],cols:[],footers:[],dragStart:function(c,e,f){this.resizing={idx:c,startX:e.clientX,sOL:f[0]};this.hDiv.style.cursor="col-resize";this.curGbox=b("#rs_m"+b.jgrid.jqID(d.id),"#gbox_"+b.jgrid.jqID(d.id));this.curGbox.css({display:"block",left:f[0],top:f[1],height:f[2]});b(a).triggerHandler("jqGridResizeStart",[e,c]);b.isFunction(d.resizeStart)&&d.resizeStart.call(this,e,c);document.onselectstart=
-function(){return!1}},dragMove:function(a){if(this.resizing){var b=a.clientX-this.resizing.startX,a=this.headers[this.resizing.idx],c="ltr"===d.direction?a.width+b:a.width-b,e;33<c&&(this.curGbox.css({left:this.resizing.sOL+b}),!0===d.forceFit?(e=this.headers[this.resizing.idx+d.nv],b="ltr"===d.direction?e.width-b:e.width+b,33<b&&(a.newWidth=c,e.newWidth=b)):(this.newWidth="ltr"===d.direction?d.tblwidth+b:d.tblwidth-b,a.newWidth=c))}},dragEnd:function(){this.hDiv.style.cursor="default";if(this.resizing){var c=
-this.resizing.idx,e=this.headers[c].newWidth||this.headers[c].width,e=parseInt(e,10);this.resizing=!1;b("#rs_m"+b.jgrid.jqID(d.id)).css("display","none");d.colModel[c].width=e;this.headers[c].width=e;this.headers[c].el.style.width=e+"px";this.cols[c].style.width=e+"px";0<this.footers.length&&(this.footers[c].style.width=e+"px");!0===d.forceFit?(e=this.headers[c+d.nv].newWidth||this.headers[c+d.nv].width,this.headers[c+d.nv].width=e,this.headers[c+d.nv].el.style.width=e+"px",this.cols[c+d.nv].style.width=
-e+"px",0<this.footers.length&&(this.footers[c+d.nv].style.width=e+"px"),d.colModel[c+d.nv].width=e):(d.tblwidth=this.newWidth||d.tblwidth,b("table:first",this.bDiv).css("width",d.tblwidth+"px"),b("table:first",this.hDiv).css("width",d.tblwidth+"px"),this.hDiv.scrollLeft=this.bDiv.scrollLeft,d.footerrow&&(b("table:first",this.sDiv).css("width",d.tblwidth+"px"),this.sDiv.scrollLeft=this.bDiv.scrollLeft));b(a).triggerHandler("jqGridResizeStop",[e,c]);b.isFunction(d.resizeStop)&&d.resizeStop.call(this,
-e,c)}this.curGbox=null;document.onselectstart=function(){return!0}},populateVisible:function(){c.timer&&clearTimeout(c.timer);c.timer=null;var a=b(c.bDiv).height();if(a){var e=b("table:first",c.bDiv),f,G;if(e[0].rows.length)try{G=(f=e[0].rows[1])?b(f).outerHeight()||c.prevRowHeight:c.prevRowHeight}catch(g){G=c.prevRowHeight}if(G){c.prevRowHeight=G;var i=d.rowNum;f=c.scrollTop=c.bDiv.scrollTop;var j=Math.round(e.position().top)-f,k=j+e.height();G*=i;var y,z,B;if(k<a&&0>=j&&(void 0===d.lastpage||parseInt((k+
-f+G-1)/G,10)<=d.lastpage))z=parseInt((a-k+G-1)/G,10),0<=k||2>z||!0===d.scroll?(y=Math.round((k+f)/G)+1,j=-1):j=1;0<j&&(y=parseInt(f/G,10)+1,z=parseInt((f+a)/G,10)+2-y,B=!0);if(z&&!(d.lastpage&&y>d.lastpage||1==d.lastpage||y===d.page&&y===d.lastpage))c.hDiv.loading?c.timer=setTimeout(c.populateVisible,d.scrollTimeout):(d.page=y,B&&(c.selectionPreserver(e[0]),c.emptyRows.call(e[0],!1,!1)),c.populate(z))}}},scrollGrid:function(a){if(d.scroll){var b=c.bDiv.scrollTop;void 0===c.scrollTop&&(c.scrollTop=
-0);b!=c.scrollTop&&(c.scrollTop=b,c.timer&&clearTimeout(c.timer),c.timer=setTimeout(c.populateVisible,d.scrollTimeout))}c.hDiv.scrollLeft=c.bDiv.scrollLeft;d.footerrow&&(c.sDiv.scrollLeft=c.bDiv.scrollLeft);a&&a.stopPropagation()},selectionPreserver:function(a){var c=a.p,d=c.selrow,e=c.selarrrow?b.makeArray(c.selarrrow):null,f=a.grid.bDiv.scrollLeft,g=function(){var h;c.selrow=null;c.selarrrow=[];if(c.multiselect&&e&&0<e.length)for(h=0;h<e.length;h++)e[h]!=d&&b(a).jqGrid("setSelection",e[h],!1,null);
-d&&b(a).jqGrid("setSelection",d,!1,null);a.grid.bDiv.scrollLeft=f;b(a).unbind(".selectionPreserver",g)};b(a).bind("jqGridGridComplete.selectionPreserver",g)}};if("TABLE"!=this.tagName.toUpperCase())alert("Element is not a table");else if(void 0!==document.documentMode&&5>=document.documentMode)alert("Grid can not be used in this ('quirks') mode!");else{b(this).empty().attr("tabindex","1");this.p=d;this.p.useProp=!!b.fn.prop;var e,i;if(0===this.p.colNames.length)for(e=0;e<this.p.colModel.length;e++)this.p.colNames[e]=
-this.p.colModel[e].label||this.p.colModel[e].name;if(this.p.colNames.length!==this.p.colModel.length)alert(b.jgrid.errors.model);else{var j=b("<div class='ui-jqgrid-view'></div>"),l,k=b.browser.msie?!0:!1;a.p.direction=b.trim(a.p.direction.toLowerCase());-1==b.inArray(a.p.direction,["ltr","rtl"])&&(a.p.direction="ltr");i=a.p.direction;b(j).insertBefore(this);b(this).appendTo(j).removeClass("scroll");var m=b("<div class='ui-jqgrid ui-widget ui-widget-content ui-corner-all'></div>");b(m).insertBefore(j).attr({id:"gbox_"+
-this.id,dir:i});b(j).appendTo(m).attr("id","gview_"+this.id);l=k&&6>=b.browser.version?'<iframe style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=\'0\');" src="javascript:false;"></iframe>':"";b("<div class='ui-widget-overlay jqgrid-overlay' id='lui_"+this.id+"'></div>").append(l).insertBefore(j);b("<div class='loading ui-state-default ui-state-active' id='load_"+this.id+"'>"+this.p.loadtext+"</div>").insertBefore(j);b(this).attr({cellspacing:"0",cellpadding:"0",border:"0",role:"grid",
-"aria-multiselectable":!!this.p.multiselect,"aria-labelledby":"gbox_"+this.id});var o=function(a,b){a=parseInt(a,10);return isNaN(a)?b?b:0:a},p=function(d,e,f,g,i,j){var K=a.p.colModel[d],k=K.align,y='style="',z=K.classes,B=K.name,q=[];k&&(y=y+("text-align:"+k+";"));K.hidden===true&&(y=y+"display:none;");if(e===0)y=y+("width: "+c.headers[d].width+"px;");else if(K.cellattr&&b.isFunction(K.cellattr))if((d=K.cellattr.call(a,i,f,g,K,j))&&typeof d==="string"){d=d.replace(/style/i,"style").replace(/title/i,
-"title");if(d.indexOf("title")>-1)K.title=false;d.indexOf("class")>-1&&(z=void 0);q=d.split("style");if(q.length===2){q[1]=b.trim(q[1].replace("=",""));if(q[1].indexOf("'")===0||q[1].indexOf('"')===0)q[1]=q[1].substring(1);y=y+q[1].replace(/'/gi,'"')}else y=y+'"'}if(!q.length){q[0]="";y=y+'"'}y=y+((z!==void 0?' class="'+z+'"':"")+(K.title&&f?' title="'+b.jgrid.stripHtml(f)+'"':""));y=y+(' aria-describedby="'+a.p.id+"_"+B+'"');return y+q[0]},v=function(c){return c===void 0||c===null||c===""?"&#160;":
-a.p.autoencode?b.jgrid.htmlEncode(c):c+""},u=function(c,d,e,f,g){var h=a.p.colModel[e];if(typeof h.formatter!=="undefined"){c={rowId:c,colModel:h,gid:a.p.id,pos:e};d=b.isFunction(h.formatter)?h.formatter.call(a,d,c,f,g):b.fmatter?b.fn.fmatter.call(a,h.formatter,d,c,f,g):v(d)}else d=v(d);return d},M=function(a,b,c,d,e){b=u(a,b,c,e,"add");return'<td role="gridcell" '+p(c,d,b,e,a,true)+">"+b+"</td>"},F=function(b,c,d){var e='<input role="checkbox" type="checkbox" id="jqg_'+a.p.id+"_"+b+'" class="cbox" name="jqg_'+
-a.p.id+"_"+b+'"/>';return'<td role="gridcell" '+p(c,d,"",null,b,true)+">"+e+"</td>"},Z=function(a,b,c,d){c=(parseInt(c,10)-1)*parseInt(d,10)+1+b;return'<td role="gridcell" class="ui-state-default jqgrid-rownum" '+p(a,b,c,null,b,true)+">"+c+"</td>"},U=function(b){var c,d=[],e=0,f;for(f=0;f<a.p.colModel.length;f++){c=a.p.colModel[f];if(c.name!=="cb"&&c.name!=="subgrid"&&c.name!=="rn"){d[e]=b=="local"?c.name:b=="xml"||b==="xmlstring"?c.xmlmap||c.name:c.jsonmap||c.name;e++}}return d},V=function(c){var d=
-a.p.remapColumns;if(!d||!d.length)d=b.map(a.p.colModel,function(a,b){return b});c&&(d=b.map(d,function(a){return a<c?null:a-c}));return d},N=function(a,c){var d;if(this.p.deepempty)b(this.rows).slice(1).remove();else{d=this.rows.length>0?this.rows[0]:null;b(this.firstChild).empty().append(d)}if(a&&this.p.scroll){b(this.grid.bDiv.firstChild).css({height:"auto"});b(this.grid.bDiv.firstChild.firstChild).css({height:0,display:"none"});if(this.grid.bDiv.scrollTop!==0)this.grid.bDiv.scrollTop=0}if(c===
-true&&this.p.treeGrid){this.p.data=[];this.p._index={}}},S=function(){var c=a.p.data.length,d,e,f;d=a.p.rownumbers===true?1:0;e=a.p.multiselect===true?1:0;f=a.p.subGrid===true?1:0;d=a.p.keyIndex===false||a.p.loadonce===true?a.p.localReader.id:a.p.colModel[a.p.keyIndex+e+f+d].name;for(e=0;e<c;e++){f=b.jgrid.getAccessor(a.p.data[e],d);a.p._index[f]=e}},J=function(c,d,e,f,g){var h="-1",i="",j,d=d?"display:none;":"",e="ui-widget-content jqgrow ui-row-"+a.p.direction+e,f=b.isFunction(a.p.rowattr)?a.p.rowattr.call(a,
-f,g):{};if(!b.isEmptyObject(f)){if(f.hasOwnProperty("id")){c=f.id;delete f.id}if(f.hasOwnProperty("tabindex")){h=f.tabindex;delete f.tabindex}if(f.hasOwnProperty("style")){d=d+f.style;delete f.style}if(f.hasOwnProperty("class")){e=e+(" "+f["class"]);delete f["class"]}try{delete f.role}catch(k){}for(j in f)f.hasOwnProperty(j)&&(i=i+(" "+j+"="+f[j]))}return'<tr role="row" id="'+c+'" tabindex="'+h+'" class="'+e+'"'+(d===""?"":' style="'+d+'"')+i+">"},$=function(c,d,e,f,g){var h=new Date,i=a.p.datatype!=
-"local"&&a.p.loadonce||a.p.datatype=="xmlstring",j=a.p.xmlReader,k=a.p.datatype=="local"?"local":"xml";if(i){a.p.data=[];a.p._index={};a.p.localReader.id="_id_"}a.p.reccount=0;if(b.isXMLDoc(c)){if(a.p.treeANode===-1&&!a.p.scroll){N.call(a,false,true);e=1}else e=e>1?e:1;var z,B,q=0,l,s=a.p.multiselect===true?1:0,P=a.p.subGrid===true?1:0,m=a.p.rownumbers===true?1:0,o,p=[],u,n={},r,w,C=[],v=a.p.altRows===true?" "+a.p.altclass:"",A;j.repeatitems||(p=U(k));o=a.p.keyIndex===false?b.isFunction(j.id)?j.id.call(a,
-c):j.id:a.p.keyIndex;if(p.length>0&&!isNaN(o)){a.p.remapColumns&&a.p.remapColumns.length&&(o=b.inArray(o,a.p.remapColumns));o=p[o]}k=(o+"").indexOf("[")===-1?p.length?function(a,c){return b(o,a).text()||c}:function(a,c){return b(j.cell,a).eq(o).text()||c}:function(a,b){return a.getAttribute(o.replace(/[\[\]]/g,""))||b};a.p.userData={};a.p.page=b.jgrid.getXmlData(c,j.page)||0;a.p.lastpage=b.jgrid.getXmlData(c,j.total);if(a.p.lastpage===void 0)a.p.lastpage=1;a.p.records=b.jgrid.getXmlData(c,j.records)||
-0;b.isFunction(j.userdata)?a.p.userData=j.userdata.call(a,c)||{}:b.jgrid.getXmlData(c,j.userdata,true).each(function(){a.p.userData[this.getAttribute("name")]=b(this).text()});c=b.jgrid.getXmlData(c,j.root,true);(c=b.jgrid.getXmlData(c,j.row,true))||(c=[]);var t=c.length,H=0,Q=[],x=parseInt(a.p.rowNum,10);if(t>0&&a.p.page<=0)a.p.page=1;if(c&&t){var D=a.p.scroll?b.jgrid.randId():1;g&&(x=x*(g+1));for(var g=b.isFunction(a.p.afterInsertRow),E=a.p.grouping&&a.p.groupingView.groupCollapse===true;H<t;){r=
-c[H];w=k(r,D+H);w=a.p.idPrefix+w;z=e===0?0:e+1;A=(z+H)%2==1?v:"";var I=C.length;C.push("");m&&C.push(Z(0,H,a.p.page,a.p.rowNum));s&&C.push(F(w,m,H));P&&C.push(b(a).jqGrid("addSubGridCell",s+m,H+e));if(j.repeatitems){u||(u=V(s+P+m));var L=b.jgrid.getXmlData(r,j.cell,true);b.each(u,function(b){var c=L[this];if(!c)return false;l=c.textContent||c.text;n[a.p.colModel[b+s+P+m].name]=l;C.push(M(w,l,b+s+P+m,H+e,r))})}else for(z=0;z<p.length;z++){l=b.jgrid.getXmlData(r,p[z]);n[a.p.colModel[z+s+P+m].name]=
-l;C.push(M(w,l,z+s+P+m,H+e,r))}C[I]=J(w,E,A,n,r);C.push("</tr>");if(a.p.grouping){Q=b(a).jqGrid("groupingPrepare",C,Q,n,H);C=[]}if(i||a.p.treeGrid===true){n._id_=w;a.p.data.push(n);a.p._index[w]=a.p.data.length-1}if(a.p.gridview===false){b("tbody:first",d).append(C.join(""));b(a).triggerHandler("jqGridAfterInsertRow",[w,n,r]);g&&a.p.afterInsertRow.call(a,w,n,r);C=[]}n={};q++;H++;if(q==x)break}}if(a.p.gridview===true){B=a.p.treeANode>-1?a.p.treeANode:0;if(a.p.grouping){b(a).jqGrid("groupingRender",
-Q,a.p.colModel.length);Q=null}else a.p.treeGrid===true&&B>0?b(a.rows[B]).after(C.join("")):b("tbody:first",d).append(C.join(""))}if(a.p.subGrid===true)try{b(a).jqGrid("addSubGrid",s+m)}catch(R){}a.p.totaltime=new Date-h;if(q>0&&a.p.records===0)a.p.records=t;C=null;if(a.p.treeGrid===true)try{b(a).jqGrid("setTreeNode",B+1,q+B+1)}catch(S){}if(!a.p.treeGrid&&!a.p.scroll)a.grid.bDiv.scrollTop=0;a.p.reccount=q;a.p.treeANode=-1;a.p.userDataOnFooter&&b(a).jqGrid("footerData","set",a.p.userData,true);if(i){a.p.records=
-t;a.p.lastpage=Math.ceil(t/x)}f||a.updatepager(false,true);if(i)for(;q<t;){r=c[q];w=k(r,q+D);w=a.p.idPrefix+w;if(j.repeatitems){u||(u=V(s+P+m));var O=b.jgrid.getXmlData(r,j.cell,true);b.each(u,function(b){var c=O[this];if(!c)return false;l=c.textContent||c.text;n[a.p.colModel[b+s+P+m].name]=l})}else for(z=0;z<p.length;z++){l=b.jgrid.getXmlData(r,p[z]);n[a.p.colModel[z+s+P+m].name]=l}n._id_=w;a.p.data.push(n);a.p._index[w]=a.p.data.length-1;n={};q++}}},aa=function(c,d,e,f,g){d=new Date;if(c){if(a.p.treeANode===
--1&&!a.p.scroll){N.call(a,false,true);e=1}else e=e>1?e:1;var h,i,j=a.p.datatype!="local"&&a.p.loadonce||a.p.datatype=="jsonstring";if(j){a.p.data=[];a.p._index={};a.p.localReader.id="_id_"}a.p.reccount=0;if(a.p.datatype=="local"){h=a.p.localReader;i="local"}else{h=a.p.jsonReader;i="json"}var k=0,l,B,q=[],m,s=a.p.multiselect?1:0,o=a.p.subGrid?1:0,p=a.p.rownumbers===true?1:0,n,u,t={},v,r,w=[],C=a.p.altRows===true?" "+a.p.altclass:"",A;a.p.page=b.jgrid.getAccessor(c,h.page)||0;n=b.jgrid.getAccessor(c,
-h.total);a.p.lastpage=n===void 0?1:n;a.p.records=b.jgrid.getAccessor(c,h.records)||0;a.p.userData=b.jgrid.getAccessor(c,h.userdata)||{};h.repeatitems||(m=q=U(i));i=a.p.keyIndex===false?b.isFunction(h.id)?h.id.call(a,c):h.id:a.p.keyIndex;if(q.length>0&&!isNaN(i)){a.p.remapColumns&&a.p.remapColumns.length&&(i=b.inArray(i,a.p.remapColumns));i=q[i]}(u=b.jgrid.getAccessor(c,h.root))||(u=[]);n=u.length;c=0;if(n>0&&a.p.page<=0)a.p.page=1;var x=parseInt(a.p.rowNum,10),D=a.p.scroll?b.jgrid.randId():1;g&&(x=
-x*(g+1));for(var H=b.isFunction(a.p.afterInsertRow),Q=[],E=a.p.grouping&&a.p.groupingView.groupCollapse===true;c<n;){g=u[c];r=b.jgrid.getAccessor(g,i);if(r===void 0){r=D+c;if(q.length===0&&h.cell){l=b.jgrid.getAccessor(g,h.cell);r=l!==void 0?l[i]||r:r}}r=a.p.idPrefix+r;l=e===1?0:e;A=(l+c)%2==1?C:"";var I=w.length;w.push("");p&&w.push(Z(0,c,a.p.page,a.p.rowNum));s&&w.push(F(r,p,c));o&&w.push(b(a).jqGrid("addSubGridCell",s+p,c+e));if(h.repeatitems){h.cell&&(g=b.jgrid.getAccessor(g,h.cell));m||(m=V(s+
-o+p))}for(B=0;B<m.length;B++){l=b.jgrid.getAccessor(g,m[B]);w.push(M(r,l,B+s+o+p,c+e,g));t[a.p.colModel[B+s+o+p].name]=l}w[I]=J(r,E,A,t,g);w.push("</tr>");if(a.p.grouping){Q=b(a).jqGrid("groupingPrepare",w,Q,t,c);w=[]}if(j||a.p.treeGrid===true){t._id_=r;a.p.data.push(t);a.p._index[r]=a.p.data.length-1}if(a.p.gridview===false){b("#"+b.jgrid.jqID(a.p.id)+" tbody:first").append(w.join(""));b(a).triggerHandler("jqGridAfterInsertRow",[r,t,g]);H&&a.p.afterInsertRow.call(a,r,t,g);w=[]}t={};k++;c++;if(k==
-x)break}if(a.p.gridview===true){v=a.p.treeANode>-1?a.p.treeANode:0;a.p.grouping?b(a).jqGrid("groupingRender",Q,a.p.colModel.length):a.p.treeGrid===true&&v>0?b(a.rows[v]).after(w.join("")):b("#"+b.jgrid.jqID(a.p.id)+" tbody:first").append(w.join(""))}if(a.p.subGrid===true)try{b(a).jqGrid("addSubGrid",s+p)}catch(L){}a.p.totaltime=new Date-d;if(k>0&&a.p.records===0)a.p.records=n;if(a.p.treeGrid===true)try{b(a).jqGrid("setTreeNode",v+1,k+v+1)}catch(O){}if(!a.p.treeGrid&&!a.p.scroll)a.grid.bDiv.scrollTop=
-0;a.p.reccount=k;a.p.treeANode=-1;a.p.userDataOnFooter&&b(a).jqGrid("footerData","set",a.p.userData,true);if(j){a.p.records=n;a.p.lastpage=Math.ceil(n/x)}f||a.updatepager(false,true);if(j)for(;k<n&&u[k];){g=u[k];r=b.jgrid.getAccessor(g,i);if(r===void 0){r=D+k;q.length===0&&h.cell&&(r=b.jgrid.getAccessor(g,h.cell)[i]||r)}if(g){r=a.p.idPrefix+r;if(h.repeatitems){h.cell&&(g=b.jgrid.getAccessor(g,h.cell));m||(m=V(s+o+p))}for(B=0;B<m.length;B++){l=b.jgrid.getAccessor(g,m[B]);t[a.p.colModel[B+s+o+p].name]=
-l}t._id_=r;a.p.data.push(t);a.p._index[r]=a.p.data.length-1;t={}}k++}}},ma=function(){function c(d){var e=0,g,h,i,j,T;if(d.groups!==void 0){(h=d.groups.length&&d.groupOp.toString().toUpperCase()==="OR")&&s.orBegin();for(g=0;g<d.groups.length;g++){e>0&&h&&s.or();try{c(d.groups[g])}catch(k){alert(k)}e++}h&&s.orEnd()}if(d.rules!==void 0){if(e>0){h=s.select();s=b.jgrid.from(h);a.p.ignoreCase&&(s=s.ignoreCase())}try{(i=d.rules.length&&d.groupOp.toString().toUpperCase()==="OR")&&s.orBegin();for(g=0;g<d.rules.length;g++){T=
-d.rules[g];j=d.groupOp.toString().toUpperCase();if(o[T.op]&&T.field){e>0&&j&&j==="OR"&&(s=s.or());s=o[T.op](s,j)(T.field,T.data,f[T.field])}e++}i&&s.orEnd()}catch(na){alert(na)}}}var d,e=false,f={},g=[],h=[],i,j,k;if(b.isArray(a.p.data)){var l=a.p.grouping?a.p.groupingView:false,m,q;b.each(a.p.colModel,function(){j=this.sorttype||"text";if(j=="date"||j=="datetime"){if(this.formatter&&typeof this.formatter==="string"&&this.formatter=="date"){i=this.formatoptions&&this.formatoptions.srcformat?this.formatoptions.srcformat:
-b.jgrid.formatter.date.srcformat;k=this.formatoptions&&this.formatoptions.newformat?this.formatoptions.newformat:b.jgrid.formatter.date.newformat}else i=k=this.datefmt||"Y-m-d";f[this.name]={stype:j,srcfmt:i,newfmt:k}}else f[this.name]={stype:j,srcfmt:"",newfmt:""};if(a.p.grouping){q=0;for(m=l.groupField.length;q<m;q++)if(this.name==l.groupField[q]){var c=this.name;if(typeof this.index!="undefined")c=this.index;g[q]=f[c];h[q]=c}}if(!e&&(this.index==a.p.sortname||this.name==a.p.sortname)){d=this.name;
-e=true}});if(a.p.treeGrid)b(a).jqGrid("SortTree",d,a.p.sortorder,f[d].stype,f[d].srcfmt);else{var o={eq:function(a){return a.equals},ne:function(a){return a.notEquals},lt:function(a){return a.less},le:function(a){return a.lessOrEquals},gt:function(a){return a.greater},ge:function(a){return a.greaterOrEquals},cn:function(a){return a.contains},nc:function(a,b){return b==="OR"?a.orNot().contains:a.andNot().contains},bw:function(a){return a.startsWith},bn:function(a,b){return b==="OR"?a.orNot().startsWith:
-a.andNot().startsWith},en:function(a,b){return b==="OR"?a.orNot().endsWith:a.andNot().endsWith},ew:function(a){return a.endsWith},ni:function(a,b){return b==="OR"?a.orNot().equals:a.andNot().equals},"in":function(a){return a.equals},nu:function(a){return a.isNull},nn:function(a,b){return b==="OR"?a.orNot().isNull:a.andNot().isNull}},s=b.jgrid.from(a.p.data);a.p.ignoreCase&&(s=s.ignoreCase());if(a.p.search===true){var n=a.p.postData.filters;if(n){typeof n=="string"&&(n=b.jgrid.parse(n));c(n)}else try{s=
-o[a.p.postData.searchOper](s)(a.p.postData.searchField,a.p.postData.searchString,f[a.p.postData.searchField])}catch(p){}}if(a.p.grouping)for(q=0;q<m;q++)s.orderBy(h[q],l.groupOrder[q],g[q].stype,g[q].srcfmt);d&&a.p.sortorder&&e&&(a.p.sortorder.toUpperCase()=="DESC"?s.orderBy(a.p.sortname,"d",f[d].stype,f[d].srcfmt):s.orderBy(a.p.sortname,"a",f[d].stype,f[d].srcfmt));var n=s.select(),u=parseInt(a.p.rowNum,10),t=n.length,v=parseInt(a.p.page,10),x=Math.ceil(t/u),r={},n=n.slice((v-1)*u,v*u),f=s=null;
-r[a.p.localReader.total]=x;r[a.p.localReader.page]=v;r[a.p.localReader.records]=t;r[a.p.localReader.root]=n;r[a.p.localReader.userdata]=a.p.userData;n=null;return r}}},ca=function(){a.grid.hDiv.loading=true;if(!a.p.hiddengrid)switch(a.p.loadui){case "enable":b("#load_"+b.jgrid.jqID(a.p.id)).show();break;case "block":b("#lui_"+b.jgrid.jqID(a.p.id)).show();b("#load_"+b.jgrid.jqID(a.p.id)).show()}},O=function(){a.grid.hDiv.loading=false;switch(a.p.loadui){case "enable":b("#load_"+b.jgrid.jqID(a.p.id)).hide();
-break;case "block":b("#lui_"+b.jgrid.jqID(a.p.id)).hide();b("#load_"+b.jgrid.jqID(a.p.id)).hide()}},I=function(c){if(!a.grid.hDiv.loading){var d=a.p.scroll&&c===false,e={},f,g=a.p.prmNames;if(a.p.page<=0)a.p.page=1;if(g.search!==null)e[g.search]=a.p.search;g.nd!==null&&(e[g.nd]=(new Date).getTime());if(g.rows!==null)e[g.rows]=a.p.rowNum;if(g.page!==null)e[g.page]=a.p.page;if(g.sort!==null)e[g.sort]=a.p.sortname;if(g.order!==null)e[g.order]=a.p.sortorder;if(a.p.rowTotal!==null&&g.totalrows!==null)e[g.totalrows]=
-a.p.rowTotal;var h=b.isFunction(a.p.loadComplete),i=h?a.p.loadComplete:null,j=0,c=c||1;if(c>1)if(g.npage!==null){e[g.npage]=c;j=c-1;c=1}else i=function(b){a.p.page++;a.grid.hDiv.loading=false;h&&a.p.loadComplete.call(a,b);I(c-1)};else g.npage!==null&&delete a.p.postData[g.npage];if(a.p.grouping){b(a).jqGrid("groupingSetup");var k=a.p.groupingView,l,m="";for(l=0;l<k.groupField.length;l++)m=m+(k.groupField[l]+" "+k.groupOrder[l]+", ");e[g.sort]=m+e[g.sort]}b.extend(a.p.postData,e);var q=!a.p.scroll?
-1:a.rows.length-1,e=b(a).triggerHandler("jqGridBeforeRequest");if(!(e===false||e==="stop"))if(b.isFunction(a.p.datatype))a.p.datatype.call(a,a.p.postData,"load_"+a.p.id);else{if(b.isFunction(a.p.beforeRequest)){e=a.p.beforeRequest.call(a);e===void 0&&(e=true);if(e===false)return}f=a.p.datatype.toLowerCase();switch(f){case "json":case "jsonp":case "xml":case "script":b.ajax(b.extend({url:a.p.url,type:a.p.mtype,dataType:f,data:b.isFunction(a.p.serializeGridData)?a.p.serializeGridData.call(a,a.p.postData):
-a.p.postData,success:function(e,g,h){if(b.isFunction(a.p.beforeProcessing)&&a.p.beforeProcessing.call(a,e,g,h)===false)O();else{f==="xml"?$(e,a.grid.bDiv,q,c>1,j):aa(e,a.grid.bDiv,q,c>1,j);b(a).triggerHandler("jqGridLoadComplete",[e]);i&&i.call(a,e);b(a).triggerHandler("jqGridAfterLoadComplete",[e]);d&&a.grid.populateVisible();if(a.p.loadonce||a.p.treeGrid)a.p.datatype="local";c===1&&O()}},error:function(d,e,f){b.isFunction(a.p.loadError)&&a.p.loadError.call(a,d,e,f);c===1&&O()},beforeSend:function(c,
-d){var e=true;b.isFunction(a.p.loadBeforeSend)&&(e=a.p.loadBeforeSend.call(a,c,d));e===void 0&&(e=true);if(e===false)return false;ca()}},b.jgrid.ajaxOptions,a.p.ajaxGridOptions));break;case "xmlstring":ca();e=b.jgrid.stringToDoc(a.p.datastr);$(e,a.grid.bDiv);b(a).triggerHandler("jqGridLoadComplete",[e]);h&&a.p.loadComplete.call(a,e);b(a).triggerHandler("jqGridAfterLoadComplete",[e]);a.p.datatype="local";a.p.datastr=null;O();break;case "jsonstring":ca();e=typeof a.p.datastr=="string"?b.jgrid.parse(a.p.datastr):
-a.p.datastr;aa(e,a.grid.bDiv);b(a).triggerHandler("jqGridLoadComplete",[e]);h&&a.p.loadComplete.call(a,e);b(a).triggerHandler("jqGridAfterLoadComplete",[e]);a.p.datatype="local";a.p.datastr=null;O();break;case "local":case "clientside":ca();a.p.datatype="local";e=ma();aa(e,a.grid.bDiv,q,c>1,j);b(a).triggerHandler("jqGridLoadComplete",[e]);i&&i.call(a,e);b(a).triggerHandler("jqGridAfterLoadComplete",[e]);d&&a.grid.populateVisible();O()}}}},da=function(c){b("#cb_"+b.jgrid.jqID(a.p.id),a.grid.hDiv)[a.p.useProp?
-"prop":"attr"]("checked",c);if(a.p.frozenColumns&&a.p.id+"_frozen")b("#cb_"+b.jgrid.jqID(a.p.id),a.grid.fhDiv)[a.p.useProp?"prop":"attr"]("checked",c)};l=function(c,e){var d="",f="<table cellspacing='0' cellpadding='0' border='0' style='table-layout:auto;' class='ui-pg-table'><tbody><tr>",g="",h,j,k,l,m=function(c){var e;b.isFunction(a.p.onPaging)&&(e=a.p.onPaging.call(a,c));a.p.selrow=null;if(a.p.multiselect){a.p.selarrrow=[];da(false)}a.p.savedRow=[];return e=="stop"?false:true},c=c.substr(1),e=
-e+("_"+c);h="pg_"+c;j=c+"_left";k=c+"_center";l=c+"_right";b("#"+b.jgrid.jqID(c)).append("<div id='"+h+"' class='ui-pager-control' role='group'><table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table' style='width:100%;table-layout:fixed;height:100%;' role='row'><tbody><tr><td id='"+j+"' align='left'></td><td id='"+k+"' align='center' style='white-space:pre;'></td><td id='"+l+"' align='right'></td></tr></tbody></table></div>").attr("dir","ltr");if(a.p.rowList.length>0){g="<td dir='"+
-i+"'>";g=g+"<select class='ui-pg-selbox' role='listbox'>";for(j=0;j<a.p.rowList.length;j++)g=g+('<option role="option" value="'+a.p.rowList[j]+'"'+(a.p.rowNum==a.p.rowList[j]?' selected="selected"':"")+">"+a.p.rowList[j]+"</option>");g=g+"</select></td>"}i=="rtl"&&(f=f+g);a.p.pginput===true&&(d="<td dir='"+i+"'>"+b.jgrid.format(a.p.pgtext||"","<input class='ui-pg-input' type='text' size='2' maxlength='7' value='0' role='textbox'/>","<span id='sp_1_"+b.jgrid.jqID(c)+"'></span>")+"</td>");if(a.p.pgbuttons===
-true){j=["first"+e,"prev"+e,"next"+e,"last"+e];i=="rtl"&&j.reverse();f=f+("<td id='"+j[0]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-first'></span></td>");f=f+("<td id='"+j[1]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-prev'></span></td>");f=f+(d!==""?"<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>"+d+"<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>":
-"")+("<td id='"+j[2]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-next'></span></td>");f=f+("<td id='"+j[3]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-end'></span></td>")}else d!==""&&(f=f+d);i=="ltr"&&(f=f+g);f=f+"</tr></tbody></table>";a.p.viewrecords===true&&b("td#"+c+"_"+a.p.recordpos,"#"+h).append("<div dir='"+i+"' style='text-align:"+a.p.recordpos+"' class='ui-paging-info'></div>");b("td#"+c+"_"+a.p.pagerpos,"#"+h).append(f);g=b(".ui-jqgrid").css("font-size")||
-"11px";b(document.body).append("<div id='testpg' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:"+g+";visibility:hidden;' ></div>");f=b(f).clone().appendTo("#testpg").width();b("#testpg").remove();if(f>0){d!==""&&(f=f+50);b("td#"+c+"_"+a.p.pagerpos,"#"+h).width(f)}a.p._nvtd=[];a.p._nvtd[0]=f?Math.floor((a.p.width-f)/2):Math.floor(a.p.width/3);a.p._nvtd[1]=0;f=null;b(".ui-pg-selbox","#"+h).bind("change",function(){a.p.page=Math.round(a.p.rowNum*(a.p.page-1)/this.value-0.5)+1;a.p.rowNum=
-this.value;a.p.pager&&b(".ui-pg-selbox",a.p.pager).val(this.value);a.p.toppager&&b(".ui-pg-selbox",a.p.toppager).val(this.value);if(!m("records"))return false;I();return false});if(a.p.pgbuttons===true){b(".ui-pg-button","#"+h).hover(function(){if(b(this).hasClass("ui-state-disabled"))this.style.cursor="default";else{b(this).addClass("ui-state-hover");this.style.cursor="pointer"}},function(){if(!b(this).hasClass("ui-state-disabled")){b(this).removeClass("ui-state-hover");this.style.cursor="default"}});
-b("#first"+b.jgrid.jqID(e)+", #prev"+b.jgrid.jqID(e)+", #next"+b.jgrid.jqID(e)+", #last"+b.jgrid.jqID(e)).click(function(){var b=o(a.p.page,1),c=o(a.p.lastpage,1),d=false,f=true,g=true,h=true,i=true;if(c===0||c===1)i=h=g=f=false;else if(c>1&&b>=1)if(b===1)g=f=false;else{if(b===c)i=h=false}else if(c>1&&b===0){i=h=false;b=c-1}if(this.id==="first"+e&&f){a.p.page=1;d=true}if(this.id==="prev"+e&&g){a.p.page=b-1;d=true}if(this.id==="next"+e&&h){a.p.page=b+1;d=true}if(this.id==="last"+e&&i){a.p.page=c;d=
-true}if(d){if(!m(this.id))return false;I()}return false})}a.p.pginput===true&&b("input.ui-pg-input","#"+h).keypress(function(c){if((c.charCode?c.charCode:c.keyCode?c.keyCode:0)==13){a.p.page=b(this).val()>0?b(this).val():a.p.page;if(!m("user"))return false;I();return false}return this})};var ja=function(c,e,d,f){if(a.p.colModel[e].sortable&&!(a.p.savedRow.length>0)){if(!d){if(a.p.lastsort==e)if(a.p.sortorder=="asc")a.p.sortorder="desc";else{if(a.p.sortorder=="desc")a.p.sortorder="asc"}else a.p.sortorder=
-a.p.colModel[e].firstsortorder||"asc";a.p.page=1}if(f){if(a.p.lastsort==e&&a.p.sortorder==f&&!d)return;a.p.sortorder=f}d=a.grid.headers[a.p.lastsort].el;f=a.grid.headers[e].el;b("span.ui-grid-ico-sort",d).addClass("ui-state-disabled");b(d).attr("aria-selected","false");b("span.ui-icon-"+a.p.sortorder,f).removeClass("ui-state-disabled");b(f).attr("aria-selected","true");if(!a.p.viewsortcols[0]&&a.p.lastsort!=e){b("span.s-ico",d).hide();b("span.s-ico",f).show()}c=c.substring(5+a.p.id.length+1);a.p.sortname=
-a.p.colModel[e].index||c;d=a.p.sortorder;if(b(a).triggerHandler("jqGridSortCol",[c,e,d])==="stop")a.p.lastsort=e;else if(b.isFunction(a.p.onSortCol)&&a.p.onSortCol.call(a,c,e,d)=="stop")a.p.lastsort=e;else{if(a.p.datatype=="local")a.p.deselectAfterSort&&b(a).jqGrid("resetSelection");else{a.p.selrow=null;a.p.multiselect&&da(false);a.p.selarrrow=[];a.p.savedRow=[]}if(a.p.scroll){d=a.grid.bDiv.scrollLeft;N.call(a,true,false);a.grid.hDiv.scrollLeft=d}a.p.subGrid&&a.p.datatype=="local"&&b("td.sgexpanded",
-"#"+b.jgrid.jqID(a.p.id)).each(function(){b(this).trigger("click")});I();a.p.lastsort=e;if(a.p.sortname!=c&&e)a.p.lastsort=e}}},oa=function(c){var e,d={},f=b.jgrid.cellWidth()?0:a.p.cellLayout;for(e=d[0]=d[1]=d[2]=0;e<=c;e++)a.p.colModel[e].hidden===false&&(d[0]=d[0]+(a.p.colModel[e].width+f));a.p.direction=="rtl"&&(d[0]=a.p.width-d[0]);d[0]=d[0]-a.grid.bDiv.scrollLeft;b(a.grid.cDiv).is(":visible")&&(d[1]=d[1]+(b(a.grid.cDiv).height()+parseInt(b(a.grid.cDiv).css("padding-top"),10)+parseInt(b(a.grid.cDiv).css("padding-bottom"),
-10)));if(a.p.toolbar[0]===true&&(a.p.toolbar[1]=="top"||a.p.toolbar[1]=="both"))d[1]=d[1]+(b(a.grid.uDiv).height()+parseInt(b(a.grid.uDiv).css("border-top-width"),10)+parseInt(b(a.grid.uDiv).css("border-bottom-width"),10));a.p.toppager&&(d[1]=d[1]+(b(a.grid.topDiv).height()+parseInt(b(a.grid.topDiv).css("border-bottom-width"),10)));d[2]=d[2]+(b(a.grid.bDiv).height()+b(a.grid.hDiv).height());return d},ka=function(c){var d,e=a.grid.headers,f=b.jgrid.getCellIndex(c);for(d=0;d<e.length;d++)if(c===e[d].el){f=
-d;break}return f};this.p.id=this.id;-1==b.inArray(a.p.multikey,["shiftKey","altKey","ctrlKey"])&&(a.p.multikey=!1);a.p.keyIndex=!1;for(e=0;e<a.p.colModel.length;e++)a.p.colModel[e]=b.extend(!0,{},a.p.cmTemplate,a.p.colModel[e].template||{},a.p.colModel[e]),!1===a.p.keyIndex&&!0===a.p.colModel[e].key&&(a.p.keyIndex=e);a.p.sortorder=a.p.sortorder.toLowerCase();!0===a.p.grouping&&(a.p.scroll=!1,a.p.rownumbers=!1,a.p.treeGrid=!1,a.p.gridview=!0);if(!0===this.p.treeGrid){try{b(this).jqGrid("setTreeGrid")}catch(qa){}"local"!=
-a.p.datatype&&(a.p.localReader={id:"_id_"})}if(this.p.subGrid)try{b(a).jqGrid("setSubGrid")}catch(ra){}this.p.multiselect&&(this.p.colNames.unshift("<input role='checkbox' id='cb_"+this.p.id+"' class='cbox' type='checkbox'/>"),this.p.colModel.unshift({name:"cb",width:b.jgrid.cellWidth()?a.p.multiselectWidth+a.p.cellLayout:a.p.multiselectWidth,sortable:!1,resizable:!1,hidedlg:!0,search:!1,align:"center",fixed:!0}));this.p.rownumbers&&(this.p.colNames.unshift(""),this.p.colModel.unshift({name:"rn",
-width:a.p.rownumWidth,sortable:!1,resizable:!1,hidedlg:!0,search:!1,align:"center",fixed:!0}));a.p.xmlReader=b.extend(!0,{root:"rows",row:"row",page:"rows>page",total:"rows>total",records:"rows>records",repeatitems:!0,cell:"cell",id:"[id]",userdata:"userdata",subgrid:{root:"rows",row:"row",repeatitems:!0,cell:"cell"}},a.p.xmlReader);a.p.jsonReader=b.extend(!0,{root:"rows",page:"page",total:"total",records:"records",repeatitems:!0,cell:"cell",id:"id",userdata:"userdata",subgrid:{root:"rows",repeatitems:!0,
-cell:"cell"}},a.p.jsonReader);a.p.localReader=b.extend(!0,{root:"rows",page:"page",total:"total",records:"records",repeatitems:!1,cell:"cell",id:"id",userdata:"userdata",subgrid:{root:"rows",repeatitems:!0,cell:"cell"}},a.p.localReader);a.p.scroll&&(a.p.pgbuttons=!1,a.p.pginput=!1,a.p.rowList=[]);a.p.data.length&&S();var x="<thead><tr class='ui-jqgrid-labels' role='rowheader'>",la,L,ea,ba,fa,A,n,W;L=W="";if(!0===a.p.shrinkToFit&&!0===a.p.forceFit)for(e=a.p.colModel.length-1;0<=e;e--)if(!a.p.colModel[e].hidden){a.p.colModel[e].resizable=
-!1;break}"horizontal"==a.p.viewsortcols[1]&&(W=" ui-i-asc",L=" ui-i-desc");la=k?"class='ui-th-div-ie'":"";W="<span class='s-ico' style='display:none'><span sort='asc' class='ui-grid-ico-sort ui-icon-asc"+W+" ui-state-disabled ui-icon ui-icon-triangle-1-n ui-sort-"+i+"'></span>"+("<span sort='desc' class='ui-grid-ico-sort ui-icon-desc"+L+" ui-state-disabled ui-icon ui-icon-triangle-1-s ui-sort-"+i+"'></span></span>");for(e=0;e<this.p.colNames.length;e++)L=a.p.headertitles?' title="'+b.jgrid.stripHtml(a.p.colNames[e])+
-'"':"",x+="<th id='"+a.p.id+"_"+a.p.colModel[e].name+"' role='columnheader' class='ui-state-default ui-th-column ui-th-"+i+"'"+L+">",L=a.p.colModel[e].index||a.p.colModel[e].name,x+="<div id='jqgh_"+a.p.id+"_"+a.p.colModel[e].name+"' "+la+">"+a.p.colNames[e],a.p.colModel[e].width=a.p.colModel[e].width?parseInt(a.p.colModel[e].width,10):150,"boolean"!==typeof a.p.colModel[e].title&&(a.p.colModel[e].title=!0),L==a.p.sortname&&(a.p.lastsort=e),x+=W+"</div></th>";W=null;b(this).append(x+"</tr></thead>");
-b("thead tr:first th",this).hover(function(){b(this).addClass("ui-state-hover")},function(){b(this).removeClass("ui-state-hover")});if(this.p.multiselect){var ga=[],X;b("#cb_"+b.jgrid.jqID(a.p.id),this).bind("click",function(){a.p.selarrrow=[];var c=a.p.frozenColumns===true?a.p.id+"_frozen":"";if(this.checked){b(a.rows).each(function(d){if(d>0&&!b(this).hasClass("ui-subgrid")&&!b(this).hasClass("jqgroup")&&!b(this).hasClass("ui-state-disabled")){b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+b.jgrid.jqID(this.id))[a.p.useProp?
-"prop":"attr"]("checked",true);b(this).addClass("ui-state-highlight").attr("aria-selected","true");a.p.selarrrow.push(this.id);a.p.selrow=this.id;if(c){b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+b.jgrid.jqID(this.id),a.grid.fbDiv)[a.p.useProp?"prop":"attr"]("checked",true);b("#"+b.jgrid.jqID(this.id),a.grid.fbDiv).addClass("ui-state-highlight")}}});X=true;ga=[]}else{b(a.rows).each(function(d){if(d>0&&!b(this).hasClass("ui-subgrid")&&!b(this).hasClass("ui-state-disabled")){b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+
-b.jgrid.jqID(this.id))[a.p.useProp?"prop":"attr"]("checked",false);b(this).removeClass("ui-state-highlight").attr("aria-selected","false");ga.push(this.id);if(c){b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+b.jgrid.jqID(this.id),a.grid.fbDiv)[a.p.useProp?"prop":"attr"]("checked",false);b("#"+b.jgrid.jqID(this.id),a.grid.fbDiv).removeClass("ui-state-highlight")}}});a.p.selrow=null;X=false}b(a).triggerHandler("jqGridSelectAll",[X?a.p.selarrrow:ga,X]);b.isFunction(a.p.onSelectAll)&&a.p.onSelectAll.call(a,X?a.p.selarrrow:
-ga,X)})}!0===a.p.autowidth&&(x=b(m).innerWidth(),a.p.width=0<x?x:"nw");(function(){var d=0,e=b.jgrid.cellWidth()?0:o(a.p.cellLayout,0),f=0,g,i=o(a.p.scrollOffset,0),j,k=false,l,m=0,n=0,p;b.each(a.p.colModel,function(){if(typeof this.hidden==="undefined")this.hidden=false;this.widthOrg=j=o(this.width,0);if(this.hidden===false){d=d+(j+e);this.fixed?m=m+(j+e):f++;n++}});if(isNaN(a.p.width))a.p.width=d+(a.p.shrinkToFit===false&&!isNaN(a.p.height)?i:0);c.width=a.p.width;a.p.tblwidth=d;if(a.p.shrinkToFit===
-false&&a.p.forceFit===true)a.p.forceFit=false;if(a.p.shrinkToFit===true&&f>0){l=c.width-e*f-m;if(!isNaN(a.p.height)){l=l-i;k=true}d=0;b.each(a.p.colModel,function(b){if(this.hidden===false&&!this.fixed){this.width=j=Math.round(l*this.width/(a.p.tblwidth-e*f-m));d=d+j;g=b}});p=0;k?c.width-m-(d+e*f)!==i&&(p=c.width-m-(d+e*f)-i):!k&&Math.abs(c.width-m-(d+e*f))!==1&&(p=c.width-m-(d+e*f));a.p.colModel[g].width=a.p.colModel[g].width+p;a.p.tblwidth=d+p+e*f+m;if(a.p.tblwidth>a.p.width){a.p.colModel[g].width=
-a.p.colModel[g].width-(a.p.tblwidth-parseInt(a.p.width,10));a.p.tblwidth=a.p.width}}})();b(m).css("width",c.width+"px").append("<div class='ui-jqgrid-resize-mark' id='rs_m"+a.p.id+"'>&#160;</div>");b(j).css("width",c.width+"px");var x=b("thead:first",a).get(0),R="";a.p.footerrow&&(R+="<table role='grid' style='width:"+a.p.tblwidth+"px' class='ui-jqgrid-ftable' cellspacing='0' cellpadding='0' border='0'><tbody><tr role='row' class='ui-widget-content footrow footrow-"+i+"'>");var j=b("tr:first",x),
-Y="<tr class='jqgfirstrow' role='row' style='height:auto'>";a.p.disableClick=!1;b("th",j).each(function(d){ea=a.p.colModel[d].width;if(typeof a.p.colModel[d].resizable==="undefined")a.p.colModel[d].resizable=true;if(a.p.colModel[d].resizable){ba=document.createElement("span");b(ba).html("&#160;").addClass("ui-jqgrid-resize ui-jqgrid-resize-"+i);b.browser.opera||b(ba).css("cursor","col-resize");b(this).addClass(a.p.resizeclass)}else ba="";b(this).css("width",ea+"px").prepend(ba);var e="";if(a.p.colModel[d].hidden){b(this).css("display",
-"none");e="display:none;"}Y=Y+("<td role='gridcell' style='height:0px;width:"+ea+"px;"+e+"'></td>");c.headers[d]={width:ea,el:this};fa=a.p.colModel[d].sortable;if(typeof fa!=="boolean")fa=a.p.colModel[d].sortable=true;e=a.p.colModel[d].name;e=="cb"||e=="subgrid"||e=="rn"||a.p.viewsortcols[2]&&b(">div",this).addClass("ui-jqgrid-sortable");if(fa)if(a.p.viewsortcols[0]){b("div span.s-ico",this).show();d==a.p.lastsort&&b("div span.ui-icon-"+a.p.sortorder,this).removeClass("ui-state-disabled")}else if(d==
-a.p.lastsort){b("div span.s-ico",this).show();b("div span.ui-icon-"+a.p.sortorder,this).removeClass("ui-state-disabled")}a.p.footerrow&&(R=R+("<td role='gridcell' "+p(d,0,"",null,"",false)+">&#160;</td>"))}).mousedown(function(d){if(b(d.target).closest("th>span.ui-jqgrid-resize").length==1){var e=ka(this);if(a.p.forceFit===true){var f=a.p,g=e,i;for(i=e+1;i<a.p.colModel.length;i++)if(a.p.colModel[i].hidden!==true){g=i;break}f.nv=g-e}c.dragStart(e,d,oa(e));return false}}).click(function(c){if(a.p.disableClick)return a.p.disableClick=
-false;var d="th>div.ui-jqgrid-sortable",e,f;a.p.viewsortcols[2]||(d="th>div>span>span.ui-grid-ico-sort");c=b(c.target).closest(d);if(c.length==1){d=ka(this);if(!a.p.viewsortcols[2]){e=true;f=c.attr("sort")}ja(b("div",this)[0].id,d,e,f);return false}});if(a.p.sortable&&b.fn.sortable)try{b(a).jqGrid("sortableColumns",j)}catch(sa){}a.p.footerrow&&(R+="</tr></tbody></table>");Y+="</tr>";this.appendChild(document.createElement("tbody"));b(this).addClass("ui-jqgrid-btable").append(Y);var Y=null,j=b("<table class='ui-jqgrid-htable' style='width:"+
-a.p.tblwidth+"px' role='grid' aria-labelledby='gbox_"+this.id+"' cellspacing='0' cellpadding='0' border='0'></table>").append(x),D=a.p.caption&&!0===a.p.hiddengrid?!0:!1;e=b("<div class='ui-jqgrid-hbox"+("rtl"==i?"-rtl":"")+"'></div>");x=null;c.hDiv=document.createElement("div");b(c.hDiv).css({width:c.width+"px"}).addClass("ui-state-default ui-jqgrid-hdiv").append(e);b(e).append(j);j=null;D&&b(c.hDiv).hide();a.p.pager&&("string"==typeof a.p.pager?"#"!=a.p.pager.substr(0,1)&&(a.p.pager="#"+a.p.pager):
-a.p.pager="#"+b(a.p.pager).attr("id"),b(a.p.pager).css({width:c.width+"px"}).appendTo(m).addClass("ui-state-default ui-jqgrid-pager ui-corner-bottom"),D&&b(a.p.pager).hide(),l(a.p.pager,""));!1===a.p.cellEdit&&!0===a.p.hoverrows&&b(a).bind("mouseover",function(a){n=b(a.target).closest("tr.jqgrow");b(n).attr("class")!=="ui-subgrid"&&b(n).addClass("ui-state-hover")}).bind("mouseout",function(a){n=b(a.target).closest("tr.jqgrow");b(n).removeClass("ui-state-hover")});var t,E,ha;b(a).before(c.hDiv).click(function(c){A=
-c.target;n=b(A,a.rows).closest("tr.jqgrow");if(b(n).length===0||n[0].className.indexOf("ui-state-disabled")>-1||(b(A,a).closest("table.ui-jqgrid-btable").attr("id")||"").replace("_frozen","")!==a.id)return this;var d=b(A).hasClass("cbox"),e=b(a).triggerHandler("jqGridBeforeSelectRow",[n[0].id,c]);(e=e===false||e==="stop"?false:true)&&b.isFunction(a.p.beforeSelectRow)&&(e=a.p.beforeSelectRow.call(a,n[0].id,c));if(!(A.tagName=="A"||(A.tagName=="INPUT"||A.tagName=="TEXTAREA"||A.tagName=="OPTION"||A.tagName==
-"SELECT")&&!d)&&e===true){t=n[0].id;E=b.jgrid.getCellIndex(A);ha=b(A).closest("td,th").html();b(a).triggerHandler("jqGridCellSelect",[t,E,ha,c]);b.isFunction(a.p.onCellSelect)&&a.p.onCellSelect.call(a,t,E,ha,c);if(a.p.cellEdit===true)if(a.p.multiselect&&d)b(a).jqGrid("setSelection",t,true,c);else{t=n[0].rowIndex;try{b(a).jqGrid("editCell",t,E,true)}catch(f){}}else if(a.p.multikey)if(c[a.p.multikey])b(a).jqGrid("setSelection",t,true,c);else{if(a.p.multiselect&&d){d=b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+
-t).is(":checked");b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+t)[a.p.useProp?"prop":"attr"]("checked",d)}}else{if(a.p.multiselect&&a.p.multiboxonly&&!d){var g=a.p.frozenColumns?a.p.id+"_frozen":"";b(a.p.selarrrow).each(function(c,d){var e=a.rows.namedItem(d);b(e).removeClass("ui-state-highlight");b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+b.jgrid.jqID(d))[a.p.useProp?"prop":"attr"]("checked",false);if(g){b("#"+b.jgrid.jqID(d),"#"+b.jgrid.jqID(g)).removeClass("ui-state-highlight");b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+
-b.jgrid.jqID(d),"#"+b.jgrid.jqID(g))[a.p.useProp?"prop":"attr"]("checked",false)}});a.p.selarrrow=[]}b(a).jqGrid("setSelection",t,true,c)}}}).bind("reloadGrid",function(c,d){if(a.p.treeGrid===true)a.p.datatype=a.p.treedatatype;d&&d.current&&a.grid.selectionPreserver(a);if(a.p.datatype=="local"){b(a).jqGrid("resetSelection");a.p.data.length&&S()}else if(!a.p.treeGrid){a.p.selrow=null;if(a.p.multiselect){a.p.selarrrow=[];da(false)}a.p.savedRow=[]}a.p.scroll&&N.call(a,true,false);if(d&&d.page){var e=
-d.page;if(e>a.p.lastpage)e=a.p.lastpage;e<1&&(e=1);a.p.page=e;a.grid.bDiv.scrollTop=a.grid.prevRowHeight?(e-1)*a.grid.prevRowHeight*a.p.rowNum:0}if(a.grid.prevRowHeight&&a.p.scroll){delete a.p.lastpage;a.grid.populateVisible()}else a.grid.populate();a.p._inlinenav===true&&b(a).jqGrid("showAddEditButtons");return false}).dblclick(function(c){A=c.target;n=b(A,a.rows).closest("tr.jqgrow");if(b(n).length!==0){t=n[0].rowIndex;E=b.jgrid.getCellIndex(A);b(a).triggerHandler("jqGridDblClickRow",[b(n).attr("id"),
-t,E,c]);b.isFunction(this.p.ondblClickRow)&&a.p.ondblClickRow.call(a,b(n).attr("id"),t,E,c)}}).bind("contextmenu",function(c){A=c.target;n=b(A,a.rows).closest("tr.jqgrow");if(b(n).length!==0){a.p.multiselect||b(a).jqGrid("setSelection",n[0].id,true,c);t=n[0].rowIndex;E=b.jgrid.getCellIndex(A);b(a).triggerHandler("jqGridRightClickRow",[b(n).attr("id"),t,E,c]);b.isFunction(this.p.onRightClickRow)&&a.p.onRightClickRow.call(a,b(n).attr("id"),t,E,c)}});c.bDiv=document.createElement("div");k&&"auto"===
-(""+a.p.height).toLowerCase()&&(a.p.height="100%");b(c.bDiv).append(b('<div style="position:relative;'+(k&&8>b.browser.version?"height:0.01%;":"")+'"></div>').append("<div></div>").append(this)).addClass("ui-jqgrid-bdiv").css({height:a.p.height+(isNaN(a.p.height)?"":"px"),width:c.width+"px"}).scroll(c.scrollGrid);b("table:first",c.bDiv).css({width:a.p.tblwidth+"px"});k?(2==b("tbody",this).size()&&b("tbody:gt(0)",this).remove(),a.p.multikey&&b(c.bDiv).bind("selectstart",function(){return false})):
-a.p.multikey&&b(c.bDiv).bind("mousedown",function(){return false});D&&b(c.bDiv).hide();c.cDiv=document.createElement("div");var ia=!0===a.p.hidegrid?b("<a role='link' href='javascript:void(0)'/>").addClass("ui-jqgrid-titlebar-close HeaderButton").hover(function(){ia.addClass("ui-state-hover")},function(){ia.removeClass("ui-state-hover")}).append("<span class='ui-icon ui-icon-circle-triangle-n'></span>").css("rtl"==i?"left":"right","0px"):"";b(c.cDiv).append(ia).append("<span class='ui-jqgrid-title"+
-("rtl"==i?"-rtl":"")+"'>"+a.p.caption+"</span>").addClass("ui-jqgrid-titlebar ui-widget-header ui-corner-top ui-helper-clearfix");b(c.cDiv).insertBefore(c.hDiv);a.p.toolbar[0]&&(c.uDiv=document.createElement("div"),"top"==a.p.toolbar[1]?b(c.uDiv).insertBefore(c.hDiv):"bottom"==a.p.toolbar[1]&&b(c.uDiv).insertAfter(c.hDiv),"both"==a.p.toolbar[1]?(c.ubDiv=document.createElement("div"),b(c.uDiv).insertBefore(c.hDiv).addClass("ui-userdata ui-state-default").attr("id","t_"+this.id),b(c.ubDiv).insertAfter(c.hDiv).addClass("ui-userdata ui-state-default").attr("id",
-"tb_"+this.id),D&&b(c.ubDiv).hide()):b(c.uDiv).width(c.width).addClass("ui-userdata ui-state-default").attr("id","t_"+this.id),D&&b(c.uDiv).hide());a.p.toppager&&(a.p.toppager=b.jgrid.jqID(a.p.id)+"_toppager",c.topDiv=b("<div id='"+a.p.toppager+"'></div>")[0],a.p.toppager="#"+a.p.toppager,b(c.topDiv).insertBefore(c.hDiv).addClass("ui-state-default ui-jqgrid-toppager").width(c.width),l(a.p.toppager,"_t"));a.p.footerrow&&(c.sDiv=b("<div class='ui-jqgrid-sdiv'></div>")[0],e=b("<div class='ui-jqgrid-hbox"+
-("rtl"==i?"-rtl":"")+"'></div>"),b(c.sDiv).append(e).insertAfter(c.hDiv).width(c.width),b(e).append(R),c.footers=b(".ui-jqgrid-ftable",c.sDiv)[0].rows[0].cells,a.p.rownumbers&&(c.footers[0].className="ui-state-default jqgrid-rownum"),D&&b(c.sDiv).hide());e=null;if(a.p.caption){var pa=a.p.datatype;!0===a.p.hidegrid&&(b(".ui-jqgrid-titlebar-close",c.cDiv).click(function(d){var e=b.isFunction(a.p.onHeaderClick),f=".ui-jqgrid-bdiv, .ui-jqgrid-hdiv, .ui-jqgrid-pager, .ui-jqgrid-sdiv",g,i=this;if(a.p.toolbar[0]===
-true){a.p.toolbar[1]=="both"&&(f=f+(", #"+b(c.ubDiv).attr("id")));f=f+(", #"+b(c.uDiv).attr("id"))}g=b(f,"#gview_"+b.jgrid.jqID(a.p.id)).length;a.p.gridstate=="visible"?b(f,"#gbox_"+b.jgrid.jqID(a.p.id)).slideUp("fast",function(){g--;if(g===0){b("span",i).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-s");a.p.gridstate="hidden";b("#gbox_"+b.jgrid.jqID(a.p.id)).hasClass("ui-resizable")&&b(".ui-resizable-handle","#gbox_"+b.jgrid.jqID(a.p.id)).hide();b(a).triggerHandler("jqGridHeaderClick",
-[a.p.gridstate,d]);e&&(D||a.p.onHeaderClick.call(a,a.p.gridstate,d))}}):a.p.gridstate=="hidden"&&b(f,"#gbox_"+b.jgrid.jqID(a.p.id)).slideDown("fast",function(){g--;if(g===0){b("span",i).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-n");if(D){a.p.datatype=pa;I();D=false}a.p.gridstate="visible";b("#gbox_"+b.jgrid.jqID(a.p.id)).hasClass("ui-resizable")&&b(".ui-resizable-handle","#gbox_"+b.jgrid.jqID(a.p.id)).show();b(a).triggerHandler("jqGridHeaderClick",[a.p.gridstate,d]);
-e&&(D||a.p.onHeaderClick.call(a,a.p.gridstate,d))}});return false}),D&&(a.p.datatype="local",b(".ui-jqgrid-titlebar-close",c.cDiv).trigger("click")))}else b(c.cDiv).hide();b(c.hDiv).after(c.bDiv).mousemove(function(a){if(c.resizing){c.dragMove(a);return false}});b(".ui-jqgrid-labels",c.hDiv).bind("selectstart",function(){return false});b(document).mouseup(function(){if(c.resizing){c.dragEnd();return false}return true});a.formatCol=p;a.sortData=ja;a.updatepager=function(c,d){var e,f,g,h,i,j,k,l="",
-m=a.p.pager?"_"+b.jgrid.jqID(a.p.pager.substr(1)):"",n=a.p.toppager?"_"+a.p.toppager.substr(1):"";g=parseInt(a.p.page,10)-1;g<0&&(g=0);g=g*parseInt(a.p.rowNum,10);i=g+a.p.reccount;if(a.p.scroll){e=b("tbody:first > tr:gt(0)",a.grid.bDiv);g=i-e.length;a.p.reccount=e.length;if(f=e.outerHeight()||a.grid.prevRowHeight){e=g*f;f=parseInt(a.p.records,10)*f;b(">div:first",a.grid.bDiv).css({height:f}).children("div:first").css({height:e,display:e?"":"none"})}a.grid.bDiv.scrollLeft=a.grid.hDiv.scrollLeft}l=
-a.p.pager?a.p.pager:"";if(l=l+(a.p.toppager?l?","+a.p.toppager:a.p.toppager:"")){k=b.jgrid.formatter.integer||{};e=o(a.p.page);f=o(a.p.lastpage);b(".selbox",l)[this.p.useProp?"prop":"attr"]("disabled",false);if(a.p.pginput===true){b(".ui-pg-input",l).val(a.p.page);h=a.p.toppager?"#sp_1"+m+",#sp_1"+n:"#sp_1"+m;b(h).html(b.fmatter?b.fmatter.util.NumberFormat(a.p.lastpage,k):a.p.lastpage)}if(a.p.viewrecords)if(a.p.reccount===0)b(".ui-paging-info",l).html(a.p.emptyrecords);else{h=g+1;j=a.p.records;if(b.fmatter){h=
-b.fmatter.util.NumberFormat(h,k);i=b.fmatter.util.NumberFormat(i,k);j=b.fmatter.util.NumberFormat(j,k)}b(".ui-paging-info",l).html(b.jgrid.format(a.p.recordtext,h,i,j))}if(a.p.pgbuttons===true){e<=0&&(e=f=0);if(e==1||e===0){b("#first"+m+", #prev"+m).addClass("ui-state-disabled").removeClass("ui-state-hover");a.p.toppager&&b("#first_t"+n+", #prev_t"+n).addClass("ui-state-disabled").removeClass("ui-state-hover")}else{b("#first"+m+", #prev"+m).removeClass("ui-state-disabled");a.p.toppager&&b("#first_t"+
-n+", #prev_t"+n).removeClass("ui-state-disabled")}if(e==f||e===0){b("#next"+m+", #last"+m).addClass("ui-state-disabled").removeClass("ui-state-hover");a.p.toppager&&b("#next_t"+n+", #last_t"+n).addClass("ui-state-disabled").removeClass("ui-state-hover")}else{b("#next"+m+", #last"+m).removeClass("ui-state-disabled");a.p.toppager&&b("#next_t"+n+", #last_t"+n).removeClass("ui-state-disabled")}}}c===true&&a.p.rownumbers===true&&b("td.jqgrid-rownum",a.rows).each(function(a){b(this).html(g+1+a)});d&&a.p.jqgdnd&&
-b(a).jqGrid("gridDnD","updateDnD");b(a).triggerHandler("jqGridGridComplete");b.isFunction(a.p.gridComplete)&&a.p.gridComplete.call(a);b(a).triggerHandler("jqGridAfterGridComplete")};a.refreshIndex=S;a.setHeadCheckBox=da;a.constructTr=J;a.formatter=function(a,b,c,d,e){return u(a,b,c,d,e)};b.extend(c,{populate:I,emptyRows:N});this.grid=c;a.addXmlData=function(b){$(b,a.grid.bDiv)};a.addJSONData=function(b){aa(b,a.grid.bDiv)};this.grid.cols=this.rows[0].cells;I();a.p.hiddengrid=!1;b(window).unload(function(){a=
-null})}}}})};b.jgrid.extend({getGridParam:function(b){var e=this[0];return!e||!e.grid?void 0:b?"undefined"!=typeof e.p[b]?e.p[b]:null:e.p},setGridParam:function(f){return this.each(function(){this.grid&&"object"===typeof f&&b.extend(!0,this.p,f)})},getDataIDs:function(){var f=[],e=0,c,d=0;this.each(function(){if((c=this.rows.length)&&0<c)for(;e<c;)b(this.rows[e]).hasClass("jqgrow")&&(f[d]=this.rows[e].id,d++),e++});return f},setSelection:function(f,e,c){return this.each(function(){var d,a,h,g,i,j;
-if(void 0!==f&&(e=!1===e?!1:!0,(a=this.rows.namedItem(f+""))&&a.className&&!(-1<a.className.indexOf("ui-state-disabled"))))(!0===this.p.scrollrows&&(h=this.rows.namedItem(f).rowIndex,0<=h&&(d=b(this.grid.bDiv)[0].clientHeight,g=b(this.grid.bDiv)[0].scrollTop,i=this.rows[h].offsetTop,h=this.rows[h].clientHeight,i+h>=d+g?b(this.grid.bDiv)[0].scrollTop=i-(d+g)+h+g:i<d+g&&i<g&&(b(this.grid.bDiv)[0].scrollTop=i))),!0===this.p.frozenColumns&&(j=this.p.id+"_frozen"),this.p.multiselect)?(this.setHeadCheckBox(!1),
-this.p.selrow=a.id,g=b.inArray(this.p.selrow,this.p.selarrrow),-1===g?("ui-subgrid"!==a.className&&b(a).addClass("ui-state-highlight").attr("aria-selected","true"),d=!0,this.p.selarrrow.push(this.p.selrow)):("ui-subgrid"!==a.className&&b(a).removeClass("ui-state-highlight").attr("aria-selected","false"),d=!1,this.p.selarrrow.splice(g,1),i=this.p.selarrrow[0],this.p.selrow=void 0===i?null:i),b("#jqg_"+b.jgrid.jqID(this.p.id)+"_"+b.jgrid.jqID(a.id))[this.p.useProp?"prop":"attr"]("checked",d),j&&(-1===
-g?b("#"+b.jgrid.jqID(f),"#"+b.jgrid.jqID(j)).addClass("ui-state-highlight"):b("#"+b.jgrid.jqID(f),"#"+b.jgrid.jqID(j)).removeClass("ui-state-highlight"),b("#jqg_"+b.jgrid.jqID(this.p.id)+"_"+b.jgrid.jqID(f),"#"+b.jgrid.jqID(j))[this.p.useProp?"prop":"attr"]("checked",d)),b(this).triggerHandler("jqGridSelectRow",[a.id,d,c]),this.p.onSelectRow&&e&&this.p.onSelectRow.call(this,a.id,d,c)):"ui-subgrid"!==a.className&&(this.p.selrow!=a.id?(b(this.rows.namedItem(this.p.selrow)).removeClass("ui-state-highlight").attr({"aria-selected":"false",
-tabindex:"-1"}),b(a).addClass("ui-state-highlight").attr({"aria-selected":"true",tabindex:"0"}),j&&(b("#"+b.jgrid.jqID(this.p.selrow),"#"+b.jgrid.jqID(j)).removeClass("ui-state-highlight"),b("#"+b.jgrid.jqID(f),"#"+b.jgrid.jqID(j)).addClass("ui-state-highlight")),d=!0):d=!1,this.p.selrow=a.id,b(this).triggerHandler("jqGridSelectRow",[a.id,d,c]),this.p.onSelectRow&&e&&this.p.onSelectRow.call(this,a.id,d,c))})},resetSelection:function(f){return this.each(function(){var e=this,c,d,a;!0===e.p.frozenColumns&&
-(a=e.p.id+"_frozen");if("undefined"!==typeof f){d=f===e.p.selrow?e.p.selrow:f;b("#"+b.jgrid.jqID(e.p.id)+" tbody:first tr#"+b.jgrid.jqID(d)).removeClass("ui-state-highlight").attr("aria-selected","false");a&&b("#"+b.jgrid.jqID(d),"#"+b.jgrid.jqID(a)).removeClass("ui-state-highlight");if(e.p.multiselect){b("#jqg_"+b.jgrid.jqID(e.p.id)+"_"+b.jgrid.jqID(d),"#"+b.jgrid.jqID(e.p.id))[e.p.useProp?"prop":"attr"]("checked",!1);if(a)b("#jqg_"+b.jgrid.jqID(e.p.id)+"_"+b.jgrid.jqID(d),"#"+b.jgrid.jqID(a))[e.p.useProp?
-"prop":"attr"]("checked",!1);e.setHeadCheckBox(!1)}d=null}else e.p.multiselect?(b(e.p.selarrrow).each(function(d,f){c=e.rows.namedItem(f);b(c).removeClass("ui-state-highlight").attr("aria-selected","false");b("#jqg_"+b.jgrid.jqID(e.p.id)+"_"+b.jgrid.jqID(f))[e.p.useProp?"prop":"attr"]("checked",!1);a&&(b("#"+b.jgrid.jqID(f),"#"+b.jgrid.jqID(a)).removeClass("ui-state-highlight"),b("#jqg_"+b.jgrid.jqID(e.p.id)+"_"+b.jgrid.jqID(f),"#"+b.jgrid.jqID(a))[e.p.useProp?"prop":"attr"]("checked",!1))}),e.setHeadCheckBox(!1),
-e.p.selarrrow=[]):e.p.selrow&&(b("#"+b.jgrid.jqID(e.p.id)+" tbody:first tr#"+b.jgrid.jqID(e.p.selrow)).removeClass("ui-state-highlight").attr("aria-selected","false"),a&&b("#"+b.jgrid.jqID(e.p.selrow),"#"+b.jgrid.jqID(a)).removeClass("ui-state-highlight"),e.p.selrow=null);!0===e.p.cellEdit&&0<=parseInt(e.p.iCol,10)&&0<=parseInt(e.p.iRow,10)&&(b("td:eq("+e.p.iCol+")",e.rows[e.p.iRow]).removeClass("edit-cell ui-state-highlight"),b(e.rows[e.p.iRow]).removeClass("selected-row ui-state-hover"));e.p.savedRow=
-[]})},getRowData:function(f){var e={},c,d=!1,a,h=0;this.each(function(){var g=this,i,j;if("undefined"==typeof f)d=!0,c=[],a=g.rows.length;else{j=g.rows.namedItem(f);if(!j)return e;a=2}for(;h<a;)d&&(j=g.rows[h]),b(j).hasClass("jqgrow")&&(b('td[role="gridcell"]',j).each(function(a){i=g.p.colModel[a].name;if("cb"!==i&&"subgrid"!==i&&"rn"!==i)if(!0===g.p.treeGrid&&i==g.p.ExpandColumn)e[i]=b.jgrid.htmlDecode(b("span:first",this).html());else try{e[i]=b.unformat.call(g,this,{rowId:j.id,colModel:g.p.colModel[a]},
-a)}catch(c){e[i]=b.jgrid.htmlDecode(b(this).html())}}),d&&(c.push(e),e={})),h++});return c?c:e},delRowData:function(f){var e=!1,c,d;this.each(function(){if(c=this.rows.namedItem(f)){if(b(c).remove(),this.p.records--,this.p.reccount--,this.updatepager(!0,!1),e=!0,this.p.multiselect&&(d=b.inArray(f,this.p.selarrrow),-1!=d&&this.p.selarrrow.splice(d,1)),f==this.p.selrow)this.p.selrow=null}else return!1;if("local"==this.p.datatype){var a=this.p._index[b.jgrid.stripPref(this.p.idPrefix,f)];"undefined"!=
-typeof a&&(this.p.data.splice(a,1),this.refreshIndex())}if(!0===this.p.altRows&&e){var h=this.p.altclass;b(this.rows).each(function(a){1==a%2?b(this).addClass(h):b(this).removeClass(h)})}});return e},setRowData:function(f,e,c){var d,a=!0,h;this.each(function(){if(!this.grid)return!1;var g=this,i,j,l=typeof c,k={};j=g.rows.namedItem(f);if(!j)return!1;if(e)try{if(b(this.p.colModel).each(function(a){d=this.name;void 0!==e[d]&&(k[d]=this.formatter&&"string"===typeof this.formatter&&"date"==this.formatter?
-b.unformat.date.call(g,e[d],this):e[d],i=g.formatter(f,e[d],a,e,"edit"),h=this.title?{title:b.jgrid.stripHtml(i)}:{},!0===g.p.treeGrid&&d==g.p.ExpandColumn?b("td:eq("+a+") > span:first",j).html(i).attr(h):b("td:eq("+a+")",j).html(i).attr(h))}),"local"==g.p.datatype){var m=b.jgrid.stripPref(g.p.idPrefix,f),o=g.p._index[m];if(g.p.treeGrid)for(var p in g.p.treeReader)k.hasOwnProperty(g.p.treeReader[p])&&delete k[g.p.treeReader[p]];"undefined"!=typeof o&&(g.p.data[o]=b.extend(!0,g.p.data[o],k));k=null}}catch(v){a=
-!1}a&&("string"===l?b(j).addClass(c):"object"===l&&b(j).css(c),b(g).triggerHandler("jqGridAfterGridComplete"))});return a},addRowData:function(f,e,c,d){c||(c="last");var a=!1,h,g,i,j,l,k,m,o,p="",v,u,M,F,Z,U;e&&(b.isArray(e)?(v=!0,c="last",u=f):(e=[e],v=!1),this.each(function(){var V=e.length;l=this.p.rownumbers===true?1:0;i=this.p.multiselect===true?1:0;j=this.p.subGrid===true?1:0;if(!v)if(typeof f!="undefined")f=f+"";else{f=b.jgrid.randId();if(this.p.keyIndex!==false){u=this.p.colModel[this.p.keyIndex+
-i+j+l].name;typeof e[0][u]!="undefined"&&(f=e[0][u])}}M=this.p.altclass;for(var N=0,S="",J={},$=b.isFunction(this.p.afterInsertRow)?true:false;N<V;){F=e[N];g=[];if(v){try{f=F[u]}catch(aa){f=b.jgrid.randId()}S=this.p.altRows===true?(this.rows.length-1)%2===0?M:"":""}U=f;f=this.p.idPrefix+f;if(l){p=this.formatCol(0,1,"",null,f,true);g[g.length]='<td role="gridcell" class="ui-state-default jqgrid-rownum" '+p+">0</td>"}if(i){o='<input role="checkbox" type="checkbox" id="jqg_'+this.p.id+"_"+f+'" class="cbox"/>';
-p=this.formatCol(l,1,"",null,f,true);g[g.length]='<td role="gridcell" '+p+">"+o+"</td>"}j&&(g[g.length]=b(this).jqGrid("addSubGridCell",i+l,1));for(m=i+j+l;m<this.p.colModel.length;m++){Z=this.p.colModel[m];h=Z.name;J[h]=F[h];o=this.formatter(f,b.jgrid.getAccessor(F,h),m,F);p=this.formatCol(m,1,o,F,f,true);g[g.length]='<td role="gridcell" '+p+">"+o+"</td>"}g.unshift(this.constructTr(f,false,S,J,J));g[g.length]="</tr>";if(this.rows.length===0)b("table:first",this.grid.bDiv).append(g.join(""));else switch(c){case "last":b(this.rows[this.rows.length-
-1]).after(g.join(""));k=this.rows.length-1;break;case "first":b(this.rows[0]).after(g.join(""));k=1;break;case "after":(k=this.rows.namedItem(d))&&(b(this.rows[k.rowIndex+1]).hasClass("ui-subgrid")?b(this.rows[k.rowIndex+1]).after(g):b(k).after(g.join("")));k++;break;case "before":if(k=this.rows.namedItem(d)){b(k).before(g.join(""));k=k.rowIndex}k--}this.p.subGrid===true&&b(this).jqGrid("addSubGrid",i+l,k);this.p.records++;this.p.reccount++;b(this).triggerHandler("jqGridAfterInsertRow",[f,F,F]);$&&
-this.p.afterInsertRow.call(this,f,F,F);N++;if(this.p.datatype=="local"){J[this.p.localReader.id]=U;this.p._index[U]=this.p.data.length;this.p.data.push(J);J={}}}this.p.altRows===true&&!v&&(c=="last"?(this.rows.length-1)%2==1&&b(this.rows[this.rows.length-1]).addClass(M):b(this.rows).each(function(a){a%2==1?b(this).addClass(M):b(this).removeClass(M)}));this.updatepager(true,true);a=true}));return a},footerData:function(f,e,c){function d(a){for(var b in a)if(a.hasOwnProperty(b))return!1;return!0}var a,
-h=!1,g={},i;"undefined"==typeof f&&(f="get");"boolean"!=typeof c&&(c=!0);f=f.toLowerCase();this.each(function(){var j=this,l;if(!j.grid||!j.p.footerrow||"set"==f&&d(e))return!1;h=!0;b(this.p.colModel).each(function(d){a=this.name;"set"==f?void 0!==e[a]&&(l=c?j.formatter("",e[a],d,e,"edit"):e[a],i=this.title?{title:b.jgrid.stripHtml(l)}:{},b("tr.footrow td:eq("+d+")",j.grid.sDiv).html(l).attr(i),h=!0):"get"==f&&(g[a]=b("tr.footrow td:eq("+d+")",j.grid.sDiv).html())})});return"get"==f?g:h},showHideCol:function(f,
-e){return this.each(function(){var c=this,d=!1,a=b.jgrid.cellWidth()?0:c.p.cellLayout,h;if(c.grid){"string"===typeof f&&(f=[f]);e="none"!=e?"":"none";var g=""===e?!0:!1,i=c.p.groupHeader&&("object"===typeof c.p.groupHeader||b.isFunction(c.p.groupHeader));i&&b(c).jqGrid("destroyGroupHeader",!1);b(this.p.colModel).each(function(i){if(-1!==b.inArray(this.name,f)&&this.hidden===g){if(!0===c.p.frozenColumns&&!0===this.frozen)return!0;b("tr",c.grid.hDiv).each(function(){b(this.cells[i]).css("display",e)});
-b(c.rows).each(function(){b(this).hasClass("jqgroup")||b(this.cells[i]).css("display",e)});c.p.footerrow&&b("tr.footrow td:eq("+i+")",c.grid.sDiv).css("display",e);h=parseInt(this.width,10);c.p.tblwidth="none"===e?c.p.tblwidth-(h+a):c.p.tblwidth+(h+a);this.hidden=!g;d=!0;b(c).triggerHandler("jqGridShowHideCol",[g,this.name,i])}});!0===d&&(!0===c.p.shrinkToFit&&!isNaN(c.p.height)&&(c.p.tblwidth+=parseInt(c.p.scrollOffset,10)),b(c).jqGrid("setGridWidth",!0===c.p.shrinkToFit?c.p.tblwidth:c.p.width));
-i&&b(c).jqGrid("setGroupHeaders",c.p.groupHeader)}})},hideCol:function(f){return this.each(function(){b(this).jqGrid("showHideCol",f,"none")})},showCol:function(f){return this.each(function(){b(this).jqGrid("showHideCol",f,"")})},remapColumns:function(f,e,c){function d(a){var c;c=a.length?b.makeArray(a):b.extend({},a);b.each(f,function(b){a[b]=c[this]})}function a(a,c){b(">tr"+(c||""),a).each(function(){var a=this,c=b.makeArray(a.cells);b.each(f,function(){var b=c[this];b&&a.appendChild(b)})})}var h=
-this.get(0);d(h.p.colModel);d(h.p.colNames);d(h.grid.headers);a(b("thead:first",h.grid.hDiv),c&&":not(.ui-jqgrid-labels)");e&&a(b("#"+b.jgrid.jqID(h.p.id)+" tbody:first"),".jqgfirstrow, tr.jqgrow, tr.jqfoot");h.p.footerrow&&a(b("tbody:first",h.grid.sDiv));h.p.remapColumns&&(h.p.remapColumns.length?d(h.p.remapColumns):h.p.remapColumns=b.makeArray(f));h.p.lastsort=b.inArray(h.p.lastsort,f);h.p.treeGrid&&(h.p.expColInd=b.inArray(h.p.expColInd,f));b(h).triggerHandler("jqGridRemapColumns",[f,e,c])},setGridWidth:function(f,
-e){return this.each(function(){if(this.grid){var c=this,d,a=0,h=b.jgrid.cellWidth()?0:c.p.cellLayout,g,i=0,j=!1,l=c.p.scrollOffset,k,m=0,o=0,p;"boolean"!=typeof e&&(e=c.p.shrinkToFit);if(!isNaN(f)){f=parseInt(f,10);c.grid.width=c.p.width=f;b("#gbox_"+b.jgrid.jqID(c.p.id)).css("width",f+"px");b("#gview_"+b.jgrid.jqID(c.p.id)).css("width",f+"px");b(c.grid.bDiv).css("width",f+"px");b(c.grid.hDiv).css("width",f+"px");c.p.pager&&b(c.p.pager).css("width",f+"px");c.p.toppager&&b(c.p.toppager).css("width",
-f+"px");!0===c.p.toolbar[0]&&(b(c.grid.uDiv).css("width",f+"px"),"both"==c.p.toolbar[1]&&b(c.grid.ubDiv).css("width",f+"px"));c.p.footerrow&&b(c.grid.sDiv).css("width",f+"px");!1===e&&!0===c.p.forceFit&&(c.p.forceFit=!1);if(!0===e){b.each(c.p.colModel,function(){if(this.hidden===false){d=this.widthOrg;a=a+(d+h);this.fixed?m=m+(d+h):i++;o++}});if(0===i)return;c.p.tblwidth=a;k=f-h*i-m;if(!isNaN(c.p.height)&&(b(c.grid.bDiv)[0].clientHeight<b(c.grid.bDiv)[0].scrollHeight||1===c.rows.length))j=!0,k-=l;
-var a=0,v=0<c.grid.cols.length;b.each(c.p.colModel,function(b){if(this.hidden===false&&!this.fixed){d=this.widthOrg;d=Math.round(k*d/(c.p.tblwidth-h*i-m));if(!(d<0)){this.width=d;a=a+d;c.grid.headers[b].width=d;c.grid.headers[b].el.style.width=d+"px";if(c.p.footerrow)c.grid.footers[b].style.width=d+"px";if(v)c.grid.cols[b].style.width=d+"px";g=b}}});if(!g)return;p=0;j?f-m-(a+h*i)!==l&&(p=f-m-(a+h*i)-l):1!==Math.abs(f-m-(a+h*i))&&(p=f-m-(a+h*i));c.p.colModel[g].width+=p;c.p.tblwidth=a+p+h*i+m;c.p.tblwidth>
-f?(j=c.p.tblwidth-parseInt(f,10),c.p.tblwidth=f,d=c.p.colModel[g].width-=j):d=c.p.colModel[g].width;c.grid.headers[g].width=d;c.grid.headers[g].el.style.width=d+"px";v&&(c.grid.cols[g].style.width=d+"px");c.p.footerrow&&(c.grid.footers[g].style.width=d+"px")}c.p.tblwidth&&(b("table:first",c.grid.bDiv).css("width",c.p.tblwidth+"px"),b("table:first",c.grid.hDiv).css("width",c.p.tblwidth+"px"),c.grid.hDiv.scrollLeft=c.grid.bDiv.scrollLeft,c.p.footerrow&&b("table:first",c.grid.sDiv).css("width",c.p.tblwidth+
-"px"))}}})},setGridHeight:function(f){return this.each(function(){if(this.grid){var e=b(this.grid.bDiv);e.css({height:f+(isNaN(f)?"":"px")});!0===this.p.frozenColumns&&b("#"+b.jgrid.jqID(this.p.id)+"_frozen").parent().height(e.height()-16);this.p.height=f;this.p.scroll&&this.grid.populateVisible()}})},setCaption:function(f){return this.each(function(){this.p.caption=f;b("span.ui-jqgrid-title, span.ui-jqgrid-title-rtl",this.grid.cDiv).html(f);b(this.grid.cDiv).show()})},setLabel:function(f,e,c,d){return this.each(function(){var a=
--1;if(this.grid&&"undefined"!=typeof f&&(b(this.p.colModel).each(function(b){if(this.name==f)return a=b,!1}),0<=a)){var h=b("tr.ui-jqgrid-labels th:eq("+a+")",this.grid.hDiv);if(e){var g=b(".s-ico",h);b("[id^=jqgh_]",h).empty().html(e).append(g);this.p.colNames[a]=e}c&&("string"===typeof c?b(h).addClass(c):b(h).css(c));"object"===typeof d&&b(h).attr(d)}})},setCell:function(f,e,c,d,a,h){return this.each(function(){var g=-1,i,j;if(this.grid&&(isNaN(e)?b(this.p.colModel).each(function(a){if(this.name==
-e)return g=a,!1}):g=parseInt(e,10),0<=g&&(i=this.rows.namedItem(f)))){var l=b("td:eq("+g+")",i);if(""!==c||!0===h)i=this.formatter(f,c,g,i,"edit"),j=this.p.colModel[g].title?{title:b.jgrid.stripHtml(i)}:{},this.p.treeGrid&&0<b(".tree-wrap",b(l)).length?b("span",b(l)).html(i).attr(j):b(l).html(i).attr(j),"local"==this.p.datatype&&(i=this.p.colModel[g],c=i.formatter&&"string"===typeof i.formatter&&"date"==i.formatter?b.unformat.date.call(this,c,i):c,j=this.p._index[f],"undefined"!=typeof j&&(this.p.data[j][i.name]=
-c));"string"===typeof d?b(l).addClass(d):d&&b(l).css(d);"object"===typeof a&&b(l).attr(a)}})},getCell:function(f,e){var c=!1;this.each(function(){var d=-1;if(this.grid&&(isNaN(e)?b(this.p.colModel).each(function(a){if(this.name===e)return d=a,!1}):d=parseInt(e,10),0<=d)){var a=this.rows.namedItem(f);if(a)try{c=b.unformat.call(this,b("td:eq("+d+")",a),{rowId:a.id,colModel:this.p.colModel[d]},d)}catch(h){c=b.jgrid.htmlDecode(b("td:eq("+d+")",a).html())}}});return c},getCol:function(f,e,c){var d=[],
-a,h=0,g,i,j,e="boolean"!=typeof e?!1:e;"undefined"==typeof c&&(c=!1);this.each(function(){var l=-1;if(this.grid&&(isNaN(f)?b(this.p.colModel).each(function(a){if(this.name===f)return l=a,!1}):l=parseInt(f,10),0<=l)){var k=this.rows.length,m=0;if(k&&0<k){for(;m<k;){if(b(this.rows[m]).hasClass("jqgrow")){try{a=b.unformat.call(this,b(this.rows[m].cells[l]),{rowId:this.rows[m].id,colModel:this.p.colModel[l]},l)}catch(o){a=b.jgrid.htmlDecode(this.rows[m].cells[l].innerHTML)}c?(j=parseFloat(a),h+=j,0===
-m?i=g=j:(g=Math.min(g,j),i=Math.max(i,j))):e?d.push({id:this.rows[m].id,value:a}):d.push(a)}m++}if(c)switch(c.toLowerCase()){case "sum":d=h;break;case "avg":d=h/k;break;case "count":d=k;break;case "min":d=g;break;case "max":d=i}}}});return d},clearGridData:function(f){return this.each(function(){if(this.grid){"boolean"!=typeof f&&(f=!1);if(this.p.deepempty)b("#"+b.jgrid.jqID(this.p.id)+" tbody:first tr:gt(0)").remove();else{var e=b("#"+b.jgrid.jqID(this.p.id)+" tbody:first tr:first")[0];b("#"+b.jgrid.jqID(this.p.id)+
-" tbody:first").empty().append(e)}this.p.footerrow&&f&&b(".ui-jqgrid-ftable td",this.grid.sDiv).html("&#160;");this.p.selrow=null;this.p.selarrrow=[];this.p.savedRow=[];this.p.records=0;this.p.page=1;this.p.lastpage=0;this.p.reccount=0;this.p.data=[];this.p._index={};this.updatepager(!0,!1)}})},getInd:function(b,e){var c=!1,d;this.each(function(){(d=this.rows.namedItem(b))&&(c=!0===e?d:d.rowIndex)});return c},bindKeys:function(f){var e=b.extend({onEnter:null,onSpace:null,onLeftKey:null,onRightKey:null,
-scrollingRows:!0},f||{});return this.each(function(){var c=this;b("body").is("[role]")||b("body").attr("role","application");c.p.scrollrows=e.scrollingRows;b(c).keydown(function(d){var a=b(c).find("tr[tabindex=0]")[0],f,g,i,j=c.p.treeReader.expanded_field;if(a)if(i=c.p._index[a.id],37===d.keyCode||38===d.keyCode||39===d.keyCode||40===d.keyCode){if(38===d.keyCode){g=a.previousSibling;f="";if(g)if(b(g).is(":hidden"))for(;g;){if(g=g.previousSibling,!b(g).is(":hidden")&&b(g).hasClass("jqgrow")){f=g.id;
-break}}else f=g.id;b(c).jqGrid("setSelection",f,!0,d)}if(40===d.keyCode){g=a.nextSibling;f="";if(g)if(b(g).is(":hidden"))for(;g;){if(g=g.nextSibling,!b(g).is(":hidden")&&b(g).hasClass("jqgrow")){f=g.id;break}}else f=g.id;b(c).jqGrid("setSelection",f,!0,d)}37===d.keyCode&&(c.p.treeGrid&&c.p.data[i][j]&&b(a).find("div.treeclick").trigger("click"),b(c).triggerHandler("jqGridKeyLeft",[c.p.selrow]),b.isFunction(e.onLeftKey)&&e.onLeftKey.call(c,c.p.selrow));39===d.keyCode&&(c.p.treeGrid&&!c.p.data[i][j]&&
-b(a).find("div.treeclick").trigger("click"),b(c).triggerHandler("jqGridKeyRight",[c.p.selrow]),b.isFunction(e.onRightKey)&&e.onRightKey.call(c,c.p.selrow))}else 13===d.keyCode?(b(c).triggerHandler("jqGridKeyEnter",[c.p.selrow]),b.isFunction(e.onEnter)&&e.onEnter.call(c,c.p.selrow)):32===d.keyCode&&(b(c).triggerHandler("jqGridKeySpace",[c.p.selrow]),b.isFunction(e.onSpace)&&e.onSpace.call(c,c.p.selrow))})})},unbindKeys:function(){return this.each(function(){b(this).unbind("keydown")})},getLocalRow:function(b){var e=
-!1,c;this.each(function(){"undefined"!==typeof b&&(c=this.p._index[b],0<=c&&(e=this.p.data[c]))});return e}})})(jQuery);
-(function(a){a.extend(a.jgrid,{showModal:function(a){a.w.show()},closeModal:function(a){a.w.hide().attr("aria-hidden","true");a.o&&a.o.remove()},hideModal:function(d,b){b=a.extend({jqm:!0,gb:""},b||{});if(b.onClose){var c=b.onClose(d);if("boolean"==typeof c&&!c)return}if(a.fn.jqm&&!0===b.jqm)a(d).attr("aria-hidden","true").jqmHide();else{if(""!==b.gb)try{a(".jqgrid-overlay:first",b.gb).hide()}catch(f){}a(d).hide().attr("aria-hidden","true")}},findPos:function(a){var b=0,c=0;if(a.offsetParent){do b+=
-a.offsetLeft,c+=a.offsetTop;while(a=a.offsetParent)}return[b,c]},createModal:function(d,b,c,f,g,h,i){var e=document.createElement("div"),l,j=this,i=a.extend({},i||{});l="rtl"==a(c.gbox).attr("dir")?!0:!1;e.className="ui-widget ui-widget-content ui-corner-all ui-jqdialog";e.id=d.themodal;var k=document.createElement("div");k.className="ui-jqdialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix";k.id=d.modalhead;a(k).append("<span class='ui-jqdialog-title'>"+c.caption+"</span>");var n=a("<a href='javascript:void(0)' class='ui-jqdialog-titlebar-close ui-corner-all'></a>").hover(function(){n.addClass("ui-state-hover")},
-function(){n.removeClass("ui-state-hover")}).append("<span class='ui-icon ui-icon-closethick'></span>");a(k).append(n);l?(e.dir="rtl",a(".ui-jqdialog-title",k).css("float","right"),a(".ui-jqdialog-titlebar-close",k).css("left","0.3em")):(e.dir="ltr",a(".ui-jqdialog-title",k).css("float","left"),a(".ui-jqdialog-titlebar-close",k).css("right","0.3em"));var m=document.createElement("div");a(m).addClass("ui-jqdialog-content ui-widget-content").attr("id",d.modalcontent);a(m).append(b);e.appendChild(m);
-a(e).prepend(k);!0===h?a("body").append(e):"string"==typeof h?a(h).append(e):a(e).insertBefore(f);a(e).css(i);"undefined"===typeof c.jqModal&&(c.jqModal=!0);b={};if(a.fn.jqm&&!0===c.jqModal)0===c.left&&(0===c.top&&c.overlay)&&(i=[],i=a.jgrid.findPos(g),c.left=i[0]+4,c.top=i[1]+4),b.top=c.top+"px",b.left=c.left;else if(0!==c.left||0!==c.top)b.left=c.left,b.top=c.top+"px";a("a.ui-jqdialog-titlebar-close",k).click(function(){var b=a("#"+a.jgrid.jqID(d.themodal)).data("onClose")||c.onClose,e=a("#"+a.jgrid.jqID(d.themodal)).data("gbox")||
-c.gbox;j.hideModal("#"+a.jgrid.jqID(d.themodal),{gb:e,jqm:c.jqModal,onClose:b});return false});if(0===c.width||!c.width)c.width=300;if(0===c.height||!c.height)c.height=200;c.zIndex||(f=a(f).parents("*[role=dialog]").filter(":first").css("z-index"),c.zIndex=f?parseInt(f,10)+2:950);f=0;l&&(b.left&&!h)&&(f=a(c.gbox).width()-(!isNaN(c.width)?parseInt(c.width,10):0)-8,b.left=parseInt(b.left,10)+parseInt(f,10));b.left&&(b.left+="px");a(e).css(a.extend({width:isNaN(c.width)?"auto":c.width+"px",height:isNaN(c.height)?
-"auto":c.height+"px",zIndex:c.zIndex,overflow:"hidden"},b)).attr({tabIndex:"-1",role:"dialog","aria-labelledby":d.modalhead,"aria-hidden":"true"});"undefined"==typeof c.drag&&(c.drag=!0);"undefined"==typeof c.resize&&(c.resize=!0);if(c.drag)if(a(k).css("cursor","move"),a.fn.jqDrag)a(e).jqDrag(k);else try{a(e).draggable({handle:a("#"+a.jgrid.jqID(k.id))})}catch(o){}if(c.resize)if(a.fn.jqResize)a(e).append("<div class='jqResize ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se ui-icon-grip-diagonal-se'></div>"),
-a("#"+a.jgrid.jqID(d.themodal)).jqResize(".jqResize",d.scrollelm?"#"+a.jgrid.jqID(d.scrollelm):!1);else try{a(e).resizable({handles:"se, sw",alsoResize:d.scrollelm?"#"+a.jgrid.jqID(d.scrollelm):!1})}catch(p){}!0===c.closeOnEscape&&a(e).keydown(function(b){if(b.which==27){b=a("#"+a.jgrid.jqID(d.themodal)).data("onClose")||c.onClose;j.hideModal(this,{gb:c.gbox,jqm:c.jqModal,onClose:b})}})},viewModal:function(d,b){b=a.extend({toTop:!0,overlay:10,modal:!1,overlayClass:"ui-widget-overlay",onShow:a.jgrid.showModal,
-onHide:a.jgrid.closeModal,gbox:"",jqm:!0,jqM:!0},b||{});if(a.fn.jqm&&!0===b.jqm)b.jqM?a(d).attr("aria-hidden","false").jqm(b).jqmShow():a(d).attr("aria-hidden","false").jqmShow();else{""!==b.gbox&&(a(".jqgrid-overlay:first",b.gbox).show(),a(d).data("gbox",b.gbox));a(d).show().attr("aria-hidden","false");try{a(":input:visible",d)[0].focus()}catch(c){}}},info_dialog:function(d,b,c,f){var g={width:290,height:"auto",dataheight:"auto",drag:!0,resize:!1,caption:"<b>"+d+"</b>",left:250,top:170,zIndex:1E3,
-jqModal:!0,modal:!1,closeOnEscape:!0,align:"center",buttonalign:"center",buttons:[]};a.extend(g,f||{});var h=g.jqModal,i=this;a.fn.jqm&&!h&&(h=!1);d="";if(0<g.buttons.length)for(f=0;f<g.buttons.length;f++)"undefined"==typeof g.buttons[f].id&&(g.buttons[f].id="info_button_"+f),d+="<a href='javascript:void(0)' id='"+g.buttons[f].id+"' class='fm-button ui-state-default ui-corner-all'>"+g.buttons[f].text+"</a>";f=isNaN(g.dataheight)?g.dataheight:g.dataheight+"px";b="<div id='info_id'>"+("<div id='infocnt' style='margin:0px;padding-bottom:1em;width:100%;overflow:auto;position:relative;height:"+
-f+";"+("text-align:"+g.align+";")+"'>"+b+"</div>");b+=c?"<div class='ui-widget-content ui-helper-clearfix' style='text-align:"+g.buttonalign+";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'><a href='javascript:void(0)' id='closedialog' class='fm-button ui-state-default ui-corner-all'>"+c+"</a>"+d+"</div>":""!==d?"<div class='ui-widget-content ui-helper-clearfix' style='text-align:"+g.buttonalign+";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'>"+
-d+"</div>":"";b+="</div>";try{"false"==a("#info_dialog").attr("aria-hidden")&&a.jgrid.hideModal("#info_dialog",{jqm:h}),a("#info_dialog").remove()}catch(e){}a.jgrid.createModal({themodal:"info_dialog",modalhead:"info_head",modalcontent:"info_content",scrollelm:"infocnt"},b,g,"","",!0);d&&a.each(g.buttons,function(b){a("#"+a.jgrid.jqID(this.id),"#info_id").bind("click",function(){g.buttons[b].onClick.call(a("#info_dialog"));return!1})});a("#closedialog","#info_id").click(function(){i.hideModal("#info_dialog",
-{jqm:h});return!1});a(".fm-button","#info_dialog").hover(function(){a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")});a.isFunction(g.beforeOpen)&&g.beforeOpen();a.jgrid.viewModal("#info_dialog",{onHide:function(a){a.w.hide().remove();a.o&&a.o.remove()},modal:g.modal,jqm:h});a.isFunction(g.afterOpen)&&g.afterOpen();try{a("#info_dialog").focus()}catch(l){}},createEl:function(d,b,c,f,g){function h(b,d){a.isFunction(d.dataInit)&&d.dataInit.call(l,b);d.dataEvents&&
-a.each(d.dataEvents,function(){void 0!==this.data?a(b).bind(this.type,this.data,this.fn):a(b).bind(this.type,this.fn)});return d}function i(b,d,c){var e="dataInit dataEvents dataUrl buildSelect sopt searchhidden defaultValue attr".split(" ");"undefined"!=typeof c&&a.isArray(c)&&a.merge(e,c);a.each(d,function(d,c){-1===a.inArray(d,e)&&a(b).attr(d,c)});d.hasOwnProperty("id")||a(b).attr("id",a.jgrid.randId())}var e="",l=this;switch(d){case "textarea":e=document.createElement("textarea");f?b.cols||a(e).css({width:"98%"}):
-b.cols||(b.cols=20);b.rows||(b.rows=2);if("&nbsp;"==c||"&#160;"==c||1==c.length&&160==c.charCodeAt(0))c="";e.value=c;i(e,b);b=h(e,b);a(e).attr({role:"textbox",multiline:"true"});break;case "checkbox":e=document.createElement("input");e.type="checkbox";b.value?(d=b.value.split(":"),c===d[0]&&(e.checked=!0,e.defaultChecked=!0),e.value=d[0],a(e).attr("offval",d[1])):(d=c.toLowerCase(),0>d.search(/(false|0|no|off|undefined)/i)&&""!==d?(e.checked=!0,e.defaultChecked=!0,e.value=c):e.value="on",a(e).attr("offval",
-"off"));i(e,b,["value"]);b=h(e,b);a(e).attr("role","checkbox");break;case "select":e=document.createElement("select");e.setAttribute("role","select");f=[];!0===b.multiple?(d=!0,e.multiple="multiple",a(e).attr("aria-multiselectable","true")):d=!1;if("undefined"!=typeof b.dataUrl)a.ajax(a.extend({url:b.dataUrl,type:"GET",dataType:"html",context:{elem:e,options:b,vl:c},success:function(d){var b=[],c=this.elem,e=this.vl,f=a.extend({},this.options),g=f.multiple===true;a.isFunction(f.buildSelect)&&(d=f.buildSelect.call(l,
-d));if(d=a(d).html()){a(c).append(d);i(c,f);f=h(c,f);if(typeof f.size==="undefined")f.size=g?3:1;if(g){b=e.split(",");b=a.map(b,function(b){return a.trim(b)})}else b[0]=a.trim(e);setTimeout(function(){a("option",c).each(function(d){if(d===0&&c.multiple)this.selected=false;a(this).attr("role","option");if(a.inArray(a.trim(a(this).text()),b)>-1||a.inArray(a.trim(a(this).val()),b)>-1)this.selected="selected"})},0)}}},g||{}));else if(b.value){var j;"undefined"===typeof b.size&&(b.size=d?3:1);d&&(f=c.split(","),
-f=a.map(f,function(b){return a.trim(b)}));"function"===typeof b.value&&(b.value=b.value());var k,n,m=void 0===b.separator?":":b.separator,g=void 0===b.delimiter?";":b.delimiter;if("string"===typeof b.value){k=b.value.split(g);for(j=0;j<k.length;j++){n=k[j].split(m);2<n.length&&(n[1]=a.map(n,function(a,b){if(b>0)return a}).join(m));g=document.createElement("option");g.setAttribute("role","option");g.value=n[0];g.innerHTML=n[1];e.appendChild(g);if(!d&&(a.trim(n[0])==a.trim(c)||a.trim(n[1])==a.trim(c)))g.selected=
-"selected";if(d&&(-1<a.inArray(a.trim(n[1]),f)||-1<a.inArray(a.trim(n[0]),f)))g.selected="selected"}}else if("object"===typeof b.value)for(j in m=b.value,m)if(m.hasOwnProperty(j)){g=document.createElement("option");g.setAttribute("role","option");g.value=j;g.innerHTML=m[j];e.appendChild(g);if(!d&&(a.trim(j)==a.trim(c)||a.trim(m[j])==a.trim(c)))g.selected="selected";if(d&&(-1<a.inArray(a.trim(m[j]),f)||-1<a.inArray(a.trim(j),f)))g.selected="selected"}i(e,b,["value"]);b=h(e,b)}break;case "text":case "password":case "button":j=
-"button"==d?"button":"textbox";e=document.createElement("input");e.type=d;e.value=c;i(e,b);b=h(e,b);"button"!=d&&(f?b.size||a(e).css({width:"98%"}):b.size||(b.size=20));a(e).attr("role",j);break;case "image":case "file":e=document.createElement("input");e.type=d;i(e,b);b=h(e,b);break;case "custom":e=document.createElement("span");try{if(a.isFunction(b.custom_element))if(m=b.custom_element.call(l,c,b))m=a(m).addClass("customelement").attr({id:b.id,name:b.name}),a(e).empty().append(m);else throw"e2";
-else throw"e1";}catch(o){"e1"==o&&a.jgrid.info_dialog(a.jgrid.errors.errcap,"function 'custom_element' "+a.jgrid.edit.msg.nodefined,a.jgrid.edit.bClose),"e2"==o?a.jgrid.info_dialog(a.jgrid.errors.errcap,"function 'custom_element' "+a.jgrid.edit.msg.novalue,a.jgrid.edit.bClose):a.jgrid.info_dialog(a.jgrid.errors.errcap,"string"===typeof o?o:o.message,a.jgrid.edit.bClose)}}return e},checkDate:function(a,b){var c={},f,a=a.toLowerCase();f=-1!=a.indexOf("/")?"/":-1!=a.indexOf("-")?"-":-1!=a.indexOf(".")?
-".":"/";a=a.split(f);b=b.split(f);if(3!=b.length)return!1;f=-1;for(var g,h=-1,i=-1,e=0;e<a.length;e++)g=isNaN(b[e])?0:parseInt(b[e],10),c[a[e]]=g,g=a[e],-1!=g.indexOf("y")&&(f=e),-1!=g.indexOf("m")&&(i=e),-1!=g.indexOf("d")&&(h=e);g="y"==a[f]||"yyyy"==a[f]?4:"yy"==a[f]?2:-1;var e=function(a){for(var b=1;b<=a;b++){this[b]=31;if(4==b||6==b||9==b||11==b)this[b]=30;2==b&&(this[b]=29)}return this}(12),l;if(-1===f)return!1;l=c[a[f]].toString();2==g&&1==l.length&&(g=1);if(l.length!=g||0===c[a[f]]&&"00"!=
-b[f]||-1===i)return!1;l=c[a[i]].toString();if(1>l.length||(1>c[a[i]]||12<c[a[i]])||-1===h)return!1;l=c[a[h]].toString();return 1>l.length||1>c[a[h]]||31<c[a[h]]||2==c[a[i]]&&c[a[h]]>(0===c[a[f]]%4&&(0!==c[a[f]]%100||0===c[a[f]]%400)?29:28)||c[a[h]]>e[c[a[i]]]?!1:!0},isEmpty:function(a){return a.match(/^\s+$/)||""===a?!0:!1},checkTime:function(d){var b=/^(\d{1,2}):(\d{2})([ap]m)?$/;if(!a.jgrid.isEmpty(d))if(d=d.match(b)){if(d[3]){if(1>d[1]||12<d[1])return!1}else if(23<d[1])return!1;if(59<d[2])return!1}else return!1;
-return!0},checkValues:function(d,b,c,f,g){var h,i;if("undefined"===typeof f)if("string"==typeof b){f=0;for(g=c.p.colModel.length;f<g;f++)if(c.p.colModel[f].name==b){h=c.p.colModel[f].editrules;b=f;try{i=c.p.colModel[f].formoptions.label}catch(e){}break}}else 0<=b&&(h=c.p.colModel[b].editrules);else h=f,i=void 0===g?"_":g;if(h){i||(i=c.p.colNames[b]);if(!0===h.required&&a.jgrid.isEmpty(d))return[!1,i+": "+a.jgrid.edit.msg.required,""];f=!1===h.required?!1:!0;if(!0===h.number&&!(!1===f&&a.jgrid.isEmpty(d))&&
-isNaN(d))return[!1,i+": "+a.jgrid.edit.msg.number,""];if("undefined"!=typeof h.minValue&&!isNaN(h.minValue)&&parseFloat(d)<parseFloat(h.minValue))return[!1,i+": "+a.jgrid.edit.msg.minValue+" "+h.minValue,""];if("undefined"!=typeof h.maxValue&&!isNaN(h.maxValue)&&parseFloat(d)>parseFloat(h.maxValue))return[!1,i+": "+a.jgrid.edit.msg.maxValue+" "+h.maxValue,""];if(!0===h.email&&!(!1===f&&a.jgrid.isEmpty(d))&&(g=/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,
-!g.test(d)))return[!1,i+": "+a.jgrid.edit.msg.email,""];if(!0===h.integer&&!(!1===f&&a.jgrid.isEmpty(d))&&(isNaN(d)||0!==d%1||-1!=d.indexOf(".")))return[!1,i+": "+a.jgrid.edit.msg.integer,""];if(!0===h.date&&!(!1===f&&a.jgrid.isEmpty(d))&&(b=c.p.colModel[b].formatoptions&&c.p.colModel[b].formatoptions.newformat?c.p.colModel[b].formatoptions.newformat:c.p.colModel[b].datefmt||"Y-m-d",!a.jgrid.checkDate(b,d)))return[!1,i+": "+a.jgrid.edit.msg.date+" - "+b,""];if(!0===h.time&&!(!1===f&&a.jgrid.isEmpty(d))&&
-!a.jgrid.checkTime(d))return[!1,i+": "+a.jgrid.edit.msg.date+" - hh:mm (am/pm)",""];if(!0===h.url&&!(!1===f&&a.jgrid.isEmpty(d))&&(g=/^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i,!g.test(d)))return[!1,i+": "+a.jgrid.edit.msg.url,""];if(!0===h.custom&&!(!1===f&&a.jgrid.isEmpty(d)))return a.isFunction(h.custom_func)?(d=h.custom_func.call(c,d,i),a.isArray(d)?d:[!1,a.jgrid.edit.msg.customarray,""]):[!1,a.jgrid.edit.msg.customfcheck,
-""]}return[!0,"",""]}})})(jQuery);
-(function(a){var c={};a.jgrid.extend({searchGrid:function(c){c=a.extend({recreateFilter:!1,drag:!0,sField:"searchField",sValue:"searchString",sOper:"searchOper",sFilter:"filters",loadDefaults:!0,beforeShowSearch:null,afterShowSearch:null,onInitializeSearch:null,afterRedraw:null,afterChange:null,closeAfterSearch:!1,closeAfterReset:!1,closeOnEscape:!1,searchOnEnter:!1,multipleSearch:!1,multipleGroup:!1,top:0,left:0,jqModal:!0,modal:!1,resize:!0,width:450,height:"auto",dataheight:"auto",showQuery:!1,
-errorcheck:!0,sopt:null,stringResult:void 0,onClose:null,onSearch:null,onReset:null,toTop:!0,overlay:30,columns:[],tmplNames:null,tmplFilters:null,tmplLabel:" Template: ",showOnLoad:!1,layer:null},a.jgrid.search,c||{});return this.each(function(){function d(b){r=a(e).triggerHandler("jqGridFilterBeforeShow",[b]);"undefined"===typeof r&&(r=!0);r&&a.isFunction(c.beforeShowSearch)&&(r=c.beforeShowSearch.call(e,b));r&&(a.jgrid.viewModal("#"+a.jgrid.jqID(t.themodal),{gbox:"#gbox_"+a.jgrid.jqID(l),jqm:c.jqModal,
-modal:c.modal,overlay:c.overlay,toTop:c.toTop}),a(e).triggerHandler("jqGridFilterAfterShow",[b]),a.isFunction(c.afterShowSearch)&&c.afterShowSearch.call(e,b))}var e=this;if(e.grid){var l="fbox_"+e.p.id,r=!0,t={themodal:"searchmod"+l,modalhead:"searchhd"+l,modalcontent:"searchcnt"+l,scrollelm:l},s=e.p.postData[c.sFilter];"string"===typeof s&&(s=a.jgrid.parse(s));!0===c.recreateFilter&&a("#"+a.jgrid.jqID(t.themodal)).remove();if(null!==a("#"+a.jgrid.jqID(t.themodal)).html())d(a("#fbox_"+a.jgrid.jqID(+e.p.id)));
-else{var p=a("<div><div id='"+l+"' class='searchFilter' style='overflow:auto'></div></div>").insertBefore("#gview_"+a.jgrid.jqID(e.p.id)),g="left",f="";"rtl"==e.p.direction&&(g="right",f=" style='text-align:left'",p.attr("dir","rtl"));var n=a.extend([],e.p.colModel),w="<a href='javascript:void(0)' id='"+l+"_search' class='fm-button ui-state-default ui-corner-all fm-button-icon-right ui-reset'><span class='ui-icon ui-icon-search'></span>"+c.Find+"</a>",b="<a href='javascript:void(0)' id='"+l+"_reset' class='fm-button ui-state-default ui-corner-all fm-button-icon-left ui-search'><span class='ui-icon ui-icon-arrowreturnthick-1-w'></span>"+
-c.Reset+"</a>",m="",h="",k,j=!1,o=-1;c.showQuery&&(m="<a href='javascript:void(0)' id='"+l+"_query' class='fm-button ui-state-default ui-corner-all fm-button-icon-left'><span class='ui-icon ui-icon-comment'></span>Query</a>");c.columns.length?n=c.columns:a.each(n,function(a,b){if(!b.label)b.label=e.p.colNames[a];if(!j){var c=typeof b.search==="undefined"?true:b.search,d=b.hidden===true;if(b.searchoptions&&b.searchoptions.searchhidden===true&&c||c&&!d){j=true;k=b.index||b.name;o=a}}});if(!s&&k||!1===
-c.multipleSearch){var y="eq";0<=o&&n[o].searchoptions&&n[o].searchoptions.sopt?y=n[o].searchoptions.sopt[0]:c.sopt&&c.sopt.length&&(y=c.sopt[0]);s={groupOp:"AND",rules:[{field:k,op:y,data:""}]}}j=!1;c.tmplNames&&c.tmplNames.length&&(j=!0,h=c.tmplLabel,h+="<select class='ui-template'>",h+="<option value='default'>Default</option>",a.each(c.tmplNames,function(a,b){h=h+("<option value='"+a+"'>"+b+"</option>")}),h+="</select>");g="<table class='EditTable' style='border:0px none;margin-top:5px' id='"+
-l+"_2'><tbody><tr><td colspan='2'><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr><td class='EditButton' style='text-align:"+g+"'>"+b+h+"</td><td class='EditButton' "+f+">"+m+w+"</td></tr></tbody></table>";l=a.jgrid.jqID(l);a("#"+l).jqFilter({columns:n,filter:c.loadDefaults?s:null,showQuery:c.showQuery,errorcheck:c.errorcheck,sopt:c.sopt,groupButton:c.multipleGroup,ruleButtons:c.multipleSearch,afterRedraw:c.afterRedraw,_gridsopt:a.jgrid.search.odata,ajaxSelectOptions:e.p.ajaxSelectOptions,
-groupOps:c.groupOps,onChange:function(){this.p.showQuery&&a(".query",this).html(this.toUserFriendlyString());a.isFunction(c.afterChange)&&c.afterChange.call(e,a("#"+l),c)},direction:e.p.direction});p.append(g);j&&(c.tmplFilters&&c.tmplFilters.length)&&a(".ui-template",p).bind("change",function(){var b=a(this).val();b=="default"?a("#"+l).jqFilter("addFilter",s):a("#"+l).jqFilter("addFilter",c.tmplFilters[parseInt(b,10)]);return false});!0===c.multipleGroup&&(c.multipleSearch=!0);a(e).triggerHandler("jqGridFilterInitialize",
-[a("#"+l)]);a.isFunction(c.onInitializeSearch)&&c.onInitializeSearch.call(e,a("#"+l));c.gbox="#gbox_"+l;c.layer?a.jgrid.createModal(t,p,c,"#gview_"+a.jgrid.jqID(e.p.id),a("#gbox_"+a.jgrid.jqID(e.p.id))[0],"#"+a.jgrid.jqID(c.layer),{position:"relative"}):a.jgrid.createModal(t,p,c,"#gview_"+a.jgrid.jqID(e.p.id),a("#gbox_"+a.jgrid.jqID(e.p.id))[0]);(c.searchOnEnter||c.closeOnEscape)&&a("#"+a.jgrid.jqID(t.themodal)).keydown(function(b){var d=a(b.target);if(c.searchOnEnter&&b.which===13&&!d.hasClass("add-group")&&
-!d.hasClass("add-rule")&&!d.hasClass("delete-group")&&!d.hasClass("delete-rule")&&(!d.hasClass("fm-button")||!d.is("[id$=_query]"))){a("#"+l+"_search").focus().click();return false}if(c.closeOnEscape&&b.which===27){a("#"+a.jgrid.jqID(t.modalhead)).find(".ui-jqdialog-titlebar-close").focus().click();return false}});m&&a("#"+l+"_query").bind("click",function(){a(".queryresult",p).toggle();return false});void 0===c.stringResult&&(c.stringResult=c.multipleSearch);a("#"+l+"_search").bind("click",function(){var b=
-a("#"+l),d={},h,q=b.jqFilter("filterData");if(c.errorcheck){b[0].hideError();c.showQuery||b.jqFilter("toSQLString");if(b[0].p.error){b[0].showError();return false}}if(c.stringResult){try{h=xmlJsonClass.toJson(q,"","",false)}catch(f){try{h=JSON.stringify(q)}catch(g){}}if(typeof h==="string"){d[c.sFilter]=h;a.each([c.sField,c.sValue,c.sOper],function(){d[this]=""})}}else if(c.multipleSearch){d[c.sFilter]=q;a.each([c.sField,c.sValue,c.sOper],function(){d[this]=""})}else{d[c.sField]=q.rules[0].field;
-d[c.sValue]=q.rules[0].data;d[c.sOper]=q.rules[0].op;d[c.sFilter]=""}e.p.search=true;a.extend(e.p.postData,d);a(e).triggerHandler("jqGridFilterSearch");a.isFunction(c.onSearch)&&c.onSearch.call(e);a(e).trigger("reloadGrid",[{page:1}]);c.closeAfterSearch&&a.jgrid.hideModal("#"+a.jgrid.jqID(t.themodal),{gb:"#gbox_"+a.jgrid.jqID(e.p.id),jqm:c.jqModal,onClose:c.onClose});return false});a("#"+l+"_reset").bind("click",function(){var b={},d=a("#"+l);e.p.search=false;c.multipleSearch===false?b[c.sField]=
-b[c.sValue]=b[c.sOper]="":b[c.sFilter]="";d[0].resetFilter();j&&a(".ui-template",p).val("default");a.extend(e.p.postData,b);a(e).triggerHandler("jqGridFilterReset");a.isFunction(c.onReset)&&c.onReset.call(e);a(e).trigger("reloadGrid",[{page:1}]);return false});d(a("#"+l));a(".fm-button:not(.ui-state-disabled)",p).hover(function(){a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")})}}})},editGridRow:function(u,d){d=a.extend({top:0,left:0,width:300,height:"auto",dataheight:"auto",
-modal:!1,overlay:30,drag:!0,resize:!0,url:null,mtype:"POST",clearAfterAdd:!0,closeAfterEdit:!1,reloadAfterSubmit:!0,onInitializeForm:null,beforeInitData:null,beforeShowForm:null,afterShowForm:null,beforeSubmit:null,afterSubmit:null,onclickSubmit:null,afterComplete:null,onclickPgButtons:null,afterclickPgButtons:null,editData:{},recreateForm:!1,jqModal:!0,closeOnEscape:!1,addedrow:"first",topinfo:"",bottominfo:"",saveicon:[],closeicon:[],savekey:[!1,13],navkeys:[!1,38,40],checkOnSubmit:!1,checkOnUpdate:!1,
-_savedData:{},processing:!1,onClose:null,ajaxEditOptions:{},serializeEditData:null,viewPagerButtons:!0},a.jgrid.edit,d||{});c[a(this)[0].p.id]=d;return this.each(function(){function e(){a(j+" > tbody > tr > td > .FormElement").each(function(){var d=a(".customelement",this);if(d.length){var c=a(d[0]).attr("name");a.each(b.p.colModel,function(){if(this.name===c&&this.editoptions&&a.isFunction(this.editoptions.custom_value)){try{if(i[c]=this.editoptions.custom_value.call(b,a("#"+a.jgrid.jqID(c),j),"get"),
-void 0===i[c])throw"e1";}catch(d){"e1"===d?a.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+a.jgrid.edit.msg.novalue,jQuery.jgrid.edit.bClose):a.jgrid.info_dialog(jQuery.jgrid.errors.errcap,d.message,jQuery.jgrid.edit.bClose)}return!0}})}else{switch(a(this).get(0).type){case "checkbox":a(this).is(":checked")?i[this.name]=a(this).val():(d=a(this).attr("offval"),i[this.name]=d);break;case "select-one":i[this.name]=a("option:selected",this).val();B[this.name]=a("option:selected",
-this).text();break;case "select-multiple":i[this.name]=a(this).val();i[this.name]=i[this.name]?i[this.name].join(","):"";var e=[];a("option:selected",this).each(function(b,d){e[b]=a(d).text()});B[this.name]=e.join(",");break;case "password":case "text":case "textarea":case "button":i[this.name]=a(this).val()}b.p.autoencode&&(i[this.name]=a.jgrid.htmlEncode(i[this.name]))}});return!0}function l(d,e,h,q){var i,f,g,k=0,j,o,l,p=[],n=!1,u="",m;for(m=1;m<=q;m++)u+="<td class='CaptionTD'>&#160;</td><td class='DataTD'>&#160;</td>";
-"_empty"!=d&&(n=a(e).jqGrid("getInd",d));a(e.p.colModel).each(function(m){i=this.name;o=(f=this.editrules&&!0===this.editrules.edithidden?!1:!0===this.hidden?!0:!1)?"style='display:none'":"";if("cb"!==i&&"subgrid"!==i&&!0===this.editable&&"rn"!==i){if(!1===n)j="";else if(i==e.p.ExpandColumn&&!0===e.p.treeGrid)j=a("td:eq("+m+")",e.rows[n]).text();else{try{j=a.unformat.call(e,a("td:eq("+m+")",e.rows[n]),{rowId:d,colModel:this},m)}catch(r){j=this.edittype&&"textarea"==this.edittype?a("td:eq("+m+")",
-e.rows[n]).text():a("td:eq("+m+")",e.rows[n]).html()}if(!j||"&nbsp;"==j||"&#160;"==j||1==j.length&&160==j.charCodeAt(0))j=""}var v=a.extend({},this.editoptions||{},{id:i,name:i}),s=a.extend({},{elmprefix:"",elmsuffix:"",rowabove:!1,rowcontent:""},this.formoptions||{}),t=parseInt(s.rowpos,10)||k+1,y=parseInt(2*(parseInt(s.colpos,10)||1),10);"_empty"==d&&v.defaultValue&&(j=a.isFunction(v.defaultValue)?v.defaultValue.call(b):v.defaultValue);this.edittype||(this.edittype="text");b.p.autoencode&&(j=a.jgrid.htmlDecode(j));
-l=a.jgrid.createEl.call(b,this.edittype,v,j,!1,a.extend({},a.jgrid.ajaxOptions,e.p.ajaxSelectOptions||{}));""===j&&"checkbox"==this.edittype&&(j=a(l).attr("offval"));""===j&&"select"==this.edittype&&(j=a("option:eq(0)",l).text());if(c[b.p.id].checkOnSubmit||c[b.p.id].checkOnUpdate)c[b.p.id]._savedData[i]=j;a(l).addClass("FormElement");("text"==this.edittype||"textarea"==this.edittype)&&a(l).addClass("ui-widget-content ui-corner-all");g=a(h).find("tr[rowpos="+t+"]");s.rowabove&&(v=a("<tr><td class='contentinfo' colspan='"+
-2*q+"'>"+s.rowcontent+"</td></tr>"),a(h).append(v),v[0].rp=t);0===g.length&&(g=a("<tr "+o+" rowpos='"+t+"'></tr>").addClass("FormData").attr("id","tr_"+i),a(g).append(u),a(h).append(g),g[0].rp=t);a("td:eq("+(y-2)+")",g[0]).html("undefined"===typeof s.label?e.p.colNames[m]:s.label);a("td:eq("+(y-1)+")",g[0]).append(s.elmprefix).append(l).append(s.elmsuffix);p[k]=m;k++}});if(0<k&&(m=a("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='"+(2*q-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='"+
-e.p.id+"_id' value='"+d+"'/></td></tr>"),m[0].rp=k+999,a(h).append(m),c[b.p.id].checkOnSubmit||c[b.p.id].checkOnUpdate))c[b.p.id]._savedData[e.p.id+"_id"]=d;return p}function r(d,e,h){var i,q=0,g,f,k,o,l;if(c[b.p.id].checkOnSubmit||c[b.p.id].checkOnUpdate)c[b.p.id]._savedData={},c[b.p.id]._savedData[e.p.id+"_id"]=d;var m=e.p.colModel;if("_empty"==d)a(m).each(function(){i=this.name;k=a.extend({},this.editoptions||{});if((f=a("#"+a.jgrid.jqID(i),"#"+h))&&f.length&&null!==f[0])if(o="",k.defaultValue?
-(o=a.isFunction(k.defaultValue)?k.defaultValue.call(b):k.defaultValue,"checkbox"==f[0].type?(l=o.toLowerCase(),0>l.search(/(false|0|no|off|undefined)/i)&&""!==l?(f[0].checked=!0,f[0].defaultChecked=!0,f[0].value=o):(f[0].checked=!1,f[0].defaultChecked=!1)):f.val(o)):"checkbox"==f[0].type?(f[0].checked=!1,f[0].defaultChecked=!1,o=a(f).attr("offval")):f[0].type&&"select"==f[0].type.substr(0,6)?f[0].selectedIndex=0:f.val(o),!0===c[b.p.id].checkOnSubmit||c[b.p.id].checkOnUpdate)c[b.p.id]._savedData[i]=
-o}),a("#id_g","#"+h).val(d);else{var n=a(e).jqGrid("getInd",d,!0);n&&(a('td[role="gridcell"]',n).each(function(f){i=m[f].name;if("cb"!==i&&"subgrid"!==i&&"rn"!==i&&!0===m[f].editable){if(i==e.p.ExpandColumn&&!0===e.p.treeGrid)g=a(this).text();else try{g=a.unformat.call(e,a(this),{rowId:d,colModel:m[f]},f)}catch(j){g="textarea"==m[f].edittype?a(this).text():a(this).html()}b.p.autoencode&&(g=a.jgrid.htmlDecode(g));if(!0===c[b.p.id].checkOnSubmit||c[b.p.id].checkOnUpdate)c[b.p.id]._savedData[i]=g;i=
-a.jgrid.jqID(i);switch(m[f].edittype){case "password":case "text":case "button":case "image":case "textarea":if("&nbsp;"==g||"&#160;"==g||1==g.length&&160==g.charCodeAt(0))g="";a("#"+i,"#"+h).val(g);break;case "select":var k=g.split(","),k=a.map(k,function(b){return a.trim(b)});a("#"+i+" option","#"+h).each(function(){this.selected=!m[f].editoptions.multiple&&(a.trim(g)==a.trim(a(this).text())||k[0]==a.trim(a(this).text())||k[0]==a.trim(a(this).val()))?!0:m[f].editoptions.multiple?-1<a.inArray(a.trim(a(this).text()),
-k)||-1<a.inArray(a.trim(a(this).val()),k)?!0:!1:!1});break;case "checkbox":g+="";m[f].editoptions&&m[f].editoptions.value?m[f].editoptions.value.split(":")[0]==g?(a("#"+i,"#"+h)[b.p.useProp?"prop":"attr"]("checked",!0),a("#"+i,"#"+h)[b.p.useProp?"prop":"attr"]("defaultChecked",!0)):(a("#"+i,"#"+h)[b.p.useProp?"prop":"attr"]("checked",!1),a("#"+i,"#"+h)[b.p.useProp?"prop":"attr"]("defaultChecked",!1)):(g=g.toLowerCase(),0>g.search(/(false|0|no|off|undefined)/i)&&""!==g?(a("#"+i,"#"+h)[b.p.useProp?
-"prop":"attr"]("checked",!0),a("#"+i,"#"+h)[b.p.useProp?"prop":"attr"]("defaultChecked",!0)):(a("#"+i,"#"+h)[b.p.useProp?"prop":"attr"]("checked",!1),a("#"+i,"#"+h)[b.p.useProp?"prop":"attr"]("defaultChecked",!1)));break;case "custom":try{if(m[f].editoptions&&a.isFunction(m[f].editoptions.custom_value))m[f].editoptions.custom_value.call(b,a("#"+i,"#"+h),"set",g);else throw"e1";}catch(o){"e1"==o?a.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+a.jgrid.edit.msg.nodefined,jQuery.jgrid.edit.bClose):
-a.jgrid.info_dialog(jQuery.jgrid.errors.errcap,o.message,jQuery.jgrid.edit.bClose)}}q++}}),0<q&&a("#id_g",j).val(d))}}function t(){a.each(b.p.colModel,function(a,b){b.editoptions&&!0===b.editoptions.NullIfEmpty&&i.hasOwnProperty(b.name)&&""===i[b.name]&&(i[b.name]="null")})}function s(){var e,f=[!0,"",""],g={},q=b.p.prmNames,k,l,n,p,v,u=a(b).triggerHandler("jqGridAddEditBeforeCheckValues",[a("#"+h),z]);u&&"object"===typeof u&&(i=u);a.isFunction(c[b.p.id].beforeCheckValues)&&(u=c[b.p.id].beforeCheckValues.call(b,
-i,a("#"+h),"_empty"==i[b.p.id+"_id"]?q.addoper:q.editoper))&&"object"===typeof u&&(i=u);for(n in i)if(i.hasOwnProperty(n)&&(f=a.jgrid.checkValues.call(b,i[n],n,b),!1===f[0]))break;t();f[0]&&(g=a(b).triggerHandler("jqGridAddEditClickSubmit",[c[b.p.id],i,z]),void 0===g&&a.isFunction(c[b.p.id].onclickSubmit)&&(g=c[b.p.id].onclickSubmit.call(b,c[b.p.id],i)||{}),f=a(b).triggerHandler("jqGridAddEditBeforeSubmit",[i,a("#"+h),z]),void 0===f&&(f=[!0,"",""]),f[0]&&a.isFunction(c[b.p.id].beforeSubmit)&&(f=c[b.p.id].beforeSubmit.call(b,
-i,a("#"+h))));if(f[0]&&!c[b.p.id].processing){c[b.p.id].processing=!0;a("#sData",j+"_2").addClass("ui-state-active");l=q.oper;k=q.id;i[l]="_empty"==a.trim(i[b.p.id+"_id"])?q.addoper:q.editoper;i[l]!=q.addoper?i[k]=i[b.p.id+"_id"]:void 0===i[k]&&(i[k]=i[b.p.id+"_id"]);delete i[b.p.id+"_id"];i=a.extend(i,c[b.p.id].editData,g);if(!0===b.p.treeGrid)for(v in i[l]==q.addoper&&(p=a(b).jqGrid("getGridParam","selrow"),i["adjacency"==b.p.treeGridModel?b.p.treeReader.parent_id_field:"parent_id"]=p),b.p.treeReader)b.p.treeReader.hasOwnProperty(v)&&
-(g=b.p.treeReader[v],i.hasOwnProperty(g)&&!(i[l]==q.addoper&&"parent_id_field"===v)&&delete i[g]);i[k]=a.jgrid.stripPref(b.p.idPrefix,i[k]);v=a.extend({url:c[b.p.id].url?c[b.p.id].url:a(b).jqGrid("getGridParam","editurl"),type:c[b.p.id].mtype,data:a.isFunction(c[b.p.id].serializeEditData)?c[b.p.id].serializeEditData.call(b,i):i,complete:function(g,n){i[k]=b.p.idPrefix+i[k];if(n!="success"){f[0]=false;f[1]=a(b).triggerHandler("jqGridAddEditErrorTextFormat",[g,z]);f[1]=a.isFunction(c[b.p.id].errorTextFormat)?
-c[b.p.id].errorTextFormat.call(b,g):n+" Status: '"+g.statusText+"'. Error code: "+g.status}else{f=a(b).triggerHandler("jqGridAddEditAfterSubmit",[g,i,z]);f===void 0&&(f=[true,"",""]);f[0]&&a.isFunction(c[b.p.id].afterSubmit)&&(f=c[b.p.id].afterSubmit.call(b,g,i))}if(f[0]===false){a("#FormError>td",j).html(f[1]);a("#FormError",j).show()}else{a.each(b.p.colModel,function(){if(B[this.name]&&this.formatter&&this.formatter=="select")try{delete B[this.name]}catch(a){}});i=a.extend(i,B);b.p.autoencode&&
-a.each(i,function(b,d){i[b]=a.jgrid.htmlDecode(d)});if(i[l]==q.addoper){f[2]||(f[2]=a.jgrid.randId());i[k]=f[2];if(c[b.p.id].closeAfterAdd){if(c[b.p.id].reloadAfterSubmit)a(b).trigger("reloadGrid");else if(b.p.treeGrid===true)a(b).jqGrid("addChildNode",f[2],p,i);else{a(b).jqGrid("addRowData",f[2],i,d.addedrow);a(b).jqGrid("setSelection",f[2])}a.jgrid.hideModal("#"+a.jgrid.jqID(o.themodal),{gb:"#gbox_"+a.jgrid.jqID(m),jqm:d.jqModal,onClose:c[b.p.id].onClose})}else if(c[b.p.id].clearAfterAdd){c[b.p.id].reloadAfterSubmit?
-a(b).trigger("reloadGrid"):b.p.treeGrid===true?a(b).jqGrid("addChildNode",f[2],p,i):a(b).jqGrid("addRowData",f[2],i,d.addedrow);r("_empty",b,h)}else c[b.p.id].reloadAfterSubmit?a(b).trigger("reloadGrid"):b.p.treeGrid===true?a(b).jqGrid("addChildNode",f[2],p,i):a(b).jqGrid("addRowData",f[2],i,d.addedrow)}else{if(c[b.p.id].reloadAfterSubmit){a(b).trigger("reloadGrid");c[b.p.id].closeAfterEdit||setTimeout(function(){a(b).jqGrid("setSelection",i[k])},1E3)}else b.p.treeGrid===true?a(b).jqGrid("setTreeRow",
-i[k],i):a(b).jqGrid("setRowData",i[k],i);c[b.p.id].closeAfterEdit&&a.jgrid.hideModal("#"+a.jgrid.jqID(o.themodal),{gb:"#gbox_"+a.jgrid.jqID(m),jqm:d.jqModal,onClose:c[b.p.id].onClose})}if(a.isFunction(c[b.p.id].afterComplete)){e=g;setTimeout(function(){a(b).triggerHandler("jqGridAddEditAfterComplete",[e,i,a("#"+h),z]);c[b.p.id].afterComplete.call(b,e,i,a("#"+h));e=null},500)}if(c[b.p.id].checkOnSubmit||c[b.p.id].checkOnUpdate){a("#"+h).data("disabled",false);if(c[b.p.id]._savedData[b.p.id+"_id"]!=
-"_empty")for(var v in c[b.p.id]._savedData)i[v]&&(c[b.p.id]._savedData[v]=i[v])}}c[b.p.id].processing=false;a("#sData",j+"_2").removeClass("ui-state-active");try{a(":input:visible","#"+h)[0].focus()}catch(u){}}},a.jgrid.ajaxOptions,c[b.p.id].ajaxEditOptions);!v.url&&!c[b.p.id].useDataProxy&&(a.isFunction(b.p.dataProxy)?c[b.p.id].useDataProxy=!0:(f[0]=!1,f[1]+=" "+a.jgrid.errors.nourl));f[0]&&(c[b.p.id].useDataProxy?(g=b.p.dataProxy.call(b,v,"set_"+b.p.id),"undefined"==typeof g&&(g=[!0,""]),!1===g[0]?
-(f[0]=!1,f[1]=g[1]||"Error deleting the selected row!"):(v.data.oper==q.addoper&&c[b.p.id].closeAfterAdd&&a.jgrid.hideModal("#"+a.jgrid.jqID(o.themodal),{gb:"#gbox_"+a.jgrid.jqID(m),jqm:d.jqModal,onClose:c[b.p.id].onClose}),v.data.oper==q.editoper&&c[b.p.id].closeAfterEdit&&a.jgrid.hideModal("#"+a.jgrid.jqID(o.themodal),{gb:"#gbox_"+a.jgrid.jqID(m),jqm:d.jqModal,onClose:c[b.p.id].onClose}))):a.ajax(v))}!1===f[0]&&(a("#FormError>td",j).html(f[1]),a("#FormError",j).show())}function p(a,b){var d=!1,
-c;for(c in a)if(a[c]!=b[c]){d=!0;break}return d}function g(){var d=!0;a("#FormError",j).hide();if(c[b.p.id].checkOnUpdate&&(i={},B={},e(),F=a.extend({},i,B),M=p(F,c[b.p.id]._savedData)))a("#"+h).data("disabled",!0),a(".confirm","#"+o.themodal).show(),d=!1;return d}function f(){if("_empty"!==u&&"undefined"!==typeof b.p.savedRow&&0<b.p.savedRow.length&&a.isFunction(a.fn.jqGrid.restoreRow))for(var d=0;d<b.p.savedRow.length;d++)if(b.p.savedRow[d].id==u){a(b).jqGrid("restoreRow",u);break}}function n(b,
-d){0===b?a("#pData",j+"_2").addClass("ui-state-disabled"):a("#pData",j+"_2").removeClass("ui-state-disabled");b==d?a("#nData",j+"_2").addClass("ui-state-disabled"):a("#nData",j+"_2").removeClass("ui-state-disabled")}function w(){var d=a(b).jqGrid("getDataIDs"),c=a("#id_g",j).val();return[a.inArray(c,d),d]}var b=this;if(b.grid&&u){var m=b.p.id,h="FrmGrid_"+m,k="TblGrid_"+m,j="#"+a.jgrid.jqID(k),o={themodal:"editmod"+m,modalhead:"edithd"+m,modalcontent:"editcnt"+m,scrollelm:h},y=a.isFunction(c[b.p.id].beforeShowForm)?
-c[b.p.id].beforeShowForm:!1,A=a.isFunction(c[b.p.id].afterShowForm)?c[b.p.id].afterShowForm:!1,x=a.isFunction(c[b.p.id].beforeInitData)?c[b.p.id].beforeInitData:!1,E=a.isFunction(c[b.p.id].onInitializeForm)?c[b.p.id].onInitializeForm:!1,q=!0,v=1,H=0,i,B,F,M,z,h=a.jgrid.jqID(h);"new"===u?(u="_empty",z="add",d.caption=c[b.p.id].addCaption):(d.caption=c[b.p.id].editCaption,z="edit");!0===d.recreateForm&&null!==a("#"+a.jgrid.jqID(o.themodal)).html()&&a("#"+a.jgrid.jqID(o.themodal)).remove();var I=!0;
-d.checkOnUpdate&&(d.jqModal&&!d.modal)&&(I=!1);if(null!==a("#"+a.jgrid.jqID(o.themodal)).html()){q=a(b).triggerHandler("jqGridAddEditBeforeInitData",[a("#"+a.jgrid.jqID(h))]);"undefined"==typeof q&&(q=!0);q&&x&&(q=x.call(b,a("#"+h)));if(!1===q)return;f();a(".ui-jqdialog-title","#"+a.jgrid.jqID(o.modalhead)).html(d.caption);a("#FormError",j).hide();c[b.p.id].topinfo?(a(".topinfo",j).html(c[b.p.id].topinfo),a(".tinfo",j).show()):a(".tinfo",j).hide();c[b.p.id].bottominfo?(a(".bottominfo",j+"_2").html(c[b.p.id].bottominfo),
-a(".binfo",j+"_2").show()):a(".binfo",j+"_2").hide();r(u,b,h);"_empty"==u||!c[b.p.id].viewPagerButtons?a("#pData, #nData",j+"_2").hide():a("#pData, #nData",j+"_2").show();!0===c[b.p.id].processing&&(c[b.p.id].processing=!1,a("#sData",j+"_2").removeClass("ui-state-active"));!0===a("#"+h).data("disabled")&&(a(".confirm","#"+a.jgrid.jqID(o.themodal)).hide(),a("#"+h).data("disabled",!1));a(b).triggerHandler("jqGridAddEditBeforeShowForm",[a("#"+h),z]);y&&y.call(b,a("#"+h));a("#"+a.jgrid.jqID(o.themodal)).data("onClose",
-c[b.p.id].onClose);a.jgrid.viewModal("#"+a.jgrid.jqID(o.themodal),{gbox:"#gbox_"+a.jgrid.jqID(m),jqm:d.jqModal,jqM:!1,overlay:d.overlay,modal:d.modal});I||a(".jqmOverlay").click(function(){if(!g())return false;a.jgrid.hideModal("#"+a.jgrid.jqID(o.themodal),{gb:"#gbox_"+a.jgrid.jqID(m),jqm:d.jqModal,onClose:c[b.p.id].onClose});return false});a(b).triggerHandler("jqGridAddEditAfterShowForm",[a("#"+h),z]);A&&A.call(b,a("#"+h))}else{var G=isNaN(d.dataheight)?d.dataheight:d.dataheight+"px",G=a("<form name='FormPost' id='"+
-h+"' class='FormGrid' onSubmit='return false;' style='width:100%;overflow:auto;position:relative;height:"+G+";'></form>").data("disabled",!1),C=a("<table id='"+k+"' class='EditTable' cellspacing='0' cellpadding='0' border='0'><tbody></tbody></table>"),q=a(b).triggerHandler("jqGridAddEditBeforeInitData",[a("#"+h),z]);"undefined"==typeof q&&(q=!0);q&&x&&(q=x.call(b,a("#"+h)));if(!1===q)return;f();a(b.p.colModel).each(function(){var a=this.formoptions;v=Math.max(v,a?a.colpos||0:0);H=Math.max(H,a?a.rowpos||
-0:0)});a(G).append(C);x=a("<tr id='FormError' style='display:none'><td class='ui-state-error' colspan='"+2*v+"'></td></tr>");x[0].rp=0;a(C).append(x);x=a("<tr style='display:none' class='tinfo'><td class='topinfo' colspan='"+2*v+"'>"+c[b.p.id].topinfo+"</td></tr>");x[0].rp=0;a(C).append(x);var q=(x="rtl"==b.p.direction?!0:!1)?"nData":"pData",D=x?"pData":"nData";l(u,b,C,v);var q="<a href='javascript:void(0)' id='"+q+"' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></a>",
-D="<a href='javascript:void(0)' id='"+D+"' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></a>",J="<a href='javascript:void(0)' id='sData' class='fm-button ui-state-default ui-corner-all'>"+d.bSubmit+"</a>",K="<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>"+d.bCancel+"</a>",k="<table border='0' cellspacing='0' cellpadding='0' class='EditTable' id='"+k+"_2'><tbody><tr><td colspan='2'><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr id='Act_Buttons'><td class='navButton'>"+
-(x?D+q:q+D)+"</td><td class='EditButton'>"+J+K+"</td></tr>"+("<tr style='display:none' class='binfo'><td class='bottominfo' colspan='2'>"+c[b.p.id].bottominfo+"</td></tr>"),k=k+"</tbody></table>";if(0<H){var L=[];a.each(a(C)[0].rows,function(a,b){L[a]=b});L.sort(function(a,b){return a.rp>b.rp?1:a.rp<b.rp?-1:0});a.each(L,function(b,d){a("tbody",C).append(d)})}d.gbox="#gbox_"+a.jgrid.jqID(m);var N=!1;!0===d.closeOnEscape&&(d.closeOnEscape=!1,N=!0);k=a("<span></span>").append(G).append(k);a.jgrid.createModal(o,
-k,d,"#gview_"+a.jgrid.jqID(b.p.id),a("#gbox_"+a.jgrid.jqID(b.p.id))[0]);x&&(a("#pData, #nData",j+"_2").css("float","right"),a(".EditButton",j+"_2").css("text-align","left"));c[b.p.id].topinfo&&a(".tinfo",j).show();c[b.p.id].bottominfo&&a(".binfo",j+"_2").show();k=k=null;a("#"+a.jgrid.jqID(o.themodal)).keydown(function(e){var f=e.target;if(a("#"+h).data("disabled")===true)return false;if(c[b.p.id].savekey[0]===true&&e.which==c[b.p.id].savekey[1]&&f.tagName!="TEXTAREA"){a("#sData",j+"_2").trigger("click");
-return false}if(e.which===27){if(!g())return false;N&&a.jgrid.hideModal(this,{gb:d.gbox,jqm:d.jqModal,onClose:c[b.p.id].onClose});return false}if(c[b.p.id].navkeys[0]===true){if(a("#id_g",j).val()=="_empty")return true;if(e.which==c[b.p.id].navkeys[1]){a("#pData",j+"_2").trigger("click");return false}if(e.which==c[b.p.id].navkeys[2]){a("#nData",j+"_2").trigger("click");return false}}});d.checkOnUpdate&&(a("a.ui-jqdialog-titlebar-close span","#"+a.jgrid.jqID(o.themodal)).removeClass("jqmClose"),a("a.ui-jqdialog-titlebar-close",
-"#"+a.jgrid.jqID(o.themodal)).unbind("click").click(function(){if(!g())return false;a.jgrid.hideModal("#"+a.jgrid.jqID(o.themodal),{gb:"#gbox_"+a.jgrid.jqID(m),jqm:d.jqModal,onClose:c[b.p.id].onClose});return false}));d.saveicon=a.extend([!0,"left","ui-icon-disk"],d.saveicon);d.closeicon=a.extend([!0,"left","ui-icon-close"],d.closeicon);!0===d.saveicon[0]&&a("#sData",j+"_2").addClass("right"==d.saveicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+d.saveicon[2]+
-"'></span>");!0===d.closeicon[0]&&a("#cData",j+"_2").addClass("right"==d.closeicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+d.closeicon[2]+"'></span>");if(c[b.p.id].checkOnSubmit||c[b.p.id].checkOnUpdate)J="<a href='javascript:void(0)' id='sNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+d.bYes+"</a>",D="<a href='javascript:void(0)' id='nNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+d.bNo+"</a>",K="<a href='javascript:void(0)' id='cNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+
-d.bExit+"</a>",k=d.zIndex||999,k++,a("<div class='ui-widget-overlay jqgrid-overlay confirm' style='z-index:"+k+";display:none;'>&#160;"+(a.browser.msie&&6==a.browser.version?'<iframe style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=\'0\');" src="javascript:false;"></iframe>':"")+"</div><div class='confirm ui-widget-content ui-jqconfirm' style='z-index:"+(k+1)+"'>"+d.saveData+"<br/><br/>"+J+D+K+"</div>").insertAfter("#"+h),a("#sNew","#"+a.jgrid.jqID(o.themodal)).click(function(){s();
-a("#"+h).data("disabled",false);a(".confirm","#"+a.jgrid.jqID(o.themodal)).hide();return false}),a("#nNew","#"+a.jgrid.jqID(o.themodal)).click(function(){a(".confirm","#"+a.jgrid.jqID(o.themodal)).hide();a("#"+h).data("disabled",false);setTimeout(function(){a(":input","#"+h)[0].focus()},0);return false}),a("#cNew","#"+a.jgrid.jqID(o.themodal)).click(function(){a(".confirm","#"+a.jgrid.jqID(o.themodal)).hide();a("#"+h).data("disabled",false);a.jgrid.hideModal("#"+a.jgrid.jqID(o.themodal),{gb:"#gbox_"+
-a.jgrid.jqID(m),jqm:d.jqModal,onClose:c[b.p.id].onClose});return false});a(b).triggerHandler("jqGridAddEditInitializeForm",[a("#"+h),z]);E&&E.call(b,a("#"+h));"_empty"==u||!c[b.p.id].viewPagerButtons?a("#pData,#nData",j+"_2").hide():a("#pData,#nData",j+"_2").show();a(b).triggerHandler("jqGridAddEditBeforeShowForm",[a("#"+h),z]);y&&y.call(b,a("#"+h));a("#"+a.jgrid.jqID(o.themodal)).data("onClose",c[b.p.id].onClose);a.jgrid.viewModal("#"+a.jgrid.jqID(o.themodal),{gbox:"#gbox_"+a.jgrid.jqID(m),jqm:d.jqModal,
-overlay:d.overlay,modal:d.modal});I||a(".jqmOverlay").click(function(){if(!g())return false;a.jgrid.hideModal("#"+a.jgrid.jqID(o.themodal),{gb:"#gbox_"+a.jgrid.jqID(m),jqm:d.jqModal,onClose:c[b.p.id].onClose});return false});a(b).triggerHandler("jqGridAddEditAfterShowForm",[a("#"+h),z]);A&&A.call(b,a("#"+h));a(".fm-button","#"+a.jgrid.jqID(o.themodal)).hover(function(){a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")});a("#sData",j+"_2").click(function(){i={};B=
-{};a("#FormError",j).hide();e();if(i[b.p.id+"_id"]=="_empty")s();else if(d.checkOnSubmit===true){F=a.extend({},i,B);if(M=p(F,c[b.p.id]._savedData)){a("#"+h).data("disabled",true);a(".confirm","#"+a.jgrid.jqID(o.themodal)).show()}else s()}else s();return false});a("#cData",j+"_2").click(function(){if(!g())return false;a.jgrid.hideModal("#"+a.jgrid.jqID(o.themodal),{gb:"#gbox_"+a.jgrid.jqID(m),jqm:d.jqModal,onClose:c[b.p.id].onClose});return false});a("#nData",j+"_2").click(function(){if(!g())return false;
-a("#FormError",j).hide();var c=w();c[0]=parseInt(c[0],10);if(c[0]!=-1&&c[1][c[0]+1]){a(b).triggerHandler("jqGridAddEditClickPgButtons",["next",a("#"+h),c[1][c[0]]]);a.isFunction(d.onclickPgButtons)&&d.onclickPgButtons.call(b,"next",a("#"+h),c[1][c[0]]);r(c[1][c[0]+1],b,h);a(b).jqGrid("setSelection",c[1][c[0]+1]);a(b).triggerHandler("jqGridAddEditAfterClickPgButtons",["next",a("#"+h),c[1][c[0]]]);a.isFunction(d.afterclickPgButtons)&&d.afterclickPgButtons.call(b,"next",a("#"+h),c[1][c[0]+1]);n(c[0]+
-1,c[1].length-1)}return false});a("#pData",j+"_2").click(function(){if(!g())return false;a("#FormError",j).hide();var c=w();if(c[0]!=-1&&c[1][c[0]-1]){a(b).triggerHandler("jqGridAddEditClickPgButtons",["prev",a("#"+h),c[1][c[0]]]);a.isFunction(d.onclickPgButtons)&&d.onclickPgButtons.call(b,"prev",a("#"+h),c[1][c[0]]);r(c[1][c[0]-1],b,h);a(b).jqGrid("setSelection",c[1][c[0]-1]);a(b).triggerHandler("jqGridAddEditAfterClickPgButtons",["prev",a("#"+h),c[1][c[0]]]);a.isFunction(d.afterclickPgButtons)&&
-d.afterclickPgButtons.call(b,"prev",a("#"+h),c[1][c[0]-1]);n(c[0]-1,c[1].length-1)}return false})}y=w();n(y[0],y[1].length-1)}})},viewGridRow:function(c,d){d=a.extend({top:0,left:0,width:0,height:"auto",dataheight:"auto",modal:!1,overlay:30,drag:!0,resize:!0,jqModal:!0,closeOnEscape:!1,labelswidth:"30%",closeicon:[],navkeys:[!1,38,40],onClose:null,beforeShowForm:null,beforeInitData:null,viewPagerButtons:!0},a.jgrid.view,d||{});return this.each(function(){function e(){(!0===d.closeOnEscape||!0===d.navkeys[0])&&
-setTimeout(function(){a(".ui-jqdialog-titlebar-close","#"+a.jgrid.jqID(m.modalhead)).focus()},0)}function l(b,c,e,f){for(var g,h,k,j=0,o,m,l=[],n=!1,p="<td class='CaptionTD form-view-label ui-widget-content' width='"+d.labelswidth+"'>&#160;</td><td class='DataTD form-view-data ui-helper-reset ui-widget-content'>&#160;</td>",u="",s=["integer","number","currency"],r=0,t=0,y,x,w,A=1;A<=f;A++)u+=1==A?p:"<td class='CaptionTD form-view-label ui-widget-content'>&#160;</td><td class='DataTD form-view-data ui-widget-content'>&#160;</td>";
-a(c.p.colModel).each(function(){h=this.editrules&&!0===this.editrules.edithidden?!1:!0===this.hidden?!0:!1;!h&&"right"===this.align&&(this.formatter&&-1!==a.inArray(this.formatter,s)?r=Math.max(r,parseInt(this.width,10)):t=Math.max(t,parseInt(this.width,10)))});y=0!==r?r:0!==t?t:0;n=a(c).jqGrid("getInd",b);a(c.p.colModel).each(function(b){g=this.name;x=!1;m=(h=this.editrules&&!0===this.editrules.edithidden?!1:!0===this.hidden?!0:!1)?"style='display:none'":"";w="boolean"!=typeof this.viewable?!0:this.viewable;
-if("cb"!==g&&"subgrid"!==g&&"rn"!==g&&w){o=!1===n?"":g==c.p.ExpandColumn&&!0===c.p.treeGrid?a("td:eq("+b+")",c.rows[n]).text():a("td:eq("+b+")",c.rows[n]).html();x="right"===this.align&&0!==y?!0:!1;a.extend({},this.editoptions||{},{id:g,name:g});var d=a.extend({},{rowabove:!1,rowcontent:""},this.formoptions||{}),q=parseInt(d.rowpos,10)||j+1,p=parseInt(2*(parseInt(d.colpos,10)||1),10);if(d.rowabove){var r=a("<tr><td class='contentinfo' colspan='"+2*f+"'>"+d.rowcontent+"</td></tr>");a(e).append(r);
-r[0].rp=q}k=a(e).find("tr[rowpos="+q+"]");0===k.length&&(k=a("<tr "+m+" rowpos='"+q+"'></tr>").addClass("FormData").attr("id","trv_"+g),a(k).append(u),a(e).append(k),k[0].rp=q);a("td:eq("+(p-2)+")",k[0]).html("<b>"+("undefined"===typeof d.label?c.p.colNames[b]:d.label)+"</b>");a("td:eq("+(p-1)+")",k[0]).append("<span>"+o+"</span>").attr("id","v_"+g);x&&a("td:eq("+(p-1)+") span",k[0]).css({"text-align":"right",width:y+"px"});l[j]=b;j++}});0<j&&(b=a("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='"+
-(2*f-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='id' value='"+b+"'/></td></tr>"),b[0].rp=j+99,a(e).append(b));return l}function r(b,c){var d,e,f=0,g,h;if(h=a(c).jqGrid("getInd",b,!0))a("td",h).each(function(b){d=c.p.colModel[b].name;e=c.p.colModel[b].editrules&&!0===c.p.colModel[b].editrules.edithidden?!1:!0===c.p.colModel[b].hidden?!0:!1;"cb"!==d&&("subgrid"!==d&&"rn"!==d)&&(g=d==c.p.ExpandColumn&&!0===c.p.treeGrid?a(this).text():a(this).html(),a.extend({},c.p.colModel[b].editoptions||
-{}),d=a.jgrid.jqID("v_"+d),a("#"+d+" span","#"+n).html(g),e&&a("#"+d,"#"+n).parents("tr:first").hide(),f++)}),0<f&&a("#id_g","#"+n).val(b)}function t(b,c){0===b?a("#pData","#"+n+"_2").addClass("ui-state-disabled"):a("#pData","#"+n+"_2").removeClass("ui-state-disabled");b==c?a("#nData","#"+n+"_2").addClass("ui-state-disabled"):a("#nData","#"+n+"_2").removeClass("ui-state-disabled")}function s(){var b=a(p).jqGrid("getDataIDs"),c=a("#id_g","#"+n).val();return[a.inArray(c,b),b]}var p=this;if(p.grid&&
-c){var g=p.p.id,f="ViewGrid_"+a.jgrid.jqID(g),n="ViewTbl_"+a.jgrid.jqID(g),w="ViewGrid_"+g,b="ViewTbl_"+g,m={themodal:"viewmod"+g,modalhead:"viewhd"+g,modalcontent:"viewcnt"+g,scrollelm:f},h=a.isFunction(d.beforeInitData)?d.beforeInitData:!1,k=!0,j=1,o=0;if(null!==a("#"+a.jgrid.jqID(m.themodal)).html()){h&&(k=h.call(p,a("#"+f)),"undefined"==typeof k&&(k=!0));if(!1===k)return;a(".ui-jqdialog-title","#"+a.jgrid.jqID(m.modalhead)).html(d.caption);a("#FormError","#"+n).hide();r(c,p);a.isFunction(d.beforeShowForm)&&
-d.beforeShowForm.call(p,a("#"+f));a.jgrid.viewModal("#"+a.jgrid.jqID(m.themodal),{gbox:"#gbox_"+a.jgrid.jqID(g),jqm:d.jqModal,jqM:!1,overlay:d.overlay,modal:d.modal});e()}else{var y=isNaN(d.dataheight)?d.dataheight:d.dataheight+"px",w=a("<form name='FormPost' id='"+w+"' class='FormGrid' style='width:100%;overflow:auto;position:relative;height:"+y+";'></form>"),A=a("<table id='"+b+"' class='EditTable' cellspacing='1' cellpadding='2' border='0' style='table-layout:fixed'><tbody></tbody></table>");h&&
-(k=h.call(p,a("#"+f)),"undefined"==typeof k&&(k=!0));if(!1===k)return;a(p.p.colModel).each(function(){var a=this.formoptions;j=Math.max(j,a?a.colpos||0:0);o=Math.max(o,a?a.rowpos||0:0)});a(w).append(A);l(c,p,A,j);b="rtl"==p.p.direction?!0:!1;h="<a href='javascript:void(0)' id='"+(b?"nData":"pData")+"' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></a>";k="<a href='javascript:void(0)' id='"+(b?"pData":"nData")+"' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></a>";
-y="<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>"+d.bClose+"</a>";if(0<o){var x=[];a.each(a(A)[0].rows,function(a,b){x[a]=b});x.sort(function(a,b){return a.rp>b.rp?1:a.rp<b.rp?-1:0});a.each(x,function(b,c){a("tbody",A).append(c)})}d.gbox="#gbox_"+a.jgrid.jqID(g);var E=!1;!0===d.closeOnEscape&&(d.closeOnEscape=!1,E=!0);w=a("<span></span>").append(w).append("<table border='0' class='EditTable' id='"+n+"_2'><tbody><tr id='Act_Buttons'><td class='navButton' width='"+
-d.labelswidth+"'>"+(b?k+h:h+k)+"</td><td class='EditButton'>"+y+"</td></tr></tbody></table>");a.jgrid.createModal(m,w,d,"#gview_"+a.jgrid.jqID(p.p.id),a("#gview_"+a.jgrid.jqID(p.p.id))[0]);b&&(a("#pData, #nData","#"+n+"_2").css("float","right"),a(".EditButton","#"+n+"_2").css("text-align","left"));d.viewPagerButtons||a("#pData, #nData","#"+n+"_2").hide();w=null;a("#"+m.themodal).keydown(function(b){if(b.which===27){E&&a.jgrid.hideModal(this,{gb:d.gbox,jqm:d.jqModal,onClose:d.onClose});return false}if(d.navkeys[0]===
-true){if(b.which===d.navkeys[1]){a("#pData","#"+n+"_2").trigger("click");return false}if(b.which===d.navkeys[2]){a("#nData","#"+n+"_2").trigger("click");return false}}});d.closeicon=a.extend([!0,"left","ui-icon-close"],d.closeicon);!0===d.closeicon[0]&&a("#cData","#"+n+"_2").addClass("right"==d.closeicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+d.closeicon[2]+"'></span>");a.isFunction(d.beforeShowForm)&&d.beforeShowForm.call(p,a("#"+f));a.jgrid.viewModal("#"+
-a.jgrid.jqID(m.themodal),{gbox:"#gbox_"+a.jgrid.jqID(g),jqm:d.jqModal,modal:d.modal});a(".fm-button:not(.ui-state-disabled)","#"+n+"_2").hover(function(){a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")});e();a("#cData","#"+n+"_2").click(function(){a.jgrid.hideModal("#"+a.jgrid.jqID(m.themodal),{gb:"#gbox_"+a.jgrid.jqID(g),jqm:d.jqModal,onClose:d.onClose});return false});a("#nData","#"+n+"_2").click(function(){a("#FormError","#"+n).hide();var b=s();b[0]=parseInt(b[0],
-10);if(b[0]!=-1&&b[1][b[0]+1]){a.isFunction(d.onclickPgButtons)&&d.onclickPgButtons.call(p,"next",a("#"+f),b[1][b[0]]);r(b[1][b[0]+1],p);a(p).jqGrid("setSelection",b[1][b[0]+1]);a.isFunction(d.afterclickPgButtons)&&d.afterclickPgButtons.call(p,"next",a("#"+f),b[1][b[0]+1]);t(b[0]+1,b[1].length-1)}e();return false});a("#pData","#"+n+"_2").click(function(){a("#FormError","#"+n).hide();var b=s();if(b[0]!=-1&&b[1][b[0]-1]){a.isFunction(d.onclickPgButtons)&&d.onclickPgButtons.call(p,"prev",a("#"+f),b[1][b[0]]);
-r(b[1][b[0]-1],p);a(p).jqGrid("setSelection",b[1][b[0]-1]);a.isFunction(d.afterclickPgButtons)&&d.afterclickPgButtons.call(p,"prev",a("#"+f),b[1][b[0]-1]);t(b[0]-1,b[1].length-1)}e();return false})}w=s();t(w[0],w[1].length-1)}})},delGridRow:function(u,d){d=a.extend({top:0,left:0,width:240,height:"auto",dataheight:"auto",modal:!1,overlay:30,drag:!0,resize:!0,url:"",mtype:"POST",reloadAfterSubmit:!0,beforeShowForm:null,beforeInitData:null,afterShowForm:null,beforeSubmit:null,onclickSubmit:null,afterSubmit:null,
-jqModal:!0,closeOnEscape:!1,delData:{},delicon:[],cancelicon:[],onClose:null,ajaxDelOptions:{},processing:!1,serializeDelData:null,useDataProxy:!1},a.jgrid.del,d||{});c[a(this)[0].p.id]=d;return this.each(function(){var e=this;if(e.grid&&u){var l=a.isFunction(c[e.p.id].beforeShowForm),r=a.isFunction(c[e.p.id].afterShowForm),t=a.isFunction(c[e.p.id].beforeInitData)?c[e.p.id].beforeInitData:!1,s=e.p.id,p={},g=!0,f="DelTbl_"+a.jgrid.jqID(s),n,w,b,m,h="DelTbl_"+s,k={themodal:"delmod"+s,modalhead:"delhd"+
-s,modalcontent:"delcnt"+s,scrollelm:f};jQuery.isArray(u)&&(u=u.join());if(null!==a("#"+a.jgrid.jqID(k.themodal)).html()){t&&(g=t.call(e,a("#"+f)),"undefined"==typeof g&&(g=!0));if(!1===g)return;a("#DelData>td","#"+f).text(u);a("#DelError","#"+f).hide();!0===c[e.p.id].processing&&(c[e.p.id].processing=!1,a("#dData","#"+f).removeClass("ui-state-active"));l&&c[e.p.id].beforeShowForm.call(e,a("#"+f));a.jgrid.viewModal("#"+a.jgrid.jqID(k.themodal),{gbox:"#gbox_"+a.jgrid.jqID(s),jqm:c[e.p.id].jqModal,jqM:!1,
-overlay:c[e.p.id].overlay,modal:c[e.p.id].modal})}else{var j=isNaN(c[e.p.id].dataheight)?c[e.p.id].dataheight:c[e.p.id].dataheight+"px",h="<div id='"+h+"' class='formdata' style='width:100%;overflow:auto;position:relative;height:"+j+";'><table class='DelTable'><tbody><tr id='DelError' style='display:none'><td class='ui-state-error'></td></tr>"+("<tr id='DelData' style='display:none'><td >"+u+"</td></tr>"),h=h+('<tr><td class="delmsg" style="white-space:pre;">'+c[e.p.id].msg+"</td></tr><tr><td >&#160;</td></tr>"),
-h=h+"</tbody></table></div>"+("<table cellspacing='0' cellpadding='0' border='0' class='EditTable' id='"+f+"_2'><tbody><tr><td><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr><td class='DelButton EditButton'>"+("<a href='javascript:void(0)' id='dData' class='fm-button ui-state-default ui-corner-all'>"+d.bSubmit+"</a>")+"&#160;"+("<a href='javascript:void(0)' id='eData' class='fm-button ui-state-default ui-corner-all'>"+d.bCancel+"</a>")+"</td></tr></tbody></table>");d.gbox="#gbox_"+
-a.jgrid.jqID(s);a.jgrid.createModal(k,h,d,"#gview_"+a.jgrid.jqID(e.p.id),a("#gview_"+a.jgrid.jqID(e.p.id))[0]);t&&(g=t.call(e,a("#"+f)),"undefined"==typeof g&&(g=!0));if(!1===g)return;a(".fm-button","#"+f+"_2").hover(function(){a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")});d.delicon=a.extend([!0,"left","ui-icon-scissors"],c[e.p.id].delicon);d.cancelicon=a.extend([!0,"left","ui-icon-cancel"],c[e.p.id].cancelicon);!0===d.delicon[0]&&a("#dData","#"+f+"_2").addClass("right"==
-d.delicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+d.delicon[2]+"'></span>");!0===d.cancelicon[0]&&a("#eData","#"+f+"_2").addClass("right"==d.cancelicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+d.cancelicon[2]+"'></span>");a("#dData","#"+f+"_2").click(function(){var g=[true,""];p={};var h=a("#DelData>td","#"+f).text();a.isFunction(c[e.p.id].onclickSubmit)&&(p=c[e.p.id].onclickSubmit.call(e,c[e.p.id],h)||{});a.isFunction(c[e.p.id].beforeSubmit)&&
-(g=c[e.p.id].beforeSubmit.call(e,h));if(g[0]&&!c[e.p.id].processing){c[e.p.id].processing=true;b=e.p.prmNames;n=a.extend({},c[e.p.id].delData,p);m=b.oper;n[m]=b.deloper;w=b.id;h=(""+h).split(",");if(!h.length)return false;for(var j in h)h.hasOwnProperty(j)&&(h[j]=a.jgrid.stripPref(e.p.idPrefix,h[j]));n[w]=h.join();a(this).addClass("ui-state-active");j=a.extend({url:c[e.p.id].url?c[e.p.id].url:a(e).jqGrid("getGridParam","editurl"),type:c[e.p.id].mtype,data:a.isFunction(c[e.p.id].serializeDelData)?
-c[e.p.id].serializeDelData.call(e,n):n,complete:function(b,j){if(j!="success"){g[0]=false;g[1]=a.isFunction(c[e.p.id].errorTextFormat)?c[e.p.id].errorTextFormat.call(e,b):j+" Status: '"+b.statusText+"'. Error code: "+b.status}else a.isFunction(c[e.p.id].afterSubmit)&&(g=c[e.p.id].afterSubmit.call(e,b,n));if(g[0]===false){a("#DelError>td","#"+f).html(g[1]);a("#DelError","#"+f).show()}else{if(c[e.p.id].reloadAfterSubmit&&e.p.datatype!="local")a(e).trigger("reloadGrid");else{if(e.p.treeGrid===true)try{a(e).jqGrid("delTreeNode",
-e.p.idPrefix+h[0])}catch(m){}else for(var l=0;l<h.length;l++)a(e).jqGrid("delRowData",e.p.idPrefix+h[l]);e.p.selrow=null;e.p.selarrrow=[]}a.isFunction(c[e.p.id].afterComplete)&&setTimeout(function(){c[e.p.id].afterComplete.call(e,b,h)},500)}c[e.p.id].processing=false;a("#dData","#"+f+"_2").removeClass("ui-state-active");g[0]&&a.jgrid.hideModal("#"+a.jgrid.jqID(k.themodal),{gb:"#gbox_"+a.jgrid.jqID(s),jqm:d.jqModal,onClose:c[e.p.id].onClose})}},a.jgrid.ajaxOptions,c[e.p.id].ajaxDelOptions);if(!j.url&&
-!c[e.p.id].useDataProxy)if(a.isFunction(e.p.dataProxy))c[e.p.id].useDataProxy=true;else{g[0]=false;g[1]=g[1]+(" "+a.jgrid.errors.nourl)}if(g[0])if(c[e.p.id].useDataProxy){j=e.p.dataProxy.call(e,j,"del_"+e.p.id);typeof j=="undefined"&&(j=[true,""]);if(j[0]===false){g[0]=false;g[1]=j[1]||"Error deleting the selected row!"}else a.jgrid.hideModal("#"+a.jgrid.jqID(k.themodal),{gb:"#gbox_"+a.jgrid.jqID(s),jqm:d.jqModal,onClose:c[e.p.id].onClose})}else a.ajax(j)}if(g[0]===false){a("#DelError>td","#"+f).html(g[1]);
-a("#DelError","#"+f).show()}return false});a("#eData","#"+f+"_2").click(function(){a.jgrid.hideModal("#"+a.jgrid.jqID(k.themodal),{gb:"#gbox_"+a.jgrid.jqID(s),jqm:c[e.p.id].jqModal,onClose:c[e.p.id].onClose});return false});l&&c[e.p.id].beforeShowForm.call(e,a("#"+f));a.jgrid.viewModal("#"+a.jgrid.jqID(k.themodal),{gbox:"#gbox_"+a.jgrid.jqID(s),jqm:c[e.p.id].jqModal,overlay:c[e.p.id].overlay,modal:c[e.p.id].modal})}r&&c[e.p.id].afterShowForm.call(e,a("#"+f));!0===c[e.p.id].closeOnEscape&&setTimeout(function(){a(".ui-jqdialog-titlebar-close",
-"#"+a.jgrid.jqID(k.modalhead)).focus()},0)}})},navGrid:function(c,d,e,l,r,t,s){d=a.extend({edit:!0,editicon:"ui-icon-pencil",add:!0,addicon:"ui-icon-plus",del:!0,delicon:"ui-icon-trash",search:!0,searchicon:"ui-icon-search",refresh:!0,refreshicon:"ui-icon-refresh",refreshstate:"firstpage",view:!1,viewicon:"ui-icon-document",position:"left",closeOnEscape:!0,beforeRefresh:null,afterRefresh:null,cloneToTop:!1,alertwidth:200,alertheight:"auto",alerttop:null,alertleft:null,alertzIndex:null},a.jgrid.nav,
-d||{});return this.each(function(){if(!this.nav){var p={themodal:"alertmod",modalhead:"alerthd",modalcontent:"alertcnt"},g=this,f;if(g.grid&&"string"==typeof c){null===a("#"+p.themodal).html()&&(!d.alerttop&&!d.alertleft&&("undefined"!=typeof window.innerWidth?(d.alertleft=window.innerWidth,d.alerttop=window.innerHeight):"undefined"!=typeof document.documentElement&&"undefined"!=typeof document.documentElement.clientWidth&&0!==document.documentElement.clientWidth?(d.alertleft=document.documentElement.clientWidth,
-d.alerttop=document.documentElement.clientHeight):(d.alertleft=1024,d.alerttop=768),d.alertleft=d.alertleft/2-parseInt(d.alertwidth,10)/2,d.alerttop=d.alerttop/2-25),a.jgrid.createModal(p,"<div>"+d.alerttext+"</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>",{gbox:"#gbox_"+a.jgrid.jqID(g.p.id),jqModal:!0,drag:!0,resize:!0,caption:d.alertcap,top:d.alerttop,left:d.alertleft,width:d.alertwidth,height:d.alertheight,closeOnEscape:d.closeOnEscape,zIndex:d.alertzIndex},"","",!0));
-var n=1;d.cloneToTop&&g.p.toppager&&(n=2);for(var w=0;w<n;w++){var b=a("<table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table navtable' style='float:left;table-layout:auto;'><tbody><tr></tr></tbody></table>"),m,h;0===w?(m=c,h=g.p.id,m==g.p.toppager&&(h+="_top",n=1)):(m=g.p.toppager,h=g.p.id+"_top");"rtl"==g.p.direction&&a(b).attr("dir","rtl").css("float","right");d.add&&(l=l||{},f=a("<td class='ui-pg-button ui-corner-all'></td>"),a(f).append("<div class='ui-pg-div'><span class='ui-icon "+
-d.addicon+"'></span>"+d.addtext+"</div>"),a("tr",b).append(f),a(f,b).attr({title:d.addtitle||"",id:l.id||"add_"+h}).click(function(){a(this).hasClass("ui-state-disabled")||(a.isFunction(d.addfunc)?d.addfunc.call(g):a(g).jqGrid("editGridRow","new",l));return false}).hover(function(){a(this).hasClass("ui-state-disabled")||a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")}),f=null);d.edit&&(f=a("<td class='ui-pg-button ui-corner-all'></td>"),e=e||{},a(f).append("<div class='ui-pg-div'><span class='ui-icon "+
-d.editicon+"'></span>"+d.edittext+"</div>"),a("tr",b).append(f),a(f,b).attr({title:d.edittitle||"",id:e.id||"edit_"+h}).click(function(){if(!a(this).hasClass("ui-state-disabled")){var b=g.p.selrow;if(b)a.isFunction(d.editfunc)?d.editfunc.call(g,b):a(g).jqGrid("editGridRow",b,e);else{a.jgrid.viewModal("#"+p.themodal,{gbox:"#gbox_"+a.jgrid.jqID(g.p.id),jqm:true});a("#jqg_alrt").focus()}}return false}).hover(function(){a(this).hasClass("ui-state-disabled")||a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")}),
-f=null);d.view&&(f=a("<td class='ui-pg-button ui-corner-all'></td>"),s=s||{},a(f).append("<div class='ui-pg-div'><span class='ui-icon "+d.viewicon+"'></span>"+d.viewtext+"</div>"),a("tr",b).append(f),a(f,b).attr({title:d.viewtitle||"",id:s.id||"view_"+h}).click(function(){if(!a(this).hasClass("ui-state-disabled")){var b=g.p.selrow;if(b)a.isFunction(d.viewfunc)?d.viewfunc.call(g,b):a(g).jqGrid("viewGridRow",b,s);else{a.jgrid.viewModal("#"+p.themodal,{gbox:"#gbox_"+a.jgrid.jqID(g.p.id),jqm:true});a("#jqg_alrt").focus()}}return false}).hover(function(){a(this).hasClass("ui-state-disabled")||
-a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")}),f=null);d.del&&(f=a("<td class='ui-pg-button ui-corner-all'></td>"),r=r||{},a(f).append("<div class='ui-pg-div'><span class='ui-icon "+d.delicon+"'></span>"+d.deltext+"</div>"),a("tr",b).append(f),a(f,b).attr({title:d.deltitle||"",id:r.id||"del_"+h}).click(function(){if(!a(this).hasClass("ui-state-disabled")){var b;if(g.p.multiselect){b=g.p.selarrrow;b.length===0&&(b=null)}else b=g.p.selrow;if(b)a.isFunction(d.delfunc)?
-d.delfunc.call(g,b):a(g).jqGrid("delGridRow",b,r);else{a.jgrid.viewModal("#"+p.themodal,{gbox:"#gbox_"+a.jgrid.jqID(g.p.id),jqm:true});a("#jqg_alrt").focus()}}return false}).hover(function(){a(this).hasClass("ui-state-disabled")||a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")}),f=null);(d.add||d.edit||d.del||d.view)&&a("tr",b).append("<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>");d.search&&(f=a("<td class='ui-pg-button ui-corner-all'></td>"),
-t=t||{},a(f).append("<div class='ui-pg-div'><span class='ui-icon "+d.searchicon+"'></span>"+d.searchtext+"</div>"),a("tr",b).append(f),a(f,b).attr({title:d.searchtitle||"",id:t.id||"search_"+h}).click(function(){a(this).hasClass("ui-state-disabled")||(a.isFunction(d.searchfunc)?d.searchfunc.call(g,t):a(g).jqGrid("searchGrid",t));return false}).hover(function(){a(this).hasClass("ui-state-disabled")||a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")}),t.showOnLoad&&
-!0===t.showOnLoad&&a(f,b).click(),f=null);d.refresh&&(f=a("<td class='ui-pg-button ui-corner-all'></td>"),a(f).append("<div class='ui-pg-div'><span class='ui-icon "+d.refreshicon+"'></span>"+d.refreshtext+"</div>"),a("tr",b).append(f),a(f,b).attr({title:d.refreshtitle||"",id:"refresh_"+h}).click(function(){if(!a(this).hasClass("ui-state-disabled")){a.isFunction(d.beforeRefresh)&&d.beforeRefresh.call(g);g.p.search=false;try{var b=g.p.id;g.p.postData.filters="";a("#fbox_"+a.jgrid.jqID(b)).jqFilter("resetFilter");
-a.isFunction(g.clearToolbar)&&g.clearToolbar.call(g,false)}catch(c){}switch(d.refreshstate){case "firstpage":a(g).trigger("reloadGrid",[{page:1}]);break;case "current":a(g).trigger("reloadGrid",[{current:true}])}a.isFunction(d.afterRefresh)&&d.afterRefresh.call(g)}return false}).hover(function(){a(this).hasClass("ui-state-disabled")||a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")}),f=null);f=a(".ui-jqgrid").css("font-size")||"11px";a("body").append("<div id='testpg2' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:"+
-f+";visibility:hidden;' ></div>");f=a(b).clone().appendTo("#testpg2").width();a("#testpg2").remove();a(m+"_"+d.position,m).append(b);g.p._nvtd&&(f>g.p._nvtd[0]&&(a(m+"_"+d.position,m).width(f),g.p._nvtd[0]=f),g.p._nvtd[1]=f);b=f=f=null;this.nav=!0}}}})},navButtonAdd:function(c,d){d=a.extend({caption:"newButton",title:"",buttonicon:"ui-icon-newwin",onClickButton:null,position:"last",cursor:"pointer"},d||{});return this.each(function(){if(this.grid){"string"===typeof c&&0!==c.indexOf("#")&&(c="#"+a.jgrid.jqID(c));
-var e=a(".navtable",c)[0],l=this;if(e&&!(d.id&&null!==a("#"+a.jgrid.jqID(d.id),e).html())){var r=a("<td></td>");"NONE"==d.buttonicon.toString().toUpperCase()?a(r).addClass("ui-pg-button ui-corner-all").append("<div class='ui-pg-div'>"+d.caption+"</div>"):a(r).addClass("ui-pg-button ui-corner-all").append("<div class='ui-pg-div'><span class='ui-icon "+d.buttonicon+"'></span>"+d.caption+"</div>");d.id&&a(r).attr("id",d.id);"first"==d.position?0===e.rows[0].cells.length?a("tr",e).append(r):a("tr td:eq(0)",
-e).before(r):a("tr",e).append(r);a(r,e).attr("title",d.title||"").click(function(c){a(this).hasClass("ui-state-disabled")||a.isFunction(d.onClickButton)&&d.onClickButton.call(l,c);return!1}).hover(function(){a(this).hasClass("ui-state-disabled")||a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")})}}})},navSeparatorAdd:function(c,d){d=a.extend({sepclass:"ui-separator",sepcontent:""},d||{});return this.each(function(){if(this.grid){"string"===typeof c&&0!==c.indexOf("#")&&
-(c="#"+a.jgrid.jqID(c));var e=a(".navtable",c)[0];if(e){var l="<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='"+d.sepclass+"'></span>"+d.sepcontent+"</td>";a("tr",e).append(l)}}})},GridToForm:function(c,d){return this.each(function(){var e=this;if(e.grid){var l=a(e).jqGrid("getRowData",c);if(l)for(var r in l)a("[name="+a.jgrid.jqID(r)+"]",d).is("input:radio")||a("[name="+a.jgrid.jqID(r)+"]",d).is("input:checkbox")?a("[name="+a.jgrid.jqID(r)+"]",d).each(function(){if(a(this).val()==
-l[r])a(this)[e.p.useProp?"prop":"attr"]("checked",!0);else a(this)[e.p.useProp?"prop":"attr"]("checked",!1)}):a("[name="+a.jgrid.jqID(r)+"]",d).val(l[r])}})},FormToGrid:function(c,d,e,l){return this.each(function(){if(this.grid){e||(e="set");l||(l="first");var r=a(d).serializeArray(),t={};a.each(r,function(a,c){t[c.name]=c.value});"add"==e?a(this).jqGrid("addRowData",c,t,l):"set"==e&&a(this).jqGrid("setRowData",c,t)}})}})})(jQuery);
-(function(a){a.fn.jqFilter=function(d){if("string"===typeof d){var n=a.fn.jqFilter[d];if(!n)throw"jqFilter - No such method: "+d;var u=a.makeArray(arguments).slice(1);return n.apply(this,u)}var o=a.extend(!0,{filter:null,columns:[],onChange:null,afterRedraw:null,checkValues:null,error:!1,errmsg:"",errorcheck:!0,showQuery:!0,sopt:null,ops:[{name:"eq",description:"equal",operator:"="},{name:"ne",description:"not equal",operator:"<>"},{name:"lt",description:"less",operator:"<"},{name:"le",description:"less or equal",
-operator:"<="},{name:"gt",description:"greater",operator:">"},{name:"ge",description:"greater or equal",operator:">="},{name:"bw",description:"begins with",operator:"LIKE"},{name:"bn",description:"does not begin with",operator:"NOT LIKE"},{name:"in",description:"in",operator:"IN"},{name:"ni",description:"not in",operator:"NOT IN"},{name:"ew",description:"ends with",operator:"LIKE"},{name:"en",description:"does not end with",operator:"NOT LIKE"},{name:"cn",description:"contains",operator:"LIKE"},{name:"nc",
-description:"does not contain",operator:"NOT LIKE"},{name:"nu",description:"is null",operator:"IS NULL"},{name:"nn",description:"is not null",operator:"IS NOT NULL"}],numopts:"eq ne lt le gt ge nu nn in ni".split(" "),stropts:"eq ne bw bn ew en cn nc nu nn in ni".split(" "),_gridsopt:[],groupOps:[{op:"AND",text:"AND"},{op:"OR",text:"OR"}],groupButton:!0,ruleButtons:!0,direction:"ltr"},a.jgrid.filter,d||{});return this.each(function(){if(!this.filter){this.p=o;if(null===this.p.filter||void 0===this.p.filter)this.p.filter=
-{groupOp:this.p.groupOps[0].op,rules:[],groups:[]};var d,n=this.p.columns.length,f,t=/msie/i.test(navigator.userAgent)&&!window.opera;if(this.p._gridsopt.length)for(d=0;d<this.p._gridsopt.length;d++)this.p.ops[d].description=this.p._gridsopt[d];this.p.initFilter=a.extend(!0,{},this.p.filter);if(n){for(d=0;d<n;d++)if(f=this.p.columns[d],f.stype?f.inputtype=f.stype:f.inputtype||(f.inputtype="text"),f.sorttype?f.searchtype=f.sorttype:f.searchtype||(f.searchtype="string"),void 0===f.hidden&&(f.hidden=
-!1),f.label||(f.label=f.name),f.index&&(f.name=f.index),f.hasOwnProperty("searchoptions")||(f.searchoptions={}),!f.hasOwnProperty("searchrules"))f.searchrules={};this.p.showQuery&&a(this).append("<table class='queryresult ui-widget ui-widget-content' style='display:block;max-width:440px;border:0px none;' dir='"+this.p.direction+"'><tbody><tr><td class='query'></td></tr></tbody></table>");var r=function(g,k){var b=[!0,""];if(a.isFunction(k.searchrules))b=k.searchrules(g,k);else if(a.jgrid&&a.jgrid.checkValues)try{b=
-a.jgrid.checkValues(g,-1,null,k.searchrules,k.label)}catch(c){}b&&(b.length&&!1===b[0])&&(o.error=!b[0],o.errmsg=b[1])};this.onchange=function(){this.p.error=!1;this.p.errmsg="";return a.isFunction(this.p.onChange)?this.p.onChange.call(this,this.p):!1};this.reDraw=function(){a("table.group:first",this).remove();var g=this.createTableForGroup(o.filter,null);a(this).append(g);a.isFunction(this.p.afterRedraw)&&this.p.afterRedraw.call(this,this.p)};this.createTableForGroup=function(g,k){var b=this,c,
-e=a("<table class='group ui-widget ui-widget-content' style='border:0px none;'><tbody></tbody></table>"),d="left";"rtl"==this.p.direction&&(d="right",e.attr("dir","rtl"));null===k&&e.append("<tr class='error' style='display:none;'><th colspan='5' class='ui-state-error' align='"+d+"'></th></tr>");var h=a("<tr></tr>");e.append(h);d=a("<th colspan='5' align='"+d+"'></th>");h.append(d);if(!0===this.p.ruleButtons){var i=a("<select class='opsel'></select>");d.append(i);var h="",f;for(c=0;c<o.groupOps.length;c++)f=
-g.groupOp===b.p.groupOps[c].op?" selected='selected'":"",h+="<option value='"+b.p.groupOps[c].op+"'"+f+">"+b.p.groupOps[c].text+"</option>";i.append(h).bind("change",function(){g.groupOp=a(i).val();b.onchange()})}h="<span></span>";this.p.groupButton&&(h=a("<input type='button' value='+ {}' title='Add subgroup' class='add-group'/>"),h.bind("click",function(){if(g.groups===void 0)g.groups=[];g.groups.push({groupOp:o.groupOps[0].op,rules:[],groups:[]});b.reDraw();b.onchange();return false}));d.append(h);
-if(!0===this.p.ruleButtons){var h=a("<input type='button' value='+' title='Add rule' class='add-rule ui-add'/>"),l;h.bind("click",function(){if(g.rules===void 0)g.rules=[];for(c=0;c<b.p.columns.length;c++){var a=typeof b.p.columns[c].search==="undefined"?true:b.p.columns[c].search,e=b.p.columns[c].hidden===true;if(b.p.columns[c].searchoptions.searchhidden===true&&a||a&&!e){l=b.p.columns[c];break}}g.rules.push({field:l.name,op:(l.searchoptions.sopt?l.searchoptions.sopt:b.p.sopt?b.p.sopt:l.searchtype===
-"string"?b.p.stropts:b.p.numopts)[0],data:""});b.reDraw();return false});d.append(h)}null!==k&&(h=a("<input type='button' value='-' title='Delete group' class='delete-group'/>"),d.append(h),h.bind("click",function(){for(c=0;c<k.groups.length;c++)if(k.groups[c]===g){k.groups.splice(c,1);break}b.reDraw();b.onchange();return false}));if(void 0!==g.groups)for(c=0;c<g.groups.length;c++)d=a("<tr></tr>"),e.append(d),h=a("<td class='first'></td>"),d.append(h),h=a("<td colspan='4'></td>"),h.append(this.createTableForGroup(g.groups[c],
-g)),d.append(h);void 0===g.groupOp&&(g.groupOp=b.p.groupOps[0].op);if(void 0!==g.rules)for(c=0;c<g.rules.length;c++)e.append(this.createTableRowForRule(g.rules[c],g));return e};this.createTableRowForRule=function(g,d){var b=this,c=a("<tr></tr>"),e,f,h,i,j="",l;c.append("<td class='first'></td>");var m=a("<td class='columns'></td>");c.append(m);var n=a("<select></select>"),p,q=[];m.append(n);n.bind("change",function(){g.field=a(n).val();h=a(this).parents("tr:first");for(e=0;e<b.p.columns.length;e++)if(b.p.columns[e].name===
-g.field){i=b.p.columns[e];break}if(i){i.searchoptions.id=a.jgrid.randId();t&&"text"===i.inputtype&&!i.searchoptions.size&&(i.searchoptions.size=10);var c=a.jgrid.createEl(i.inputtype,i.searchoptions,"",!0,b.p.ajaxSelectOptions,!0);a(c).addClass("input-elm");f=i.searchoptions.sopt?i.searchoptions.sopt:b.p.sopt?b.p.sopt:"string"===i.searchtype?b.p.stropts:b.p.numopts;var d="",k=0;q=[];a.each(b.p.ops,function(){q.push(this.name)});for(e=0;e<f.length;e++)p=a.inArray(f[e],q),-1!==p&&(0===k&&(g.op=b.p.ops[p].name),
-d+="<option value='"+b.p.ops[p].name+"'>"+b.p.ops[p].description+"</option>",k++);a(".selectopts",h).empty().append(d);a(".selectopts",h)[0].selectedIndex=0;a.browser.msie&&9>a.browser.version&&(d=parseInt(a("select.selectopts",h)[0].offsetWidth)+1,a(".selectopts",h).width(d),a(".selectopts",h).css("width","auto"));a(".data",h).empty().append(c);a(".input-elm",h).bind("change",function(c){var d=a(this).hasClass("ui-autocomplete-input")?200:0;setTimeout(function(){var d=c.target;g.data=d.nodeName.toUpperCase()===
-"SPAN"&&i.searchoptions&&a.isFunction(i.searchoptions.custom_value)?i.searchoptions.custom_value(a(d).children(".customelement:first"),"get"):d.value;b.onchange()},d)});setTimeout(function(){g.data=a(c).val();b.onchange()},0)}});for(e=m=0;e<b.p.columns.length;e++){l="undefined"===typeof b.p.columns[e].search?!0:b.p.columns[e].search;var r=!0===b.p.columns[e].hidden;if(!0===b.p.columns[e].searchoptions.searchhidden&&l||l&&!r)l="",g.field===b.p.columns[e].name&&(l=" selected='selected'",m=e),j+="<option value='"+
-b.p.columns[e].name+"'"+l+">"+b.p.columns[e].label+"</option>"}n.append(j);j=a("<td class='operators'></td>");c.append(j);i=o.columns[m];i.searchoptions.id=a.jgrid.randId();t&&"text"===i.inputtype&&!i.searchoptions.size&&(i.searchoptions.size=10);var m=a.jgrid.createEl(i.inputtype,i.searchoptions,g.data,!0,b.p.ajaxSelectOptions,!0),s=a("<select class='selectopts'></select>");j.append(s);s.bind("change",function(){g.op=a(s).val();h=a(this).parents("tr:first");var c=a(".input-elm",h)[0];if(g.op==="nu"||
-g.op==="nn"){g.data="";c.value="";c.setAttribute("readonly","true");c.setAttribute("disabled","true")}else{c.removeAttribute("readonly");c.removeAttribute("disabled")}b.onchange()});f=i.searchoptions.sopt?i.searchoptions.sopt:b.p.sopt?b.p.sopt:"string"===i.searchtype?o.stropts:b.p.numopts;j="";a.each(b.p.ops,function(){q.push(this.name)});for(e=0;e<f.length;e++)p=a.inArray(f[e],q),-1!==p&&(l=g.op===b.p.ops[p].name?" selected='selected'":"",j+="<option value='"+b.p.ops[p].name+"'"+l+">"+b.p.ops[p].description+
-"</option>");s.append(j);j=a("<td class='data'></td>");c.append(j);j.append(m);a(m).addClass("input-elm").bind("change",function(){g.data=i.inputtype==="custom"?i.searchoptions.custom_value(a(this).children(".customelement:first"),"get"):a(this).val();b.onchange()});j=a("<td></td>");c.append(j);!0===this.p.ruleButtons&&(m=a("<input type='button' value='-' title='Delete rule' class='delete-rule ui-del'/>"),j.append(m),m.bind("click",function(){for(e=0;e<d.rules.length;e++)if(d.rules[e]===g){d.rules.splice(e,
-1);break}b.reDraw();b.onchange();return false}));return c};this.getStringForGroup=function(a){var d="(",b;if(void 0!==a.groups)for(b=0;b<a.groups.length;b++){1<d.length&&(d+=" "+a.groupOp+" ");try{d+=this.getStringForGroup(a.groups[b])}catch(c){alert(c)}}if(void 0!==a.rules)try{for(b=0;b<a.rules.length;b++)1<d.length&&(d+=" "+a.groupOp+" "),d+=this.getStringForRule(a.rules[b])}catch(e){alert(e)}d+=")";return"()"===d?"":d};this.getStringForRule=function(d){var f="",b="",c,e;for(c=0;c<this.p.ops.length;c++)if(this.p.ops[c].name===
-d.op){f=this.p.ops[c].operator;b=this.p.ops[c].name;break}for(c=0;c<this.p.columns.length;c++)if(this.p.columns[c].name===d.field){e=this.p.columns[c];break}c=d.data;if("bw"===b||"bn"===b)c+="%";if("ew"===b||"en"===b)c="%"+c;if("cn"===b||"nc"===b)c="%"+c+"%";if("in"===b||"ni"===b)c=" ("+c+")";o.errorcheck&&r(d.data,e);return-1!==a.inArray(e.searchtype,["int","integer","float","number","currency"])||"nn"===b||"nu"===b?d.field+" "+f+" "+c:d.field+" "+f+' "'+c+'"'};this.resetFilter=function(){this.p.filter=
-a.extend(!0,{},this.p.initFilter);this.reDraw();this.onchange()};this.hideError=function(){a("th.ui-state-error",this).html("");a("tr.error",this).hide()};this.showError=function(){a("th.ui-state-error",this).html(this.p.errmsg);a("tr.error",this).show()};this.toUserFriendlyString=function(){return this.getStringForGroup(o.filter)};this.toString=function(){function a(b){var c="(",e;if(void 0!==b.groups)for(e=0;e<b.groups.length;e++)1<c.length&&(c="OR"===b.groupOp?c+" || ":c+" && "),c+=a(b.groups[e]);
-if(void 0!==b.rules)for(e=0;e<b.rules.length;e++){1<c.length&&(c="OR"===b.groupOp?c+" || ":c+" && ");var f=b.rules[e];if(d.p.errorcheck){for(var h=void 0,i=void 0,h=0;h<d.p.columns.length;h++)if(d.p.columns[h].name===f.field){i=d.p.columns[h];break}i&&r(f.data,i)}c+=f.op+"(item."+f.field+",'"+f.data+"')"}c+=")";return"()"===c?"":c}var d=this;return a(this.p.filter)};this.reDraw();if(this.p.showQuery)this.onchange();this.filter=!0}}})};a.extend(a.fn.jqFilter,{toSQLString:function(){var a="";this.each(function(){a=
-this.toUserFriendlyString()});return a},filterData:function(){var a;this.each(function(){a=this.p.filter});return a},getParameter:function(a){return void 0!==a&&this.p.hasOwnProperty(a)?this.p[a]:this.p},resetFilter:function(){return this.each(function(){this.resetFilter()})},addFilter:function(a){"string"===typeof a&&(a=jQuery.jgrid.parse(a));this.each(function(){this.p.filter=a;this.reDraw();this.onchange()})}})})(jQuery);
-(function(b){b.browser.msie&&8==b.browser.version&&(b.expr[":"].hidden=function(b){return 0===b.offsetWidth||0===b.offsetHeight||"none"==b.style.display});b.jgrid._multiselect=!1;if(b.ui&&b.ui.multiselect){if(b.ui.multiselect.prototype._setSelected){var m=b.ui.multiselect.prototype._setSelected;b.ui.multiselect.prototype._setSelected=function(a,e){var c=m.call(this,a,e);if(e&&this.selectedList){var d=this.element;this.selectedList.find("li").each(function(){b(this).data("optionLink")&&b(this).data("optionLink").remove().appendTo(d)})}return c}}b.ui.multiselect.prototype.destroy&&
-(b.ui.multiselect.prototype.destroy=function(){this.element.show();this.container.remove();b.Widget===void 0?b.widget.prototype.destroy.apply(this,arguments):b.Widget.prototype.destroy.apply(this,arguments)});b.jgrid._multiselect=!0}b.jgrid.extend({sortableColumns:function(a){return this.each(function(){function e(){c.p.disableClick=true}var c=this,d=b.jgrid.jqID(c.p.id),d={tolerance:"pointer",axis:"x",scrollSensitivity:"1",items:">th:not(:has(#jqgh_"+d+"_cb,#jqgh_"+d+"_rn,#jqgh_"+d+"_subgrid),:hidden)",
-placeholder:{element:function(a){return b(document.createElement(a[0].nodeName)).addClass(a[0].className+" ui-sortable-placeholder ui-state-highlight").removeClass("ui-sortable-helper")[0]},update:function(b,a){a.height(b.currentItem.innerHeight()-parseInt(b.currentItem.css("paddingTop")||0,10)-parseInt(b.currentItem.css("paddingBottom")||0,10));a.width(b.currentItem.innerWidth()-parseInt(b.currentItem.css("paddingLeft")||0,10)-parseInt(b.currentItem.css("paddingRight")||0,10))}},update:function(a,
-g){var d=b(g.item).parent(),d=b(">th",d),e={},i=c.p.id+"_";b.each(c.p.colModel,function(b){e[this.name]=b});var h=[];d.each(function(){var a=b(">div",this).get(0).id.replace(/^jqgh_/,"").replace(i,"");a in e&&h.push(e[a])});b(c).jqGrid("remapColumns",h,true,true);b.isFunction(c.p.sortable.update)&&c.p.sortable.update(h);setTimeout(function(){c.p.disableClick=false},50)}};if(c.p.sortable.options)b.extend(d,c.p.sortable.options);else if(b.isFunction(c.p.sortable))c.p.sortable={update:c.p.sortable};
-if(d.start){var g=d.start;d.start=function(b,a){e();g.call(this,b,a)}}else d.start=e;if(c.p.sortable.exclude)d.items=d.items+(":not("+c.p.sortable.exclude+")");a.sortable(d).data("sortable").floating=true})},columnChooser:function(a){function e(a,c){a&&(typeof a=="string"?b.fn[a]&&b.fn[a].apply(c,b.makeArray(arguments).slice(2)):b.isFunction(a)&&a.apply(c,b.makeArray(arguments).slice(2)))}var c=this;if(!b("#colchooser_"+b.jgrid.jqID(c[0].p.id)).length){var d=b('<div id="colchooser_'+c[0].p.id+'" style="position:relative;overflow:hidden"><div><select multiple="multiple"></select></div></div>'),
-g=b("select",d),a=b.extend({width:420,height:240,classname:null,done:function(b){b&&c.jqGrid("remapColumns",b,true)},msel:"multiselect",dlog:"dialog",dialog_opts:{minWidth:470},dlog_opts:function(a){var c={};c[a.bSubmit]=function(){a.apply_perm();a.cleanup(false)};c[a.bCancel]=function(){a.cleanup(true)};return b.extend(true,{buttons:c,close:function(){a.cleanup(true)},modal:a.modal?a.modal:false,resizable:a.resizable?a.resizable:true,width:a.width+20},a.dialog_opts||{})},apply_perm:function(){b("option",
-g).each(function(){this.selected?c.jqGrid("showCol",k[this.value].name):c.jqGrid("hideCol",k[this.value].name)});var d=[];b("option:selected",g).each(function(){d.push(parseInt(this.value,10))});b.each(d,function(){delete f[k[parseInt(this,10)].name]});b.each(f,function(){var b=parseInt(this,10);var a=d,c=b;if(c>=0){var g=a.slice(),e=g.splice(c,Math.max(a.length-c,c));if(c>a.length)c=a.length;g[c]=b;d=g.concat(e)}else d=void 0});a.done&&a.done.call(c,d)},cleanup:function(b){e(a.dlog,d,"destroy");
-e(a.msel,g,"destroy");d.remove();b&&a.done&&a.done.call(c)},msel_opts:{}},b.jgrid.col,a||{});if(b.ui&&b.ui.multiselect&&a.msel=="multiselect"){if(!b.jgrid._multiselect){alert("Multiselect plugin loaded after jqGrid. Please load the plugin before the jqGrid!");return}a.msel_opts=b.extend(b.ui.multiselect.defaults,a.msel_opts)}a.caption&&d.attr("title",a.caption);if(a.classname){d.addClass(a.classname);g.addClass(a.classname)}if(a.width){b(">div",d).css({width:a.width,margin:"0 auto"});g.css("width",
-a.width)}if(a.height){b(">div",d).css("height",a.height);g.css("height",a.height-10)}var k=c.jqGrid("getGridParam","colModel"),p=c.jqGrid("getGridParam","colNames"),f={},j=[];g.empty();b.each(k,function(b){f[this.name]=b;this.hidedlg?this.hidden||j.push(b):g.append("<option value='"+b+"' "+(this.hidden?"":"selected='selected'")+">"+jQuery.jgrid.stripHtml(p[b])+"</option>")});var i=b.isFunction(a.dlog_opts)?a.dlog_opts.call(c,a):a.dlog_opts;e(a.dlog,d,i);i=b.isFunction(a.msel_opts)?a.msel_opts.call(c,
-a):a.msel_opts;e(a.msel,g,i)}},sortableRows:function(a){return this.each(function(){var e=this;if(e.grid&&!e.p.treeGrid&&b.fn.sortable){a=b.extend({cursor:"move",axis:"y",items:".jqgrow"},a||{});if(a.start&&b.isFunction(a.start)){a._start_=a.start;delete a.start}else a._start_=false;if(a.update&&b.isFunction(a.update)){a._update_=a.update;delete a.update}else a._update_=false;a.start=function(c,d){b(d.item).css("border-width","0px");b("td",d.item).each(function(b){this.style.width=e.grid.cols[b].style.width});
-if(e.p.subGrid){var g=b(d.item).attr("id");try{b(e).jqGrid("collapseSubGridRow",g)}catch(k){}}a._start_&&a._start_.apply(this,[c,d])};a.update=function(c,d){b(d.item).css("border-width","");e.p.rownumbers===true&&b("td.jqgrid-rownum",e.rows).each(function(a){b(this).html(a+1+(parseInt(e.p.page,10)-1)*parseInt(e.p.rowNum,10))});a._update_&&a._update_.apply(this,[c,d])};b("tbody:first",e).sortable(a);b("tbody:first",e).disableSelection()}})},gridDnD:function(a){return this.each(function(){function e(){var a=
-b.data(c,"dnd");b("tr.jqgrow:not(.ui-draggable)",c).draggable(b.isFunction(a.drag)?a.drag.call(b(c),a):a.drag)}var c=this;if(c.grid&&!c.p.treeGrid&&b.fn.draggable&&b.fn.droppable){b("#jqgrid_dnd").html()===null&&b("body").append("<table id='jqgrid_dnd' class='ui-jqgrid-dnd'></table>");if(typeof a=="string"&&a=="updateDnD"&&c.p.jqgdnd===true)e();else{a=b.extend({drag:function(a){return b.extend({start:function(d,e){if(c.p.subGrid){var f=b(e.helper).attr("id");try{b(c).jqGrid("collapseSubGridRow",f)}catch(j){}}for(f=
-0;f<b.data(c,"dnd").connectWith.length;f++)b(b.data(c,"dnd").connectWith[f]).jqGrid("getGridParam","reccount")=="0"&&b(b.data(c,"dnd").connectWith[f]).jqGrid("addRowData","jqg_empty_row",{});e.helper.addClass("ui-state-highlight");b("td",e.helper).each(function(b){this.style.width=c.grid.headers[b].width+"px"});a.onstart&&b.isFunction(a.onstart)&&a.onstart.call(b(c),d,e)},stop:function(d,e){if(e.helper.dropped&&!a.dragcopy){var f=b(e.helper).attr("id");f===void 0&&(f=b(this).attr("id"));b(c).jqGrid("delRowData",
-f)}for(f=0;f<b.data(c,"dnd").connectWith.length;f++)b(b.data(c,"dnd").connectWith[f]).jqGrid("delRowData","jqg_empty_row");a.onstop&&b.isFunction(a.onstop)&&a.onstop.call(b(c),d,e)}},a.drag_opts||{})},drop:function(a){return b.extend({accept:function(a){if(!b(a).hasClass("jqgrow"))return a;a=b(a).closest("table.ui-jqgrid-btable");if(a.length>0&&b.data(a[0],"dnd")!==void 0){a=b.data(a[0],"dnd").connectWith;return b.inArray("#"+b.jgrid.jqID(this.id),a)!=-1?true:false}return false},drop:function(d,e){if(b(e.draggable).hasClass("jqgrow")){var f=
-b(e.draggable).attr("id"),f=e.draggable.parent().parent().jqGrid("getRowData",f);if(!a.dropbyname){var j=0,i={},h,n=b("#"+b.jgrid.jqID(this.id)).jqGrid("getGridParam","colModel");try{for(var o in f){h=n[j].name;h=="cb"||(h=="rn"||h=="subgrid")||f.hasOwnProperty(o)&&n[j]&&(i[h]=f[o]);j++}f=i}catch(m){}}e.helper.dropped=true;if(a.beforedrop&&b.isFunction(a.beforedrop)){h=a.beforedrop.call(this,d,e,f,b("#"+b.jgrid.jqID(c.p.id)),b(this));typeof h!="undefined"&&(h!==null&&typeof h=="object")&&(f=h)}if(e.helper.dropped){var l;
-if(a.autoid)if(b.isFunction(a.autoid))l=a.autoid.call(this,f);else{l=Math.ceil(Math.random()*1E3);l=a.autoidprefix+l}b("#"+b.jgrid.jqID(this.id)).jqGrid("addRowData",l,f,a.droppos)}a.ondrop&&b.isFunction(a.ondrop)&&a.ondrop.call(this,d,e,f)}}},a.drop_opts||{})},onstart:null,onstop:null,beforedrop:null,ondrop:null,drop_opts:{activeClass:"ui-state-active",hoverClass:"ui-state-hover"},drag_opts:{revert:"invalid",helper:"clone",cursor:"move",appendTo:"#jqgrid_dnd",zIndex:5E3},dragcopy:false,dropbyname:false,
-droppos:"first",autoid:true,autoidprefix:"dnd_"},a||{});if(a.connectWith){a.connectWith=a.connectWith.split(",");a.connectWith=b.map(a.connectWith,function(a){return b.trim(a)});b.data(c,"dnd",a);c.p.reccount!="0"&&!c.p.jqgdnd&&e();c.p.jqgdnd=true;for(var d=0;d<a.connectWith.length;d++)b(a.connectWith[d]).droppable(b.isFunction(a.drop)?a.drop.call(b(c),a):a.drop)}}}})},gridResize:function(a){return this.each(function(){var e=this,c=b.jgrid.jqID(e.p.id);if(e.grid&&b.fn.resizable){a=b.extend({},a||
-{});if(a.alsoResize){a._alsoResize_=a.alsoResize;delete a.alsoResize}else a._alsoResize_=false;if(a.stop&&b.isFunction(a.stop)){a._stop_=a.stop;delete a.stop}else a._stop_=false;a.stop=function(d,g){b(e).jqGrid("setGridParam",{height:b("#gview_"+c+" .ui-jqgrid-bdiv").height()});b(e).jqGrid("setGridWidth",g.size.width,a.shrinkToFit);a._stop_&&a._stop_.call(e,d,g)};a.alsoResize=a._alsoResize_?eval("("+("{'#gview_"+c+" .ui-jqgrid-bdiv':true,'"+a._alsoResize_+"':true}")+")"):b(".ui-jqgrid-bdiv","#gview_"+
-c);delete a._alsoResize_;b("#gbox_"+c).resizable(a)}})}})})(jQuery);
+ * jqGrid  4.4.0 - jQuery Grid 
+ * Copyright (c) 2008, Tony Tomov, tony@trirand.com 
+ * Dual licensed under the MIT and GPL licenses 
+ * http://www.opensource.org/licenses/mit-license.php 
+ * http://www.gnu.org/licenses/gpl-2.0.html 
+ * Date:2012-06-14 
+ * Modules: grid.base.js; grid.common.js; grid.formedit.js; grid.filter.js; grid.jqueryui.js; 
+ */
+(function (b) {
+    b.jgrid = b.jgrid || {};
+    b.extend(b.jgrid, {version: "4.4.0", htmlDecode: function (b) {
+        return b && ("&nbsp;" == b || "&#160;" == b || 1 === b.length && 160 === b.charCodeAt(0)) ? "" : !b ? b : ("" + b).replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"').replace(/&amp;/g, "&")
+    }, htmlEncode: function (b) {
+        return!b ? b : ("" + b).replace(/&/g, "&amp;").replace(/\"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
+    }, format: function (f) {
+        var e = b.makeArray(arguments).slice(1);
+        void 0 === f && (f = "");
+        return f.replace(/\{(\d+)\}/g,
+            function (b, d) {
+                return e[d]
+            })
+    }, getCellIndex: function (f) {
+        f = b(f);
+        if (f.is("tr"))return-1;
+        f = (!f.is("td") && !f.is("th") ? f.closest("td,th") : f)[0];
+        return b.browser.msie ? b.inArray(f, f.parentNode.cells) : f.cellIndex
+    }, stripHtml: function (b) {
+        var b = b + "", e = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
+        return b ? (b = b.replace(e, "")) && "&nbsp;" !== b && "&#160;" !== b ? b.replace(/\"/g, "'") : "" : b
+    }, stripPref: function (f, e) {
+        var c = b.type(f);
+        if ("string" == c || "number" == c)f = "" + f, e = "" !== f ? ("" + e).replace("" + f, "") : e;
+        return e
+    }, stringToDoc: function (b) {
+        var e;
+        if ("string" !== typeof b)return b;
+        try {
+            e = (new DOMParser).parseFromString(b, "text/xml")
+        } catch (c) {
+            e = new ActiveXObject("Microsoft.XMLDOM"), e.async = !1, e.loadXML(b)
+        }
+        return e && e.documentElement && "parsererror" != e.documentElement.tagName ? e : null
+    }, parse: function (f) {
+        "while(1);" == f.substr(0, 9) && (f = f.substr(9));
+        "/*" == f.substr(0, 2) && (f = f.substr(2, f.length - 4));
+        f || (f = "{}");
+        return!0 === b.jgrid.useJSON && "object" === typeof JSON && "function" === typeof JSON.parse ? JSON.parse(f) : eval("(" + f + ")")
+    }, parseDate: function (f, e) {
+        var c =
+        {m: 1, d: 1, y: 1970, h: 0, i: 0, s: 0, u: 0}, d, a, h;
+        d = /[\\\/:_;.,\t\T\s-]/;
+        if (e && null !== e && void 0 !== e) {
+            e = b.trim(e);
+            e = e.split(d);
+            void 0 !== b.jgrid.formatter.date.masks[f] && (f = b.jgrid.formatter.date.masks[f]);
+            var f = f.split(d), g = b.jgrid.formatter.date.monthNames, i = b.jgrid.formatter.date.AmPm, j = function (a, b) {
+                0 === a ? 12 === b && (b = 0) : 12 !== b && (b += 12);
+                return b
+            };
+            d = 0;
+            for (a = f.length; d < a; d++)"M" == f[d] && (h = b.inArray(e[d], g), -1 !== h && 12 > h && (e[d] = h + 1, c.m = e[d])), "F" == f[d] && (h = b.inArray(e[d], g), -1 !== h && 11 < h && (e[d] = h + 1 - 12, c.m = e[d])),
+                "a" == f[d] && (h = b.inArray(e[d], i), -1 !== h && 2 > h && e[d] == i[h] && (e[d] = h, c.h = j(e[d], c.h))), "A" == f[d] && (h = b.inArray(e[d], i), -1 !== h && 1 < h && e[d] == i[h] && (e[d] = h - 2, c.h = j(e[d], c.h))), void 0 !== e[d] && (c[f[d].toLowerCase()] = parseInt(e[d], 10));
+            c.m = parseInt(c.m, 10) - 1;
+            d = c.y;
+            70 <= d && 99 >= d ? c.y = 1900 + c.y : 0 <= d && 69 >= d && (c.y = 2E3 + c.y);
+            void 0 !== c.j && (c.d = c.j);
+            void 0 !== c.n && (c.m = parseInt(c.n, 10) - 1)
+        }
+        return new Date(c.y, c.m, c.d, c.h, c.i, c.s, c.u)
+    }, jqID: function (b) {
+        return("" + b).replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g, "\\$&")
+    },
+        guid: 1, uidPref: "jqg", randId: function (f) {
+            return(f ? f : b.jgrid.uidPref) + b.jgrid.guid++
+        }, getAccessor: function (b, e) {
+            var c, d, a = [], h;
+            if ("function" === typeof e)return e(b);
+            c = b[e];
+            if (void 0 === c)try {
+                if ("string" === typeof e && (a = e.split(".")), h = a.length)for (c = b; c && h--;)d = a.shift(), c = c[d]
+            } catch (g) {
+            }
+            return c
+        }, getXmlData: function (f, e, c) {
+            var d = "string" === typeof e ? e.match(/^(.*)\[(\w+)\]$/) : null;
+            if ("function" === typeof e)return e(f);
+            if (d && d[2])return d[1] ? b(d[1], f).attr(d[2]) : b(f).attr(d[2]);
+            f = b(e, f);
+            return c ? f : 0 < f.length ?
+                b(f).text() : void 0
+        }, cellWidth: function () {
+            var f = b("<div class='ui-jqgrid' style='left:10000px'><table class='ui-jqgrid-btable' style='width:5px;'><tr class='jqgrow'><td style='width:5px;'></td></tr></table></div>"), e = f.appendTo("body").find("td").width();
+            f.remove();
+            return 5 !== e
+        }, ajaxOptions: {}, from: function (f) {
+            return new function (e, c) {
+                "string" == typeof e && (e = b.data(e));
+                var d = this, a = e, h = !0, f = !1, i = c, j = /[\$,%]/g, l = null, k = null, m = 0, o = !1, p = "", v = [], u = !0;
+                if ("object" == typeof e && e.push)0 < e.length && (u = "object" != typeof e[0] ? !1 : !0); else throw"data provides is not an array";
+                this._hasData = function () {
+                    return null === a ? !1 : 0 === a.length ? !1 : !0
+                };
+                this._getStr = function (a) {
+                    var b = [];
+                    f && b.push("jQuery.trim(");
+                    b.push("String(" + a + ")");
+                    f && b.push(")");
+                    h || b.push(".toLowerCase()");
+                    return b.join("")
+                };
+                this._strComp = function (a) {
+                    return"string" == typeof a ? ".toString()" : ""
+                };
+                this._group = function (a, b) {
+                    return{field: a.toString(), unique: b, items: []}
+                };
+                this._toStr = function (a) {
+                    f && (a = b.trim(a));
+                    a = a.toString().replace(/\\/g, "\\\\").replace(/\"/g,
+                        '\\"');
+                    return h ? a : a.toLowerCase()
+                };
+                this._funcLoop = function (d) {
+                    var c = [];
+                    b.each(a, function (a, b) {
+                        c.push(d(b))
+                    });
+                    return c
+                };
+                this._append = function (a) {
+                    var b;
+                    i = null === i ? "" : i + ("" === p ? " && " : p);
+                    for (b = 0; b < m; b++)i += "(";
+                    o && (i += "!");
+                    i += "(" + a + ")";
+                    o = !1;
+                    p = "";
+                    m = 0
+                };
+                this._setCommand = function (a, b) {
+                    l = a;
+                    k = b
+                };
+                this._resetNegate = function () {
+                    o = !1
+                };
+                this._repeatCommand = function (a, b) {
+                    return null === l ? d : null !== a && null !== b ? l(a, b) : null === k || !u ? l(a) : l(k, a)
+                };
+                this._equals = function (a, b) {
+                    return 0 === d._compare(a, b, 1)
+                };
+                this._compare = function (a, b, d) {
+                    var c = Object.prototype.toString;
+                    void 0 === d && (d = 1);
+                    void 0 === a && (a = null);
+                    void 0 === b && (b = null);
+                    if (null === a && null === b)return 0;
+                    if (null === a && null !== b)return 1;
+                    if (null !== a && null === b)return-1;
+                    if ("[object Date]" === c.call(a) && "[object Date]" === c.call(b))return a < b ? -d : a > b ? d : 0;
+                    !h && "number" !== typeof a && "number" !== typeof b && (a = ("" + a).toLowerCase(), b = ("" + b).toLowerCase());
+                    return a < b ? -d : a > b ? d : 0
+                };
+                this._performSort = function () {
+                    0 !== v.length && (a = d._doSort(a, 0))
+                };
+                this._doSort = function (a, b) {
+                    var c = v[b].by, f = v[b].dir,
+                        h = v[b].type, e = v[b].datefmt;
+                    if (b == v.length - 1)return d._getOrder(a, c, f, h, e);
+                    b++;
+                    c = d._getGroup(a, c, f, h, e);
+                    f = [];
+                    for (h = 0; h < c.length; h++)for (var e = d._doSort(c[h].items, b), g = 0; g < e.length; g++)f.push(e[g]);
+                    return f
+                };
+                this._getOrder = function (a, c, h, f, e) {
+                    var g = [], i = [], l = "a" == h ? 1 : -1, k, m;
+                    void 0 === f && (f = "text");
+                    m = "float" == f || "number" == f || "currency" == f || "numeric" == f ? function (a) {
+                        a = parseFloat(("" + a).replace(j, ""));
+                        return isNaN(a) ? 0 : a
+                    } : "int" == f || "integer" == f ? function (a) {
+                        return a ? parseFloat(("" + a).replace(j, "")) : 0
+                    } : "date" ==
+                        f || "datetime" == f ? function (a) {
+                        return b.jgrid.parseDate(e, a).getTime()
+                    } : b.isFunction(f) ? f : function (a) {
+                        a || (a = "");
+                        return b.trim(("" + a).toUpperCase())
+                    };
+                    b.each(a, function (a, d) {
+                        k = "" !== c ? b.jgrid.getAccessor(d, c) : d;
+                        void 0 === k && (k = "");
+                        k = m(k, d);
+                        i.push({vSort: k, index: a})
+                    });
+                    i.sort(function (a, b) {
+                        a = a.vSort;
+                        b = b.vSort;
+                        return d._compare(a, b, l)
+                    });
+                    for (var f = 0, o = a.length; f < o;)h = i[f].index, g.push(a[h]), f++;
+                    return g
+                };
+                this._getGroup = function (a, c, f, h, e) {
+                    var g = [], i = null, j = null, k;
+                    b.each(d._getOrder(a, c, f, h, e), function (a, f) {
+                        k =
+                            b.jgrid.getAccessor(f, c);
+                        void 0 === k && (k = "");
+                        d._equals(j, k) || (j = k, null !== i && g.push(i), i = d._group(c, k));
+                        i.items.push(f)
+                    });
+                    null !== i && g.push(i);
+                    return g
+                };
+                this.ignoreCase = function () {
+                    h = !1;
+                    return d
+                };
+                this.useCase = function () {
+                    h = !0;
+                    return d
+                };
+                this.trim = function () {
+                    f = !0;
+                    return d
+                };
+                this.noTrim = function () {
+                    f = !1;
+                    return d
+                };
+                this.execute = function () {
+                    var c = i, f = [];
+                    if (null === c)return d;
+                    b.each(a, function () {
+                        eval(c) && f.push(this)
+                    });
+                    a = f;
+                    return d
+                };
+                this.data = function () {
+                    return a
+                };
+                this.select = function (c) {
+                    d._performSort();
+                    if (!d._hasData())return[];
+                    d.execute();
+                    if (b.isFunction(c)) {
+                        var f = [];
+                        b.each(a, function (a, b) {
+                            f.push(c(b))
+                        });
+                        return f
+                    }
+                    return a
+                };
+                this.hasMatch = function () {
+                    if (!d._hasData())return!1;
+                    d.execute();
+                    return 0 < a.length
+                };
+                this.andNot = function (a, b, c) {
+                    o = !o;
+                    return d.and(a, b, c)
+                };
+                this.orNot = function (a, b, c) {
+                    o = !o;
+                    return d.or(a, b, c)
+                };
+                this.not = function (a, b, c) {
+                    return d.andNot(a, b, c)
+                };
+                this.and = function (a, b, c) {
+                    p = " && ";
+                    return void 0 === a ? d : d._repeatCommand(a, b, c)
+                };
+                this.or = function (a, b, c) {
+                    p = " || ";
+                    return void 0 === a ? d : d._repeatCommand(a, b, c)
+                };
+                this.orBegin =
+                    function () {
+                        m++;
+                        return d
+                    };
+                this.orEnd = function () {
+                    null !== i && (i += ")");
+                    return d
+                };
+                this.isNot = function (a) {
+                    o = !o;
+                    return d.is(a)
+                };
+                this.is = function (a) {
+                    d._append("this." + a);
+                    d._resetNegate();
+                    return d
+                };
+                this._compareValues = function (a, c, f, h, e) {
+                    var g;
+                    g = u ? "jQuery.jgrid.getAccessor(this,'" + c + "')" : "this";
+                    void 0 === f && (f = null);
+                    var i = f, k = void 0 === e.stype ? "text" : e.stype;
+                    if (null !== f)switch (k) {
+                        case "int":
+                        case "integer":
+                            i = isNaN(Number(i)) || "" === i ? "0" : i;
+                            g = "parseInt(" + g + ",10)";
+                            i = "parseInt(" + i + ",10)";
+                            break;
+                        case "float":
+                        case "number":
+                        case "numeric":
+                            i =
+                                ("" + i).replace(j, "");
+                            i = isNaN(Number(i)) || "" === i ? "0" : i;
+                            g = "parseFloat(" + g + ")";
+                            i = "parseFloat(" + i + ")";
+                            break;
+                        case "date":
+                        case "datetime":
+                            i = "" + b.jgrid.parseDate(e.newfmt || "Y-m-d", i).getTime();
+                            g = 'jQuery.jgrid.parseDate("' + e.srcfmt + '",' + g + ").getTime()";
+                            break;
+                        default:
+                            g = d._getStr(g), i = d._getStr('"' + d._toStr(i) + '"')
+                    }
+                    d._append(g + " " + h + " " + i);
+                    d._setCommand(a, c);
+                    d._resetNegate();
+                    return d
+                };
+                this.equals = function (a, b, c) {
+                    return d._compareValues(d.equals, a, b, "==", c)
+                };
+                this.notEquals = function (a, b, c) {
+                    return d._compareValues(d.equals,
+                        a, b, "!==", c)
+                };
+                this.isNull = function (a, b, c) {
+                    return d._compareValues(d.equals, a, null, "===", c)
+                };
+                this.greater = function (a, b, c) {
+                    return d._compareValues(d.greater, a, b, ">", c)
+                };
+                this.less = function (a, b, c) {
+                    return d._compareValues(d.less, a, b, "<", c)
+                };
+                this.greaterOrEquals = function (a, b, c) {
+                    return d._compareValues(d.greaterOrEquals, a, b, ">=", c)
+                };
+                this.lessOrEquals = function (a, b, c) {
+                    return d._compareValues(d.lessOrEquals, a, b, "<=", c)
+                };
+                this.startsWith = function (a, c) {
+                    var h = void 0 === c || null === c ? a : c, h = f ? b.trim(h.toString()).length :
+                        h.toString().length;
+                    u ? d._append(d._getStr("jQuery.jgrid.getAccessor(this,'" + a + "')") + ".substr(0," + h + ") == " + d._getStr('"' + d._toStr(c) + '"')) : (h = f ? b.trim(c.toString()).length : c.toString().length, d._append(d._getStr("this") + ".substr(0," + h + ") == " + d._getStr('"' + d._toStr(a) + '"')));
+                    d._setCommand(d.startsWith, a);
+                    d._resetNegate();
+                    return d
+                };
+                this.endsWith = function (a, c) {
+                    var h = void 0 === c || null === c ? a : c, h = f ? b.trim(h.toString()).length : h.toString().length;
+                    u ? d._append(d._getStr("jQuery.jgrid.getAccessor(this,'" + a +
+                        "')") + ".substr(" + d._getStr("jQuery.jgrid.getAccessor(this,'" + a + "')") + ".length-" + h + "," + h + ') == "' + d._toStr(c) + '"') : d._append(d._getStr("this") + ".substr(" + d._getStr("this") + '.length-"' + d._toStr(a) + '".length,"' + d._toStr(a) + '".length) == "' + d._toStr(a) + '"');
+                    d._setCommand(d.endsWith, a);
+                    d._resetNegate();
+                    return d
+                };
+                this.contains = function (a, b) {
+                    u ? d._append(d._getStr("jQuery.jgrid.getAccessor(this,'" + a + "')") + '.indexOf("' + d._toStr(b) + '",0) > -1') : d._append(d._getStr("this") + '.indexOf("' + d._toStr(a) + '",0) > -1');
+                    d._setCommand(d.contains, a);
+                    d._resetNegate();
+                    return d
+                };
+                this.groupBy = function (b, c, f, h) {
+                    return!d._hasData() ? null : d._getGroup(a, b, c, f, h)
+                };
+                this.orderBy = function (a, c, f, h) {
+                    c = void 0 === c || null === c ? "a" : b.trim(c.toString().toLowerCase());
+                    if (null === f || void 0 === f)f = "text";
+                    if (null === h || void 0 === h)h = "Y-m-d";
+                    if ("desc" == c || "descending" == c)c = "d";
+                    if ("asc" == c || "ascending" == c)c = "a";
+                    v.push({by: a, dir: c, type: f, datefmt: h});
+                    return d
+                };
+                return d
+            }(f, null)
+        }, extend: function (f) {
+            b.extend(b.fn.jqGrid, f);
+            this.no_legacy_api || b.fn.extend(f)
+        }});
+    b.fn.jqGrid = function (f) {
+        if ("string" == typeof f) {
+            var e = b.jgrid.getAccessor(b.fn.jqGrid, f);
+            if (!e)throw"jqGrid - No such method: " + f;
+            var c = b.makeArray(arguments).slice(1);
+            return e.apply(this, c)
+        }
+        return this.each(function () {
+            if (!this.grid) {
+                var d = b.extend(!0, {url: "", height: 150, page: 1, rowNum: 20, rowTotal: null, records: 0, pager: "", pgbuttons: !0, pginput: !0, colModel: [], rowList: [], colNames: [], sortorder: "asc", sortname: "", datatype: "xml", mtype: "GET", altRows: !1, selarrrow: [], savedRow: [], shrinkToFit: !0, xmlReader: {}, jsonReader: {},
+                    subGrid: !1, subGridModel: [], reccount: 0, lastpage: 0, lastsort: 0, selrow: null, beforeSelectRow: null, onSelectRow: null, onSortCol: null, ondblClickRow: null, onRightClickRow: null, onPaging: null, onSelectAll: null, loadComplete: null, gridComplete: null, loadError: null, loadBeforeSend: null, afterInsertRow: null, beforeRequest: null, beforeProcessing: null, onHeaderClick: null, viewrecords: !1, loadonce: !1, multiselect: !1, multikey: !1, editurl: null, search: !1, caption: "", hidegrid: !0, hiddengrid: !1, postData: {}, userData: {}, treeGrid: !1, treeGridModel: "nested",
+                    treeReader: {}, treeANode: -1, ExpandColumn: null, tree_root_level: 0, prmNames: {page: "page", rows: "rows", sort: "sidx", order: "sord", search: "_search", nd: "nd", id: "id", oper: "oper", editoper: "edit", addoper: "add", deloper: "del", subgridid: "id", npage: null, totalrows: "totalrows"}, forceFit: !1, gridstate: "visible", cellEdit: !1, cellsubmit: "remote", nv: 0, loadui: "enable", toolbar: [!1, ""], scroll: !1, multiboxonly: !1, deselectAfterSort: !0, scrollrows: !1, autowidth: !1, scrollOffset: 18, cellLayout: 5, subGridWidth: 20, multiselectWidth: 20, gridview: !1,
+                    rownumWidth: 25, rownumbers: !1, pagerpos: "center", recordpos: "right", footerrow: !1, userDataOnFooter: !1, hoverrows: !0, altclass: "ui-priority-secondary", viewsortcols: [!1, "vertical", !0], resizeclass: "", autoencode: !1, remapColumns: [], ajaxGridOptions: {}, direction: "ltr", toppager: !1, headertitles: !1, scrollTimeout: 40, data: [], _index: {}, grouping: !1, groupingView: {groupField: [], groupOrder: [], groupText: [], groupColumnShow: [], groupSummary: [], showSummaryOnHide: !1, sortitems: [], sortnames: [], summary: [], summaryval: [], plusicon: "ui-icon-circlesmall-plus",
+                        minusicon: "ui-icon-circlesmall-minus"}, ignoreCase: !1, cmTemplate: {}, idPrefix: ""}, b.jgrid.defaults, f || {}), a = this, c = {headers: [], cols: [], footers: [], dragStart: function (c, e, f) {
+                    this.resizing = {idx: c, startX: e.clientX, sOL: f[0]};
+                    this.hDiv.style.cursor = "col-resize";
+                    this.curGbox = b("#rs_m" + b.jgrid.jqID(d.id), "#gbox_" + b.jgrid.jqID(d.id));
+                    this.curGbox.css({display: "block", left: f[0], top: f[1], height: f[2]});
+                    b(a).triggerHandler("jqGridResizeStart", [e, c]);
+                    b.isFunction(d.resizeStart) && d.resizeStart.call(this, e, c);
+                    document.onselectstart =
+                        function () {
+                            return!1
+                        }
+                }, dragMove: function (a) {
+                    if (this.resizing) {
+                        var b = a.clientX - this.resizing.startX, a = this.headers[this.resizing.idx], c = "ltr" === d.direction ? a.width + b : a.width - b, e;
+                        33 < c && (this.curGbox.css({left: this.resizing.sOL + b}), !0 === d.forceFit ? (e = this.headers[this.resizing.idx + d.nv], b = "ltr" === d.direction ? e.width - b : e.width + b, 33 < b && (a.newWidth = c, e.newWidth = b)) : (this.newWidth = "ltr" === d.direction ? d.tblwidth + b : d.tblwidth - b, a.newWidth = c))
+                    }
+                }, dragEnd: function () {
+                    this.hDiv.style.cursor = "default";
+                    if (this.resizing) {
+                        var c =
+                            this.resizing.idx, e = this.headers[c].newWidth || this.headers[c].width, e = parseInt(e, 10);
+                        this.resizing = !1;
+                        b("#rs_m" + b.jgrid.jqID(d.id)).css("display", "none");
+                        d.colModel[c].width = e;
+                        this.headers[c].width = e;
+                        this.headers[c].el.style.width = e + "px";
+                        this.cols[c].style.width = e + "px";
+                        0 < this.footers.length && (this.footers[c].style.width = e + "px");
+                        !0 === d.forceFit ? (e = this.headers[c + d.nv].newWidth || this.headers[c + d.nv].width, this.headers[c + d.nv].width = e, this.headers[c + d.nv].el.style.width = e + "px", this.cols[c + d.nv].style.width =
+                            e + "px", 0 < this.footers.length && (this.footers[c + d.nv].style.width = e + "px"), d.colModel[c + d.nv].width = e) : (d.tblwidth = this.newWidth || d.tblwidth, b("table:first", this.bDiv).css("width", d.tblwidth + "px"), b("table:first", this.hDiv).css("width", d.tblwidth + "px"), this.hDiv.scrollLeft = this.bDiv.scrollLeft, d.footerrow && (b("table:first", this.sDiv).css("width", d.tblwidth + "px"), this.sDiv.scrollLeft = this.bDiv.scrollLeft));
+                        b(a).triggerHandler("jqGridResizeStop", [e, c]);
+                        b.isFunction(d.resizeStop) && d.resizeStop.call(this,
+                            e, c)
+                    }
+                    this.curGbox = null;
+                    document.onselectstart = function () {
+                        return!0
+                    }
+                }, populateVisible: function () {
+                    c.timer && clearTimeout(c.timer);
+                    c.timer = null;
+                    var a = b(c.bDiv).height();
+                    if (a) {
+                        var e = b("table:first", c.bDiv), f, G;
+                        if (e[0].rows.length)try {
+                            G = (f = e[0].rows[1]) ? b(f).outerHeight() || c.prevRowHeight : c.prevRowHeight
+                        } catch (g) {
+                            G = c.prevRowHeight
+                        }
+                        if (G) {
+                            c.prevRowHeight = G;
+                            var i = d.rowNum;
+                            f = c.scrollTop = c.bDiv.scrollTop;
+                            var j = Math.round(e.position().top) - f, k = j + e.height();
+                            G *= i;
+                            var y, z, B;
+                            if (k < a && 0 >= j && (void 0 === d.lastpage || parseInt((k +
+                                f + G - 1) / G, 10) <= d.lastpage))z = parseInt((a - k + G - 1) / G, 10), 0 <= k || 2 > z || !0 === d.scroll ? (y = Math.round((k + f) / G) + 1, j = -1) : j = 1;
+                            0 < j && (y = parseInt(f / G, 10) + 1, z = parseInt((f + a) / G, 10) + 2 - y, B = !0);
+                            if (z && !(d.lastpage && y > d.lastpage || 1 == d.lastpage || y === d.page && y === d.lastpage))c.hDiv.loading ? c.timer = setTimeout(c.populateVisible, d.scrollTimeout) : (d.page = y, B && (c.selectionPreserver(e[0]), c.emptyRows.call(e[0], !1, !1)), c.populate(z))
+                        }
+                    }
+                }, scrollGrid: function (a) {
+                    if (d.scroll) {
+                        var b = c.bDiv.scrollTop;
+                        void 0 === c.scrollTop && (c.scrollTop =
+                            0);
+                        b != c.scrollTop && (c.scrollTop = b, c.timer && clearTimeout(c.timer), c.timer = setTimeout(c.populateVisible, d.scrollTimeout))
+                    }
+                    c.hDiv.scrollLeft = c.bDiv.scrollLeft;
+                    d.footerrow && (c.sDiv.scrollLeft = c.bDiv.scrollLeft);
+                    a && a.stopPropagation()
+                }, selectionPreserver: function (a) {
+                    var c = a.p, d = c.selrow, e = c.selarrrow ? b.makeArray(c.selarrrow) : null, f = a.grid.bDiv.scrollLeft, g = function () {
+                        var h;
+                        c.selrow = null;
+                        c.selarrrow = [];
+                        if (c.multiselect && e && 0 < e.length)for (h = 0; h < e.length; h++)e[h] != d && b(a).jqGrid("setSelection", e[h], !1, null);
+                        d && b(a).jqGrid("setSelection", d, !1, null);
+                        a.grid.bDiv.scrollLeft = f;
+                        b(a).unbind(".selectionPreserver", g)
+                    };
+                    b(a).bind("jqGridGridComplete.selectionPreserver", g)
+                }};
+                if ("TABLE" != this.tagName.toUpperCase())alert("Element is not a table"); else if (void 0 !== document.documentMode && 5 >= document.documentMode)alert("Grid can not be used in this ('quirks') mode!"); else {
+                    b(this).empty().attr("tabindex", "1");
+                    this.p = d;
+                    this.p.useProp = !!b.fn.prop;
+                    var e, i;
+                    if (0 === this.p.colNames.length)for (e = 0; e < this.p.colModel.length; e++)this.p.colNames[e] =
+                        this.p.colModel[e].label || this.p.colModel[e].name;
+                    if (this.p.colNames.length !== this.p.colModel.length)alert(b.jgrid.errors.model); else {
+                        var j = b("<div class='ui-jqgrid-view'></div>"), l, k = b.browser.msie ? !0 : !1;
+                        a.p.direction = b.trim(a.p.direction.toLowerCase());
+                        -1 == b.inArray(a.p.direction, ["ltr", "rtl"]) && (a.p.direction = "ltr");
+                        i = a.p.direction;
+                        b(j).insertBefore(this);
+                        b(this).appendTo(j).removeClass("scroll");
+                        var m = b("<div class='ui-jqgrid ui-widget ui-widget-content ui-corner-all'></div>");
+                        b(m).insertBefore(j).attr({id: "gbox_" +
+                            this.id, dir: i});
+                        b(j).appendTo(m).attr("id", "gview_" + this.id);
+                        l = k && 6 >= b.browser.version ? '<iframe style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=\'0\');" src="javascript:false;"></iframe>' : "";
+                        b("<div class='ui-widget-overlay jqgrid-overlay' id='lui_" + this.id + "'></div>").append(l).insertBefore(j);
+                        b("<div class='loading ui-state-default ui-state-active' id='load_" + this.id + "'>" + this.p.loadtext + "</div>").insertBefore(j);
+                        b(this).attr({cellspacing: "0", cellpadding: "0", border: "0", role: "grid",
+                            "aria-multiselectable": !!this.p.multiselect, "aria-labelledby": "gbox_" + this.id});
+                        var o = function (a, b) {
+                            a = parseInt(a, 10);
+                            return isNaN(a) ? b ? b : 0 : a
+                        }, p = function (d, e, f, g, i, j) {
+                            var K = a.p.colModel[d], k = K.align, y = 'style="', z = K.classes, B = K.name, q = [];
+                            k && (y = y + ("text-align:" + k + ";"));
+                            K.hidden === true && (y = y + "display:none;");
+                            if (e === 0)y = y + ("width: " + c.headers[d].width + "px;"); else if (K.cellattr && b.isFunction(K.cellattr))if ((d = K.cellattr.call(a, i, f, g, K, j)) && typeof d === "string") {
+                                d = d.replace(/style/i, "style").replace(/title/i,
+                                    "title");
+                                if (d.indexOf("title") > -1)K.title = false;
+                                d.indexOf("class") > -1 && (z = void 0);
+                                q = d.split("style");
+                                if (q.length === 2) {
+                                    q[1] = b.trim(q[1].replace("=", ""));
+                                    if (q[1].indexOf("'") === 0 || q[1].indexOf('"') === 0)q[1] = q[1].substring(1);
+                                    y = y + q[1].replace(/'/gi, '"')
+                                } else y = y + '"'
+                            }
+                            if (!q.length) {
+                                q[0] = "";
+                                y = y + '"'
+                            }
+                            y = y + ((z !== void 0 ? ' class="' + z + '"' : "") + (K.title && f ? ' title="' + b.jgrid.stripHtml(f) + '"' : ""));
+                            y = y + (' aria-describedby="' + a.p.id + "_" + B + '"');
+                            return y + q[0]
+                        }, v = function (c) {
+                            return c === void 0 || c === null || c === "" ? "&#160;" :
+                                a.p.autoencode ? b.jgrid.htmlEncode(c) : c + ""
+                        }, u = function (c, d, e, f, g) {
+                            var h = a.p.colModel[e];
+                            if (typeof h.formatter !== "undefined") {
+                                c = {rowId: c, colModel: h, gid: a.p.id, pos: e};
+                                d = b.isFunction(h.formatter) ? h.formatter.call(a, d, c, f, g) : b.fmatter ? b.fn.fmatter.call(a, h.formatter, d, c, f, g) : v(d)
+                            } else d = v(d);
+                            return d
+                        }, M = function (a, b, c, d, e) {
+                            b = u(a, b, c, e, "add");
+                            return'<td role="gridcell" ' + p(c, d, b, e, a, true) + ">" + b + "</td>"
+                        }, F = function (b, c, d) {
+                            var e = '<input role="checkbox" type="checkbox" id="jqg_' + a.p.id + "_" + b + '" class="cbox" name="jqg_' +
+                                a.p.id + "_" + b + '"/>';
+                            return'<td role="gridcell" ' + p(c, d, "", null, b, true) + ">" + e + "</td>"
+                        }, Z = function (a, b, c, d) {
+                            c = (parseInt(c, 10) - 1) * parseInt(d, 10) + 1 + b;
+                            return'<td role="gridcell" class="ui-state-default jqgrid-rownum" ' + p(a, b, c, null, b, true) + ">" + c + "</td>"
+                        }, U = function (b) {
+                            var c, d = [], e = 0, f;
+                            for (f = 0; f < a.p.colModel.length; f++) {
+                                c = a.p.colModel[f];
+                                if (c.name !== "cb" && c.name !== "subgrid" && c.name !== "rn") {
+                                    d[e] = b == "local" ? c.name : b == "xml" || b === "xmlstring" ? c.xmlmap || c.name : c.jsonmap || c.name;
+                                    e++
+                                }
+                            }
+                            return d
+                        }, V = function (c) {
+                            var d =
+                                a.p.remapColumns;
+                            if (!d || !d.length)d = b.map(a.p.colModel, function (a, b) {
+                                return b
+                            });
+                            c && (d = b.map(d, function (a) {
+                                return a < c ? null : a - c
+                            }));
+                            return d
+                        }, N = function (a, c) {
+                            var d;
+                            if (this.p.deepempty)b(this.rows).slice(1).remove(); else {
+                                d = this.rows.length > 0 ? this.rows[0] : null;
+                                b(this.firstChild).empty().append(d)
+                            }
+                            if (a && this.p.scroll) {
+                                b(this.grid.bDiv.firstChild).css({height: "auto"});
+                                b(this.grid.bDiv.firstChild.firstChild).css({height: 0, display: "none"});
+                                if (this.grid.bDiv.scrollTop !== 0)this.grid.bDiv.scrollTop = 0
+                            }
+                            if (c ===
+                                true && this.p.treeGrid) {
+                                this.p.data = [];
+                                this.p._index = {}
+                            }
+                        }, S = function () {
+                            var c = a.p.data.length, d, e, f;
+                            d = a.p.rownumbers === true ? 1 : 0;
+                            e = a.p.multiselect === true ? 1 : 0;
+                            f = a.p.subGrid === true ? 1 : 0;
+                            d = a.p.keyIndex === false || a.p.loadonce === true ? a.p.localReader.id : a.p.colModel[a.p.keyIndex + e + f + d].name;
+                            for (e = 0; e < c; e++) {
+                                f = b.jgrid.getAccessor(a.p.data[e], d);
+                                a.p._index[f] = e
+                            }
+                        }, J = function (c, d, e, f, g) {
+                            var h = "-1", i = "", j, d = d ? "display:none;" : "", e = "ui-widget-content jqgrow ui-row-" + a.p.direction + e, f = b.isFunction(a.p.rowattr) ? a.p.rowattr.call(a,
+                                f, g) : {};
+                            if (!b.isEmptyObject(f)) {
+                                if (f.hasOwnProperty("id")) {
+                                    c = f.id;
+                                    delete f.id
+                                }
+                                if (f.hasOwnProperty("tabindex")) {
+                                    h = f.tabindex;
+                                    delete f.tabindex
+                                }
+                                if (f.hasOwnProperty("style")) {
+                                    d = d + f.style;
+                                    delete f.style
+                                }
+                                if (f.hasOwnProperty("class")) {
+                                    e = e + (" " + f["class"]);
+                                    delete f["class"]
+                                }
+                                try {
+                                    delete f.role
+                                } catch (k) {
+                                }
+                                for (j in f)f.hasOwnProperty(j) && (i = i + (" " + j + "=" + f[j]))
+                            }
+                            return'<tr role="row" id="' + c + '" tabindex="' + h + '" class="' + e + '"' + (d === "" ? "" : ' style="' + d + '"') + i + ">"
+                        }, $ = function (c, d, e, f, g) {
+                            var h = new Date, i = a.p.datatype !=
+                                "local" && a.p.loadonce || a.p.datatype == "xmlstring", j = a.p.xmlReader, k = a.p.datatype == "local" ? "local" : "xml";
+                            if (i) {
+                                a.p.data = [];
+                                a.p._index = {};
+                                a.p.localReader.id = "_id_"
+                            }
+                            a.p.reccount = 0;
+                            if (b.isXMLDoc(c)) {
+                                if (a.p.treeANode === -1 && !a.p.scroll) {
+                                    N.call(a, false, true);
+                                    e = 1
+                                } else e = e > 1 ? e : 1;
+                                var z, B, q = 0, l, s = a.p.multiselect === true ? 1 : 0, P = a.p.subGrid === true ? 1 : 0, m = a.p.rownumbers === true ? 1 : 0, o, p = [], u, n = {}, r, w, C = [], v = a.p.altRows === true ? " " + a.p.altclass : "", A;
+                                j.repeatitems || (p = U(k));
+                                o = a.p.keyIndex === false ? b.isFunction(j.id) ? j.id.call(a,
+                                    c) : j.id : a.p.keyIndex;
+                                if (p.length > 0 && !isNaN(o)) {
+                                    a.p.remapColumns && a.p.remapColumns.length && (o = b.inArray(o, a.p.remapColumns));
+                                    o = p[o]
+                                }
+                                k = (o + "").indexOf("[") === -1 ? p.length ? function (a, c) {
+                                    return b(o, a).text() || c
+                                } : function (a, c) {
+                                    return b(j.cell, a).eq(o).text() || c
+                                } : function (a, b) {
+                                    return a.getAttribute(o.replace(/[\[\]]/g, "")) || b
+                                };
+                                a.p.userData = {};
+                                a.p.page = b.jgrid.getXmlData(c, j.page) || 0;
+                                a.p.lastpage = b.jgrid.getXmlData(c, j.total);
+                                if (a.p.lastpage === void 0)a.p.lastpage = 1;
+                                a.p.records = b.jgrid.getXmlData(c, j.records) ||
+                                    0;
+                                b.isFunction(j.userdata) ? a.p.userData = j.userdata.call(a, c) || {} : b.jgrid.getXmlData(c, j.userdata, true).each(function () {
+                                    a.p.userData[this.getAttribute("name")] = b(this).text()
+                                });
+                                c = b.jgrid.getXmlData(c, j.root, true);
+                                (c = b.jgrid.getXmlData(c, j.row, true)) || (c = []);
+                                var t = c.length, H = 0, Q = [], x = parseInt(a.p.rowNum, 10);
+                                if (t > 0 && a.p.page <= 0)a.p.page = 1;
+                                if (c && t) {
+                                    var D = a.p.scroll ? b.jgrid.randId() : 1;
+                                    g && (x = x * (g + 1));
+                                    for (var g = b.isFunction(a.p.afterInsertRow), E = a.p.grouping && a.p.groupingView.groupCollapse === true; H < t;) {
+                                        r =
+                                            c[H];
+                                        w = k(r, D + H);
+                                        w = a.p.idPrefix + w;
+                                        z = e === 0 ? 0 : e + 1;
+                                        A = (z + H) % 2 == 1 ? v : "";
+                                        var I = C.length;
+                                        C.push("");
+                                        m && C.push(Z(0, H, a.p.page, a.p.rowNum));
+                                        s && C.push(F(w, m, H));
+                                        P && C.push(b(a).jqGrid("addSubGridCell", s + m, H + e));
+                                        if (j.repeatitems) {
+                                            u || (u = V(s + P + m));
+                                            var L = b.jgrid.getXmlData(r, j.cell, true);
+                                            b.each(u, function (b) {
+                                                var c = L[this];
+                                                if (!c)return false;
+                                                l = c.textContent || c.text;
+                                                n[a.p.colModel[b + s + P + m].name] = l;
+                                                C.push(M(w, l, b + s + P + m, H + e, r))
+                                            })
+                                        } else for (z = 0; z < p.length; z++) {
+                                            l = b.jgrid.getXmlData(r, p[z]);
+                                            n[a.p.colModel[z + s + P + m].name] =
+                                                l;
+                                            C.push(M(w, l, z + s + P + m, H + e, r))
+                                        }
+                                        C[I] = J(w, E, A, n, r);
+                                        C.push("</tr>");
+                                        if (a.p.grouping) {
+                                            Q = b(a).jqGrid("groupingPrepare", C, Q, n, H);
+                                            C = []
+                                        }
+                                        if (i || a.p.treeGrid === true) {
+                                            n._id_ = w;
+                                            a.p.data.push(n);
+                                            a.p._index[w] = a.p.data.length - 1
+                                        }
+                                        if (a.p.gridview === false) {
+                                            b("tbody:first", d).append(C.join(""));
+                                            b(a).triggerHandler("jqGridAfterInsertRow", [w, n, r]);
+                                            g && a.p.afterInsertRow.call(a, w, n, r);
+                                            C = []
+                                        }
+                                        n = {};
+                                        q++;
+                                        H++;
+                                        if (q == x)break
+                                    }
+                                }
+                                if (a.p.gridview === true) {
+                                    B = a.p.treeANode > -1 ? a.p.treeANode : 0;
+                                    if (a.p.grouping) {
+                                        b(a).jqGrid("groupingRender",
+                                            Q, a.p.colModel.length);
+                                        Q = null
+                                    } else a.p.treeGrid === true && B > 0 ? b(a.rows[B]).after(C.join("")) : b("tbody:first", d).append(C.join(""))
+                                }
+                                if (a.p.subGrid === true)try {
+                                    b(a).jqGrid("addSubGrid", s + m)
+                                } catch (R) {
+                                }
+                                a.p.totaltime = new Date - h;
+                                if (q > 0 && a.p.records === 0)a.p.records = t;
+                                C = null;
+                                if (a.p.treeGrid === true)try {
+                                    b(a).jqGrid("setTreeNode", B + 1, q + B + 1)
+                                } catch (S) {
+                                }
+                                if (!a.p.treeGrid && !a.p.scroll)a.grid.bDiv.scrollTop = 0;
+                                a.p.reccount = q;
+                                a.p.treeANode = -1;
+                                a.p.userDataOnFooter && b(a).jqGrid("footerData", "set", a.p.userData, true);
+                                if (i) {
+                                    a.p.records =
+                                        t;
+                                    a.p.lastpage = Math.ceil(t / x)
+                                }
+                                f || a.updatepager(false, true);
+                                if (i)for (; q < t;) {
+                                    r = c[q];
+                                    w = k(r, q + D);
+                                    w = a.p.idPrefix + w;
+                                    if (j.repeatitems) {
+                                        u || (u = V(s + P + m));
+                                        var O = b.jgrid.getXmlData(r, j.cell, true);
+                                        b.each(u, function (b) {
+                                            var c = O[this];
+                                            if (!c)return false;
+                                            l = c.textContent || c.text;
+                                            n[a.p.colModel[b + s + P + m].name] = l
+                                        })
+                                    } else for (z = 0; z < p.length; z++) {
+                                        l = b.jgrid.getXmlData(r, p[z]);
+                                        n[a.p.colModel[z + s + P + m].name] = l
+                                    }
+                                    n._id_ = w;
+                                    a.p.data.push(n);
+                                    a.p._index[w] = a.p.data.length - 1;
+                                    n = {};
+                                    q++
+                                }
+                            }
+                        }, aa = function (c, d, e, f, g) {
+                            d = new Date;
+                            if (c) {
+                                if (a.p.treeANode === -1 && !a.p.scroll) {
+                                    N.call(a, false, true);
+                                    e = 1
+                                } else e = e > 1 ? e : 1;
+                                var h, i, j = a.p.datatype != "local" && a.p.loadonce || a.p.datatype == "jsonstring";
+                                if (j) {
+                                    a.p.data = [];
+                                    a.p._index = {};
+                                    a.p.localReader.id = "_id_"
+                                }
+                                a.p.reccount = 0;
+                                if (a.p.datatype == "local") {
+                                    h = a.p.localReader;
+                                    i = "local"
+                                } else {
+                                    h = a.p.jsonReader;
+                                    i = "json"
+                                }
+                                var k = 0, l, B, q = [], m, s = a.p.multiselect ? 1 : 0, o = a.p.subGrid ? 1 : 0, p = a.p.rownumbers === true ? 1 : 0, n, u, t = {}, v, r, w = [], C = a.p.altRows === true ? " " + a.p.altclass : "", A;
+                                a.p.page = b.jgrid.getAccessor(c, h.page) || 0;
+                                n = b.jgrid.getAccessor(c,
+                                    h.total);
+                                a.p.lastpage = n === void 0 ? 1 : n;
+                                a.p.records = b.jgrid.getAccessor(c, h.records) || 0;
+                                a.p.userData = b.jgrid.getAccessor(c, h.userdata) || {};
+                                h.repeatitems || (m = q = U(i));
+                                i = a.p.keyIndex === false ? b.isFunction(h.id) ? h.id.call(a, c) : h.id : a.p.keyIndex;
+                                if (q.length > 0 && !isNaN(i)) {
+                                    a.p.remapColumns && a.p.remapColumns.length && (i = b.inArray(i, a.p.remapColumns));
+                                    i = q[i]
+                                }
+                                (u = b.jgrid.getAccessor(c, h.root)) || (u = []);
+                                n = u.length;
+                                c = 0;
+                                if (n > 0 && a.p.page <= 0)a.p.page = 1;
+                                var x = parseInt(a.p.rowNum, 10), D = a.p.scroll ? b.jgrid.randId() : 1;
+                                g && (x =
+                                    x * (g + 1));
+                                for (var H = b.isFunction(a.p.afterInsertRow), Q = [], E = a.p.grouping && a.p.groupingView.groupCollapse === true; c < n;) {
+                                    g = u[c];
+                                    r = b.jgrid.getAccessor(g, i);
+                                    if (r === void 0) {
+                                        r = D + c;
+                                        if (q.length === 0 && h.cell) {
+                                            l = b.jgrid.getAccessor(g, h.cell);
+                                            r = l !== void 0 ? l[i] || r : r
+                                        }
+                                    }
+                                    r = a.p.idPrefix + r;
+                                    l = e === 1 ? 0 : e;
+                                    A = (l + c) % 2 == 1 ? C : "";
+                                    var I = w.length;
+                                    w.push("");
+                                    p && w.push(Z(0, c, a.p.page, a.p.rowNum));
+                                    s && w.push(F(r, p, c));
+                                    o && w.push(b(a).jqGrid("addSubGridCell", s + p, c + e));
+                                    if (h.repeatitems) {
+                                        h.cell && (g = b.jgrid.getAccessor(g, h.cell));
+                                        m || (m = V(s +
+                                            o + p))
+                                    }
+                                    for (B = 0; B < m.length; B++) {
+                                        l = b.jgrid.getAccessor(g, m[B]);
+                                        w.push(M(r, l, B + s + o + p, c + e, g));
+                                        t[a.p.colModel[B + s + o + p].name] = l
+                                    }
+                                    w[I] = J(r, E, A, t, g);
+                                    w.push("</tr>");
+                                    if (a.p.grouping) {
+                                        Q = b(a).jqGrid("groupingPrepare", w, Q, t, c);
+                                        w = []
+                                    }
+                                    if (j || a.p.treeGrid === true) {
+                                        t._id_ = r;
+                                        a.p.data.push(t);
+                                        a.p._index[r] = a.p.data.length - 1
+                                    }
+                                    if (a.p.gridview === false) {
+                                        b("#" + b.jgrid.jqID(a.p.id) + " tbody:first").append(w.join(""));
+                                        b(a).triggerHandler("jqGridAfterInsertRow", [r, t, g]);
+                                        H && a.p.afterInsertRow.call(a, r, t, g);
+                                        w = []
+                                    }
+                                    t = {};
+                                    k++;
+                                    c++;
+                                    if (k ==
+                                        x)break
+                                }
+                                if (a.p.gridview === true) {
+                                    v = a.p.treeANode > -1 ? a.p.treeANode : 0;
+                                    a.p.grouping ? b(a).jqGrid("groupingRender", Q, a.p.colModel.length) : a.p.treeGrid === true && v > 0 ? b(a.rows[v]).after(w.join("")) : b("#" + b.jgrid.jqID(a.p.id) + " tbody:first").append(w.join(""))
+                                }
+                                if (a.p.subGrid === true)try {
+                                    b(a).jqGrid("addSubGrid", s + p)
+                                } catch (L) {
+                                }
+                                a.p.totaltime = new Date - d;
+                                if (k > 0 && a.p.records === 0)a.p.records = n;
+                                if (a.p.treeGrid === true)try {
+                                    b(a).jqGrid("setTreeNode", v + 1, k + v + 1)
+                                } catch (O) {
+                                }
+                                if (!a.p.treeGrid && !a.p.scroll)a.grid.bDiv.scrollTop =
+                                    0;
+                                a.p.reccount = k;
+                                a.p.treeANode = -1;
+                                a.p.userDataOnFooter && b(a).jqGrid("footerData", "set", a.p.userData, true);
+                                if (j) {
+                                    a.p.records = n;
+                                    a.p.lastpage = Math.ceil(n / x)
+                                }
+                                f || a.updatepager(false, true);
+                                if (j)for (; k < n && u[k];) {
+                                    g = u[k];
+                                    r = b.jgrid.getAccessor(g, i);
+                                    if (r === void 0) {
+                                        r = D + k;
+                                        q.length === 0 && h.cell && (r = b.jgrid.getAccessor(g, h.cell)[i] || r)
+                                    }
+                                    if (g) {
+                                        r = a.p.idPrefix + r;
+                                        if (h.repeatitems) {
+                                            h.cell && (g = b.jgrid.getAccessor(g, h.cell));
+                                            m || (m = V(s + o + p))
+                                        }
+                                        for (B = 0; B < m.length; B++) {
+                                            l = b.jgrid.getAccessor(g, m[B]);
+                                            t[a.p.colModel[B + s + o + p].name] =
+                                                l
+                                        }
+                                        t._id_ = r;
+                                        a.p.data.push(t);
+                                        a.p._index[r] = a.p.data.length - 1;
+                                        t = {}
+                                    }
+                                    k++
+                                }
+                            }
+                        }, ma = function () {
+                            function c(d) {
+                                var e = 0, g, h, i, j, T;
+                                if (d.groups !== void 0) {
+                                    (h = d.groups.length && d.groupOp.toString().toUpperCase() === "OR") && s.orBegin();
+                                    for (g = 0; g < d.groups.length; g++) {
+                                        e > 0 && h && s.or();
+                                        try {
+                                            c(d.groups[g])
+                                        } catch (k) {
+                                            alert(k)
+                                        }
+                                        e++
+                                    }
+                                    h && s.orEnd()
+                                }
+                                if (d.rules !== void 0) {
+                                    if (e > 0) {
+                                        h = s.select();
+                                        s = b.jgrid.from(h);
+                                        a.p.ignoreCase && (s = s.ignoreCase())
+                                    }
+                                    try {
+                                        (i = d.rules.length && d.groupOp.toString().toUpperCase() === "OR") && s.orBegin();
+                                        for (g = 0; g < d.rules.length; g++) {
+                                            T =
+                                                d.rules[g];
+                                            j = d.groupOp.toString().toUpperCase();
+                                            if (o[T.op] && T.field) {
+                                                e > 0 && j && j === "OR" && (s = s.or());
+                                                s = o[T.op](s, j)(T.field, T.data, f[T.field])
+                                            }
+                                            e++
+                                        }
+                                        i && s.orEnd()
+                                    } catch (na) {
+                                        alert(na)
+                                    }
+                                }
+                            }
+
+                            var d, e = false, f = {}, g = [], h = [], i, j, k;
+                            if (b.isArray(a.p.data)) {
+                                var l = a.p.grouping ? a.p.groupingView : false, m, q;
+                                b.each(a.p.colModel, function () {
+                                    j = this.sorttype || "text";
+                                    if (j == "date" || j == "datetime") {
+                                        if (this.formatter && typeof this.formatter === "string" && this.formatter == "date") {
+                                            i = this.formatoptions && this.formatoptions.srcformat ? this.formatoptions.srcformat :
+                                                b.jgrid.formatter.date.srcformat;
+                                            k = this.formatoptions && this.formatoptions.newformat ? this.formatoptions.newformat : b.jgrid.formatter.date.newformat
+                                        } else i = k = this.datefmt || "Y-m-d";
+                                        f[this.name] = {stype: j, srcfmt: i, newfmt: k}
+                                    } else f[this.name] = {stype: j, srcfmt: "", newfmt: ""};
+                                    if (a.p.grouping) {
+                                        q = 0;
+                                        for (m = l.groupField.length; q < m; q++)if (this.name == l.groupField[q]) {
+                                            var c = this.name;
+                                            if (typeof this.index != "undefined")c = this.index;
+                                            g[q] = f[c];
+                                            h[q] = c
+                                        }
+                                    }
+                                    if (!e && (this.index == a.p.sortname || this.name == a.p.sortname)) {
+                                        d = this.name;
+                                        e = true
+                                    }
+                                });
+                                if (a.p.treeGrid)b(a).jqGrid("SortTree", d, a.p.sortorder, f[d].stype, f[d].srcfmt); else {
+                                    var o = {eq: function (a) {
+                                        return a.equals
+                                    }, ne: function (a) {
+                                        return a.notEquals
+                                    }, lt: function (a) {
+                                        return a.less
+                                    }, le: function (a) {
+                                        return a.lessOrEquals
+                                    }, gt: function (a) {
+                                        return a.greater
+                                    }, ge: function (a) {
+                                        return a.greaterOrEquals
+                                    }, cn: function (a) {
+                                        return a.contains
+                                    }, nc: function (a, b) {
+                                        return b === "OR" ? a.orNot().contains : a.andNot().contains
+                                    }, bw: function (a) {
+                                        return a.startsWith
+                                    }, bn: function (a, b) {
+                                        return b === "OR" ? a.orNot().startsWith :
+                                            a.andNot().startsWith
+                                    }, en: function (a, b) {
+                                        return b === "OR" ? a.orNot().endsWith : a.andNot().endsWith
+                                    }, ew: function (a) {
+                                        return a.endsWith
+                                    }, ni: function (a, b) {
+                                        return b === "OR" ? a.orNot().equals : a.andNot().equals
+                                    }, "in": function (a) {
+                                        return a.equals
+                                    }, nu: function (a) {
+                                        return a.isNull
+                                    }, nn: function (a, b) {
+                                        return b === "OR" ? a.orNot().isNull : a.andNot().isNull
+                                    }}, s = b.jgrid.from(a.p.data);
+                                    a.p.ignoreCase && (s = s.ignoreCase());
+                                    if (a.p.search === true) {
+                                        var n = a.p.postData.filters;
+                                        if (n) {
+                                            typeof n == "string" && (n = b.jgrid.parse(n));
+                                            c(n)
+                                        } else try {
+                                            s =
+                                                o[a.p.postData.searchOper](s)(a.p.postData.searchField, a.p.postData.searchString, f[a.p.postData.searchField])
+                                        } catch (p) {
+                                        }
+                                    }
+                                    if (a.p.grouping)for (q = 0; q < m; q++)s.orderBy(h[q], l.groupOrder[q], g[q].stype, g[q].srcfmt);
+                                    d && a.p.sortorder && e && (a.p.sortorder.toUpperCase() == "DESC" ? s.orderBy(a.p.sortname, "d", f[d].stype, f[d].srcfmt) : s.orderBy(a.p.sortname, "a", f[d].stype, f[d].srcfmt));
+                                    var n = s.select(), u = parseInt(a.p.rowNum, 10), t = n.length, v = parseInt(a.p.page, 10), x = Math.ceil(t / u), r = {}, n = n.slice((v - 1) * u, v * u), f = s = null;
+                                    r[a.p.localReader.total] = x;
+                                    r[a.p.localReader.page] = v;
+                                    r[a.p.localReader.records] = t;
+                                    r[a.p.localReader.root] = n;
+                                    r[a.p.localReader.userdata] = a.p.userData;
+                                    n = null;
+                                    return r
+                                }
+                            }
+                        }, ca = function () {
+                            a.grid.hDiv.loading = true;
+                            if (!a.p.hiddengrid)switch (a.p.loadui) {
+                                case "enable":
+                                    b("#load_" + b.jgrid.jqID(a.p.id)).show();
+                                    break;
+                                case "block":
+                                    b("#lui_" + b.jgrid.jqID(a.p.id)).show();
+                                    b("#load_" + b.jgrid.jqID(a.p.id)).show()
+                            }
+                        }, O = function () {
+                            a.grid.hDiv.loading = false;
+                            switch (a.p.loadui) {
+                                case "enable":
+                                    b("#load_" + b.jgrid.jqID(a.p.id)).hide();
+                                    break;
+                                case "block":
+                                    b("#lui_" + b.jgrid.jqID(a.p.id)).hide();
+                                    b("#load_" + b.jgrid.jqID(a.p.id)).hide()
+                            }
+                        }, I = function (c) {
+                            if (!a.grid.hDiv.loading) {
+                                var d = a.p.scroll && c === false, e = {}, f, g = a.p.prmNames;
+                                if (a.p.page <= 0)a.p.page = 1;
+                                if (g.search !== null)e[g.search] = a.p.search;
+                                g.nd !== null && (e[g.nd] = (new Date).getTime());
+                                if (g.rows !== null)e[g.rows] = a.p.rowNum;
+                                if (g.page !== null)e[g.page] = a.p.page;
+                                if (g.sort !== null)e[g.sort] = a.p.sortname;
+                                if (g.order !== null)e[g.order] = a.p.sortorder;
+                                if (a.p.rowTotal !== null && g.totalrows !== null)e[g.totalrows] =
+                                    a.p.rowTotal;
+                                var h = b.isFunction(a.p.loadComplete), i = h ? a.p.loadComplete : null, j = 0, c = c || 1;
+                                if (c > 1)if (g.npage !== null) {
+                                    e[g.npage] = c;
+                                    j = c - 1;
+                                    c = 1
+                                } else i = function (b) {
+                                    a.p.page++;
+                                    a.grid.hDiv.loading = false;
+                                    h && a.p.loadComplete.call(a, b);
+                                    I(c - 1)
+                                }; else g.npage !== null && delete a.p.postData[g.npage];
+                                if (a.p.grouping) {
+                                    b(a).jqGrid("groupingSetup");
+                                    var k = a.p.groupingView, l, m = "";
+                                    for (l = 0; l < k.groupField.length; l++)m = m + (k.groupField[l] + " " + k.groupOrder[l] + ", ");
+                                    e[g.sort] = m + e[g.sort]
+                                }
+                                b.extend(a.p.postData, e);
+                                var q = !a.p.scroll ?
+                                    1 : a.rows.length - 1, e = b(a).triggerHandler("jqGridBeforeRequest");
+                                if (!(e === false || e === "stop"))if (b.isFunction(a.p.datatype))a.p.datatype.call(a, a.p.postData, "load_" + a.p.id); else {
+                                    if (b.isFunction(a.p.beforeRequest)) {
+                                        e = a.p.beforeRequest.call(a);
+                                        e === void 0 && (e = true);
+                                        if (e === false)return
+                                    }
+                                    f = a.p.datatype.toLowerCase();
+                                    switch (f) {
+                                        case "json":
+                                        case "jsonp":
+                                        case "xml":
+                                        case "script":
+                                            b.ajax(b.extend({url: a.p.url, type: a.p.mtype, dataType: f, data: b.isFunction(a.p.serializeGridData) ? a.p.serializeGridData.call(a, a.p.postData) :
+                                                a.p.postData, success: function (e, g, h) {
+                                                if (b.isFunction(a.p.beforeProcessing) && a.p.beforeProcessing.call(a, e, g, h) === false)O(); else {
+                                                    f === "xml" ? $(e, a.grid.bDiv, q, c > 1, j) : aa(e, a.grid.bDiv, q, c > 1, j);
+                                                    b(a).triggerHandler("jqGridLoadComplete", [e]);
+                                                    i && i.call(a, e);
+                                                    b(a).triggerHandler("jqGridAfterLoadComplete", [e]);
+                                                    d && a.grid.populateVisible();
+                                                    if (a.p.loadonce || a.p.treeGrid)a.p.datatype = "local";
+                                                    c === 1 && O()
+                                                }
+                                            }, error: function (d, e, f) {
+                                                b.isFunction(a.p.loadError) && a.p.loadError.call(a, d, e, f);
+                                                c === 1 && O()
+                                            }, beforeSend: function (c, d) {
+                                                var e = true;
+                                                b.isFunction(a.p.loadBeforeSend) && (e = a.p.loadBeforeSend.call(a, c, d));
+                                                e === void 0 && (e = true);
+                                                if (e === false)return false;
+                                                ca()
+                                            }}, b.jgrid.ajaxOptions, a.p.ajaxGridOptions));
+                                            break;
+                                        case "xmlstring":
+                                            ca();
+                                            e = b.jgrid.stringToDoc(a.p.datastr);
+                                            $(e, a.grid.bDiv);
+                                            b(a).triggerHandler("jqGridLoadComplete", [e]);
+                                            h && a.p.loadComplete.call(a, e);
+                                            b(a).triggerHandler("jqGridAfterLoadComplete", [e]);
+                                            a.p.datatype = "local";
+                                            a.p.datastr = null;
+                                            O();
+                                            break;
+                                        case "jsonstring":
+                                            ca();
+                                            e = typeof a.p.datastr == "string" ? b.jgrid.parse(a.p.datastr) :
+                                                a.p.datastr;
+                                            aa(e, a.grid.bDiv);
+                                            b(a).triggerHandler("jqGridLoadComplete", [e]);
+                                            h && a.p.loadComplete.call(a, e);
+                                            b(a).triggerHandler("jqGridAfterLoadComplete", [e]);
+                                            a.p.datatype = "local";
+                                            a.p.datastr = null;
+                                            O();
+                                            break;
+                                        case "local":
+                                        case "clientside":
+                                            ca();
+                                            a.p.datatype = "local";
+                                            e = ma();
+                                            aa(e, a.grid.bDiv, q, c > 1, j);
+                                            b(a).triggerHandler("jqGridLoadComplete", [e]);
+                                            i && i.call(a, e);
+                                            b(a).triggerHandler("jqGridAfterLoadComplete", [e]);
+                                            d && a.grid.populateVisible();
+                                            O()
+                                    }
+                                }
+                            }
+                        }, da = function (c) {
+                            b("#cb_" + b.jgrid.jqID(a.p.id), a.grid.hDiv)[a.p.useProp ?
+                                "prop" : "attr"]("checked", c);
+                            if (a.p.frozenColumns && a.p.id + "_frozen")b("#cb_" + b.jgrid.jqID(a.p.id), a.grid.fhDiv)[a.p.useProp ? "prop" : "attr"]("checked", c)
+                        };
+                        l = function (c, e) {
+                            var d = "", f = "<table cellspacing='0' cellpadding='0' border='0' style='table-layout:auto;' class='ui-pg-table'><tbody><tr>", g = "", h, j, k, l, m = function (c) {
+                                var e;
+                                b.isFunction(a.p.onPaging) && (e = a.p.onPaging.call(a, c));
+                                a.p.selrow = null;
+                                if (a.p.multiselect) {
+                                    a.p.selarrrow = [];
+                                    da(false)
+                                }
+                                a.p.savedRow = [];
+                                return e == "stop" ? false : true
+                            }, c = c.substr(1), e =
+                                e + ("_" + c);
+                            h = "pg_" + c;
+                            j = c + "_left";
+                            k = c + "_center";
+                            l = c + "_right";
+                            b("#" + b.jgrid.jqID(c)).append("<div id='" + h + "' class='ui-pager-control' role='group'><table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table' style='width:100%;table-layout:fixed;height:100%;' role='row'><tbody><tr><td id='" + j + "' align='left'></td><td id='" + k + "' align='center' style='white-space:pre;'></td><td id='" + l + "' align='right'></td></tr></tbody></table></div>").attr("dir", "ltr");
+                            if (a.p.rowList.length > 0) {
+                                g = "<td dir='" +
+                                    i + "'>";
+                                g = g + "<select class='ui-pg-selbox' role='listbox'>";
+                                for (j = 0; j < a.p.rowList.length; j++)g = g + ('<option role="option" value="' + a.p.rowList[j] + '"' + (a.p.rowNum == a.p.rowList[j] ? ' selected="selected"' : "") + ">" + a.p.rowList[j] + "</option>");
+                                g = g + "</select></td>"
+                            }
+                            i == "rtl" && (f = f + g);
+                            a.p.pginput === true && (d = "<td dir='" + i + "'>" + b.jgrid.format(a.p.pgtext || "", "<input class='ui-pg-input' type='text' size='2' maxlength='7' value='0' role='textbox'/>", "<span id='sp_1_" + b.jgrid.jqID(c) + "'></span>") + "</td>");
+                            if (a.p.pgbuttons ===
+                                true) {
+                                j = ["first" + e, "prev" + e, "next" + e, "last" + e];
+                                i == "rtl" && j.reverse();
+                                f = f + ("<td id='" + j[0] + "' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-first'></span></td>");
+                                f = f + ("<td id='" + j[1] + "' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-prev'></span></td>");
+                                f = f + (d !== "" ? "<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>" + d + "<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>" :
+                                    "") + ("<td id='" + j[2] + "' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-next'></span></td>");
+                                f = f + ("<td id='" + j[3] + "' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-end'></span></td>")
+                            } else d !== "" && (f = f + d);
+                            i == "ltr" && (f = f + g);
+                            f = f + "</tr></tbody></table>";
+                            a.p.viewrecords === true && b("td#" + c + "_" + a.p.recordpos, "#" + h).append("<div dir='" + i + "' style='text-align:" + a.p.recordpos + "' class='ui-paging-info'></div>");
+                            b("td#" + c + "_" + a.p.pagerpos, "#" + h).append(f);
+                            g = b(".ui-jqgrid").css("font-size") ||
+                                "11px";
+                            b(document.body).append("<div id='testpg' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:" + g + ";visibility:hidden;' ></div>");
+                            f = b(f).clone().appendTo("#testpg").width();
+                            b("#testpg").remove();
+                            if (f > 0) {
+                                d !== "" && (f = f + 50);
+                                b("td#" + c + "_" + a.p.pagerpos, "#" + h).width(f)
+                            }
+                            a.p._nvtd = [];
+                            a.p._nvtd[0] = f ? Math.floor((a.p.width - f) / 2) : Math.floor(a.p.width / 3);
+                            a.p._nvtd[1] = 0;
+                            f = null;
+                            b(".ui-pg-selbox", "#" + h).bind("change", function () {
+                                a.p.page = Math.round(a.p.rowNum * (a.p.page - 1) / this.value - 0.5) + 1;
+                                a.p.rowNum =
+                                    this.value;
+                                a.p.pager && b(".ui-pg-selbox", a.p.pager).val(this.value);
+                                a.p.toppager && b(".ui-pg-selbox", a.p.toppager).val(this.value);
+                                if (!m("records"))return false;
+                                I();
+                                return false
+                            });
+                            if (a.p.pgbuttons === true) {
+                                b(".ui-pg-button", "#" + h).hover(function () {
+                                    if (b(this).hasClass("ui-state-disabled"))this.style.cursor = "default"; else {
+                                        b(this).addClass("ui-state-hover");
+                                        this.style.cursor = "pointer"
+                                    }
+                                }, function () {
+                                    if (!b(this).hasClass("ui-state-disabled")) {
+                                        b(this).removeClass("ui-state-hover");
+                                        this.style.cursor = "default"
+                                    }
+                                });
+                                b("#first" + b.jgrid.jqID(e) + ", #prev" + b.jgrid.jqID(e) + ", #next" + b.jgrid.jqID(e) + ", #last" + b.jgrid.jqID(e)).click(function () {
+                                    var b = o(a.p.page, 1), c = o(a.p.lastpage, 1), d = false, f = true, g = true, h = true, i = true;
+                                    if (c === 0 || c === 1)i = h = g = f = false; else if (c > 1 && b >= 1)if (b === 1)g = f = false; else {
+                                        if (b === c)i = h = false
+                                    } else if (c > 1 && b === 0) {
+                                        i = h = false;
+                                        b = c - 1
+                                    }
+                                    if (this.id === "first" + e && f) {
+                                        a.p.page = 1;
+                                        d = true
+                                    }
+                                    if (this.id === "prev" + e && g) {
+                                        a.p.page = b - 1;
+                                        d = true
+                                    }
+                                    if (this.id === "next" + e && h) {
+                                        a.p.page = b + 1;
+                                        d = true
+                                    }
+                                    if (this.id === "last" + e && i) {
+                                        a.p.page = c;
+                                        d =
+                                            true
+                                    }
+                                    if (d) {
+                                        if (!m(this.id))return false;
+                                        I()
+                                    }
+                                    return false
+                                })
+                            }
+                            a.p.pginput === true && b("input.ui-pg-input", "#" + h).keypress(function (c) {
+                                if ((c.charCode ? c.charCode : c.keyCode ? c.keyCode : 0) == 13) {
+                                    a.p.page = b(this).val() > 0 ? b(this).val() : a.p.page;
+                                    if (!m("user"))return false;
+                                    I();
+                                    return false
+                                }
+                                return this
+                            })
+                        };
+                        var ja = function (c, e, d, f) {
+                            if (a.p.colModel[e].sortable && !(a.p.savedRow.length > 0)) {
+                                if (!d) {
+                                    if (a.p.lastsort == e)if (a.p.sortorder == "asc")a.p.sortorder = "desc"; else {
+                                        if (a.p.sortorder == "desc")a.p.sortorder = "asc"
+                                    } else a.p.sortorder =
+                                        a.p.colModel[e].firstsortorder || "asc";
+                                    a.p.page = 1
+                                }
+                                if (f) {
+                                    if (a.p.lastsort == e && a.p.sortorder == f && !d)return;
+                                    a.p.sortorder = f
+                                }
+                                d = a.grid.headers[a.p.lastsort].el;
+                                f = a.grid.headers[e].el;
+                                b("span.ui-grid-ico-sort", d).addClass("ui-state-disabled");
+                                b(d).attr("aria-selected", "false");
+                                b("span.ui-icon-" + a.p.sortorder, f).removeClass("ui-state-disabled");
+                                b(f).attr("aria-selected", "true");
+                                if (!a.p.viewsortcols[0] && a.p.lastsort != e) {
+                                    b("span.s-ico", d).hide();
+                                    b("span.s-ico", f).show()
+                                }
+                                c = c.substring(5 + a.p.id.length + 1);
+                                a.p.sortname =
+                                    a.p.colModel[e].index || c;
+                                d = a.p.sortorder;
+                                if (b(a).triggerHandler("jqGridSortCol", [c, e, d]) === "stop")a.p.lastsort = e; else if (b.isFunction(a.p.onSortCol) && a.p.onSortCol.call(a, c, e, d) == "stop")a.p.lastsort = e; else {
+                                    if (a.p.datatype == "local")a.p.deselectAfterSort && b(a).jqGrid("resetSelection"); else {
+                                        a.p.selrow = null;
+                                        a.p.multiselect && da(false);
+                                        a.p.selarrrow = [];
+                                        a.p.savedRow = []
+                                    }
+                                    if (a.p.scroll) {
+                                        d = a.grid.bDiv.scrollLeft;
+                                        N.call(a, true, false);
+                                        a.grid.hDiv.scrollLeft = d
+                                    }
+                                    a.p.subGrid && a.p.datatype == "local" && b("td.sgexpanded",
+                                        "#" + b.jgrid.jqID(a.p.id)).each(function () {
+                                            b(this).trigger("click")
+                                        });
+                                    I();
+                                    a.p.lastsort = e;
+                                    if (a.p.sortname != c && e)a.p.lastsort = e
+                                }
+                            }
+                        }, oa = function (c) {
+                            var e, d = {}, f = b.jgrid.cellWidth() ? 0 : a.p.cellLayout;
+                            for (e = d[0] = d[1] = d[2] = 0; e <= c; e++)a.p.colModel[e].hidden === false && (d[0] = d[0] + (a.p.colModel[e].width + f));
+                            a.p.direction == "rtl" && (d[0] = a.p.width - d[0]);
+                            d[0] = d[0] - a.grid.bDiv.scrollLeft;
+                            b(a.grid.cDiv).is(":visible") && (d[1] = d[1] + (b(a.grid.cDiv).height() + parseInt(b(a.grid.cDiv).css("padding-top"), 10) + parseInt(b(a.grid.cDiv).css("padding-bottom"),
+                                10)));
+                            if (a.p.toolbar[0] === true && (a.p.toolbar[1] == "top" || a.p.toolbar[1] == "both"))d[1] = d[1] + (b(a.grid.uDiv).height() + parseInt(b(a.grid.uDiv).css("border-top-width"), 10) + parseInt(b(a.grid.uDiv).css("border-bottom-width"), 10));
+                            a.p.toppager && (d[1] = d[1] + (b(a.grid.topDiv).height() + parseInt(b(a.grid.topDiv).css("border-bottom-width"), 10)));
+                            d[2] = d[2] + (b(a.grid.bDiv).height() + b(a.grid.hDiv).height());
+                            return d
+                        }, ka = function (c) {
+                            var d, e = a.grid.headers, f = b.jgrid.getCellIndex(c);
+                            for (d = 0; d < e.length; d++)if (c === e[d].el) {
+                                f =
+                                    d;
+                                break
+                            }
+                            return f
+                        };
+                        this.p.id = this.id;
+                        -1 == b.inArray(a.p.multikey, ["shiftKey", "altKey", "ctrlKey"]) && (a.p.multikey = !1);
+                        a.p.keyIndex = !1;
+                        for (e = 0; e < a.p.colModel.length; e++)a.p.colModel[e] = b.extend(!0, {}, a.p.cmTemplate, a.p.colModel[e].template || {}, a.p.colModel[e]), !1 === a.p.keyIndex && !0 === a.p.colModel[e].key && (a.p.keyIndex = e);
+                        a.p.sortorder = a.p.sortorder.toLowerCase();
+                        !0 === a.p.grouping && (a.p.scroll = !1, a.p.rownumbers = !1, a.p.treeGrid = !1, a.p.gridview = !0);
+                        if (!0 === this.p.treeGrid) {
+                            try {
+                                b(this).jqGrid("setTreeGrid")
+                            } catch (qa) {
+                            }
+                            "local" !=
+                                a.p.datatype && (a.p.localReader = {id: "_id_"})
+                        }
+                        if (this.p.subGrid)try {
+                            b(a).jqGrid("setSubGrid")
+                        } catch (ra) {
+                        }
+                        this.p.multiselect && (this.p.colNames.unshift("<input role='checkbox' id='cb_" + this.p.id + "' class='cbox' type='checkbox'/>"), this.p.colModel.unshift({name: "cb", width: b.jgrid.cellWidth() ? a.p.multiselectWidth + a.p.cellLayout : a.p.multiselectWidth, sortable: !1, resizable: !1, hidedlg: !0, search: !1, align: "center", fixed: !0}));
+                        this.p.rownumbers && (this.p.colNames.unshift(""), this.p.colModel.unshift({name: "rn",
+                            width: a.p.rownumWidth, sortable: !1, resizable: !1, hidedlg: !0, search: !1, align: "center", fixed: !0}));
+                        a.p.xmlReader = b.extend(!0, {root: "rows", row: "row", page: "rows>page", total: "rows>total", records: "rows>records", repeatitems: !0, cell: "cell", id: "[id]", userdata: "userdata", subgrid: {root: "rows", row: "row", repeatitems: !0, cell: "cell"}}, a.p.xmlReader);
+                        a.p.jsonReader = b.extend(!0, {root: "rows", page: "page", total: "total", records: "records", repeatitems: !0, cell: "cell", id: "id", userdata: "userdata", subgrid: {root: "rows", repeatitems: !0,
+                            cell: "cell"}}, a.p.jsonReader);
+                        a.p.localReader = b.extend(!0, {root: "rows", page: "page", total: "total", records: "records", repeatitems: !1, cell: "cell", id: "id", userdata: "userdata", subgrid: {root: "rows", repeatitems: !0, cell: "cell"}}, a.p.localReader);
+                        a.p.scroll && (a.p.pgbuttons = !1, a.p.pginput = !1, a.p.rowList = []);
+                        a.p.data.length && S();
+                        var x = "<thead><tr class='ui-jqgrid-labels' role='rowheader'>", la, L, ea, ba, fa, A, n, W;
+                        L = W = "";
+                        if (!0 === a.p.shrinkToFit && !0 === a.p.forceFit)for (e = a.p.colModel.length - 1; 0 <= e; e--)if (!a.p.colModel[e].hidden) {
+                            a.p.colModel[e].resizable = !1;
+                            break
+                        }
+                        "horizontal" == a.p.viewsortcols[1] && (W = " ui-i-asc", L = " ui-i-desc");
+                        la = k ? "class='ui-th-div-ie'" : "";
+                        W = "<span class='s-ico' style='display:none'><span sort='asc' class='ui-grid-ico-sort ui-icon-asc" + W + " ui-state-disabled ui-icon ui-icon-triangle-1-n ui-sort-" + i + "'></span>" + ("<span sort='desc' class='ui-grid-ico-sort ui-icon-desc" + L + " ui-state-disabled ui-icon ui-icon-triangle-1-s ui-sort-" + i + "'></span></span>");
+                        for (e = 0; e < this.p.colNames.length; e++)L = a.p.headertitles ? ' title="' + b.jgrid.stripHtml(a.p.colNames[e]) +
+                            '"' : "", x += "<th id='" + a.p.id + "_" + a.p.colModel[e].name + "' role='columnheader' class='ui-state-default ui-th-column ui-th-" + i + "'" + L + ">", L = a.p.colModel[e].index || a.p.colModel[e].name, x += "<div id='jqgh_" + a.p.id + "_" + a.p.colModel[e].name + "' " + la + ">" + a.p.colNames[e], a.p.colModel[e].width = a.p.colModel[e].width ? parseInt(a.p.colModel[e].width, 10) : 150, "boolean" !== typeof a.p.colModel[e].title && (a.p.colModel[e].title = !0), L == a.p.sortname && (a.p.lastsort = e), x += W + "</div></th>";
+                        W = null;
+                        b(this).append(x + "</tr></thead>");
+                        b("thead tr:first th", this).hover(function () {
+                            b(this).addClass("ui-state-hover")
+                        }, function () {
+                            b(this).removeClass("ui-state-hover")
+                        });
+                        if (this.p.multiselect) {
+                            var ga = [], X;
+                            b("#cb_" + b.jgrid.jqID(a.p.id), this).bind("click", function () {
+                                a.p.selarrrow = [];
+                                var c = a.p.frozenColumns === true ? a.p.id + "_frozen" : "";
+                                if (this.checked) {
+                                    b(a.rows).each(function (d) {
+                                        if (d > 0 && !b(this).hasClass("ui-subgrid") && !b(this).hasClass("jqgroup") && !b(this).hasClass("ui-state-disabled")) {
+                                            b("#jqg_" + b.jgrid.jqID(a.p.id) + "_" + b.jgrid.jqID(this.id))[a.p.useProp ?
+                                                "prop" : "attr"]("checked", true);
+                                            b(this).addClass("ui-state-highlight").attr("aria-selected", "true");
+                                            a.p.selarrrow.push(this.id);
+                                            a.p.selrow = this.id;
+                                            if (c) {
+                                                b("#jqg_" + b.jgrid.jqID(a.p.id) + "_" + b.jgrid.jqID(this.id), a.grid.fbDiv)[a.p.useProp ? "prop" : "attr"]("checked", true);
+                                                b("#" + b.jgrid.jqID(this.id), a.grid.fbDiv).addClass("ui-state-highlight")
+                                            }
+                                        }
+                                    });
+                                    X = true;
+                                    ga = []
+                                } else {
+                                    b(a.rows).each(function (d) {
+                                        if (d > 0 && !b(this).hasClass("ui-subgrid") && !b(this).hasClass("ui-state-disabled")) {
+                                            b("#jqg_" + b.jgrid.jqID(a.p.id) + "_" +
+                                                b.jgrid.jqID(this.id))[a.p.useProp ? "prop" : "attr"]("checked", false);
+                                            b(this).removeClass("ui-state-highlight").attr("aria-selected", "false");
+                                            ga.push(this.id);
+                                            if (c) {
+                                                b("#jqg_" + b.jgrid.jqID(a.p.id) + "_" + b.jgrid.jqID(this.id), a.grid.fbDiv)[a.p.useProp ? "prop" : "attr"]("checked", false);
+                                                b("#" + b.jgrid.jqID(this.id), a.grid.fbDiv).removeClass("ui-state-highlight")
+                                            }
+                                        }
+                                    });
+                                    a.p.selrow = null;
+                                    X = false
+                                }
+                                b(a).triggerHandler("jqGridSelectAll", [X ? a.p.selarrrow : ga, X]);
+                                b.isFunction(a.p.onSelectAll) && a.p.onSelectAll.call(a, X ? a.p.selarrrow :
+                                    ga, X)
+                            })
+                        }
+                        !0 === a.p.autowidth && (x = b(m).innerWidth(), a.p.width = 0 < x ? x : "nw");
+                        (function () {
+                            var d = 0, e = b.jgrid.cellWidth() ? 0 : o(a.p.cellLayout, 0), f = 0, g, i = o(a.p.scrollOffset, 0), j, k = false, l, m = 0, n = 0, p;
+                            b.each(a.p.colModel, function () {
+                                if (typeof this.hidden === "undefined")this.hidden = false;
+                                this.widthOrg = j = o(this.width, 0);
+                                if (this.hidden === false) {
+                                    d = d + (j + e);
+                                    this.fixed ? m = m + (j + e) : f++;
+                                    n++
+                                }
+                            });
+                            if (isNaN(a.p.width))a.p.width = d + (a.p.shrinkToFit === false && !isNaN(a.p.height) ? i : 0);
+                            c.width = a.p.width;
+                            a.p.tblwidth = d;
+                            if (a.p.shrinkToFit ===
+                                false && a.p.forceFit === true)a.p.forceFit = false;
+                            if (a.p.shrinkToFit === true && f > 0) {
+                                l = c.width - e * f - m;
+                                if (!isNaN(a.p.height)) {
+                                    l = l - i;
+                                    k = true
+                                }
+                                d = 0;
+                                b.each(a.p.colModel, function (b) {
+                                    if (this.hidden === false && !this.fixed) {
+                                        this.width = j = Math.round(l * this.width / (a.p.tblwidth - e * f - m));
+                                        d = d + j;
+                                        g = b
+                                    }
+                                });
+                                p = 0;
+                                k ? c.width - m - (d + e * f) !== i && (p = c.width - m - (d + e * f) - i) : !k && Math.abs(c.width - m - (d + e * f)) !== 1 && (p = c.width - m - (d + e * f));
+                                a.p.colModel[g].width = a.p.colModel[g].width + p;
+                                a.p.tblwidth = d + p + e * f + m;
+                                if (a.p.tblwidth > a.p.width) {
+                                    a.p.colModel[g].width =
+                                        a.p.colModel[g].width - (a.p.tblwidth - parseInt(a.p.width, 10));
+                                    a.p.tblwidth = a.p.width
+                                }
+                            }
+                        })();
+                        b(m).css("width", c.width + "px").append("<div class='ui-jqgrid-resize-mark' id='rs_m" + a.p.id + "'>&#160;</div>");
+                        b(j).css("width", c.width + "px");
+                        var x = b("thead:first", a).get(0), R = "";
+                        a.p.footerrow && (R += "<table role='grid' style='width:" + a.p.tblwidth + "px' class='ui-jqgrid-ftable' cellspacing='0' cellpadding='0' border='0'><tbody><tr role='row' class='ui-widget-content footrow footrow-" + i + "'>");
+                        var j = b("tr:first", x),
+                            Y = "<tr class='jqgfirstrow' role='row' style='height:auto'>";
+                        a.p.disableClick = !1;
+                        b("th", j).each(function (d) {
+                            ea = a.p.colModel[d].width;
+                            if (typeof a.p.colModel[d].resizable === "undefined")a.p.colModel[d].resizable = true;
+                            if (a.p.colModel[d].resizable) {
+                                ba = document.createElement("span");
+                                b(ba).html("&#160;").addClass("ui-jqgrid-resize ui-jqgrid-resize-" + i);
+                                b.browser.opera || b(ba).css("cursor", "col-resize");
+                                b(this).addClass(a.p.resizeclass)
+                            } else ba = "";
+                            b(this).css("width", ea + "px").prepend(ba);
+                            var e = "";
+                            if (a.p.colModel[d].hidden) {
+                                b(this).css("display",
+                                    "none");
+                                e = "display:none;"
+                            }
+                            Y = Y + ("<td role='gridcell' style='height:0px;width:" + ea + "px;" + e + "'></td>");
+                            c.headers[d] = {width: ea, el: this};
+                            fa = a.p.colModel[d].sortable;
+                            if (typeof fa !== "boolean")fa = a.p.colModel[d].sortable = true;
+                            e = a.p.colModel[d].name;
+                            e == "cb" || e == "subgrid" || e == "rn" || a.p.viewsortcols[2] && b(">div", this).addClass("ui-jqgrid-sortable");
+                            if (fa)if (a.p.viewsortcols[0]) {
+                                b("div span.s-ico", this).show();
+                                d == a.p.lastsort && b("div span.ui-icon-" + a.p.sortorder, this).removeClass("ui-state-disabled")
+                            } else if (d ==
+                                a.p.lastsort) {
+                                b("div span.s-ico", this).show();
+                                b("div span.ui-icon-" + a.p.sortorder, this).removeClass("ui-state-disabled")
+                            }
+                            a.p.footerrow && (R = R + ("<td role='gridcell' " + p(d, 0, "", null, "", false) + ">&#160;</td>"))
+                        }).mousedown(function (d) {
+                                if (b(d.target).closest("th>span.ui-jqgrid-resize").length == 1) {
+                                    var e = ka(this);
+                                    if (a.p.forceFit === true) {
+                                        var f = a.p, g = e, i;
+                                        for (i = e + 1; i < a.p.colModel.length; i++)if (a.p.colModel[i].hidden !== true) {
+                                            g = i;
+                                            break
+                                        }
+                                        f.nv = g - e
+                                    }
+                                    c.dragStart(e, d, oa(e));
+                                    return false
+                                }
+                            }).click(function (c) {
+                                if (a.p.disableClick)return a.p.disableClick =
+                                    false;
+                                var d = "th>div.ui-jqgrid-sortable", e, f;
+                                a.p.viewsortcols[2] || (d = "th>div>span>span.ui-grid-ico-sort");
+                                c = b(c.target).closest(d);
+                                if (c.length == 1) {
+                                    d = ka(this);
+                                    if (!a.p.viewsortcols[2]) {
+                                        e = true;
+                                        f = c.attr("sort")
+                                    }
+                                    ja(b("div", this)[0].id, d, e, f);
+                                    return false
+                                }
+                            });
+                        if (a.p.sortable && b.fn.sortable)try {
+                            b(a).jqGrid("sortableColumns", j)
+                        } catch (sa) {
+                        }
+                        a.p.footerrow && (R += "</tr></tbody></table>");
+                        Y += "</tr>";
+                        this.appendChild(document.createElement("tbody"));
+                        b(this).addClass("ui-jqgrid-btable").append(Y);
+                        var Y = null, j = b("<table class='ui-jqgrid-htable' style='width:" +
+                            a.p.tblwidth + "px' role='grid' aria-labelledby='gbox_" + this.id + "' cellspacing='0' cellpadding='0' border='0'></table>").append(x), D = a.p.caption && !0 === a.p.hiddengrid ? !0 : !1;
+                        e = b("<div class='ui-jqgrid-hbox" + ("rtl" == i ? "-rtl" : "") + "'></div>");
+                        x = null;
+                        c.hDiv = document.createElement("div");
+                        b(c.hDiv).css({width: c.width + "px"}).addClass("ui-state-default ui-jqgrid-hdiv").append(e);
+                        b(e).append(j);
+                        j = null;
+                        D && b(c.hDiv).hide();
+                        a.p.pager && ("string" == typeof a.p.pager ? "#" != a.p.pager.substr(0, 1) && (a.p.pager = "#" + a.p.pager) :
+                            a.p.pager = "#" + b(a.p.pager).attr("id"), b(a.p.pager).css({width: c.width + "px"}).appendTo(m).addClass("ui-state-default ui-jqgrid-pager ui-corner-bottom"), D && b(a.p.pager).hide(), l(a.p.pager, ""));
+                        !1 === a.p.cellEdit && !0 === a.p.hoverrows && b(a).bind("mouseover",function (a) {
+                            n = b(a.target).closest("tr.jqgrow");
+                            b(n).attr("class") !== "ui-subgrid" && b(n).addClass("ui-state-hover")
+                        }).bind("mouseout", function (a) {
+                            n = b(a.target).closest("tr.jqgrow");
+                            b(n).removeClass("ui-state-hover")
+                        });
+                        var t, E, ha;
+                        b(a).before(c.hDiv).click(function (c) {
+                            A =
+                                c.target;
+                            n = b(A, a.rows).closest("tr.jqgrow");
+                            if (b(n).length === 0 || n[0].className.indexOf("ui-state-disabled") > -1 || (b(A, a).closest("table.ui-jqgrid-btable").attr("id") || "").replace("_frozen", "") !== a.id)return this;
+                            var d = b(A).hasClass("cbox"), e = b(a).triggerHandler("jqGridBeforeSelectRow", [n[0].id, c]);
+                            (e = e === false || e === "stop" ? false : true) && b.isFunction(a.p.beforeSelectRow) && (e = a.p.beforeSelectRow.call(a, n[0].id, c));
+                            if (!(A.tagName == "A" || (A.tagName == "INPUT" || A.tagName == "TEXTAREA" || A.tagName == "OPTION" || A.tagName ==
+                                "SELECT") && !d) && e === true) {
+                                t = n[0].id;
+                                E = b.jgrid.getCellIndex(A);
+                                ha = b(A).closest("td,th").html();
+                                b(a).triggerHandler("jqGridCellSelect", [t, E, ha, c]);
+                                b.isFunction(a.p.onCellSelect) && a.p.onCellSelect.call(a, t, E, ha, c);
+                                if (a.p.cellEdit === true)if (a.p.multiselect && d)b(a).jqGrid("setSelection", t, true, c); else {
+                                    t = n[0].rowIndex;
+                                    try {
+                                        b(a).jqGrid("editCell", t, E, true)
+                                    } catch (f) {
+                                    }
+                                } else if (a.p.multikey)if (c[a.p.multikey])b(a).jqGrid("setSelection", t, true, c); else {
+                                    if (a.p.multiselect && d) {
+                                        d = b("#jqg_" + b.jgrid.jqID(a.p.id) + "_" +
+                                            t).is(":checked");
+                                        b("#jqg_" + b.jgrid.jqID(a.p.id) + "_" + t)[a.p.useProp ? "prop" : "attr"]("checked", d)
+                                    }
+                                } else {
+                                    if (a.p.multiselect && a.p.multiboxonly && !d) {
+                                        var g = a.p.frozenColumns ? a.p.id + "_frozen" : "";
+                                        b(a.p.selarrrow).each(function (c, d) {
+                                            var e = a.rows.namedItem(d);
+                                            b(e).removeClass("ui-state-highlight");
+                                            b("#jqg_" + b.jgrid.jqID(a.p.id) + "_" + b.jgrid.jqID(d))[a.p.useProp ? "prop" : "attr"]("checked", false);
+                                            if (g) {
+                                                b("#" + b.jgrid.jqID(d), "#" + b.jgrid.jqID(g)).removeClass("ui-state-highlight");
+                                                b("#jqg_" + b.jgrid.jqID(a.p.id) + "_" +
+                                                    b.jgrid.jqID(d), "#" + b.jgrid.jqID(g))[a.p.useProp ? "prop" : "attr"]("checked", false)
+                                            }
+                                        });
+                                        a.p.selarrrow = []
+                                    }
+                                    b(a).jqGrid("setSelection", t, true, c)
+                                }
+                            }
+                        }).bind("reloadGrid",function (c, d) {
+                                if (a.p.treeGrid === true)a.p.datatype = a.p.treedatatype;
+                                d && d.current && a.grid.selectionPreserver(a);
+                                if (a.p.datatype == "local") {
+                                    b(a).jqGrid("resetSelection");
+                                    a.p.data.length && S()
+                                } else if (!a.p.treeGrid) {
+                                    a.p.selrow = null;
+                                    if (a.p.multiselect) {
+                                        a.p.selarrrow = [];
+                                        da(false)
+                                    }
+                                    a.p.savedRow = []
+                                }
+                                a.p.scroll && N.call(a, true, false);
+                                if (d && d.page) {
+                                    var e =
+                                        d.page;
+                                    if (e > a.p.lastpage)e = a.p.lastpage;
+                                    e < 1 && (e = 1);
+                                    a.p.page = e;
+                                    a.grid.bDiv.scrollTop = a.grid.prevRowHeight ? (e - 1) * a.grid.prevRowHeight * a.p.rowNum : 0
+                                }
+                                if (a.grid.prevRowHeight && a.p.scroll) {
+                                    delete a.p.lastpage;
+                                    a.grid.populateVisible()
+                                } else a.grid.populate();
+                                a.p._inlinenav === true && b(a).jqGrid("showAddEditButtons");
+                                return false
+                            }).dblclick(function (c) {
+                                A = c.target;
+                                n = b(A, a.rows).closest("tr.jqgrow");
+                                if (b(n).length !== 0) {
+                                    t = n[0].rowIndex;
+                                    E = b.jgrid.getCellIndex(A);
+                                    b(a).triggerHandler("jqGridDblClickRow", [b(n).attr("id"),
+                                        t, E, c]);
+                                    b.isFunction(this.p.ondblClickRow) && a.p.ondblClickRow.call(a, b(n).attr("id"), t, E, c)
+                                }
+                            }).bind("contextmenu", function (c) {
+                                A = c.target;
+                                n = b(A, a.rows).closest("tr.jqgrow");
+                                if (b(n).length !== 0) {
+                                    a.p.multiselect || b(a).jqGrid("setSelection", n[0].id, true, c);
+                                    t = n[0].rowIndex;
+                                    E = b.jgrid.getCellIndex(A);
+                                    b(a).triggerHandler("jqGridRightClickRow", [b(n).attr("id"), t, E, c]);
+                                    b.isFunction(this.p.onRightClickRow) && a.p.onRightClickRow.call(a, b(n).attr("id"), t, E, c)
+                                }
+                            });
+                        c.bDiv = document.createElement("div");
+                        k && "auto" ===
+                            ("" + a.p.height).toLowerCase() && (a.p.height = "100%");
+                        b(c.bDiv).append(b('<div style="position:relative;' + (k && 8 > b.browser.version ? "height:0.01%;" : "") + '"></div>').append("<div></div>").append(this)).addClass("ui-jqgrid-bdiv").css({height: a.p.height + (isNaN(a.p.height) ? "" : "px"), width: c.width + "px"}).scroll(c.scrollGrid);
+                        b("table:first", c.bDiv).css({width: a.p.tblwidth + "px"});
+                        k ? (2 == b("tbody", this).size() && b("tbody:gt(0)", this).remove(), a.p.multikey && b(c.bDiv).bind("selectstart", function () {
+                            return false
+                        })) :
+                            a.p.multikey && b(c.bDiv).bind("mousedown", function () {
+                                return false
+                            });
+                        D && b(c.bDiv).hide();
+                        c.cDiv = document.createElement("div");
+                        var ia = !0 === a.p.hidegrid ? b("<a role='link' href='javascript:void(0)'/>").addClass("ui-jqgrid-titlebar-close HeaderButton").hover(function () {
+                            ia.addClass("ui-state-hover")
+                        },function () {
+                            ia.removeClass("ui-state-hover")
+                        }).append("<span class='ui-icon ui-icon-circle-triangle-n'></span>").css("rtl" == i ? "left" : "right", "0px") : "";
+                        b(c.cDiv).append(ia).append("<span class='ui-jqgrid-title" +
+                            ("rtl" == i ? "-rtl" : "") + "'>" + a.p.caption + "</span>").addClass("ui-jqgrid-titlebar ui-widget-header ui-corner-top ui-helper-clearfix");
+                        b(c.cDiv).insertBefore(c.hDiv);
+                        a.p.toolbar[0] && (c.uDiv = document.createElement("div"), "top" == a.p.toolbar[1] ? b(c.uDiv).insertBefore(c.hDiv) : "bottom" == a.p.toolbar[1] && b(c.uDiv).insertAfter(c.hDiv), "both" == a.p.toolbar[1] ? (c.ubDiv = document.createElement("div"), b(c.uDiv).insertBefore(c.hDiv).addClass("ui-userdata ui-state-default").attr("id", "t_" + this.id), b(c.ubDiv).insertAfter(c.hDiv).addClass("ui-userdata ui-state-default").attr("id",
+                            "tb_" + this.id), D && b(c.ubDiv).hide()) : b(c.uDiv).width(c.width).addClass("ui-userdata ui-state-default").attr("id", "t_" + this.id), D && b(c.uDiv).hide());
+                        a.p.toppager && (a.p.toppager = b.jgrid.jqID(a.p.id) + "_toppager", c.topDiv = b("<div id='" + a.p.toppager + "'></div>")[0], a.p.toppager = "#" + a.p.toppager, b(c.topDiv).insertBefore(c.hDiv).addClass("ui-state-default ui-jqgrid-toppager").width(c.width), l(a.p.toppager, "_t"));
+                        a.p.footerrow && (c.sDiv = b("<div class='ui-jqgrid-sdiv'></div>")[0], e = b("<div class='ui-jqgrid-hbox" +
+                            ("rtl" == i ? "-rtl" : "") + "'></div>"), b(c.sDiv).append(e).insertAfter(c.hDiv).width(c.width), b(e).append(R), c.footers = b(".ui-jqgrid-ftable", c.sDiv)[0].rows[0].cells, a.p.rownumbers && (c.footers[0].className = "ui-state-default jqgrid-rownum"), D && b(c.sDiv).hide());
+                        e = null;
+                        if (a.p.caption) {
+                            var pa = a.p.datatype;
+                            !0 === a.p.hidegrid && (b(".ui-jqgrid-titlebar-close", c.cDiv).click(function (d) {
+                                var e = b.isFunction(a.p.onHeaderClick), f = ".ui-jqgrid-bdiv, .ui-jqgrid-hdiv, .ui-jqgrid-pager, .ui-jqgrid-sdiv", g, i = this;
+                                if (a.p.toolbar[0] ===
+                                    true) {
+                                    a.p.toolbar[1] == "both" && (f = f + (", #" + b(c.ubDiv).attr("id")));
+                                    f = f + (", #" + b(c.uDiv).attr("id"))
+                                }
+                                g = b(f, "#gview_" + b.jgrid.jqID(a.p.id)).length;
+                                a.p.gridstate == "visible" ? b(f, "#gbox_" + b.jgrid.jqID(a.p.id)).slideUp("fast", function () {
+                                    g--;
+                                    if (g === 0) {
+                                        b("span", i).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-s");
+                                        a.p.gridstate = "hidden";
+                                        b("#gbox_" + b.jgrid.jqID(a.p.id)).hasClass("ui-resizable") && b(".ui-resizable-handle", "#gbox_" + b.jgrid.jqID(a.p.id)).hide();
+                                        b(a).triggerHandler("jqGridHeaderClick",
+                                            [a.p.gridstate, d]);
+                                        e && (D || a.p.onHeaderClick.call(a, a.p.gridstate, d))
+                                    }
+                                }) : a.p.gridstate == "hidden" && b(f, "#gbox_" + b.jgrid.jqID(a.p.id)).slideDown("fast", function () {
+                                    g--;
+                                    if (g === 0) {
+                                        b("span", i).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-n");
+                                        if (D) {
+                                            a.p.datatype = pa;
+                                            I();
+                                            D = false
+                                        }
+                                        a.p.gridstate = "visible";
+                                        b("#gbox_" + b.jgrid.jqID(a.p.id)).hasClass("ui-resizable") && b(".ui-resizable-handle", "#gbox_" + b.jgrid.jqID(a.p.id)).show();
+                                        b(a).triggerHandler("jqGridHeaderClick", [a.p.gridstate, d]);
+                                        e && (D || a.p.onHeaderClick.call(a, a.p.gridstate, d))
+                                    }
+                                });
+                                return false
+                            }), D && (a.p.datatype = "local", b(".ui-jqgrid-titlebar-close", c.cDiv).trigger("click")))
+                        } else b(c.cDiv).hide();
+                        b(c.hDiv).after(c.bDiv).mousemove(function (a) {
+                            if (c.resizing) {
+                                c.dragMove(a);
+                                return false
+                            }
+                        });
+                        b(".ui-jqgrid-labels", c.hDiv).bind("selectstart", function () {
+                            return false
+                        });
+                        b(document).mouseup(function () {
+                            if (c.resizing) {
+                                c.dragEnd();
+                                return false
+                            }
+                            return true
+                        });
+                        a.formatCol = p;
+                        a.sortData = ja;
+                        a.updatepager = function (c, d) {
+                            var e, f, g, h, i, j, k, l = "",
+                                m = a.p.pager ? "_" + b.jgrid.jqID(a.p.pager.substr(1)) : "", n = a.p.toppager ? "_" + a.p.toppager.substr(1) : "";
+                            g = parseInt(a.p.page, 10) - 1;
+                            g < 0 && (g = 0);
+                            g = g * parseInt(a.p.rowNum, 10);
+                            i = g + a.p.reccount;
+                            if (a.p.scroll) {
+                                e = b("tbody:first > tr:gt(0)", a.grid.bDiv);
+                                g = i - e.length;
+                                a.p.reccount = e.length;
+                                if (f = e.outerHeight() || a.grid.prevRowHeight) {
+                                    e = g * f;
+                                    f = parseInt(a.p.records, 10) * f;
+                                    b(">div:first", a.grid.bDiv).css({height: f}).children("div:first").css({height: e, display: e ? "" : "none"})
+                                }
+                                a.grid.bDiv.scrollLeft = a.grid.hDiv.scrollLeft
+                            }
+                            l =
+                                a.p.pager ? a.p.pager : "";
+                            if (l = l + (a.p.toppager ? l ? "," + a.p.toppager : a.p.toppager : "")) {
+                                k = b.jgrid.formatter.integer || {};
+                                e = o(a.p.page);
+                                f = o(a.p.lastpage);
+                                b(".selbox", l)[this.p.useProp ? "prop" : "attr"]("disabled", false);
+                                if (a.p.pginput === true) {
+                                    b(".ui-pg-input", l).val(a.p.page);
+                                    h = a.p.toppager ? "#sp_1" + m + ",#sp_1" + n : "#sp_1" + m;
+                                    b(h).html(b.fmatter ? b.fmatter.util.NumberFormat(a.p.lastpage, k) : a.p.lastpage)
+                                }
+                                if (a.p.viewrecords)if (a.p.reccount === 0)b(".ui-paging-info", l).html(a.p.emptyrecords); else {
+                                    h = g + 1;
+                                    j = a.p.records;
+                                    if (b.fmatter) {
+                                        h =
+                                            b.fmatter.util.NumberFormat(h, k);
+                                        i = b.fmatter.util.NumberFormat(i, k);
+                                        j = b.fmatter.util.NumberFormat(j, k)
+                                    }
+                                    b(".ui-paging-info", l).html(b.jgrid.format(a.p.recordtext, h, i, j))
+                                }
+                                if (a.p.pgbuttons === true) {
+                                    e <= 0 && (e = f = 0);
+                                    if (e == 1 || e === 0) {
+                                        b("#first" + m + ", #prev" + m).addClass("ui-state-disabled").removeClass("ui-state-hover");
+                                        a.p.toppager && b("#first_t" + n + ", #prev_t" + n).addClass("ui-state-disabled").removeClass("ui-state-hover")
+                                    } else {
+                                        b("#first" + m + ", #prev" + m).removeClass("ui-state-disabled");
+                                        a.p.toppager && b("#first_t" +
+                                            n + ", #prev_t" + n).removeClass("ui-state-disabled")
+                                    }
+                                    if (e == f || e === 0) {
+                                        b("#next" + m + ", #last" + m).addClass("ui-state-disabled").removeClass("ui-state-hover");
+                                        a.p.toppager && b("#next_t" + n + ", #last_t" + n).addClass("ui-state-disabled").removeClass("ui-state-hover")
+                                    } else {
+                                        b("#next" + m + ", #last" + m).removeClass("ui-state-disabled");
+                                        a.p.toppager && b("#next_t" + n + ", #last_t" + n).removeClass("ui-state-disabled")
+                                    }
+                                }
+                            }
+                            c === true && a.p.rownumbers === true && b("td.jqgrid-rownum", a.rows).each(function (a) {
+                                b(this).html(g + 1 + a)
+                            });
+                            d && a.p.jqgdnd &&
+                            b(a).jqGrid("gridDnD", "updateDnD");
+                            b(a).triggerHandler("jqGridGridComplete");
+                            b.isFunction(a.p.gridComplete) && a.p.gridComplete.call(a);
+                            b(a).triggerHandler("jqGridAfterGridComplete")
+                        };
+                        a.refreshIndex = S;
+                        a.setHeadCheckBox = da;
+                        a.constructTr = J;
+                        a.formatter = function (a, b, c, d, e) {
+                            return u(a, b, c, d, e)
+                        };
+                        b.extend(c, {populate: I, emptyRows: N});
+                        this.grid = c;
+                        a.addXmlData = function (b) {
+                            $(b, a.grid.bDiv)
+                        };
+                        a.addJSONData = function (b) {
+                            aa(b, a.grid.bDiv)
+                        };
+                        this.grid.cols = this.rows[0].cells;
+                        I();
+                        a.p.hiddengrid = !1;
+                        b(window).unload(function () {
+                            a =
+                                null
+                        })
+                    }
+                }
+            }
+        })
+    };
+    b.jgrid.extend({getGridParam: function (b) {
+        var e = this[0];
+        return!e || !e.grid ? void 0 : b ? "undefined" != typeof e.p[b] ? e.p[b] : null : e.p
+    }, setGridParam: function (f) {
+        return this.each(function () {
+            this.grid && "object" === typeof f && b.extend(!0, this.p, f)
+        })
+    }, getDataIDs: function () {
+        var f = [], e = 0, c, d = 0;
+        this.each(function () {
+            if ((c = this.rows.length) && 0 < c)for (; e < c;)b(this.rows[e]).hasClass("jqgrow") && (f[d] = this.rows[e].id, d++), e++
+        });
+        return f
+    }, setSelection: function (f, e, c) {
+        return this.each(function () {
+            var d, a, h, g, i, j;
+            if (void 0 !== f && (e = !1 === e ? !1 : !0, (a = this.rows.namedItem(f + "")) && a.className && !(-1 < a.className.indexOf("ui-state-disabled"))))(!0 === this.p.scrollrows && (h = this.rows.namedItem(f).rowIndex, 0 <= h && (d = b(this.grid.bDiv)[0].clientHeight, g = b(this.grid.bDiv)[0].scrollTop, i = this.rows[h].offsetTop, h = this.rows[h].clientHeight, i + h >= d + g ? b(this.grid.bDiv)[0].scrollTop = i - (d + g) + h + g : i < d + g && i < g && (b(this.grid.bDiv)[0].scrollTop = i))), !0 === this.p.frozenColumns && (j = this.p.id + "_frozen"), this.p.multiselect) ? (this.setHeadCheckBox(!1),
+                this.p.selrow = a.id, g = b.inArray(this.p.selrow, this.p.selarrrow), -1 === g ? ("ui-subgrid" !== a.className && b(a).addClass("ui-state-highlight").attr("aria-selected", "true"), d = !0, this.p.selarrrow.push(this.p.selrow)) : ("ui-subgrid" !== a.className && b(a).removeClass("ui-state-highlight").attr("aria-selected", "false"), d = !1, this.p.selarrrow.splice(g, 1), i = this.p.selarrrow[0], this.p.selrow = void 0 === i ? null : i), b("#jqg_" + b.jgrid.jqID(this.p.id) + "_" + b.jgrid.jqID(a.id))[this.p.useProp ? "prop" : "attr"]("checked", d), j && (-1 ===
+                g ? b("#" + b.jgrid.jqID(f), "#" + b.jgrid.jqID(j)).addClass("ui-state-highlight") : b("#" + b.jgrid.jqID(f), "#" + b.jgrid.jqID(j)).removeClass("ui-state-highlight"), b("#jqg_" + b.jgrid.jqID(this.p.id) + "_" + b.jgrid.jqID(f), "#" + b.jgrid.jqID(j))[this.p.useProp ? "prop" : "attr"]("checked", d)), b(this).triggerHandler("jqGridSelectRow", [a.id, d, c]), this.p.onSelectRow && e && this.p.onSelectRow.call(this, a.id, d, c)) : "ui-subgrid" !== a.className && (this.p.selrow != a.id ? (b(this.rows.namedItem(this.p.selrow)).removeClass("ui-state-highlight").attr({"aria-selected": "false",
+                tabindex: "-1"}), b(a).addClass("ui-state-highlight").attr({"aria-selected": "true", tabindex: "0"}), j && (b("#" + b.jgrid.jqID(this.p.selrow), "#" + b.jgrid.jqID(j)).removeClass("ui-state-highlight"), b("#" + b.jgrid.jqID(f), "#" + b.jgrid.jqID(j)).addClass("ui-state-highlight")), d = !0) : d = !1, this.p.selrow = a.id, b(this).triggerHandler("jqGridSelectRow", [a.id, d, c]), this.p.onSelectRow && e && this.p.onSelectRow.call(this, a.id, d, c))
+        })
+    }, resetSelection: function (f) {
+        return this.each(function () {
+            var e = this, c, d, a;
+            !0 === e.p.frozenColumns &&
+            (a = e.p.id + "_frozen");
+            if ("undefined" !== typeof f) {
+                d = f === e.p.selrow ? e.p.selrow : f;
+                b("#" + b.jgrid.jqID(e.p.id) + " tbody:first tr#" + b.jgrid.jqID(d)).removeClass("ui-state-highlight").attr("aria-selected", "false");
+                a && b("#" + b.jgrid.jqID(d), "#" + b.jgrid.jqID(a)).removeClass("ui-state-highlight");
+                if (e.p.multiselect) {
+                    b("#jqg_" + b.jgrid.jqID(e.p.id) + "_" + b.jgrid.jqID(d), "#" + b.jgrid.jqID(e.p.id))[e.p.useProp ? "prop" : "attr"]("checked", !1);
+                    if (a)b("#jqg_" + b.jgrid.jqID(e.p.id) + "_" + b.jgrid.jqID(d), "#" + b.jgrid.jqID(a))[e.p.useProp ?
+                        "prop" : "attr"]("checked", !1);
+                    e.setHeadCheckBox(!1)
+                }
+                d = null
+            } else e.p.multiselect ? (b(e.p.selarrrow).each(function (d, f) {
+                c = e.rows.namedItem(f);
+                b(c).removeClass("ui-state-highlight").attr("aria-selected", "false");
+                b("#jqg_" + b.jgrid.jqID(e.p.id) + "_" + b.jgrid.jqID(f))[e.p.useProp ? "prop" : "attr"]("checked", !1);
+                a && (b("#" + b.jgrid.jqID(f), "#" + b.jgrid.jqID(a)).removeClass("ui-state-highlight"), b("#jqg_" + b.jgrid.jqID(e.p.id) + "_" + b.jgrid.jqID(f), "#" + b.jgrid.jqID(a))[e.p.useProp ? "prop" : "attr"]("checked", !1))
+            }), e.setHeadCheckBox(!1),
+                e.p.selarrrow = []) : e.p.selrow && (b("#" + b.jgrid.jqID(e.p.id) + " tbody:first tr#" + b.jgrid.jqID(e.p.selrow)).removeClass("ui-state-highlight").attr("aria-selected", "false"), a && b("#" + b.jgrid.jqID(e.p.selrow), "#" + b.jgrid.jqID(a)).removeClass("ui-state-highlight"), e.p.selrow = null);
+            !0 === e.p.cellEdit && 0 <= parseInt(e.p.iCol, 10) && 0 <= parseInt(e.p.iRow, 10) && (b("td:eq(" + e.p.iCol + ")", e.rows[e.p.iRow]).removeClass("edit-cell ui-state-highlight"), b(e.rows[e.p.iRow]).removeClass("selected-row ui-state-hover"));
+            e.p.savedRow =
+                []
+        })
+    }, getRowData: function (f) {
+        var e = {}, c, d = !1, a, h = 0;
+        this.each(function () {
+            var g = this, i, j;
+            if ("undefined" == typeof f)d = !0, c = [], a = g.rows.length; else {
+                j = g.rows.namedItem(f);
+                if (!j)return e;
+                a = 2
+            }
+            for (; h < a;)d && (j = g.rows[h]), b(j).hasClass("jqgrow") && (b('td[role="gridcell"]', j).each(function (a) {
+                i = g.p.colModel[a].name;
+                if ("cb" !== i && "subgrid" !== i && "rn" !== i)if (!0 === g.p.treeGrid && i == g.p.ExpandColumn)e[i] = b.jgrid.htmlDecode(b("span:first", this).html()); else try {
+                    e[i] = b.unformat.call(g, this, {rowId: j.id, colModel: g.p.colModel[a]},
+                        a)
+                } catch (c) {
+                    e[i] = b.jgrid.htmlDecode(b(this).html())
+                }
+            }), d && (c.push(e), e = {})), h++
+        });
+        return c ? c : e
+    }, delRowData: function (f) {
+        var e = !1, c, d;
+        this.each(function () {
+            if (c = this.rows.namedItem(f)) {
+                if (b(c).remove(), this.p.records--, this.p.reccount--, this.updatepager(!0, !1), e = !0, this.p.multiselect && (d = b.inArray(f, this.p.selarrrow), -1 != d && this.p.selarrrow.splice(d, 1)), f == this.p.selrow)this.p.selrow = null
+            } else return!1;
+            if ("local" == this.p.datatype) {
+                var a = this.p._index[b.jgrid.stripPref(this.p.idPrefix, f)];
+                "undefined" != typeof a && (this.p.data.splice(a, 1), this.refreshIndex())
+            }
+            if (!0 === this.p.altRows && e) {
+                var h = this.p.altclass;
+                b(this.rows).each(function (a) {
+                    1 == a % 2 ? b(this).addClass(h) : b(this).removeClass(h)
+                })
+            }
+        });
+        return e
+    }, setRowData: function (f, e, c) {
+        var d, a = !0, h;
+        this.each(function () {
+            if (!this.grid)return!1;
+            var g = this, i, j, l = typeof c, k = {};
+            j = g.rows.namedItem(f);
+            if (!j)return!1;
+            if (e)try {
+                if (b(this.p.colModel).each(function (a) {
+                    d = this.name;
+                    void 0 !== e[d] && (k[d] = this.formatter && "string" === typeof this.formatter && "date" == this.formatter ?
+                        b.unformat.date.call(g, e[d], this) : e[d], i = g.formatter(f, e[d], a, e, "edit"), h = this.title ? {title: b.jgrid.stripHtml(i)} : {}, !0 === g.p.treeGrid && d == g.p.ExpandColumn ? b("td:eq(" + a + ") > span:first", j).html(i).attr(h) : b("td:eq(" + a + ")", j).html(i).attr(h))
+                }), "local" == g.p.datatype) {
+                    var m = b.jgrid.stripPref(g.p.idPrefix, f), o = g.p._index[m];
+                    if (g.p.treeGrid)for (var p in g.p.treeReader)k.hasOwnProperty(g.p.treeReader[p]) && delete k[g.p.treeReader[p]];
+                    "undefined" != typeof o && (g.p.data[o] = b.extend(!0, g.p.data[o], k));
+                    k = null
+                }
+            } catch (v) {
+                a = !1
+            }
+            a && ("string" === l ? b(j).addClass(c) : "object" === l && b(j).css(c), b(g).triggerHandler("jqGridAfterGridComplete"))
+        });
+        return a
+    }, addRowData: function (f, e, c, d) {
+        c || (c = "last");
+        var a = !1, h, g, i, j, l, k, m, o, p = "", v, u, M, F, Z, U;
+        e && (b.isArray(e) ? (v = !0, c = "last", u = f) : (e = [e], v = !1), this.each(function () {
+            var V = e.length;
+            l = this.p.rownumbers === true ? 1 : 0;
+            i = this.p.multiselect === true ? 1 : 0;
+            j = this.p.subGrid === true ? 1 : 0;
+            if (!v)if (typeof f != "undefined")f = f + ""; else {
+                f = b.jgrid.randId();
+                if (this.p.keyIndex !== false) {
+                    u = this.p.colModel[this.p.keyIndex +
+                        i + j + l].name;
+                    typeof e[0][u] != "undefined" && (f = e[0][u])
+                }
+            }
+            M = this.p.altclass;
+            for (var N = 0, S = "", J = {}, $ = b.isFunction(this.p.afterInsertRow) ? true : false; N < V;) {
+                F = e[N];
+                g = [];
+                if (v) {
+                    try {
+                        f = F[u]
+                    } catch (aa) {
+                        f = b.jgrid.randId()
+                    }
+                    S = this.p.altRows === true ? (this.rows.length - 1) % 2 === 0 ? M : "" : ""
+                }
+                U = f;
+                f = this.p.idPrefix + f;
+                if (l) {
+                    p = this.formatCol(0, 1, "", null, f, true);
+                    g[g.length] = '<td role="gridcell" class="ui-state-default jqgrid-rownum" ' + p + ">0</td>"
+                }
+                if (i) {
+                    o = '<input role="checkbox" type="checkbox" id="jqg_' + this.p.id + "_" + f + '" class="cbox"/>';
+                    p = this.formatCol(l, 1, "", null, f, true);
+                    g[g.length] = '<td role="gridcell" ' + p + ">" + o + "</td>"
+                }
+                j && (g[g.length] = b(this).jqGrid("addSubGridCell", i + l, 1));
+                for (m = i + j + l; m < this.p.colModel.length; m++) {
+                    Z = this.p.colModel[m];
+                    h = Z.name;
+                    J[h] = F[h];
+                    o = this.formatter(f, b.jgrid.getAccessor(F, h), m, F);
+                    p = this.formatCol(m, 1, o, F, f, true);
+                    g[g.length] = '<td role="gridcell" ' + p + ">" + o + "</td>"
+                }
+                g.unshift(this.constructTr(f, false, S, J, J));
+                g[g.length] = "</tr>";
+                if (this.rows.length === 0)b("table:first", this.grid.bDiv).append(g.join("")); else switch (c) {
+                    case "last":
+                        b(this.rows[this.rows.length -
+                            1]).after(g.join(""));
+                        k = this.rows.length - 1;
+                        break;
+                    case "first":
+                        b(this.rows[0]).after(g.join(""));
+                        k = 1;
+                        break;
+                    case "after":
+                        (k = this.rows.namedItem(d)) && (b(this.rows[k.rowIndex + 1]).hasClass("ui-subgrid") ? b(this.rows[k.rowIndex + 1]).after(g) : b(k).after(g.join("")));
+                        k++;
+                        break;
+                    case "before":
+                        if (k = this.rows.namedItem(d)) {
+                            b(k).before(g.join(""));
+                            k = k.rowIndex
+                        }
+                        k--
+                }
+                this.p.subGrid === true && b(this).jqGrid("addSubGrid", i + l, k);
+                this.p.records++;
+                this.p.reccount++;
+                b(this).triggerHandler("jqGridAfterInsertRow", [f, F, F]);
+                $ &&
+                this.p.afterInsertRow.call(this, f, F, F);
+                N++;
+                if (this.p.datatype == "local") {
+                    J[this.p.localReader.id] = U;
+                    this.p._index[U] = this.p.data.length;
+                    this.p.data.push(J);
+                    J = {}
+                }
+            }
+            this.p.altRows === true && !v && (c == "last" ? (this.rows.length - 1) % 2 == 1 && b(this.rows[this.rows.length - 1]).addClass(M) : b(this.rows).each(function (a) {
+                a % 2 == 1 ? b(this).addClass(M) : b(this).removeClass(M)
+            }));
+            this.updatepager(true, true);
+            a = true
+        }));
+        return a
+    }, footerData: function (f, e, c) {
+        function d(a) {
+            for (var b in a)if (a.hasOwnProperty(b))return!1;
+            return!0
+        }
+
+        var a,
+            h = !1, g = {}, i;
+        "undefined" == typeof f && (f = "get");
+        "boolean" != typeof c && (c = !0);
+        f = f.toLowerCase();
+        this.each(function () {
+            var j = this, l;
+            if (!j.grid || !j.p.footerrow || "set" == f && d(e))return!1;
+            h = !0;
+            b(this.p.colModel).each(function (d) {
+                a = this.name;
+                "set" == f ? void 0 !== e[a] && (l = c ? j.formatter("", e[a], d, e, "edit") : e[a], i = this.title ? {title: b.jgrid.stripHtml(l)} : {}, b("tr.footrow td:eq(" + d + ")", j.grid.sDiv).html(l).attr(i), h = !0) : "get" == f && (g[a] = b("tr.footrow td:eq(" + d + ")", j.grid.sDiv).html())
+            })
+        });
+        return"get" == f ? g : h
+    }, showHideCol: function (f, e) {
+        return this.each(function () {
+            var c = this, d = !1, a = b.jgrid.cellWidth() ? 0 : c.p.cellLayout, h;
+            if (c.grid) {
+                "string" === typeof f && (f = [f]);
+                e = "none" != e ? "" : "none";
+                var g = "" === e ? !0 : !1, i = c.p.groupHeader && ("object" === typeof c.p.groupHeader || b.isFunction(c.p.groupHeader));
+                i && b(c).jqGrid("destroyGroupHeader", !1);
+                b(this.p.colModel).each(function (i) {
+                    if (-1 !== b.inArray(this.name, f) && this.hidden === g) {
+                        if (!0 === c.p.frozenColumns && !0 === this.frozen)return!0;
+                        b("tr", c.grid.hDiv).each(function () {
+                            b(this.cells[i]).css("display", e)
+                        });
+                        b(c.rows).each(function () {
+                            b(this).hasClass("jqgroup") || b(this.cells[i]).css("display", e)
+                        });
+                        c.p.footerrow && b("tr.footrow td:eq(" + i + ")", c.grid.sDiv).css("display", e);
+                        h = parseInt(this.width, 10);
+                        c.p.tblwidth = "none" === e ? c.p.tblwidth - (h + a) : c.p.tblwidth + (h + a);
+                        this.hidden = !g;
+                        d = !0;
+                        b(c).triggerHandler("jqGridShowHideCol", [g, this.name, i])
+                    }
+                });
+                !0 === d && (!0 === c.p.shrinkToFit && !isNaN(c.p.height) && (c.p.tblwidth += parseInt(c.p.scrollOffset, 10)), b(c).jqGrid("setGridWidth", !0 === c.p.shrinkToFit ? c.p.tblwidth : c.p.width));
+                i && b(c).jqGrid("setGroupHeaders", c.p.groupHeader)
+            }
+        })
+    }, hideCol: function (f) {
+        return this.each(function () {
+            b(this).jqGrid("showHideCol", f, "none")
+        })
+    }, showCol: function (f) {
+        return this.each(function () {
+            b(this).jqGrid("showHideCol", f, "")
+        })
+    }, remapColumns: function (f, e, c) {
+        function d(a) {
+            var c;
+            c = a.length ? b.makeArray(a) : b.extend({}, a);
+            b.each(f, function (b) {
+                a[b] = c[this]
+            })
+        }
+
+        function a(a, c) {
+            b(">tr" + (c || ""), a).each(function () {
+                var a = this, c = b.makeArray(a.cells);
+                b.each(f, function () {
+                    var b = c[this];
+                    b && a.appendChild(b)
+                })
+            })
+        }
+
+        var h =
+            this.get(0);
+        d(h.p.colModel);
+        d(h.p.colNames);
+        d(h.grid.headers);
+        a(b("thead:first", h.grid.hDiv), c && ":not(.ui-jqgrid-labels)");
+        e && a(b("#" + b.jgrid.jqID(h.p.id) + " tbody:first"), ".jqgfirstrow, tr.jqgrow, tr.jqfoot");
+        h.p.footerrow && a(b("tbody:first", h.grid.sDiv));
+        h.p.remapColumns && (h.p.remapColumns.length ? d(h.p.remapColumns) : h.p.remapColumns = b.makeArray(f));
+        h.p.lastsort = b.inArray(h.p.lastsort, f);
+        h.p.treeGrid && (h.p.expColInd = b.inArray(h.p.expColInd, f));
+        b(h).triggerHandler("jqGridRemapColumns", [f, e, c])
+    }, setGridWidth: function (f, e) {
+        return this.each(function () {
+            if (this.grid) {
+                var c = this, d, a = 0, h = b.jgrid.cellWidth() ? 0 : c.p.cellLayout, g, i = 0, j = !1, l = c.p.scrollOffset, k, m = 0, o = 0, p;
+                "boolean" != typeof e && (e = c.p.shrinkToFit);
+                if (!isNaN(f)) {
+                    f = parseInt(f, 10);
+                    c.grid.width = c.p.width = f;
+                    b("#gbox_" + b.jgrid.jqID(c.p.id)).css("width", f + "px");
+                    b("#gview_" + b.jgrid.jqID(c.p.id)).css("width", f + "px");
+                    b(c.grid.bDiv).css("width", f + "px");
+                    b(c.grid.hDiv).css("width", f + "px");
+                    c.p.pager && b(c.p.pager).css("width", f + "px");
+                    c.p.toppager && b(c.p.toppager).css("width",
+                        f + "px");
+                    !0 === c.p.toolbar[0] && (b(c.grid.uDiv).css("width", f + "px"), "both" == c.p.toolbar[1] && b(c.grid.ubDiv).css("width", f + "px"));
+                    c.p.footerrow && b(c.grid.sDiv).css("width", f + "px");
+                    !1 === e && !0 === c.p.forceFit && (c.p.forceFit = !1);
+                    if (!0 === e) {
+                        b.each(c.p.colModel, function () {
+                            if (this.hidden === false) {
+                                d = this.widthOrg;
+                                a = a + (d + h);
+                                this.fixed ? m = m + (d + h) : i++;
+                                o++
+                            }
+                        });
+                        if (0 === i)return;
+                        c.p.tblwidth = a;
+                        k = f - h * i - m;
+                        if (!isNaN(c.p.height) && (b(c.grid.bDiv)[0].clientHeight < b(c.grid.bDiv)[0].scrollHeight || 1 === c.rows.length))j = !0, k -= l;
+                        var a = 0, v = 0 < c.grid.cols.length;
+                        b.each(c.p.colModel, function (b) {
+                            if (this.hidden === false && !this.fixed) {
+                                d = this.widthOrg;
+                                d = Math.round(k * d / (c.p.tblwidth - h * i - m));
+                                if (!(d < 0)) {
+                                    this.width = d;
+                                    a = a + d;
+                                    c.grid.headers[b].width = d;
+                                    c.grid.headers[b].el.style.width = d + "px";
+                                    if (c.p.footerrow)c.grid.footers[b].style.width = d + "px";
+                                    if (v)c.grid.cols[b].style.width = d + "px";
+                                    g = b
+                                }
+                            }
+                        });
+                        if (!g)return;
+                        p = 0;
+                        j ? f - m - (a + h * i) !== l && (p = f - m - (a + h * i) - l) : 1 !== Math.abs(f - m - (a + h * i)) && (p = f - m - (a + h * i));
+                        c.p.colModel[g].width += p;
+                        c.p.tblwidth = a + p + h * i + m;
+                        c.p.tblwidth >
+                            f ? (j = c.p.tblwidth - parseInt(f, 10), c.p.tblwidth = f, d = c.p.colModel[g].width -= j) : d = c.p.colModel[g].width;
+                        c.grid.headers[g].width = d;
+                        c.grid.headers[g].el.style.width = d + "px";
+                        v && (c.grid.cols[g].style.width = d + "px");
+                        c.p.footerrow && (c.grid.footers[g].style.width = d + "px")
+                    }
+                    c.p.tblwidth && (b("table:first", c.grid.bDiv).css("width", c.p.tblwidth + "px"), b("table:first", c.grid.hDiv).css("width", c.p.tblwidth + "px"), c.grid.hDiv.scrollLeft = c.grid.bDiv.scrollLeft, c.p.footerrow && b("table:first", c.grid.sDiv).css("width", c.p.tblwidth +
+                        "px"))
+                }
+            }
+        })
+    }, setGridHeight: function (f) {
+        return this.each(function () {
+            if (this.grid) {
+                var e = b(this.grid.bDiv);
+                e.css({height: f + (isNaN(f) ? "" : "px")});
+                !0 === this.p.frozenColumns && b("#" + b.jgrid.jqID(this.p.id) + "_frozen").parent().height(e.height() - 16);
+                this.p.height = f;
+                this.p.scroll && this.grid.populateVisible()
+            }
+        })
+    }, setCaption: function (f) {
+        return this.each(function () {
+            this.p.caption = f;
+            b("span.ui-jqgrid-title, span.ui-jqgrid-title-rtl", this.grid.cDiv).html(f);
+            b(this.grid.cDiv).show()
+        })
+    }, setLabel: function (f, e, c, d) {
+        return this.each(function () {
+            var a =
+                -1;
+            if (this.grid && "undefined" != typeof f && (b(this.p.colModel).each(function (b) {
+                if (this.name == f)return a = b, !1
+            }), 0 <= a)) {
+                var h = b("tr.ui-jqgrid-labels th:eq(" + a + ")", this.grid.hDiv);
+                if (e) {
+                    var g = b(".s-ico", h);
+                    b("[id^=jqgh_]", h).empty().html(e).append(g);
+                    this.p.colNames[a] = e
+                }
+                c && ("string" === typeof c ? b(h).addClass(c) : b(h).css(c));
+                "object" === typeof d && b(h).attr(d)
+            }
+        })
+    }, setCell: function (f, e, c, d, a, h) {
+        return this.each(function () {
+            var g = -1, i, j;
+            if (this.grid && (isNaN(e) ? b(this.p.colModel).each(function (a) {
+                if (this.name ==
+                    e)return g = a, !1
+            }) : g = parseInt(e, 10), 0 <= g && (i = this.rows.namedItem(f)))) {
+                var l = b("td:eq(" + g + ")", i);
+                if ("" !== c || !0 === h)i = this.formatter(f, c, g, i, "edit"), j = this.p.colModel[g].title ? {title: b.jgrid.stripHtml(i)} : {}, this.p.treeGrid && 0 < b(".tree-wrap", b(l)).length ? b("span", b(l)).html(i).attr(j) : b(l).html(i).attr(j), "local" == this.p.datatype && (i = this.p.colModel[g], c = i.formatter && "string" === typeof i.formatter && "date" == i.formatter ? b.unformat.date.call(this, c, i) : c, j = this.p._index[f], "undefined" != typeof j && (this.p.data[j][i.name] =
+                    c));
+                "string" === typeof d ? b(l).addClass(d) : d && b(l).css(d);
+                "object" === typeof a && b(l).attr(a)
+            }
+        })
+    }, getCell: function (f, e) {
+        var c = !1;
+        this.each(function () {
+            var d = -1;
+            if (this.grid && (isNaN(e) ? b(this.p.colModel).each(function (a) {
+                if (this.name === e)return d = a, !1
+            }) : d = parseInt(e, 10), 0 <= d)) {
+                var a = this.rows.namedItem(f);
+                if (a)try {
+                    c = b.unformat.call(this, b("td:eq(" + d + ")", a), {rowId: a.id, colModel: this.p.colModel[d]}, d)
+                } catch (h) {
+                    c = b.jgrid.htmlDecode(b("td:eq(" + d + ")", a).html())
+                }
+            }
+        });
+        return c
+    }, getCol: function (f, e, c) {
+        var d = [],
+            a, h = 0, g, i, j, e = "boolean" != typeof e ? !1 : e;
+        "undefined" == typeof c && (c = !1);
+        this.each(function () {
+            var l = -1;
+            if (this.grid && (isNaN(f) ? b(this.p.colModel).each(function (a) {
+                if (this.name === f)return l = a, !1
+            }) : l = parseInt(f, 10), 0 <= l)) {
+                var k = this.rows.length, m = 0;
+                if (k && 0 < k) {
+                    for (; m < k;) {
+                        if (b(this.rows[m]).hasClass("jqgrow")) {
+                            try {
+                                a = b.unformat.call(this, b(this.rows[m].cells[l]), {rowId: this.rows[m].id, colModel: this.p.colModel[l]}, l)
+                            } catch (o) {
+                                a = b.jgrid.htmlDecode(this.rows[m].cells[l].innerHTML)
+                            }
+                            c ? (j = parseFloat(a), h += j, 0 ===
+                                m ? i = g = j : (g = Math.min(g, j), i = Math.max(i, j))) : e ? d.push({id: this.rows[m].id, value: a}) : d.push(a)
+                        }
+                        m++
+                    }
+                    if (c)switch (c.toLowerCase()) {
+                        case "sum":
+                            d = h;
+                            break;
+                        case "avg":
+                            d = h / k;
+                            break;
+                        case "count":
+                            d = k;
+                            break;
+                        case "min":
+                            d = g;
+                            break;
+                        case "max":
+                            d = i
+                    }
+                }
+            }
+        });
+        return d
+    }, clearGridData: function (f) {
+        return this.each(function () {
+            if (this.grid) {
+                "boolean" != typeof f && (f = !1);
+                if (this.p.deepempty)b("#" + b.jgrid.jqID(this.p.id) + " tbody:first tr:gt(0)").remove(); else {
+                    var e = b("#" + b.jgrid.jqID(this.p.id) + " tbody:first tr:first")[0];
+                    b("#" + b.jgrid.jqID(this.p.id) +
+                        " tbody:first").empty().append(e)
+                }
+                this.p.footerrow && f && b(".ui-jqgrid-ftable td", this.grid.sDiv).html("&#160;");
+                this.p.selrow = null;
+                this.p.selarrrow = [];
+                this.p.savedRow = [];
+                this.p.records = 0;
+                this.p.page = 1;
+                this.p.lastpage = 0;
+                this.p.reccount = 0;
+                this.p.data = [];
+                this.p._index = {};
+                this.updatepager(!0, !1)
+            }
+        })
+    }, getInd: function (b, e) {
+        var c = !1, d;
+        this.each(function () {
+            (d = this.rows.namedItem(b)) && (c = !0 === e ? d : d.rowIndex)
+        });
+        return c
+    }, bindKeys: function (f) {
+        var e = b.extend({onEnter: null, onSpace: null, onLeftKey: null, onRightKey: null,
+            scrollingRows: !0}, f || {});
+        return this.each(function () {
+            var c = this;
+            b("body").is("[role]") || b("body").attr("role", "application");
+            c.p.scrollrows = e.scrollingRows;
+            b(c).keydown(function (d) {
+                var a = b(c).find("tr[tabindex=0]")[0], f, g, i, j = c.p.treeReader.expanded_field;
+                if (a)if (i = c.p._index[a.id], 37 === d.keyCode || 38 === d.keyCode || 39 === d.keyCode || 40 === d.keyCode) {
+                    if (38 === d.keyCode) {
+                        g = a.previousSibling;
+                        f = "";
+                        if (g)if (b(g).is(":hidden"))for (; g;) {
+                            if (g = g.previousSibling, !b(g).is(":hidden") && b(g).hasClass("jqgrow")) {
+                                f = g.id;
+                                break
+                            }
+                        } else f = g.id;
+                        b(c).jqGrid("setSelection", f, !0, d)
+                    }
+                    if (40 === d.keyCode) {
+                        g = a.nextSibling;
+                        f = "";
+                        if (g)if (b(g).is(":hidden"))for (; g;) {
+                            if (g = g.nextSibling, !b(g).is(":hidden") && b(g).hasClass("jqgrow")) {
+                                f = g.id;
+                                break
+                            }
+                        } else f = g.id;
+                        b(c).jqGrid("setSelection", f, !0, d)
+                    }
+                    37 === d.keyCode && (c.p.treeGrid && c.p.data[i][j] && b(a).find("div.treeclick").trigger("click"), b(c).triggerHandler("jqGridKeyLeft", [c.p.selrow]), b.isFunction(e.onLeftKey) && e.onLeftKey.call(c, c.p.selrow));
+                    39 === d.keyCode && (c.p.treeGrid && !c.p.data[i][j] &&
+                        b(a).find("div.treeclick").trigger("click"), b(c).triggerHandler("jqGridKeyRight", [c.p.selrow]), b.isFunction(e.onRightKey) && e.onRightKey.call(c, c.p.selrow))
+                } else 13 === d.keyCode ? (b(c).triggerHandler("jqGridKeyEnter", [c.p.selrow]), b.isFunction(e.onEnter) && e.onEnter.call(c, c.p.selrow)) : 32 === d.keyCode && (b(c).triggerHandler("jqGridKeySpace", [c.p.selrow]), b.isFunction(e.onSpace) && e.onSpace.call(c, c.p.selrow))
+            })
+        })
+    }, unbindKeys: function () {
+        return this.each(function () {
+            b(this).unbind("keydown")
+        })
+    }, getLocalRow: function (b) {
+        var e =
+            !1, c;
+        this.each(function () {
+            "undefined" !== typeof b && (c = this.p._index[b], 0 <= c && (e = this.p.data[c]))
+        });
+        return e
+    }})
+})(jQuery);
+(function (a) {
+    a.extend(a.jgrid, {showModal: function (a) {
+        a.w.show()
+    }, closeModal: function (a) {
+        a.w.hide().attr("aria-hidden", "true");
+        a.o && a.o.remove()
+    }, hideModal: function (d, b) {
+        b = a.extend({jqm: !0, gb: ""}, b || {});
+        if (b.onClose) {
+            var c = b.onClose(d);
+            if ("boolean" == typeof c && !c)return
+        }
+        if (a.fn.jqm && !0 === b.jqm)a(d).attr("aria-hidden", "true").jqmHide(); else {
+            if ("" !== b.gb)try {
+                a(".jqgrid-overlay:first", b.gb).hide()
+            } catch (f) {
+            }
+            a(d).hide().attr("aria-hidden", "true")
+        }
+    }, findPos: function (a) {
+        var b = 0, c = 0;
+        if (a.offsetParent) {
+            do b +=
+                a.offsetLeft, c += a.offsetTop; while (a = a.offsetParent)
+        }
+        return[b, c]
+    }, createModal: function (d, b, c, f, g, h, i) {
+        var e = document.createElement("div"), l, j = this, i = a.extend({}, i || {});
+        l = "rtl" == a(c.gbox).attr("dir") ? !0 : !1;
+        e.className = "ui-widget ui-widget-content ui-corner-all ui-jqdialog";
+        e.id = d.themodal;
+        var k = document.createElement("div");
+        k.className = "ui-jqdialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix";
+        k.id = d.modalhead;
+        a(k).append("<span class='ui-jqdialog-title'>" + c.caption + "</span>");
+        var n = a("<a href='javascript:void(0)' class='ui-jqdialog-titlebar-close ui-corner-all'></a>").hover(function () {
+                n.addClass("ui-state-hover")
+            },
+            function () {
+                n.removeClass("ui-state-hover")
+            }).append("<span class='ui-icon ui-icon-closethick'></span>");
+        a(k).append(n);
+        l ? (e.dir = "rtl", a(".ui-jqdialog-title", k).css("float", "right"), a(".ui-jqdialog-titlebar-close", k).css("left", "0.3em")) : (e.dir = "ltr", a(".ui-jqdialog-title", k).css("float", "left"), a(".ui-jqdialog-titlebar-close", k).css("right", "0.3em"));
+        var m = document.createElement("div");
+        a(m).addClass("ui-jqdialog-content ui-widget-content").attr("id", d.modalcontent);
+        a(m).append(b);
+        e.appendChild(m);
+        a(e).prepend(k);
+        !0 === h ? a("body").append(e) : "string" == typeof h ? a(h).append(e) : a(e).insertBefore(f);
+        a(e).css(i);
+        "undefined" === typeof c.jqModal && (c.jqModal = !0);
+        b = {};
+        if (a.fn.jqm && !0 === c.jqModal)0 === c.left && (0 === c.top && c.overlay) && (i = [], i = a.jgrid.findPos(g), c.left = i[0] + 4, c.top = i[1] + 4), b.top = c.top + "px", b.left = c.left; else if (0 !== c.left || 0 !== c.top)b.left = c.left, b.top = c.top + "px";
+        a("a.ui-jqdialog-titlebar-close", k).click(function () {
+            var b = a("#" + a.jgrid.jqID(d.themodal)).data("onClose") || c.onClose, e = a("#" + a.jgrid.jqID(d.themodal)).data("gbox") ||
+                c.gbox;
+            j.hideModal("#" + a.jgrid.jqID(d.themodal), {gb: e, jqm: c.jqModal, onClose: b});
+            return false
+        });
+        if (0 === c.width || !c.width)c.width = 300;
+        if (0 === c.height || !c.height)c.height = 200;
+        c.zIndex || (f = a(f).parents("*[role=dialog]").filter(":first").css("z-index"), c.zIndex = f ? parseInt(f, 10) + 2 : 950);
+        f = 0;
+        l && (b.left && !h) && (f = a(c.gbox).width() - (!isNaN(c.width) ? parseInt(c.width, 10) : 0) - 8, b.left = parseInt(b.left, 10) + parseInt(f, 10));
+        b.left && (b.left += "px");
+        a(e).css(a.extend({width: isNaN(c.width) ? "auto" : c.width + "px", height: isNaN(c.height) ?
+            "auto" : c.height + "px", zIndex: c.zIndex, overflow: "hidden"}, b)).attr({tabIndex: "-1", role: "dialog", "aria-labelledby": d.modalhead, "aria-hidden": "true"});
+        "undefined" == typeof c.drag && (c.drag = !0);
+        "undefined" == typeof c.resize && (c.resize = !0);
+        if (c.drag)if (a(k).css("cursor", "move"), a.fn.jqDrag)a(e).jqDrag(k); else try {
+            a(e).draggable({handle: a("#" + a.jgrid.jqID(k.id))})
+        } catch (o) {
+        }
+        if (c.resize)if (a.fn.jqResize)a(e).append("<div class='jqResize ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se ui-icon-grip-diagonal-se'></div>"),
+            a("#" + a.jgrid.jqID(d.themodal)).jqResize(".jqResize", d.scrollelm ? "#" + a.jgrid.jqID(d.scrollelm) : !1); else try {
+            a(e).resizable({handles: "se, sw", alsoResize: d.scrollelm ? "#" + a.jgrid.jqID(d.scrollelm) : !1})
+        } catch (p) {
+        }
+        !0 === c.closeOnEscape && a(e).keydown(function (b) {
+            if (b.which == 27) {
+                b = a("#" + a.jgrid.jqID(d.themodal)).data("onClose") || c.onClose;
+                j.hideModal(this, {gb: c.gbox, jqm: c.jqModal, onClose: b})
+            }
+        })
+    }, viewModal: function (d, b) {
+        b = a.extend({toTop: !0, overlay: 10, modal: !1, overlayClass: "ui-widget-overlay", onShow: a.jgrid.showModal,
+            onHide: a.jgrid.closeModal, gbox: "", jqm: !0, jqM: !0}, b || {});
+        if (a.fn.jqm && !0 === b.jqm)b.jqM ? a(d).attr("aria-hidden", "false").jqm(b).jqmShow() : a(d).attr("aria-hidden", "false").jqmShow(); else {
+            "" !== b.gbox && (a(".jqgrid-overlay:first", b.gbox).show(), a(d).data("gbox", b.gbox));
+            a(d).show().attr("aria-hidden", "false");
+            try {
+                a(":input:visible", d)[0].focus()
+            } catch (c) {
+            }
+        }
+    }, info_dialog: function (d, b, c, f) {
+        var g = {width: 290, height: "auto", dataheight: "auto", drag: !0, resize: !1, caption: "<b>" + d + "</b>", left: 250, top: 170, zIndex: 1E3,
+            jqModal: !0, modal: !1, closeOnEscape: !0, align: "center", buttonalign: "center", buttons: []};
+        a.extend(g, f || {});
+        var h = g.jqModal, i = this;
+        a.fn.jqm && !h && (h = !1);
+        d = "";
+        if (0 < g.buttons.length)for (f = 0; f < g.buttons.length; f++)"undefined" == typeof g.buttons[f].id && (g.buttons[f].id = "info_button_" + f), d += "<a href='javascript:void(0)' id='" + g.buttons[f].id + "' class='fm-button ui-state-default ui-corner-all'>" + g.buttons[f].text + "</a>";
+        f = isNaN(g.dataheight) ? g.dataheight : g.dataheight + "px";
+        b = "<div id='info_id'>" + ("<div id='infocnt' style='margin:0px;padding-bottom:1em;width:100%;overflow:auto;position:relative;height:" +
+            f + ";" + ("text-align:" + g.align + ";") + "'>" + b + "</div>");
+        b += c ? "<div class='ui-widget-content ui-helper-clearfix' style='text-align:" + g.buttonalign + ";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'><a href='javascript:void(0)' id='closedialog' class='fm-button ui-state-default ui-corner-all'>" + c + "</a>" + d + "</div>" : "" !== d ? "<div class='ui-widget-content ui-helper-clearfix' style='text-align:" + g.buttonalign + ";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'>" +
+            d + "</div>" : "";
+        b += "</div>";
+        try {
+            "false" == a("#info_dialog").attr("aria-hidden") && a.jgrid.hideModal("#info_dialog", {jqm: h}), a("#info_dialog").remove()
+        } catch (e) {
+        }
+        a.jgrid.createModal({themodal: "info_dialog", modalhead: "info_head", modalcontent: "info_content", scrollelm: "infocnt"}, b, g, "", "", !0);
+        d && a.each(g.buttons, function (b) {
+            a("#" + a.jgrid.jqID(this.id), "#info_id").bind("click", function () {
+                g.buttons[b].onClick.call(a("#info_dialog"));
+                return!1
+            })
+        });
+        a("#closedialog", "#info_id").click(function () {
+            i.hideModal("#info_dialog",
+                {jqm: h});
+            return!1
+        });
+        a(".fm-button", "#info_dialog").hover(function () {
+            a(this).addClass("ui-state-hover")
+        }, function () {
+            a(this).removeClass("ui-state-hover")
+        });
+        a.isFunction(g.beforeOpen) && g.beforeOpen();
+        a.jgrid.viewModal("#info_dialog", {onHide: function (a) {
+            a.w.hide().remove();
+            a.o && a.o.remove()
+        }, modal: g.modal, jqm: h});
+        a.isFunction(g.afterOpen) && g.afterOpen();
+        try {
+            a("#info_dialog").focus()
+        } catch (l) {
+        }
+    }, createEl: function (d, b, c, f, g) {
+        function h(b, d) {
+            a.isFunction(d.dataInit) && d.dataInit.call(l, b);
+            d.dataEvents &&
+            a.each(d.dataEvents, function () {
+                void 0 !== this.data ? a(b).bind(this.type, this.data, this.fn) : a(b).bind(this.type, this.fn)
+            });
+            return d
+        }
+
+        function i(b, d, c) {
+            var e = "dataInit dataEvents dataUrl buildSelect sopt searchhidden defaultValue attr".split(" ");
+            "undefined" != typeof c && a.isArray(c) && a.merge(e, c);
+            a.each(d, function (d, c) {
+                -1 === a.inArray(d, e) && a(b).attr(d, c)
+            });
+            d.hasOwnProperty("id") || a(b).attr("id", a.jgrid.randId())
+        }
+
+        var e = "", l = this;
+        switch (d) {
+            case "textarea":
+                e = document.createElement("textarea");
+                f ? b.cols || a(e).css({width: "98%"}) :
+                    b.cols || (b.cols = 20);
+                b.rows || (b.rows = 2);
+                if ("&nbsp;" == c || "&#160;" == c || 1 == c.length && 160 == c.charCodeAt(0))c = "";
+                e.value = c;
+                i(e, b);
+                b = h(e, b);
+                a(e).attr({role: "textbox", multiline: "true"});
+                break;
+            case "checkbox":
+                e = document.createElement("input");
+                e.type = "checkbox";
+                b.value ? (d = b.value.split(":"), c === d[0] && (e.checked = !0, e.defaultChecked = !0), e.value = d[0], a(e).attr("offval", d[1])) : (d = c.toLowerCase(), 0 > d.search(/(false|0|no|off|undefined)/i) && "" !== d ? (e.checked = !0, e.defaultChecked = !0, e.value = c) : e.value = "on", a(e).attr("offval",
+                    "off"));
+                i(e, b, ["value"]);
+                b = h(e, b);
+                a(e).attr("role", "checkbox");
+                break;
+            case "select":
+                e = document.createElement("select");
+                e.setAttribute("role", "select");
+                f = [];
+                !0 === b.multiple ? (d = !0, e.multiple = "multiple", a(e).attr("aria-multiselectable", "true")) : d = !1;
+                if ("undefined" != typeof b.dataUrl)a.ajax(a.extend({url: b.dataUrl, type: "GET", dataType: "html", context: {elem: e, options: b, vl: c}, success: function (d) {
+                    var b = [], c = this.elem, e = this.vl, f = a.extend({}, this.options), g = f.multiple === true;
+                    a.isFunction(f.buildSelect) && (d = f.buildSelect.call(l,
+                        d));
+                    if (d = a(d).html()) {
+                        a(c).append(d);
+                        i(c, f);
+                        f = h(c, f);
+                        if (typeof f.size === "undefined")f.size = g ? 3 : 1;
+                        if (g) {
+                            b = e.split(",");
+                            b = a.map(b, function (b) {
+                                return a.trim(b)
+                            })
+                        } else b[0] = a.trim(e);
+                        setTimeout(function () {
+                            a("option", c).each(function (d) {
+                                if (d === 0 && c.multiple)this.selected = false;
+                                a(this).attr("role", "option");
+                                if (a.inArray(a.trim(a(this).text()), b) > -1 || a.inArray(a.trim(a(this).val()), b) > -1)this.selected = "selected"
+                            })
+                        }, 0)
+                    }
+                }}, g || {})); else if (b.value) {
+                    var j;
+                    "undefined" === typeof b.size && (b.size = d ? 3 : 1);
+                    d && (f = c.split(","),
+                        f = a.map(f, function (b) {
+                            return a.trim(b)
+                        }));
+                    "function" === typeof b.value && (b.value = b.value());
+                    var k, n, m = void 0 === b.separator ? ":" : b.separator, g = void 0 === b.delimiter ? ";" : b.delimiter;
+                    if ("string" === typeof b.value) {
+                        k = b.value.split(g);
+                        for (j = 0; j < k.length; j++) {
+                            n = k[j].split(m);
+                            2 < n.length && (n[1] = a.map(n,function (a, b) {
+                                if (b > 0)return a
+                            }).join(m));
+                            g = document.createElement("option");
+                            g.setAttribute("role", "option");
+                            g.value = n[0];
+                            g.innerHTML = n[1];
+                            e.appendChild(g);
+                            if (!d && (a.trim(n[0]) == a.trim(c) || a.trim(n[1]) == a.trim(c)))g.selected =
+                                "selected";
+                            if (d && (-1 < a.inArray(a.trim(n[1]), f) || -1 < a.inArray(a.trim(n[0]), f)))g.selected = "selected"
+                        }
+                    } else if ("object" === typeof b.value)for (j in m = b.value, m)if (m.hasOwnProperty(j)) {
+                        g = document.createElement("option");
+                        g.setAttribute("role", "option");
+                        g.value = j;
+                        g.innerHTML = m[j];
+                        e.appendChild(g);
+                        if (!d && (a.trim(j) == a.trim(c) || a.trim(m[j]) == a.trim(c)))g.selected = "selected";
+                        if (d && (-1 < a.inArray(a.trim(m[j]), f) || -1 < a.inArray(a.trim(j), f)))g.selected = "selected"
+                    }
+                    i(e, b, ["value"]);
+                    b = h(e, b)
+                }
+                break;
+            case "text":
+            case "password":
+            case "button":
+                j =
+                    "button" == d ? "button" : "textbox";
+                e = document.createElement("input");
+                e.type = d;
+                e.value = c;
+                i(e, b);
+                b = h(e, b);
+                "button" != d && (f ? b.size || a(e).css({width: "98%"}) : b.size || (b.size = 20));
+                a(e).attr("role", j);
+                break;
+            case "image":
+            case "file":
+                e = document.createElement("input");
+                e.type = d;
+                i(e, b);
+                b = h(e, b);
+                break;
+            case "custom":
+                e = document.createElement("span");
+                try {
+                    if (a.isFunction(b.custom_element))if (m = b.custom_element.call(l, c, b))m = a(m).addClass("customelement").attr({id: b.id, name: b.name}), a(e).empty().append(m); else throw"e2";
+                    else throw"e1";
+                } catch (o) {
+                    "e1" == o && a.jgrid.info_dialog(a.jgrid.errors.errcap, "function 'custom_element' " + a.jgrid.edit.msg.nodefined, a.jgrid.edit.bClose), "e2" == o ? a.jgrid.info_dialog(a.jgrid.errors.errcap, "function 'custom_element' " + a.jgrid.edit.msg.novalue, a.jgrid.edit.bClose) : a.jgrid.info_dialog(a.jgrid.errors.errcap, "string" === typeof o ? o : o.message, a.jgrid.edit.bClose)
+                }
+        }
+        return e
+    }, checkDate: function (a, b) {
+        var c = {}, f, a = a.toLowerCase();
+        f = -1 != a.indexOf("/") ? "/" : -1 != a.indexOf("-") ? "-" : -1 != a.indexOf(".") ?
+            "." : "/";
+        a = a.split(f);
+        b = b.split(f);
+        if (3 != b.length)return!1;
+        f = -1;
+        for (var g, h = -1, i = -1, e = 0; e < a.length; e++)g = isNaN(b[e]) ? 0 : parseInt(b[e], 10), c[a[e]] = g, g = a[e], -1 != g.indexOf("y") && (f = e), -1 != g.indexOf("m") && (i = e), -1 != g.indexOf("d") && (h = e);
+        g = "y" == a[f] || "yyyy" == a[f] ? 4 : "yy" == a[f] ? 2 : -1;
+        var e = function (a) {
+            for (var b = 1; b <= a; b++) {
+                this[b] = 31;
+                if (4 == b || 6 == b || 9 == b || 11 == b)this[b] = 30;
+                2 == b && (this[b] = 29)
+            }
+            return this
+        }(12), l;
+        if (-1 === f)return!1;
+        l = c[a[f]].toString();
+        2 == g && 1 == l.length && (g = 1);
+        if (l.length != g || 0 === c[a[f]] && "00" !=
+            b[f] || -1 === i)return!1;
+        l = c[a[i]].toString();
+        if (1 > l.length || (1 > c[a[i]] || 12 < c[a[i]]) || -1 === h)return!1;
+        l = c[a[h]].toString();
+        return 1 > l.length || 1 > c[a[h]] || 31 < c[a[h]] || 2 == c[a[i]] && c[a[h]] > (0 === c[a[f]] % 4 && (0 !== c[a[f]] % 100 || 0 === c[a[f]] % 400) ? 29 : 28) || c[a[h]] > e[c[a[i]]] ? !1 : !0
+    }, isEmpty: function (a) {
+        return a.match(/^\s+$/) || "" === a ? !0 : !1
+    }, checkTime: function (d) {
+        var b = /^(\d{1,2}):(\d{2})([ap]m)?$/;
+        if (!a.jgrid.isEmpty(d))if (d = d.match(b)) {
+            if (d[3]) {
+                if (1 > d[1] || 12 < d[1])return!1
+            } else if (23 < d[1])return!1;
+            if (59 < d[2])return!1
+        } else return!1;
+        return!0
+    }, checkValues: function (d, b, c, f, g) {
+        var h, i;
+        if ("undefined" === typeof f)if ("string" == typeof b) {
+            f = 0;
+            for (g = c.p.colModel.length; f < g; f++)if (c.p.colModel[f].name == b) {
+                h = c.p.colModel[f].editrules;
+                b = f;
+                try {
+                    i = c.p.colModel[f].formoptions.label
+                } catch (e) {
+                }
+                break
+            }
+        } else 0 <= b && (h = c.p.colModel[b].editrules); else h = f, i = void 0 === g ? "_" : g;
+        if (h) {
+            i || (i = c.p.colNames[b]);
+            if (!0 === h.required && a.jgrid.isEmpty(d))return[!1, i + ": " + a.jgrid.edit.msg.required, ""];
+            f = !1 === h.required ? !1 : !0;
+            if (!0 === h.number && !(!1 === f && a.jgrid.isEmpty(d)) &&
+                isNaN(d))return[!1, i + ": " + a.jgrid.edit.msg.number, ""];
+            if ("undefined" != typeof h.minValue && !isNaN(h.minValue) && parseFloat(d) < parseFloat(h.minValue))return[!1, i + ": " + a.jgrid.edit.msg.minValue + " " + h.minValue, ""];
+            if ("undefined" != typeof h.maxValue && !isNaN(h.maxValue) && parseFloat(d) > parseFloat(h.maxValue))return[!1, i + ": " + a.jgrid.edit.msg.maxValue + " " + h.maxValue, ""];
+            if (!0 === h.email && !(!1 === f && a.jgrid.isEmpty(d)) && (g = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,
+                !g.test(d)))return[!1, i + ": " + a.jgrid.edit.msg.email, ""];
+            if (!0 === h.integer && !(!1 === f && a.jgrid.isEmpty(d)) && (isNaN(d) || 0 !== d % 1 || -1 != d.indexOf(".")))return[!1, i + ": " + a.jgrid.edit.msg.integer, ""];
+            if (!0 === h.date && !(!1 === f && a.jgrid.isEmpty(d)) && (b = c.p.colModel[b].formatoptions && c.p.colModel[b].formatoptions.newformat ? c.p.colModel[b].formatoptions.newformat : c.p.colModel[b].datefmt || "Y-m-d", !a.jgrid.checkDate(b, d)))return[!1, i + ": " + a.jgrid.edit.msg.date + " - " + b, ""];
+            if (!0 === h.time && !(!1 === f && a.jgrid.isEmpty(d)) && !a.jgrid.checkTime(d))return[!1, i + ": " + a.jgrid.edit.msg.date + " - hh:mm (am/pm)", ""];
+            if (!0 === h.url && !(!1 === f && a.jgrid.isEmpty(d)) && (g = /^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i, !g.test(d)))return[!1, i + ": " + a.jgrid.edit.msg.url, ""];
+            if (!0 === h.custom && !(!1 === f && a.jgrid.isEmpty(d)))return a.isFunction(h.custom_func) ? (d = h.custom_func.call(c, d, i), a.isArray(d) ? d : [!1, a.jgrid.edit.msg.customarray, ""]) : [!1, a.jgrid.edit.msg.customfcheck,
+                ""]
+        }
+        return[!0, "", ""]
+    }})
+})(jQuery);
+(function (a) {
+    var c = {};
+    a.jgrid.extend({searchGrid: function (c) {
+        c = a.extend({recreateFilter: !1, drag: !0, sField: "searchField", sValue: "searchString", sOper: "searchOper", sFilter: "filters", loadDefaults: !0, beforeShowSearch: null, afterShowSearch: null, onInitializeSearch: null, afterRedraw: null, afterChange: null, closeAfterSearch: !1, closeAfterReset: !1, closeOnEscape: !1, searchOnEnter: !1, multipleSearch: !1, multipleGroup: !1, top: 0, left: 0, jqModal: !0, modal: !1, resize: !0, width: 450, height: "auto", dataheight: "auto", showQuery: !1,
+            errorcheck: !0, sopt: null, stringResult: void 0, onClose: null, onSearch: null, onReset: null, toTop: !0, overlay: 30, columns: [], tmplNames: null, tmplFilters: null, tmplLabel: " Template: ", showOnLoad: !1, layer: null}, a.jgrid.search, c || {});
+        return this.each(function () {
+            function d(b) {
+                r = a(e).triggerHandler("jqGridFilterBeforeShow", [b]);
+                "undefined" === typeof r && (r = !0);
+                r && a.isFunction(c.beforeShowSearch) && (r = c.beforeShowSearch.call(e, b));
+                r && (a.jgrid.viewModal("#" + a.jgrid.jqID(t.themodal), {gbox: "#gbox_" + a.jgrid.jqID(l), jqm: c.jqModal,
+                    modal: c.modal, overlay: c.overlay, toTop: c.toTop}), a(e).triggerHandler("jqGridFilterAfterShow", [b]), a.isFunction(c.afterShowSearch) && c.afterShowSearch.call(e, b))
+            }
+
+            var e = this;
+            if (e.grid) {
+                var l = "fbox_" + e.p.id, r = !0, t = {themodal: "searchmod" + l, modalhead: "searchhd" + l, modalcontent: "searchcnt" + l, scrollelm: l}, s = e.p.postData[c.sFilter];
+                "string" === typeof s && (s = a.jgrid.parse(s));
+                !0 === c.recreateFilter && a("#" + a.jgrid.jqID(t.themodal)).remove();
+                if (null !== a("#" + a.jgrid.jqID(t.themodal)).html())d(a("#fbox_" + a.jgrid.jqID(+e.p.id)));
+                else {
+                    var p = a("<div><div id='" + l + "' class='searchFilter' style='overflow:auto'></div></div>").insertBefore("#gview_" + a.jgrid.jqID(e.p.id)), g = "left", f = "";
+                    "rtl" == e.p.direction && (g = "right", f = " style='text-align:left'", p.attr("dir", "rtl"));
+                    var n = a.extend([], e.p.colModel), w = "<a href='javascript:void(0)' id='" + l + "_search' class='fm-button ui-state-default ui-corner-all fm-button-icon-right ui-reset'><span class='ui-icon ui-icon-search'></span>" + c.Find + "</a>", b = "<a href='javascript:void(0)' id='" + l + "_reset' class='fm-button ui-state-default ui-corner-all fm-button-icon-left ui-search'><span class='ui-icon ui-icon-arrowreturnthick-1-w'></span>" +
+                        c.Reset + "</a>", m = "", h = "", k, j = !1, o = -1;
+                    c.showQuery && (m = "<a href='javascript:void(0)' id='" + l + "_query' class='fm-button ui-state-default ui-corner-all fm-button-icon-left'><span class='ui-icon ui-icon-comment'></span>Query</a>");
+                    c.columns.length ? n = c.columns : a.each(n, function (a, b) {
+                        if (!b.label)b.label = e.p.colNames[a];
+                        if (!j) {
+                            var c = typeof b.search === "undefined" ? true : b.search, d = b.hidden === true;
+                            if (b.searchoptions && b.searchoptions.searchhidden === true && c || c && !d) {
+                                j = true;
+                                k = b.index || b.name;
+                                o = a
+                            }
+                        }
+                    });
+                    if (!s && k || !1 ===
+                        c.multipleSearch) {
+                        var y = "eq";
+                        0 <= o && n[o].searchoptions && n[o].searchoptions.sopt ? y = n[o].searchoptions.sopt[0] : c.sopt && c.sopt.length && (y = c.sopt[0]);
+                        s = {groupOp: "AND", rules: [
+                            {field: k, op: y, data: ""}
+                        ]}
+                    }
+                    j = !1;
+                    c.tmplNames && c.tmplNames.length && (j = !0, h = c.tmplLabel, h += "<select class='ui-template'>", h += "<option value='default'>Default</option>", a.each(c.tmplNames, function (a, b) {
+                        h = h + ("<option value='" + a + "'>" + b + "</option>")
+                    }), h += "</select>");
+                    g = "<table class='EditTable' style='border:0px none;margin-top:5px' id='" +
+                        l + "_2'><tbody><tr><td colspan='2'><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr><td class='EditButton' style='text-align:" + g + "'>" + b + h + "</td><td class='EditButton' " + f + ">" + m + w + "</td></tr></tbody></table>";
+                    l = a.jgrid.jqID(l);
+                    a("#" + l).jqFilter({columns: n, filter: c.loadDefaults ? s : null, showQuery: c.showQuery, errorcheck: c.errorcheck, sopt: c.sopt, groupButton: c.multipleGroup, ruleButtons: c.multipleSearch, afterRedraw: c.afterRedraw, _gridsopt: a.jgrid.search.odata, ajaxSelectOptions: e.p.ajaxSelectOptions,
+                        groupOps: c.groupOps, onChange: function () {
+                            this.p.showQuery && a(".query", this).html(this.toUserFriendlyString());
+                            a.isFunction(c.afterChange) && c.afterChange.call(e, a("#" + l), c)
+                        }, direction: e.p.direction});
+                    p.append(g);
+                    j && (c.tmplFilters && c.tmplFilters.length) && a(".ui-template", p).bind("change", function () {
+                        var b = a(this).val();
+                        b == "default" ? a("#" + l).jqFilter("addFilter", s) : a("#" + l).jqFilter("addFilter", c.tmplFilters[parseInt(b, 10)]);
+                        return false
+                    });
+                    !0 === c.multipleGroup && (c.multipleSearch = !0);
+                    a(e).triggerHandler("jqGridFilterInitialize",
+                        [a("#" + l)]);
+                    a.isFunction(c.onInitializeSearch) && c.onInitializeSearch.call(e, a("#" + l));
+                    c.gbox = "#gbox_" + l;
+                    c.layer ? a.jgrid.createModal(t, p, c, "#gview_" + a.jgrid.jqID(e.p.id), a("#gbox_" + a.jgrid.jqID(e.p.id))[0], "#" + a.jgrid.jqID(c.layer), {position: "relative"}) : a.jgrid.createModal(t, p, c, "#gview_" + a.jgrid.jqID(e.p.id), a("#gbox_" + a.jgrid.jqID(e.p.id))[0]);
+                    (c.searchOnEnter || c.closeOnEscape) && a("#" + a.jgrid.jqID(t.themodal)).keydown(function (b) {
+                        var d = a(b.target);
+                        if (c.searchOnEnter && b.which === 13 && !d.hasClass("add-group") && !d.hasClass("add-rule") && !d.hasClass("delete-group") && !d.hasClass("delete-rule") && (!d.hasClass("fm-button") || !d.is("[id$=_query]"))) {
+                            a("#" + l + "_search").focus().click();
+                            return false
+                        }
+                        if (c.closeOnEscape && b.which === 27) {
+                            a("#" + a.jgrid.jqID(t.modalhead)).find(".ui-jqdialog-titlebar-close").focus().click();
+                            return false
+                        }
+                    });
+                    m && a("#" + l + "_query").bind("click", function () {
+                        a(".queryresult", p).toggle();
+                        return false
+                    });
+                    void 0 === c.stringResult && (c.stringResult = c.multipleSearch);
+                    a("#" + l + "_search").bind("click", function () {
+                        var b =
+                            a("#" + l), d = {}, h, q = b.jqFilter("filterData");
+                        if (c.errorcheck) {
+                            b[0].hideError();
+                            c.showQuery || b.jqFilter("toSQLString");
+                            if (b[0].p.error) {
+                                b[0].showError();
+                                return false
+                            }
+                        }
+                        if (c.stringResult) {
+                            try {
+                                h = xmlJsonClass.toJson(q, "", "", false)
+                            } catch (f) {
+                                try {
+                                    h = JSON.stringify(q)
+                                } catch (g) {
+                                }
+                            }
+                            if (typeof h === "string") {
+                                d[c.sFilter] = h;
+                                a.each([c.sField, c.sValue, c.sOper], function () {
+                                    d[this] = ""
+                                })
+                            }
+                        } else if (c.multipleSearch) {
+                            d[c.sFilter] = q;
+                            a.each([c.sField, c.sValue, c.sOper], function () {
+                                d[this] = ""
+                            })
+                        } else {
+                            d[c.sField] = q.rules[0].field;
+                            d[c.sValue] = q.rules[0].data;
+                            d[c.sOper] = q.rules[0].op;
+                            d[c.sFilter] = ""
+                        }
+                        e.p.search = true;
+                        a.extend(e.p.postData, d);
+                        a(e).triggerHandler("jqGridFilterSearch");
+                        a.isFunction(c.onSearch) && c.onSearch.call(e);
+                        a(e).trigger("reloadGrid", [
+                            {page: 1}
+                        ]);
+                        c.closeAfterSearch && a.jgrid.hideModal("#" + a.jgrid.jqID(t.themodal), {gb: "#gbox_" + a.jgrid.jqID(e.p.id), jqm: c.jqModal, onClose: c.onClose});
+                        return false
+                    });
+                    a("#" + l + "_reset").bind("click", function () {
+                        var b = {}, d = a("#" + l);
+                        e.p.search = false;
+                        c.multipleSearch === false ? b[c.sField] =
+                            b[c.sValue] = b[c.sOper] = "" : b[c.sFilter] = "";
+                        d[0].resetFilter();
+                        j && a(".ui-template", p).val("default");
+                        a.extend(e.p.postData, b);
+                        a(e).triggerHandler("jqGridFilterReset");
+                        a.isFunction(c.onReset) && c.onReset.call(e);
+                        a(e).trigger("reloadGrid", [
+                            {page: 1}
+                        ]);
+                        return false
+                    });
+                    d(a("#" + l));
+                    a(".fm-button:not(.ui-state-disabled)", p).hover(function () {
+                        a(this).addClass("ui-state-hover")
+                    }, function () {
+                        a(this).removeClass("ui-state-hover")
+                    })
+                }
+            }
+        })
+    }, editGridRow: function (u, d) {
+        d = a.extend({top: 0, left: 0, width: 300, height: "auto", dataheight: "auto",
+            modal: !1, overlay: 30, drag: !0, resize: !0, url: null, mtype: "POST", clearAfterAdd: !0, closeAfterEdit: !1, reloadAfterSubmit: !0, onInitializeForm: null, beforeInitData: null, beforeShowForm: null, afterShowForm: null, beforeSubmit: null, afterSubmit: null, onclickSubmit: null, afterComplete: null, onclickPgButtons: null, afterclickPgButtons: null, editData: {}, recreateForm: !1, jqModal: !0, closeOnEscape: !1, addedrow: "first", topinfo: "", bottominfo: "", saveicon: [], closeicon: [], savekey: [!1, 13], navkeys: [!1, 38, 40], checkOnSubmit: !1, checkOnUpdate: !1,
+            _savedData: {}, processing: !1, onClose: null, ajaxEditOptions: {}, serializeEditData: null, viewPagerButtons: !0}, a.jgrid.edit, d || {});
+        c[a(this)[0].p.id] = d;
+        return this.each(function () {
+            function e() {
+                a(j + " > tbody > tr > td > .FormElement").each(function () {
+                    var d = a(".customelement", this);
+                    if (d.length) {
+                        var c = a(d[0]).attr("name");
+                        a.each(b.p.colModel, function () {
+                            if (this.name === c && this.editoptions && a.isFunction(this.editoptions.custom_value)) {
+                                try {
+                                    if (i[c] = this.editoptions.custom_value.call(b, a("#" + a.jgrid.jqID(c), j), "get"),
+                                        void 0 === i[c])throw"e1";
+                                } catch (d) {
+                                    "e1" === d ? a.jgrid.info_dialog(jQuery.jgrid.errors.errcap, "function 'custom_value' " + a.jgrid.edit.msg.novalue, jQuery.jgrid.edit.bClose) : a.jgrid.info_dialog(jQuery.jgrid.errors.errcap, d.message, jQuery.jgrid.edit.bClose)
+                                }
+                                return!0
+                            }
+                        })
+                    } else {
+                        switch (a(this).get(0).type) {
+                            case "checkbox":
+                                a(this).is(":checked") ? i[this.name] = a(this).val() : (d = a(this).attr("offval"), i[this.name] = d);
+                                break;
+                            case "select-one":
+                                i[this.name] = a("option:selected", this).val();
+                                B[this.name] = a("option:selected",
+                                    this).text();
+                                break;
+                            case "select-multiple":
+                                i[this.name] = a(this).val();
+                                i[this.name] = i[this.name] ? i[this.name].join(",") : "";
+                                var e = [];
+                                a("option:selected", this).each(function (b, d) {
+                                    e[b] = a(d).text()
+                                });
+                                B[this.name] = e.join(",");
+                                break;
+                            case "password":
+                            case "text":
+                            case "textarea":
+                            case "button":
+                                i[this.name] = a(this).val()
+                        }
+                        b.p.autoencode && (i[this.name] = a.jgrid.htmlEncode(i[this.name]))
+                    }
+                });
+                return!0
+            }
+
+            function l(d, e, h, q) {
+                var i, f, g, k = 0, j, o, l, p = [], n = !1, u = "", m;
+                for (m = 1; m <= q; m++)u += "<td class='CaptionTD'>&#160;</td><td class='DataTD'>&#160;</td>";
+                "_empty" != d && (n = a(e).jqGrid("getInd", d));
+                a(e.p.colModel).each(function (m) {
+                    i = this.name;
+                    o = (f = this.editrules && !0 === this.editrules.edithidden ? !1 : !0 === this.hidden ? !0 : !1) ? "style='display:none'" : "";
+                    if ("cb" !== i && "subgrid" !== i && !0 === this.editable && "rn" !== i) {
+                        if (!1 === n)j = ""; else if (i == e.p.ExpandColumn && !0 === e.p.treeGrid)j = a("td:eq(" + m + ")", e.rows[n]).text(); else {
+                            try {
+                                j = a.unformat.call(e, a("td:eq(" + m + ")", e.rows[n]), {rowId: d, colModel: this}, m)
+                            } catch (r) {
+                                j = this.edittype && "textarea" == this.edittype ? a("td:eq(" + m + ")",
+                                    e.rows[n]).text() : a("td:eq(" + m + ")", e.rows[n]).html()
+                            }
+                            if (!j || "&nbsp;" == j || "&#160;" == j || 1 == j.length && 160 == j.charCodeAt(0))j = ""
+                        }
+                        var v = a.extend({}, this.editoptions || {}, {id: i, name: i}), s = a.extend({}, {elmprefix: "", elmsuffix: "", rowabove: !1, rowcontent: ""}, this.formoptions || {}), t = parseInt(s.rowpos, 10) || k + 1, y = parseInt(2 * (parseInt(s.colpos, 10) || 1), 10);
+                        "_empty" == d && v.defaultValue && (j = a.isFunction(v.defaultValue) ? v.defaultValue.call(b) : v.defaultValue);
+                        this.edittype || (this.edittype = "text");
+                        b.p.autoencode && (j = a.jgrid.htmlDecode(j));
+                        l = a.jgrid.createEl.call(b, this.edittype, v, j, !1, a.extend({}, a.jgrid.ajaxOptions, e.p.ajaxSelectOptions || {}));
+                        "" === j && "checkbox" == this.edittype && (j = a(l).attr("offval"));
+                        "" === j && "select" == this.edittype && (j = a("option:eq(0)", l).text());
+                        if (c[b.p.id].checkOnSubmit || c[b.p.id].checkOnUpdate)c[b.p.id]._savedData[i] = j;
+                        a(l).addClass("FormElement");
+                        ("text" == this.edittype || "textarea" == this.edittype) && a(l).addClass("ui-widget-content ui-corner-all");
+                        g = a(h).find("tr[rowpos=" + t + "]");
+                        s.rowabove && (v = a("<tr><td class='contentinfo' colspan='" +
+                            2 * q + "'>" + s.rowcontent + "</td></tr>"), a(h).append(v), v[0].rp = t);
+                        0 === g.length && (g = a("<tr " + o + " rowpos='" + t + "'></tr>").addClass("FormData").attr("id", "tr_" + i), a(g).append(u), a(h).append(g), g[0].rp = t);
+                        a("td:eq(" + (y - 2) + ")", g[0]).html("undefined" === typeof s.label ? e.p.colNames[m] : s.label);
+                        a("td:eq(" + (y - 1) + ")", g[0]).append(s.elmprefix).append(l).append(s.elmsuffix);
+                        p[k] = m;
+                        k++
+                    }
+                });
+                if (0 < k && (m = a("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='" + (2 * q - 1) + "' class='DataTD'><input class='FormElement' id='id_g' type='text' name='" +
+                    e.p.id + "_id' value='" + d + "'/></td></tr>"), m[0].rp = k + 999, a(h).append(m), c[b.p.id].checkOnSubmit || c[b.p.id].checkOnUpdate))c[b.p.id]._savedData[e.p.id + "_id"] = d;
+                return p
+            }
+
+            function r(d, e, h) {
+                var i, q = 0, g, f, k, o, l;
+                if (c[b.p.id].checkOnSubmit || c[b.p.id].checkOnUpdate)c[b.p.id]._savedData = {}, c[b.p.id]._savedData[e.p.id + "_id"] = d;
+                var m = e.p.colModel;
+                if ("_empty" == d)a(m).each(function () {
+                    i = this.name;
+                    k = a.extend({}, this.editoptions || {});
+                    if ((f = a("#" + a.jgrid.jqID(i), "#" + h)) && f.length && null !== f[0])if (o = "", k.defaultValue ?
+                        (o = a.isFunction(k.defaultValue) ? k.defaultValue.call(b) : k.defaultValue, "checkbox" == f[0].type ? (l = o.toLowerCase(), 0 > l.search(/(false|0|no|off|undefined)/i) && "" !== l ? (f[0].checked = !0, f[0].defaultChecked = !0, f[0].value = o) : (f[0].checked = !1, f[0].defaultChecked = !1)) : f.val(o)) : "checkbox" == f[0].type ? (f[0].checked = !1, f[0].defaultChecked = !1, o = a(f).attr("offval")) : f[0].type && "select" == f[0].type.substr(0, 6) ? f[0].selectedIndex = 0 : f.val(o), !0 === c[b.p.id].checkOnSubmit || c[b.p.id].checkOnUpdate)c[b.p.id]._savedData[i] =
+                        o
+                }), a("#id_g", "#" + h).val(d); else {
+                    var n = a(e).jqGrid("getInd", d, !0);
+                    n && (a('td[role="gridcell"]', n).each(function (f) {
+                        i = m[f].name;
+                        if ("cb" !== i && "subgrid" !== i && "rn" !== i && !0 === m[f].editable) {
+                            if (i == e.p.ExpandColumn && !0 === e.p.treeGrid)g = a(this).text(); else try {
+                                g = a.unformat.call(e, a(this), {rowId: d, colModel: m[f]}, f)
+                            } catch (j) {
+                                g = "textarea" == m[f].edittype ? a(this).text() : a(this).html()
+                            }
+                            b.p.autoencode && (g = a.jgrid.htmlDecode(g));
+                            if (!0 === c[b.p.id].checkOnSubmit || c[b.p.id].checkOnUpdate)c[b.p.id]._savedData[i] = g;
+                            i =
+                                a.jgrid.jqID(i);
+                            switch (m[f].edittype) {
+                                case "password":
+                                case "text":
+                                case "button":
+                                case "image":
+                                case "textarea":
+                                    if ("&nbsp;" == g || "&#160;" == g || 1 == g.length && 160 == g.charCodeAt(0))g = "";
+                                    a("#" + i, "#" + h).val(g);
+                                    break;
+                                case "select":
+                                    var k = g.split(","), k = a.map(k, function (b) {
+                                        return a.trim(b)
+                                    });
+                                    a("#" + i + " option", "#" + h).each(function () {
+                                        this.selected = !m[f].editoptions.multiple && (a.trim(g) == a.trim(a(this).text()) || k[0] == a.trim(a(this).text()) || k[0] == a.trim(a(this).val())) ? !0 : m[f].editoptions.multiple ? -1 < a.inArray(a.trim(a(this).text()),
+                                            k) || -1 < a.inArray(a.trim(a(this).val()), k) ? !0 : !1 : !1
+                                    });
+                                    break;
+                                case "checkbox":
+                                    g += "";
+                                    m[f].editoptions && m[f].editoptions.value ? m[f].editoptions.value.split(":")[0] == g ? (a("#" + i, "#" + h)[b.p.useProp ? "prop" : "attr"]("checked", !0), a("#" + i, "#" + h)[b.p.useProp ? "prop" : "attr"]("defaultChecked", !0)) : (a("#" + i, "#" + h)[b.p.useProp ? "prop" : "attr"]("checked", !1), a("#" + i, "#" + h)[b.p.useProp ? "prop" : "attr"]("defaultChecked", !1)) : (g = g.toLowerCase(), 0 > g.search(/(false|0|no|off|undefined)/i) && "" !== g ? (a("#" + i, "#" + h)[b.p.useProp ?
+                                        "prop" : "attr"]("checked", !0), a("#" + i, "#" + h)[b.p.useProp ? "prop" : "attr"]("defaultChecked", !0)) : (a("#" + i, "#" + h)[b.p.useProp ? "prop" : "attr"]("checked", !1), a("#" + i, "#" + h)[b.p.useProp ? "prop" : "attr"]("defaultChecked", !1)));
+                                    break;
+                                case "custom":
+                                    try {
+                                        if (m[f].editoptions && a.isFunction(m[f].editoptions.custom_value))m[f].editoptions.custom_value.call(b, a("#" + i, "#" + h), "set", g); else throw"e1";
+                                    } catch (o) {
+                                        "e1" == o ? a.jgrid.info_dialog(jQuery.jgrid.errors.errcap, "function 'custom_value' " + a.jgrid.edit.msg.nodefined, jQuery.jgrid.edit.bClose) :
+                                            a.jgrid.info_dialog(jQuery.jgrid.errors.errcap, o.message, jQuery.jgrid.edit.bClose)
+                                    }
+                            }
+                            q++
+                        }
+                    }), 0 < q && a("#id_g", j).val(d))
+                }
+            }
+
+            function t() {
+                a.each(b.p.colModel, function (a, b) {
+                    b.editoptions && !0 === b.editoptions.NullIfEmpty && i.hasOwnProperty(b.name) && "" === i[b.name] && (i[b.name] = "null")
+                })
+            }
+
+            function s() {
+                var e, f = [!0, "", ""], g = {}, q = b.p.prmNames, k, l, n, p, v, u = a(b).triggerHandler("jqGridAddEditBeforeCheckValues", [a("#" + h), z]);
+                u && "object" === typeof u && (i = u);
+                a.isFunction(c[b.p.id].beforeCheckValues) && (u = c[b.p.id].beforeCheckValues.call(b,
+                    i, a("#" + h), "_empty" == i[b.p.id + "_id"] ? q.addoper : q.editoper)) && "object" === typeof u && (i = u);
+                for (n in i)if (i.hasOwnProperty(n) && (f = a.jgrid.checkValues.call(b, i[n], n, b), !1 === f[0]))break;
+                t();
+                f[0] && (g = a(b).triggerHandler("jqGridAddEditClickSubmit", [c[b.p.id], i, z]), void 0 === g && a.isFunction(c[b.p.id].onclickSubmit) && (g = c[b.p.id].onclickSubmit.call(b, c[b.p.id], i) || {}), f = a(b).triggerHandler("jqGridAddEditBeforeSubmit", [i, a("#" + h), z]), void 0 === f && (f = [!0, "", ""]), f[0] && a.isFunction(c[b.p.id].beforeSubmit) && (f = c[b.p.id].beforeSubmit.call(b,
+                    i, a("#" + h))));
+                if (f[0] && !c[b.p.id].processing) {
+                    c[b.p.id].processing = !0;
+                    a("#sData", j + "_2").addClass("ui-state-active");
+                    l = q.oper;
+                    k = q.id;
+                    i[l] = "_empty" == a.trim(i[b.p.id + "_id"]) ? q.addoper : q.editoper;
+                    i[l] != q.addoper ? i[k] = i[b.p.id + "_id"] : void 0 === i[k] && (i[k] = i[b.p.id + "_id"]);
+                    delete i[b.p.id + "_id"];
+                    i = a.extend(i, c[b.p.id].editData, g);
+                    if (!0 === b.p.treeGrid)for (v in i[l] == q.addoper && (p = a(b).jqGrid("getGridParam", "selrow"), i["adjacency" == b.p.treeGridModel ? b.p.treeReader.parent_id_field : "parent_id"] = p), b.p.treeReader)b.p.treeReader.hasOwnProperty(v) &&
+                    (g = b.p.treeReader[v], i.hasOwnProperty(g) && !(i[l] == q.addoper && "parent_id_field" === v) && delete i[g]);
+                    i[k] = a.jgrid.stripPref(b.p.idPrefix, i[k]);
+                    v = a.extend({url: c[b.p.id].url ? c[b.p.id].url : a(b).jqGrid("getGridParam", "editurl"), type: c[b.p.id].mtype, data: a.isFunction(c[b.p.id].serializeEditData) ? c[b.p.id].serializeEditData.call(b, i) : i, complete: function (g, n) {
+                        i[k] = b.p.idPrefix + i[k];
+                        if (n != "success") {
+                            f[0] = false;
+                            f[1] = a(b).triggerHandler("jqGridAddEditErrorTextFormat", [g, z]);
+                            f[1] = a.isFunction(c[b.p.id].errorTextFormat) ?
+                                c[b.p.id].errorTextFormat.call(b, g) : n + " Status: '" + g.statusText + "'. Error code: " + g.status
+                        } else {
+                            f = a(b).triggerHandler("jqGridAddEditAfterSubmit", [g, i, z]);
+                            f === void 0 && (f = [true, "", ""]);
+                            f[0] && a.isFunction(c[b.p.id].afterSubmit) && (f = c[b.p.id].afterSubmit.call(b, g, i))
+                        }
+                        if (f[0] === false) {
+                            a("#FormError>td", j).html(f[1]);
+                            a("#FormError", j).show()
+                        } else {
+                            a.each(b.p.colModel, function () {
+                                if (B[this.name] && this.formatter && this.formatter == "select")try {
+                                    delete B[this.name]
+                                } catch (a) {
+                                }
+                            });
+                            i = a.extend(i, B);
+                            b.p.autoencode &&
+                            a.each(i, function (b, d) {
+                                i[b] = a.jgrid.htmlDecode(d)
+                            });
+                            if (i[l] == q.addoper) {
+                                f[2] || (f[2] = a.jgrid.randId());
+                                i[k] = f[2];
+                                if (c[b.p.id].closeAfterAdd) {
+                                    if (c[b.p.id].reloadAfterSubmit)a(b).trigger("reloadGrid"); else if (b.p.treeGrid === true)a(b).jqGrid("addChildNode", f[2], p, i); else {
+                                        a(b).jqGrid("addRowData", f[2], i, d.addedrow);
+                                        a(b).jqGrid("setSelection", f[2])
+                                    }
+                                    a.jgrid.hideModal("#" + a.jgrid.jqID(o.themodal), {gb: "#gbox_" + a.jgrid.jqID(m), jqm: d.jqModal, onClose: c[b.p.id].onClose})
+                                } else if (c[b.p.id].clearAfterAdd) {
+                                    c[b.p.id].reloadAfterSubmit ?
+                                        a(b).trigger("reloadGrid") : b.p.treeGrid === true ? a(b).jqGrid("addChildNode", f[2], p, i) : a(b).jqGrid("addRowData", f[2], i, d.addedrow);
+                                    r("_empty", b, h)
+                                } else c[b.p.id].reloadAfterSubmit ? a(b).trigger("reloadGrid") : b.p.treeGrid === true ? a(b).jqGrid("addChildNode", f[2], p, i) : a(b).jqGrid("addRowData", f[2], i, d.addedrow)
+                            } else {
+                                if (c[b.p.id].reloadAfterSubmit) {
+                                    a(b).trigger("reloadGrid");
+                                    c[b.p.id].closeAfterEdit || setTimeout(function () {
+                                        a(b).jqGrid("setSelection", i[k])
+                                    }, 1E3)
+                                } else b.p.treeGrid === true ? a(b).jqGrid("setTreeRow",
+                                    i[k], i) : a(b).jqGrid("setRowData", i[k], i);
+                                c[b.p.id].closeAfterEdit && a.jgrid.hideModal("#" + a.jgrid.jqID(o.themodal), {gb: "#gbox_" + a.jgrid.jqID(m), jqm: d.jqModal, onClose: c[b.p.id].onClose})
+                            }
+                            if (a.isFunction(c[b.p.id].afterComplete)) {
+                                e = g;
+                                setTimeout(function () {
+                                    a(b).triggerHandler("jqGridAddEditAfterComplete", [e, i, a("#" + h), z]);
+                                    c[b.p.id].afterComplete.call(b, e, i, a("#" + h));
+                                    e = null
+                                }, 500)
+                            }
+                            if (c[b.p.id].checkOnSubmit || c[b.p.id].checkOnUpdate) {
+                                a("#" + h).data("disabled", false);
+                                if (c[b.p.id]._savedData[b.p.id + "_id"] !=
+                                    "_empty")for (var v in c[b.p.id]._savedData)i[v] && (c[b.p.id]._savedData[v] = i[v])
+                            }
+                        }
+                        c[b.p.id].processing = false;
+                        a("#sData", j + "_2").removeClass("ui-state-active");
+                        try {
+                            a(":input:visible", "#" + h)[0].focus()
+                        } catch (u) {
+                        }
+                    }}, a.jgrid.ajaxOptions, c[b.p.id].ajaxEditOptions);
+                    !v.url && !c[b.p.id].useDataProxy && (a.isFunction(b.p.dataProxy) ? c[b.p.id].useDataProxy = !0 : (f[0] = !1, f[1] += " " + a.jgrid.errors.nourl));
+                    f[0] && (c[b.p.id].useDataProxy ? (g = b.p.dataProxy.call(b, v, "set_" + b.p.id), "undefined" == typeof g && (g = [!0, ""]), !1 === g[0] ?
+                        (f[0] = !1, f[1] = g[1] || "Error deleting the selected row!") : (v.data.oper == q.addoper && c[b.p.id].closeAfterAdd && a.jgrid.hideModal("#" + a.jgrid.jqID(o.themodal), {gb: "#gbox_" + a.jgrid.jqID(m), jqm: d.jqModal, onClose: c[b.p.id].onClose}), v.data.oper == q.editoper && c[b.p.id].closeAfterEdit && a.jgrid.hideModal("#" + a.jgrid.jqID(o.themodal), {gb: "#gbox_" + a.jgrid.jqID(m), jqm: d.jqModal, onClose: c[b.p.id].onClose}))) : a.ajax(v))
+                }
+                !1 === f[0] && (a("#FormError>td", j).html(f[1]), a("#FormError", j).show())
+            }
+
+            function p(a, b) {
+                var d = !1,
+                    c;
+                for (c in a)if (a[c] != b[c]) {
+                    d = !0;
+                    break
+                }
+                return d
+            }
+
+            function g() {
+                var d = !0;
+                a("#FormError", j).hide();
+                if (c[b.p.id].checkOnUpdate && (i = {}, B = {}, e(), F = a.extend({}, i, B), M = p(F, c[b.p.id]._savedData)))a("#" + h).data("disabled", !0), a(".confirm", "#" + o.themodal).show(), d = !1;
+                return d
+            }
+
+            function f() {
+                if ("_empty" !== u && "undefined" !== typeof b.p.savedRow && 0 < b.p.savedRow.length && a.isFunction(a.fn.jqGrid.restoreRow))for (var d = 0; d < b.p.savedRow.length; d++)if (b.p.savedRow[d].id == u) {
+                    a(b).jqGrid("restoreRow", u);
+                    break
+                }
+            }
+
+            function n(b, d) {
+                0 === b ? a("#pData", j + "_2").addClass("ui-state-disabled") : a("#pData", j + "_2").removeClass("ui-state-disabled");
+                b == d ? a("#nData", j + "_2").addClass("ui-state-disabled") : a("#nData", j + "_2").removeClass("ui-state-disabled")
+            }
+
+            function w() {
+                var d = a(b).jqGrid("getDataIDs"), c = a("#id_g", j).val();
+                return[a.inArray(c, d), d]
+            }
+
+            var b = this;
+            if (b.grid && u) {
+                var m = b.p.id, h = "FrmGrid_" + m, k = "TblGrid_" + m, j = "#" + a.jgrid.jqID(k), o = {themodal: "editmod" + m, modalhead: "edithd" + m, modalcontent: "editcnt" + m, scrollelm: h}, y = a.isFunction(c[b.p.id].beforeShowForm) ?
+                    c[b.p.id].beforeShowForm : !1, A = a.isFunction(c[b.p.id].afterShowForm) ? c[b.p.id].afterShowForm : !1, x = a.isFunction(c[b.p.id].beforeInitData) ? c[b.p.id].beforeInitData : !1, E = a.isFunction(c[b.p.id].onInitializeForm) ? c[b.p.id].onInitializeForm : !1, q = !0, v = 1, H = 0, i, B, F, M, z, h = a.jgrid.jqID(h);
+                "new" === u ? (u = "_empty", z = "add", d.caption = c[b.p.id].addCaption) : (d.caption = c[b.p.id].editCaption, z = "edit");
+                !0 === d.recreateForm && null !== a("#" + a.jgrid.jqID(o.themodal)).html() && a("#" + a.jgrid.jqID(o.themodal)).remove();
+                var I = !0;
+                d.checkOnUpdate && (d.jqModal && !d.modal) && (I = !1);
+                if (null !== a("#" + a.jgrid.jqID(o.themodal)).html()) {
+                    q = a(b).triggerHandler("jqGridAddEditBeforeInitData", [a("#" + a.jgrid.jqID(h))]);
+                    "undefined" == typeof q && (q = !0);
+                    q && x && (q = x.call(b, a("#" + h)));
+                    if (!1 === q)return;
+                    f();
+                    a(".ui-jqdialog-title", "#" + a.jgrid.jqID(o.modalhead)).html(d.caption);
+                    a("#FormError", j).hide();
+                    c[b.p.id].topinfo ? (a(".topinfo", j).html(c[b.p.id].topinfo), a(".tinfo", j).show()) : a(".tinfo", j).hide();
+                    c[b.p.id].bottominfo ? (a(".bottominfo", j + "_2").html(c[b.p.id].bottominfo),
+                        a(".binfo", j + "_2").show()) : a(".binfo", j + "_2").hide();
+                    r(u, b, h);
+                    "_empty" == u || !c[b.p.id].viewPagerButtons ? a("#pData, #nData", j + "_2").hide() : a("#pData, #nData", j + "_2").show();
+                    !0 === c[b.p.id].processing && (c[b.p.id].processing = !1, a("#sData", j + "_2").removeClass("ui-state-active"));
+                    !0 === a("#" + h).data("disabled") && (a(".confirm", "#" + a.jgrid.jqID(o.themodal)).hide(), a("#" + h).data("disabled", !1));
+                    a(b).triggerHandler("jqGridAddEditBeforeShowForm", [a("#" + h), z]);
+                    y && y.call(b, a("#" + h));
+                    a("#" + a.jgrid.jqID(o.themodal)).data("onClose",
+                        c[b.p.id].onClose);
+                    a.jgrid.viewModal("#" + a.jgrid.jqID(o.themodal), {gbox: "#gbox_" + a.jgrid.jqID(m), jqm: d.jqModal, jqM: !1, overlay: d.overlay, modal: d.modal});
+                    I || a(".jqmOverlay").click(function () {
+                        if (!g())return false;
+                        a.jgrid.hideModal("#" + a.jgrid.jqID(o.themodal), {gb: "#gbox_" + a.jgrid.jqID(m), jqm: d.jqModal, onClose: c[b.p.id].onClose});
+                        return false
+                    });
+                    a(b).triggerHandler("jqGridAddEditAfterShowForm", [a("#" + h), z]);
+                    A && A.call(b, a("#" + h))
+                } else {
+                    var G = isNaN(d.dataheight) ? d.dataheight : d.dataheight + "px", G = a("<form name='FormPost' id='" +
+                        h + "' class='FormGrid' onSubmit='return false;' style='width:100%;overflow:auto;position:relative;height:" + G + ";'></form>").data("disabled", !1), C = a("<table id='" + k + "' class='EditTable' cellspacing='0' cellpadding='0' border='0'><tbody></tbody></table>"), q = a(b).triggerHandler("jqGridAddEditBeforeInitData", [a("#" + h), z]);
+                    "undefined" == typeof q && (q = !0);
+                    q && x && (q = x.call(b, a("#" + h)));
+                    if (!1 === q)return;
+                    f();
+                    a(b.p.colModel).each(function () {
+                        var a = this.formoptions;
+                        v = Math.max(v, a ? a.colpos || 0 : 0);
+                        H = Math.max(H, a ? a.rowpos ||
+                            0 : 0)
+                    });
+                    a(G).append(C);
+                    x = a("<tr id='FormError' style='display:none'><td class='ui-state-error' colspan='" + 2 * v + "'></td></tr>");
+                    x[0].rp = 0;
+                    a(C).append(x);
+                    x = a("<tr style='display:none' class='tinfo'><td class='topinfo' colspan='" + 2 * v + "'>" + c[b.p.id].topinfo + "</td></tr>");
+                    x[0].rp = 0;
+                    a(C).append(x);
+                    var q = (x = "rtl" == b.p.direction ? !0 : !1) ? "nData" : "pData", D = x ? "pData" : "nData";
+                    l(u, b, C, v);
+                    var q = "<a href='javascript:void(0)' id='" + q + "' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></a>",
+                        D = "<a href='javascript:void(0)' id='" + D + "' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></a>", J = "<a href='javascript:void(0)' id='sData' class='fm-button ui-state-default ui-corner-all'>" + d.bSubmit + "</a>", K = "<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>" + d.bCancel + "</a>", k = "<table border='0' cellspacing='0' cellpadding='0' class='EditTable' id='" + k + "_2'><tbody><tr><td colspan='2'><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr id='Act_Buttons'><td class='navButton'>" +
+                            (x ? D + q : q + D) + "</td><td class='EditButton'>" + J + K + "</td></tr>" + ("<tr style='display:none' class='binfo'><td class='bottominfo' colspan='2'>" + c[b.p.id].bottominfo + "</td></tr>"), k = k + "</tbody></table>";
+                    if (0 < H) {
+                        var L = [];
+                        a.each(a(C)[0].rows, function (a, b) {
+                            L[a] = b
+                        });
+                        L.sort(function (a, b) {
+                            return a.rp > b.rp ? 1 : a.rp < b.rp ? -1 : 0
+                        });
+                        a.each(L, function (b, d) {
+                            a("tbody", C).append(d)
+                        })
+                    }
+                    d.gbox = "#gbox_" + a.jgrid.jqID(m);
+                    var N = !1;
+                    !0 === d.closeOnEscape && (d.closeOnEscape = !1, N = !0);
+                    k = a("<span></span>").append(G).append(k);
+                    a.jgrid.createModal(o,
+                        k, d, "#gview_" + a.jgrid.jqID(b.p.id), a("#gbox_" + a.jgrid.jqID(b.p.id))[0]);
+                    x && (a("#pData, #nData", j + "_2").css("float", "right"), a(".EditButton", j + "_2").css("text-align", "left"));
+                    c[b.p.id].topinfo && a(".tinfo", j).show();
+                    c[b.p.id].bottominfo && a(".binfo", j + "_2").show();
+                    k = k = null;
+                    a("#" + a.jgrid.jqID(o.themodal)).keydown(function (e) {
+                        var f = e.target;
+                        if (a("#" + h).data("disabled") === true)return false;
+                        if (c[b.p.id].savekey[0] === true && e.which == c[b.p.id].savekey[1] && f.tagName != "TEXTAREA") {
+                            a("#sData", j + "_2").trigger("click");
+                            return false
+                        }
+                        if (e.which === 27) {
+                            if (!g())return false;
+                            N && a.jgrid.hideModal(this, {gb: d.gbox, jqm: d.jqModal, onClose: c[b.p.id].onClose});
+                            return false
+                        }
+                        if (c[b.p.id].navkeys[0] === true) {
+                            if (a("#id_g", j).val() == "_empty")return true;
+                            if (e.which == c[b.p.id].navkeys[1]) {
+                                a("#pData", j + "_2").trigger("click");
+                                return false
+                            }
+                            if (e.which == c[b.p.id].navkeys[2]) {
+                                a("#nData", j + "_2").trigger("click");
+                                return false
+                            }
+                        }
+                    });
+                    d.checkOnUpdate && (a("a.ui-jqdialog-titlebar-close span", "#" + a.jgrid.jqID(o.themodal)).removeClass("jqmClose"), a("a.ui-jqdialog-titlebar-close",
+                        "#" + a.jgrid.jqID(o.themodal)).unbind("click").click(function () {
+                            if (!g())return false;
+                            a.jgrid.hideModal("#" + a.jgrid.jqID(o.themodal), {gb: "#gbox_" + a.jgrid.jqID(m), jqm: d.jqModal, onClose: c[b.p.id].onClose});
+                            return false
+                        }));
+                    d.saveicon = a.extend([!0, "left", "ui-icon-disk"], d.saveicon);
+                    d.closeicon = a.extend([!0, "left", "ui-icon-close"], d.closeicon);
+                    !0 === d.saveicon[0] && a("#sData", j + "_2").addClass("right" == d.saveicon[1] ? "fm-button-icon-right" : "fm-button-icon-left").append("<span class='ui-icon " + d.saveicon[2] +
+                        "'></span>");
+                    !0 === d.closeicon[0] && a("#cData", j + "_2").addClass("right" == d.closeicon[1] ? "fm-button-icon-right" : "fm-button-icon-left").append("<span class='ui-icon " + d.closeicon[2] + "'></span>");
+                    if (c[b.p.id].checkOnSubmit || c[b.p.id].checkOnUpdate)J = "<a href='javascript:void(0)' id='sNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>" + d.bYes + "</a>", D = "<a href='javascript:void(0)' id='nNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>" + d.bNo + "</a>", K = "<a href='javascript:void(0)' id='cNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>" +
+                        d.bExit + "</a>", k = d.zIndex || 999, k++, a("<div class='ui-widget-overlay jqgrid-overlay confirm' style='z-index:" + k + ";display:none;'>&#160;" + (a.browser.msie && 6 == a.browser.version ? '<iframe style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=\'0\');" src="javascript:false;"></iframe>' : "") + "</div><div class='confirm ui-widget-content ui-jqconfirm' style='z-index:" + (k + 1) + "'>" + d.saveData + "<br/><br/>" + J + D + K + "</div>").insertAfter("#" + h), a("#sNew", "#" + a.jgrid.jqID(o.themodal)).click(function () {
+                        s();
+                        a("#" + h).data("disabled", false);
+                        a(".confirm", "#" + a.jgrid.jqID(o.themodal)).hide();
+                        return false
+                    }), a("#nNew", "#" + a.jgrid.jqID(o.themodal)).click(function () {
+                        a(".confirm", "#" + a.jgrid.jqID(o.themodal)).hide();
+                        a("#" + h).data("disabled", false);
+                        setTimeout(function () {
+                            a(":input", "#" + h)[0].focus()
+                        }, 0);
+                        return false
+                    }), a("#cNew", "#" + a.jgrid.jqID(o.themodal)).click(function () {
+                        a(".confirm", "#" + a.jgrid.jqID(o.themodal)).hide();
+                        a("#" + h).data("disabled", false);
+                        a.jgrid.hideModal("#" + a.jgrid.jqID(o.themodal), {gb: "#gbox_" +
+                            a.jgrid.jqID(m), jqm: d.jqModal, onClose: c[b.p.id].onClose});
+                        return false
+                    });
+                    a(b).triggerHandler("jqGridAddEditInitializeForm", [a("#" + h), z]);
+                    E && E.call(b, a("#" + h));
+                    "_empty" == u || !c[b.p.id].viewPagerButtons ? a("#pData,#nData", j + "_2").hide() : a("#pData,#nData", j + "_2").show();
+                    a(b).triggerHandler("jqGridAddEditBeforeShowForm", [a("#" + h), z]);
+                    y && y.call(b, a("#" + h));
+                    a("#" + a.jgrid.jqID(o.themodal)).data("onClose", c[b.p.id].onClose);
+                    a.jgrid.viewModal("#" + a.jgrid.jqID(o.themodal), {gbox: "#gbox_" + a.jgrid.jqID(m), jqm: d.jqModal,
+                        overlay: d.overlay, modal: d.modal});
+                    I || a(".jqmOverlay").click(function () {
+                        if (!g())return false;
+                        a.jgrid.hideModal("#" + a.jgrid.jqID(o.themodal), {gb: "#gbox_" + a.jgrid.jqID(m), jqm: d.jqModal, onClose: c[b.p.id].onClose});
+                        return false
+                    });
+                    a(b).triggerHandler("jqGridAddEditAfterShowForm", [a("#" + h), z]);
+                    A && A.call(b, a("#" + h));
+                    a(".fm-button", "#" + a.jgrid.jqID(o.themodal)).hover(function () {
+                        a(this).addClass("ui-state-hover")
+                    }, function () {
+                        a(this).removeClass("ui-state-hover")
+                    });
+                    a("#sData", j + "_2").click(function () {
+                        i = {};
+                        B =
+                        {};
+                        a("#FormError", j).hide();
+                        e();
+                        if (i[b.p.id + "_id"] == "_empty")s(); else if (d.checkOnSubmit === true) {
+                            F = a.extend({}, i, B);
+                            if (M = p(F, c[b.p.id]._savedData)) {
+                                a("#" + h).data("disabled", true);
+                                a(".confirm", "#" + a.jgrid.jqID(o.themodal)).show()
+                            } else s()
+                        } else s();
+                        return false
+                    });
+                    a("#cData", j + "_2").click(function () {
+                        if (!g())return false;
+                        a.jgrid.hideModal("#" + a.jgrid.jqID(o.themodal), {gb: "#gbox_" + a.jgrid.jqID(m), jqm: d.jqModal, onClose: c[b.p.id].onClose});
+                        return false
+                    });
+                    a("#nData", j + "_2").click(function () {
+                        if (!g())return false;
+                        a("#FormError", j).hide();
+                        var c = w();
+                        c[0] = parseInt(c[0], 10);
+                        if (c[0] != -1 && c[1][c[0] + 1]) {
+                            a(b).triggerHandler("jqGridAddEditClickPgButtons", ["next", a("#" + h), c[1][c[0]]]);
+                            a.isFunction(d.onclickPgButtons) && d.onclickPgButtons.call(b, "next", a("#" + h), c[1][c[0]]);
+                            r(c[1][c[0] + 1], b, h);
+                            a(b).jqGrid("setSelection", c[1][c[0] + 1]);
+                            a(b).triggerHandler("jqGridAddEditAfterClickPgButtons", ["next", a("#" + h), c[1][c[0]]]);
+                            a.isFunction(d.afterclickPgButtons) && d.afterclickPgButtons.call(b, "next", a("#" + h), c[1][c[0] + 1]);
+                            n(c[0] +
+                                1, c[1].length - 1)
+                        }
+                        return false
+                    });
+                    a("#pData", j + "_2").click(function () {
+                        if (!g())return false;
+                        a("#FormError", j).hide();
+                        var c = w();
+                        if (c[0] != -1 && c[1][c[0] - 1]) {
+                            a(b).triggerHandler("jqGridAddEditClickPgButtons", ["prev", a("#" + h), c[1][c[0]]]);
+                            a.isFunction(d.onclickPgButtons) && d.onclickPgButtons.call(b, "prev", a("#" + h), c[1][c[0]]);
+                            r(c[1][c[0] - 1], b, h);
+                            a(b).jqGrid("setSelection", c[1][c[0] - 1]);
+                            a(b).triggerHandler("jqGridAddEditAfterClickPgButtons", ["prev", a("#" + h), c[1][c[0]]]);
+                            a.isFunction(d.afterclickPgButtons) &&
+                            d.afterclickPgButtons.call(b, "prev", a("#" + h), c[1][c[0] - 1]);
+                            n(c[0] - 1, c[1].length - 1)
+                        }
+                        return false
+                    })
+                }
+                y = w();
+                n(y[0], y[1].length - 1)
+            }
+        })
+    }, viewGridRow: function (c, d) {
+        d = a.extend({top: 0, left: 0, width: 0, height: "auto", dataheight: "auto", modal: !1, overlay: 30, drag: !0, resize: !0, jqModal: !0, closeOnEscape: !1, labelswidth: "30%", closeicon: [], navkeys: [!1, 38, 40], onClose: null, beforeShowForm: null, beforeInitData: null, viewPagerButtons: !0}, a.jgrid.view, d || {});
+        return this.each(function () {
+            function e() {
+                (!0 === d.closeOnEscape || !0 === d.navkeys[0]) &&
+                setTimeout(function () {
+                    a(".ui-jqdialog-titlebar-close", "#" + a.jgrid.jqID(m.modalhead)).focus()
+                }, 0)
+            }
+
+            function l(b, c, e, f) {
+                for (var g, h, k, j = 0, o, m, l = [], n = !1, p = "<td class='CaptionTD form-view-label ui-widget-content' width='" + d.labelswidth + "'>&#160;</td><td class='DataTD form-view-data ui-helper-reset ui-widget-content'>&#160;</td>", u = "", s = ["integer", "number", "currency"], r = 0, t = 0, y, x, w, A = 1; A <= f; A++)u += 1 == A ? p : "<td class='CaptionTD form-view-label ui-widget-content'>&#160;</td><td class='DataTD form-view-data ui-widget-content'>&#160;</td>";
+                a(c.p.colModel).each(function () {
+                    h = this.editrules && !0 === this.editrules.edithidden ? !1 : !0 === this.hidden ? !0 : !1;
+                    !h && "right" === this.align && (this.formatter && -1 !== a.inArray(this.formatter, s) ? r = Math.max(r, parseInt(this.width, 10)) : t = Math.max(t, parseInt(this.width, 10)))
+                });
+                y = 0 !== r ? r : 0 !== t ? t : 0;
+                n = a(c).jqGrid("getInd", b);
+                a(c.p.colModel).each(function (b) {
+                    g = this.name;
+                    x = !1;
+                    m = (h = this.editrules && !0 === this.editrules.edithidden ? !1 : !0 === this.hidden ? !0 : !1) ? "style='display:none'" : "";
+                    w = "boolean" != typeof this.viewable ? !0 : this.viewable;
+                    if ("cb" !== g && "subgrid" !== g && "rn" !== g && w) {
+                        o = !1 === n ? "" : g == c.p.ExpandColumn && !0 === c.p.treeGrid ? a("td:eq(" + b + ")", c.rows[n]).text() : a("td:eq(" + b + ")", c.rows[n]).html();
+                        x = "right" === this.align && 0 !== y ? !0 : !1;
+                        a.extend({}, this.editoptions || {}, {id: g, name: g});
+                        var d = a.extend({}, {rowabove: !1, rowcontent: ""}, this.formoptions || {}), q = parseInt(d.rowpos, 10) || j + 1, p = parseInt(2 * (parseInt(d.colpos, 10) || 1), 10);
+                        if (d.rowabove) {
+                            var r = a("<tr><td class='contentinfo' colspan='" + 2 * f + "'>" + d.rowcontent + "</td></tr>");
+                            a(e).append(r);
+                            r[0].rp = q
+                        }
+                        k = a(e).find("tr[rowpos=" + q + "]");
+                        0 === k.length && (k = a("<tr " + m + " rowpos='" + q + "'></tr>").addClass("FormData").attr("id", "trv_" + g), a(k).append(u), a(e).append(k), k[0].rp = q);
+                        a("td:eq(" + (p - 2) + ")", k[0]).html("<b>" + ("undefined" === typeof d.label ? c.p.colNames[b] : d.label) + "</b>");
+                        a("td:eq(" + (p - 1) + ")", k[0]).append("<span>" + o + "</span>").attr("id", "v_" + g);
+                        x && a("td:eq(" + (p - 1) + ") span", k[0]).css({"text-align": "right", width: y + "px"});
+                        l[j] = b;
+                        j++
+                    }
+                });
+                0 < j && (b = a("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='" +
+                    (2 * f - 1) + "' class='DataTD'><input class='FormElement' id='id_g' type='text' name='id' value='" + b + "'/></td></tr>"), b[0].rp = j + 99, a(e).append(b));
+                return l
+            }
+
+            function r(b, c) {
+                var d, e, f = 0, g, h;
+                if (h = a(c).jqGrid("getInd", b, !0))a("td", h).each(function (b) {
+                    d = c.p.colModel[b].name;
+                    e = c.p.colModel[b].editrules && !0 === c.p.colModel[b].editrules.edithidden ? !1 : !0 === c.p.colModel[b].hidden ? !0 : !1;
+                    "cb" !== d && ("subgrid" !== d && "rn" !== d) && (g = d == c.p.ExpandColumn && !0 === c.p.treeGrid ? a(this).text() : a(this).html(), a.extend({}, c.p.colModel[b].editoptions ||
+                    {}), d = a.jgrid.jqID("v_" + d), a("#" + d + " span", "#" + n).html(g), e && a("#" + d, "#" + n).parents("tr:first").hide(), f++)
+                }), 0 < f && a("#id_g", "#" + n).val(b)
+            }
+
+            function t(b, c) {
+                0 === b ? a("#pData", "#" + n + "_2").addClass("ui-state-disabled") : a("#pData", "#" + n + "_2").removeClass("ui-state-disabled");
+                b == c ? a("#nData", "#" + n + "_2").addClass("ui-state-disabled") : a("#nData", "#" + n + "_2").removeClass("ui-state-disabled")
+            }
+
+            function s() {
+                var b = a(p).jqGrid("getDataIDs"), c = a("#id_g", "#" + n).val();
+                return[a.inArray(c, b), b]
+            }
+
+            var p = this;
+            if (p.grid &&
+                c) {
+                var g = p.p.id, f = "ViewGrid_" + a.jgrid.jqID(g), n = "ViewTbl_" + a.jgrid.jqID(g), w = "ViewGrid_" + g, b = "ViewTbl_" + g, m = {themodal: "viewmod" + g, modalhead: "viewhd" + g, modalcontent: "viewcnt" + g, scrollelm: f}, h = a.isFunction(d.beforeInitData) ? d.beforeInitData : !1, k = !0, j = 1, o = 0;
+                if (null !== a("#" + a.jgrid.jqID(m.themodal)).html()) {
+                    h && (k = h.call(p, a("#" + f)), "undefined" == typeof k && (k = !0));
+                    if (!1 === k)return;
+                    a(".ui-jqdialog-title", "#" + a.jgrid.jqID(m.modalhead)).html(d.caption);
+                    a("#FormError", "#" + n).hide();
+                    r(c, p);
+                    a.isFunction(d.beforeShowForm) &&
+                    d.beforeShowForm.call(p, a("#" + f));
+                    a.jgrid.viewModal("#" + a.jgrid.jqID(m.themodal), {gbox: "#gbox_" + a.jgrid.jqID(g), jqm: d.jqModal, jqM: !1, overlay: d.overlay, modal: d.modal});
+                    e()
+                } else {
+                    var y = isNaN(d.dataheight) ? d.dataheight : d.dataheight + "px", w = a("<form name='FormPost' id='" + w + "' class='FormGrid' style='width:100%;overflow:auto;position:relative;height:" + y + ";'></form>"), A = a("<table id='" + b + "' class='EditTable' cellspacing='1' cellpadding='2' border='0' style='table-layout:fixed'><tbody></tbody></table>");
+                    h &&
+                    (k = h.call(p, a("#" + f)), "undefined" == typeof k && (k = !0));
+                    if (!1 === k)return;
+                    a(p.p.colModel).each(function () {
+                        var a = this.formoptions;
+                        j = Math.max(j, a ? a.colpos || 0 : 0);
+                        o = Math.max(o, a ? a.rowpos || 0 : 0)
+                    });
+                    a(w).append(A);
+                    l(c, p, A, j);
+                    b = "rtl" == p.p.direction ? !0 : !1;
+                    h = "<a href='javascript:void(0)' id='" + (b ? "nData" : "pData") + "' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></a>";
+                    k = "<a href='javascript:void(0)' id='" + (b ? "pData" : "nData") + "' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></a>";
+                    y = "<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>" + d.bClose + "</a>";
+                    if (0 < o) {
+                        var x = [];
+                        a.each(a(A)[0].rows, function (a, b) {
+                            x[a] = b
+                        });
+                        x.sort(function (a, b) {
+                            return a.rp > b.rp ? 1 : a.rp < b.rp ? -1 : 0
+                        });
+                        a.each(x, function (b, c) {
+                            a("tbody", A).append(c)
+                        })
+                    }
+                    d.gbox = "#gbox_" + a.jgrid.jqID(g);
+                    var E = !1;
+                    !0 === d.closeOnEscape && (d.closeOnEscape = !1, E = !0);
+                    w = a("<span></span>").append(w).append("<table border='0' class='EditTable' id='" + n + "_2'><tbody><tr id='Act_Buttons'><td class='navButton' width='" +
+                        d.labelswidth + "'>" + (b ? k + h : h + k) + "</td><td class='EditButton'>" + y + "</td></tr></tbody></table>");
+                    a.jgrid.createModal(m, w, d, "#gview_" + a.jgrid.jqID(p.p.id), a("#gview_" + a.jgrid.jqID(p.p.id))[0]);
+                    b && (a("#pData, #nData", "#" + n + "_2").css("float", "right"), a(".EditButton", "#" + n + "_2").css("text-align", "left"));
+                    d.viewPagerButtons || a("#pData, #nData", "#" + n + "_2").hide();
+                    w = null;
+                    a("#" + m.themodal).keydown(function (b) {
+                        if (b.which === 27) {
+                            E && a.jgrid.hideModal(this, {gb: d.gbox, jqm: d.jqModal, onClose: d.onClose});
+                            return false
+                        }
+                        if (d.navkeys[0] ===
+                            true) {
+                            if (b.which === d.navkeys[1]) {
+                                a("#pData", "#" + n + "_2").trigger("click");
+                                return false
+                            }
+                            if (b.which === d.navkeys[2]) {
+                                a("#nData", "#" + n + "_2").trigger("click");
+                                return false
+                            }
+                        }
+                    });
+                    d.closeicon = a.extend([!0, "left", "ui-icon-close"], d.closeicon);
+                    !0 === d.closeicon[0] && a("#cData", "#" + n + "_2").addClass("right" == d.closeicon[1] ? "fm-button-icon-right" : "fm-button-icon-left").append("<span class='ui-icon " + d.closeicon[2] + "'></span>");
+                    a.isFunction(d.beforeShowForm) && d.beforeShowForm.call(p, a("#" + f));
+                    a.jgrid.viewModal("#" +
+                        a.jgrid.jqID(m.themodal), {gbox: "#gbox_" + a.jgrid.jqID(g), jqm: d.jqModal, modal: d.modal});
+                    a(".fm-button:not(.ui-state-disabled)", "#" + n + "_2").hover(function () {
+                        a(this).addClass("ui-state-hover")
+                    }, function () {
+                        a(this).removeClass("ui-state-hover")
+                    });
+                    e();
+                    a("#cData", "#" + n + "_2").click(function () {
+                        a.jgrid.hideModal("#" + a.jgrid.jqID(m.themodal), {gb: "#gbox_" + a.jgrid.jqID(g), jqm: d.jqModal, onClose: d.onClose});
+                        return false
+                    });
+                    a("#nData", "#" + n + "_2").click(function () {
+                        a("#FormError", "#" + n).hide();
+                        var b = s();
+                        b[0] = parseInt(b[0],
+                            10);
+                        if (b[0] != -1 && b[1][b[0] + 1]) {
+                            a.isFunction(d.onclickPgButtons) && d.onclickPgButtons.call(p, "next", a("#" + f), b[1][b[0]]);
+                            r(b[1][b[0] + 1], p);
+                            a(p).jqGrid("setSelection", b[1][b[0] + 1]);
+                            a.isFunction(d.afterclickPgButtons) && d.afterclickPgButtons.call(p, "next", a("#" + f), b[1][b[0] + 1]);
+                            t(b[0] + 1, b[1].length - 1)
+                        }
+                        e();
+                        return false
+                    });
+                    a("#pData", "#" + n + "_2").click(function () {
+                        a("#FormError", "#" + n).hide();
+                        var b = s();
+                        if (b[0] != -1 && b[1][b[0] - 1]) {
+                            a.isFunction(d.onclickPgButtons) && d.onclickPgButtons.call(p, "prev", a("#" + f), b[1][b[0]]);
+                            r(b[1][b[0] - 1], p);
+                            a(p).jqGrid("setSelection", b[1][b[0] - 1]);
+                            a.isFunction(d.afterclickPgButtons) && d.afterclickPgButtons.call(p, "prev", a("#" + f), b[1][b[0] - 1]);
+                            t(b[0] - 1, b[1].length - 1)
+                        }
+                        e();
+                        return false
+                    })
+                }
+                w = s();
+                t(w[0], w[1].length - 1)
+            }
+        })
+    }, delGridRow: function (u, d) {
+        d = a.extend({top: 0, left: 0, width: 240, height: "auto", dataheight: "auto", modal: !1, overlay: 30, drag: !0, resize: !0, url: "", mtype: "POST", reloadAfterSubmit: !0, beforeShowForm: null, beforeInitData: null, afterShowForm: null, beforeSubmit: null, onclickSubmit: null, afterSubmit: null,
+            jqModal: !0, closeOnEscape: !1, delData: {}, delicon: [], cancelicon: [], onClose: null, ajaxDelOptions: {}, processing: !1, serializeDelData: null, useDataProxy: !1}, a.jgrid.del, d || {});
+        c[a(this)[0].p.id] = d;
+        return this.each(function () {
+            var e = this;
+            if (e.grid && u) {
+                var l = a.isFunction(c[e.p.id].beforeShowForm), r = a.isFunction(c[e.p.id].afterShowForm), t = a.isFunction(c[e.p.id].beforeInitData) ? c[e.p.id].beforeInitData : !1, s = e.p.id, p = {}, g = !0, f = "DelTbl_" + a.jgrid.jqID(s), n, w, b, m, h = "DelTbl_" + s, k = {themodal: "delmod" + s, modalhead: "delhd" +
+                    s, modalcontent: "delcnt" + s, scrollelm: f};
+                jQuery.isArray(u) && (u = u.join());
+                if (null !== a("#" + a.jgrid.jqID(k.themodal)).html()) {
+                    t && (g = t.call(e, a("#" + f)), "undefined" == typeof g && (g = !0));
+                    if (!1 === g)return;
+                    a("#DelData>td", "#" + f).text(u);
+                    a("#DelError", "#" + f).hide();
+                    !0 === c[e.p.id].processing && (c[e.p.id].processing = !1, a("#dData", "#" + f).removeClass("ui-state-active"));
+                    l && c[e.p.id].beforeShowForm.call(e, a("#" + f));
+                    a.jgrid.viewModal("#" + a.jgrid.jqID(k.themodal), {gbox: "#gbox_" + a.jgrid.jqID(s), jqm: c[e.p.id].jqModal, jqM: !1,
+                        overlay: c[e.p.id].overlay, modal: c[e.p.id].modal})
+                } else {
+                    var j = isNaN(c[e.p.id].dataheight) ? c[e.p.id].dataheight : c[e.p.id].dataheight + "px", h = "<div id='" + h + "' class='formdata' style='width:100%;overflow:auto;position:relative;height:" + j + ";'><table class='DelTable'><tbody><tr id='DelError' style='display:none'><td class='ui-state-error'></td></tr>" + ("<tr id='DelData' style='display:none'><td >" + u + "</td></tr>"), h = h + ('<tr><td class="delmsg" style="white-space:pre;">' + c[e.p.id].msg + "</td></tr><tr><td >&#160;</td></tr>"),
+                        h = h + "</tbody></table></div>" + ("<table cellspacing='0' cellpadding='0' border='0' class='EditTable' id='" + f + "_2'><tbody><tr><td><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr><td class='DelButton EditButton'>" + ("<a href='javascript:void(0)' id='dData' class='fm-button ui-state-default ui-corner-all'>" + d.bSubmit + "</a>") + "&#160;" + ("<a href='javascript:void(0)' id='eData' class='fm-button ui-state-default ui-corner-all'>" + d.bCancel + "</a>") + "</td></tr></tbody></table>");
+                    d.gbox = "#gbox_" +
+                        a.jgrid.jqID(s);
+                    a.jgrid.createModal(k, h, d, "#gview_" + a.jgrid.jqID(e.p.id), a("#gview_" + a.jgrid.jqID(e.p.id))[0]);
+                    t && (g = t.call(e, a("#" + f)), "undefined" == typeof g && (g = !0));
+                    if (!1 === g)return;
+                    a(".fm-button", "#" + f + "_2").hover(function () {
+                        a(this).addClass("ui-state-hover")
+                    }, function () {
+                        a(this).removeClass("ui-state-hover")
+                    });
+                    d.delicon = a.extend([!0, "left", "ui-icon-scissors"], c[e.p.id].delicon);
+                    d.cancelicon = a.extend([!0, "left", "ui-icon-cancel"], c[e.p.id].cancelicon);
+                    !0 === d.delicon[0] && a("#dData", "#" + f + "_2").addClass("right" ==
+                        d.delicon[1] ? "fm-button-icon-right" : "fm-button-icon-left").append("<span class='ui-icon " + d.delicon[2] + "'></span>");
+                    !0 === d.cancelicon[0] && a("#eData", "#" + f + "_2").addClass("right" == d.cancelicon[1] ? "fm-button-icon-right" : "fm-button-icon-left").append("<span class='ui-icon " + d.cancelicon[2] + "'></span>");
+                    a("#dData", "#" + f + "_2").click(function () {
+                        var g = [true, ""];
+                        p = {};
+                        var h = a("#DelData>td", "#" + f).text();
+                        a.isFunction(c[e.p.id].onclickSubmit) && (p = c[e.p.id].onclickSubmit.call(e, c[e.p.id], h) || {});
+                        a.isFunction(c[e.p.id].beforeSubmit) &&
+                        (g = c[e.p.id].beforeSubmit.call(e, h));
+                        if (g[0] && !c[e.p.id].processing) {
+                            c[e.p.id].processing = true;
+                            b = e.p.prmNames;
+                            n = a.extend({}, c[e.p.id].delData, p);
+                            m = b.oper;
+                            n[m] = b.deloper;
+                            w = b.id;
+                            h = ("" + h).split(",");
+                            if (!h.length)return false;
+                            for (var j in h)h.hasOwnProperty(j) && (h[j] = a.jgrid.stripPref(e.p.idPrefix, h[j]));
+                            n[w] = h.join();
+                            a(this).addClass("ui-state-active");
+                            j = a.extend({url: c[e.p.id].url ? c[e.p.id].url : a(e).jqGrid("getGridParam", "editurl"), type: c[e.p.id].mtype, data: a.isFunction(c[e.p.id].serializeDelData) ?
+                                c[e.p.id].serializeDelData.call(e, n) : n, complete: function (b, j) {
+                                if (j != "success") {
+                                    g[0] = false;
+                                    g[1] = a.isFunction(c[e.p.id].errorTextFormat) ? c[e.p.id].errorTextFormat.call(e, b) : j + " Status: '" + b.statusText + "'. Error code: " + b.status
+                                } else a.isFunction(c[e.p.id].afterSubmit) && (g = c[e.p.id].afterSubmit.call(e, b, n));
+                                if (g[0] === false) {
+                                    a("#DelError>td", "#" + f).html(g[1]);
+                                    a("#DelError", "#" + f).show()
+                                } else {
+                                    if (c[e.p.id].reloadAfterSubmit && e.p.datatype != "local")a(e).trigger("reloadGrid"); else {
+                                        if (e.p.treeGrid === true)try {
+                                            a(e).jqGrid("delTreeNode",
+                                                e.p.idPrefix + h[0])
+                                        } catch (m) {
+                                        } else for (var l = 0; l < h.length; l++)a(e).jqGrid("delRowData", e.p.idPrefix + h[l]);
+                                        e.p.selrow = null;
+                                        e.p.selarrrow = []
+                                    }
+                                    a.isFunction(c[e.p.id].afterComplete) && setTimeout(function () {
+                                        c[e.p.id].afterComplete.call(e, b, h)
+                                    }, 500)
+                                }
+                                c[e.p.id].processing = false;
+                                a("#dData", "#" + f + "_2").removeClass("ui-state-active");
+                                g[0] && a.jgrid.hideModal("#" + a.jgrid.jqID(k.themodal), {gb: "#gbox_" + a.jgrid.jqID(s), jqm: d.jqModal, onClose: c[e.p.id].onClose})
+                            }}, a.jgrid.ajaxOptions, c[e.p.id].ajaxDelOptions);
+                            if (!j.url && !c[e.p.id].useDataProxy)if (a.isFunction(e.p.dataProxy))c[e.p.id].useDataProxy = true; else {
+                                g[0] = false;
+                                g[1] = g[1] + (" " + a.jgrid.errors.nourl)
+                            }
+                            if (g[0])if (c[e.p.id].useDataProxy) {
+                                j = e.p.dataProxy.call(e, j, "del_" + e.p.id);
+                                typeof j == "undefined" && (j = [true, ""]);
+                                if (j[0] === false) {
+                                    g[0] = false;
+                                    g[1] = j[1] || "Error deleting the selected row!"
+                                } else a.jgrid.hideModal("#" + a.jgrid.jqID(k.themodal), {gb: "#gbox_" + a.jgrid.jqID(s), jqm: d.jqModal, onClose: c[e.p.id].onClose})
+                            } else a.ajax(j)
+                        }
+                        if (g[0] === false) {
+                            a("#DelError>td", "#" + f).html(g[1]);
+                            a("#DelError", "#" + f).show()
+                        }
+                        return false
+                    });
+                    a("#eData", "#" + f + "_2").click(function () {
+                        a.jgrid.hideModal("#" + a.jgrid.jqID(k.themodal), {gb: "#gbox_" + a.jgrid.jqID(s), jqm: c[e.p.id].jqModal, onClose: c[e.p.id].onClose});
+                        return false
+                    });
+                    l && c[e.p.id].beforeShowForm.call(e, a("#" + f));
+                    a.jgrid.viewModal("#" + a.jgrid.jqID(k.themodal), {gbox: "#gbox_" + a.jgrid.jqID(s), jqm: c[e.p.id].jqModal, overlay: c[e.p.id].overlay, modal: c[e.p.id].modal})
+                }
+                r && c[e.p.id].afterShowForm.call(e, a("#" + f));
+                !0 === c[e.p.id].closeOnEscape && setTimeout(function () {
+                    a(".ui-jqdialog-titlebar-close",
+                        "#" + a.jgrid.jqID(k.modalhead)).focus()
+                }, 0)
+            }
+        })
+    }, navGrid: function (c, d, e, l, r, t, s) {
+        d = a.extend({edit: !0, editicon: "ui-icon-pencil", add: !0, addicon: "ui-icon-plus", del: !0, delicon: "ui-icon-trash", search: !0, searchicon: "ui-icon-search", refresh: !0, refreshicon: "ui-icon-refresh", refreshstate: "firstpage", view: !1, viewicon: "ui-icon-document", position: "left", closeOnEscape: !0, beforeRefresh: null, afterRefresh: null, cloneToTop: !1, alertwidth: 200, alertheight: "auto", alerttop: null, alertleft: null, alertzIndex: null}, a.jgrid.nav,
+            d || {});
+        return this.each(function () {
+            if (!this.nav) {
+                var p = {themodal: "alertmod", modalhead: "alerthd", modalcontent: "alertcnt"}, g = this, f;
+                if (g.grid && "string" == typeof c) {
+                    null === a("#" + p.themodal).html() && (!d.alerttop && !d.alertleft && ("undefined" != typeof window.innerWidth ? (d.alertleft = window.innerWidth, d.alerttop = window.innerHeight) : "undefined" != typeof document.documentElement && "undefined" != typeof document.documentElement.clientWidth && 0 !== document.documentElement.clientWidth ? (d.alertleft = document.documentElement.clientWidth,
+                        d.alerttop = document.documentElement.clientHeight) : (d.alertleft = 1024, d.alerttop = 768), d.alertleft = d.alertleft / 2 - parseInt(d.alertwidth, 10) / 2, d.alerttop = d.alerttop / 2 - 25), a.jgrid.createModal(p, "<div>" + d.alerttext + "</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>", {gbox: "#gbox_" + a.jgrid.jqID(g.p.id), jqModal: !0, drag: !0, resize: !0, caption: d.alertcap, top: d.alerttop, left: d.alertleft, width: d.alertwidth, height: d.alertheight, closeOnEscape: d.closeOnEscape, zIndex: d.alertzIndex}, "", "", !0));
+                    var n = 1;
+                    d.cloneToTop && g.p.toppager && (n = 2);
+                    for (var w = 0; w < n; w++) {
+                        var b = a("<table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table navtable' style='float:left;table-layout:auto;'><tbody><tr></tr></tbody></table>"), m, h;
+                        0 === w ? (m = c, h = g.p.id, m == g.p.toppager && (h += "_top", n = 1)) : (m = g.p.toppager, h = g.p.id + "_top");
+                        "rtl" == g.p.direction && a(b).attr("dir", "rtl").css("float", "right");
+                        d.add && (l = l || {}, f = a("<td class='ui-pg-button ui-corner-all'></td>"), a(f).append("<div class='ui-pg-div'><span class='ui-icon " +
+                            d.addicon + "'></span>" + d.addtext + "</div>"), a("tr", b).append(f), a(f, b).attr({title: d.addtitle || "", id: l.id || "add_" + h}).click(function () {
+                            a(this).hasClass("ui-state-disabled") || (a.isFunction(d.addfunc) ? d.addfunc.call(g) : a(g).jqGrid("editGridRow", "new", l));
+                            return false
+                        }).hover(function () {
+                            a(this).hasClass("ui-state-disabled") || a(this).addClass("ui-state-hover")
+                        }, function () {
+                            a(this).removeClass("ui-state-hover")
+                        }), f = null);
+                        d.edit && (f = a("<td class='ui-pg-button ui-corner-all'></td>"), e = e || {}, a(f).append("<div class='ui-pg-div'><span class='ui-icon " +
+                            d.editicon + "'></span>" + d.edittext + "</div>"), a("tr", b).append(f), a(f, b).attr({title: d.edittitle || "", id: e.id || "edit_" + h}).click(function () {
+                            if (!a(this).hasClass("ui-state-disabled")) {
+                                var b = g.p.selrow;
+                                if (b)a.isFunction(d.editfunc) ? d.editfunc.call(g, b) : a(g).jqGrid("editGridRow", b, e); else {
+                                    a.jgrid.viewModal("#" + p.themodal, {gbox: "#gbox_" + a.jgrid.jqID(g.p.id), jqm: true});
+                                    a("#jqg_alrt").focus()
+                                }
+                            }
+                            return false
+                        }).hover(function () {
+                            a(this).hasClass("ui-state-disabled") || a(this).addClass("ui-state-hover")
+                        }, function () {
+                            a(this).removeClass("ui-state-hover")
+                        }),
+                            f = null);
+                        d.view && (f = a("<td class='ui-pg-button ui-corner-all'></td>"), s = s || {}, a(f).append("<div class='ui-pg-div'><span class='ui-icon " + d.viewicon + "'></span>" + d.viewtext + "</div>"), a("tr", b).append(f), a(f, b).attr({title: d.viewtitle || "", id: s.id || "view_" + h}).click(function () {
+                            if (!a(this).hasClass("ui-state-disabled")) {
+                                var b = g.p.selrow;
+                                if (b)a.isFunction(d.viewfunc) ? d.viewfunc.call(g, b) : a(g).jqGrid("viewGridRow", b, s); else {
+                                    a.jgrid.viewModal("#" + p.themodal, {gbox: "#gbox_" + a.jgrid.jqID(g.p.id), jqm: true});
+                                    a("#jqg_alrt").focus()
+                                }
+                            }
+                            return false
+                        }).hover(function () {
+                            a(this).hasClass("ui-state-disabled") ||
+                            a(this).addClass("ui-state-hover")
+                        }, function () {
+                            a(this).removeClass("ui-state-hover")
+                        }), f = null);
+                        d.del && (f = a("<td class='ui-pg-button ui-corner-all'></td>"), r = r || {}, a(f).append("<div class='ui-pg-div'><span class='ui-icon " + d.delicon + "'></span>" + d.deltext + "</div>"), a("tr", b).append(f), a(f, b).attr({title: d.deltitle || "", id: r.id || "del_" + h}).click(function () {
+                            if (!a(this).hasClass("ui-state-disabled")) {
+                                var b;
+                                if (g.p.multiselect) {
+                                    b = g.p.selarrrow;
+                                    b.length === 0 && (b = null)
+                                } else b = g.p.selrow;
+                                if (b)a.isFunction(d.delfunc) ?
+                                    d.delfunc.call(g, b) : a(g).jqGrid("delGridRow", b, r); else {
+                                    a.jgrid.viewModal("#" + p.themodal, {gbox: "#gbox_" + a.jgrid.jqID(g.p.id), jqm: true});
+                                    a("#jqg_alrt").focus()
+                                }
+                            }
+                            return false
+                        }).hover(function () {
+                                a(this).hasClass("ui-state-disabled") || a(this).addClass("ui-state-hover")
+                            }, function () {
+                                a(this).removeClass("ui-state-hover")
+                            }), f = null);
+                        (d.add || d.edit || d.del || d.view) && a("tr", b).append("<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>");
+                        d.search && (f = a("<td class='ui-pg-button ui-corner-all'></td>"),
+                            t = t || {}, a(f).append("<div class='ui-pg-div'><span class='ui-icon " + d.searchicon + "'></span>" + d.searchtext + "</div>"), a("tr", b).append(f), a(f, b).attr({title: d.searchtitle || "", id: t.id || "search_" + h}).click(function () {
+                            a(this).hasClass("ui-state-disabled") || (a.isFunction(d.searchfunc) ? d.searchfunc.call(g, t) : a(g).jqGrid("searchGrid", t));
+                            return false
+                        }).hover(function () {
+                            a(this).hasClass("ui-state-disabled") || a(this).addClass("ui-state-hover")
+                        }, function () {
+                            a(this).removeClass("ui-state-hover")
+                        }), t.showOnLoad &&
+                            !0 === t.showOnLoad && a(f, b).click(), f = null);
+                        d.refresh && (f = a("<td class='ui-pg-button ui-corner-all'></td>"), a(f).append("<div class='ui-pg-div'><span class='ui-icon " + d.refreshicon + "'></span>" + d.refreshtext + "</div>"), a("tr", b).append(f), a(f, b).attr({title: d.refreshtitle || "", id: "refresh_" + h}).click(function () {
+                            if (!a(this).hasClass("ui-state-disabled")) {
+                                a.isFunction(d.beforeRefresh) && d.beforeRefresh.call(g);
+                                g.p.search = false;
+                                try {
+                                    var b = g.p.id;
+                                    g.p.postData.filters = "";
+                                    a("#fbox_" + a.jgrid.jqID(b)).jqFilter("resetFilter");
+                                    a.isFunction(g.clearToolbar) && g.clearToolbar.call(g, false)
+                                } catch (c) {
+                                }
+                                switch (d.refreshstate) {
+                                    case "firstpage":
+                                        a(g).trigger("reloadGrid", [
+                                            {page: 1}
+                                        ]);
+                                        break;
+                                    case "current":
+                                        a(g).trigger("reloadGrid", [
+                                            {current: true}
+                                        ])
+                                }
+                                a.isFunction(d.afterRefresh) && d.afterRefresh.call(g)
+                            }
+                            return false
+                        }).hover(function () {
+                                a(this).hasClass("ui-state-disabled") || a(this).addClass("ui-state-hover")
+                            }, function () {
+                                a(this).removeClass("ui-state-hover")
+                            }), f = null);
+                        f = a(".ui-jqgrid").css("font-size") || "11px";
+                        a("body").append("<div id='testpg2' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:" +
+                            f + ";visibility:hidden;' ></div>");
+                        f = a(b).clone().appendTo("#testpg2").width();
+                        a("#testpg2").remove();
+                        a(m + "_" + d.position, m).append(b);
+                        g.p._nvtd && (f > g.p._nvtd[0] && (a(m + "_" + d.position, m).width(f), g.p._nvtd[0] = f), g.p._nvtd[1] = f);
+                        b = f = f = null;
+                        this.nav = !0
+                    }
+                }
+            }
+        })
+    }, navButtonAdd: function (c, d) {
+        d = a.extend({caption: "newButton", title: "", buttonicon: "ui-icon-newwin", onClickButton: null, position: "last", cursor: "pointer"}, d || {});
+        return this.each(function () {
+            if (this.grid) {
+                "string" === typeof c && 0 !== c.indexOf("#") && (c = "#" + a.jgrid.jqID(c));
+                var e = a(".navtable", c)[0], l = this;
+                if (e && !(d.id && null !== a("#" + a.jgrid.jqID(d.id), e).html())) {
+                    var r = a("<td></td>");
+                    "NONE" == d.buttonicon.toString().toUpperCase() ? a(r).addClass("ui-pg-button ui-corner-all").append("<div class='ui-pg-div'>" + d.caption + "</div>") : a(r).addClass("ui-pg-button ui-corner-all").append("<div class='ui-pg-div'><span class='ui-icon " + d.buttonicon + "'></span>" + d.caption + "</div>");
+                    d.id && a(r).attr("id", d.id);
+                    "first" == d.position ? 0 === e.rows[0].cells.length ? a("tr", e).append(r) : a("tr td:eq(0)",
+                        e).before(r) : a("tr", e).append(r);
+                    a(r, e).attr("title", d.title || "").click(function (c) {
+                        a(this).hasClass("ui-state-disabled") || a.isFunction(d.onClickButton) && d.onClickButton.call(l, c);
+                        return!1
+                    }).hover(function () {
+                        a(this).hasClass("ui-state-disabled") || a(this).addClass("ui-state-hover")
+                    }, function () {
+                        a(this).removeClass("ui-state-hover")
+                    })
+                }
+            }
+        })
+    }, navSeparatorAdd: function (c, d) {
+        d = a.extend({sepclass: "ui-separator", sepcontent: ""}, d || {});
+        return this.each(function () {
+            if (this.grid) {
+                "string" === typeof c && 0 !== c.indexOf("#") &&
+                (c = "#" + a.jgrid.jqID(c));
+                var e = a(".navtable", c)[0];
+                if (e) {
+                    var l = "<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='" + d.sepclass + "'></span>" + d.sepcontent + "</td>";
+                    a("tr", e).append(l)
+                }
+            }
+        })
+    }, GridToForm: function (c, d) {
+        return this.each(function () {
+            var e = this;
+            if (e.grid) {
+                var l = a(e).jqGrid("getRowData", c);
+                if (l)for (var r in l)a("[name=" + a.jgrid.jqID(r) + "]", d).is("input:radio") || a("[name=" + a.jgrid.jqID(r) + "]", d).is("input:checkbox") ? a("[name=" + a.jgrid.jqID(r) + "]", d).each(function () {
+                    if (a(this).val() ==
+                        l[r])a(this)[e.p.useProp ? "prop" : "attr"]("checked", !0); else a(this)[e.p.useProp ? "prop" : "attr"]("checked", !1)
+                }) : a("[name=" + a.jgrid.jqID(r) + "]", d).val(l[r])
+            }
+        })
+    }, FormToGrid: function (c, d, e, l) {
+        return this.each(function () {
+            if (this.grid) {
+                e || (e = "set");
+                l || (l = "first");
+                var r = a(d).serializeArray(), t = {};
+                a.each(r, function (a, c) {
+                    t[c.name] = c.value
+                });
+                "add" == e ? a(this).jqGrid("addRowData", c, t, l) : "set" == e && a(this).jqGrid("setRowData", c, t)
+            }
+        })
+    }})
+})(jQuery);
+(function (a) {
+    a.fn.jqFilter = function (d) {
+        if ("string" === typeof d) {
+            var n = a.fn.jqFilter[d];
+            if (!n)throw"jqFilter - No such method: " + d;
+            var u = a.makeArray(arguments).slice(1);
+            return n.apply(this, u)
+        }
+        var o = a.extend(!0, {filter: null, columns: [], onChange: null, afterRedraw: null, checkValues: null, error: !1, errmsg: "", errorcheck: !0, showQuery: !0, sopt: null, ops: [
+            {name: "eq", description: "equal", operator: "="},
+            {name: "ne", description: "not equal", operator: "<>"},
+            {name: "lt", description: "less", operator: "<"},
+            {name: "le", description: "less or equal",
+                operator: "<="},
+            {name: "gt", description: "greater", operator: ">"},
+            {name: "ge", description: "greater or equal", operator: ">="},
+            {name: "bw", description: "begins with", operator: "LIKE"},
+            {name: "bn", description: "does not begin with", operator: "NOT LIKE"},
+            {name: "in", description: "in", operator: "IN"},
+            {name: "ni", description: "not in", operator: "NOT IN"},
+            {name: "ew", description: "ends with", operator: "LIKE"},
+            {name: "en", description: "does not end with", operator: "NOT LIKE"},
+            {name: "cn", description: "contains", operator: "LIKE"},
+            {name: "nc",
+                description: "does not contain", operator: "NOT LIKE"},
+            {name: "nu", description: "is null", operator: "IS NULL"},
+            {name: "nn", description: "is not null", operator: "IS NOT NULL"}
+        ], numopts: "eq ne lt le gt ge nu nn in ni".split(" "), stropts: "eq ne bw bn ew en cn nc nu nn in ni".split(" "), _gridsopt: [], groupOps: [
+            {op: "AND", text: "AND"},
+            {op: "OR", text: "OR"}
+        ], groupButton: !0, ruleButtons: !0, direction: "ltr"}, a.jgrid.filter, d || {});
+        return this.each(function () {
+            if (!this.filter) {
+                this.p = o;
+                if (null === this.p.filter || void 0 === this.p.filter)this.p.filter =
+                {groupOp: this.p.groupOps[0].op, rules: [], groups: []};
+                var d, n = this.p.columns.length, f, t = /msie/i.test(navigator.userAgent) && !window.opera;
+                if (this.p._gridsopt.length)for (d = 0; d < this.p._gridsopt.length; d++)this.p.ops[d].description = this.p._gridsopt[d];
+                this.p.initFilter = a.extend(!0, {}, this.p.filter);
+                if (n) {
+                    for (d = 0; d < n; d++)if (f = this.p.columns[d], f.stype ? f.inputtype = f.stype : f.inputtype || (f.inputtype = "text"), f.sorttype ? f.searchtype = f.sorttype : f.searchtype || (f.searchtype = "string"), void 0 === f.hidden && (f.hidden = !1), f.label || (f.label = f.name), f.index && (f.name = f.index), f.hasOwnProperty("searchoptions") || (f.searchoptions = {}), !f.hasOwnProperty("searchrules"))f.searchrules = {};
+                    this.p.showQuery && a(this).append("<table class='queryresult ui-widget ui-widget-content' style='display:block;max-width:440px;border:0px none;' dir='" + this.p.direction + "'><tbody><tr><td class='query'></td></tr></tbody></table>");
+                    var r = function (g, k) {
+                        var b = [!0, ""];
+                        if (a.isFunction(k.searchrules))b = k.searchrules(g, k); else if (a.jgrid && a.jgrid.checkValues)try {
+                            b =
+                                a.jgrid.checkValues(g, -1, null, k.searchrules, k.label)
+                        } catch (c) {
+                        }
+                        b && (b.length && !1 === b[0]) && (o.error = !b[0], o.errmsg = b[1])
+                    };
+                    this.onchange = function () {
+                        this.p.error = !1;
+                        this.p.errmsg = "";
+                        return a.isFunction(this.p.onChange) ? this.p.onChange.call(this, this.p) : !1
+                    };
+                    this.reDraw = function () {
+                        a("table.group:first", this).remove();
+                        var g = this.createTableForGroup(o.filter, null);
+                        a(this).append(g);
+                        a.isFunction(this.p.afterRedraw) && this.p.afterRedraw.call(this, this.p)
+                    };
+                    this.createTableForGroup = function (g, k) {
+                        var b = this, c,
+                            e = a("<table class='group ui-widget ui-widget-content' style='border:0px none;'><tbody></tbody></table>"), d = "left";
+                        "rtl" == this.p.direction && (d = "right", e.attr("dir", "rtl"));
+                        null === k && e.append("<tr class='error' style='display:none;'><th colspan='5' class='ui-state-error' align='" + d + "'></th></tr>");
+                        var h = a("<tr></tr>");
+                        e.append(h);
+                        d = a("<th colspan='5' align='" + d + "'></th>");
+                        h.append(d);
+                        if (!0 === this.p.ruleButtons) {
+                            var i = a("<select class='opsel'></select>");
+                            d.append(i);
+                            var h = "", f;
+                            for (c = 0; c < o.groupOps.length; c++)f =
+                                g.groupOp === b.p.groupOps[c].op ? " selected='selected'" : "", h += "<option value='" + b.p.groupOps[c].op + "'" + f + ">" + b.p.groupOps[c].text + "</option>";
+                            i.append(h).bind("change", function () {
+                                g.groupOp = a(i).val();
+                                b.onchange()
+                            })
+                        }
+                        h = "<span></span>";
+                        this.p.groupButton && (h = a("<input type='button' value='+ {}' title='Add subgroup' class='add-group'/>"), h.bind("click", function () {
+                            if (g.groups === void 0)g.groups = [];
+                            g.groups.push({groupOp: o.groupOps[0].op, rules: [], groups: []});
+                            b.reDraw();
+                            b.onchange();
+                            return false
+                        }));
+                        d.append(h);
+                        if (!0 === this.p.ruleButtons) {
+                            var h = a("<input type='button' value='+' title='Add rule' class='add-rule ui-add'/>"), l;
+                            h.bind("click", function () {
+                                if (g.rules === void 0)g.rules = [];
+                                for (c = 0; c < b.p.columns.length; c++) {
+                                    var a = typeof b.p.columns[c].search === "undefined" ? true : b.p.columns[c].search, e = b.p.columns[c].hidden === true;
+                                    if (b.p.columns[c].searchoptions.searchhidden === true && a || a && !e) {
+                                        l = b.p.columns[c];
+                                        break
+                                    }
+                                }
+                                g.rules.push({field: l.name, op: (l.searchoptions.sopt ? l.searchoptions.sopt : b.p.sopt ? b.p.sopt : l.searchtype ===
+                                    "string" ? b.p.stropts : b.p.numopts)[0], data: ""});
+                                b.reDraw();
+                                return false
+                            });
+                            d.append(h)
+                        }
+                        null !== k && (h = a("<input type='button' value='-' title='Delete group' class='delete-group'/>"), d.append(h), h.bind("click", function () {
+                            for (c = 0; c < k.groups.length; c++)if (k.groups[c] === g) {
+                                k.groups.splice(c, 1);
+                                break
+                            }
+                            b.reDraw();
+                            b.onchange();
+                            return false
+                        }));
+                        if (void 0 !== g.groups)for (c = 0; c < g.groups.length; c++)d = a("<tr></tr>"), e.append(d), h = a("<td class='first'></td>"), d.append(h), h = a("<td colspan='4'></td>"), h.append(this.createTableForGroup(g.groups[c],
+                            g)), d.append(h);
+                        void 0 === g.groupOp && (g.groupOp = b.p.groupOps[0].op);
+                        if (void 0 !== g.rules)for (c = 0; c < g.rules.length; c++)e.append(this.createTableRowForRule(g.rules[c], g));
+                        return e
+                    };
+                    this.createTableRowForRule = function (g, d) {
+                        var b = this, c = a("<tr></tr>"), e, f, h, i, j = "", l;
+                        c.append("<td class='first'></td>");
+                        var m = a("<td class='columns'></td>");
+                        c.append(m);
+                        var n = a("<select></select>"), p, q = [];
+                        m.append(n);
+                        n.bind("change", function () {
+                            g.field = a(n).val();
+                            h = a(this).parents("tr:first");
+                            for (e = 0; e < b.p.columns.length; e++)if (b.p.columns[e].name ===
+                                g.field) {
+                                i = b.p.columns[e];
+                                break
+                            }
+                            if (i) {
+                                i.searchoptions.id = a.jgrid.randId();
+                                t && "text" === i.inputtype && !i.searchoptions.size && (i.searchoptions.size = 10);
+                                var c = a.jgrid.createEl(i.inputtype, i.searchoptions, "", !0, b.p.ajaxSelectOptions, !0);
+                                a(c).addClass("input-elm");
+                                f = i.searchoptions.sopt ? i.searchoptions.sopt : b.p.sopt ? b.p.sopt : "string" === i.searchtype ? b.p.stropts : b.p.numopts;
+                                var d = "", k = 0;
+                                q = [];
+                                a.each(b.p.ops, function () {
+                                    q.push(this.name)
+                                });
+                                for (e = 0; e < f.length; e++)p = a.inArray(f[e], q), -1 !== p && (0 === k && (g.op = b.p.ops[p].name),
+                                    d += "<option value='" + b.p.ops[p].name + "'>" + b.p.ops[p].description + "</option>", k++);
+                                a(".selectopts", h).empty().append(d);
+                                a(".selectopts", h)[0].selectedIndex = 0;
+                                a.browser.msie && 9 > a.browser.version && (d = parseInt(a("select.selectopts", h)[0].offsetWidth) + 1, a(".selectopts", h).width(d), a(".selectopts", h).css("width", "auto"));
+                                a(".data", h).empty().append(c);
+                                a(".input-elm", h).bind("change", function (c) {
+                                    var d = a(this).hasClass("ui-autocomplete-input") ? 200 : 0;
+                                    setTimeout(function () {
+                                        var d = c.target;
+                                        g.data = d.nodeName.toUpperCase() ===
+                                            "SPAN" && i.searchoptions && a.isFunction(i.searchoptions.custom_value) ? i.searchoptions.custom_value(a(d).children(".customelement:first"), "get") : d.value;
+                                        b.onchange()
+                                    }, d)
+                                });
+                                setTimeout(function () {
+                                    g.data = a(c).val();
+                                    b.onchange()
+                                }, 0)
+                            }
+                        });
+                        for (e = m = 0; e < b.p.columns.length; e++) {
+                            l = "undefined" === typeof b.p.columns[e].search ? !0 : b.p.columns[e].search;
+                            var r = !0 === b.p.columns[e].hidden;
+                            if (!0 === b.p.columns[e].searchoptions.searchhidden && l || l && !r)l = "", g.field === b.p.columns[e].name && (l = " selected='selected'", m = e), j += "<option value='" +
+                                b.p.columns[e].name + "'" + l + ">" + b.p.columns[e].label + "</option>"
+                        }
+                        n.append(j);
+                        j = a("<td class='operators'></td>");
+                        c.append(j);
+                        i = o.columns[m];
+                        i.searchoptions.id = a.jgrid.randId();
+                        t && "text" === i.inputtype && !i.searchoptions.size && (i.searchoptions.size = 10);
+                        var m = a.jgrid.createEl(i.inputtype, i.searchoptions, g.data, !0, b.p.ajaxSelectOptions, !0), s = a("<select class='selectopts'></select>");
+                        j.append(s);
+                        s.bind("change", function () {
+                            g.op = a(s).val();
+                            h = a(this).parents("tr:first");
+                            var c = a(".input-elm", h)[0];
+                            if (g.op === "nu" ||
+                                g.op === "nn") {
+                                g.data = "";
+                                c.value = "";
+                                c.setAttribute("readonly", "true");
+                                c.setAttribute("disabled", "true")
+                            } else {
+                                c.removeAttribute("readonly");
+                                c.removeAttribute("disabled")
+                            }
+                            b.onchange()
+                        });
+                        f = i.searchoptions.sopt ? i.searchoptions.sopt : b.p.sopt ? b.p.sopt : "string" === i.searchtype ? o.stropts : b.p.numopts;
+                        j = "";
+                        a.each(b.p.ops, function () {
+                            q.push(this.name)
+                        });
+                        for (e = 0; e < f.length; e++)p = a.inArray(f[e], q), -1 !== p && (l = g.op === b.p.ops[p].name ? " selected='selected'" : "", j += "<option value='" + b.p.ops[p].name + "'" + l + ">" + b.p.ops[p].description +
+                            "</option>");
+                        s.append(j);
+                        j = a("<td class='data'></td>");
+                        c.append(j);
+                        j.append(m);
+                        a(m).addClass("input-elm").bind("change", function () {
+                            g.data = i.inputtype === "custom" ? i.searchoptions.custom_value(a(this).children(".customelement:first"), "get") : a(this).val();
+                            b.onchange()
+                        });
+                        j = a("<td></td>");
+                        c.append(j);
+                        !0 === this.p.ruleButtons && (m = a("<input type='button' value='-' title='Delete rule' class='delete-rule ui-del'/>"), j.append(m), m.bind("click", function () {
+                            for (e = 0; e < d.rules.length; e++)if (d.rules[e] === g) {
+                                d.rules.splice(e,
+                                    1);
+                                break
+                            }
+                            b.reDraw();
+                            b.onchange();
+                            return false
+                        }));
+                        return c
+                    };
+                    this.getStringForGroup = function (a) {
+                        var d = "(", b;
+                        if (void 0 !== a.groups)for (b = 0; b < a.groups.length; b++) {
+                            1 < d.length && (d += " " + a.groupOp + " ");
+                            try {
+                                d += this.getStringForGroup(a.groups[b])
+                            } catch (c) {
+                                alert(c)
+                            }
+                        }
+                        if (void 0 !== a.rules)try {
+                            for (b = 0; b < a.rules.length; b++)1 < d.length && (d += " " + a.groupOp + " "), d += this.getStringForRule(a.rules[b])
+                        } catch (e) {
+                            alert(e)
+                        }
+                        d += ")";
+                        return"()" === d ? "" : d
+                    };
+                    this.getStringForRule = function (d) {
+                        var f = "", b = "", c, e;
+                        for (c = 0; c < this.p.ops.length; c++)if (this.p.ops[c].name ===
+                            d.op) {
+                            f = this.p.ops[c].operator;
+                            b = this.p.ops[c].name;
+                            break
+                        }
+                        for (c = 0; c < this.p.columns.length; c++)if (this.p.columns[c].name === d.field) {
+                            e = this.p.columns[c];
+                            break
+                        }
+                        c = d.data;
+                        if ("bw" === b || "bn" === b)c += "%";
+                        if ("ew" === b || "en" === b)c = "%" + c;
+                        if ("cn" === b || "nc" === b)c = "%" + c + "%";
+                        if ("in" === b || "ni" === b)c = " (" + c + ")";
+                        o.errorcheck && r(d.data, e);
+                        return-1 !== a.inArray(e.searchtype, ["int", "integer", "float", "number", "currency"]) || "nn" === b || "nu" === b ? d.field + " " + f + " " + c : d.field + " " + f + ' "' + c + '"'
+                    };
+                    this.resetFilter = function () {
+                        this.p.filter =
+                            a.extend(!0, {}, this.p.initFilter);
+                        this.reDraw();
+                        this.onchange()
+                    };
+                    this.hideError = function () {
+                        a("th.ui-state-error", this).html("");
+                        a("tr.error", this).hide()
+                    };
+                    this.showError = function () {
+                        a("th.ui-state-error", this).html(this.p.errmsg);
+                        a("tr.error", this).show()
+                    };
+                    this.toUserFriendlyString = function () {
+                        return this.getStringForGroup(o.filter)
+                    };
+                    this.toString = function () {
+                        function a(b) {
+                            var c = "(", e;
+                            if (void 0 !== b.groups)for (e = 0; e < b.groups.length; e++)1 < c.length && (c = "OR" === b.groupOp ? c + " || " : c + " && "), c += a(b.groups[e]);
+                            if (void 0 !== b.rules)for (e = 0; e < b.rules.length; e++) {
+                                1 < c.length && (c = "OR" === b.groupOp ? c + " || " : c + " && ");
+                                var f = b.rules[e];
+                                if (d.p.errorcheck) {
+                                    for (var h = void 0, i = void 0, h = 0; h < d.p.columns.length; h++)if (d.p.columns[h].name === f.field) {
+                                        i = d.p.columns[h];
+                                        break
+                                    }
+                                    i && r(f.data, i)
+                                }
+                                c += f.op + "(item." + f.field + ",'" + f.data + "')"
+                            }
+                            c += ")";
+                            return"()" === c ? "" : c
+                        }
+
+                        var d = this;
+                        return a(this.p.filter)
+                    };
+                    this.reDraw();
+                    if (this.p.showQuery)this.onchange();
+                    this.filter = !0
+                }
+            }
+        })
+    };
+    a.extend(a.fn.jqFilter, {toSQLString: function () {
+        var a = "";
+        this.each(function () {
+            a =
+                this.toUserFriendlyString()
+        });
+        return a
+    }, filterData: function () {
+        var a;
+        this.each(function () {
+            a = this.p.filter
+        });
+        return a
+    }, getParameter: function (a) {
+        return void 0 !== a && this.p.hasOwnProperty(a) ? this.p[a] : this.p
+    }, resetFilter: function () {
+        return this.each(function () {
+            this.resetFilter()
+        })
+    }, addFilter: function (a) {
+        "string" === typeof a && (a = jQuery.jgrid.parse(a));
+        this.each(function () {
+            this.p.filter = a;
+            this.reDraw();
+            this.onchange()
+        })
+    }})
+})(jQuery);
+(function (b) {
+    b.browser.msie && 8 == b.browser.version && (b.expr[":"].hidden = function (b) {
+        return 0 === b.offsetWidth || 0 === b.offsetHeight || "none" == b.style.display
+    });
+    b.jgrid._multiselect = !1;
+    if (b.ui && b.ui.multiselect) {
+        if (b.ui.multiselect.prototype._setSelected) {
+            var m = b.ui.multiselect.prototype._setSelected;
+            b.ui.multiselect.prototype._setSelected = function (a, e) {
+                var c = m.call(this, a, e);
+                if (e && this.selectedList) {
+                    var d = this.element;
+                    this.selectedList.find("li").each(function () {
+                        b(this).data("optionLink") && b(this).data("optionLink").remove().appendTo(d)
+                    })
+                }
+                return c
+            }
+        }
+        b.ui.multiselect.prototype.destroy &&
+        (b.ui.multiselect.prototype.destroy = function () {
+            this.element.show();
+            this.container.remove();
+            b.Widget === void 0 ? b.widget.prototype.destroy.apply(this, arguments) : b.Widget.prototype.destroy.apply(this, arguments)
+        });
+        b.jgrid._multiselect = !0
+    }
+    b.jgrid.extend({sortableColumns: function (a) {
+        return this.each(function () {
+            function e() {
+                c.p.disableClick = true
+            }
+
+            var c = this, d = b.jgrid.jqID(c.p.id), d = {tolerance: "pointer", axis: "x", scrollSensitivity: "1", items: ">th:not(:has(#jqgh_" + d + "_cb,#jqgh_" + d + "_rn,#jqgh_" + d + "_subgrid),:hidden)",
+                placeholder: {element: function (a) {
+                    return b(document.createElement(a[0].nodeName)).addClass(a[0].className + " ui-sortable-placeholder ui-state-highlight").removeClass("ui-sortable-helper")[0]
+                }, update: function (b, a) {
+                    a.height(b.currentItem.innerHeight() - parseInt(b.currentItem.css("paddingTop") || 0, 10) - parseInt(b.currentItem.css("paddingBottom") || 0, 10));
+                    a.width(b.currentItem.innerWidth() - parseInt(b.currentItem.css("paddingLeft") || 0, 10) - parseInt(b.currentItem.css("paddingRight") || 0, 10))
+                }}, update: function (a, g) {
+                    var d = b(g.item).parent(), d = b(">th", d), e = {}, i = c.p.id + "_";
+                    b.each(c.p.colModel, function (b) {
+                        e[this.name] = b
+                    });
+                    var h = [];
+                    d.each(function () {
+                        var a = b(">div", this).get(0).id.replace(/^jqgh_/, "").replace(i, "");
+                        a in e && h.push(e[a])
+                    });
+                    b(c).jqGrid("remapColumns", h, true, true);
+                    b.isFunction(c.p.sortable.update) && c.p.sortable.update(h);
+                    setTimeout(function () {
+                        c.p.disableClick = false
+                    }, 50)
+                }};
+            if (c.p.sortable.options)b.extend(d, c.p.sortable.options); else if (b.isFunction(c.p.sortable))c.p.sortable = {update: c.p.sortable};
+            if (d.start) {
+                var g = d.start;
+                d.start = function (b, a) {
+                    e();
+                    g.call(this, b, a)
+                }
+            } else d.start = e;
+            if (c.p.sortable.exclude)d.items = d.items + (":not(" + c.p.sortable.exclude + ")");
+            a.sortable(d).data("sortable").floating = true
+        })
+    }, columnChooser: function (a) {
+        function e(a, c) {
+            a && (typeof a == "string" ? b.fn[a] && b.fn[a].apply(c, b.makeArray(arguments).slice(2)) : b.isFunction(a) && a.apply(c, b.makeArray(arguments).slice(2)))
+        }
+
+        var c = this;
+        if (!b("#colchooser_" + b.jgrid.jqID(c[0].p.id)).length) {
+            var d = b('<div id="colchooser_' + c[0].p.id + '" style="position:relative;overflow:hidden"><div><select multiple="multiple"></select></div></div>'),
+                g = b("select", d), a = b.extend({width: 420, height: 240, classname: null, done: function (b) {
+                    b && c.jqGrid("remapColumns", b, true)
+                }, msel: "multiselect", dlog: "dialog", dialog_opts: {minWidth: 470}, dlog_opts: function (a) {
+                    var c = {};
+                    c[a.bSubmit] = function () {
+                        a.apply_perm();
+                        a.cleanup(false)
+                    };
+                    c[a.bCancel] = function () {
+                        a.cleanup(true)
+                    };
+                    return b.extend(true, {buttons: c, close: function () {
+                        a.cleanup(true)
+                    }, modal: a.modal ? a.modal : false, resizable: a.resizable ? a.resizable : true, width: a.width + 20}, a.dialog_opts || {})
+                }, apply_perm: function () {
+                    b("option",
+                        g).each(function () {
+                            this.selected ? c.jqGrid("showCol", k[this.value].name) : c.jqGrid("hideCol", k[this.value].name)
+                        });
+                    var d = [];
+                    b("option:selected", g).each(function () {
+                        d.push(parseInt(this.value, 10))
+                    });
+                    b.each(d, function () {
+                        delete f[k[parseInt(this, 10)].name]
+                    });
+                    b.each(f, function () {
+                        var b = parseInt(this, 10);
+                        var a = d, c = b;
+                        if (c >= 0) {
+                            var g = a.slice(), e = g.splice(c, Math.max(a.length - c, c));
+                            if (c > a.length)c = a.length;
+                            g[c] = b;
+                            d = g.concat(e)
+                        } else d = void 0
+                    });
+                    a.done && a.done.call(c, d)
+                }, cleanup: function (b) {
+                    e(a.dlog, d, "destroy");
+                    e(a.msel, g, "destroy");
+                    d.remove();
+                    b && a.done && a.done.call(c)
+                }, msel_opts: {}}, b.jgrid.col, a || {});
+            if (b.ui && b.ui.multiselect && a.msel == "multiselect") {
+                if (!b.jgrid._multiselect) {
+                    alert("Multiselect plugin loaded after jqGrid. Please load the plugin before the jqGrid!");
+                    return
+                }
+                a.msel_opts = b.extend(b.ui.multiselect.defaults, a.msel_opts)
+            }
+            a.caption && d.attr("title", a.caption);
+            if (a.classname) {
+                d.addClass(a.classname);
+                g.addClass(a.classname)
+            }
+            if (a.width) {
+                b(">div", d).css({width: a.width, margin: "0 auto"});
+                g.css("width",
+                    a.width)
+            }
+            if (a.height) {
+                b(">div", d).css("height", a.height);
+                g.css("height", a.height - 10)
+            }
+            var k = c.jqGrid("getGridParam", "colModel"), p = c.jqGrid("getGridParam", "colNames"), f = {}, j = [];
+            g.empty();
+            b.each(k, function (b) {
+                f[this.name] = b;
+                this.hidedlg ? this.hidden || j.push(b) : g.append("<option value='" + b + "' " + (this.hidden ? "" : "selected='selected'") + ">" + jQuery.jgrid.stripHtml(p[b]) + "</option>")
+            });
+            var i = b.isFunction(a.dlog_opts) ? a.dlog_opts.call(c, a) : a.dlog_opts;
+            e(a.dlog, d, i);
+            i = b.isFunction(a.msel_opts) ? a.msel_opts.call(c,
+                a) : a.msel_opts;
+            e(a.msel, g, i)
+        }
+    }, sortableRows: function (a) {
+        return this.each(function () {
+            var e = this;
+            if (e.grid && !e.p.treeGrid && b.fn.sortable) {
+                a = b.extend({cursor: "move", axis: "y", items: ".jqgrow"}, a || {});
+                if (a.start && b.isFunction(a.start)) {
+                    a._start_ = a.start;
+                    delete a.start
+                } else a._start_ = false;
+                if (a.update && b.isFunction(a.update)) {
+                    a._update_ = a.update;
+                    delete a.update
+                } else a._update_ = false;
+                a.start = function (c, d) {
+                    b(d.item).css("border-width", "0px");
+                    b("td", d.item).each(function (b) {
+                        this.style.width = e.grid.cols[b].style.width
+                    });
+                    if (e.p.subGrid) {
+                        var g = b(d.item).attr("id");
+                        try {
+                            b(e).jqGrid("collapseSubGridRow", g)
+                        } catch (k) {
+                        }
+                    }
+                    a._start_ && a._start_.apply(this, [c, d])
+                };
+                a.update = function (c, d) {
+                    b(d.item).css("border-width", "");
+                    e.p.rownumbers === true && b("td.jqgrid-rownum", e.rows).each(function (a) {
+                        b(this).html(a + 1 + (parseInt(e.p.page, 10) - 1) * parseInt(e.p.rowNum, 10))
+                    });
+                    a._update_ && a._update_.apply(this, [c, d])
+                };
+                b("tbody:first", e).sortable(a);
+                b("tbody:first", e).disableSelection()
+            }
+        })
+    }, gridDnD: function (a) {
+        return this.each(function () {
+            function e() {
+                var a =
+                    b.data(c, "dnd");
+                b("tr.jqgrow:not(.ui-draggable)", c).draggable(b.isFunction(a.drag) ? a.drag.call(b(c), a) : a.drag)
+            }
+
+            var c = this;
+            if (c.grid && !c.p.treeGrid && b.fn.draggable && b.fn.droppable) {
+                b("#jqgrid_dnd").html() === null && b("body").append("<table id='jqgrid_dnd' class='ui-jqgrid-dnd'></table>");
+                if (typeof a == "string" && a == "updateDnD" && c.p.jqgdnd === true)e(); else {
+                    a = b.extend({drag: function (a) {
+                        return b.extend({start: function (d, e) {
+                            if (c.p.subGrid) {
+                                var f = b(e.helper).attr("id");
+                                try {
+                                    b(c).jqGrid("collapseSubGridRow", f)
+                                } catch (j) {
+                                }
+                            }
+                            for (f =
+                                     0; f < b.data(c, "dnd").connectWith.length; f++)b(b.data(c, "dnd").connectWith[f]).jqGrid("getGridParam", "reccount") == "0" && b(b.data(c, "dnd").connectWith[f]).jqGrid("addRowData", "jqg_empty_row", {});
+                            e.helper.addClass("ui-state-highlight");
+                            b("td", e.helper).each(function (b) {
+                                this.style.width = c.grid.headers[b].width + "px"
+                            });
+                            a.onstart && b.isFunction(a.onstart) && a.onstart.call(b(c), d, e)
+                        }, stop: function (d, e) {
+                            if (e.helper.dropped && !a.dragcopy) {
+                                var f = b(e.helper).attr("id");
+                                f === void 0 && (f = b(this).attr("id"));
+                                b(c).jqGrid("delRowData",
+                                    f)
+                            }
+                            for (f = 0; f < b.data(c, "dnd").connectWith.length; f++)b(b.data(c, "dnd").connectWith[f]).jqGrid("delRowData", "jqg_empty_row");
+                            a.onstop && b.isFunction(a.onstop) && a.onstop.call(b(c), d, e)
+                        }}, a.drag_opts || {})
+                    }, drop: function (a) {
+                        return b.extend({accept: function (a) {
+                            if (!b(a).hasClass("jqgrow"))return a;
+                            a = b(a).closest("table.ui-jqgrid-btable");
+                            if (a.length > 0 && b.data(a[0], "dnd") !== void 0) {
+                                a = b.data(a[0], "dnd").connectWith;
+                                return b.inArray("#" + b.jgrid.jqID(this.id), a) != -1 ? true : false
+                            }
+                            return false
+                        }, drop: function (d, e) {
+                            if (b(e.draggable).hasClass("jqgrow")) {
+                                var f =
+                                    b(e.draggable).attr("id"), f = e.draggable.parent().parent().jqGrid("getRowData", f);
+                                if (!a.dropbyname) {
+                                    var j = 0, i = {}, h, n = b("#" + b.jgrid.jqID(this.id)).jqGrid("getGridParam", "colModel");
+                                    try {
+                                        for (var o in f) {
+                                            h = n[j].name;
+                                            h == "cb" || (h == "rn" || h == "subgrid") || f.hasOwnProperty(o) && n[j] && (i[h] = f[o]);
+                                            j++
+                                        }
+                                        f = i
+                                    } catch (m) {
+                                    }
+                                }
+                                e.helper.dropped = true;
+                                if (a.beforedrop && b.isFunction(a.beforedrop)) {
+                                    h = a.beforedrop.call(this, d, e, f, b("#" + b.jgrid.jqID(c.p.id)), b(this));
+                                    typeof h != "undefined" && (h !== null && typeof h == "object") && (f = h)
+                                }
+                                if (e.helper.dropped) {
+                                    var l;
+                                    if (a.autoid)if (b.isFunction(a.autoid))l = a.autoid.call(this, f); else {
+                                        l = Math.ceil(Math.random() * 1E3);
+                                        l = a.autoidprefix + l
+                                    }
+                                    b("#" + b.jgrid.jqID(this.id)).jqGrid("addRowData", l, f, a.droppos)
+                                }
+                                a.ondrop && b.isFunction(a.ondrop) && a.ondrop.call(this, d, e, f)
+                            }
+                        }}, a.drop_opts || {})
+                    }, onstart: null, onstop: null, beforedrop: null, ondrop: null, drop_opts: {activeClass: "ui-state-active", hoverClass: "ui-state-hover"}, drag_opts: {revert: "invalid", helper: "clone", cursor: "move", appendTo: "#jqgrid_dnd", zIndex: 5E3}, dragcopy: false, dropbyname: false,
+                        droppos: "first", autoid: true, autoidprefix: "dnd_"}, a || {});
+                    if (a.connectWith) {
+                        a.connectWith = a.connectWith.split(",");
+                        a.connectWith = b.map(a.connectWith, function (a) {
+                            return b.trim(a)
+                        });
+                        b.data(c, "dnd", a);
+                        c.p.reccount != "0" && !c.p.jqgdnd && e();
+                        c.p.jqgdnd = true;
+                        for (var d = 0; d < a.connectWith.length; d++)b(a.connectWith[d]).droppable(b.isFunction(a.drop) ? a.drop.call(b(c), a) : a.drop)
+                    }
+                }
+            }
+        })
+    }, gridResize: function (a) {
+        return this.each(function () {
+            var e = this, c = b.jgrid.jqID(e.p.id);
+            if (e.grid && b.fn.resizable) {
+                a = b.extend({}, a ||
+                {});
+                if (a.alsoResize) {
+                    a._alsoResize_ = a.alsoResize;
+                    delete a.alsoResize
+                } else a._alsoResize_ = false;
+                if (a.stop && b.isFunction(a.stop)) {
+                    a._stop_ = a.stop;
+                    delete a.stop
+                } else a._stop_ = false;
+                a.stop = function (d, g) {
+                    b(e).jqGrid("setGridParam", {height: b("#gview_" + c + " .ui-jqgrid-bdiv").height()});
+                    b(e).jqGrid("setGridWidth", g.size.width, a.shrinkToFit);
+                    a._stop_ && a._stop_.call(e, d, g)
+                };
+                a.alsoResize = a._alsoResize_ ? eval("(" + ("{'#gview_" + c + " .ui-jqgrid-bdiv':true,'" + a._alsoResize_ + "':true}") + ")") : b(".ui-jqgrid-bdiv", "#gview_" +
+                    c);
+                delete a._alsoResize_;
+                b("#gbox_" + c).resizable(a)
+            }
+        })
+    }})
+})(jQuery);
diff --git a/media/js/lib/jquery.jqGrid.src.js b/media/js/lib/jquery.jqGrid.src.js
index 1bd9881..a73e214 100644
--- a/media/js/lib/jquery.jqGrid.src.js
+++ b/media/js/lib/jquery.jqGrid.src.js
@@ -13,11453 +13,13419 @@
 /*global document, window, jQuery, DOMParser, ActiveXObject, $, alert */
 
 (function ($) {
-"use strict";
-$.jgrid = $.jgrid || {};
-$.extend($.jgrid,{
-	version : "4.4.0",
-	htmlDecode : function(value){
-		if(value && (value=='&nbsp;' || value=='&#160;' || (value.length===1 && value.charCodeAt(0)===160))) { return "";}
-		return !value ? value : String(value).replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"').replace(/&amp;/g, "&");
-	},
-	htmlEncode : function (value){
-		return !value ? value : String(value).replace(/&/g, "&amp;").replace(/\"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
-	},
-	format : function(format){ //jqgformat
-		var args = $.makeArray(arguments).slice(1);
-		if(format===undefined) { format = ""; }
-		return format.replace(/\{(\d+)\}/g, function(m, i){
-			return args[i];
-		});
-	},
-	getCellIndex : function (cell) {
-		var c = $(cell);
-		if (c.is('tr')) { return -1; }
-		c = (!c.is('td') && !c.is('th') ? c.closest("td,th") : c)[0];
-		if ($.browser.msie) { return $.inArray(c, c.parentNode.cells); }
-		return c.cellIndex;
-	},
-	stripHtml : function(v) {
-		v = v+"";
-		var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
-		if (v) {
-			v = v.replace(regexp,"");
-			return (v && v !== '&nbsp;' && v !== '&#160;') ? v.replace(/\"/g,"'") : "";
-		} else {
-			return v;
-		}
-	},
-	stripPref : function (pref, id) {
-		var obj = $.type( pref );
-		if( obj == "string" || obj =="number") {
-			pref =  String(pref);
-			id = pref !== "" ? String(id).replace(String(pref), "") : id;
-		}
-		return id;
-	},
-	stringToDoc : function (xmlString) {
-		var xmlDoc;
-		if(typeof xmlString !== 'string') { return xmlString; }
-		try	{
-			var parser = new DOMParser();
-			xmlDoc = parser.parseFromString(xmlString,"text/xml");
-		}
-		catch(e) {
-			xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
-			xmlDoc.async=false;
-			xmlDoc.loadXML(xmlString);
-		}
-		return (xmlDoc && xmlDoc.documentElement && xmlDoc.documentElement.tagName != 'parsererror') ? xmlDoc : null;
-	},
-	parse : function(jsonString) {
-		var js = jsonString;
-		if (js.substr(0,9) == "while(1);") { js = js.substr(9); }
-		if (js.substr(0,2) == "/*") { js = js.substr(2,js.length-4); }
-		if(!js) { js = "{}"; }
-		return ($.jgrid.useJSON===true && typeof (JSON) === 'object' && typeof (JSON.parse) === 'function') ?
-			JSON.parse(js) :
-			eval('(' + js + ')');
-	},
-	parseDate : function(format, date) {
-		var tsp = {m : 1, d : 1, y : 1970, h : 0, i : 0, s : 0, u:0},k,hl,dM, regdate = /[\\\/:_;.,\t\T\s-]/;
-		if(date && date !== null && date !== undefined){
-			date = $.trim(date);
-			date = date.split(regdate);
-			if ($.jgrid.formatter.date.masks[format] !== undefined) {
-				format = $.jgrid.formatter.date.masks[format];
-			}
-			format = format.split(regdate);
-			var dfmt  = $.jgrid.formatter.date.monthNames;
-			var afmt  = $.jgrid.formatter.date.AmPm;
-			var h12to24 = function(ampm, h){
-				if (ampm === 0){ if (h === 12) { h = 0;} }
-				else { if (h !== 12) { h += 12; } }
-				return h;
-			};
-			for(k=0,hl=format.length;k<hl;k++){
-				if(format[k] == 'M') {
-					dM = $.inArray(date[k],dfmt);
-					if(dM !== -1 && dM < 12){
-						date[k] = dM+1;
-						tsp.m = date[k];
-					}
-				}
-				if(format[k] == 'F') {
-					dM = $.inArray(date[k],dfmt);
-					if(dM !== -1 && dM > 11){
-						date[k] = dM+1-12;
-						tsp.m = date[k];
-					}
-				}
-				if(format[k] == 'a') {
-					dM = $.inArray(date[k],afmt);
-					if(dM !== -1 && dM < 2 && date[k] == afmt[dM]){
-						date[k] = dM;
-						tsp.h = h12to24(date[k], tsp.h);
-					}
-				}
-				if(format[k] == 'A') {
-					dM = $.inArray(date[k],afmt);
-					if(dM !== -1 && dM > 1 && date[k] == afmt[dM]){
-						date[k] = dM-2;
-						tsp.h = h12to24(date[k], tsp.h);
-					}
-				}
-				if(date[k] !== undefined) {
-					tsp[format[k].toLowerCase()] = parseInt(date[k],10);
-				}
-			}
-			tsp.m = parseInt(tsp.m,10)-1;
-			var ty = tsp.y;
-			if (ty >= 70 && ty <= 99) {tsp.y = 1900+tsp.y;}
-			else if (ty >=0 && ty <=69) {tsp.y= 2000+tsp.y;}
-			if(tsp.j !== undefined) { tsp.d = tsp.j; }
-			if(tsp.n !== undefined) { tsp.m = parseInt(tsp.n,10)-1; }
-		}
-		return new Date(tsp.y, tsp.m, tsp.d, tsp.h, tsp.i, tsp.s, tsp.u);
-	},
-	jqID : function(sid){
-		return String(sid).replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g,"\\$&");
-	},
-	guid : 1,
-	uidPref: 'jqg',
-	randId : function( prefix )	{
-		return (prefix? prefix: $.jgrid.uidPref) + ($.jgrid.guid++);
-	},
-	getAccessor : function(obj, expr) {
-		var ret,p,prm = [], i;
-		if( typeof expr === 'function') { return expr(obj); }
-		ret = obj[expr];
-		if(ret===undefined) {
-			try {
-				if ( typeof expr === 'string' ) {
-					prm = expr.split('.');
-				}
-				i = prm.length;
-				if( i ) {
-					ret = obj;
-					while (ret && i--) {
-						p = prm.shift();
-						ret = ret[p];
-					}
-				}
-			} catch (e) {}
-		}
-		return ret;
-	},
-	getXmlData: function (obj, expr, returnObj) {
-		var ret, m = typeof (expr) === 'string' ? expr.match(/^(.*)\[(\w+)\]$/) : null;
-		if (typeof (expr) === 'function') { return expr(obj); }
-		if (m && m[2]) {
-			// m[2] is the attribute selector
-			// m[1] is an optional element selector
-			// examples: "[id]", "rows[page]"
-			return m[1] ? $(m[1], obj).attr(m[2]) : $(obj).attr(m[2]);
-		} else {
-			ret = $(expr, obj);
-			if (returnObj) { return ret; }
-			//$(expr, obj).filter(':last'); // we use ':last' to be more compatible with old version of jqGrid
-			return ret.length > 0 ? $(ret).text() : undefined;
-		}
-	},
-	cellWidth : function () {
-		var $testDiv = $("<div class='ui-jqgrid' style='left:10000px'><table class='ui-jqgrid-btable' style='width:5px;'><tr class='jqgrow'><td style='width:5px;'></td></tr></table></div>"),
-		testCell = $testDiv.appendTo("body")
-			.find("td")
-			.width();
-		$testDiv.remove();
-		return testCell !== 5;
-	},
-	ajaxOptions: {},
-	from : function(source){
-		// Original Author Hugo Bonacci
-		// License MIT http://jlinq.codeplex.com/license
-		var QueryObject=function(d,q){
-		if(typeof(d)=="string"){
-			d=$.data(d);
-		}
-		var self=this,
-		_data=d,
-		_usecase=true,
-		_trim=false,
-		_query=q,
-		_stripNum = /[\$,%]/g,
-		_lastCommand=null,
-		_lastField=null,
-		_orDepth=0,
-		_negate=false,
-		_queuedOperator="",
-		_sorting=[],
-		_useProperties=true;
-		if(typeof(d)=="object"&&d.push) {
-			if(d.length>0){
-				if(typeof(d[0])!="object"){
-					_useProperties=false;
-				}else{
-					_useProperties=true;
-				}
-			}
-		}else{
-			throw "data provides is not an array";
-		}
-		this._hasData=function(){
-			return _data===null?false:_data.length===0?false:true;
-		};
-		this._getStr=function(s){
-			var phrase=[];
-			if(_trim){
-				phrase.push("jQuery.trim(");
-			}
-			phrase.push("String("+s+")");
-			if(_trim){
-				phrase.push(")");
-			}
-			if(!_usecase){
-				phrase.push(".toLowerCase()");
-			}
-			return phrase.join("");
-		};
-		this._strComp=function(val){
-			if(typeof(val)=="string"){
-				return".toString()";
-			}else{
-				return"";
-			}
-		};
-		this._group=function(f,u){
-			return({field:f.toString(),unique:u,items:[]});
-		};
-		this._toStr=function(phrase){
-			if(_trim){
-				phrase=$.trim(phrase);
-			}
-			phrase=phrase.toString().replace(/\\/g,'\\\\').replace(/\"/g,'\\"');
-			return _usecase ? phrase : phrase.toLowerCase();
-		};
-		this._funcLoop=function(func){
-			var results=[];
-			$.each(_data,function(i,v){
-				results.push(func(v));
-			});
-			return results;
-		};
-		this._append=function(s){
-			var i;
-			if(_query===null){
-				_query="";
-			} else {
-				_query+=_queuedOperator === "" ? " && " :_queuedOperator;
-			}
-			for (i=0;i<_orDepth;i++){
-				_query+="(";
-			}
-			if(_negate){
-				_query+="!";
-			}
-			_query+="("+s+")";
-			_negate=false;
-			_queuedOperator="";
-			_orDepth=0;
-		};
-		this._setCommand=function(f,c){
-			_lastCommand=f;
-			_lastField=c;
-		};
-		this._resetNegate=function(){
-			_negate=false;
-		};
-		this._repeatCommand=function(f,v){
-			if(_lastCommand===null){
-				return self;
-			}
-			if(f!==null&&v!==null){
-				return _lastCommand(f,v);
-			}
-			if(_lastField===null){
-				return _lastCommand(f);
-			}
-			if(!_useProperties){
-				return _lastCommand(f);
-			}
-			return _lastCommand(_lastField,f);
-		};
-		this._equals=function(a,b){
-			return(self._compare(a,b,1)===0);
-		};
-		this._compare=function(a,b,d){
-			var toString = Object.prototype.toString;
-			if( d === undefined) { d = 1; }
-			if(a===undefined) { a = null; }
-			if(b===undefined) { b = null; }
-			if(a===null && b===null){
-				return 0;
-			}
-			if(a===null&&b!==null){
-				return 1;
-			}
-			if(a!==null&&b===null){
-				return -1;
-			}
-			if (toString.call(a) === '[object Date]' && toString.call(b) === '[object Date]') {
-				if (a < b) { return -d; }
-				if (a > b) { return d; }
-				return 0;
-			}
-			if(!_usecase && typeof(a) !== "number" && typeof(b) !== "number" ) {
-				a=String(a).toLowerCase();
-				b=String(b).toLowerCase();
-			}
-			if(a<b){return -d;}
-			if(a>b){return d;}
-			return 0;
-		};
-		this._performSort=function(){
-			if(_sorting.length===0){return;}
-			_data=self._doSort(_data,0);
-		};
-		this._doSort=function(d,q){
-			var by=_sorting[q].by,
-			dir=_sorting[q].dir,
-			type = _sorting[q].type,
-			dfmt = _sorting[q].datefmt;
-			if(q==_sorting.length-1){
-				return self._getOrder(d, by, dir, type, dfmt);
-			}
-			q++;
-			var values=self._getGroup(d,by,dir,type,dfmt);
-			var results=[];
-			for(var i=0;i<values.length;i++){
-				var sorted=self._doSort(values[i].items,q);
-				for(var j=0;j<sorted.length;j++){
-					results.push(sorted[j]);
-				}
-			}
-			return results;
-		};
-		this._getOrder=function(data,by,dir,type, dfmt){
-			var sortData=[],_sortData=[], newDir = dir=="a" ? 1 : -1, i,ab,j,
-			findSortKey;
-
-			if(type === undefined ) { type = "text"; }
-			if (type == 'float' || type== 'number' || type== 'currency' || type== 'numeric') {
-				findSortKey = function($cell) {
-					var key = parseFloat( String($cell).replace(_stripNum, ''));
-					return isNaN(key) ? 0.00 : key;
-				};
-			} else if (type=='int' || type=='integer') {
-				findSortKey = function($cell) {
-					return $cell ? parseFloat(String($cell).replace(_stripNum, '')) : 0;
-				};
-			} else if(type == 'date' || type == 'datetime') {
-				findSortKey = function($cell) {
-					return $.jgrid.parseDate(dfmt,$cell).getTime();
-				};
-			} else if($.isFunction(type)) {
-				findSortKey = type;
-			} else {
-				findSortKey = function($cell) {
-					if(!$cell) {$cell ="";}
-					return $.trim(String($cell).toUpperCase());
-				};
-			}
-			$.each(data,function(i,v){
-				ab = by!=="" ? $.jgrid.getAccessor(v,by) : v;
-				if(ab === undefined) { ab = ""; }
-				ab = findSortKey(ab, v);
-				_sortData.push({ 'vSort': ab,'index':i});
-			});
-
-			_sortData.sort(function(a,b){
-				a = a.vSort;
-				b = b.vSort;
-				return self._compare(a,b,newDir);
-			});
-			j=0;
-			var nrec= data.length;
-			// overhead, but we do not change the original data.
-			while(j<nrec) {
-				i = _sortData[j].index;
-				sortData.push(data[i]);
-				j++;
-			}
-			return sortData;
-		};
-		this._getGroup=function(data,by,dir,type, dfmt){
-			var results=[],
-			group=null,
-			last=null, val;
-			$.each(self._getOrder(data,by,dir,type, dfmt),function(i,v){
-				val = $.jgrid.getAccessor(v, by);
-				if(val === undefined) { val = ""; }
-				if(!self._equals(last,val)){
-					last=val;
-					if(group !== null){
-						results.push(group);
-					}
-					group=self._group(by,val);
-				}
-				group.items.push(v);
-			});
-			if(group !== null){
-				results.push(group);
-			}
-			return results;
-		};
-		this.ignoreCase=function(){
-			_usecase=false;
-			return self;
-		};
-		this.useCase=function(){
-			_usecase=true;
-			return self;
-		};
-		this.trim=function(){
-			_trim=true;
-			return self;
-		};
-		this.noTrim=function(){
-			_trim=false;
-			return self;
-		};
-		this.execute=function(){
-			var match=_query, results=[];
-			if(match === null){
-				return self;
-			}
-			$.each(_data,function(){
-				if(eval(match)){results.push(this);}
-			});
-			_data=results;
-			return self;
-		};
-		this.data=function(){
-			return _data;
-		};
-		this.select=function(f){
-			self._performSort();
-			if(!self._hasData()){ return[]; }
-			self.execute();
-			if($.isFunction(f)){
-				var results=[];
-				$.each(_data,function(i,v){
-					results.push(f(v));
-				});
-				return results;
-			}
-			return _data;
-		};
-		this.hasMatch=function(){
-			if(!self._hasData()) { return false; }
-			self.execute();
-			return _data.length>0;
-		};
-		this.andNot=function(f,v,x){
-			_negate=!_negate;
-			return self.and(f,v,x);
-		};
-		this.orNot=function(f,v,x){
-			_negate=!_negate;
-			return self.or(f,v,x);
-		};
-		this.not=function(f,v,x){
-			return self.andNot(f,v,x);
-		};
-		this.and=function(f,v,x){
-			_queuedOperator=" && ";
-			if(f===undefined){
-				return self;
-			}
-			return self._repeatCommand(f,v,x);
-		};
-		this.or=function(f,v,x){
-			_queuedOperator=" || ";
-			if(f===undefined) { return self; }
-			return self._repeatCommand(f,v,x);
-		};
-		this.orBegin=function(){
-			_orDepth++;
-			return self;
-		};
-		this.orEnd=function(){
-			if (_query !== null){
-				_query+=")";
-			}
-			return self;
-		};
-		this.isNot=function(f){
-			_negate=!_negate;
-			return self.is(f);
-		};
-		this.is=function(f){
-			self._append('this.'+f);
-			self._resetNegate();
-			return self;
-		};
-		this._compareValues=function(func,f,v,how,t){
-			var fld;
-			if(_useProperties){
-				fld='jQuery.jgrid.getAccessor(this,\''+f+'\')';
-			}else{
-				fld='this';
-			}
-			if(v===undefined) { v = null; }
-			//var val=v===null?f:v,
-			var val =v,
-			swst = t.stype === undefined ? "text" : t.stype;
-			if(v !== null) {
-			switch(swst) {
-				case 'int':
-				case 'integer':
-					val = (isNaN(Number(val)) || val==="") ? '0' : val; // To be fixed with more inteligent code
-					fld = 'parseInt('+fld+',10)';
-					val = 'parseInt('+val+',10)';
-					break;
-				case 'float':
-				case 'number':
-				case 'numeric':
-					val = String(val).replace(_stripNum, '');
-					val = (isNaN(Number(val)) || val==="") ? '0' : val; // To be fixed with more inteligent code
-					fld = 'parseFloat('+fld+')';
-					val = 'parseFloat('+val+')';
-					break;
-				case 'date':
-				case 'datetime':
-					val = String($.jgrid.parseDate(t.newfmt || 'Y-m-d',val).getTime());
-					fld = 'jQuery.jgrid.parseDate("'+t.srcfmt+'",'+fld+').getTime()';
-					break;
-				default :
-					fld=self._getStr(fld);
-					val=self._getStr('"'+self._toStr(val)+'"');
-			}
-			}
-			self._append(fld+' '+how+' '+val);
-			self._setCommand(func,f);
-			self._resetNegate();
-			return self;
-		};
-		this.equals=function(f,v,t){
-			return self._compareValues(self.equals,f,v,"==",t);
-		};
-		this.notEquals=function(f,v,t){
-			return self._compareValues(self.equals,f,v,"!==",t);
-		};
-		this.isNull = function(f,v,t){
-			return self._compareValues(self.equals,f,null,"===",t);
-		};
-		this.greater=function(f,v,t){
-			return self._compareValues(self.greater,f,v,">",t);
-		};
-		this.less=function(f,v,t){
-			return self._compareValues(self.less,f,v,"<",t);
-		};
-		this.greaterOrEquals=function(f,v,t){
-			return self._compareValues(self.greaterOrEquals,f,v,">=",t);
-		};
-		this.lessOrEquals=function(f,v,t){
-			return self._compareValues(self.lessOrEquals,f,v,"<=",t);
-		};
-		this.startsWith=function(f,v){
-			var val = (v===undefined || v===null) ? f: v,
-			length=_trim ? $.trim(val.toString()).length : val.toString().length;
-			if(_useProperties){
-				self._append(self._getStr('jQuery.jgrid.getAccessor(this,\''+f+'\')')+'.substr(0,'+length+') == '+self._getStr('"'+self._toStr(v)+'"'));
-			}else{
-				length=_trim?$.trim(v.toString()).length:v.toString().length;
-				self._append(self._getStr('this')+'.substr(0,'+length+') == '+self._getStr('"'+self._toStr(f)+'"'));
-			}
-			self._setCommand(self.startsWith,f);
-			self._resetNegate();
-			return self;
-		};
-		this.endsWith=function(f,v){
-			var val = (v===undefined || v===null) ? f: v,
-			length=_trim ? $.trim(val.toString()).length:val.toString().length;
-			if(_useProperties){
-				self._append(self._getStr('jQuery.jgrid.getAccessor(this,\''+f+'\')')+'.substr('+self._getStr('jQuery.jgrid.getAccessor(this,\''+f+'\')')+'.length-'+length+','+length+') == "'+self._toStr(v)+'"');
-			} else {
-				self._append(self._getStr('this')+'.substr('+self._getStr('this')+'.length-"'+self._toStr(f)+'".length,"'+self._toStr(f)+'".length) == "'+self._toStr(f)+'"');
-			}
-			self._setCommand(self.endsWith,f);self._resetNegate();
-			return self;
-		};
-		this.contains=function(f,v){
-			if(_useProperties){
-				self._append(self._getStr('jQuery.jgrid.getAccessor(this,\''+f+'\')')+'.indexOf("'+self._toStr(v)+'",0) > -1');
-			}else{
-				self._append(self._getStr('this')+'.indexOf("'+self._toStr(f)+'",0) > -1');
-			}
-			self._setCommand(self.contains,f);
-			self._resetNegate();
-			return self;
-		};
-		this.groupBy=function(by,dir,type, datefmt){
-			if(!self._hasData()){
-				return null;
-			}
-			return self._getGroup(_data,by,dir,type, datefmt);
-		};
-		this.orderBy=function(by,dir,stype, dfmt){
-			dir =  dir === undefined || dir === null ? "a" :$.trim(dir.toString().toLowerCase());
-			if(stype === null || stype === undefined) { stype = "text"; }
-			if(dfmt === null || dfmt === undefined) { dfmt = "Y-m-d"; }
-			if(dir=="desc"||dir=="descending"){dir="d";}
-			if(dir=="asc"||dir=="ascending"){dir="a";}
-			_sorting.push({by:by,dir:dir,type:stype, datefmt: dfmt});
-			return self;
-		};
-		return self;
-		};
-	return new QueryObject(source,null);
-	},
-	extend : function(methods) {
-		$.extend($.fn.jqGrid,methods);
-		if (!this.no_legacy_api) {
-			$.fn.extend(methods);
-		}
-	}
-});
-
-$.fn.jqGrid = function( pin ) {
-	if (typeof pin == 'string') {
-		//var fn = $.fn.jqGrid[pin];
-		var fn = $.jgrid.getAccessor($.fn.jqGrid,pin);
-		if (!fn) {
-			throw ("jqGrid - No such method: " + pin);
-		}
-		var args = $.makeArray(arguments).slice(1);
-		return fn.apply(this,args);
-	}
-	return this.each( function() {
-		if(this.grid) {return;}
-
-		var p = $.extend(true,{
-			url: "",
-			height: 150,
-			page: 1,
-			rowNum: 20,
-			rowTotal : null,
-			records: 0,
-			pager: "",
-			pgbuttons: true,
-			pginput: true,
-			colModel: [],
-			rowList: [],
-			colNames: [],
-			sortorder: "asc",
-			sortname: "",
-			datatype: "xml",
-			mtype: "GET",
-			altRows: false,
-			selarrrow: [],
-			savedRow: [],
-			shrinkToFit: true,
-			xmlReader: {},
-			jsonReader: {},
-			subGrid: false,
-			subGridModel :[],
-			reccount: 0,
-			lastpage: 0,
-			lastsort: 0,
-			selrow: null,
-			beforeSelectRow: null,
-			onSelectRow: null,
-			onSortCol: null,
-			ondblClickRow: null,
-			onRightClickRow: null,
-			onPaging: null,
-			onSelectAll: null,
-			loadComplete: null,
-			gridComplete: null,
-			loadError: null,
-			loadBeforeSend: null,
-			afterInsertRow: null,
-			beforeRequest: null,
-			beforeProcessing : null,
-			onHeaderClick: null,
-			viewrecords: false,
-			loadonce: false,
-			multiselect: false,
-			multikey: false,
-			editurl: null,
-			search: false,
-			caption: "",
-			hidegrid: true,
-			hiddengrid: false,
-			postData: {},
-			userData: {},
-			treeGrid : false,
-			treeGridModel : 'nested',
-			treeReader : {},
-			treeANode : -1,
-			ExpandColumn: null,
-			tree_root_level : 0,
-			prmNames: {page:"page",rows:"rows", sort: "sidx",order: "sord", search:"_search", nd:"nd", id:"id",oper:"oper",editoper:"edit",addoper:"add",deloper:"del", subgridid:"id", npage: null, totalrows:"totalrows"},
-			forceFit : false,
-			gridstate : "visible",
-			cellEdit: false,
-			cellsubmit: "remote",
-			nv:0,
-			loadui: "enable",
-			toolbar: [false,""],
-			scroll: false,
-			multiboxonly : false,
-			deselectAfterSort : true,
-			scrollrows : false,
-			autowidth: false,
-			scrollOffset :18,
-			cellLayout: 5,
-			subGridWidth: 20,
-			multiselectWidth: 20,
-			gridview: false,
-			rownumWidth: 25,
-			rownumbers : false,
-			pagerpos: 'center',
-			recordpos: 'right',
-			footerrow : false,
-			userDataOnFooter : false,
-			hoverrows : true,
-			altclass : 'ui-priority-secondary',
-			viewsortcols : [false,'vertical',true],
-			resizeclass : '',
-			autoencode : false,
-			remapColumns : [],
-			ajaxGridOptions :{},
-			direction : "ltr",
-			toppager: false,
-			headertitles: false,
-			scrollTimeout: 40,
-			data : [],
-			_index : {},
-			grouping : false,
-			groupingView : {groupField:[],groupOrder:[], groupText:[],groupColumnShow:[],groupSummary:[], showSummaryOnHide: false, sortitems:[], sortnames:[], summary:[],summaryval:[], plusicon: 'ui-icon-circlesmall-plus', minusicon: 'ui-icon-circlesmall-minus'},
-			ignoreCase : false,
-			cmTemplate : {},
-			idPrefix : ""
-		}, $.jgrid.defaults, pin || {});
-		var ts= this, grid={
-			headers:[],
-			cols:[],
-			footers: [],
-			dragStart: function(i,x,y) {
-				this.resizing = { idx: i, startX: x.clientX, sOL : y[0]};
-				this.hDiv.style.cursor = "col-resize";
-				this.curGbox = $("#rs_m"+$.jgrid.jqID(p.id),"#gbox_"+$.jgrid.jqID(p.id));
-				this.curGbox.css({display:"block",left:y[0],top:y[1],height:y[2]});
-				$(ts).triggerHandler("jqGridResizeStart", [x, i]);
-				if($.isFunction(p.resizeStart)) { p.resizeStart.call(this,x,i); }
-				document.onselectstart=function(){return false;};
-			},
-			dragMove: function(x) {
-				if(this.resizing) {
-					var diff = x.clientX-this.resizing.startX,
-					h = this.headers[this.resizing.idx],
-					newWidth = p.direction === "ltr" ? h.width + diff : h.width - diff, hn, nWn;
-					if(newWidth > 33) {
-						this.curGbox.css({left:this.resizing.sOL+diff});
-						if(p.forceFit===true ){
-							hn = this.headers[this.resizing.idx+p.nv];
-							nWn = p.direction === "ltr" ? hn.width - diff : hn.width + diff;
-							if(nWn >33) {
-								h.newWidth = newWidth;
-								hn.newWidth = nWn;
-							}
-						} else {
-							this.newWidth = p.direction === "ltr" ? p.tblwidth+diff : p.tblwidth-diff;
-							h.newWidth = newWidth;
-						}
-					}
-				}
-			},
-			dragEnd: function() {
-				this.hDiv.style.cursor = "default";
-				if(this.resizing) {
-					var idx = this.resizing.idx,
-					nw = this.headers[idx].newWidth || this.headers[idx].width;
-					nw = parseInt(nw,10);
-					this.resizing = false;
-					$("#rs_m"+$.jgrid.jqID(p.id)).css("display","none");
-					p.colModel[idx].width = nw;
-					this.headers[idx].width = nw;
-					this.headers[idx].el.style.width = nw + "px";
-					this.cols[idx].style.width = nw+"px";
-					if(this.footers.length>0) {this.footers[idx].style.width = nw+"px";}
-					if(p.forceFit===true){
-						nw = this.headers[idx+p.nv].newWidth || this.headers[idx+p.nv].width;
-						this.headers[idx+p.nv].width = nw;
-						this.headers[idx+p.nv].el.style.width = nw + "px";
-						this.cols[idx+p.nv].style.width = nw+"px";
-						if(this.footers.length>0) {this.footers[idx+p.nv].style.width = nw+"px";}
-						p.colModel[idx+p.nv].width = nw;
-					} else {
-						p.tblwidth = this.newWidth || p.tblwidth;
-						$('table:first',this.bDiv).css("width",p.tblwidth+"px");
-						$('table:first',this.hDiv).css("width",p.tblwidth+"px");
-						this.hDiv.scrollLeft = this.bDiv.scrollLeft;
-						if(p.footerrow) {
-							$('table:first',this.sDiv).css("width",p.tblwidth+"px");
-							this.sDiv.scrollLeft = this.bDiv.scrollLeft;
-						}
-					}
-					$(ts).triggerHandler("jqGridResizeStop", [nw, idx]);
-					if($.isFunction(p.resizeStop)) { p.resizeStop.call(this,nw,idx); }
-				}
-				this.curGbox = null;
-				document.onselectstart=function(){return true;};
-			},
-			populateVisible: function() {
-				if (grid.timer) { clearTimeout(grid.timer); }
-				grid.timer = null;
-				var dh = $(grid.bDiv).height();
-				if (!dh) { return; }
-				var table = $("table:first", grid.bDiv);
-				var rows, rh;
-				if(table[0].rows.length) {
-					try {
-						rows = table[0].rows[1];
-						rh = rows ? $(rows).outerHeight() || grid.prevRowHeight : grid.prevRowHeight;
-					} catch (pv) {
-						rh = grid.prevRowHeight;
-					}
-				}
-				if (!rh) { return; }
-				grid.prevRowHeight = rh;
-				var rn = p.rowNum;
-				var scrollTop = grid.scrollTop = grid.bDiv.scrollTop;
-				var ttop = Math.round(table.position().top) - scrollTop;
-				var tbot = ttop + table.height();
-				var div = rh * rn;
-				var page, npage, empty;
-				if ( tbot < dh && ttop <= 0 &&
-					(p.lastpage===undefined||parseInt((tbot + scrollTop + div - 1) / div,10) <= p.lastpage))
-				{
-					npage = parseInt((dh - tbot + div - 1) / div,10);
-					if (tbot >= 0 || npage < 2 || p.scroll === true) {
-						page = Math.round((tbot + scrollTop) / div) + 1;
-						ttop = -1;
-					} else {
-						ttop = 1;
-					}
-				}
-				if (ttop > 0) {
-					page = parseInt(scrollTop / div,10) + 1;
-					npage = parseInt((scrollTop + dh) / div,10) + 2 - page;
-					empty = true;
-				}
-				if (npage) {
-					if (p.lastpage && page > p.lastpage || p.lastpage==1 || (page === p.page && page===p.lastpage) ) {
-						return;
-					}
-					if (grid.hDiv.loading) {
-						grid.timer = setTimeout(grid.populateVisible, p.scrollTimeout);
-					} else {
-						p.page = page;
-						if (empty) {
-							grid.selectionPreserver(table[0]);
-							grid.emptyRows.call(table[0], false, false);
-						}
-						grid.populate(npage);
-					}
-				}
-			},
-			scrollGrid: function( e ) {
-				if(p.scroll) {
-					var scrollTop = grid.bDiv.scrollTop;
-					if(grid.scrollTop === undefined) { grid.scrollTop = 0; }
-					if (scrollTop != grid.scrollTop) {
-						grid.scrollTop = scrollTop;
-						if (grid.timer) { clearTimeout(grid.timer); }
-						grid.timer = setTimeout(grid.populateVisible, p.scrollTimeout);
-					}
-				}
-				grid.hDiv.scrollLeft = grid.bDiv.scrollLeft;
-				if(p.footerrow) {
-					grid.sDiv.scrollLeft = grid.bDiv.scrollLeft;
-				}
-				if( e ) { e.stopPropagation(); }
-			},
-			selectionPreserver : function(ts) {
-				var p = ts.p,
-				sr = p.selrow, sra = p.selarrrow ? $.makeArray(p.selarrrow) : null,
-				left = ts.grid.bDiv.scrollLeft,
-				restoreSelection = function() {
-					var i;
-					p.selrow = null;
-					p.selarrrow = [];
-					if(p.multiselect && sra && sra.length>0) {
-						for(i=0;i<sra.length;i++){
-							if (sra[i] != sr) {
-								$(ts).jqGrid("setSelection",sra[i],false, null);
-							}
-						}
-					}
-					if (sr) {
-						$(ts).jqGrid("setSelection",sr,false,null);
-					}
-					ts.grid.bDiv.scrollLeft = left;
-					$(ts).unbind('.selectionPreserver', restoreSelection);
-				};
-				$(ts).bind('jqGridGridComplete.selectionPreserver', restoreSelection);
-			}
-		};
-		if(this.tagName.toUpperCase()!='TABLE') {
-			alert("Element is not a table");
-			return;
-		}
-		if(document.documentMode !== undefined ) { // IE only
-			if(document.documentMode <= 5) {
-				alert("Grid can not be used in this ('quirks') mode!");
-				return;
-			}
-		}
-		$(this).empty().attr("tabindex","1");
-		this.p = p ;
-		this.p.useProp = !!$.fn.prop;
-		var i, dir;
-		if(this.p.colNames.length === 0) {
-			for (i=0;i<this.p.colModel.length;i++){
-				this.p.colNames[i] = this.p.colModel[i].label || this.p.colModel[i].name;
-			}
-		}
-		if( this.p.colNames.length !== this.p.colModel.length ) {
-			alert($.jgrid.errors.model);
-			return;
-		}
-		var gv = $("<div class='ui-jqgrid-view'></div>"), ii,
-		isMSIE = $.browser.msie ? true:false;
-		ts.p.direction = $.trim(ts.p.direction.toLowerCase());
-		if($.inArray(ts.p.direction,["ltr","rtl"]) == -1) { ts.p.direction = "ltr"; }
-		dir = ts.p.direction;
-
-		$(gv).insertBefore(this);
-		$(this).appendTo(gv).removeClass("scroll");
-		var eg = $("<div class='ui-jqgrid ui-widget ui-widget-content ui-corner-all'></div>");
-		$(eg).insertBefore(gv).attr({"id" : "gbox_"+this.id,"dir":dir});
-		$(gv).appendTo(eg).attr("id","gview_"+this.id);
-		if (isMSIE && $.browser.version <= 6) {
-			ii = '<iframe style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=\'0\');" src="javascript:false;"></iframe>';
-		} else { ii="";}
-		$("<div class='ui-widget-overlay jqgrid-overlay' id='lui_"+this.id+"'></div>").append(ii).insertBefore(gv);
-		$("<div class='loading ui-state-default ui-state-active' id='load_"+this.id+"'>"+this.p.loadtext+"</div>").insertBefore(gv);
-		$(this).attr({cellspacing:"0",cellpadding:"0",border:"0","role":"grid","aria-multiselectable":!!this.p.multiselect,"aria-labelledby":"gbox_"+this.id});
-		var sortkeys = ["shiftKey","altKey","ctrlKey"],
-		intNum = function(val,defval) {
-			val = parseInt(val,10);
-			if (isNaN(val)) { return defval ? defval : 0;}
-			else {return val;}
-		},
-		formatCol = function (pos, rowInd, tv, rawObject, rowId, rdata){
-			var cm = ts.p.colModel[pos],
-			ral = cm.align, result="style=\"", clas = cm.classes, nm = cm.name, celp, acp=[];
-			if(ral) { result += "text-align:"+ral+";"; }
-			if(cm.hidden===true) { result += "display:none;"; }
-			if(rowInd===0) {
-				result += "width: "+grid.headers[pos].width+"px;";
-			} else if (cm.cellattr && $.isFunction(cm.cellattr))
-			{
-				celp = cm.cellattr.call(ts, rowId, tv, rawObject, cm, rdata);
-				if(celp && typeof(celp) === "string") {
-					celp = celp.replace(/style/i,'style').replace(/title/i,'title');
-					if(celp.indexOf('title') > -1) { cm.title=false;}
-					if(celp.indexOf('class') > -1) { clas = undefined;}
-					acp = celp.split("style");
-					if(acp.length === 2 ) {
-						acp[1] =  $.trim(acp[1].replace("=",""));
-						if(acp[1].indexOf("'") === 0 || acp[1].indexOf('"') === 0) {
-							acp[1] = acp[1].substring(1);
-						}
-						result += acp[1].replace(/'/gi,'"');
-					} else {
-						result += "\"";
-					}
-				}
-			}
-			if(!acp.length) { acp[0] = ""; result += "\"";}
-			result += (clas !== undefined ? (" class=\""+clas+"\"") :"") + ((cm.title && tv) ? (" title=\""+$.jgrid.stripHtml(tv)+"\"") :"");
-			result += " aria-describedby=\""+ts.p.id+"_"+nm+"\"";
-			return result + acp[0];
-		},
-		cellVal =  function (val) {
-			return val === undefined || val === null || val === "" ? "&#160;" : (ts.p.autoencode ? $.jgrid.htmlEncode(val) : val+"");
-		},
-		formatter = function (rowId, cellval , colpos, rwdat, _act){
-			var cm = ts.p.colModel[colpos],v;
-			if(typeof cm.formatter !== 'undefined') {
-				var opts= {rowId: rowId, colModel:cm, gid:ts.p.id, pos:colpos };
-				if($.isFunction( cm.formatter ) ) {
-					v = cm.formatter.call(ts,cellval,opts,rwdat,_act);
-				} else if($.fmatter){
-					v = $.fn.fmatter.call(ts,cm.formatter,cellval,opts,rwdat,_act);
-				} else {
-					v = cellVal(cellval);
-				}
-			} else {
-				v = cellVal(cellval);
-			}
-			return v;
-		},
-		addCell = function(rowId,cell,pos,irow, srvr) {
-			var v,prp;
-			v = formatter(rowId,cell,pos,srvr,'add');
-			prp = formatCol( pos,irow, v, srvr, rowId, true);
-			return "<td role=\"gridcell\" "+prp+">"+v+"</td>";
-		},
-		addMulti = function(rowid,pos,irow){
-			var	v = "<input role=\"checkbox\" type=\"checkbox\""+" id=\"jqg_"+ts.p.id+"_"+rowid+"\" class=\"cbox\" name=\"jqg_"+ts.p.id+"_"+rowid+"\"/>",
-			prp = formatCol( pos,irow,'',null, rowid, true);
-			return "<td role=\"gridcell\" "+prp+">"+v+"</td>";
-		},
-		addRowNum = function (pos,irow,pG,rN) {
-			var v =  (parseInt(pG,10)-1)*parseInt(rN,10)+1+irow,
-			prp = formatCol( pos,irow,v, null, irow, true);
-			return "<td role=\"gridcell\" class=\"ui-state-default jqgrid-rownum\" "+prp+">"+v+"</td>";
-		},
-		reader = function (datatype) {
-			var field, f=[], j=0, i;
-			for(i =0; i<ts.p.colModel.length; i++){
-				field = ts.p.colModel[i];
-				if (field.name !== 'cb' && field.name !=='subgrid' && field.name !=='rn') {
-					f[j]= datatype == "local" ?
-					field.name :
-					( (datatype=="xml" || datatype === "xmlstring") ? field.xmlmap || field.name : field.jsonmap || field.name );
-					j++;
-				}
-			}
-			return f;
-		},
-		orderedCols = function (offset) {
-			var order = ts.p.remapColumns;
-			if (!order || !order.length) {
-				order = $.map(ts.p.colModel, function(v,i) { return i; });
-			}
-			if (offset) {
-				order = $.map(order, function(v) { return v<offset?null:v-offset; });
-			}
-			return order;
-		},
-		emptyRows = function (scroll, locdata) {
-			var firstrow;
-			if (this.p.deepempty) {
-				$(this.rows).slice(1).remove();
-			} else {
-				firstrow = this.rows.length > 0 ? this.rows[0] : null;
-				$(this.firstChild).empty().append(firstrow);
-			}
-			if (scroll && this.p.scroll) {
-				$(this.grid.bDiv.firstChild).css({height: "auto"});
-				$(this.grid.bDiv.firstChild.firstChild).css({height: 0, display: "none"});
-				if (this.grid.bDiv.scrollTop !== 0) {
-					this.grid.bDiv.scrollTop = 0;
-				}
-			}
-			if(locdata === true && this.p.treeGrid) {
-				this.p.data = []; this.p._index = {};
-			}
-		},
-		refreshIndex = function() {
-			var datalen = ts.p.data.length, idname, i, val,
-			ni = ts.p.rownumbers===true ? 1 :0,
-			gi = ts.p.multiselect ===true ? 1 :0,
-			si = ts.p.subGrid===true ? 1 :0;
-
-			if(ts.p.keyIndex === false || ts.p.loadonce === true) {
-				idname = ts.p.localReader.id;
-			} else {
-				idname = ts.p.colModel[ts.p.keyIndex+gi+si+ni].name;
-			}
-			for(i =0;i < datalen; i++) {
-				val = $.jgrid.getAccessor(ts.p.data[i],idname);
-				ts.p._index[val] = i;
-			}
-		},
-		constructTr = function(id, hide, altClass, rd, cur) {
-			var tabindex = '-1', restAttr = '', attrName, style = hide ? 'display:none;' : '',
-				classes = 'ui-widget-content jqgrow ui-row-' + ts.p.direction + altClass,
-				rowAttrObj = $.isFunction(ts.p.rowattr) ? ts.p.rowattr.call(ts, rd, cur) : {};
-			if(!$.isEmptyObject( rowAttrObj )) {
-				if (rowAttrObj.hasOwnProperty("id")) {
-					id = rowAttrObj.id;
-					delete rowAttrObj.id;
-				}
-				if (rowAttrObj.hasOwnProperty("tabindex")) {
-					tabindex = rowAttrObj.tabindex;
-					delete rowAttrObj.tabindex;
-				}
-				if (rowAttrObj.hasOwnProperty("style")) {
-					style += rowAttrObj.style;
-					delete rowAttrObj.style;
-				}
-				if (rowAttrObj.hasOwnProperty("class")) {
-					classes += ' ' + rowAttrObj['class'];
-					delete rowAttrObj['class'];
-				}
-				// dot't allow to change role attribute
-				try { delete rowAttrObj.role; } catch(ra){}
-				for (attrName in rowAttrObj) {
-					if (rowAttrObj.hasOwnProperty(attrName)) {
-						restAttr += ' ' + attrName + '=' + rowAttrObj[attrName];
-					}
-				}
-			}
-			return '<tr role="row" id="' + id + '" tabindex="' + tabindex + '" class="' + classes + '"' +
-				(style === '' ? '' : ' style="' + style + '"') + restAttr + '>';
-		},
-		addXmlData = function (xml,t, rcnt, more, adjust) {
-			var startReq = new Date(),
-			locdata = (ts.p.datatype != "local" && ts.p.loadonce) || ts.p.datatype == "xmlstring",
-			xmlid = "_id_", xmlRd = ts.p.xmlReader,
-			frd = ts.p.datatype == "local" ? "local" : "xml";
-			if(locdata) {
-				ts.p.data = [];
-				ts.p._index = {};
-				ts.p.localReader.id = xmlid;
-			}
-			ts.p.reccount = 0;
-			if($.isXMLDoc(xml)) {
-				if(ts.p.treeANode===-1 && !ts.p.scroll) {
-					emptyRows.call(ts, false, true);
-					rcnt=1;
-				} else { rcnt = rcnt > 1 ? rcnt :1; }
-			} else { return; }
-			var i,fpos,ir=0,v,gi=ts.p.multiselect===true?1:0,si=ts.p.subGrid===true?1:0,ni=ts.p.rownumbers===true?1:0,idn, getId,f=[],F,rd ={}, xmlr,rid, rowData=[], cn=(ts.p.altRows === true) ? " "+ts.p.altclass:"",cn1;
-			if(!xmlRd.repeatitems) {f = reader(frd);}
-			if( ts.p.keyIndex===false) {
-				idn = $.isFunction( xmlRd.id ) ?  xmlRd.id.call(ts, xml) : xmlRd.id;
-			} else {
-				idn = ts.p.keyIndex;
-			}
-			if(f.length>0 && !isNaN(idn)) {
-				if (ts.p.remapColumns && ts.p.remapColumns.length) {
-					idn = $.inArray(idn, ts.p.remapColumns);
-				}
-				idn=f[idn];
-			}
-			if( (idn+"").indexOf("[") === -1 ) {
-				if (f.length) {
-					getId = function( trow, k) {return $(idn,trow).text() || k;};
-				} else {
-					getId = function( trow, k) {return $(xmlRd.cell,trow).eq(idn).text() || k;};
-				}
-			}
-			else {
-				getId = function( trow, k) {return trow.getAttribute(idn.replace(/[\[\]]/g,"")) || k;};
-			}
-			ts.p.userData = {};
-			ts.p.page = $.jgrid.getXmlData( xml,xmlRd.page ) || 0;
-			ts.p.lastpage = $.jgrid.getXmlData( xml,xmlRd.total );
-			if(ts.p.lastpage===undefined) { ts.p.lastpage=1; }
-			ts.p.records = $.jgrid.getXmlData( xml,xmlRd.records ) || 0;
-			if($.isFunction(xmlRd.userdata)) {
-				ts.p.userData = xmlRd.userdata.call(ts, xml) || {};
-			} else {
-				$.jgrid.getXmlData(xml, xmlRd.userdata, true).each(function() {ts.p.userData[this.getAttribute("name")]= $(this).text();});
-			}
-			var gxml = $.jgrid.getXmlData( xml, xmlRd.root, true);
-			gxml = $.jgrid.getXmlData( gxml, xmlRd.row, true);
-			if (!gxml) { gxml = []; }
-			var gl = gxml.length, j=0, grpdata=[], rn = parseInt(ts.p.rowNum,10);
-			if (gl > 0 &&  ts.p.page <= 0) { ts.p.page = 1; }
-			if(gxml && gl){
-			var br=ts.p.scroll?$.jgrid.randId():1,altr;
-			if (adjust) { rn *= adjust+1; }
-			var afterInsRow = $.isFunction(ts.p.afterInsertRow), hiderow=ts.p.grouping && ts.p.groupingView.groupCollapse === true;
-			while (j<gl) {
-				xmlr = gxml[j];
-				rid = getId(xmlr,br+j);
-				rid  = ts.p.idPrefix + rid;
-				altr = rcnt === 0 ? 0 : rcnt+1;
-				cn1 = (altr+j)%2 == 1 ? cn : '';
-				var iStartTrTag = rowData.length;
-				rowData.push("");
-				if( ni ) {
-					rowData.push( addRowNum(0,j,ts.p.page,ts.p.rowNum) );
-				}
-				if( gi ) {
-					rowData.push( addMulti(rid,ni,j) );
-				}
-				if( si ) {
-					rowData.push( $(ts).jqGrid("addSubGridCell",gi+ni,j+rcnt) );
-				}
-				if(xmlRd.repeatitems){
-					if (!F) { F=orderedCols(gi+si+ni); }
-					var cells = $.jgrid.getXmlData( xmlr, xmlRd.cell, true);
-					$.each(F, function (k) {
-						var cell = cells[this];
-						if (!cell) { return false; }
-						v = cell.textContent || cell.text;
-						rd[ts.p.colModel[k+gi+si+ni].name] = v;
-						rowData.push( addCell(rid,v,k+gi+si+ni,j+rcnt,xmlr) );
-					});
-				} else {
-					for(i = 0; i < f.length;i++) {
-						v = $.jgrid.getXmlData( xmlr, f[i]);
-						rd[ts.p.colModel[i+gi+si+ni].name] = v;
-						rowData.push( addCell(rid, v, i+gi+si+ni, j+rcnt, xmlr) );
-					}
-				}
-				rowData[iStartTrTag] = constructTr(rid, hiderow, cn1, rd, xmlr);
-				rowData.push("</tr>");
-				if(ts.p.grouping) {
-					grpdata = $(ts).jqGrid('groupingPrepare',rowData, grpdata, rd, j);
-					rowData = [];
-				}
-				if(locdata || ts.p.treeGrid === true) {
-					rd[xmlid] = rid;
-					ts.p.data.push(rd);
-					ts.p._index[rid] = ts.p.data.length-1;
-				}
-				if(ts.p.gridview === false ) {
-					$("tbody:first",t).append(rowData.join(''));
-					$(ts).triggerHandler("jqGridAfterInsertRow", [rid, rd, xmlr]);
-					if(afterInsRow) {ts.p.afterInsertRow.call(ts,rid,rd,xmlr);}
-					rowData=[];
-				}
-				rd={};
-				ir++;
-				j++;
-				if(ir==rn) {break;}
-			}
-			}
-			if(ts.p.gridview === true) {
-				fpos = ts.p.treeANode > -1 ? ts.p.treeANode: 0;
-				if(ts.p.grouping) {
-					$(ts).jqGrid('groupingRender',grpdata,ts.p.colModel.length);
-					grpdata = null;
-				} else if(ts.p.treeGrid === true && fpos > 0) {
-					$(ts.rows[fpos]).after(rowData.join(''));
-				} else {
-					$("tbody:first",t).append(rowData.join(''));
-				}
-			}
-			if(ts.p.subGrid === true ) {
-				try {$(ts).jqGrid("addSubGrid",gi+ni);} catch (_){}
-			}
-			ts.p.totaltime = new Date() - startReq;
-			if(ir>0) { if(ts.p.records===0) { ts.p.records=gl;} }
-			rowData =null;
-			if( ts.p.treeGrid === true) {
-				try {$(ts).jqGrid("setTreeNode", fpos+1, ir+fpos+1);} catch (e) {}
-			}
-			if(!ts.p.treeGrid && !ts.p.scroll) {ts.grid.bDiv.scrollTop = 0;}
-			ts.p.reccount=ir;
-			ts.p.treeANode = -1;
-			if(ts.p.userDataOnFooter) { $(ts).jqGrid("footerData","set",ts.p.userData,true); }
-			if(locdata) {
-				ts.p.records = gl;
-				ts.p.lastpage = Math.ceil(gl/ rn);
-			}
-			if (!more) { ts.updatepager(false,true); }
-			if(locdata) {
-				while (ir<gl) {
-					xmlr = gxml[ir];
-					rid = getId(xmlr,ir+br);
-					rid  = ts.p.idPrefix + rid;
-					if(xmlRd.repeatitems){
-						if (!F) { F=orderedCols(gi+si+ni); }
-						var cells2 = $.jgrid.getXmlData( xmlr, xmlRd.cell, true);
-						$.each(F, function (k) {
-							var cell = cells2[this];
-							if (!cell) { return false; }
-							v = cell.textContent || cell.text;
-							rd[ts.p.colModel[k+gi+si+ni].name] = v;
-						});
-					} else {
-						for(i = 0; i < f.length;i++) {
-							v = $.jgrid.getXmlData( xmlr, f[i]);
-							rd[ts.p.colModel[i+gi+si+ni].name] = v;
-						}
-					}
-					rd[xmlid] = rid;
-					ts.p.data.push(rd);
-					ts.p._index[rid] = ts.p.data.length-1;
-					rd = {};
-					ir++;
-				}
-			}
-		},
-		addJSONData = function(data,t, rcnt, more, adjust) {
-			var startReq = new Date();
-			if(data) {
-				if(ts.p.treeANode === -1 && !ts.p.scroll) {
-					emptyRows.call(ts, false, true);
-					rcnt=1;
-				} else { rcnt = rcnt > 1 ? rcnt :1; }
-			} else { return; }
-
-			var dReader, locid = "_id_", frd,
-			locdata = (ts.p.datatype != "local" && ts.p.loadonce) || ts.p.datatype == "jsonstring";
-			if(locdata) { ts.p.data = []; ts.p._index = {}; ts.p.localReader.id = locid;}
-			ts.p.reccount = 0;
-			if(ts.p.datatype == "local") {
-				dReader =  ts.p.localReader;
-				frd= 'local';
-			} else {
-				dReader =  ts.p.jsonReader;
-				frd='json';
-			}
-			var ir=0,v,i,j,f=[],F,cur,gi=ts.p.multiselect?1:0,si=ts.p.subGrid?1:0,ni=ts.p.rownumbers===true?1:0,len,drows,idn,rd={}, fpos, idr,rowData=[],cn=(ts.p.altRows === true) ? " "+ts.p.altclass:"",cn1,lp;
-			ts.p.page = $.jgrid.getAccessor(data,dReader.page) || 0;
-			lp = $.jgrid.getAccessor(data,dReader.total);
-			ts.p.lastpage = lp === undefined ? 1 : lp;
-			ts.p.records = $.jgrid.getAccessor(data,dReader.records) || 0;
-			ts.p.userData = $.jgrid.getAccessor(data,dReader.userdata) || {};
-			if(!dReader.repeatitems) {
-				F = f = reader(frd);
-			}
-			if( ts.p.keyIndex===false ) {
-				idn = $.isFunction(dReader.id) ? dReader.id.call(ts, data) : dReader.id;
-			} else {
-				idn = ts.p.keyIndex;
-			}
-			if(f.length>0 && !isNaN(idn)) {
-				if (ts.p.remapColumns && ts.p.remapColumns.length) {
-					idn = $.inArray(idn, ts.p.remapColumns);
-				}
-				idn=f[idn];
-			}
-			drows = $.jgrid.getAccessor(data,dReader.root);
-			if (!drows) { drows = []; }
-			len = drows.length; i=0;
-			if (len > 0 && ts.p.page <= 0) { ts.p.page = 1; }
-			var rn = parseInt(ts.p.rowNum,10),br=ts.p.scroll?$.jgrid.randId():1, altr;
-			if (adjust) { rn *= adjust+1; }
-			var afterInsRow = $.isFunction(ts.p.afterInsertRow), grpdata=[], hiderow=ts.p.grouping && ts.p.groupingView.groupCollapse === true;
-			while (i<len) {
-				cur = drows[i];
-				idr = $.jgrid.getAccessor(cur,idn);
-				if(idr === undefined) {
-					idr = br+i;
-					if(f.length===0){
-						if(dReader.cell){
-							var ccur = $.jgrid.getAccessor(cur,dReader.cell);
-							idr = ccur !== undefined ? ccur[idn] || idr : idr;
-							ccur=null;
-						}
-					}
-				}
-				idr  = ts.p.idPrefix + idr;
-				altr = rcnt === 1 ? 0 : rcnt;
-				cn1 = (altr+i)%2 == 1 ? cn : '';
-				var iStartTrTag = rowData.length;
-				rowData.push("");
-				if( ni ) {
-					rowData.push( addRowNum(0,i,ts.p.page,ts.p.rowNum) );
-				}
-				if( gi ){
-					rowData.push( addMulti(idr,ni,i) );
-				}
-				if( si ) {
-					rowData.push( $(ts).jqGrid("addSubGridCell",gi+ni,i+rcnt) );
-				}
-				if (dReader.repeatitems) {
-					if(dReader.cell) {cur = $.jgrid.getAccessor(cur,dReader.cell);}
-					if (!F) { F=orderedCols(gi+si+ni); }
-				}
-				for (j=0;j<F.length;j++) {
-					v = $.jgrid.getAccessor(cur,F[j]);
-					rowData.push( addCell(idr,v,j+gi+si+ni,i+rcnt,cur) );
-					rd[ts.p.colModel[j+gi+si+ni].name] = v;
-				}
-				rowData[iStartTrTag] = constructTr(idr, hiderow, cn1, rd, cur);
-				rowData.push( "</tr>" );
-				if(ts.p.grouping) {
-					grpdata = $(ts).jqGrid('groupingPrepare',rowData, grpdata, rd, i);
-					rowData = [];
-				}
-				if(locdata || ts.p.treeGrid===true) {
-					rd[locid] = idr;
-					ts.p.data.push(rd);
-					ts.p._index[idr] = ts.p.data.length-1;
-				}
-				if(ts.p.gridview === false ) {
-					$("#"+$.jgrid.jqID(ts.p.id)+" tbody:first").append(rowData.join(''));
-					$(ts).triggerHandler("jqGridAfterInsertRow", [idr, rd, cur]);
-					if(afterInsRow) {ts.p.afterInsertRow.call(ts,idr,rd,cur);}
-					rowData=[];//ari=0;
-				}
-				rd={};
-				ir++;
-				i++;
-				if(ir==rn) { break; }
-			}
-			if(ts.p.gridview === true ) {
-				fpos = ts.p.treeANode > -1 ? ts.p.treeANode: 0;
-				if(ts.p.grouping) {
-					$(ts).jqGrid('groupingRender',grpdata,ts.p.colModel.length);
-					grpdata = null;
-				} else if(ts.p.treeGrid === true && fpos > 0) {
-					$(ts.rows[fpos]).after(rowData.join(''));
-				} else {
-					$("#"+$.jgrid.jqID(ts.p.id)+" tbody:first").append(rowData.join(''));
-				}
-			}
-			if(ts.p.subGrid === true ) {
-				try { $(ts).jqGrid("addSubGrid",gi+ni);} catch (_){}
-			}
-			ts.p.totaltime = new Date() - startReq;
-			if(ir>0) {
-				if(ts.p.records===0) { ts.p.records=len; }
-			}
-			rowData = null;
-			if( ts.p.treeGrid === true) {
-				try {$(ts).jqGrid("setTreeNode", fpos+1, ir+fpos+1);} catch (e) {}
-			}
-			if(!ts.p.treeGrid && !ts.p.scroll) {ts.grid.bDiv.scrollTop = 0;}
-			ts.p.reccount=ir;
-			ts.p.treeANode = -1;
-			if(ts.p.userDataOnFooter) { $(ts).jqGrid("footerData","set",ts.p.userData,true); }
-			if(locdata) {
-				ts.p.records = len;
-				ts.p.lastpage = Math.ceil(len/ rn);
-			}
-			if (!more) { ts.updatepager(false,true); }
-			if(locdata) {
-				while (ir<len && drows[ir]) {
-					cur = drows[ir];
-					idr = $.jgrid.getAccessor(cur,idn);
-					if(idr === undefined) {
-						idr = br+ir;
-						if(f.length===0){
-							if(dReader.cell){
-								var ccur2 = $.jgrid.getAccessor(cur,dReader.cell);
-								idr = ccur2[idn] || idr;
-								ccur2=null;
-							}
-						}
-					}
-					if(cur) {
-						idr  = ts.p.idPrefix + idr;
-						if (dReader.repeatitems) {
-							if(dReader.cell) {cur = $.jgrid.getAccessor(cur,dReader.cell);}
-							if (!F) { F=orderedCols(gi+si+ni); }
-						}
-
-						for (j=0;j<F.length;j++) {
-							v = $.jgrid.getAccessor(cur,F[j]);
-							rd[ts.p.colModel[j+gi+si+ni].name] = v;
-						}
-						rd[locid] = idr;
-						ts.p.data.push(rd);
-						ts.p._index[idr] = ts.p.data.length-1;
-						rd = {};
-					}
-					ir++;
-				}
-			}
-		},
-		addLocalData = function() {
-			var st, fndsort=false, cmtypes={}, grtypes=[], grindexes=[], srcformat, sorttype, newformat;
-			if(!$.isArray(ts.p.data)) {
-				return;
-			}
-			var grpview = ts.p.grouping ? ts.p.groupingView : false, lengrp, gin;
-			$.each(ts.p.colModel,function(){
-				sorttype = this.sorttype || "text";
-				if(sorttype == "date" || sorttype == "datetime") {
-					if(this.formatter && typeof(this.formatter) === 'string' && this.formatter == 'date') {
-						if(this.formatoptions && this.formatoptions.srcformat) {
-							srcformat = this.formatoptions.srcformat;
-						} else {
-							srcformat = $.jgrid.formatter.date.srcformat;
-						}
-						if(this.formatoptions && this.formatoptions.newformat) {
-							newformat = this.formatoptions.newformat;
-						} else {
-							newformat = $.jgrid.formatter.date.newformat;
-						}
-					} else {
-						srcformat = newformat = this.datefmt || "Y-m-d";
-					}
-					cmtypes[this.name] = {"stype": sorttype, "srcfmt": srcformat,"newfmt":newformat};
-				} else {
-					cmtypes[this.name] = {"stype": sorttype, "srcfmt":'',"newfmt":''};
-				}
-				if(ts.p.grouping ) {
-					for(gin =0, lengrp = grpview.groupField.length; gin< lengrp; gin++) {
-						if( this.name == grpview.groupField[gin]) {
-							var grindex = this.name;
-							if (typeof this.index != 'undefined') {
-								grindex = this.index;
-							}
-							grtypes[gin] = cmtypes[grindex];
-							grindexes[gin]= grindex;
-						}
-					}
-				}
-				if(!fndsort && (this.index == ts.p.sortname || this.name == ts.p.sortname)){
-					st = this.name; // ???
-					fndsort = true;
-				}
-			});
-			if(ts.p.treeGrid) {
-				$(ts).jqGrid("SortTree", st, ts.p.sortorder, cmtypes[st].stype, cmtypes[st].srcfmt);
-				return;
-			}
-			var compareFnMap = {
-				'eq':function(queryObj) {return queryObj.equals;},
-				'ne':function(queryObj) {return queryObj.notEquals;},
-				'lt':function(queryObj) {return queryObj.less;},
-				'le':function(queryObj) {return queryObj.lessOrEquals;},
-				'gt':function(queryObj) {return queryObj.greater;},
-				'ge':function(queryObj) {return queryObj.greaterOrEquals;},
-				'cn':function(queryObj) {return queryObj.contains;},
-				'nc':function(queryObj,op) {return op === "OR" ? queryObj.orNot().contains : queryObj.andNot().contains;},
-				'bw':function(queryObj) {return queryObj.startsWith;},
-				'bn':function(queryObj,op) {return op === "OR" ? queryObj.orNot().startsWith : queryObj.andNot().startsWith;},
-				'en':function(queryObj,op) {return op === "OR" ? queryObj.orNot().endsWith : queryObj.andNot().endsWith;},
-				'ew':function(queryObj) {return queryObj.endsWith;},
-				'ni':function(queryObj,op) {return op === "OR" ? queryObj.orNot().equals : queryObj.andNot().equals;},
-				'in':function(queryObj) {return queryObj.equals;},
-				'nu':function(queryObj) {return queryObj.isNull;},
-				'nn':function(queryObj,op) {return op === "OR" ? queryObj.orNot().isNull : queryObj.andNot().isNull;}
-
-			},
-			query = $.jgrid.from(ts.p.data);
-			if (ts.p.ignoreCase) { query = query.ignoreCase(); }
-			function tojLinq ( group ) {
-				var s = 0, index, gor, ror, opr, rule;
-				if (group.groups !== undefined) {
-					gor = group.groups.length && group.groupOp.toString().toUpperCase() === "OR";
-					if (gor) {
-						query.orBegin();
-					}
-					for (index = 0; index < group.groups.length; index++) {
-						if (s > 0 && gor) {
-							query.or();
-						}
-						try {
-							tojLinq(group.groups[index]);
-						} catch (e) {alert(e);}
-						s++;
-					}
-					if (gor) {
-						query.orEnd();
-					}
-				}
-				if (group.rules !== undefined) {
-					if(s>0) {
-						var result = query.select();
-						query = $.jgrid.from( result);
-						if (ts.p.ignoreCase) { query = query.ignoreCase(); }
-					}
-					try{
-						ror = group.rules.length && group.groupOp.toString().toUpperCase() === "OR";
-						if (ror) {
-							query.orBegin();
-						}
-						for (index = 0; index < group.rules.length; index++) {
-							rule = group.rules[index];
-							opr = group.groupOp.toString().toUpperCase();
-							if (compareFnMap[rule.op] && rule.field ) {
-								if(s > 0 && opr && opr === "OR") {
-									query = query.or();
-								}
-								query = compareFnMap[rule.op](query, opr)(rule.field, rule.data, cmtypes[rule.field]);
-							}
-							s++;
-						}
-						if (ror) {
-							query.orEnd();
-						}
-					} catch (g) {alert(g);}
-				}
-			}
-
-			if (ts.p.search === true) {
-				var srules = ts.p.postData.filters;
-				if(srules) {
-					if(typeof srules == "string") { srules = $.jgrid.parse(srules);}
-					tojLinq( srules );
-				} else {
-					try {
-						query = compareFnMap[ts.p.postData.searchOper](query)(ts.p.postData.searchField, ts.p.postData.searchString,cmtypes[ts.p.postData.searchField]);
-					} catch (se){}
-				}
-			}
-			if(ts.p.grouping) {
-				for(gin=0; gin<lengrp;gin++) {
-					query.orderBy(grindexes[gin],grpview.groupOrder[gin],grtypes[gin].stype, grtypes[gin].srcfmt);
-				}
-			}
-			if (st && ts.p.sortorder && fndsort) {
-				if(ts.p.sortorder.toUpperCase() == "DESC") {
-					query.orderBy(ts.p.sortname, "d", cmtypes[st].stype, cmtypes[st].srcfmt);
-				} else {
-					query.orderBy(ts.p.sortname, "a", cmtypes[st].stype, cmtypes[st].srcfmt);
-				}
-			}
-			var queryResults = query.select(),
-			recordsperpage = parseInt(ts.p.rowNum,10),
-			total = queryResults.length,
-			page = parseInt(ts.p.page,10),
-			totalpages = Math.ceil(total / recordsperpage),
-			retresult = {};
-			queryResults = queryResults.slice( (page-1)*recordsperpage , page*recordsperpage );
-			query = null;
-			cmtypes = null;
-			retresult[ts.p.localReader.total] = totalpages;
-			retresult[ts.p.localReader.page] = page;
-			retresult[ts.p.localReader.records] = total;
-			retresult[ts.p.localReader.root] = queryResults;
-			retresult[ts.p.localReader.userdata] = ts.p.userData;
-			queryResults = null;
-			return  retresult;
-		},
-		updatepager = function(rn, dnd) {
-			var cp, last, base, from,to,tot,fmt, pgboxes = "", sppg,
-			tspg = ts.p.pager ? "_"+$.jgrid.jqID(ts.p.pager.substr(1)) : "",
-			tspg_t = ts.p.toppager ? "_"+ts.p.toppager.substr(1) : "";
-			base = parseInt(ts.p.page,10)-1;
-			if(base < 0) { base = 0; }
-			base = base*parseInt(ts.p.rowNum,10);
-			to = base + ts.p.reccount;
-			if (ts.p.scroll) {
-				var rows = $("tbody:first > tr:gt(0)", ts.grid.bDiv);
-				base = to - rows.length;
-				ts.p.reccount = rows.length;
-				var rh = rows.outerHeight() || ts.grid.prevRowHeight;
-				if (rh) {
-					var top = base * rh;
-					var height = parseInt(ts.p.records,10) * rh;
-					$(">div:first",ts.grid.bDiv).css({height : height}).children("div:first").css({height:top,display:top?"":"none"});
-				}
-				ts.grid.bDiv.scrollLeft = ts.grid.hDiv.scrollLeft;
-			}
-			pgboxes = ts.p.pager ? ts.p.pager : "";
-			pgboxes += ts.p.toppager ?  (pgboxes ? "," + ts.p.toppager : ts.p.toppager) : "";
-			if(pgboxes) {
-				fmt = $.jgrid.formatter.integer || {};
-				cp = intNum(ts.p.page);
-				last = intNum(ts.p.lastpage);
-				$(".selbox",pgboxes)[ this.p.useProp ? 'prop' : 'attr' ]("disabled",false);
-				if(ts.p.pginput===true) {
-					$('.ui-pg-input',pgboxes).val(ts.p.page);
-					sppg = ts.p.toppager ? '#sp_1'+tspg+",#sp_1"+tspg_t : '#sp_1'+tspg;
-					$(sppg).html($.fmatter ? $.fmatter.util.NumberFormat(ts.p.lastpage,fmt):ts.p.lastpage);
-
-				}
-				if (ts.p.viewrecords){
-					if(ts.p.reccount === 0) {
-						$(".ui-paging-info",pgboxes).html(ts.p.emptyrecords);
-					} else {
-						from = base+1;
-						tot=ts.p.records;
-						if($.fmatter) {
-							from = $.fmatter.util.NumberFormat(from,fmt);
-							to = $.fmatter.util.NumberFormat(to,fmt);
-							tot = $.fmatter.util.NumberFormat(tot,fmt);
-						}
-						$(".ui-paging-info",pgboxes).html($.jgrid.format(ts.p.recordtext,from,to,tot));
-					}
-				}
-				if(ts.p.pgbuttons===true) {
-					if(cp<=0) {cp = last = 0;}
-					if(cp==1 || cp === 0) {
-						$("#first"+tspg+", #prev"+tspg).addClass('ui-state-disabled').removeClass('ui-state-hover');
-						if(ts.p.toppager) { $("#first_t"+tspg_t+", #prev_t"+tspg_t).addClass('ui-state-disabled').removeClass('ui-state-hover'); }
-					} else {
-						$("#first"+tspg+", #prev"+tspg).removeClass('ui-state-disabled');
-						if(ts.p.toppager) { $("#first_t"+tspg_t+", #prev_t"+tspg_t).removeClass('ui-state-disabled'); }
-					}
-					if(cp==last || cp === 0) {
-						$("#next"+tspg+", #last"+tspg).addClass('ui-state-disabled').removeClass('ui-state-hover');
-						if(ts.p.toppager) { $("#next_t"+tspg_t+", #last_t"+tspg_t).addClass('ui-state-disabled').removeClass('ui-state-hover'); }
-					} else {
-						$("#next"+tspg+", #last"+tspg).removeClass('ui-state-disabled');
-						if(ts.p.toppager) { $("#next_t"+tspg_t+", #last_t"+tspg_t).removeClass('ui-state-disabled'); }
-					}
-				}
-			}
-			if(rn===true && ts.p.rownumbers === true) {
-				$("td.jqgrid-rownum",ts.rows).each(function(i){
-					$(this).html(base+1+i);
-				});
-			}
-			if(dnd && ts.p.jqgdnd) { $(ts).jqGrid('gridDnD','updateDnD');}
-			$(ts).triggerHandler("jqGridGridComplete");
-			if($.isFunction(ts.p.gridComplete)) {ts.p.gridComplete.call(ts);}
-			$(ts).triggerHandler("jqGridAfterGridComplete");
-		},
-		beginReq = function() {
-			ts.grid.hDiv.loading = true;
-			if(ts.p.hiddengrid) { return;}
-			switch(ts.p.loadui) {
-				case "disable":
-					break;
-				case "enable":
-					$("#load_"+$.jgrid.jqID(ts.p.id)).show();
-					break;
-				case "block":
-					$("#lui_"+$.jgrid.jqID(ts.p.id)).show();
-					$("#load_"+$.jgrid.jqID(ts.p.id)).show();
-					break;
-			}
-		},
-		endReq = function() {
-			ts.grid.hDiv.loading = false;
-			switch(ts.p.loadui) {
-				case "disable":
-					break;
-				case "enable":
-					$("#load_"+$.jgrid.jqID(ts.p.id)).hide();
-					break;
-				case "block":
-					$("#lui_"+$.jgrid.jqID(ts.p.id)).hide();
-					$("#load_"+$.jgrid.jqID(ts.p.id)).hide();
-					break;
-			}
-		},
-		populate = function (npage) {
-			if(!ts.grid.hDiv.loading) {
-				var pvis = ts.p.scroll && npage === false,
-				prm = {}, dt, dstr, pN=ts.p.prmNames;
-				if(ts.p.page <=0) { ts.p.page = 1; }
-				if(pN.search !== null) {prm[pN.search] = ts.p.search;} if(pN.nd !== null) {prm[pN.nd] = new Date().getTime();}
-				if(pN.rows !== null) {prm[pN.rows]= ts.p.rowNum;} if(pN.page !== null) {prm[pN.page]= ts.p.page;}
-				if(pN.sort !== null) {prm[pN.sort]= ts.p.sortname;} if(pN.order !== null) {prm[pN.order]= ts.p.sortorder;}
-				if(ts.p.rowTotal !== null && pN.totalrows !== null) { prm[pN.totalrows]= ts.p.rowTotal; }
-				var lcf = $.isFunction(ts.p.loadComplete), lc = lcf ? ts.p.loadComplete : null;
-				var adjust = 0;
-				npage = npage || 1;
-				if (npage > 1) {
-					if(pN.npage !== null) {
-						prm[pN.npage] = npage;
-						adjust = npage - 1;
-						npage = 1;
-					} else {
-						lc = function(req) {
-							ts.p.page++;
-							ts.grid.hDiv.loading = false;
-							if (lcf) {
-								ts.p.loadComplete.call(ts,req);
-							}
-							populate(npage-1);
-						};
-					}
-				} else if (pN.npage !== null) {
-					delete ts.p.postData[pN.npage];
-				}
-				if(ts.p.grouping) {
-					$(ts).jqGrid('groupingSetup');
-					var grp = ts.p.groupingView, gi, gs="";
-					for(gi=0;gi<grp.groupField.length;gi++) {
-						gs += grp.groupField[gi]+" "+grp.groupOrder[gi]+", ";
-					}
-					prm[pN.sort] = gs + prm[pN.sort];
-				}
-				$.extend(ts.p.postData,prm);
-				var rcnt = !ts.p.scroll ? 1 : ts.rows.length-1;
-				var bfr = $(ts).triggerHandler("jqGridBeforeRequest");
-				if (bfr === false || bfr === 'stop') { return; }
-				if ($.isFunction(ts.p.datatype)) { ts.p.datatype.call(ts,ts.p.postData,"load_"+ts.p.id); return;}
-				else if($.isFunction(ts.p.beforeRequest)) {
-					bfr = ts.p.beforeRequest.call(ts);
-					if(bfr === undefined) { bfr = true; }
-					if ( bfr === false ) { return; }
-				}
-				dt = ts.p.datatype.toLowerCase();
-				switch(dt)
-				{
-				case "json":
-				case "jsonp":
-				case "xml":
-				case "script":
-					$.ajax($.extend({
-						url:ts.p.url,
-						type:ts.p.mtype,
-						dataType: dt ,
-						data: $.isFunction(ts.p.serializeGridData)? ts.p.serializeGridData.call(ts,ts.p.postData) : ts.p.postData,
-						success:function(data,st, xhr) {
-							if ($.isFunction(ts.p.beforeProcessing)) {
-								if (ts.p.beforeProcessing.call(ts, data, st, xhr) === false) {
-									endReq();
-									return;
-								}
-							}
-							if(dt === "xml") { addXmlData(data,ts.grid.bDiv,rcnt,npage>1,adjust); }
-							else { addJSONData(data,ts.grid.bDiv,rcnt,npage>1,adjust); }
-							$(ts).triggerHandler("jqGridLoadComplete", [data]);
-							if(lc) { lc.call(ts,data); }
-							$(ts).triggerHandler("jqGridAfterLoadComplete", [data]);
-							if (pvis) { ts.grid.populateVisible(); }
-							if( ts.p.loadonce || ts.p.treeGrid) {ts.p.datatype = "local";}
-							data=null;
-							if (npage === 1) { endReq(); }
-						},
-						error:function(xhr,st,err){
-							if($.isFunction(ts.p.loadError)) { ts.p.loadError.call(ts,xhr,st,err); }
-							if (npage === 1) { endReq(); }
-							xhr=null;
-						},
-						beforeSend: function(xhr, settings ){
-							var gotoreq = true;
-							if($.isFunction(ts.p.loadBeforeSend)) {
-								gotoreq = ts.p.loadBeforeSend.call(ts,xhr, settings);
-							}
-							if(gotoreq === undefined) { gotoreq = true; }
-							if(gotoreq === false) {
-								return false;
-							} else {
-								beginReq();
-							}
-						}
-					},$.jgrid.ajaxOptions, ts.p.ajaxGridOptions));
-				break;
-				case "xmlstring":
-					beginReq();
-					dstr = $.jgrid.stringToDoc(ts.p.datastr);
-					addXmlData(dstr,ts.grid.bDiv);
-					$(ts).triggerHandler("jqGridLoadComplete", [dstr]);
-					if(lcf) {ts.p.loadComplete.call(ts,dstr);}
-					$(ts).triggerHandler("jqGridAfterLoadComplete", [dstr]);
-					ts.p.datatype = "local";
-					ts.p.datastr = null;
-					endReq();
-				break;
-				case "jsonstring":
-					beginReq();
-					if(typeof ts.p.datastr == 'string') { dstr = $.jgrid.parse(ts.p.datastr); }
-					else { dstr = ts.p.datastr; }
-					addJSONData(dstr,ts.grid.bDiv);
-					$(ts).triggerHandler("jqGridLoadComplete", [dstr]);
-					if(lcf) {ts.p.loadComplete.call(ts,dstr);}
-					$(ts).triggerHandler("jqGridAfterLoadComplete", [dstr]);
-					ts.p.datatype = "local";
-					ts.p.datastr = null;
-					endReq();
-				break;
-				case "local":
-				case "clientside":
-					beginReq();
-					ts.p.datatype = "local";
-					var req = addLocalData();
-					addJSONData(req,ts.grid.bDiv,rcnt,npage>1,adjust);
-					$(ts).triggerHandler("jqGridLoadComplete", [req]);
-					if(lc) { lc.call(ts,req); }
-					$(ts).triggerHandler("jqGridAfterLoadComplete", [req]);
-					if (pvis) { ts.grid.populateVisible(); }
-					endReq();
-				break;
-				}
-			}
-		},
-		setHeadCheckBox = function ( checked ) {
-			$('#cb_'+$.jgrid.jqID(ts.p.id),ts.grid.hDiv)[ts.p.useProp ? 'prop': 'attr']("checked", checked);
-			var fid = ts.p.frozenColumns ? ts.p.id+"_frozen" : "";
-			if(fid) {
-				$('#cb_'+$.jgrid.jqID(ts.p.id),ts.grid.fhDiv)[ts.p.useProp ? 'prop': 'attr']("checked", checked);
-			}
-		},
-		setPager = function (pgid, tp){
-			// TBD - consider escaping pgid with pgid = $.jgrid.jqID(pgid);
-			var sep = "<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>",
-			pginp = "",
-			pgl="<table cellspacing='0' cellpadding='0' border='0' style='table-layout:auto;' class='ui-pg-table'><tbody><tr>",
-			str="", pgcnt, lft, cent, rgt, twd, tdw, i,
-			clearVals = function(onpaging){
-				var ret;
-				if ($.isFunction(ts.p.onPaging) ) { ret = ts.p.onPaging.call(ts,onpaging); }
-				ts.p.selrow = null;
-				if(ts.p.multiselect) {ts.p.selarrrow =[]; setHeadCheckBox( false );}
-				ts.p.savedRow = [];
-				if(ret=='stop') {return false;}
-				return true;
-			};
-			pgid = pgid.substr(1);
-			tp += "_" + pgid;
-			pgcnt = "pg_"+pgid;
-			lft = pgid+"_left"; cent = pgid+"_center"; rgt = pgid+"_right";
-			$("#"+$.jgrid.jqID(pgid) )
-			.append("<div id='"+pgcnt+"' class='ui-pager-control' role='group'><table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table' style='width:100%;table-layout:fixed;height:100%;' role='row'><tbody><tr><td id='"+lft+"' align='left'></td><td id='"+cent+"' align='center' style='white-space:pre;'></td><td id='"+rgt+"' align='right'></td></tr></tbody></table></div>")
-			.attr("dir","ltr"); //explicit setting
-			if(ts.p.rowList.length >0){
-				str = "<td dir='"+dir+"'>";
-				str +="<select class='ui-pg-selbox' role='listbox'>";
-				for(i=0;i<ts.p.rowList.length;i++){
-					str +="<option role=\"option\" value=\""+ts.p.rowList[i]+"\""+((ts.p.rowNum == ts.p.rowList[i])?" selected=\"selected\"":"")+">"+ts.p.rowList[i]+"</option>";
-				}
-				str +="</select></td>";
-			}
-			if(dir=="rtl") { pgl += str; }
-			if(ts.p.pginput===true) { pginp= "<td dir='"+dir+"'>"+$.jgrid.format(ts.p.pgtext || "","<input class='ui-pg-input' type='text' size='2' maxlength='7' value='0' role='textbox'/>","<span id='sp_1_"+$.jgrid.jqID(pgid)+"'></span>")+"</td>";}
-			if(ts.p.pgbuttons===true) {
-				var po=["first"+tp,"prev"+tp, "next"+tp,"last"+tp]; if(dir=="rtl") { po.reverse(); }
-				pgl += "<td id='"+po[0]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-first'></span></td>";
-				pgl += "<td id='"+po[1]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-prev'></span></td>";
-				pgl += pginp !== "" ? sep+pginp+sep:"";
-				pgl += "<td id='"+po[2]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-next'></span></td>";
-				pgl += "<td id='"+po[3]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-end'></span></td>";
-			} else if (pginp !== "") { pgl += pginp; }
-			if(dir=="ltr") { pgl += str; }
-			pgl += "</tr></tbody></table>";
-			if(ts.p.viewrecords===true) {$("td#"+pgid+"_"+ts.p.recordpos,"#"+pgcnt).append("<div dir='"+dir+"' style='text-align:"+ts.p.recordpos+"' class='ui-paging-info'></div>");}
-			$("td#"+pgid+"_"+ts.p.pagerpos,"#"+pgcnt).append(pgl);
-			tdw = $(".ui-jqgrid").css("font-size") || "11px";
-			$(document.body).append("<div id='testpg' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:"+tdw+";visibility:hidden;' ></div>");
-			twd = $(pgl).clone().appendTo("#testpg").width();
-			$("#testpg").remove();
-			if(twd > 0) {
-				if(pginp !== "") { twd += 50; } //should be param
-				$("td#"+pgid+"_"+ts.p.pagerpos,"#"+pgcnt).width(twd);
-			}
-			ts.p._nvtd = [];
-			ts.p._nvtd[0] = twd ? Math.floor((ts.p.width - twd)/2) : Math.floor(ts.p.width/3);
-			ts.p._nvtd[1] = 0;
-			pgl=null;
-			$('.ui-pg-selbox',"#"+pgcnt).bind('change',function() {
-				ts.p.page = Math.round(ts.p.rowNum*(ts.p.page-1)/this.value-0.5)+1;
-				ts.p.rowNum = this.value;
-				if(ts.p.pager) { $('.ui-pg-selbox',ts.p.pager).val(this.value); }
-				if(ts.p.toppager) { $('.ui-pg-selbox',ts.p.toppager).val(this.value); }
-				if(!clearVals('records')) { return false; }
-				populate();
-				return false;
-			});
-			if(ts.p.pgbuttons===true) {
-			$(".ui-pg-button","#"+pgcnt).hover(function(){
-				if($(this).hasClass('ui-state-disabled')) {
-					this.style.cursor='default';
-				} else {
-					$(this).addClass('ui-state-hover');
-					this.style.cursor='pointer';
-				}
-			},function() {
-				if(!$(this).hasClass('ui-state-disabled')) {
-					$(this).removeClass('ui-state-hover');
-					this.style.cursor= "default";
-				}
-			});
-			$("#first"+$.jgrid.jqID(tp)+", #prev"+$.jgrid.jqID(tp)+", #next"+$.jgrid.jqID(tp)+", #last"+$.jgrid.jqID(tp)).click( function() {
-				var cp = intNum(ts.p.page,1),
-				last = intNum(ts.p.lastpage,1), selclick = false,
-				fp=true, pp=true, np=true,lp=true;
-				if(last ===0 || last===1) {fp=false;pp=false;np=false;lp=false; }
-				else if( last>1 && cp >=1) {
-					if( cp === 1) { fp=false; pp=false; }
-					//else if( cp>1 && cp <last){ }
-					else if( cp===last){ np=false;lp=false; }
-				} else if( last>1 && cp===0 ) { np=false;lp=false; cp=last-1;}
-				if( this.id === 'first'+tp && fp ) { ts.p.page=1; selclick=true;}
-				if( this.id === 'prev'+tp && pp) { ts.p.page=(cp-1); selclick=true;}
-				if( this.id === 'next'+tp && np) { ts.p.page=(cp+1); selclick=true;}
-				if( this.id === 'last'+tp && lp) { ts.p.page=last; selclick=true;}
-				if(selclick) {
-					if(!clearVals(this.id)) { return false; }
-					populate();
-				}
-				return false;
-			});
-			}
-			if(ts.p.pginput===true) {
-			$('input.ui-pg-input',"#"+pgcnt).keypress( function(e) {
-				var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
-				if(key == 13) {
-					ts.p.page = ($(this).val()>0) ? $(this).val():ts.p.page;
-					if(!clearVals('user')) { return false; }
-					populate();
-					return false;
-				}
-				return this;
-			});
-			}
-		},
-		sortData = function (index, idxcol,reload,sor){
-			if(!ts.p.colModel[idxcol].sortable) { return; }
-			var so;
-			if(ts.p.savedRow.length > 0) {return;}
-			if(!reload) {
-				if( ts.p.lastsort == idxcol ) {
-					if( ts.p.sortorder == 'asc') {
-						ts.p.sortorder = 'desc';
-					} else if(ts.p.sortorder == 'desc') { ts.p.sortorder = 'asc';}
-				} else { ts.p.sortorder = ts.p.colModel[idxcol].firstsortorder || 'asc'; }
-				ts.p.page = 1;
-			}
-			if(sor) {
-				if(ts.p.lastsort == idxcol && ts.p.sortorder == sor && !reload) { return; }
-				else { ts.p.sortorder = sor; }
-			}
-			var previousSelectedTh = ts.grid.headers[ts.p.lastsort].el, newSelectedTh = ts.grid.headers[idxcol].el;
-
-			$("span.ui-grid-ico-sort",previousSelectedTh).addClass('ui-state-disabled');
-			$(previousSelectedTh).attr("aria-selected","false");
-			$("span.ui-icon-"+ts.p.sortorder,newSelectedTh).removeClass('ui-state-disabled');
-			$(newSelectedTh).attr("aria-selected","true");
-			if(!ts.p.viewsortcols[0]) {
-				if(ts.p.lastsort != idxcol) {
-					$("span.s-ico",previousSelectedTh).hide();
-					$("span.s-ico",newSelectedTh).show();
-				}
-			}
-			index = index.substring(5 + ts.p.id.length + 1); // bad to be changed!?!
-			ts.p.sortname = ts.p.colModel[idxcol].index || index;
-			so = ts.p.sortorder;
-			if ($(ts).triggerHandler("jqGridSortCol", [index, idxcol, so]) === 'stop') {
-				ts.p.lastsort = idxcol;
-				return;
-			}
-			if($.isFunction(ts.p.onSortCol)) {if (ts.p.onSortCol.call(ts,index,idxcol,so)=='stop') {ts.p.lastsort = idxcol; return;}}
-			if(ts.p.datatype == "local") {
-				if(ts.p.deselectAfterSort) {$(ts).jqGrid("resetSelection");}
-			} else {
-				ts.p.selrow = null;
-				if(ts.p.multiselect){setHeadCheckBox( false );}
-				ts.p.selarrrow =[];
-				ts.p.savedRow =[];
-			}
-			if(ts.p.scroll) {
-				var sscroll = ts.grid.bDiv.scrollLeft;
-				emptyRows.call(ts, true, false);
-				ts.grid.hDiv.scrollLeft = sscroll;
-			}
-			if(ts.p.subGrid && ts.p.datatype=='local') {
-				$("td.sgexpanded","#"+$.jgrid.jqID(ts.p.id)).each(function(){
-					$(this).trigger("click");
-				});
-			}
-			populate();
-			ts.p.lastsort = idxcol;
-			if(ts.p.sortname != index && idxcol) {ts.p.lastsort = idxcol;}
-		},
-		setColWidth = function () {
-			var initwidth = 0, brd=$.jgrid.cellWidth()? 0: intNum(ts.p.cellLayout,0), vc=0, lvc, scw=intNum(ts.p.scrollOffset,0),cw,hs=false,aw,gw=0,
-			cl = 0, cr;
-			$.each(ts.p.colModel, function() {
-				if(typeof this.hidden === 'undefined') {this.hidden=false;}
-				this.widthOrg = cw = intNum(this.width,0);
-				if(this.hidden===false){
-					initwidth += cw+brd;
-					if(this.fixed) {
-						gw += cw+brd;
-					} else {
-						vc++;
-					}
-					cl++;
-				}
-			});
-			if(isNaN(ts.p.width)) {
-				ts.p.width  = initwidth + ((ts.p.shrinkToFit ===false && !isNaN(ts.p.height)) ? scw : 0);
-			}
-			grid.width = ts.p.width;
-			ts.p.tblwidth = initwidth;
-			if(ts.p.shrinkToFit ===false && ts.p.forceFit === true) {ts.p.forceFit=false;}
-			if(ts.p.shrinkToFit===true && vc > 0) {
-				aw = grid.width-brd*vc-gw;
-				if(!isNaN(ts.p.height)) {
-					aw -= scw;
-					hs = true;
-				}
-				initwidth =0;
-				$.each(ts.p.colModel, function(i) {
-					if(this.hidden === false && !this.fixed){
-						cw = Math.round(aw*this.width/(ts.p.tblwidth-brd*vc-gw));
-						this.width =cw;
-						initwidth += cw;
-						lvc = i;
-					}
-				});
-				cr =0;
-				if (hs) {
-					if(grid.width-gw-(initwidth+brd*vc) !== scw){
-						cr = grid.width-gw-(initwidth+brd*vc)-scw;
-					}
-				} else if(!hs && Math.abs(grid.width-gw-(initwidth+brd*vc)) !== 1) {
-					cr = grid.width-gw-(initwidth+brd*vc);
-				}
-				ts.p.colModel[lvc].width += cr;
-				ts.p.tblwidth = initwidth+cr+brd*vc+gw;
-				if(ts.p.tblwidth > ts.p.width) {
-					ts.p.colModel[lvc].width -= (ts.p.tblwidth - parseInt(ts.p.width,10));
-					ts.p.tblwidth = ts.p.width;
-				}
-			}
-		},
-		nextVisible= function(iCol) {
-			var ret = iCol, j=iCol, i;
-			for (i = iCol+1;i<ts.p.colModel.length;i++){
-				if(ts.p.colModel[i].hidden !== true ) {
-					j=i; break;
-				}
-			}
-			return j-ret;
-		},
-		getOffset = function (iCol) {
-			var i, ret = {}, brd1 = $.jgrid.cellWidth() ? 0 : ts.p.cellLayout;
-			ret[0] =  ret[1] = ret[2] = 0;
-			for(i=0;i<=iCol;i++){
-				if(ts.p.colModel[i].hidden === false ) {
-					ret[0] += ts.p.colModel[i].width+brd1;
-				}
-			}
-			if(ts.p.direction=="rtl") { ret[0] = ts.p.width - ret[0]; }
-			ret[0] = ret[0] - ts.grid.bDiv.scrollLeft;
-			if($(ts.grid.cDiv).is(":visible")) {ret[1] += $(ts.grid.cDiv).height() +parseInt($(ts.grid.cDiv).css("padding-top"),10)+parseInt($(ts.grid.cDiv).css("padding-bottom"),10);}
-			if(ts.p.toolbar[0]===true && (ts.p.toolbar[1]=='top' || ts.p.toolbar[1]=='both')) {ret[1] += $(ts.grid.uDiv).height()+parseInt($(ts.grid.uDiv).css("border-top-width"),10)+parseInt($(ts.grid.uDiv).css("border-bottom-width"),10);}
-			if(ts.p.toppager) {ret[1] += $(ts.grid.topDiv).height()+parseInt($(ts.grid.topDiv).css("border-bottom-width"),10);}
-			ret[2] += $(ts.grid.bDiv).height() + $(ts.grid.hDiv).height();
-			return ret;
-		},
-		getColumnHeaderIndex = function (th) {
-			var i, headers = ts.grid.headers, ci = $.jgrid.getCellIndex(th);
-			for (i = 0; i < headers.length; i++) {
-				if (th === headers[i].el) {
-					ci = i;
-					break;
-				}
-			}
-			return ci;
-		};
-		this.p.id = this.id;
-		if ($.inArray(ts.p.multikey,sortkeys) == -1 ) {ts.p.multikey = false;}
-		ts.p.keyIndex=false;
-		for (i=0; i<ts.p.colModel.length;i++) {
-			ts.p.colModel[i] = $.extend(true, {}, ts.p.cmTemplate, ts.p.colModel[i].template || {}, ts.p.colModel[i]);
-			if (ts.p.keyIndex === false && ts.p.colModel[i].key===true) {
-				ts.p.keyIndex = i;
-			}
-		}
-		ts.p.sortorder = ts.p.sortorder.toLowerCase();
-		if(ts.p.grouping===true) {
-			ts.p.scroll = false;
-			ts.p.rownumbers = false;
-			//ts.p.subGrid = false; expiremental
-			ts.p.treeGrid = false;
-			ts.p.gridview = true;
-		}
-		if(this.p.treeGrid === true) {
-			try { $(this).jqGrid("setTreeGrid");} catch (_) {}
-			if(ts.p.datatype != "local") { ts.p.localReader = {id: "_id_"};	}
-		}
-		if(this.p.subGrid) {
-			try { $(ts).jqGrid("setSubGrid");} catch (s){}
-		}
-		if(this.p.multiselect) {
-			this.p.colNames.unshift("<input role='checkbox' id='cb_"+this.p.id+"' class='cbox' type='checkbox'/>");
-			this.p.colModel.unshift({name:'cb',width:$.jgrid.cellWidth() ? ts.p.multiselectWidth+ts.p.cellLayout : ts.p.multiselectWidth,sortable:false,resizable:false,hidedlg:true,search:false,align:'center',fixed:true});
-		}
-		if(this.p.rownumbers) {
-			this.p.colNames.unshift("");
-			this.p.colModel.unshift({name:'rn',width:ts.p.rownumWidth,sortable:false,resizable:false,hidedlg:true,search:false,align:'center',fixed:true});
-		}
-		ts.p.xmlReader = $.extend(true,{
-			root: "rows",
-			row: "row",
-			page: "rows>page",
-			total: "rows>total",
-			records : "rows>records",
-			repeatitems: true,
-			cell: "cell",
-			id: "[id]",
-			userdata: "userdata",
-			subgrid: {root:"rows", row: "row", repeatitems: true, cell:"cell"}
-		}, ts.p.xmlReader);
-		ts.p.jsonReader = $.extend(true,{
-			root: "rows",
-			page: "page",
-			total: "total",
-			records: "records",
-			repeatitems: true,
-			cell: "cell",
-			id: "id",
-			userdata: "userdata",
-			subgrid: {root:"rows", repeatitems: true, cell:"cell"}
-		},ts.p.jsonReader);
-		ts.p.localReader = $.extend(true,{
-			root: "rows",
-			page: "page",
-			total: "total",
-			records: "records",
-			repeatitems: false,
-			cell: "cell",
-			id: "id",
-			userdata: "userdata",
-			subgrid: {root:"rows", repeatitems: true, cell:"cell"}
-		},ts.p.localReader);
-		if(ts.p.scroll){
-			ts.p.pgbuttons = false; ts.p.pginput=false; ts.p.rowList=[];
-		}
-		if(ts.p.data.length) { refreshIndex(); }
-		var thead = "<thead><tr class='ui-jqgrid-labels' role='rowheader'>",
-		tdc, idn, w, res, sort,
-		td, ptr, tbody, imgs,iac="",idc="";
-		if(ts.p.shrinkToFit===true && ts.p.forceFit===true) {
-			for (i=ts.p.colModel.length-1;i>=0;i--){
-				if(!ts.p.colModel[i].hidden) {
-					ts.p.colModel[i].resizable=false;
-					break;
-				}
-			}
-		}
-		if(ts.p.viewsortcols[1] == 'horizontal') {iac=" ui-i-asc";idc=" ui-i-desc";}
-		tdc = isMSIE ?  "class='ui-th-div-ie'" :"";
-		imgs = "<span class='s-ico' style='display:none'><span sort='asc' class='ui-grid-ico-sort ui-icon-asc"+iac+" ui-state-disabled ui-icon ui-icon-triangle-1-n ui-sort-"+dir+"'></span>";
-		imgs += "<span sort='desc' class='ui-grid-ico-sort ui-icon-desc"+idc+" ui-state-disabled ui-icon ui-icon-triangle-1-s ui-sort-"+dir+"'></span></span>";
-		for(i=0;i<this.p.colNames.length;i++){
-			var tooltip = ts.p.headertitles ? (" title=\""+$.jgrid.stripHtml(ts.p.colNames[i])+"\"") :"";
-			thead += "<th id='"+ts.p.id+"_"+ts.p.colModel[i].name+"' role='columnheader' class='ui-state-default ui-th-column ui-th-"+dir+"'"+ tooltip+">";
-			idn = ts.p.colModel[i].index || ts.p.colModel[i].name;
-			thead += "<div id='jqgh_"+ts.p.id+"_"+ts.p.colModel[i].name+"' "+tdc+">"+ts.p.colNames[i];
-			if(!ts.p.colModel[i].width)  { ts.p.colModel[i].width = 150; }
-			else { ts.p.colModel[i].width = parseInt(ts.p.colModel[i].width,10); }
-			if(typeof(ts.p.colModel[i].title) !== "boolean") { ts.p.colModel[i].title = true; }
-			if (idn == ts.p.sortname) {
-				ts.p.lastsort = i;
-			}
-			thead += imgs+"</div></th>";
-		}
-		thead += "</tr></thead>";
-		imgs = null;
-		$(this).append(thead);
-		$("thead tr:first th",this).hover(function(){$(this).addClass('ui-state-hover');},function(){$(this).removeClass('ui-state-hover');});
-		if(this.p.multiselect) {
-			var emp=[], chk;
-			$('#cb_'+$.jgrid.jqID(ts.p.id),this).bind('click',function(){
-				ts.p.selarrrow = [];
-				var froz = ts.p.frozenColumns === true ? ts.p.id + "_frozen" : "";
-				if (this.checked) {
-					$(ts.rows).each(function(i) {
-						if (i>0) {
-							if(!$(this).hasClass("ui-subgrid") && !$(this).hasClass("jqgroup") && !$(this).hasClass('ui-state-disabled')){
-								$("#jqg_"+$.jgrid.jqID(ts.p.id)+"_"+$.jgrid.jqID(this.id) )[ts.p.useProp ? 'prop': 'attr']("checked",true);
-								$(this).addClass("ui-state-highlight").attr("aria-selected","true");
-								ts.p.selarrrow.push(this.id);
-								ts.p.selrow = this.id;
-								if(froz) {
-									$("#jqg_"+$.jgrid.jqID(ts.p.id)+"_"+$.jgrid.jqID(this.id), ts.grid.fbDiv )[ts.p.useProp ? 'prop': 'attr']("checked",true);
-									$("#"+$.jgrid.jqID(this.id), ts.grid.fbDiv).addClass("ui-state-highlight");
-								}
-							}
-						}
-					});
-					chk=true;
-					emp=[];
-				}
-				else {
-					$(ts.rows).each(function(i) {
-						if(i>0) {
-							if(!$(this).hasClass("ui-subgrid") && !$(this).hasClass('ui-state-disabled')){
-								$("#jqg_"+$.jgrid.jqID(ts.p.id)+"_"+$.jgrid.jqID(this.id) )[ts.p.useProp ? 'prop': 'attr']("checked", false);
-								$(this).removeClass("ui-state-highlight").attr("aria-selected","false");
-								emp.push(this.id);
-								if(froz) {
-									$("#jqg_"+$.jgrid.jqID(ts.p.id)+"_"+$.jgrid.jqID(this.id), ts.grid.fbDiv )[ts.p.useProp ? 'prop': 'attr']("checked",false);
-									$("#"+$.jgrid.jqID(this.id), ts.grid.fbDiv).removeClass("ui-state-highlight");
-								}
-							}
-						}
-					});
-					ts.p.selrow = null;
-					chk=false;
-				}
-				$(ts).triggerHandler("jqGridSelectAll", [chk ? ts.p.selarrrow : emp, chk]);
-				if($.isFunction(ts.p.onSelectAll)) {ts.p.onSelectAll.call(ts, chk ? ts.p.selarrrow : emp,chk);}
-			});
-		}
-
-		if(ts.p.autowidth===true) {
-			var pw = $(eg).innerWidth();
-			ts.p.width = pw > 0?  pw: 'nw';
-		}
-		setColWidth();
-		$(eg).css("width",grid.width+"px").append("<div class='ui-jqgrid-resize-mark' id='rs_m"+ts.p.id+"'>&#160;</div>");
-		$(gv).css("width",grid.width+"px");
-		thead = $("thead:first",ts).get(0);
-		var	tfoot = "";
-		if(ts.p.footerrow) { tfoot += "<table role='grid' style='width:"+ts.p.tblwidth+"px' class='ui-jqgrid-ftable' cellspacing='0' cellpadding='0' border='0'><tbody><tr role='row' class='ui-widget-content footrow footrow-"+dir+"'>"; }
-		var thr = $("tr:first",thead),
-		firstr = "<tr class='jqgfirstrow' role='row' style='height:auto'>";
-		ts.p.disableClick=false;
-		$("th",thr).each(function ( j ) {
-			w = ts.p.colModel[j].width;
-			if(typeof ts.p.colModel[j].resizable === 'undefined') {ts.p.colModel[j].resizable = true;}
-			if(ts.p.colModel[j].resizable){
-				res = document.createElement("span");
-				$(res).html("&#160;").addClass('ui-jqgrid-resize ui-jqgrid-resize-'+dir);
-				if(!$.browser.opera) { $(res).css("cursor","col-resize"); }
-				$(this).addClass(ts.p.resizeclass);
-			} else {
-				res = "";
-			}
-			$(this).css("width",w+"px").prepend(res);
-			var hdcol = "";
-			if( ts.p.colModel[j].hidden ) {
-				$(this).css("display","none");
-				hdcol = "display:none;";
-			}
-			firstr += "<td role='gridcell' style='height:0px;width:"+w+"px;"+hdcol+"'></td>";
-			grid.headers[j] = { width: w, el: this };
-			sort = ts.p.colModel[j].sortable;
-			if( typeof sort !== 'boolean') {ts.p.colModel[j].sortable =  true; sort=true;}
-			var nm = ts.p.colModel[j].name;
-			if( !(nm == 'cb' || nm=='subgrid' || nm=='rn') ) {
-				if(ts.p.viewsortcols[2]){
-					$(">div",this).addClass('ui-jqgrid-sortable');
-				}
-			}
-			if(sort) {
-				if(ts.p.viewsortcols[0]) {$("div span.s-ico",this).show(); if(j==ts.p.lastsort){ $("div span.ui-icon-"+ts.p.sortorder,this).removeClass("ui-state-disabled");}}
-				else if( j == ts.p.lastsort) {$("div span.s-ico",this).show();$("div span.ui-icon-"+ts.p.sortorder,this).removeClass("ui-state-disabled");}
-			}
-			if(ts.p.footerrow) { tfoot += "<td role='gridcell' "+formatCol(j,0,'', null, '', false)+">&#160;</td>"; }
-		}).mousedown(function(e) {
-			if ($(e.target).closest("th>span.ui-jqgrid-resize").length != 1) { return; }
-			var ci = getColumnHeaderIndex(this);
-			if(ts.p.forceFit===true) {ts.p.nv= nextVisible(ci);}
-			grid.dragStart(ci, e, getOffset(ci));
-			return false;
-		}).click(function(e) {
-			if (ts.p.disableClick) {
-				ts.p.disableClick = false;
-				return false;
-			}
-			var s = "th>div.ui-jqgrid-sortable",r,d;
-			if (!ts.p.viewsortcols[2]) { s = "th>div>span>span.ui-grid-ico-sort"; }
-			var t = $(e.target).closest(s);
-			if (t.length != 1) { return; }
-			var ci = getColumnHeaderIndex(this);
-			if (!ts.p.viewsortcols[2]) { r=true;d=t.attr("sort"); }
-			sortData( $('div',this)[0].id, ci, r, d);
-			return false;
-		});
-		if (ts.p.sortable && $.fn.sortable) {
-			try {
-				$(ts).jqGrid("sortableColumns", thr);
-			} catch (e){}
-		}
-		if(ts.p.footerrow) { tfoot += "</tr></tbody></table>"; }
-		firstr += "</tr>";
-		tbody = document.createElement("tbody");
-		this.appendChild(tbody);
-		$(this).addClass('ui-jqgrid-btable').append(firstr);
-		firstr = null;
-		var hTable = $("<table class='ui-jqgrid-htable' style='width:"+ts.p.tblwidth+"px' role='grid' aria-labelledby='gbox_"+this.id+"' cellspacing='0' cellpadding='0' border='0'></table>").append(thead),
-		hg = (ts.p.caption && ts.p.hiddengrid===true) ? true : false,
-		hb = $("<div class='ui-jqgrid-hbox" + (dir=="rtl" ? "-rtl" : "" )+"'></div>");
-		thead = null;
-		grid.hDiv = document.createElement("div");
-		$(grid.hDiv)
-			.css({ width: grid.width+"px"})
-			.addClass("ui-state-default ui-jqgrid-hdiv")
-			.append(hb);
-		$(hb).append(hTable);
-		hTable = null;
-		if(hg) { $(grid.hDiv).hide(); }
-		if(ts.p.pager){
-			// TBD -- escape ts.p.pager here?
-			if(typeof ts.p.pager == "string") {if(ts.p.pager.substr(0,1) !="#") { ts.p.pager = "#"+ts.p.pager;} }
-			else { ts.p.pager = "#"+ $(ts.p.pager).attr("id");}
-			$(ts.p.pager).css({width: grid.width+"px"}).appendTo(eg).addClass('ui-state-default ui-jqgrid-pager ui-corner-bottom');
-			if(hg) {$(ts.p.pager).hide();}
-			setPager(ts.p.pager,'');
-		}
-		if( ts.p.cellEdit === false && ts.p.hoverrows === true) {
-		$(ts).bind('mouseover',function(e) {
-			ptr = $(e.target).closest("tr.jqgrow");
-			if($(ptr).attr("class") !== "ui-subgrid") {
-				$(ptr).addClass("ui-state-hover");
-			}
-		}).bind('mouseout',function(e) {
-			ptr = $(e.target).closest("tr.jqgrow");
-			$(ptr).removeClass("ui-state-hover");
-		});
-		}
-		var ri,ci, tdHtml;
-		$(ts).before(grid.hDiv).click(function(e) {
-			td = e.target;
-			ptr = $(td,ts.rows).closest("tr.jqgrow");
-			if($(ptr).length === 0 || ptr[0].className.indexOf( 'ui-state-disabled' ) > -1 || ($(td,ts).closest("table.ui-jqgrid-btable").attr('id') || '').replace("_frozen","") !== ts.id ) {
-				return this;
-			}
-			var scb = $(td).hasClass("cbox"),
-			cSel = $(ts).triggerHandler("jqGridBeforeSelectRow", [ptr[0].id, e]);
-			cSel = (cSel === false || cSel === 'stop') ? false : true;
-			if(cSel && $.isFunction(ts.p.beforeSelectRow)) { cSel = ts.p.beforeSelectRow.call(ts,ptr[0].id, e); }
-			if (td.tagName == 'A' || ((td.tagName == 'INPUT' || td.tagName == 'TEXTAREA' || td.tagName == 'OPTION' || td.tagName == 'SELECT' ) && !scb) ) { return; }
-			if(cSel === true) {
-				ri = ptr[0].id;
-				ci = $.jgrid.getCellIndex(td);
-				tdHtml = $(td).closest("td,th").html();
-				$(ts).triggerHandler("jqGridCellSelect", [ri,ci,tdHtml,e]);
-				if($.isFunction(ts.p.onCellSelect)) {
-					ts.p.onCellSelect.call(ts,ri,ci,tdHtml,e);
-				}
-				if(ts.p.cellEdit === true) {
-					if(ts.p.multiselect && scb){
-						$(ts).jqGrid("setSelection", ri ,true,e);
-					} else {
-						ri = ptr[0].rowIndex;
-						try {$(ts).jqGrid("editCell",ri,ci,true);} catch (_) {}
-					}
-				} else if ( !ts.p.multikey ) {
-					if(ts.p.multiselect && ts.p.multiboxonly) {
-						if(scb){$(ts).jqGrid("setSelection",ri,true,e);}
-						else {
-							var frz = ts.p.frozenColumns ? ts.p.id+"_frozen" : "";
-							$(ts.p.selarrrow).each(function(i,n){
-								var ind = ts.rows.namedItem(n);
-								$(ind).removeClass("ui-state-highlight");
-								$("#jqg_"+$.jgrid.jqID(ts.p.id)+"_"+$.jgrid.jqID(n))[ts.p.useProp ? 'prop': 'attr']("checked", false);
-								if(frz) {
-									$("#"+$.jgrid.jqID(n), "#"+$.jgrid.jqID(frz)).removeClass("ui-state-highlight");
-									$("#jqg_"+$.jgrid.jqID(ts.p.id)+"_"+$.jgrid.jqID(n), "#"+$.jgrid.jqID(frz))[ts.p.useProp ? 'prop': 'attr']("checked", false);
-								}
-							});
-							ts.p.selarrrow = [];
-							$(ts).jqGrid("setSelection",ri,true,e);
-						}
-					} else {
-						$(ts).jqGrid("setSelection",ri,true,e);
-					}
-				} else {
-					if(e[ts.p.multikey]) {
-						$(ts).jqGrid("setSelection",ri,true,e);
-					} else if(ts.p.multiselect && scb) {
-						scb = $("#jqg_"+$.jgrid.jqID(ts.p.id)+"_"+ri).is(":checked");
-						$("#jqg_"+$.jgrid.jqID(ts.p.id)+"_"+ri)[ts.p.useProp ? 'prop' : 'attr']("checked", scb);
-					}
-				}
-			}
-		}).bind('reloadGrid', function(e,opts) {
-			if(ts.p.treeGrid ===true) {	ts.p.datatype = ts.p.treedatatype;}
-			if (opts && opts.current) {
-				ts.grid.selectionPreserver(ts);
-			}
-			if(ts.p.datatype=="local"){ $(ts).jqGrid("resetSelection");  if(ts.p.data.length) { refreshIndex();} }
-			else if(!ts.p.treeGrid) {
-				ts.p.selrow=null;
-				if(ts.p.multiselect) {ts.p.selarrrow =[];setHeadCheckBox(false);}
-				ts.p.savedRow = [];
-			}
-			if(ts.p.scroll) {emptyRows.call(ts, true, false);}
-			if (opts && opts.page) {
-				var page = opts.page;
-				if (page > ts.p.lastpage) { page = ts.p.lastpage; }
-				if (page < 1) { page = 1; }
-				ts.p.page = page;
-				if (ts.grid.prevRowHeight) {
-					ts.grid.bDiv.scrollTop = (page - 1) * ts.grid.prevRowHeight * ts.p.rowNum;
-				} else {
-					ts.grid.bDiv.scrollTop = 0;
-				}
-			}
-			if (ts.grid.prevRowHeight && ts.p.scroll) {
-				delete ts.p.lastpage;
-				ts.grid.populateVisible();
-			} else {
-				ts.grid.populate();
-			}
-			if(ts.p._inlinenav===true) {$(ts).jqGrid('showAddEditButtons');}
-			return false;
-		})
-		.dblclick(function(e) {
-			td = e.target;
-			ptr = $(td,ts.rows).closest("tr.jqgrow");
-			if($(ptr).length === 0 ){return;}
-			ri = ptr[0].rowIndex;
-			ci = $.jgrid.getCellIndex(td);
-			$(ts).triggerHandler("jqGridDblClickRow", [$(ptr).attr("id"),ri,ci,e]);
-			if ($.isFunction(this.p.ondblClickRow)) { ts.p.ondblClickRow.call(ts,$(ptr).attr("id"),ri,ci, e); }
-		})
-		.bind('contextmenu', function(e) {
-			td = e.target;
-			ptr = $(td,ts.rows).closest("tr.jqgrow");
-			if($(ptr).length === 0 ){return;}
-			if(!ts.p.multiselect) {	$(ts).jqGrid("setSelection",ptr[0].id,true,e);	}
-			ri = ptr[0].rowIndex;
-			ci = $.jgrid.getCellIndex(td);
-			$(ts).triggerHandler("jqGridRightClickRow", [$(ptr).attr("id"),ri,ci,e]);
-			if ($.isFunction(this.p.onRightClickRow)) { ts.p.onRightClickRow.call(ts,$(ptr).attr("id"),ri,ci, e); }
-		});
-		grid.bDiv = document.createElement("div");
-		if(isMSIE) { if(String(ts.p.height).toLowerCase() === "auto") { ts.p.height = "100%"; } }
-		$(grid.bDiv)
-			.append($('<div style="position:relative;'+(isMSIE && $.browser.version < 8 ? "height:0.01%;" : "")+'"></div>').append('<div></div>').append(this))
-			.addClass("ui-jqgrid-bdiv")
-			.css({ height: ts.p.height+(isNaN(ts.p.height)?"":"px"), width: (grid.width)+"px"})
-			.scroll(grid.scrollGrid);
-		$("table:first",grid.bDiv).css({width:ts.p.tblwidth+"px"});
-		if( isMSIE ) {
-			if( $("tbody",this).size() == 2 ) { $("tbody:gt(0)",this).remove();}
-			if( ts.p.multikey) {$(grid.bDiv).bind("selectstart",function(){return false;});}
-		} else {
-			if( ts.p.multikey) {$(grid.bDiv).bind("mousedown",function(){return false;});}
-		}
-		if(hg) {$(grid.bDiv).hide();}
-		grid.cDiv = document.createElement("div");
-		var arf = ts.p.hidegrid===true ? $("<a role='link' href='javascript:void(0)'/>").addClass('ui-jqgrid-titlebar-close HeaderButton').hover(
-			function(){ arf.addClass('ui-state-hover');},
-			function() {arf.removeClass('ui-state-hover');})
-		.append("<span class='ui-icon ui-icon-circle-triangle-n'></span>").css((dir=="rtl"?"left":"right"),"0px") : "";
-		$(grid.cDiv).append(arf).append("<span class='ui-jqgrid-title"+(dir=="rtl" ? "-rtl" :"" )+"'>"+ts.p.caption+"</span>")
-		.addClass("ui-jqgrid-titlebar ui-widget-header ui-corner-top ui-helper-clearfix");
-		$(grid.cDiv).insertBefore(grid.hDiv);
-		if( ts.p.toolbar[0] ) {
-			grid.uDiv = document.createElement("div");
-			if(ts.p.toolbar[1] == "top") {$(grid.uDiv).insertBefore(grid.hDiv);}
-			else if (ts.p.toolbar[1]=="bottom" ) {$(grid.uDiv).insertAfter(grid.hDiv);}
-			if(ts.p.toolbar[1]=="both") {
-				grid.ubDiv = document.createElement("div");
-				$(grid.uDiv).insertBefore(grid.hDiv).addClass("ui-userdata ui-state-default").attr("id","t_"+this.id);
-				$(grid.ubDiv).insertAfter(grid.hDiv).addClass("ui-userdata ui-state-default").attr("id","tb_"+this.id);
-				if(hg)  {$(grid.ubDiv).hide();}
-			} else {
-				$(grid.uDiv).width(grid.width).addClass("ui-userdata ui-state-default").attr("id","t_"+this.id);
-			}
-			if(hg) {$(grid.uDiv).hide();}
-		}
-		if(ts.p.toppager) {
-			ts.p.toppager = $.jgrid.jqID(ts.p.id)+"_toppager";
-			grid.topDiv = $("<div id='"+ts.p.toppager+"'></div>")[0];
-			ts.p.toppager = "#"+ts.p.toppager;
-			$(grid.topDiv).insertBefore(grid.hDiv).addClass('ui-state-default ui-jqgrid-toppager').width(grid.width);
-			setPager(ts.p.toppager,'_t');
-		}
-		if(ts.p.footerrow) {
-			grid.sDiv = $("<div class='ui-jqgrid-sdiv'></div>")[0];
-			hb = $("<div class='ui-jqgrid-hbox"+(dir=="rtl"?"-rtl":"")+"'></div>");
-			$(grid.sDiv).append(hb).insertAfter(grid.hDiv).width(grid.width);
-			$(hb).append(tfoot);
-			grid.footers = $(".ui-jqgrid-ftable",grid.sDiv)[0].rows[0].cells;
-			if(ts.p.rownumbers) { grid.footers[0].className = 'ui-state-default jqgrid-rownum'; }
-			if(hg) {$(grid.sDiv).hide();}
-		}
-		hb = null;
-		if(ts.p.caption) {
-			var tdt = ts.p.datatype;
-			if(ts.p.hidegrid===true) {
-				$(".ui-jqgrid-titlebar-close",grid.cDiv).click( function(e){
-					var onHdCl = $.isFunction(ts.p.onHeaderClick),
-					elems = ".ui-jqgrid-bdiv, .ui-jqgrid-hdiv, .ui-jqgrid-pager, .ui-jqgrid-sdiv",
-					counter, self = this;
-					if(ts.p.toolbar[0]===true) {
-						if( ts.p.toolbar[1]=='both') {
-							elems += ', #' + $(grid.ubDiv).attr('id');
-						}
-						elems += ', #' + $(grid.uDiv).attr('id');
-					}
-					counter = $(elems,"#gview_"+$.jgrid.jqID(ts.p.id)).length;
-
-					if(ts.p.gridstate == 'visible') {
-						$(elems,"#gbox_"+$.jgrid.jqID(ts.p.id)).slideUp("fast", function() {
-							counter--;
-							if (counter === 0) {
-								$("span",self).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-s");
-								ts.p.gridstate = 'hidden';
-								if($("#gbox_"+$.jgrid.jqID(ts.p.id)).hasClass("ui-resizable")) { $(".ui-resizable-handle","#gbox_"+$.jgrid.jqID(ts.p.id)).hide(); }
-								$(ts).triggerHandler("jqGridHeaderClick", [ts.p.gridstate,e]);
-								if(onHdCl) {if(!hg) {ts.p.onHeaderClick.call(ts,ts.p.gridstate,e);}}
-							}
-						});
-					} else if(ts.p.gridstate == 'hidden'){
-						$(elems,"#gbox_"+$.jgrid.jqID(ts.p.id)).slideDown("fast", function() {
-							counter--;
-							if (counter === 0) {
-								$("span",self).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-n");
-								if(hg) {ts.p.datatype = tdt;populate();hg=false;}
-								ts.p.gridstate = 'visible';
-								if($("#gbox_"+$.jgrid.jqID(ts.p.id)).hasClass("ui-resizable")) { $(".ui-resizable-handle","#gbox_"+$.jgrid.jqID(ts.p.id)).show(); }
-								$(ts).triggerHandler("jqGridHeaderClick", [ts.p.gridstate,e]);
-								if(onHdCl) {if(!hg) {ts.p.onHeaderClick.call(ts,ts.p.gridstate,e);}}
-							}
-						});
-					}
-					return false;
-				});
-				if(hg) {ts.p.datatype="local"; $(".ui-jqgrid-titlebar-close",grid.cDiv).trigger("click");}
-			}
-		} else {$(grid.cDiv).hide();}
-		$(grid.hDiv).after(grid.bDiv)
-		.mousemove(function (e) {
-			if(grid.resizing){grid.dragMove(e);return false;}
-		});
-		$(".ui-jqgrid-labels",grid.hDiv).bind("selectstart", function () { return false; });
-		$(document).mouseup(function () {
-			if(grid.resizing) {	grid.dragEnd(); return false;}
-			return true;
-		});
-		ts.formatCol = formatCol;
-		ts.sortData = sortData;
-		ts.updatepager = updatepager;
-		ts.refreshIndex = refreshIndex;
-		ts.setHeadCheckBox = setHeadCheckBox;
-		ts.constructTr = constructTr;
-		ts.formatter = function ( rowId, cellval , colpos, rwdat, act){return formatter(rowId, cellval , colpos, rwdat, act);};
-		$.extend(grid,{populate : populate, emptyRows: emptyRows});
-		this.grid = grid;
-		ts.addXmlData = function(d) {addXmlData(d,ts.grid.bDiv);};
-		ts.addJSONData = function(d) {addJSONData(d,ts.grid.bDiv);};
-		this.grid.cols = this.rows[0].cells;
-
-		populate();ts.p.hiddengrid=false;
-		$(window).unload(function () {
-			ts = null;
-		});
-	});
+    "use strict";
+    $.jgrid = $.jgrid || {};
+    $.extend($.jgrid, {
+        version: "4.4.0",
+        htmlDecode: function (value) {
+            if (value && (value == '&nbsp;' || value == '&#160;' || (value.length === 1 && value.charCodeAt(0) === 160))) {
+                return "";
+            }
+            return !value ? value : String(value).replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"').replace(/&amp;/g, "&");
+        },
+        htmlEncode: function (value) {
+            return !value ? value : String(value).replace(/&/g, "&amp;").replace(/\"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+        },
+        format: function (format) { //jqgformat
+            var args = $.makeArray(arguments).slice(1);
+            if (format === undefined) {
+                format = "";
+            }
+            return format.replace(/\{(\d+)\}/g, function (m, i) {
+                return args[i];
+            });
+        },
+        getCellIndex: function (cell) {
+            var c = $(cell);
+            if (c.is('tr')) {
+                return -1;
+            }
+            c = (!c.is('td') && !c.is('th') ? c.closest("td,th") : c)[0];
+            if ($.browser.msie) {
+                return $.inArray(c, c.parentNode.cells);
+            }
+            return c.cellIndex;
+        },
+        stripHtml: function (v) {
+            v = v + "";
+            var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
+            if (v) {
+                v = v.replace(regexp, "");
+                return (v && v !== '&nbsp;' && v !== '&#160;') ? v.replace(/\"/g, "'") : "";
+            } else {
+                return v;
+            }
+        },
+        stripPref: function (pref, id) {
+            var obj = $.type(pref);
+            if (obj == "string" || obj == "number") {
+                pref = String(pref);
+                id = pref !== "" ? String(id).replace(String(pref), "") : id;
+            }
+            return id;
+        },
+        stringToDoc: function (xmlString) {
+            var xmlDoc;
+            if (typeof xmlString !== 'string') {
+                return xmlString;
+            }
+            try {
+                var parser = new DOMParser();
+                xmlDoc = parser.parseFromString(xmlString, "text/xml");
+            }
+            catch (e) {
+                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
+                xmlDoc.async = false;
+                xmlDoc.loadXML(xmlString);
+            }
+            return (xmlDoc && xmlDoc.documentElement && xmlDoc.documentElement.tagName != 'parsererror') ? xmlDoc : null;
+        },
+        parse: function (jsonString) {
+            var js = jsonString;
+            if (js.substr(0, 9) == "while(1);") {
+                js = js.substr(9);
+            }
+            if (js.substr(0, 2) == "/*") {
+                js = js.substr(2, js.length - 4);
+            }
+            if (!js) {
+                js = "{}";
+            }
+            return ($.jgrid.useJSON === true && typeof (JSON) === 'object' && typeof (JSON.parse) === 'function') ?
+                JSON.parse(js) :
+                eval('(' + js + ')');
+        },
+        parseDate: function (format, date) {
+            var tsp = {m: 1, d: 1, y: 1970, h: 0, i: 0, s: 0, u: 0}, k, hl, dM, regdate = /[\\\/:_;.,\t\T\s-]/;
+            if (date && date !== null && date !== undefined) {
+                date = $.trim(date);
+                date = date.split(regdate);
+                if ($.jgrid.formatter.date.masks[format] !== undefined) {
+                    format = $.jgrid.formatter.date.masks[format];
+                }
+                format = format.split(regdate);
+                var dfmt = $.jgrid.formatter.date.monthNames;
+                var afmt = $.jgrid.formatter.date.AmPm;
+                var h12to24 = function (ampm, h) {
+                    if (ampm === 0) {
+                        if (h === 12) {
+                            h = 0;
+                        }
+                    }
+                    else {
+                        if (h !== 12) {
+                            h += 12;
+                        }
+                    }
+                    return h;
+                };
+                for (k = 0, hl = format.length; k < hl; k++) {
+                    if (format[k] == 'M') {
+                        dM = $.inArray(date[k], dfmt);
+                        if (dM !== -1 && dM < 12) {
+                            date[k] = dM + 1;
+                            tsp.m = date[k];
+                        }
+                    }
+                    if (format[k] == 'F') {
+                        dM = $.inArray(date[k], dfmt);
+                        if (dM !== -1 && dM > 11) {
+                            date[k] = dM + 1 - 12;
+                            tsp.m = date[k];
+                        }
+                    }
+                    if (format[k] == 'a') {
+                        dM = $.inArray(date[k], afmt);
+                        if (dM !== -1 && dM < 2 && date[k] == afmt[dM]) {
+                            date[k] = dM;
+                            tsp.h = h12to24(date[k], tsp.h);
+                        }
+                    }
+                    if (format[k] == 'A') {
+                        dM = $.inArray(date[k], afmt);
+                        if (dM !== -1 && dM > 1 && date[k] == afmt[dM]) {
+                            date[k] = dM - 2;
+                            tsp.h = h12to24(date[k], tsp.h);
+                        }
+                    }
+                    if (date[k] !== undefined) {
+                        tsp[format[k].toLowerCase()] = parseInt(date[k], 10);
+                    }
+                }
+                tsp.m = parseInt(tsp.m, 10) - 1;
+                var ty = tsp.y;
+                if (ty >= 70 && ty <= 99) {
+                    tsp.y = 1900 + tsp.y;
+                }
+                else if (ty >= 0 && ty <= 69) {
+                    tsp.y = 2000 + tsp.y;
+                }
+                if (tsp.j !== undefined) {
+                    tsp.d = tsp.j;
+                }
+                if (tsp.n !== undefined) {
+                    tsp.m = parseInt(tsp.n, 10) - 1;
+                }
+            }
+            return new Date(tsp.y, tsp.m, tsp.d, tsp.h, tsp.i, tsp.s, tsp.u);
+        },
+        jqID: function (sid) {
+            return String(sid).replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g, "\\$&");
+        },
+        guid: 1,
+        uidPref: 'jqg',
+        randId: function (prefix) {
+            return (prefix ? prefix : $.jgrid.uidPref) + ($.jgrid.guid++);
+        },
+        getAccessor: function (obj, expr) {
+            var ret, p, prm = [], i;
+            if (typeof expr === 'function') {
+                return expr(obj);
+            }
+            ret = obj[expr];
+            if (ret === undefined) {
+                try {
+                    if (typeof expr === 'string') {
+                        prm = expr.split('.');
+                    }
+                    i = prm.length;
+                    if (i) {
+                        ret = obj;
+                        while (ret && i--) {
+                            p = prm.shift();
+                            ret = ret[p];
+                        }
+                    }
+                } catch (e) {
+                }
+            }
+            return ret;
+        },
+        getXmlData: function (obj, expr, returnObj) {
+            var ret, m = typeof (expr) === 'string' ? expr.match(/^(.*)\[(\w+)\]$/) : null;
+            if (typeof (expr) === 'function') {
+                return expr(obj);
+            }
+            if (m && m[2]) {
+                // m[2] is the attribute selector
+                // m[1] is an optional element selector
+                // examples: "[id]", "rows[page]"
+                return m[1] ? $(m[1], obj).attr(m[2]) : $(obj).attr(m[2]);
+            } else {
+                ret = $(expr, obj);
+                if (returnObj) {
+                    return ret;
+                }
+                //$(expr, obj).filter(':last'); // we use ':last' to be more compatible with old version of jqGrid
+                return ret.length > 0 ? $(ret).text() : undefined;
+            }
+        },
+        cellWidth: function () {
+            var $testDiv = $("<div class='ui-jqgrid' style='left:10000px'><table class='ui-jqgrid-btable' style='width:5px;'><tr class='jqgrow'><td style='width:5px;'></td></tr></table></div>"),
+                testCell = $testDiv.appendTo("body")
+                    .find("td")
+                    .width();
+            $testDiv.remove();
+            return testCell !== 5;
+        },
+        ajaxOptions: {},
+        from: function (source) {
+            // Original Author Hugo Bonacci
+            // License MIT http://jlinq.codeplex.com/license
+            var QueryObject = function (d, q) {
+                if (typeof(d) == "string") {
+                    d = $.data(d);
+                }
+                var self = this,
+                    _data = d,
+                    _usecase = true,
+                    _trim = false,
+                    _query = q,
+                    _stripNum = /[\$,%]/g,
+                    _lastCommand = null,
+                    _lastField = null,
+                    _orDepth = 0,
+                    _negate = false,
+                    _queuedOperator = "",
+                    _sorting = [],
+                    _useProperties = true;
+                if (typeof(d) == "object" && d.push) {
+                    if (d.length > 0) {
+                        if (typeof(d[0]) != "object") {
+                            _useProperties = false;
+                        } else {
+                            _useProperties = true;
+                        }
+                    }
+                } else {
+                    throw "data provides is not an array";
+                }
+                this._hasData = function () {
+                    return _data === null ? false : _data.length === 0 ? false : true;
+                };
+                this._getStr = function (s) {
+                    var phrase = [];
+                    if (_trim) {
+                        phrase.push("jQuery.trim(");
+                    }
+                    phrase.push("String(" + s + ")");
+                    if (_trim) {
+                        phrase.push(")");
+                    }
+                    if (!_usecase) {
+                        phrase.push(".toLowerCase()");
+                    }
+                    return phrase.join("");
+                };
+                this._strComp = function (val) {
+                    if (typeof(val) == "string") {
+                        return".toString()";
+                    } else {
+                        return"";
+                    }
+                };
+                this._group = function (f, u) {
+                    return({field: f.toString(), unique: u, items: []});
+                };
+                this._toStr = function (phrase) {
+                    if (_trim) {
+                        phrase = $.trim(phrase);
+                    }
+                    phrase = phrase.toString().replace(/\\/g, '\\\\').replace(/\"/g, '\\"');
+                    return _usecase ? phrase : phrase.toLowerCase();
+                };
+                this._funcLoop = function (func) {
+                    var results = [];
+                    $.each(_data, function (i, v) {
+                        results.push(func(v));
+                    });
+                    return results;
+                };
+                this._append = function (s) {
+                    var i;
+                    if (_query === null) {
+                        _query = "";
+                    } else {
+                        _query += _queuedOperator === "" ? " && " : _queuedOperator;
+                    }
+                    for (i = 0; i < _orDepth; i++) {
+                        _query += "(";
+                    }
+                    if (_negate) {
+                        _query += "!";
+                    }
+                    _query += "(" + s + ")";
+                    _negate = false;
+                    _queuedOperator = "";
+                    _orDepth = 0;
+                };
+                this._setCommand = function (f, c) {
+                    _lastCommand = f;
+                    _lastField = c;
+                };
+                this._resetNegate = function () {
+                    _negate = false;
+                };
+                this._repeatCommand = function (f, v) {
+                    if (_lastCommand === null) {
+                        return self;
+                    }
+                    if (f !== null && v !== null) {
+                        return _lastCommand(f, v);
+                    }
+                    if (_lastField === null) {
+                        return _lastCommand(f);
+                    }
+                    if (!_useProperties) {
+                        return _lastCommand(f);
+                    }
+                    return _lastCommand(_lastField, f);
+                };
+                this._equals = function (a, b) {
+                    return(self._compare(a, b, 1) === 0);
+                };
+                this._compare = function (a, b, d) {
+                    var toString = Object.prototype.toString;
+                    if (d === undefined) {
+                        d = 1;
+                    }
+                    if (a === undefined) {
+                        a = null;
+                    }
+                    if (b === undefined) {
+                        b = null;
+                    }
+                    if (a === null && b === null) {
+                        return 0;
+                    }
+                    if (a === null && b !== null) {
+                        return 1;
+                    }
+                    if (a !== null && b === null) {
+                        return -1;
+                    }
+                    if (toString.call(a) === '[object Date]' && toString.call(b) === '[object Date]') {
+                        if (a < b) {
+                            return -d;
+                        }
+                        if (a > b) {
+                            return d;
+                        }
+                        return 0;
+                    }
+                    if (!_usecase && typeof(a) !== "number" && typeof(b) !== "number") {
+                        a = String(a).toLowerCase();
+                        b = String(b).toLowerCase();
+                    }
+                    if (a < b) {
+                        return -d;
+                    }
+                    if (a > b) {
+                        return d;
+                    }
+                    return 0;
+                };
+                this._performSort = function () {
+                    if (_sorting.length === 0) {
+                        return;
+                    }
+                    _data = self._doSort(_data, 0);
+                };
+                this._doSort = function (d, q) {
+                    var by = _sorting[q].by,
+                        dir = _sorting[q].dir,
+                        type = _sorting[q].type,
+                        dfmt = _sorting[q].datefmt;
+                    if (q == _sorting.length - 1) {
+                        return self._getOrder(d, by, dir, type, dfmt);
+                    }
+                    q++;
+                    var values = self._getGroup(d, by, dir, type, dfmt);
+                    var results = [];
+                    for (var i = 0; i < values.length; i++) {
+                        var sorted = self._doSort(values[i].items, q);
+                        for (var j = 0; j < sorted.length; j++) {
+                            results.push(sorted[j]);
+                        }
+                    }
+                    return results;
+                };
+                this._getOrder = function (data, by, dir, type, dfmt) {
+                    var sortData = [], _sortData = [], newDir = dir == "a" ? 1 : -1, i, ab, j,
+                        findSortKey;
+
+                    if (type === undefined) {
+                        type = "text";
+                    }
+                    if (type == 'float' || type == 'number' || type == 'currency' || type == 'numeric') {
+                        findSortKey = function ($cell) {
+                            var key = parseFloat(String($cell).replace(_stripNum, ''));
+                            return isNaN(key) ? 0.00 : key;
+                        };
+                    } else if (type == 'int' || type == 'integer') {
+                        findSortKey = function ($cell) {
+                            return $cell ? parseFloat(String($cell).replace(_stripNum, '')) : 0;
+                        };
+                    } else if (type == 'date' || type == 'datetime') {
+                        findSortKey = function ($cell) {
+                            return $.jgrid.parseDate(dfmt, $cell).getTime();
+                        };
+                    } else if ($.isFunction(type)) {
+                        findSortKey = type;
+                    } else {
+                        findSortKey = function ($cell) {
+                            if (!$cell) {
+                                $cell = "";
+                            }
+                            return $.trim(String($cell).toUpperCase());
+                        };
+                    }
+                    $.each(data, function (i, v) {
+                        ab = by !== "" ? $.jgrid.getAccessor(v, by) : v;
+                        if (ab === undefined) {
+                            ab = "";
+                        }
+                        ab = findSortKey(ab, v);
+                        _sortData.push({ 'vSort': ab, 'index': i});
+                    });
+
+                    _sortData.sort(function (a, b) {
+                        a = a.vSort;
+                        b = b.vSort;
+                        return self._compare(a, b, newDir);
+                    });
+                    j = 0;
+                    var nrec = data.length;
+                    // overhead, but we do not change the original data.
+                    while (j < nrec) {
+                        i = _sortData[j].index;
+                        sortData.push(data[i]);
+                        j++;
+                    }
+                    return sortData;
+                };
+                this._getGroup = function (data, by, dir, type, dfmt) {
+                    var results = [],
+                        group = null,
+                        last = null, val;
+                    $.each(self._getOrder(data, by, dir, type, dfmt), function (i, v) {
+                        val = $.jgrid.getAccessor(v, by);
+                        if (val === undefined) {
+                            val = "";
+                        }
+                        if (!self._equals(last, val)) {
+                            last = val;
+                            if (group !== null) {
+                                results.push(group);
+                            }
+                            group = self._group(by, val);
+                        }
+                        group.items.push(v);
+                    });
+                    if (group !== null) {
+                        results.push(group);
+                    }
+                    return results;
+                };
+                this.ignoreCase = function () {
+                    _usecase = false;
+                    return self;
+                };
+                this.useCase = function () {
+                    _usecase = true;
+                    return self;
+                };
+                this.trim = function () {
+                    _trim = true;
+                    return self;
+                };
+                this.noTrim = function () {
+                    _trim = false;
+                    return self;
+                };
+                this.execute = function () {
+                    var match = _query, results = [];
+                    if (match === null) {
+                        return self;
+                    }
+                    $.each(_data, function () {
+                        if (eval(match)) {
+                            results.push(this);
+                        }
+                    });
+                    _data = results;
+                    return self;
+                };
+                this.data = function () {
+                    return _data;
+                };
+                this.select = function (f) {
+                    self._performSort();
+                    if (!self._hasData()) {
+                        return[];
+                    }
+                    self.execute();
+                    if ($.isFunction(f)) {
+                        var results = [];
+                        $.each(_data, function (i, v) {
+                            results.push(f(v));
+                        });
+                        return results;
+                    }
+                    return _data;
+                };
+                this.hasMatch = function () {
+                    if (!self._hasData()) {
+                        return false;
+                    }
+                    self.execute();
+                    return _data.length > 0;
+                };
+                this.andNot = function (f, v, x) {
+                    _negate = !_negate;
+                    return self.and(f, v, x);
+                };
+                this.orNot = function (f, v, x) {
+                    _negate = !_negate;
+                    return self.or(f, v, x);
+                };
+                this.not = function (f, v, x) {
+                    return self.andNot(f, v, x);
+                };
+                this.and = function (f, v, x) {
+                    _queuedOperator = " && ";
+                    if (f === undefined) {
+                        return self;
+                    }
+                    return self._repeatCommand(f, v, x);
+                };
+                this.or = function (f, v, x) {
+                    _queuedOperator = " || ";
+                    if (f === undefined) {
+                        return self;
+                    }
+                    return self._repeatCommand(f, v, x);
+                };
+                this.orBegin = function () {
+                    _orDepth++;
+                    return self;
+                };
+                this.orEnd = function () {
+                    if (_query !== null) {
+                        _query += ")";
+                    }
+                    return self;
+                };
+                this.isNot = function (f) {
+                    _negate = !_negate;
+                    return self.is(f);
+                };
+                this.is = function (f) {
+                    self._append('this.' + f);
+                    self._resetNegate();
+                    return self;
+                };
+                this._compareValues = function (func, f, v, how, t) {
+                    var fld;
+                    if (_useProperties) {
+                        fld = 'jQuery.jgrid.getAccessor(this,\'' + f + '\')';
+                    } else {
+                        fld = 'this';
+                    }
+                    if (v === undefined) {
+                        v = null;
+                    }
+                    //var val=v===null?f:v,
+                    var val = v,
+                        swst = t.stype === undefined ? "text" : t.stype;
+                    if (v !== null) {
+                        switch (swst) {
+                            case 'int':
+                            case 'integer':
+                                val = (isNaN(Number(val)) || val === "") ? '0' : val; // To be fixed with more inteligent code
+                                fld = 'parseInt(' + fld + ',10)';
+                                val = 'parseInt(' + val + ',10)';
+                                break;
+                            case 'float':
+                            case 'number':
+                            case 'numeric':
+                                val = String(val).replace(_stripNum, '');
+                                val = (isNaN(Number(val)) || val === "") ? '0' : val; // To be fixed with more inteligent code
+                                fld = 'parseFloat(' + fld + ')';
+                                val = 'parseFloat(' + val + ')';
+                                break;
+                            case 'date':
+                            case 'datetime':
+                                val = String($.jgrid.parseDate(t.newfmt || 'Y-m-d', val).getTime());
+                                fld = 'jQuery.jgrid.parseDate("' + t.srcfmt + '",' + fld + ').getTime()';
+                                break;
+                            default :
+                                fld = self._getStr(fld);
+                                val = self._getStr('"' + self._toStr(val) + '"');
+                        }
+                    }
+                    self._append(fld + ' ' + how + ' ' + val);
+                    self._setCommand(func, f);
+                    self._resetNegate();
+                    return self;
+                };
+                this.equals = function (f, v, t) {
+                    return self._compareValues(self.equals, f, v, "==", t);
+                };
+                this.notEquals = function (f, v, t) {
+                    return self._compareValues(self.equals, f, v, "!==", t);
+                };
+                this.isNull = function (f, v, t) {
+                    return self._compareValues(self.equals, f, null, "===", t);
+                };
+                this.greater = function (f, v, t) {
+                    return self._compareValues(self.greater, f, v, ">", t);
+                };
+                this.less = function (f, v, t) {
+                    return self._compareValues(self.less, f, v, "<", t);
+                };
+                this.greaterOrEquals = function (f, v, t) {
+                    return self._compareValues(self.greaterOrEquals, f, v, ">=", t);
+                };
+                this.lessOrEquals = function (f, v, t) {
+                    return self._compareValues(self.lessOrEquals, f, v, "<=", t);
+                };
+                this.startsWith = function (f, v) {
+                    var val = (v === undefined || v === null) ? f : v,
+                        length = _trim ? $.trim(val.toString()).length : val.toString().length;
+                    if (_useProperties) {
+                        self._append(self._getStr('jQuery.jgrid.getAccessor(this,\'' + f + '\')') + '.substr(0,' + length + ') == ' + self._getStr('"' + self._toStr(v) + '"'));
+                    } else {
+                        length = _trim ? $.trim(v.toString()).length : v.toString().length;
+                        self._append(self._getStr('this') + '.substr(0,' + length + ') == ' + self._getStr('"' + self._toStr(f) + '"'));
+                    }
+                    self._setCommand(self.startsWith, f);
+                    self._resetNegate();
+                    return self;
+                };
+                this.endsWith = function (f, v) {
+                    var val = (v === undefined || v === null) ? f : v,
+                        length = _trim ? $.trim(val.toString()).length : val.toString().length;
+                    if (_useProperties) {
+                        self._append(self._getStr('jQuery.jgrid.getAccessor(this,\'' + f + '\')') + '.substr(' + self._getStr('jQuery.jgrid.getAccessor(this,\'' + f + '\')') + '.length-' + length + ',' + length + ') == "' + self._toStr(v) + '"');
+                    } else {
+                        self._append(self._getStr('this') + '.substr(' + self._getStr('this') + '.length-"' + self._toStr(f) + '".length,"' + self._toStr(f) + '".length) == "' + self._toStr(f) + '"');
+                    }
+                    self._setCommand(self.endsWith, f);
+                    self._resetNegate();
+                    return self;
+                };
+                this.contains = function (f, v) {
+                    if (_useProperties) {
+                        self._append(self._getStr('jQuery.jgrid.getAccessor(this,\'' + f + '\')') + '.indexOf("' + self._toStr(v) + '",0) > -1');
+                    } else {
+                        self._append(self._getStr('this') + '.indexOf("' + self._toStr(f) + '",0) > -1');
+                    }
+                    self._setCommand(self.contains, f);
+                    self._resetNegate();
+                    return self;
+                };
+                this.groupBy = function (by, dir, type, datefmt) {
+                    if (!self._hasData()) {
+                        return null;
+                    }
+                    return self._getGroup(_data, by, dir, type, datefmt);
+                };
+                this.orderBy = function (by, dir, stype, dfmt) {
+                    dir = dir === undefined || dir === null ? "a" : $.trim(dir.toString().toLowerCase());
+                    if (stype === null || stype === undefined) {
+                        stype = "text";
+                    }
+                    if (dfmt === null || dfmt === undefined) {
+                        dfmt = "Y-m-d";
+                    }
+                    if (dir == "desc" || dir == "descending") {
+                        dir = "d";
+                    }
+                    if (dir == "asc" || dir == "ascending") {
+                        dir = "a";
+                    }
+                    _sorting.push({by: by, dir: dir, type: stype, datefmt: dfmt});
+                    return self;
+                };
+                return self;
+            };
+            return new QueryObject(source, null);
+        },
+        extend: function (methods) {
+            $.extend($.fn.jqGrid, methods);
+            if (!this.no_legacy_api) {
+                $.fn.extend(methods);
+            }
+        }
+    });
+
+    $.fn.jqGrid = function (pin) {
+        if (typeof pin == 'string') {
+            //var fn = $.fn.jqGrid[pin];
+            var fn = $.jgrid.getAccessor($.fn.jqGrid, pin);
+            if (!fn) {
+                throw ("jqGrid - No such method: " + pin);
+            }
+            var args = $.makeArray(arguments).slice(1);
+            return fn.apply(this, args);
+        }
+        return this.each(function () {
+            if (this.grid) {
+                return;
+            }
+
+            var p = $.extend(true, {
+                url: "",
+                height: 150,
+                page: 1,
+                rowNum: 20,
+                rowTotal: null,
+                records: 0,
+                pager: "",
+                pgbuttons: true,
+                pginput: true,
+                colModel: [],
+                rowList: [],
+                colNames: [],
+                sortorder: "asc",
+                sortname: "",
+                datatype: "xml",
+                mtype: "GET",
+                altRows: false,
+                selarrrow: [],
+                savedRow: [],
+                shrinkToFit: true,
+                xmlReader: {},
+                jsonReader: {},
+                subGrid: false,
+                subGridModel: [],
+                reccount: 0,
+                lastpage: 0,
+                lastsort: 0,
+                selrow: null,
+                beforeSelectRow: null,
+                onSelectRow: null,
+                onSortCol: null,
+                ondblClickRow: null,
+                onRightClickRow: null,
+                onPaging: null,
+                onSelectAll: null,
+                loadComplete: null,
+                gridComplete: null,
+                loadError: null,
+                loadBeforeSend: null,
+                afterInsertRow: null,
+                beforeRequest: null,
+                beforeProcessing: null,
+                onHeaderClick: null,
+                viewrecords: false,
+                loadonce: false,
+                multiselect: false,
+                multikey: false,
+                editurl: null,
+                search: false,
+                caption: "",
+                hidegrid: true,
+                hiddengrid: false,
+                postData: {},
+                userData: {},
+                treeGrid: false,
+                treeGridModel: 'nested',
+                treeReader: {},
+                treeANode: -1,
+                ExpandColumn: null,
+                tree_root_level: 0,
+                prmNames: {page: "page", rows: "rows", sort: "sidx", order: "sord", search: "_search", nd: "nd", id: "id", oper: "oper", editoper: "edit", addoper: "add", deloper: "del", subgridid: "id", npage: null, totalrows: "totalrows"},
+                forceFit: false,
+                gridstate: "visible",
+                cellEdit: false,
+                cellsubmit: "remote",
+                nv: 0,
+                loadui: "enable",
+                toolbar: [false, ""],
+                scroll: false,
+                multiboxonly: false,
+                deselectAfterSort: true,
+                scrollrows: false,
+                autowidth: false,
+                scrollOffset: 18,
+                cellLayout: 5,
+                subGridWidth: 20,
+                multiselectWidth: 20,
+                gridview: false,
+                rownumWidth: 25,
+                rownumbers: false,
+                pagerpos: 'center',
+                recordpos: 'right',
+                footerrow: false,
+                userDataOnFooter: false,
+                hoverrows: true,
+                altclass: 'ui-priority-secondary',
+                viewsortcols: [false, 'vertical', true],
+                resizeclass: '',
+                autoencode: false,
+                remapColumns: [],
+                ajaxGridOptions: {},
+                direction: "ltr",
+                toppager: false,
+                headertitles: false,
+                scrollTimeout: 40,
+                data: [],
+                _index: {},
+                grouping: false,
+                groupingView: {groupField: [], groupOrder: [], groupText: [], groupColumnShow: [], groupSummary: [], showSummaryOnHide: false, sortitems: [], sortnames: [], summary: [], summaryval: [], plusicon: 'ui-icon-circlesmall-plus', minusicon: 'ui-icon-circlesmall-minus'},
+                ignoreCase: false,
+                cmTemplate: {},
+                idPrefix: ""
+            }, $.jgrid.defaults, pin || {});
+            var ts = this, grid = {
+                headers: [],
+                cols: [],
+                footers: [],
+                dragStart: function (i, x, y) {
+                    this.resizing = { idx: i, startX: x.clientX, sOL: y[0]};
+                    this.hDiv.style.cursor = "col-resize";
+                    this.curGbox = $("#rs_m" + $.jgrid.jqID(p.id), "#gbox_" + $.jgrid.jqID(p.id));
+                    this.curGbox.css({display: "block", left: y[0], top: y[1], height: y[2]});
+                    $(ts).triggerHandler("jqGridResizeStart", [x, i]);
+                    if ($.isFunction(p.resizeStart)) {
+                        p.resizeStart.call(this, x, i);
+                    }
+                    document.onselectstart = function () {
+                        return false;
+                    };
+                },
+                dragMove: function (x) {
+                    if (this.resizing) {
+                        var diff = x.clientX - this.resizing.startX,
+                            h = this.headers[this.resizing.idx],
+                            newWidth = p.direction === "ltr" ? h.width + diff : h.width - diff, hn, nWn;
+                        if (newWidth > 33) {
+                            this.curGbox.css({left: this.resizing.sOL + diff});
+                            if (p.forceFit === true) {
+                                hn = this.headers[this.resizing.idx + p.nv];
+                                nWn = p.direction === "ltr" ? hn.width - diff : hn.width + diff;
+                                if (nWn > 33) {
+                                    h.newWidth = newWidth;
+                                    hn.newWidth = nWn;
+                                }
+                            } else {
+                                this.newWidth = p.direction === "ltr" ? p.tblwidth + diff : p.tblwidth - diff;
+                                h.newWidth = newWidth;
+                            }
+                        }
+                    }
+                },
+                dragEnd: function () {
+                    this.hDiv.style.cursor = "default";
+                    if (this.resizing) {
+                        var idx = this.resizing.idx,
+                            nw = this.headers[idx].newWidth || this.headers[idx].width;
+                        nw = parseInt(nw, 10);
+                        this.resizing = false;
+                        $("#rs_m" + $.jgrid.jqID(p.id)).css("display", "none");
+                        p.colModel[idx].width = nw;
+                        this.headers[idx].width = nw;
+                        this.headers[idx].el.style.width = nw + "px";
+                        this.cols[idx].style.width = nw + "px";
+                        if (this.footers.length > 0) {
+                            this.footers[idx].style.width = nw + "px";
+                        }
+                        if (p.forceFit === true) {
+                            nw = this.headers[idx + p.nv].newWidth || this.headers[idx + p.nv].width;
+                            this.headers[idx + p.nv].width = nw;
+                            this.headers[idx + p.nv].el.style.width = nw + "px";
+                            this.cols[idx + p.nv].style.width = nw + "px";
+                            if (this.footers.length > 0) {
+                                this.footers[idx + p.nv].style.width = nw + "px";
+                            }
+                            p.colModel[idx + p.nv].width = nw;
+                        } else {
+                            p.tblwidth = this.newWidth || p.tblwidth;
+                            $('table:first', this.bDiv).css("width", p.tblwidth + "px");
+                            $('table:first', this.hDiv).css("width", p.tblwidth + "px");
+                            this.hDiv.scrollLeft = this.bDiv.scrollLeft;
+                            if (p.footerrow) {
+                                $('table:first', this.sDiv).css("width", p.tblwidth + "px");
+                                this.sDiv.scrollLeft = this.bDiv.scrollLeft;
+                            }
+                        }
+                        $(ts).triggerHandler("jqGridResizeStop", [nw, idx]);
+                        if ($.isFunction(p.resizeStop)) {
+                            p.resizeStop.call(this, nw, idx);
+                        }
+                    }
+                    this.curGbox = null;
+                    document.onselectstart = function () {
+                        return true;
+                    };
+                },
+                populateVisible: function () {
+                    if (grid.timer) {
+                        clearTimeout(grid.timer);
+                    }
+                    grid.timer = null;
+                    var dh = $(grid.bDiv).height();
+                    if (!dh) {
+                        return;
+                    }
+                    var table = $("table:first", grid.bDiv);
+                    var rows, rh;
+                    if (table[0].rows.length) {
+                        try {
+                            rows = table[0].rows[1];
+                            rh = rows ? $(rows).outerHeight() || grid.prevRowHeight : grid.prevRowHeight;
+                        } catch (pv) {
+                            rh = grid.prevRowHeight;
+                        }
+                    }
+                    if (!rh) {
+                        return;
+                    }
+                    grid.prevRowHeight = rh;
+                    var rn = p.rowNum;
+                    var scrollTop = grid.scrollTop = grid.bDiv.scrollTop;
+                    var ttop = Math.round(table.position().top) - scrollTop;
+                    var tbot = ttop + table.height();
+                    var div = rh * rn;
+                    var page, npage, empty;
+                    if (tbot < dh && ttop <= 0 &&
+                        (p.lastpage === undefined || parseInt((tbot + scrollTop + div - 1) / div, 10) <= p.lastpage)) {
+                        npage = parseInt((dh - tbot + div - 1) / div, 10);
+                        if (tbot >= 0 || npage < 2 || p.scroll === true) {
+                            page = Math.round((tbot + scrollTop) / div) + 1;
+                            ttop = -1;
+                        } else {
+                            ttop = 1;
+                        }
+                    }
+                    if (ttop > 0) {
+                        page = parseInt(scrollTop / div, 10) + 1;
+                        npage = parseInt((scrollTop + dh) / div, 10) + 2 - page;
+                        empty = true;
+                    }
+                    if (npage) {
+                        if (p.lastpage && page > p.lastpage || p.lastpage == 1 || (page === p.page && page === p.lastpage)) {
+                            return;
+                        }
+                        if (grid.hDiv.loading) {
+                            grid.timer = setTimeout(grid.populateVisible, p.scrollTimeout);
+                        } else {
+                            p.page = page;
+                            if (empty) {
+                                grid.selectionPreserver(table[0]);
+                                grid.emptyRows.call(table[0], false, false);
+                            }
+                            grid.populate(npage);
+                        }
+                    }
+                },
+                scrollGrid: function (e) {
+                    if (p.scroll) {
+                        var scrollTop = grid.bDiv.scrollTop;
+                        if (grid.scrollTop === undefined) {
+                            grid.scrollTop = 0;
+                        }
+                        if (scrollTop != grid.scrollTop) {
+                            grid.scrollTop = scrollTop;
+                            if (grid.timer) {
+                                clearTimeout(grid.timer);
+                            }
+                            grid.timer = setTimeout(grid.populateVisible, p.scrollTimeout);
+                        }
+                    }
+                    grid.hDiv.scrollLeft = grid.bDiv.scrollLeft;
+                    if (p.footerrow) {
+                        grid.sDiv.scrollLeft = grid.bDiv.scrollLeft;
+                    }
+                    if (e) {
+                        e.stopPropagation();
+                    }
+                },
+                selectionPreserver: function (ts) {
+                    var p = ts.p,
+                        sr = p.selrow, sra = p.selarrrow ? $.makeArray(p.selarrrow) : null,
+                        left = ts.grid.bDiv.scrollLeft,
+                        restoreSelection = function () {
+                            var i;
+                            p.selrow = null;
+                            p.selarrrow = [];
+                            if (p.multiselect && sra && sra.length > 0) {
+                                for (i = 0; i < sra.length; i++) {
+                                    if (sra[i] != sr) {
+                                        $(ts).jqGrid("setSelection", sra[i], false, null);
+                                    }
+                                }
+                            }
+                            if (sr) {
+                                $(ts).jqGrid("setSelection", sr, false, null);
+                            }
+                            ts.grid.bDiv.scrollLeft = left;
+                            $(ts).unbind('.selectionPreserver', restoreSelection);
+                        };
+                    $(ts).bind('jqGridGridComplete.selectionPreserver', restoreSelection);
+                }
+            };
+            if (this.tagName.toUpperCase() != 'TABLE') {
+                alert("Element is not a table");
+                return;
+            }
+            if (document.documentMode !== undefined) { // IE only
+                if (document.documentMode <= 5) {
+                    alert("Grid can not be used in this ('quirks') mode!");
+                    return;
+                }
+            }
+            $(this).empty().attr("tabindex", "1");
+            this.p = p;
+            this.p.useProp = !!$.fn.prop;
+            var i, dir;
+            if (this.p.colNames.length === 0) {
+                for (i = 0; i < this.p.colModel.length; i++) {
+                    this.p.colNames[i] = this.p.colModel[i].label || this.p.colModel[i].name;
+                }
+            }
+            if (this.p.colNames.length !== this.p.colModel.length) {
+                alert($.jgrid.errors.model);
+                return;
+            }
+            var gv = $("<div class='ui-jqgrid-view'></div>"), ii,
+                isMSIE = $.browser.msie ? true : false;
+            ts.p.direction = $.trim(ts.p.direction.toLowerCase());
+            if ($.inArray(ts.p.direction, ["ltr", "rtl"]) == -1) {
+                ts.p.direction = "ltr";
+            }
+            dir = ts.p.direction;
+
+            $(gv).insertBefore(this);
+            $(this).appendTo(gv).removeClass("scroll");
+            var eg = $("<div class='ui-jqgrid ui-widget ui-widget-content ui-corner-all'></div>");
+            $(eg).insertBefore(gv).attr({"id": "gbox_" + this.id, "dir": dir});
+            $(gv).appendTo(eg).attr("id", "gview_" + this.id);
+            if (isMSIE && $.browser.version <= 6) {
+                ii = '<iframe style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=\'0\');" src="javascript:false;"></iframe>';
+            } else {
+                ii = "";
+            }
+            $("<div class='ui-widget-overlay jqgrid-overlay' id='lui_" + this.id + "'></div>").append(ii).insertBefore(gv);
+            $("<div class='loading ui-state-default ui-state-active' id='load_" + this.id + "'>" + this.p.loadtext + "</div>").insertBefore(gv);
+            $(this).attr({cellspacing: "0", cellpadding: "0", border: "0", "role": "grid", "aria-multiselectable": !!this.p.multiselect, "aria-labelledby": "gbox_" + this.id});
+            var sortkeys = ["shiftKey", "altKey", "ctrlKey"],
+                intNum = function (val, defval) {
+                    val = parseInt(val, 10);
+                    if (isNaN(val)) {
+                        return defval ? defval : 0;
+                    }
+                    else {
+                        return val;
+                    }
+                },
+                formatCol = function (pos, rowInd, tv, rawObject, rowId, rdata) {
+                    var cm = ts.p.colModel[pos],
+                        ral = cm.align, result = "style=\"", clas = cm.classes, nm = cm.name, celp, acp = [];
+                    if (ral) {
+                        result += "text-align:" + ral + ";";
+                    }
+                    if (cm.hidden === true) {
+                        result += "display:none;";
+                    }
+                    if (rowInd === 0) {
+                        result += "width: " + grid.headers[pos].width + "px;";
+                    } else if (cm.cellattr && $.isFunction(cm.cellattr)) {
+                        celp = cm.cellattr.call(ts, rowId, tv, rawObject, cm, rdata);
+                        if (celp && typeof(celp) === "string") {
+                            celp = celp.replace(/style/i, 'style').replace(/title/i, 'title');
+                            if (celp.indexOf('title') > -1) {
+                                cm.title = false;
+                            }
+                            if (celp.indexOf('class') > -1) {
+                                clas = undefined;
+                            }
+                            acp = celp.split("style");
+                            if (acp.length === 2) {
+                                acp[1] = $.trim(acp[1].replace("=", ""));
+                                if (acp[1].indexOf("'") === 0 || acp[1].indexOf('"') === 0) {
+                                    acp[1] = acp[1].substring(1);
+                                }
+                                result += acp[1].replace(/'/gi, '"');
+                            } else {
+                                result += "\"";
+                            }
+                        }
+                    }
+                    if (!acp.length) {
+                        acp[0] = "";
+                        result += "\"";
+                    }
+                    result += (clas !== undefined ? (" class=\"" + clas + "\"") : "") + ((cm.title && tv) ? (" title=\"" + $.jgrid.stripHtml(tv) + "\"") : "");
+                    result += " aria-describedby=\"" + ts.p.id + "_" + nm + "\"";
+                    return result + acp[0];
+                },
+                cellVal = function (val) {
+                    return val === undefined || val === null || val === "" ? "&#160;" : (ts.p.autoencode ? $.jgrid.htmlEncode(val) : val + "");
+                },
+                formatter = function (rowId, cellval, colpos, rwdat, _act) {
+                    var cm = ts.p.colModel[colpos], v;
+                    if (typeof cm.formatter !== 'undefined') {
+                        var opts = {rowId: rowId, colModel: cm, gid: ts.p.id, pos: colpos };
+                        if ($.isFunction(cm.formatter)) {
+                            v = cm.formatter.call(ts, cellval, opts, rwdat, _act);
+                        } else if ($.fmatter) {
+                            v = $.fn.fmatter.call(ts, cm.formatter, cellval, opts, rwdat, _act);
+                        } else {
+                            v = cellVal(cellval);
+                        }
+                    } else {
+                        v = cellVal(cellval);
+                    }
+                    return v;
+                },
+                addCell = function (rowId, cell, pos, irow, srvr) {
+                    var v, prp;
+                    v = formatter(rowId, cell, pos, srvr, 'add');
+                    prp = formatCol(pos, irow, v, srvr, rowId, true);
+                    return "<td role=\"gridcell\" " + prp + ">" + v + "</td>";
+                },
+                addMulti = function (rowid, pos, irow) {
+                    var v = "<input role=\"checkbox\" type=\"checkbox\"" + " id=\"jqg_" + ts.p.id + "_" + rowid + "\" class=\"cbox\" name=\"jqg_" + ts.p.id + "_" + rowid + "\"/>",
+                        prp = formatCol(pos, irow, '', null, rowid, true);
+                    return "<td role=\"gridcell\" " + prp + ">" + v + "</td>";
+                },
+                addRowNum = function (pos, irow, pG, rN) {
+                    var v = (parseInt(pG, 10) - 1) * parseInt(rN, 10) + 1 + irow,
+                        prp = formatCol(pos, irow, v, null, irow, true);
+                    return "<td role=\"gridcell\" class=\"ui-state-default jqgrid-rownum\" " + prp + ">" + v + "</td>";
+                },
+                reader = function (datatype) {
+                    var field, f = [], j = 0, i;
+                    for (i = 0; i < ts.p.colModel.length; i++) {
+                        field = ts.p.colModel[i];
+                        if (field.name !== 'cb' && field.name !== 'subgrid' && field.name !== 'rn') {
+                            f[j] = datatype == "local" ?
+                                field.name :
+                                ( (datatype == "xml" || datatype === "xmlstring") ? field.xmlmap || field.name : field.jsonmap || field.name );
+                            j++;
+                        }
+                    }
+                    return f;
+                },
+                orderedCols = function (offset) {
+                    var order = ts.p.remapColumns;
+                    if (!order || !order.length) {
+                        order = $.map(ts.p.colModel, function (v, i) {
+                            return i;
+                        });
+                    }
+                    if (offset) {
+                        order = $.map(order, function (v) {
+                            return v < offset ? null : v - offset;
+                        });
+                    }
+                    return order;
+                },
+                emptyRows = function (scroll, locdata) {
+                    var firstrow;
+                    if (this.p.deepempty) {
+                        $(this.rows).slice(1).remove();
+                    } else {
+                        firstrow = this.rows.length > 0 ? this.rows[0] : null;
+                        $(this.firstChild).empty().append(firstrow);
+                    }
+                    if (scroll && this.p.scroll) {
+                        $(this.grid.bDiv.firstChild).css({height: "auto"});
+                        $(this.grid.bDiv.firstChild.firstChild).css({height: 0, display: "none"});
+                        if (this.grid.bDiv.scrollTop !== 0) {
+                            this.grid.bDiv.scrollTop = 0;
+                        }
+                    }
+                    if (locdata === true && this.p.treeGrid) {
+                        this.p.data = [];
+                        this.p._index = {};
+                    }
+                },
+                refreshIndex = function () {
+                    var datalen = ts.p.data.length, idname, i, val,
+                        ni = ts.p.rownumbers === true ? 1 : 0,
+                        gi = ts.p.multiselect === true ? 1 : 0,
+                        si = ts.p.subGrid === true ? 1 : 0;
+
+                    if (ts.p.keyIndex === false || ts.p.loadonce === true) {
+                        idname = ts.p.localReader.id;
+                    } else {
+                        idname = ts.p.colModel[ts.p.keyIndex + gi + si + ni].name;
+                    }
+                    for (i = 0; i < datalen; i++) {
+                        val = $.jgrid.getAccessor(ts.p.data[i], idname);
+                        ts.p._index[val] = i;
+                    }
+                },
+                constructTr = function (id, hide, altClass, rd, cur) {
+                    var tabindex = '-1', restAttr = '', attrName, style = hide ? 'display:none;' : '',
+                        classes = 'ui-widget-content jqgrow ui-row-' + ts.p.direction + altClass,
+                        rowAttrObj = $.isFunction(ts.p.rowattr) ? ts.p.rowattr.call(ts, rd, cur) : {};
+                    if (!$.isEmptyObject(rowAttrObj)) {
+                        if (rowAttrObj.hasOwnProperty("id")) {
+                            id = rowAttrObj.id;
+                            delete rowAttrObj.id;
+                        }
+                        if (rowAttrObj.hasOwnProperty("tabindex")) {
+                            tabindex = rowAttrObj.tabindex;
+                            delete rowAttrObj.tabindex;
+                        }
+                        if (rowAttrObj.hasOwnProperty("style")) {
+                            style += rowAttrObj.style;
+                            delete rowAttrObj.style;
+                        }
+                        if (rowAttrObj.hasOwnProperty("class")) {
+                            classes += ' ' + rowAttrObj['class'];
+                            delete rowAttrObj['class'];
+                        }
+                        // dot't allow to change role attribute
+                        try {
+                            delete rowAttrObj.role;
+                        } catch (ra) {
+                        }
+                        for (attrName in rowAttrObj) {
+                            if (rowAttrObj.hasOwnProperty(attrName)) {
+                                restAttr += ' ' + attrName + '=' + rowAttrObj[attrName];
+                            }
+                        }
+                    }
+                    return '<tr role="row" id="' + id + '" tabindex="' + tabindex + '" class="' + classes + '"' +
+                        (style === '' ? '' : ' style="' + style + '"') + restAttr + '>';
+                },
+                addXmlData = function (xml, t, rcnt, more, adjust) {
+                    var startReq = new Date(),
+                        locdata = (ts.p.datatype != "local" && ts.p.loadonce) || ts.p.datatype == "xmlstring",
+                        xmlid = "_id_", xmlRd = ts.p.xmlReader,
+                        frd = ts.p.datatype == "local" ? "local" : "xml";
+                    if (locdata) {
+                        ts.p.data = [];
+                        ts.p._index = {};
+                        ts.p.localReader.id = xmlid;
+                    }
+                    ts.p.reccount = 0;
+                    if ($.isXMLDoc(xml)) {
+                        if (ts.p.treeANode === -1 && !ts.p.scroll) {
+                            emptyRows.call(ts, false, true);
+                            rcnt = 1;
+                        } else {
+                            rcnt = rcnt > 1 ? rcnt : 1;
+                        }
+                    } else {
+                        return;
+                    }
+                    var i, fpos, ir = 0, v, gi = ts.p.multiselect === true ? 1 : 0, si = ts.p.subGrid === true ? 1 : 0, ni = ts.p.rownumbers === true ? 1 : 0, idn, getId, f = [], F, rd = {}, xmlr, rid, rowData = [], cn = (ts.p.altRows === true) ? " " + ts.p.altclass : "", cn1;
+                    if (!xmlRd.repeatitems) {
+                        f = reader(frd);
+                    }
+                    if (ts.p.keyIndex === false) {
+                        idn = $.isFunction(xmlRd.id) ? xmlRd.id.call(ts, xml) : xmlRd.id;
+                    } else {
+                        idn = ts.p.keyIndex;
+                    }
+                    if (f.length > 0 && !isNaN(idn)) {
+                        if (ts.p.remapColumns && ts.p.remapColumns.length) {
+                            idn = $.inArray(idn, ts.p.remapColumns);
+                        }
+                        idn = f[idn];
+                    }
+                    if ((idn + "").indexOf("[") === -1) {
+                        if (f.length) {
+                            getId = function (trow, k) {
+                                return $(idn, trow).text() || k;
+                            };
+                        } else {
+                            getId = function (trow, k) {
+                                return $(xmlRd.cell, trow).eq(idn).text() || k;
+                            };
+                        }
+                    }
+                    else {
+                        getId = function (trow, k) {
+                            return trow.getAttribute(idn.replace(/[\[\]]/g, "")) || k;
+                        };
+                    }
+                    ts.p.userData = {};
+                    ts.p.page = $.jgrid.getXmlData(xml, xmlRd.page) || 0;
+                    ts.p.lastpage = $.jgrid.getXmlData(xml, xmlRd.total);
+                    if (ts.p.lastpage === undefined) {
+                        ts.p.lastpage = 1;
+                    }
+                    ts.p.records = $.jgrid.getXmlData(xml, xmlRd.records) || 0;
+                    if ($.isFunction(xmlRd.userdata)) {
+                        ts.p.userData = xmlRd.userdata.call(ts, xml) || {};
+                    } else {
+                        $.jgrid.getXmlData(xml, xmlRd.userdata, true).each(function () {
+                            ts.p.userData[this.getAttribute("name")] = $(this).text();
+                        });
+                    }
+                    var gxml = $.jgrid.getXmlData(xml, xmlRd.root, true);
+                    gxml = $.jgrid.getXmlData(gxml, xmlRd.row, true);
+                    if (!gxml) {
+                        gxml = [];
+                    }
+                    var gl = gxml.length, j = 0, grpdata = [], rn = parseInt(ts.p.rowNum, 10);
+                    if (gl > 0 && ts.p.page <= 0) {
+                        ts.p.page = 1;
+                    }
+                    if (gxml && gl) {
+                        var br = ts.p.scroll ? $.jgrid.randId() : 1, altr;
+                        if (adjust) {
+                            rn *= adjust + 1;
+                        }
+                        var afterInsRow = $.isFunction(ts.p.afterInsertRow), hiderow = ts.p.grouping && ts.p.groupingView.groupCollapse === true;
+                        while (j < gl) {
+                            xmlr = gxml[j];
+                            rid = getId(xmlr, br + j);
+                            rid = ts.p.idPrefix + rid;
+                            altr = rcnt === 0 ? 0 : rcnt + 1;
+                            cn1 = (altr + j) % 2 == 1 ? cn : '';
+                            var iStartTrTag = rowData.length;
+                            rowData.push("");
+                            if (ni) {
+                                rowData.push(addRowNum(0, j, ts.p.page, ts.p.rowNum));
+                            }
+                            if (gi) {
+                                rowData.push(addMulti(rid, ni, j));
+                            }
+                            if (si) {
+                                rowData.push($(ts).jqGrid("addSubGridCell", gi + ni, j + rcnt));
+                            }
+                            if (xmlRd.repeatitems) {
+                                if (!F) {
+                                    F = orderedCols(gi + si + ni);
+                                }
+                                var cells = $.jgrid.getXmlData(xmlr, xmlRd.cell, true);
+                                $.each(F, function (k) {
+                                    var cell = cells[this];
+                                    if (!cell) {
+                                        return false;
+                                    }
+                                    v = cell.textContent || cell.text;
+                                    rd[ts.p.colModel[k + gi + si + ni].name] = v;
+                                    rowData.push(addCell(rid, v, k + gi + si + ni, j + rcnt, xmlr));
+                                });
+                            } else {
+                                for (i = 0; i < f.length; i++) {
+                                    v = $.jgrid.getXmlData(xmlr, f[i]);
+                                    rd[ts.p.colModel[i + gi + si + ni].name] = v;
+                                    rowData.push(addCell(rid, v, i + gi + si + ni, j + rcnt, xmlr));
+                                }
+                            }
+                            rowData[iStartTrTag] = constructTr(rid, hiderow, cn1, rd, xmlr);
+                            rowData.push("</tr>");
+                            if (ts.p.grouping) {
+                                grpdata = $(ts).jqGrid('groupingPrepare', rowData, grpdata, rd, j);
+                                rowData = [];
+                            }
+                            if (locdata || ts.p.treeGrid === true) {
+                                rd[xmlid] = rid;
+                                ts.p.data.push(rd);
+                                ts.p._index[rid] = ts.p.data.length - 1;
+                            }
+                            if (ts.p.gridview === false) {
+                                $("tbody:first", t).append(rowData.join(''));
+                                $(ts).triggerHandler("jqGridAfterInsertRow", [rid, rd, xmlr]);
+                                if (afterInsRow) {
+                                    ts.p.afterInsertRow.call(ts, rid, rd, xmlr);
+                                }
+                                rowData = [];
+                            }
+                            rd = {};
+                            ir++;
+                            j++;
+                            if (ir == rn) {
+                                break;
+                            }
+                        }
+                    }
+                    if (ts.p.gridview === true) {
+                        fpos = ts.p.treeANode > -1 ? ts.p.treeANode : 0;
+                        if (ts.p.grouping) {
+                            $(ts).jqGrid('groupingRender', grpdata, ts.p.colModel.length);
+                            grpdata = null;
+                        } else if (ts.p.treeGrid === true && fpos > 0) {
+                            $(ts.rows[fpos]).after(rowData.join(''));
+                        } else {
+                            $("tbody:first", t).append(rowData.join(''));
+                        }
+                    }
+                    if (ts.p.subGrid === true) {
+                        try {
+                            $(ts).jqGrid("addSubGrid", gi + ni);
+                        } catch (_) {
+                        }
+                    }
+                    ts.p.totaltime = new Date() - startReq;
+                    if (ir > 0) {
+                        if (ts.p.records === 0) {
+                            ts.p.records = gl;
+                        }
+                    }
+                    rowData = null;
+                    if (ts.p.treeGrid === true) {
+                        try {
+                            $(ts).jqGrid("setTreeNode", fpos + 1, ir + fpos + 1);
+                        } catch (e) {
+                        }
+                    }
+                    if (!ts.p.treeGrid && !ts.p.scroll) {
+                        ts.grid.bDiv.scrollTop = 0;
+                    }
+                    ts.p.reccount = ir;
+                    ts.p.treeANode = -1;
+                    if (ts.p.userDataOnFooter) {
+                        $(ts).jqGrid("footerData", "set", ts.p.userData, true);
+                    }
+                    if (locdata) {
+                        ts.p.records = gl;
+                        ts.p.lastpage = Math.ceil(gl / rn);
+                    }
+                    if (!more) {
+                        ts.updatepager(false, true);
+                    }
+                    if (locdata) {
+                        while (ir < gl) {
+                            xmlr = gxml[ir];
+                            rid = getId(xmlr, ir + br);
+                            rid = ts.p.idPrefix + rid;
+                            if (xmlRd.repeatitems) {
+                                if (!F) {
+                                    F = orderedCols(gi + si + ni);
+                                }
+                                var cells2 = $.jgrid.getXmlData(xmlr, xmlRd.cell, true);
+                                $.each(F, function (k) {
+                                    var cell = cells2[this];
+                                    if (!cell) {
+                                        return false;
+                                    }
+                                    v = cell.textContent || cell.text;
+                                    rd[ts.p.colModel[k + gi + si + ni].name] = v;
+                                });
+                            } else {
+                                for (i = 0; i < f.length; i++) {
+                                    v = $.jgrid.getXmlData(xmlr, f[i]);
+                                    rd[ts.p.colModel[i + gi + si + ni].name] = v;
+                                }
+                            }
+                            rd[xmlid] = rid;
+                            ts.p.data.push(rd);
+                            ts.p._index[rid] = ts.p.data.length - 1;
+                            rd = {};
+                            ir++;
+                        }
+                    }
+                },
+                addJSONData = function (data, t, rcnt, more, adjust) {
+                    var startReq = new Date();
+                    if (data) {
+                        if (ts.p.treeANode === -1 && !ts.p.scroll) {
+                            emptyRows.call(ts, false, true);
+                            rcnt = 1;
+                        } else {
+                            rcnt = rcnt > 1 ? rcnt : 1;
+                        }
+                    } else {
+                        return;
+                    }
+
+                    var dReader, locid = "_id_", frd,
+                        locdata = (ts.p.datatype != "local" && ts.p.loadonce) || ts.p.datatype == "jsonstring";
+                    if (locdata) {
+                        ts.p.data = [];
+                        ts.p._index = {};
+                        ts.p.localReader.id = locid;
+                    }
+                    ts.p.reccount = 0;
+                    if (ts.p.datatype == "local") {
+                        dReader = ts.p.localReader;
+                        frd = 'local';
+                    } else {
+                        dReader = ts.p.jsonReader;
+                        frd = 'json';
+                    }
+                    var ir = 0, v, i, j, f = [], F, cur, gi = ts.p.multiselect ? 1 : 0, si = ts.p.subGrid ? 1 : 0, ni = ts.p.rownumbers === true ? 1 : 0, len, drows, idn, rd = {}, fpos, idr, rowData = [], cn = (ts.p.altRows === true) ? " " + ts.p.altclass : "", cn1, lp;
+                    ts.p.page = $.jgrid.getAccessor(data, dReader.page) || 0;
+                    lp = $.jgrid.getAccessor(data, dReader.total);
+                    ts.p.lastpage = lp === undefined ? 1 : lp;
+                    ts.p.records = $.jgrid.getAccessor(data, dReader.records) || 0;
+                    ts.p.userData = $.jgrid.getAccessor(data, dReader.userdata) || {};
+                    if (!dReader.repeatitems) {
+                        F = f = reader(frd);
+                    }
+                    if (ts.p.keyIndex === false) {
+                        idn = $.isFunction(dReader.id) ? dReader.id.call(ts, data) : dReader.id;
+                    } else {
+                        idn = ts.p.keyIndex;
+                    }
+                    if (f.length > 0 && !isNaN(idn)) {
+                        if (ts.p.remapColumns && ts.p.remapColumns.length) {
+                            idn = $.inArray(idn, ts.p.remapColumns);
+                        }
+                        idn = f[idn];
+                    }
+                    drows = $.jgrid.getAccessor(data, dReader.root);
+                    if (!drows) {
+                        drows = [];
+                    }
+                    len = drows.length;
+                    i = 0;
+                    if (len > 0 && ts.p.page <= 0) {
+                        ts.p.page = 1;
+                    }
+                    var rn = parseInt(ts.p.rowNum, 10), br = ts.p.scroll ? $.jgrid.randId() : 1, altr;
+                    if (adjust) {
+                        rn *= adjust + 1;
+                    }
+                    var afterInsRow = $.isFunction(ts.p.afterInsertRow), grpdata = [], hiderow = ts.p.grouping && ts.p.groupingView.groupCollapse === true;
+                    while (i < len) {
+                        cur = drows[i];
+                        idr = $.jgrid.getAccessor(cur, idn);
+                        if (idr === undefined) {
+                            idr = br + i;
+                            if (f.length === 0) {
+                                if (dReader.cell) {
+                                    var ccur = $.jgrid.getAccessor(cur, dReader.cell);
+                                    idr = ccur !== undefined ? ccur[idn] || idr : idr;
+                                    ccur = null;
+                                }
+                            }
+                        }
+                        idr = ts.p.idPrefix + idr;
+                        altr = rcnt === 1 ? 0 : rcnt;
+                        cn1 = (altr + i) % 2 == 1 ? cn : '';
+                        var iStartTrTag = rowData.length;
+                        rowData.push("");
+                        if (ni) {
+                            rowData.push(addRowNum(0, i, ts.p.page, ts.p.rowNum));
+                        }
+                        if (gi) {
+                            rowData.push(addMulti(idr, ni, i));
+                        }
+                        if (si) {
+                            rowData.push($(ts).jqGrid("addSubGridCell", gi + ni, i + rcnt));
+                        }
+                        if (dReader.repeatitems) {
+                            if (dReader.cell) {
+                                cur = $.jgrid.getAccessor(cur, dReader.cell);
+                            }
+                            if (!F) {
+                                F = orderedCols(gi + si + ni);
+                            }
+                        }
+                        for (j = 0; j < F.length; j++) {
+                            v = $.jgrid.getAccessor(cur, F[j]);
+                            rowData.push(addCell(idr, v, j + gi + si + ni, i + rcnt, cur));
+                            rd[ts.p.colModel[j + gi + si + ni].name] = v;
+                        }
+                        rowData[iStartTrTag] = constructTr(idr, hiderow, cn1, rd, cur);
+                        rowData.push("</tr>");
+                        if (ts.p.grouping) {
+                            grpdata = $(ts).jqGrid('groupingPrepare', rowData, grpdata, rd, i);
+                            rowData = [];
+                        }
+                        if (locdata || ts.p.treeGrid === true) {
+                            rd[locid] = idr;
+                            ts.p.data.push(rd);
+                            ts.p._index[idr] = ts.p.data.length - 1;
+                        }
+                        if (ts.p.gridview === false) {
+                            $("#" + $.jgrid.jqID(ts.p.id) + " tbody:first").append(rowData.join(''));
+                            $(ts).triggerHandler("jqGridAfterInsertRow", [idr, rd, cur]);
+                            if (afterInsRow) {
+                                ts.p.afterInsertRow.call(ts, idr, rd, cur);
+                            }
+                            rowData = [];//ari=0;
+                        }
+                        rd = {};
+                        ir++;
+                        i++;
+                        if (ir == rn) {
+                            break;
+                        }
+                    }
+                    if (ts.p.gridview === true) {
+                        fpos = ts.p.treeANode > -1 ? ts.p.treeANode : 0;
+                        if (ts.p.grouping) {
+                            $(ts).jqGrid('groupingRender', grpdata, ts.p.colModel.length);
+                            grpdata = null;
+                        } else if (ts.p.treeGrid === true && fpos > 0) {
+                            $(ts.rows[fpos]).after(rowData.join(''));
+                        } else {
+                            $("#" + $.jgrid.jqID(ts.p.id) + " tbody:first").append(rowData.join(''));
+                        }
+                    }
+                    if (ts.p.subGrid === true) {
+                        try {
+                            $(ts).jqGrid("addSubGrid", gi + ni);
+                        } catch (_) {
+                        }
+                    }
+                    ts.p.totaltime = new Date() - startReq;
+                    if (ir > 0) {
+                        if (ts.p.records === 0) {
+                            ts.p.records = len;
+                        }
+                    }
+                    rowData = null;
+                    if (ts.p.treeGrid === true) {
+                        try {
+                            $(ts).jqGrid("setTreeNode", fpos + 1, ir + fpos + 1);
+                        } catch (e) {
+                        }
+                    }
+                    if (!ts.p.treeGrid && !ts.p.scroll) {
+                        ts.grid.bDiv.scrollTop = 0;
+                    }
+                    ts.p.reccount = ir;
+                    ts.p.treeANode = -1;
+                    if (ts.p.userDataOnFooter) {
+                        $(ts).jqGrid("footerData", "set", ts.p.userData, true);
+                    }
+                    if (locdata) {
+                        ts.p.records = len;
+                        ts.p.lastpage = Math.ceil(len / rn);
+                    }
+                    if (!more) {
+                        ts.updatepager(false, true);
+                    }
+                    if (locdata) {
+                        while (ir < len && drows[ir]) {
+                            cur = drows[ir];
+                            idr = $.jgrid.getAccessor(cur, idn);
+                            if (idr === undefined) {
+                                idr = br + ir;
+                                if (f.length === 0) {
+                                    if (dReader.cell) {
+                                        var ccur2 = $.jgrid.getAccessor(cur, dReader.cell);
+                                        idr = ccur2[idn] || idr;
+                                        ccur2 = null;
+                                    }
+                                }
+                            }
+                            if (cur) {
+                                idr = ts.p.idPrefix + idr;
+                                if (dReader.repeatitems) {
+                                    if (dReader.cell) {
+                                        cur = $.jgrid.getAccessor(cur, dReader.cell);
+                                    }
+                                    if (!F) {
+                                        F = orderedCols(gi + si + ni);
+                                    }
+                                }
+
+                                for (j = 0; j < F.length; j++) {
+                                    v = $.jgrid.getAccessor(cur, F[j]);
+                                    rd[ts.p.colModel[j + gi + si + ni].name] = v;
+                                }
+                                rd[locid] = idr;
+                                ts.p.data.push(rd);
+                                ts.p._index[idr] = ts.p.data.length - 1;
+                                rd = {};
+                            }
+                            ir++;
+                        }
+                    }
+                },
+                addLocalData = function () {
+                    var st, fndsort = false, cmtypes = {}, grtypes = [], grindexes = [], srcformat, sorttype, newformat;
+                    if (!$.isArray(ts.p.data)) {
+                        return;
+                    }
+                    var grpview = ts.p.grouping ? ts.p.groupingView : false, lengrp, gin;
+                    $.each(ts.p.colModel, function () {
+                        sorttype = this.sorttype || "text";
+                        if (sorttype == "date" || sorttype == "datetime") {
+                            if (this.formatter && typeof(this.formatter) === 'string' && this.formatter == 'date') {
+                                if (this.formatoptions && this.formatoptions.srcformat) {
+                                    srcformat = this.formatoptions.srcformat;
+                                } else {
+                                    srcformat = $.jgrid.formatter.date.srcformat;
+                                }
+                                if (this.formatoptions && this.formatoptions.newformat) {
+                                    newformat = this.formatoptions.newformat;
+                                } else {
+                                    newformat = $.jgrid.formatter.date.newformat;
+                                }
+                            } else {
+                                srcformat = newformat = this.datefmt || "Y-m-d";
+                            }
+                            cmtypes[this.name] = {"stype": sorttype, "srcfmt": srcformat, "newfmt": newformat};
+                        } else {
+                            cmtypes[this.name] = {"stype": sorttype, "srcfmt": '', "newfmt": ''};
+                        }
+                        if (ts.p.grouping) {
+                            for (gin = 0, lengrp = grpview.groupField.length; gin < lengrp; gin++) {
+                                if (this.name == grpview.groupField[gin]) {
+                                    var grindex = this.name;
+                                    if (typeof this.index != 'undefined') {
+                                        grindex = this.index;
+                                    }
+                                    grtypes[gin] = cmtypes[grindex];
+                                    grindexes[gin] = grindex;
+                                }
+                            }
+                        }
+                        if (!fndsort && (this.index == ts.p.sortname || this.name == ts.p.sortname)) {
+                            st = this.name; // ???
+                            fndsort = true;
+                        }
+                    });
+                    if (ts.p.treeGrid) {
+                        $(ts).jqGrid("SortTree", st, ts.p.sortorder, cmtypes[st].stype, cmtypes[st].srcfmt);
+                        return;
+                    }
+                    var compareFnMap = {
+                            'eq': function (queryObj) {
+                                return queryObj.equals;
+                            },
+                            'ne': function (queryObj) {
+                                return queryObj.notEquals;
+                            },
+                            'lt': function (queryObj) {
+                                return queryObj.less;
+                            },
+                            'le': function (queryObj) {
+                                return queryObj.lessOrEquals;
+                            },
+                            'gt': function (queryObj) {
+                                return queryObj.greater;
+                            },
+                            'ge': function (queryObj) {
+                                return queryObj.greaterOrEquals;
+                            },
+                            'cn': function (queryObj) {
+                                return queryObj.contains;
+                            },
+                            'nc': function (queryObj, op) {
+                                return op === "OR" ? queryObj.orNot().contains : queryObj.andNot().contains;
+                            },
+                            'bw': function (queryObj) {
+                                return queryObj.startsWith;
+                            },
+                            'bn': function (queryObj, op) {
+                                return op === "OR" ? queryObj.orNot().startsWith : queryObj.andNot().startsWith;
+                            },
+                            'en': function (queryObj, op) {
+                                return op === "OR" ? queryObj.orNot().endsWith : queryObj.andNot().endsWith;
+                            },
+                            'ew': function (queryObj) {
+                                return queryObj.endsWith;
+                            },
+                            'ni': function (queryObj, op) {
+                                return op === "OR" ? queryObj.orNot().equals : queryObj.andNot().equals;
+                            },
+                            'in': function (queryObj) {
+                                return queryObj.equals;
+                            },
+                            'nu': function (queryObj) {
+                                return queryObj.isNull;
+                            },
+                            'nn': function (queryObj, op) {
+                                return op === "OR" ? queryObj.orNot().isNull : queryObj.andNot().isNull;
+                            }
+
+                        },
+                        query = $.jgrid.from(ts.p.data);
+                    if (ts.p.ignoreCase) {
+                        query = query.ignoreCase();
+                    }
+                    function tojLinq(group) {
+                        var s = 0, index, gor, ror, opr, rule;
+                        if (group.groups !== undefined) {
+                            gor = group.groups.length && group.groupOp.toString().toUpperCase() === "OR";
+                            if (gor) {
+                                query.orBegin();
+                            }
+                            for (index = 0; index < group.groups.length; index++) {
+                                if (s > 0 && gor) {
+                                    query.or();
+                                }
+                                try {
+                                    tojLinq(group.groups[index]);
+                                } catch (e) {
+                                    alert(e);
+                                }
+                                s++;
+                            }
+                            if (gor) {
+                                query.orEnd();
+                            }
+                        }
+                        if (group.rules !== undefined) {
+                            if (s > 0) {
+                                var result = query.select();
+                                query = $.jgrid.from(result);
+                                if (ts.p.ignoreCase) {
+                                    query = query.ignoreCase();
+                                }
+                            }
+                            try {
+                                ror = group.rules.length && group.groupOp.toString().toUpperCase() === "OR";
+                                if (ror) {
+                                    query.orBegin();
+                                }
+                                for (index = 0; index < group.rules.length; index++) {
+                                    rule = group.rules[index];
+                                    opr = group.groupOp.toString().toUpperCase();
+                                    if (compareFnMap[rule.op] && rule.field) {
+                                        if (s > 0 && opr && opr === "OR") {
+                                            query = query.or();
+                                        }
+                                        query = compareFnMap[rule.op](query, opr)(rule.field, rule.data, cmtypes[rule.field]);
+                                    }
+                                    s++;
+                                }
+                                if (ror) {
+                                    query.orEnd();
+                                }
+                            } catch (g) {
+                                alert(g);
+                            }
+                        }
+                    }
+
+                    if (ts.p.search === true) {
+                        var srules = ts.p.postData.filters;
+                        if (srules) {
+                            if (typeof srules == "string") {
+                                srules = $.jgrid.parse(srules);
+                            }
+                            tojLinq(srules);
+                        } else {
+                            try {
+                                query = compareFnMap[ts.p.postData.searchOper](query)(ts.p.postData.searchField, ts.p.postData.searchString, cmtypes[ts.p.postData.searchField]);
+                            } catch (se) {
+                            }
+                        }
+                    }
+                    if (ts.p.grouping) {
+                        for (gin = 0; gin < lengrp; gin++) {
+                            query.orderBy(grindexes[gin], grpview.groupOrder[gin], grtypes[gin].stype, grtypes[gin].srcfmt);
+                        }
+                    }
+                    if (st && ts.p.sortorder && fndsort) {
+                        if (ts.p.sortorder.toUpperCase() == "DESC") {
+                            query.orderBy(ts.p.sortname, "d", cmtypes[st].stype, cmtypes[st].srcfmt);
+                        } else {
+                            query.orderBy(ts.p.sortname, "a", cmtypes[st].stype, cmtypes[st].srcfmt);
+                        }
+                    }
+                    var queryResults = query.select(),
+                        recordsperpage = parseInt(ts.p.rowNum, 10),
+                        total = queryResults.length,
+                        page = parseInt(ts.p.page, 10),
+                        totalpages = Math.ceil(total / recordsperpage),
+                        retresult = {};
+                    queryResults = queryResults.slice((page - 1) * recordsperpage, page * recordsperpage);
+                    query = null;
+                    cmtypes = null;
+                    retresult[ts.p.localReader.total] = totalpages;
+                    retresult[ts.p.localReader.page] = page;
+                    retresult[ts.p.localReader.records] = total;
+                    retresult[ts.p.localReader.root] = queryResults;
+                    retresult[ts.p.localReader.userdata] = ts.p.userData;
+                    queryResults = null;
+                    return  retresult;
+                },
+                updatepager = function (rn, dnd) {
+                    var cp, last, base, from, to, tot, fmt, pgboxes = "", sppg,
+                        tspg = ts.p.pager ? "_" + $.jgrid.jqID(ts.p.pager.substr(1)) : "",
+                        tspg_t = ts.p.toppager ? "_" + ts.p.toppager.substr(1) : "";
+                    base = parseInt(ts.p.page, 10) - 1;
+                    if (base < 0) {
+                        base = 0;
+                    }
+                    base = base * parseInt(ts.p.rowNum, 10);
+                    to = base + ts.p.reccount;
+                    if (ts.p.scroll) {
+                        var rows = $("tbody:first > tr:gt(0)", ts.grid.bDiv);
+                        base = to - rows.length;
+                        ts.p.reccount = rows.length;
+                        var rh = rows.outerHeight() || ts.grid.prevRowHeight;
+                        if (rh) {
+                            var top = base * rh;
+                            var height = parseInt(ts.p.records, 10) * rh;
+                            $(">div:first", ts.grid.bDiv).css({height: height}).children("div:first").css({height: top, display: top ? "" : "none"});
+                        }
+                        ts.grid.bDiv.scrollLeft = ts.grid.hDiv.scrollLeft;
+                    }
+                    pgboxes = ts.p.pager ? ts.p.pager : "";
+                    pgboxes += ts.p.toppager ? (pgboxes ? "," + ts.p.toppager : ts.p.toppager) : "";
+                    if (pgboxes) {
+                        fmt = $.jgrid.formatter.integer || {};
+                        cp = intNum(ts.p.page);
+                        last = intNum(ts.p.lastpage);
+                        $(".selbox", pgboxes)[ this.p.useProp ? 'prop' : 'attr' ]("disabled", false);
+                        if (ts.p.pginput === true) {
+                            $('.ui-pg-input', pgboxes).val(ts.p.page);
+                            sppg = ts.p.toppager ? '#sp_1' + tspg + ",#sp_1" + tspg_t : '#sp_1' + tspg;
+                            $(sppg).html($.fmatter ? $.fmatter.util.NumberFormat(ts.p.lastpage, fmt) : ts.p.lastpage);
+
+                        }
+                        if (ts.p.viewrecords) {
+                            if (ts.p.reccount === 0) {
+                                $(".ui-paging-info", pgboxes).html(ts.p.emptyrecords);
+                            } else {
+                                from = base + 1;
+                                tot = ts.p.records;
+                                if ($.fmatter) {
+                                    from = $.fmatter.util.NumberFormat(from, fmt);
+                                    to = $.fmatter.util.NumberFormat(to, fmt);
+                                    tot = $.fmatter.util.NumberFormat(tot, fmt);
+                                }
+                                $(".ui-paging-info", pgboxes).html($.jgrid.format(ts.p.recordtext, from, to, tot));
+                            }
+                        }
+                        if (ts.p.pgbuttons === true) {
+                            if (cp <= 0) {
+                                cp = last = 0;
+                            }
+                            if (cp == 1 || cp === 0) {
+                                $("#first" + tspg + ", #prev" + tspg).addClass('ui-state-disabled').removeClass('ui-state-hover');
+                                if (ts.p.toppager) {
+                                    $("#first_t" + tspg_t + ", #prev_t" + tspg_t).addClass('ui-state-disabled').removeClass('ui-state-hover');
+                                }
+                            } else {
+                                $("#first" + tspg + ", #prev" + tspg).removeClass('ui-state-disabled');
+                                if (ts.p.toppager) {
+                                    $("#first_t" + tspg_t + ", #prev_t" + tspg_t).removeClass('ui-state-disabled');
+                                }
+                            }
+                            if (cp == last || cp === 0) {
+                                $("#next" + tspg + ", #last" + tspg).addClass('ui-state-disabled').removeClass('ui-state-hover');
+                                if (ts.p.toppager) {
+                                    $("#next_t" + tspg_t + ", #last_t" + tspg_t).addClass('ui-state-disabled').removeClass('ui-state-hover');
+                                }
+                            } else {
+                                $("#next" + tspg + ", #last" + tspg).removeClass('ui-state-disabled');
+                                if (ts.p.toppager) {
+                                    $("#next_t" + tspg_t + ", #last_t" + tspg_t).removeClass('ui-state-disabled');
+                                }
+                            }
+                        }
+                    }
+                    if (rn === true && ts.p.rownumbers === true) {
+                        $("td.jqgrid-rownum", ts.rows).each(function (i) {
+                            $(this).html(base + 1 + i);
+                        });
+                    }
+                    if (dnd && ts.p.jqgdnd) {
+                        $(ts).jqGrid('gridDnD', 'updateDnD');
+                    }
+                    $(ts).triggerHandler("jqGridGridComplete");
+                    if ($.isFunction(ts.p.gridComplete)) {
+                        ts.p.gridComplete.call(ts);
+                    }
+                    $(ts).triggerHandler("jqGridAfterGridComplete");
+                },
+                beginReq = function () {
+                    ts.grid.hDiv.loading = true;
+                    if (ts.p.hiddengrid) {
+                        return;
+                    }
+                    switch (ts.p.loadui) {
+                        case "disable":
+                            break;
+                        case "enable":
+                            $("#load_" + $.jgrid.jqID(ts.p.id)).show();
+                            break;
+                        case "block":
+                            $("#lui_" + $.jgrid.jqID(ts.p.id)).show();
+                            $("#load_" + $.jgrid.jqID(ts.p.id)).show();
+                            break;
+                    }
+                },
+                endReq = function () {
+                    ts.grid.hDiv.loading = false;
+                    switch (ts.p.loadui) {
+                        case "disable":
+                            break;
+                        case "enable":
+                            $("#load_" + $.jgrid.jqID(ts.p.id)).hide();
+                            break;
+                        case "block":
+                            $("#lui_" + $.jgrid.jqID(ts.p.id)).hide();
+                            $("#load_" + $.jgrid.jqID(ts.p.id)).hide();
+                            break;
+                    }
+                },
+                populate = function (npage) {
+                    if (!ts.grid.hDiv.loading) {
+                        var pvis = ts.p.scroll && npage === false,
+                            prm = {}, dt, dstr, pN = ts.p.prmNames;
+                        if (ts.p.page <= 0) {
+                            ts.p.page = 1;
+                        }
+                        if (pN.search !== null) {
+                            prm[pN.search] = ts.p.search;
+                        }
+                        if (pN.nd !== null) {
+                            prm[pN.nd] = new Date().getTime();
+                        }
+                        if (pN.rows !== null) {
+                            prm[pN.rows] = ts.p.rowNum;
+                        }
+                        if (pN.page !== null) {
+                            prm[pN.page] = ts.p.page;
+                        }
+                        if (pN.sort !== null) {
+                            prm[pN.sort] = ts.p.sortname;
+                        }
+                        if (pN.order !== null) {
+                            prm[pN.order] = ts.p.sortorder;
+                        }
+                        if (ts.p.rowTotal !== null && pN.totalrows !== null) {
+                            prm[pN.totalrows] = ts.p.rowTotal;
+                        }
+                        var lcf = $.isFunction(ts.p.loadComplete), lc = lcf ? ts.p.loadComplete : null;
+                        var adjust = 0;
+                        npage = npage || 1;
+                        if (npage > 1) {
+                            if (pN.npage !== null) {
+                                prm[pN.npage] = npage;
+                                adjust = npage - 1;
+                                npage = 1;
+                            } else {
+                                lc = function (req) {
+                                    ts.p.page++;
+                                    ts.grid.hDiv.loading = false;
+                                    if (lcf) {
+                                        ts.p.loadComplete.call(ts, req);
+                                    }
+                                    populate(npage - 1);
+                                };
+                            }
+                        } else if (pN.npage !== null) {
+                            delete ts.p.postData[pN.npage];
+                        }
+                        if (ts.p.grouping) {
+                            $(ts).jqGrid('groupingSetup');
+                            var grp = ts.p.groupingView, gi, gs = "";
+                            for (gi = 0; gi < grp.groupField.length; gi++) {
+                                gs += grp.groupField[gi] + " " + grp.groupOrder[gi] + ", ";
+                            }
+                            prm[pN.sort] = gs + prm[pN.sort];
+                        }
+                        $.extend(ts.p.postData, prm);
+                        var rcnt = !ts.p.scroll ? 1 : ts.rows.length - 1;
+                        var bfr = $(ts).triggerHandler("jqGridBeforeRequest");
+                        if (bfr === false || bfr === 'stop') {
+                            return;
+                        }
+                        if ($.isFunction(ts.p.datatype)) {
+                            ts.p.datatype.call(ts, ts.p.postData, "load_" + ts.p.id);
+                            return;
+                        }
+                        else if ($.isFunction(ts.p.beforeRequest)) {
+                            bfr = ts.p.beforeRequest.call(ts);
+                            if (bfr === undefined) {
+                                bfr = true;
+                            }
+                            if (bfr === false) {
+                                return;
+                            }
+                        }
+                        dt = ts.p.datatype.toLowerCase();
+                        switch (dt) {
+                            case "json":
+                            case "jsonp":
+                            case "xml":
+                            case "script":
+                                $.ajax($.extend({
+                                    url: ts.p.url,
+                                    type: ts.p.mtype,
+                                    dataType: dt,
+                                    data: $.isFunction(ts.p.serializeGridData) ? ts.p.serializeGridData.call(ts, ts.p.postData) : ts.p.postData,
+                                    success: function (data, st, xhr) {
+                                        if ($.isFunction(ts.p.beforeProcessing)) {
+                                            if (ts.p.beforeProcessing.call(ts, data, st, xhr) === false) {
+                                                endReq();
+                                                return;
+                                            }
+                                        }
+                                        if (dt === "xml") {
+                                            addXmlData(data, ts.grid.bDiv, rcnt, npage > 1, adjust);
+                                        }
+                                        else {
+                                            addJSONData(data, ts.grid.bDiv, rcnt, npage > 1, adjust);
+                                        }
+                                        $(ts).triggerHandler("jqGridLoadComplete", [data]);
+                                        if (lc) {
+                                            lc.call(ts, data);
+                                        }
+                                        $(ts).triggerHandler("jqGridAfterLoadComplete", [data]);
+                                        if (pvis) {
+                                            ts.grid.populateVisible();
+                                        }
+                                        if (ts.p.loadonce || ts.p.treeGrid) {
+                                            ts.p.datatype = "local";
+                                        }
+                                        data = null;
+                                        if (npage === 1) {
+                                            endReq();
+                                        }
+                                    },
+                                    error: function (xhr, st, err) {
+                                        if ($.isFunction(ts.p.loadError)) {
+                                            ts.p.loadError.call(ts, xhr, st, err);
+                                        }
+                                        if (npage === 1) {
+                                            endReq();
+                                        }
+                                        xhr = null;
+                                    },
+                                    beforeSend: function (xhr, settings) {
+                                        var gotoreq = true;
+                                        if ($.isFunction(ts.p.loadBeforeSend)) {
+                                            gotoreq = ts.p.loadBeforeSend.call(ts, xhr, settings);
+                                        }
+                                        if (gotoreq === undefined) {
+                                            gotoreq = true;
+                                        }
+                                        if (gotoreq === false) {
+                                            return false;
+                                        } else {
+                                            beginReq();
+                                        }
+                                    }
+                                }, $.jgrid.ajaxOptions, ts.p.ajaxGridOptions));
+                                break;
+                            case "xmlstring":
+                                beginReq();
+                                dstr = $.jgrid.stringToDoc(ts.p.datastr);
+                                addXmlData(dstr, ts.grid.bDiv);
+                                $(ts).triggerHandler("jqGridLoadComplete", [dstr]);
+                                if (lcf) {
+                                    ts.p.loadComplete.call(ts, dstr);
+                                }
+                                $(ts).triggerHandler("jqGridAfterLoadComplete", [dstr]);
+                                ts.p.datatype = "local";
+                                ts.p.datastr = null;
+                                endReq();
+                                break;
+                            case "jsonstring":
+                                beginReq();
+                                if (typeof ts.p.datastr == 'string') {
+                                    dstr = $.jgrid.parse(ts.p.datastr);
+                                }
+                                else {
+                                    dstr = ts.p.datastr;
+                                }
+                                addJSONData(dstr, ts.grid.bDiv);
+                                $(ts).triggerHandler("jqGridLoadComplete", [dstr]);
+                                if (lcf) {
+                                    ts.p.loadComplete.call(ts, dstr);
+                                }
+                                $(ts).triggerHandler("jqGridAfterLoadComplete", [dstr]);
+                                ts.p.datatype = "local";
+                                ts.p.datastr = null;
+                                endReq();
+                                break;
+                            case "local":
+                            case "clientside":
+                                beginReq();
+                                ts.p.datatype = "local";
+                                var req = addLocalData();
+                                addJSONData(req, ts.grid.bDiv, rcnt, npage > 1, adjust);
+                                $(ts).triggerHandler("jqGridLoadComplete", [req]);
+                                if (lc) {
+                                    lc.call(ts, req);
+                                }
+                                $(ts).triggerHandler("jqGridAfterLoadComplete", [req]);
+                                if (pvis) {
+                                    ts.grid.populateVisible();
+                                }
+                                endReq();
+                                break;
+                        }
+                    }
+                },
+                setHeadCheckBox = function (checked) {
+                    $('#cb_' + $.jgrid.jqID(ts.p.id), ts.grid.hDiv)[ts.p.useProp ? 'prop' : 'attr']("checked", checked);
+                    var fid = ts.p.frozenColumns ? ts.p.id + "_frozen" : "";
+                    if (fid) {
+                        $('#cb_' + $.jgrid.jqID(ts.p.id), ts.grid.fhDiv)[ts.p.useProp ? 'prop' : 'attr']("checked", checked);
+                    }
+                },
+                setPager = function (pgid, tp) {
+                    // TBD - consider escaping pgid with pgid = $.jgrid.jqID(pgid);
+                    var sep = "<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>",
+                        pginp = "",
+                        pgl = "<table cellspacing='0' cellpadding='0' border='0' style='table-layout:auto;' class='ui-pg-table'><tbody><tr>",
+                        str = "", pgcnt, lft, cent, rgt, twd, tdw, i,
+                        clearVals = function (onpaging) {
+                            var ret;
+                            if ($.isFunction(ts.p.onPaging)) {
+                                ret = ts.p.onPaging.call(ts, onpaging);
+                            }
+                            ts.p.selrow = null;
+                            if (ts.p.multiselect) {
+                                ts.p.selarrrow = [];
+                                setHeadCheckBox(false);
+                            }
+                            ts.p.savedRow = [];
+                            if (ret == 'stop') {
+                                return false;
+                            }
+                            return true;
+                        };
+                    pgid = pgid.substr(1);
+                    tp += "_" + pgid;
+                    pgcnt = "pg_" + pgid;
+                    lft = pgid + "_left";
+                    cent = pgid + "_center";
+                    rgt = pgid + "_right";
+                    $("#" + $.jgrid.jqID(pgid))
+                        .append("<div id='" + pgcnt + "' class='ui-pager-control' role='group'><table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table' style='width:100%;table-layout:fixed;height:100%;' role='row'><tbody><tr><td id='" + lft + "' align='left'></td><td id='" + cent + "' align='center' style='white-space:pre;'></td><td id='" + rgt + "' align='right'></td></tr></tbody></table></div>")
+                        .attr("dir", "ltr"); //explicit setting
+                    if (ts.p.rowList.length > 0) {
+                        str = "<td dir='" + dir + "'>";
+                        str += "<select class='ui-pg-selbox' role='listbox'>";
+                        for (i = 0; i < ts.p.rowList.length; i++) {
+                            str += "<option role=\"option\" value=\"" + ts.p.rowList[i] + "\"" + ((ts.p.rowNum == ts.p.rowList[i]) ? " selected=\"selected\"" : "") + ">" + ts.p.rowList[i] + "</option>";
+                        }
+                        str += "</select></td>";
+                    }
+                    if (dir == "rtl") {
+                        pgl += str;
+                    }
+                    if (ts.p.pginput === true) {
+                        pginp = "<td dir='" + dir + "'>" + $.jgrid.format(ts.p.pgtext || "", "<input class='ui-pg-input' type='text' size='2' maxlength='7' value='0' role='textbox'/>", "<span id='sp_1_" + $.jgrid.jqID(pgid) + "'></span>") + "</td>";
+                    }
+                    if (ts.p.pgbuttons === true) {
+                        var po = ["first" + tp, "prev" + tp, "next" + tp, "last" + tp];
+                        if (dir == "rtl") {
+                            po.reverse();
+                        }
+                        pgl += "<td id='" + po[0] + "' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-first'></span></td>";
+                        pgl += "<td id='" + po[1] + "' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-prev'></span></td>";
+                        pgl += pginp !== "" ? sep + pginp + sep : "";
+                        pgl += "<td id='" + po[2] + "' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-next'></span></td>";
+                        pgl += "<td id='" + po[3] + "' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-end'></span></td>";
+                    } else if (pginp !== "") {
+                        pgl += pginp;
+                    }
+                    if (dir == "ltr") {
+                        pgl += str;
+                    }
+                    pgl += "</tr></tbody></table>";
+                    if (ts.p.viewrecords === true) {
+                        $("td#" + pgid + "_" + ts.p.recordpos, "#" + pgcnt).append("<div dir='" + dir + "' style='text-align:" + ts.p.recordpos + "' class='ui-paging-info'></div>");
+                    }
+                    $("td#" + pgid + "_" + ts.p.pagerpos, "#" + pgcnt).append(pgl);
+                    tdw = $(".ui-jqgrid").css("font-size") || "11px";
+                    $(document.body).append("<div id='testpg' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:" + tdw + ";visibility:hidden;' ></div>");
+                    twd = $(pgl).clone().appendTo("#testpg").width();
+                    $("#testpg").remove();
+                    if (twd > 0) {
+                        if (pginp !== "") {
+                            twd += 50;
+                        } //should be param
+                        $("td#" + pgid + "_" + ts.p.pagerpos, "#" + pgcnt).width(twd);
+                    }
+                    ts.p._nvtd = [];
+                    ts.p._nvtd[0] = twd ? Math.floor((ts.p.width - twd) / 2) : Math.floor(ts.p.width / 3);
+                    ts.p._nvtd[1] = 0;
+                    pgl = null;
+                    $('.ui-pg-selbox', "#" + pgcnt).bind('change', function () {
+                        ts.p.page = Math.round(ts.p.rowNum * (ts.p.page - 1) / this.value - 0.5) + 1;
+                        ts.p.rowNum = this.value;
+                        if (ts.p.pager) {
+                            $('.ui-pg-selbox', ts.p.pager).val(this.value);
+                        }
+                        if (ts.p.toppager) {
+                            $('.ui-pg-selbox', ts.p.toppager).val(this.value);
+                        }
+                        if (!clearVals('records')) {
+                            return false;
+                        }
+                        populate();
+                        return false;
+                    });
+                    if (ts.p.pgbuttons === true) {
+                        $(".ui-pg-button", "#" + pgcnt).hover(function () {
+                            if ($(this).hasClass('ui-state-disabled')) {
+                                this.style.cursor = 'default';
+                            } else {
+                                $(this).addClass('ui-state-hover');
+                                this.style.cursor = 'pointer';
+                            }
+                        }, function () {
+                            if (!$(this).hasClass('ui-state-disabled')) {
+                                $(this).removeClass('ui-state-hover');
+                                this.style.cursor = "default";
+                            }
+                        });
+                        $("#first" + $.jgrid.jqID(tp) + ", #prev" + $.jgrid.jqID(tp) + ", #next" + $.jgrid.jqID(tp) + ", #last" + $.jgrid.jqID(tp)).click(function () {
+                            var cp = intNum(ts.p.page, 1),
+                                last = intNum(ts.p.lastpage, 1), selclick = false,
+                                fp = true, pp = true, np = true, lp = true;
+                            if (last === 0 || last === 1) {
+                                fp = false;
+                                pp = false;
+                                np = false;
+                                lp = false;
+                            }
+                            else if (last > 1 && cp >= 1) {
+                                if (cp === 1) {
+                                    fp = false;
+                                    pp = false;
+                                }
+                                //else if( cp>1 && cp <last){ }
+                                else if (cp === last) {
+                                    np = false;
+                                    lp = false;
+                                }
+                            } else if (last > 1 && cp === 0) {
+                                np = false;
+                                lp = false;
+                                cp = last - 1;
+                            }
+                            if (this.id === 'first' + tp && fp) {
+                                ts.p.page = 1;
+                                selclick = true;
+                            }
+                            if (this.id === 'prev' + tp && pp) {
+                                ts.p.page = (cp - 1);
+                                selclick = true;
+                            }
+                            if (this.id === 'next' + tp && np) {
+                                ts.p.page = (cp + 1);
+                                selclick = true;
+                            }
+                            if (this.id === 'last' + tp && lp) {
+                                ts.p.page = last;
+                                selclick = true;
+                            }
+                            if (selclick) {
+                                if (!clearVals(this.id)) {
+                                    return false;
+                                }
+                                populate();
+                            }
+                            return false;
+                        });
+                    }
+                    if (ts.p.pginput === true) {
+                        $('input.ui-pg-input', "#" + pgcnt).keypress(function (e) {
+                            var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
+                            if (key == 13) {
+                                ts.p.page = ($(this).val() > 0) ? $(this).val() : ts.p.page;
+                                if (!clearVals('user')) {
+                                    return false;
+                                }
+                                populate();
+                                return false;
+                            }
+                            return this;
+                        });
+                    }
+                },
+                sortData = function (index, idxcol, reload, sor) {
+                    if (!ts.p.colModel[idxcol].sortable) {
+                        return;
+                    }
+                    var so;
+                    if (ts.p.savedRow.length > 0) {
+                        return;
+                    }
+                    if (!reload) {
+                        if (ts.p.lastsort == idxcol) {
+                            if (ts.p.sortorder == 'asc') {
+                                ts.p.sortorder = 'desc';
+                            } else if (ts.p.sortorder == 'desc') {
+                                ts.p.sortorder = 'asc';
+                            }
+                        } else {
+                            ts.p.sortorder = ts.p.colModel[idxcol].firstsortorder || 'asc';
+                        }
+                        ts.p.page = 1;
+                    }
+                    if (sor) {
+                        if (ts.p.lastsort == idxcol && ts.p.sortorder == sor && !reload) {
+                            return;
+                        }
+                        else {
+                            ts.p.sortorder = sor;
+                        }
+                    }
+                    var previousSelectedTh = ts.grid.headers[ts.p.lastsort].el, newSelectedTh = ts.grid.headers[idxcol].el;
+
+                    $("span.ui-grid-ico-sort", previousSelectedTh).addClass('ui-state-disabled');
+                    $(previousSelectedTh).attr("aria-selected", "false");
+                    $("span.ui-icon-" + ts.p.sortorder, newSelectedTh).removeClass('ui-state-disabled');
+                    $(newSelectedTh).attr("aria-selected", "true");
+                    if (!ts.p.viewsortcols[0]) {
+                        if (ts.p.lastsort != idxcol) {
+                            $("span.s-ico", previousSelectedTh).hide();
+                            $("span.s-ico", newSelectedTh).show();
+                        }
+                    }
+                    index = index.substring(5 + ts.p.id.length + 1); // bad to be changed!?!
+                    ts.p.sortname = ts.p.colModel[idxcol].index || index;
+                    so = ts.p.sortorder;
+                    if ($(ts).triggerHandler("jqGridSortCol", [index, idxcol, so]) === 'stop') {
+                        ts.p.lastsort = idxcol;
+                        return;
+                    }
+                    if ($.isFunction(ts.p.onSortCol)) {
+                        if (ts.p.onSortCol.call(ts, index, idxcol, so) == 'stop') {
+                            ts.p.lastsort = idxcol;
+                            return;
+                        }
+                    }
+                    if (ts.p.datatype == "local") {
+                        if (ts.p.deselectAfterSort) {
+                            $(ts).jqGrid("resetSelection");
+                        }
+                    } else {
+                        ts.p.selrow = null;
+                        if (ts.p.multiselect) {
+                            setHeadCheckBox(false);
+                        }
+                        ts.p.selarrrow = [];
+                        ts.p.savedRow = [];
+                    }
+                    if (ts.p.scroll) {
+                        var sscroll = ts.grid.bDiv.scrollLeft;
+                        emptyRows.call(ts, true, false);
+                        ts.grid.hDiv.scrollLeft = sscroll;
+                    }
+                    if (ts.p.subGrid && ts.p.datatype == 'local') {
+                        $("td.sgexpanded", "#" + $.jgrid.jqID(ts.p.id)).each(function () {
+                            $(this).trigger("click");
+                        });
+                    }
+                    populate();
+                    ts.p.lastsort = idxcol;
+                    if (ts.p.sortname != index && idxcol) {
+                        ts.p.lastsort = idxcol;
+                    }
+                },
+                setColWidth = function () {
+                    var initwidth = 0, brd = $.jgrid.cellWidth() ? 0 : intNum(ts.p.cellLayout, 0), vc = 0, lvc, scw = intNum(ts.p.scrollOffset, 0), cw, hs = false, aw, gw = 0,
+                        cl = 0, cr;
+                    $.each(ts.p.colModel, function () {
+                        if (typeof this.hidden === 'undefined') {
+                            this.hidden = false;
+                        }
+                        this.widthOrg = cw = intNum(this.width, 0);
+                        if (this.hidden === false) {
+                            initwidth += cw + brd;
+                            if (this.fixed) {
+                                gw += cw + brd;
+                            } else {
+                                vc++;
+                            }
+                            cl++;
+                        }
+                    });
+                    if (isNaN(ts.p.width)) {
+                        ts.p.width = initwidth + ((ts.p.shrinkToFit === false && !isNaN(ts.p.height)) ? scw : 0);
+                    }
+                    grid.width = ts.p.width;
+                    ts.p.tblwidth = initwidth;
+                    if (ts.p.shrinkToFit === false && ts.p.forceFit === true) {
+                        ts.p.forceFit = false;
+                    }
+                    if (ts.p.shrinkToFit === true && vc > 0) {
+                        aw = grid.width - brd * vc - gw;
+                        if (!isNaN(ts.p.height)) {
+                            aw -= scw;
+                            hs = true;
+                        }
+                        initwidth = 0;
+                        $.each(ts.p.colModel, function (i) {
+                            if (this.hidden === false && !this.fixed) {
+                                cw = Math.round(aw * this.width / (ts.p.tblwidth - brd * vc - gw));
+                                this.width = cw;
+                                initwidth += cw;
+                                lvc = i;
+                            }
+                        });
+                        cr = 0;
+                        if (hs) {
+                            if (grid.width - gw - (initwidth + brd * vc) !== scw) {
+                                cr = grid.width - gw - (initwidth + brd * vc) - scw;
+                            }
+                        } else if (!hs && Math.abs(grid.width - gw - (initwidth + brd * vc)) !== 1) {
+                            cr = grid.width - gw - (initwidth + brd * vc);
+                        }
+                        ts.p.colModel[lvc].width += cr;
+                        ts.p.tblwidth = initwidth + cr + brd * vc + gw;
+                        if (ts.p.tblwidth > ts.p.width) {
+                            ts.p.colModel[lvc].width -= (ts.p.tblwidth - parseInt(ts.p.width, 10));
+                            ts.p.tblwidth = ts.p.width;
+                        }
+                    }
+                },
+                nextVisible = function (iCol) {
+                    var ret = iCol, j = iCol, i;
+                    for (i = iCol + 1; i < ts.p.colModel.length; i++) {
+                        if (ts.p.colModel[i].hidden !== true) {
+                            j = i;
+                            break;
+                        }
+                    }
+                    return j - ret;
+                },
+                getOffset = function (iCol) {
+                    var i, ret = {}, brd1 = $.jgrid.cellWidth() ? 0 : ts.p.cellLayout;
+                    ret[0] = ret[1] = ret[2] = 0;
+                    for (i = 0; i <= iCol; i++) {
+                        if (ts.p.colModel[i].hidden === false) {
+                            ret[0] += ts.p.colModel[i].width + brd1;
+                        }
+                    }
+                    if (ts.p.direction == "rtl") {
+                        ret[0] = ts.p.width - ret[0];
+                    }
+                    ret[0] = ret[0] - ts.grid.bDiv.scrollLeft;
+                    if ($(ts.grid.cDiv).is(":visible")) {
+                        ret[1] += $(ts.grid.cDiv).height() + parseInt($(ts.grid.cDiv).css("padding-top"), 10) + parseInt($(ts.grid.cDiv).css("padding-bottom"), 10);
+                    }
+                    if (ts.p.toolbar[0] === true && (ts.p.toolbar[1] == 'top' || ts.p.toolbar[1] == 'both')) {
+                        ret[1] += $(ts.grid.uDiv).height() + parseInt($(ts.grid.uDiv).css("border-top-width"), 10) + parseInt($(ts.grid.uDiv).css("border-bottom-width"), 10);
+                    }
+                    if (ts.p.toppager) {
+                        ret[1] += $(ts.grid.topDiv).height() + parseInt($(ts.grid.topDiv).css("border-bottom-width"), 10);
+                    }
+                    ret[2] += $(ts.grid.bDiv).height() + $(ts.grid.hDiv).height();
+                    return ret;
+                },
+                getColumnHeaderIndex = function (th) {
+                    var i, headers = ts.grid.headers, ci = $.jgrid.getCellIndex(th);
+                    for (i = 0; i < headers.length; i++) {
+                        if (th === headers[i].el) {
+                            ci = i;
+                            break;
+                        }
+                    }
+                    return ci;
+                };
+            this.p.id = this.id;
+            if ($.inArray(ts.p.multikey, sortkeys) == -1) {
+                ts.p.multikey = false;
+            }
+            ts.p.keyIndex = false;
+            for (i = 0; i < ts.p.colModel.length; i++) {
+                ts.p.colModel[i] = $.extend(true, {}, ts.p.cmTemplate, ts.p.colModel[i].template || {}, ts.p.colModel[i]);
+                if (ts.p.keyIndex === false && ts.p.colModel[i].key === true) {
+                    ts.p.keyIndex = i;
+                }
+            }
+            ts.p.sortorder = ts.p.sortorder.toLowerCase();
+            if (ts.p.grouping === true) {
+                ts.p.scroll = false;
+                ts.p.rownumbers = false;
+                //ts.p.subGrid = false; expiremental
+                ts.p.treeGrid = false;
+                ts.p.gridview = true;
+            }
+            if (this.p.treeGrid === true) {
+                try {
+                    $(this).jqGrid("setTreeGrid");
+                } catch (_) {
+                }
+                if (ts.p.datatype != "local") {
+                    ts.p.localReader = {id: "_id_"};
+                }
+            }
+            if (this.p.subGrid) {
+                try {
+                    $(ts).jqGrid("setSubGrid");
+                } catch (s) {
+                }
+            }
+            if (this.p.multiselect) {
+                this.p.colNames.unshift("<input role='checkbox' id='cb_" + this.p.id + "' class='cbox' type='checkbox'/>");
+                this.p.colModel.unshift({name: 'cb', width: $.jgrid.cellWidth() ? ts.p.multiselectWidth + ts.p.cellLayout : ts.p.multiselectWidth, sortable: false, resizable: false, hidedlg: true, search: false, align: 'center', fixed: true});
+            }
+            if (this.p.rownumbers) {
+                this.p.colNames.unshift("");
+                this.p.colModel.unshift({name: 'rn', width: ts.p.rownumWidth, sortable: false, resizable: false, hidedlg: true, search: false, align: 'center', fixed: true});
+            }
+            ts.p.xmlReader = $.extend(true, {
+                root: "rows",
+                row: "row",
+                page: "rows>page",
+                total: "rows>total",
+                records: "rows>records",
+                repeatitems: true,
+                cell: "cell",
+                id: "[id]",
+                userdata: "userdata",
+                subgrid: {root: "rows", row: "row", repeatitems: true, cell: "cell"}
+            }, ts.p.xmlReader);
+            ts.p.jsonReader = $.extend(true, {
+                root: "rows",
+                page: "page",
+                total: "total",
+                records: "records",
+                repeatitems: true,
+                cell: "cell",
+                id: "id",
+                userdata: "userdata",
+                subgrid: {root: "rows", repeatitems: true, cell: "cell"}
+            }, ts.p.jsonReader);
+            ts.p.localReader = $.extend(true, {
+                root: "rows",
+                page: "page",
+                total: "total",
+                records: "records",
+                repeatitems: false,
+                cell: "cell",
+                id: "id",
+                userdata: "userdata",
+                subgrid: {root: "rows", repeatitems: true, cell: "cell"}
+            }, ts.p.localReader);
+            if (ts.p.scroll) {
+                ts.p.pgbuttons = false;
+                ts.p.pginput = false;
+                ts.p.rowList = [];
+            }
+            if (ts.p.data.length) {
+                refreshIndex();
+            }
+            var thead = "<thead><tr class='ui-jqgrid-labels' role='rowheader'>",
+                tdc, idn, w, res, sort,
+                td, ptr, tbody, imgs, iac = "", idc = "";
+            if (ts.p.shrinkToFit === true && ts.p.forceFit === true) {
+                for (i = ts.p.colModel.length - 1; i >= 0; i--) {
+                    if (!ts.p.colModel[i].hidden) {
+                        ts.p.colModel[i].resizable = false;
+                        break;
+                    }
+                }
+            }
+            if (ts.p.viewsortcols[1] == 'horizontal') {
+                iac = " ui-i-asc";
+                idc = " ui-i-desc";
+            }
+            tdc = isMSIE ? "class='ui-th-div-ie'" : "";
+            imgs = "<span class='s-ico' style='display:none'><span sort='asc' class='ui-grid-ico-sort ui-icon-asc" + iac + " ui-state-disabled ui-icon ui-icon-triangle-1-n ui-sort-" + dir + "'></span>";
+            imgs += "<span sort='desc' class='ui-grid-ico-sort ui-icon-desc" + idc + " ui-state-disabled ui-icon ui-icon-triangle-1-s ui-sort-" + dir + "'></span></span>";
+            for (i = 0; i < this.p.colNames.length; i++) {
+                var tooltip = ts.p.headertitles ? (" title=\"" + $.jgrid.stripHtml(ts.p.colNames[i]) + "\"") : "";
+                thead += "<th id='" + ts.p.id + "_" + ts.p.colModel[i].name + "' role='columnheader' class='ui-state-default ui-th-column ui-th-" + dir + "'" + tooltip + ">";
+                idn = ts.p.colModel[i].index || ts.p.colModel[i].name;
+                thead += "<div id='jqgh_" + ts.p.id + "_" + ts.p.colModel[i].name + "' " + tdc + ">" + ts.p.colNames[i];
+                if (!ts.p.colModel[i].width) {
+                    ts.p.colModel[i].width = 150;
+                }
+                else {
+                    ts.p.colModel[i].width = parseInt(ts.p.colModel[i].width, 10);
+                }
+                if (typeof(ts.p.colModel[i].title) !== "boolean") {
+                    ts.p.colModel[i].title = true;
+                }
+                if (idn == ts.p.sortname) {
+                    ts.p.lastsort = i;
+                }
+                thead += imgs + "</div></th>";
+            }
+            thead += "</tr></thead>";
+            imgs = null;
+            $(this).append(thead);
+            $("thead tr:first th", this).hover(function () {
+                $(this).addClass('ui-state-hover');
+            }, function () {
+                $(this).removeClass('ui-state-hover');
+            });
+            if (this.p.multiselect) {
+                var emp = [], chk;
+                $('#cb_' + $.jgrid.jqID(ts.p.id), this).bind('click', function () {
+                    ts.p.selarrrow = [];
+                    var froz = ts.p.frozenColumns === true ? ts.p.id + "_frozen" : "";
+                    if (this.checked) {
+                        $(ts.rows).each(function (i) {
+                            if (i > 0) {
+                                if (!$(this).hasClass("ui-subgrid") && !$(this).hasClass("jqgroup") && !$(this).hasClass('ui-state-disabled')) {
+                                    $("#jqg_" + $.jgrid.jqID(ts.p.id) + "_" + $.jgrid.jqID(this.id))[ts.p.useProp ? 'prop' : 'attr']("checked", true);
+                                    $(this).addClass("ui-state-highlight").attr("aria-selected", "true");
+                                    ts.p.selarrrow.push(this.id);
+                                    ts.p.selrow = this.id;
+                                    if (froz) {
+                                        $("#jqg_" + $.jgrid.jqID(ts.p.id) + "_" + $.jgrid.jqID(this.id), ts.grid.fbDiv)[ts.p.useProp ? 'prop' : 'attr']("checked", true);
+                                        $("#" + $.jgrid.jqID(this.id), ts.grid.fbDiv).addClass("ui-state-highlight");
+                                    }
+                                }
+                            }
+                        });
+                        chk = true;
+                        emp = [];
+                    }
+                    else {
+                        $(ts.rows).each(function (i) {
+                            if (i > 0) {
+                                if (!$(this).hasClass("ui-subgrid") && !$(this).hasClass('ui-state-disabled')) {
+                                    $("#jqg_" + $.jgrid.jqID(ts.p.id) + "_" + $.jgrid.jqID(this.id))[ts.p.useProp ? 'prop' : 'attr']("checked", false);
+                                    $(this).removeClass("ui-state-highlight").attr("aria-selected", "false");
+                                    emp.push(this.id);
+                                    if (froz) {
+                                        $("#jqg_" + $.jgrid.jqID(ts.p.id) + "_" + $.jgrid.jqID(this.id), ts.grid.fbDiv)[ts.p.useProp ? 'prop' : 'attr']("checked", false);
+                                        $("#" + $.jgrid.jqID(this.id), ts.grid.fbDiv).removeClass("ui-state-highlight");
+                                    }
+                                }
+                            }
+                        });
+                        ts.p.selrow = null;
+                        chk = false;
+                    }
+                    $(ts).triggerHandler("jqGridSelectAll", [chk ? ts.p.selarrrow : emp, chk]);
+                    if ($.isFunction(ts.p.onSelectAll)) {
+                        ts.p.onSelectAll.call(ts, chk ? ts.p.selarrrow : emp, chk);
+                    }
+                });
+            }
+
+            if (ts.p.autowidth === true) {
+                var pw = $(eg).innerWidth();
+                ts.p.width = pw > 0 ? pw : 'nw';
+            }
+            setColWidth();
+            $(eg).css("width", grid.width + "px").append("<div class='ui-jqgrid-resize-mark' id='rs_m" + ts.p.id + "'>&#160;</div>");
+            $(gv).css("width", grid.width + "px");
+            thead = $("thead:first", ts).get(0);
+            var tfoot = "";
+            if (ts.p.footerrow) {
+                tfoot += "<table role='grid' style='width:" + ts.p.tblwidth + "px' class='ui-jqgrid-ftable' cellspacing='0' cellpadding='0' border='0'><tbody><tr role='row' class='ui-widget-content footrow footrow-" + dir + "'>";
+            }
+            var thr = $("tr:first", thead),
+                firstr = "<tr class='jqgfirstrow' role='row' style='height:auto'>";
+            ts.p.disableClick = false;
+            $("th", thr).each(function (j) {
+                w = ts.p.colModel[j].width;
+                if (typeof ts.p.colModel[j].resizable === 'undefined') {
+                    ts.p.colModel[j].resizable = true;
+                }
+                if (ts.p.colModel[j].resizable) {
+                    res = document.createElement("span");
+                    $(res).html("&#160;").addClass('ui-jqgrid-resize ui-jqgrid-resize-' + dir);
+                    if (!$.browser.opera) {
+                        $(res).css("cursor", "col-resize");
+                    }
+                    $(this).addClass(ts.p.resizeclass);
+                } else {
+                    res = "";
+                }
+                $(this).css("width", w + "px").prepend(res);
+                var hdcol = "";
+                if (ts.p.colModel[j].hidden) {
+                    $(this).css("display", "none");
+                    hdcol = "display:none;";
+                }
+                firstr += "<td role='gridcell' style='height:0px;width:" + w + "px;" + hdcol + "'></td>";
+                grid.headers[j] = { width: w, el: this };
+                sort = ts.p.colModel[j].sortable;
+                if (typeof sort !== 'boolean') {
+                    ts.p.colModel[j].sortable = true;
+                    sort = true;
+                }
+                var nm = ts.p.colModel[j].name;
+                if (!(nm == 'cb' || nm == 'subgrid' || nm == 'rn')) {
+                    if (ts.p.viewsortcols[2]) {
+                        $(">div", this).addClass('ui-jqgrid-sortable');
+                    }
+                }
+                if (sort) {
+                    if (ts.p.viewsortcols[0]) {
+                        $("div span.s-ico", this).show();
+                        if (j == ts.p.lastsort) {
+                            $("div span.ui-icon-" + ts.p.sortorder, this).removeClass("ui-state-disabled");
+                        }
+                    }
+                    else if (j == ts.p.lastsort) {
+                        $("div span.s-ico", this).show();
+                        $("div span.ui-icon-" + ts.p.sortorder, this).removeClass("ui-state-disabled");
+                    }
+                }
+                if (ts.p.footerrow) {
+                    tfoot += "<td role='gridcell' " + formatCol(j, 0, '', null, '', false) + ">&#160;</td>";
+                }
+            }).mousedown(function (e) {
+                    if ($(e.target).closest("th>span.ui-jqgrid-resize").length != 1) {
+                        return;
+                    }
+                    var ci = getColumnHeaderIndex(this);
+                    if (ts.p.forceFit === true) {
+                        ts.p.nv = nextVisible(ci);
+                    }
+                    grid.dragStart(ci, e, getOffset(ci));
+                    return false;
+                }).click(function (e) {
+                    if (ts.p.disableClick) {
+                        ts.p.disableClick = false;
+                        return false;
+                    }
+                    var s = "th>div.ui-jqgrid-sortable", r, d;
+                    if (!ts.p.viewsortcols[2]) {
+                        s = "th>div>span>span.ui-grid-ico-sort";
+                    }
+                    var t = $(e.target).closest(s);
+                    if (t.length != 1) {
+                        return;
+                    }
+                    var ci = getColumnHeaderIndex(this);
+                    if (!ts.p.viewsortcols[2]) {
+                        r = true;
+                        d = t.attr("sort");
+                    }
+                    sortData($('div', this)[0].id, ci, r, d);
+                    return false;
+                });
+            if (ts.p.sortable && $.fn.sortable) {
+                try {
+                    $(ts).jqGrid("sortableColumns", thr);
+                } catch (e) {
+                }
+            }
+            if (ts.p.footerrow) {
+                tfoot += "</tr></tbody></table>";
+            }
+            firstr += "</tr>";
+            tbody = document.createElement("tbody");
+            this.appendChild(tbody);
+            $(this).addClass('ui-jqgrid-btable').append(firstr);
+            firstr = null;
+            var hTable = $("<table class='ui-jqgrid-htable' style='width:" + ts.p.tblwidth + "px' role='grid' aria-labelledby='gbox_" + this.id + "' cellspacing='0' cellpadding='0' border='0'></table>").append(thead),
+                hg = (ts.p.caption && ts.p.hiddengrid === true) ? true : false,
+                hb = $("<div class='ui-jqgrid-hbox" + (dir == "rtl" ? "-rtl" : "" ) + "'></div>");
+            thead = null;
+            grid.hDiv = document.createElement("div");
+            $(grid.hDiv)
+                .css({ width: grid.width + "px"})
+                .addClass("ui-state-default ui-jqgrid-hdiv")
+                .append(hb);
+            $(hb).append(hTable);
+            hTable = null;
+            if (hg) {
+                $(grid.hDiv).hide();
+            }
+            if (ts.p.pager) {
+                // TBD -- escape ts.p.pager here?
+                if (typeof ts.p.pager == "string") {
+                    if (ts.p.pager.substr(0, 1) != "#") {
+                        ts.p.pager = "#" + ts.p.pager;
+                    }
+                }
+                else {
+                    ts.p.pager = "#" + $(ts.p.pager).attr("id");
+                }
+                $(ts.p.pager).css({width: grid.width + "px"}).appendTo(eg).addClass('ui-state-default ui-jqgrid-pager ui-corner-bottom');
+                if (hg) {
+                    $(ts.p.pager).hide();
+                }
+                setPager(ts.p.pager, '');
+            }
+            if (ts.p.cellEdit === false && ts.p.hoverrows === true) {
+                $(ts).bind('mouseover',function (e) {
+                    ptr = $(e.target).closest("tr.jqgrow");
+                    if ($(ptr).attr("class") !== "ui-subgrid") {
+                        $(ptr).addClass("ui-state-hover");
+                    }
+                }).bind('mouseout', function (e) {
+                        ptr = $(e.target).closest("tr.jqgrow");
+                        $(ptr).removeClass("ui-state-hover");
+                    });
+            }
+            var ri, ci, tdHtml;
+            $(ts).before(grid.hDiv).click(function (e) {
+                td = e.target;
+                ptr = $(td, ts.rows).closest("tr.jqgrow");
+                if ($(ptr).length === 0 || ptr[0].className.indexOf('ui-state-disabled') > -1 || ($(td, ts).closest("table.ui-jqgrid-btable").attr('id') || '').replace("_frozen", "") !== ts.id) {
+                    return this;
+                }
+                var scb = $(td).hasClass("cbox"),
+                    cSel = $(ts).triggerHandler("jqGridBeforeSelectRow", [ptr[0].id, e]);
+                cSel = (cSel === false || cSel === 'stop') ? false : true;
+                if (cSel && $.isFunction(ts.p.beforeSelectRow)) {
+                    cSel = ts.p.beforeSelectRow.call(ts, ptr[0].id, e);
+                }
+                if (td.tagName == 'A' || ((td.tagName == 'INPUT' || td.tagName == 'TEXTAREA' || td.tagName == 'OPTION' || td.tagName == 'SELECT' ) && !scb)) {
+                    return;
+                }
+                if (cSel === true) {
+                    ri = ptr[0].id;
+                    ci = $.jgrid.getCellIndex(td);
+                    tdHtml = $(td).closest("td,th").html();
+                    $(ts).triggerHandler("jqGridCellSelect", [ri, ci, tdHtml, e]);
+                    if ($.isFunction(ts.p.onCellSelect)) {
+                        ts.p.onCellSelect.call(ts, ri, ci, tdHtml, e);
+                    }
+                    if (ts.p.cellEdit === true) {
+                        if (ts.p.multiselect && scb) {
+                            $(ts).jqGrid("setSelection", ri, true, e);
+                        } else {
+                            ri = ptr[0].rowIndex;
+                            try {
+                                $(ts).jqGrid("editCell", ri, ci, true);
+                            } catch (_) {
+                            }
+                        }
+                    } else if (!ts.p.multikey) {
+                        if (ts.p.multiselect && ts.p.multiboxonly) {
+                            if (scb) {
+                                $(ts).jqGrid("setSelection", ri, true, e);
+                            }
+                            else {
+                                var frz = ts.p.frozenColumns ? ts.p.id + "_frozen" : "";
+                                $(ts.p.selarrrow).each(function (i, n) {
+                                    var ind = ts.rows.namedItem(n);
+                                    $(ind).removeClass("ui-state-highlight");
+                                    $("#jqg_" + $.jgrid.jqID(ts.p.id) + "_" + $.jgrid.jqID(n))[ts.p.useProp ? 'prop' : 'attr']("checked", false);
+                                    if (frz) {
+                                        $("#" + $.jgrid.jqID(n), "#" + $.jgrid.jqID(frz)).removeClass("ui-state-highlight");
+                                        $("#jqg_" + $.jgrid.jqID(ts.p.id) + "_" + $.jgrid.jqID(n), "#" + $.jgrid.jqID(frz))[ts.p.useProp ? 'prop' : 'attr']("checked", false);
+                                    }
+                                });
+                                ts.p.selarrrow = [];
+                                $(ts).jqGrid("setSelection", ri, true, e);
+                            }
+                        } else {
+                            $(ts).jqGrid("setSelection", ri, true, e);
+                        }
+                    } else {
+                        if (e[ts.p.multikey]) {
+                            $(ts).jqGrid("setSelection", ri, true, e);
+                        } else if (ts.p.multiselect && scb) {
+                            scb = $("#jqg_" + $.jgrid.jqID(ts.p.id) + "_" + ri).is(":checked");
+                            $("#jqg_" + $.jgrid.jqID(ts.p.id) + "_" + ri)[ts.p.useProp ? 'prop' : 'attr']("checked", scb);
+                        }
+                    }
+                }
+            }).bind('reloadGrid', function (e, opts) {
+                    if (ts.p.treeGrid === true) {
+                        ts.p.datatype = ts.p.treedatatype;
+                    }
+                    if (opts && opts.current) {
+                        ts.grid.selectionPreserver(ts);
+                    }
+                    if (ts.p.datatype == "local") {
+                        $(ts).jqGrid("resetSelection");
+                        if (ts.p.data.length) {
+                            refreshIndex();
+                        }
+                    }
+                    else if (!ts.p.treeGrid) {
+                        ts.p.selrow = null;
+                        if (ts.p.multiselect) {
+                            ts.p.selarrrow = [];
+                            setHeadCheckBox(false);
+                        }
+                        ts.p.savedRow = [];
+                    }
+                    if (ts.p.scroll) {
+                        emptyRows.call(ts, true, false);
+                    }
+                    if (opts && opts.page) {
+                        var page = opts.page;
+                        if (page > ts.p.lastpage) {
+                            page = ts.p.lastpage;
+                        }
+                        if (page < 1) {
+                            page = 1;
+                        }
+                        ts.p.page = page;
+                        if (ts.grid.prevRowHeight) {
+                            ts.grid.bDiv.scrollTop = (page - 1) * ts.grid.prevRowHeight * ts.p.rowNum;
+                        } else {
+                            ts.grid.bDiv.scrollTop = 0;
+                        }
+                    }
+                    if (ts.grid.prevRowHeight && ts.p.scroll) {
+                        delete ts.p.lastpage;
+                        ts.grid.populateVisible();
+                    } else {
+                        ts.grid.populate();
+                    }
+                    if (ts.p._inlinenav === true) {
+                        $(ts).jqGrid('showAddEditButtons');
+                    }
+                    return false;
+                })
+                .dblclick(function (e) {
+                    td = e.target;
+                    ptr = $(td, ts.rows).closest("tr.jqgrow");
+                    if ($(ptr).length === 0) {
+                        return;
+                    }
+                    ri = ptr[0].rowIndex;
+                    ci = $.jgrid.getCellIndex(td);
+                    $(ts).triggerHandler("jqGridDblClickRow", [$(ptr).attr("id"), ri, ci, e]);
+                    if ($.isFunction(this.p.ondblClickRow)) {
+                        ts.p.ondblClickRow.call(ts, $(ptr).attr("id"), ri, ci, e);
+                    }
+                })
+                .bind('contextmenu', function (e) {
+                    td = e.target;
+                    ptr = $(td, ts.rows).closest("tr.jqgrow");
+                    if ($(ptr).length === 0) {
+                        return;
+                    }
+                    if (!ts.p.multiselect) {
+                        $(ts).jqGrid("setSelection", ptr[0].id, true, e);
+                    }
+                    ri = ptr[0].rowIndex;
+                    ci = $.jgrid.getCellIndex(td);
+                    $(ts).triggerHandler("jqGridRightClickRow", [$(ptr).attr("id"), ri, ci, e]);
+                    if ($.isFunction(this.p.onRightClickRow)) {
+                        ts.p.onRightClickRow.call(ts, $(ptr).attr("id"), ri, ci, e);
+                    }
+                });
+            grid.bDiv = document.createElement("div");
+            if (isMSIE) {
+                if (String(ts.p.height).toLowerCase() === "auto") {
+                    ts.p.height = "100%";
+                }
+            }
+            $(grid.bDiv)
+                .append($('<div style="position:relative;' + (isMSIE && $.browser.version < 8 ? "height:0.01%;" : "") + '"></div>').append('<div></div>').append(this))
+                .addClass("ui-jqgrid-bdiv")
+                .css({ height: ts.p.height + (isNaN(ts.p.height) ? "" : "px"), width: (grid.width) + "px"})
+                .scroll(grid.scrollGrid);
+            $("table:first", grid.bDiv).css({width: ts.p.tblwidth + "px"});
+            if (isMSIE) {
+                if ($("tbody", this).size() == 2) {
+                    $("tbody:gt(0)", this).remove();
+                }
+                if (ts.p.multikey) {
+                    $(grid.bDiv).bind("selectstart", function () {
+                        return false;
+                    });
+                }
+            } else {
+                if (ts.p.multikey) {
+                    $(grid.bDiv).bind("mousedown", function () {
+                        return false;
+                    });
+                }
+            }
+            if (hg) {
+                $(grid.bDiv).hide();
+            }
+            grid.cDiv = document.createElement("div");
+            var arf = ts.p.hidegrid === true ? $("<a role='link' href='javascript:void(0)'/>").addClass('ui-jqgrid-titlebar-close HeaderButton').hover(
+                function () {
+                    arf.addClass('ui-state-hover');
+                },
+                function () {
+                    arf.removeClass('ui-state-hover');
+                })
+                .append("<span class='ui-icon ui-icon-circle-triangle-n'></span>").css((dir == "rtl" ? "left" : "right"), "0px") : "";
+            $(grid.cDiv).append(arf).append("<span class='ui-jqgrid-title" + (dir == "rtl" ? "-rtl" : "" ) + "'>" + ts.p.caption + "</span>")
+                .addClass("ui-jqgrid-titlebar ui-widget-header ui-corner-top ui-helper-clearfix");
+            $(grid.cDiv).insertBefore(grid.hDiv);
+            if (ts.p.toolbar[0]) {
+                grid.uDiv = document.createElement("div");
+                if (ts.p.toolbar[1] == "top") {
+                    $(grid.uDiv).insertBefore(grid.hDiv);
+                }
+                else if (ts.p.toolbar[1] == "bottom") {
+                    $(grid.uDiv).insertAfter(grid.hDiv);
+                }
+                if (ts.p.toolbar[1] == "both") {
+                    grid.ubDiv = document.createElement("div");
+                    $(grid.uDiv).insertBefore(grid.hDiv).addClass("ui-userdata ui-state-default").attr("id", "t_" + this.id);
+                    $(grid.ubDiv).insertAfter(grid.hDiv).addClass("ui-userdata ui-state-default").attr("id", "tb_" + this.id);
+                    if (hg) {
+                        $(grid.ubDiv).hide();
+                    }
+                } else {
+                    $(grid.uDiv).width(grid.width).addClass("ui-userdata ui-state-default").attr("id", "t_" + this.id);
+                }
+                if (hg) {
+                    $(grid.uDiv).hide();
+                }
+            }
+            if (ts.p.toppager) {
+                ts.p.toppager = $.jgrid.jqID(ts.p.id) + "_toppager";
+                grid.topDiv = $("<div id='" + ts.p.toppager + "'></div>")[0];
+                ts.p.toppager = "#" + ts.p.toppager;
+                $(grid.topDiv).insertBefore(grid.hDiv).addClass('ui-state-default ui-jqgrid-toppager').width(grid.width);
+                setPager(ts.p.toppager, '_t');
+            }
+            if (ts.p.footerrow) {
+                grid.sDiv = $("<div class='ui-jqgrid-sdiv'></div>")[0];
+                hb = $("<div class='ui-jqgrid-hbox" + (dir == "rtl" ? "-rtl" : "") + "'></div>");
+                $(grid.sDiv).append(hb).insertAfter(grid.hDiv).width(grid.width);
+                $(hb).append(tfoot);
+                grid.footers = $(".ui-jqgrid-ftable", grid.sDiv)[0].rows[0].cells;
+                if (ts.p.rownumbers) {
+                    grid.footers[0].className = 'ui-state-default jqgrid-rownum';
+                }
+                if (hg) {
+                    $(grid.sDiv).hide();
+                }
+            }
+            hb = null;
+            if (ts.p.caption) {
+                var tdt = ts.p.datatype;
+                if (ts.p.hidegrid === true) {
+                    $(".ui-jqgrid-titlebar-close", grid.cDiv).click(function (e) {
+                        var onHdCl = $.isFunction(ts.p.onHeaderClick),
+                            elems = ".ui-jqgrid-bdiv, .ui-jqgrid-hdiv, .ui-jqgrid-pager, .ui-jqgrid-sdiv",
+                            counter, self = this;
+                        if (ts.p.toolbar[0] === true) {
+                            if (ts.p.toolbar[1] == 'both') {
+                                elems += ', #' + $(grid.ubDiv).attr('id');
+                            }
+                            elems += ', #' + $(grid.uDiv).attr('id');
+                        }
+                        counter = $(elems, "#gview_" + $.jgrid.jqID(ts.p.id)).length;
+
+                        if (ts.p.gridstate == 'visible') {
+                            $(elems, "#gbox_" + $.jgrid.jqID(ts.p.id)).slideUp("fast", function () {
+                                counter--;
+                                if (counter === 0) {
+                                    $("span", self).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-s");
+                                    ts.p.gridstate = 'hidden';
+                                    if ($("#gbox_" + $.jgrid.jqID(ts.p.id)).hasClass("ui-resizable")) {
+                                        $(".ui-resizable-handle", "#gbox_" + $.jgrid.jqID(ts.p.id)).hide();
+                                    }
+                                    $(ts).triggerHandler("jqGridHeaderClick", [ts.p.gridstate, e]);
+                                    if (onHdCl) {
+                                        if (!hg) {
+                                            ts.p.onHeaderClick.call(ts, ts.p.gridstate, e);
+                                        }
+                                    }
+                                }
+                            });
+                        } else if (ts.p.gridstate == 'hidden') {
+                            $(elems, "#gbox_" + $.jgrid.jqID(ts.p.id)).slideDown("fast", function () {
+                                counter--;
+                                if (counter === 0) {
+                                    $("span", self).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-n");
+                                    if (hg) {
+                                        ts.p.datatype = tdt;
+                                        populate();
+                                        hg = false;
+                                    }
+                                    ts.p.gridstate = 'visible';
+                                    if ($("#gbox_" + $.jgrid.jqID(ts.p.id)).hasClass("ui-resizable")) {
+                                        $(".ui-resizable-handle", "#gbox_" + $.jgrid.jqID(ts.p.id)).show();
+                                    }
+                                    $(ts).triggerHandler("jqGridHeaderClick", [ts.p.gridstate, e]);
+                                    if (onHdCl) {
+                                        if (!hg) {
+                                            ts.p.onHeaderClick.call(ts, ts.p.gridstate, e);
+                                        }
+                                    }
+                                }
+                            });
+                        }
+                        return false;
+                    });
+                    if (hg) {
+                        ts.p.datatype = "local";
+                        $(".ui-jqgrid-titlebar-close", grid.cDiv).trigger("click");
+                    }
+                }
+            } else {
+                $(grid.cDiv).hide();
+            }
+            $(grid.hDiv).after(grid.bDiv)
+                .mousemove(function (e) {
+                    if (grid.resizing) {
+                        grid.dragMove(e);
+                        return false;
+                    }
+                });
+            $(".ui-jqgrid-labels", grid.hDiv).bind("selectstart", function () {
+                return false;
+            });
+            $(document).mouseup(function () {
+                if (grid.resizing) {
+                    grid.dragEnd();
+                    return false;
+                }
+                return true;
+            });
+            ts.formatCol = formatCol;
+            ts.sortData = sortData;
+            ts.updatepager = updatepager;
+            ts.refreshIndex = refreshIndex;
+            ts.setHeadCheckBox = setHeadCheckBox;
+            ts.constructTr = constructTr;
+            ts.formatter = function (rowId, cellval, colpos, rwdat, act) {
+                return formatter(rowId, cellval, colpos, rwdat, act);
+            };
+            $.extend(grid, {populate: populate, emptyRows: emptyRows});
+            this.grid = grid;
+            ts.addXmlData = function (d) {
+                addXmlData(d, ts.grid.bDiv);
+            };
+            ts.addJSONData = function (d) {
+                addJSONData(d, ts.grid.bDiv);
+            };
+            this.grid.cols = this.rows[0].cells;
+
+            populate();
+            ts.p.hiddengrid = false;
+            $(window).unload(function () {
+                ts = null;
+            });
+        });
+    };
+    $.jgrid.extend({
+        getGridParam: function (pName) {
+            var $t = this[0];
+            if (!$t || !$t.grid) {
+                return;
+            }
+            if (!pName) {
+                return $t.p;
+            }
+            else {
+                return typeof($t.p[pName]) != "undefined" ? $t.p[pName] : null;
+            }
+        },
+        setGridParam: function (newParams) {
+            return this.each(function () {
+                if (this.grid && typeof(newParams) === 'object') {
+                    $.extend(true, this.p, newParams);
+                }
+            });
+        },
+        getDataIDs: function () {
+            var ids = [], i = 0, len, j = 0;
+            this.each(function () {
+                len = this.rows.length;
+                if (len && len > 0) {
+                    while (i < len) {
+                        if ($(this.rows[i]).hasClass('jqgrow')) {
+                            ids[j] = this.rows[i].id;
+                            j++;
+                        }
+                        i++;
+                    }
+                }
+            });
+            return ids;
+        },
+        setSelection: function (selection, onsr, e) {
+            return this.each(function () {
+                var $t = this, stat, pt, ner, ia, tpsr, fid;
+                if (selection === undefined) {
+                    return;
+                }
+                onsr = onsr === false ? false : true;
+                pt = $t.rows.namedItem(selection + "");
+                if (!pt || !pt.className || pt.className.indexOf('ui-state-disabled') > -1) {
+                    return;
+                }
+                function scrGrid(iR) {
+                    var ch = $($t.grid.bDiv)[0].clientHeight,
+                        st = $($t.grid.bDiv)[0].scrollTop,
+                        rpos = $t.rows[iR].offsetTop,
+                        rh = $t.rows[iR].clientHeight;
+                    if (rpos + rh >= ch + st) {
+                        $($t.grid.bDiv)[0].scrollTop = rpos - (ch + st) + rh + st;
+                    }
+                    else if (rpos < ch + st) {
+                        if (rpos < st) {
+                            $($t.grid.bDiv)[0].scrollTop = rpos;
+                        }
+                    }
+                }
+
+                if ($t.p.scrollrows === true) {
+                    ner = $t.rows.namedItem(selection).rowIndex;
+                    if (ner >= 0) {
+                        scrGrid(ner);
+                    }
+                }
+                if ($t.p.frozenColumns === true) {
+                    fid = $t.p.id + "_frozen";
+                }
+                if (!$t.p.multiselect) {
+                    if (pt.className !== "ui-subgrid") {
+                        if ($t.p.selrow != pt.id) {
+                            $($t.rows.namedItem($t.p.selrow)).removeClass("ui-state-highlight").attr({"aria-selected": "false", "tabindex": "-1"});
+                            $(pt).addClass("ui-state-highlight").attr({"aria-selected": "true", "tabindex": "0"});//.focus();
+                            if (fid) {
+                                $("#" + $.jgrid.jqID($t.p.selrow), "#" + $.jgrid.jqID(fid)).removeClass("ui-state-highlight");
+                                $("#" + $.jgrid.jqID(selection), "#" + $.jgrid.jqID(fid)).addClass("ui-state-highlight");
+                            }
+                            stat = true;
+                        } else {
+                            stat = false;
+                        }
+                        $t.p.selrow = pt.id;
+                        $($t).triggerHandler("jqGridSelectRow", [pt.id, stat, e]);
+                        if ($t.p.onSelectRow && onsr) {
+                            $t.p.onSelectRow.call($t, pt.id, stat, e);
+                        }
+                    }
+                } else {
+                    //unselect selectall checkbox when deselecting a specific row
+                    $t.setHeadCheckBox(false);
+                    $t.p.selrow = pt.id;
+                    ia = $.inArray($t.p.selrow, $t.p.selarrrow);
+                    if (ia === -1) {
+                        if (pt.className !== "ui-subgrid") {
+                            $(pt).addClass("ui-state-highlight").attr("aria-selected", "true");
+                        }
+                        stat = true;
+                        $t.p.selarrrow.push($t.p.selrow);
+                    } else {
+                        if (pt.className !== "ui-subgrid") {
+                            $(pt).removeClass("ui-state-highlight").attr("aria-selected", "false");
+                        }
+                        stat = false;
+                        $t.p.selarrrow.splice(ia, 1);
+                        tpsr = $t.p.selarrrow[0];
+                        $t.p.selrow = (tpsr === undefined) ? null : tpsr;
+                    }
+                    $("#jqg_" + $.jgrid.jqID($t.p.id) + "_" + $.jgrid.jqID(pt.id))[$t.p.useProp ? 'prop' : 'attr']("checked", stat);
+                    if (fid) {
+                        if (ia === -1) {
+                            $("#" + $.jgrid.jqID(selection), "#" + $.jgrid.jqID(fid)).addClass("ui-state-highlight");
+                        } else {
+                            $("#" + $.jgrid.jqID(selection), "#" + $.jgrid.jqID(fid)).removeClass("ui-state-highlight");
+                        }
+                        $("#jqg_" + $.jgrid.jqID($t.p.id) + "_" + $.jgrid.jqID(selection), "#" + $.jgrid.jqID(fid))[$t.p.useProp ? 'prop' : 'attr']("checked", stat);
+                    }
+                    $($t).triggerHandler("jqGridSelectRow", [pt.id, stat, e]);
+                    if ($t.p.onSelectRow && onsr) {
+                        $t.p.onSelectRow.call($t, pt.id, stat, e);
+                    }
+                }
+            });
+        },
+        resetSelection: function (rowid) {
+            return this.each(function () {
+                var t = this, ind, sr, fid;
+                if (t.p.frozenColumns === true) {
+                    fid = t.p.id + "_frozen";
+                }
+                if (typeof(rowid) !== "undefined") {
+                    sr = rowid === t.p.selrow ? t.p.selrow : rowid;
+                    $("#" + $.jgrid.jqID(t.p.id) + " tbody:first tr#" + $.jgrid.jqID(sr)).removeClass("ui-state-highlight").attr("aria-selected", "false");
+                    if (fid) {
+                        $("#" + $.jgrid.jqID(sr), "#" + $.jgrid.jqID(fid)).removeClass("ui-state-highlight");
+                    }
+                    if (t.p.multiselect) {
+                        $("#jqg_" + $.jgrid.jqID(t.p.id) + "_" + $.jgrid.jqID(sr), "#" + $.jgrid.jqID(t.p.id))[t.p.useProp ? 'prop' : 'attr']("checked", false);
+                        if (fid) {
+                            $("#jqg_" + $.jgrid.jqID(t.p.id) + "_" + $.jgrid.jqID(sr), "#" + $.jgrid.jqID(fid))[t.p.useProp ? 'prop' : 'attr']("checked", false);
+                        }
+                        t.setHeadCheckBox(false);
+                    }
+                    sr = null;
+                } else if (!t.p.multiselect) {
+                    if (t.p.selrow) {
+                        $("#" + $.jgrid.jqID(t.p.id) + " tbody:first tr#" + $.jgrid.jqID(t.p.selrow)).removeClass("ui-state-highlight").attr("aria-selected", "false");
+                        if (fid) {
+                            $("#" + $.jgrid.jqID(t.p.selrow), "#" + $.jgrid.jqID(fid)).removeClass("ui-state-highlight");
+                        }
+                        t.p.selrow = null;
+                    }
+                } else {
+                    $(t.p.selarrrow).each(function (i, n) {
+                        ind = t.rows.namedItem(n);
+                        $(ind).removeClass("ui-state-highlight").attr("aria-selected", "false");
+                        $("#jqg_" + $.jgrid.jqID(t.p.id) + "_" + $.jgrid.jqID(n))[t.p.useProp ? 'prop' : 'attr']("checked", false);
+                        if (fid) {
+                            $("#" + $.jgrid.jqID(n), "#" + $.jgrid.jqID(fid)).removeClass("ui-state-highlight");
+                            $("#jqg_" + $.jgrid.jqID(t.p.id) + "_" + $.jgrid.jqID(n), "#" + $.jgrid.jqID(fid))[t.p.useProp ? 'prop' : 'attr']("checked", false);
+                        }
+                    });
+                    t.setHeadCheckBox(false);
+                    t.p.selarrrow = [];
+                }
+                if (t.p.cellEdit === true) {
+                    if (parseInt(t.p.iCol, 10) >= 0 && parseInt(t.p.iRow, 10) >= 0) {
+                        $("td:eq(" + t.p.iCol + ")", t.rows[t.p.iRow]).removeClass("edit-cell ui-state-highlight");
+                        $(t.rows[t.p.iRow]).removeClass("selected-row ui-state-hover");
+                    }
+                }
+                t.p.savedRow = [];
+            });
+        },
+        getRowData: function (rowid) {
+            var res = {}, resall, getall = false, len, j = 0;
+            this.each(function () {
+                var $t = this, nm, ind;
+                if (typeof(rowid) == 'undefined') {
+                    getall = true;
+                    resall = [];
+                    len = $t.rows.length;
+                } else {
+                    ind = $t.rows.namedItem(rowid);
+                    if (!ind) {
+                        return res;
+                    }
+                    len = 2;
+                }
+                while (j < len) {
+                    if (getall) {
+                        ind = $t.rows[j];
+                    }
+                    if ($(ind).hasClass('jqgrow')) {
+                        $('td[role="gridcell"]', ind).each(function (i) {
+                            nm = $t.p.colModel[i].name;
+                            if (nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn') {
+                                if ($t.p.treeGrid === true && nm == $t.p.ExpandColumn) {
+                                    res[nm] = $.jgrid.htmlDecode($("span:first", this).html());
+                                } else {
+                                    try {
+                                        res[nm] = $.unformat.call($t, this, {rowId: ind.id, colModel: $t.p.colModel[i]}, i);
+                                    } catch (e) {
+                                        res[nm] = $.jgrid.htmlDecode($(this).html());
+                                    }
+                                }
+                            }
+                        });
+                        if (getall) {
+                            resall.push(res);
+                            res = {};
+                        }
+                    }
+                    j++;
+                }
+            });
+            return resall ? resall : res;
+        },
+        delRowData: function (rowid) {
+            var success = false, rowInd, ia, ri;
+            this.each(function () {
+                var $t = this;
+                rowInd = $t.rows.namedItem(rowid);
+                if (!rowInd) {
+                    return false;
+                }
+                else {
+                    ri = rowInd.rowIndex;
+                    $(rowInd).remove();
+                    $t.p.records--;
+                    $t.p.reccount--;
+                    $t.updatepager(true, false);
+                    success = true;
+                    if ($t.p.multiselect) {
+                        ia = $.inArray(rowid, $t.p.selarrrow);
+                        if (ia != -1) {
+                            $t.p.selarrrow.splice(ia, 1);
+                        }
+                    }
+                    if (rowid == $t.p.selrow) {
+                        $t.p.selrow = null;
+                    }
+                }
+                if ($t.p.datatype == 'local') {
+                    var id = $.jgrid.stripPref($t.p.idPrefix, rowid),
+                        pos = $t.p._index[id];
+                    if (typeof(pos) != 'undefined') {
+                        $t.p.data.splice(pos, 1);
+                        $t.refreshIndex();
+                    }
+                }
+                if ($t.p.altRows === true && success) {
+                    var cn = $t.p.altclass;
+                    $($t.rows).each(function (i) {
+                        if (i % 2 == 1) {
+                            $(this).addClass(cn);
+                        }
+                        else {
+                            $(this).removeClass(cn);
+                        }
+                    });
+                }
+            });
+            return success;
+        },
+        setRowData: function (rowid, data, cssp) {
+            var nm, success = true, title;
+            this.each(function () {
+                if (!this.grid) {
+                    return false;
+                }
+                var t = this, vl, ind, cp = typeof cssp, lcdata = {};
+                ind = t.rows.namedItem(rowid);
+                if (!ind) {
+                    return false;
+                }
+                if (data) {
+                    try {
+                        $(this.p.colModel).each(function (i) {
+                            nm = this.name;
+                            if (data[nm] !== undefined) {
+                                lcdata[nm] = this.formatter && typeof(this.formatter) === 'string' && this.formatter == 'date' ? $.unformat.date.call(t, data[nm], this) : data[nm];
+                                vl = t.formatter(rowid, data[nm], i, data, 'edit');
+                                title = this.title ? {"title": $.jgrid.stripHtml(vl)} : {};
+                                if (t.p.treeGrid === true && nm == t.p.ExpandColumn) {
+                                    $("td:eq(" + i + ") > span:first", ind).html(vl).attr(title);
+                                } else {
+                                    $("td:eq(" + i + ")", ind).html(vl).attr(title);
+                                }
+                            }
+                        });
+                        if (t.p.datatype == 'local') {
+                            var id = $.jgrid.stripPref(t.p.idPrefix, rowid),
+                                pos = t.p._index[id];
+                            if (t.p.treeGrid) {
+                                for (var key in t.p.treeReader) {
+                                    if (lcdata.hasOwnProperty(t.p.treeReader[key])) {
+                                        delete lcdata[t.p.treeReader[key]];
+                                    }
+                                }
+                            }
+                            if (typeof(pos) != 'undefined') {
+                                t.p.data[pos] = $.extend(true, t.p.data[pos], lcdata);
+                            }
+                            lcdata = null;
+                        }
+                    } catch (e) {
+                        success = false;
+                    }
+                }
+                if (success) {
+                    if (cp === 'string') {
+                        $(ind).addClass(cssp);
+                    } else if (cp === 'object') {
+                        $(ind).css(cssp);
+                    }
+                    $(t).triggerHandler("jqGridAfterGridComplete");
+                }
+            });
+            return success;
+        },
+        addRowData: function (rowid, rdata, pos, src) {
+            if (!pos) {
+                pos = "last";
+            }
+            var success = false, nm, row, gi, si, ni, sind, i, v, prp = "", aradd, cnm, cn, data, cm, id;
+            if (rdata) {
+                if ($.isArray(rdata)) {
+                    aradd = true;
+                    pos = "last";
+                    cnm = rowid;
+                } else {
+                    rdata = [rdata];
+                    aradd = false;
+                }
+                this.each(function () {
+                    var t = this, datalen = rdata.length;
+                    ni = t.p.rownumbers === true ? 1 : 0;
+                    gi = t.p.multiselect === true ? 1 : 0;
+                    si = t.p.subGrid === true ? 1 : 0;
+                    if (!aradd) {
+                        if (typeof(rowid) != 'undefined') {
+                            rowid = rowid + "";
+                        }
+                        else {
+                            rowid = $.jgrid.randId();
+                            if (t.p.keyIndex !== false) {
+                                cnm = t.p.colModel[t.p.keyIndex + gi + si + ni].name;
+                                if (typeof rdata[0][cnm] != "undefined") {
+                                    rowid = rdata[0][cnm];
+                                }
+                            }
+                        }
+                    }
+                    cn = t.p.altclass;
+                    var k = 0, cna = "", lcdata = {},
+                        air = $.isFunction(t.p.afterInsertRow) ? true : false;
+                    while (k < datalen) {
+                        data = rdata[k];
+                        row = [];
+                        if (aradd) {
+                            try {
+                                rowid = data[cnm];
+                            }
+                            catch (e) {
+                                rowid = $.jgrid.randId();
+                            }
+                            cna = t.p.altRows === true ? (t.rows.length - 1) % 2 === 0 ? cn : "" : "";
+                        }
+                        id = rowid;
+                        rowid = t.p.idPrefix + rowid;
+                        if (ni) {
+                            prp = t.formatCol(0, 1, '', null, rowid, true);
+                            row[row.length] = "<td role=\"gridcell\" class=\"ui-state-default jqgrid-rownum\" " + prp + ">0</td>";
+                        }
+                        if (gi) {
+                            v = "<input role=\"checkbox\" type=\"checkbox\"" + " id=\"jqg_" + t.p.id + "_" + rowid + "\" class=\"cbox\"/>";
+                            prp = t.formatCol(ni, 1, '', null, rowid, true);
+                            row[row.length] = "<td role=\"gridcell\" " + prp + ">" + v + "</td>";
+                        }
+                        if (si) {
+                            row[row.length] = $(t).jqGrid("addSubGridCell", gi + ni, 1);
+                        }
+                        for (i = gi + si + ni; i < t.p.colModel.length; i++) {
+                            cm = t.p.colModel[i];
+                            nm = cm.name;
+                            lcdata[nm] = data[nm];
+                            v = t.formatter(rowid, $.jgrid.getAccessor(data, nm), i, data);
+                            prp = t.formatCol(i, 1, v, data, rowid, true);
+                            row[row.length] = "<td role=\"gridcell\" " + prp + ">" + v + "</td>";
+                        }
+                        row.unshift(t.constructTr(rowid, false, cna, lcdata, lcdata));
+                        row[row.length] = "</tr>";
+                        if (t.rows.length === 0) {
+                            $("table:first", t.grid.bDiv).append(row.join(''));
+                        } else {
+                            switch (pos) {
+                                case 'last':
+                                    $(t.rows[t.rows.length - 1]).after(row.join(''));
+                                    sind = t.rows.length - 1;
+                                    break;
+                                case 'first':
+                                    $(t.rows[0]).after(row.join(''));
+                                    sind = 1;
+                                    break;
+                                case 'after':
+                                    sind = t.rows.namedItem(src);
+                                    if (sind) {
+                                        if ($(t.rows[sind.rowIndex + 1]).hasClass("ui-subgrid")) {
+                                            $(t.rows[sind.rowIndex + 1]).after(row);
+                                        }
+                                        else {
+                                            $(sind).after(row.join(''));
+                                        }
+                                    }
+                                    sind++;
+                                    break;
+                                case 'before':
+                                    sind = t.rows.namedItem(src);
+                                    if (sind) {
+                                        $(sind).before(row.join(''));
+                                        sind = sind.rowIndex;
+                                    }
+                                    sind--;
+                                    break;
+                            }
+                        }
+                        if (t.p.subGrid === true) {
+                            $(t).jqGrid("addSubGrid", gi + ni, sind);
+                        }
+                        t.p.records++;
+                        t.p.reccount++;
+                        $(t).triggerHandler("jqGridAfterInsertRow", [rowid, data, data]);
+                        if (air) {
+                            t.p.afterInsertRow.call(t, rowid, data, data);
+                        }
+                        k++;
+                        if (t.p.datatype == 'local') {
+                            lcdata[t.p.localReader.id] = id;
+                            t.p._index[id] = t.p.data.length;
+                            t.p.data.push(lcdata);
+                            lcdata = {};
+                        }
+                    }
+                    if (t.p.altRows === true && !aradd) {
+                        if (pos == "last") {
+                            if ((t.rows.length - 1) % 2 == 1) {
+                                $(t.rows[t.rows.length - 1]).addClass(cn);
+                            }
+                        } else {
+                            $(t.rows).each(function (i) {
+                                if (i % 2 == 1) {
+                                    $(this).addClass(cn);
+                                }
+                                else {
+                                    $(this).removeClass(cn);
+                                }
+                            });
+                        }
+                    }
+                    t.updatepager(true, true);
+                    success = true;
+                });
+            }
+            return success;
+        },
+        footerData: function (action, data, format) {
+            var nm, success = false, res = {}, title;
+
+            function isEmpty(obj) {
+                for (var i in obj) {
+                    if (obj.hasOwnProperty(i)) {
+                        return false;
+                    }
+                }
+                return true;
+            }
+
+            if (typeof(action) == "undefined") {
+                action = "get";
+            }
+            if (typeof(format) != "boolean") {
+                format = true;
+            }
+            action = action.toLowerCase();
+            this.each(function () {
+                var t = this, vl;
+                if (!t.grid || !t.p.footerrow) {
+                    return false;
+                }
+                if (action == "set") {
+                    if (isEmpty(data)) {
+                        return false;
+                    }
+                }
+                success = true;
+                $(this.p.colModel).each(function (i) {
+                    nm = this.name;
+                    if (action == "set") {
+                        if (data[nm] !== undefined) {
+                            vl = format ? t.formatter("", data[nm], i, data, 'edit') : data[nm];
+                            title = this.title ? {"title": $.jgrid.stripHtml(vl)} : {};
+                            $("tr.footrow td:eq(" + i + ")", t.grid.sDiv).html(vl).attr(title);
+                            success = true;
+                        }
+                    } else if (action == "get") {
+                        res[nm] = $("tr.footrow td:eq(" + i + ")", t.grid.sDiv).html();
+                    }
+                });
+            });
+            return action == "get" ? res : success;
+        },
+        showHideCol: function (colname, show) {
+            return this.each(function () {
+                var $t = this, fndh = false, brd = $.jgrid.cellWidth() ? 0 : $t.p.cellLayout, cw;
+                if (!$t.grid) {
+                    return;
+                }
+                if (typeof colname === 'string') {
+                    colname = [colname];
+                }
+                show = show != "none" ? "" : "none";
+                var sw = show === "" ? true : false,
+                    gh = $t.p.groupHeader && (typeof $t.p.groupHeader === 'object' || $.isFunction($t.p.groupHeader) );
+                if (gh) {
+                    $($t).jqGrid('destroyGroupHeader', false);
+                }
+                $(this.p.colModel).each(function (i) {
+                    if ($.inArray(this.name, colname) !== -1 && this.hidden === sw) {
+                        if ($t.p.frozenColumns === true && this.frozen === true) {
+                            return true;
+                        }
+                        $("tr", $t.grid.hDiv).each(function () {
+                            $(this.cells[i]).css("display", show);
+                        });
+                        $($t.rows).each(function () {
+                            if (!$(this).hasClass("jqgroup")) {
+                                $(this.cells[i]).css("display", show);
+                            }
+                        });
+                        if ($t.p.footerrow) {
+                            $("tr.footrow td:eq(" + i + ")", $t.grid.sDiv).css("display", show);
+                        }
+                        cw = parseInt(this.width, 10);
+                        if (show === "none") {
+                            $t.p.tblwidth -= cw + brd;
+                        } else {
+                            $t.p.tblwidth += cw + brd;
+                        }
+                        this.hidden = !sw;
+                        fndh = true;
+                        $($t).triggerHandler("jqGridShowHideCol", [sw, this.name, i]);
+                    }
+                });
+                if (fndh === true) {
+                    if ($t.p.shrinkToFit === true && !isNaN($t.p.height)) {
+                        $t.p.tblwidth += parseInt($t.p.scrollOffset, 10);
+                    }
+                    $($t).jqGrid("setGridWidth", $t.p.shrinkToFit === true ? $t.p.tblwidth : $t.p.width);
+                }
+                if (gh) {
+                    $($t).jqGrid('setGroupHeaders', $t.p.groupHeader);
+                }
+            });
+        },
+        hideCol: function (colname) {
+            return this.each(function () {
+                $(this).jqGrid("showHideCol", colname, "none");
+            });
+        },
+        showCol: function (colname) {
+            return this.each(function () {
+                $(this).jqGrid("showHideCol", colname, "");
+            });
+        },
+        remapColumns: function (permutation, updateCells, keepHeader) {
+            function resortArray(a) {
+                var ac;
+                if (a.length) {
+                    ac = $.makeArray(a);
+                } else {
+                    ac = $.extend({}, a);
+                }
+                $.each(permutation, function (i) {
+                    a[i] = ac[this];
+                });
+            }
+
+            var ts = this.get(0);
+
+            function resortRows(parent, clobj) {
+                $(">tr" + (clobj || ""), parent).each(function () {
+                    var row = this;
+                    var elems = $.makeArray(row.cells);
+                    $.each(permutation, function () {
+                        var e = elems[this];
+                        if (e) {
+                            row.appendChild(e);
+                        }
+                    });
+                });
+            }
+
+            resortArray(ts.p.colModel);
+            resortArray(ts.p.colNames);
+            resortArray(ts.grid.headers);
+            resortRows($("thead:first", ts.grid.hDiv), keepHeader && ":not(.ui-jqgrid-labels)");
+            if (updateCells) {
+                resortRows($("#" + $.jgrid.jqID(ts.p.id) + " tbody:first"), ".jqgfirstrow, tr.jqgrow, tr.jqfoot");
+            }
+            if (ts.p.footerrow) {
+                resortRows($("tbody:first", ts.grid.sDiv));
+            }
+            if (ts.p.remapColumns) {
+                if (!ts.p.remapColumns.length) {
+                    ts.p.remapColumns = $.makeArray(permutation);
+                } else {
+                    resortArray(ts.p.remapColumns);
+                }
+            }
+            ts.p.lastsort = $.inArray(ts.p.lastsort, permutation);
+            if (ts.p.treeGrid) {
+                ts.p.expColInd = $.inArray(ts.p.expColInd, permutation);
+            }
+            $(ts).triggerHandler("jqGridRemapColumns", [permutation, updateCells, keepHeader]);
+        },
+        setGridWidth: function (nwidth, shrink) {
+            return this.each(function () {
+                if (!this.grid) {
+                    return;
+                }
+                var $t = this, cw,
+                    initwidth = 0, brd = $.jgrid.cellWidth() ? 0 : $t.p.cellLayout, lvc, vc = 0, hs = false, scw = $t.p.scrollOffset, aw, gw = 0,
+                    cl = 0, cr;
+                if (typeof shrink != 'boolean') {
+                    shrink = $t.p.shrinkToFit;
+                }
+                if (isNaN(nwidth)) {
+                    return;
+                }
+                nwidth = parseInt(nwidth, 10);
+                $t.grid.width = $t.p.width = nwidth;
+                $("#gbox_" + $.jgrid.jqID($t.p.id)).css("width", nwidth + "px");
+                $("#gview_" + $.jgrid.jqID($t.p.id)).css("width", nwidth + "px");
+                $($t.grid.bDiv).css("width", nwidth + "px");
+                $($t.grid.hDiv).css("width", nwidth + "px");
+                if ($t.p.pager) {
+                    $($t.p.pager).css("width", nwidth + "px");
+                }
+                if ($t.p.toppager) {
+                    $($t.p.toppager).css("width", nwidth + "px");
+                }
+                if ($t.p.toolbar[0] === true) {
+                    $($t.grid.uDiv).css("width", nwidth + "px");
+                    if ($t.p.toolbar[1] == "both") {
+                        $($t.grid.ubDiv).css("width", nwidth + "px");
+                    }
+                }
+                if ($t.p.footerrow) {
+                    $($t.grid.sDiv).css("width", nwidth + "px");
+                }
+                if (shrink === false && $t.p.forceFit === true) {
+                    $t.p.forceFit = false;
+                }
+                if (shrink === true) {
+                    $.each($t.p.colModel, function () {
+                        if (this.hidden === false) {
+                            cw = this.widthOrg;
+                            initwidth += cw + brd;
+                            if (this.fixed) {
+                                gw += cw + brd;
+                            } else {
+                                vc++;
+                            }
+                            cl++;
+                        }
+                    });
+                    if (vc === 0) {
+                        return;
+                    }
+                    $t.p.tblwidth = initwidth;
+                    aw = nwidth - brd * vc - gw;
+                    if (!isNaN($t.p.height)) {
+                        if ($($t.grid.bDiv)[0].clientHeight < $($t.grid.bDiv)[0].scrollHeight || $t.rows.length === 1) {
+                            hs = true;
+                            aw -= scw;
+                        }
+                    }
+                    initwidth = 0;
+                    var cle = $t.grid.cols.length > 0;
+                    $.each($t.p.colModel, function (i) {
+                        if (this.hidden === false && !this.fixed) {
+                            cw = this.widthOrg;
+                            cw = Math.round(aw * cw / ($t.p.tblwidth - brd * vc - gw));
+                            if (cw < 0) {
+                                return;
+                            }
+                            this.width = cw;
+                            initwidth += cw;
+                            $t.grid.headers[i].width = cw;
+                            $t.grid.headers[i].el.style.width = cw + "px";
+                            if ($t.p.footerrow) {
+                                $t.grid.footers[i].style.width = cw + "px";
+                            }
+                            if (cle) {
+                                $t.grid.cols[i].style.width = cw + "px";
+                            }
+                            lvc = i;
+                        }
+                    });
+
+                    if (!lvc) {
+                        return;
+                    }
+
+                    cr = 0;
+                    if (hs) {
+                        if (nwidth - gw - (initwidth + brd * vc) !== scw) {
+                            cr = nwidth - gw - (initwidth + brd * vc) - scw;
+                        }
+                    } else if (Math.abs(nwidth - gw - (initwidth + brd * vc)) !== 1) {
+                        cr = nwidth - gw - (initwidth + brd * vc);
+                    }
+                    $t.p.colModel[lvc].width += cr;
+                    $t.p.tblwidth = initwidth + cr + brd * vc + gw;
+                    if ($t.p.tblwidth > nwidth) {
+                        var delta = $t.p.tblwidth - parseInt(nwidth, 10);
+                        $t.p.tblwidth = nwidth;
+                        cw = $t.p.colModel[lvc].width = $t.p.colModel[lvc].width - delta;
+                    } else {
+                        cw = $t.p.colModel[lvc].width;
+                    }
+                    $t.grid.headers[lvc].width = cw;
+                    $t.grid.headers[lvc].el.style.width = cw + "px";
+                    if (cle) {
+                        $t.grid.cols[lvc].style.width = cw + "px";
+                    }
+                    if ($t.p.footerrow) {
+                        $t.grid.footers[lvc].style.width = cw + "px";
+                    }
+                }
+                if ($t.p.tblwidth) {
+                    $('table:first', $t.grid.bDiv).css("width", $t.p.tblwidth + "px");
+                    $('table:first', $t.grid.hDiv).css("width", $t.p.tblwidth + "px");
+                    $t.grid.hDiv.scrollLeft = $t.grid.bDiv.scrollLeft;
+                    if ($t.p.footerrow) {
+                        $('table:first', $t.grid.sDiv).css("width", $t.p.tblwidth + "px");
+                    }
+                }
+            });
+        },
+        setGridHeight: function (nh) {
+            return this.each(function () {
+                var $t = this;
+                if (!$t.grid) {
+                    return;
+                }
+                var bDiv = $($t.grid.bDiv);
+                bDiv.css({height: nh + (isNaN(nh) ? "" : "px")});
+                if ($t.p.frozenColumns === true) {
+                    //follow the original set height to use 16, better scrollbar width detection
+                    $('#' + $.jgrid.jqID($t.p.id) + "_frozen").parent().height(bDiv.height() - 16);
+                }
+                $t.p.height = nh;
+                if ($t.p.scroll) {
+                    $t.grid.populateVisible();
+                }
+            });
+        },
+        setCaption: function (newcap) {
+            return this.each(function () {
+                this.p.caption = newcap;
+                $("span.ui-jqgrid-title, span.ui-jqgrid-title-rtl", this.grid.cDiv).html(newcap);
+                $(this.grid.cDiv).show();
+            });
+        },
+        setLabel: function (colname, nData, prop, attrp) {
+            return this.each(function () {
+                var $t = this, pos = -1;
+                if (!$t.grid) {
+                    return;
+                }
+                if (typeof(colname) != "undefined") {
+                    $($t.p.colModel).each(function (i) {
+                        if (this.name == colname) {
+                            pos = i;
+                            return false;
+                        }
+                    });
+                } else {
+                    return;
+                }
+                if (pos >= 0) {
+                    var thecol = $("tr.ui-jqgrid-labels th:eq(" + pos + ")", $t.grid.hDiv);
+                    if (nData) {
+                        var ico = $(".s-ico", thecol);
+                        $("[id^=jqgh_]", thecol).empty().html(nData).append(ico);
+                        $t.p.colNames[pos] = nData;
+                    }
+                    if (prop) {
+                        if (typeof prop === 'string') {
+                            $(thecol).addClass(prop);
+                        } else {
+                            $(thecol).css(prop);
+                        }
+                    }
+                    if (typeof attrp === 'object') {
+                        $(thecol).attr(attrp);
+                    }
+                }
+            });
+        },
+        setCell: function (rowid, colname, nData, cssp, attrp, forceupd) {
+            return this.each(function () {
+                var $t = this, pos = -1, v, title;
+                if (!$t.grid) {
+                    return;
+                }
+                if (isNaN(colname)) {
+                    $($t.p.colModel).each(function (i) {
+                        if (this.name == colname) {
+                            pos = i;
+                            return false;
+                        }
+                    });
+                } else {
+                    pos = parseInt(colname, 10);
+                }
+                if (pos >= 0) {
+                    var ind = $t.rows.namedItem(rowid);
+                    if (ind) {
+                        var tcell = $("td:eq(" + pos + ")", ind);
+                        if (nData !== "" || forceupd === true) {
+                            v = $t.formatter(rowid, nData, pos, ind, 'edit');
+                            title = $t.p.colModel[pos].title ? {"title": $.jgrid.stripHtml(v)} : {};
+                            if ($t.p.treeGrid && $(".tree-wrap", $(tcell)).length > 0) {
+                                $("span", $(tcell)).html(v).attr(title);
+                            } else {
+                                $(tcell).html(v).attr(title);
+                            }
+                            if ($t.p.datatype == "local") {
+                                var cm = $t.p.colModel[pos], index;
+                                nData = cm.formatter && typeof(cm.formatter) === 'string' && cm.formatter == 'date' ? $.unformat.date.call($t, nData, cm) : nData;
+                                index = $t.p._index[rowid];
+                                if (typeof index != "undefined") {
+                                    $t.p.data[index][cm.name] = nData;
+                                }
+                            }
+                        }
+                        if (typeof cssp === 'string') {
+                            $(tcell).addClass(cssp);
+                        } else if (cssp) {
+                            $(tcell).css(cssp);
+                        }
+                        if (typeof attrp === 'object') {
+                            $(tcell).attr(attrp);
+                        }
+                    }
+                }
+            });
+        },
+        getCell: function (rowid, col) {
+            var ret = false;
+            this.each(function () {
+                var $t = this, pos = -1;
+                if (!$t.grid) {
+                    return;
+                }
+                if (isNaN(col)) {
+                    $($t.p.colModel).each(function (i) {
+                        if (this.name === col) {
+                            pos = i;
+                            return false;
+                        }
+                    });
+                } else {
+                    pos = parseInt(col, 10);
+                }
+                if (pos >= 0) {
+                    var ind = $t.rows.namedItem(rowid);
+                    if (ind) {
+                        try {
+                            ret = $.unformat.call($t, $("td:eq(" + pos + ")", ind), {rowId: ind.id, colModel: $t.p.colModel[pos]}, pos);
+                        } catch (e) {
+                            ret = $.jgrid.htmlDecode($("td:eq(" + pos + ")", ind).html());
+                        }
+                    }
+                }
+            });
+            return ret;
+        },
+        getCol: function (col, obj, mathopr) {
+            var ret = [], val, sum = 0, min, max, v;
+            obj = typeof (obj) != 'boolean' ? false : obj;
+            if (typeof mathopr == 'undefined') {
+                mathopr = false;
+            }
+            this.each(function () {
+                var $t = this, pos = -1;
+                if (!$t.grid) {
+                    return;
+                }
+                if (isNaN(col)) {
+                    $($t.p.colModel).each(function (i) {
+                        if (this.name === col) {
+                            pos = i;
+                            return false;
+                        }
+                    });
+                } else {
+                    pos = parseInt(col, 10);
+                }
+                if (pos >= 0) {
+                    var ln = $t.rows.length, i = 0;
+                    if (ln && ln > 0) {
+                        while (i < ln) {
+                            if ($($t.rows[i]).hasClass('jqgrow')) {
+                                try {
+                                    val = $.unformat.call($t, $($t.rows[i].cells[pos]), {rowId: $t.rows[i].id, colModel: $t.p.colModel[pos]}, pos);
+                                } catch (e) {
+                                    val = $.jgrid.htmlDecode($t.rows[i].cells[pos].innerHTML);
+                                }
+                                if (mathopr) {
+                                    v = parseFloat(val);
+                                    sum += v;
+                                    if (i === 0) {
+                                        min = v;
+                                        max = v;
+                                    } else {
+                                        min = Math.min(min, v);
+                                        max = Math.max(max, v);
+                                    }
+                                }
+                                else if (obj) {
+                                    ret.push({id: $t.rows[i].id, value: val});
+                                }
+                                else {
+                                    ret.push(val);
+                                }
+                            }
+                            i++;
+                        }
+                        if (mathopr) {
+                            switch (mathopr.toLowerCase()) {
+                                case 'sum':
+                                    ret = sum;
+                                    break;
+                                case 'avg':
+                                    ret = sum / ln;
+                                    break;
+                                case 'count':
+                                    ret = ln;
+                                    break;
+                                case 'min':
+                                    ret = min;
+                                    break;
+                                case 'max':
+                                    ret = max;
+                                    break;
+                            }
+                        }
+                    }
+                }
+            });
+            return ret;
+        },
+        clearGridData: function (clearfooter) {
+            return this.each(function () {
+                var $t = this;
+                if (!$t.grid) {
+                    return;
+                }
+                if (typeof clearfooter != 'boolean') {
+                    clearfooter = false;
+                }
+                if ($t.p.deepempty) {
+                    $("#" + $.jgrid.jqID($t.p.id) + " tbody:first tr:gt(0)").remove();
+                }
+                else {
+                    var trf = $("#" + $.jgrid.jqID($t.p.id) + " tbody:first tr:first")[0];
+                    $("#" + $.jgrid.jqID($t.p.id) + " tbody:first").empty().append(trf);
+                }
+                if ($t.p.footerrow && clearfooter) {
+                    $(".ui-jqgrid-ftable td", $t.grid.sDiv).html("&#160;");
+                }
+                $t.p.selrow = null;
+                $t.p.selarrrow = [];
+                $t.p.savedRow = [];
+                $t.p.records = 0;
+                $t.p.page = 1;
+                $t.p.lastpage = 0;
+                $t.p.reccount = 0;
+                $t.p.data = [];
+                $t.p._index = {};
+                $t.updatepager(true, false);
+            });
+        },
+        getInd: function (rowid, rc) {
+            var ret = false, rw;
+            this.each(function () {
+                rw = this.rows.namedItem(rowid);
+                if (rw) {
+                    ret = rc === true ? rw : rw.rowIndex;
+                }
+            });
+            return ret;
+        },
+        bindKeys: function (settings) {
+            var o = $.extend({
+                onEnter: null,
+                onSpace: null,
+                onLeftKey: null,
+                onRightKey: null,
+                scrollingRows: true
+            }, settings || {});
+            return this.each(function () {
+                var $t = this;
+                if (!$('body').is('[role]')) {
+                    $('body').attr('role', 'application');
+                }
+                $t.p.scrollrows = o.scrollingRows;
+                $($t).keydown(function (event) {
+                    var target = $($t).find('tr[tabindex=0]')[0], id, r, mind,
+                        expanded = $t.p.treeReader.expanded_field;
+                    //check for arrow keys
+                    if (target) {
+                        mind = $t.p._index[target.id];
+                        if (event.keyCode === 37 || event.keyCode === 38 || event.keyCode === 39 || event.keyCode === 40) {
+                            // up key
+                            if (event.keyCode === 38) {
+                                r = target.previousSibling;
+                                id = "";
+                                if (r) {
+                                    if ($(r).is(":hidden")) {
+                                        while (r) {
+                                            r = r.previousSibling;
+                                            if (!$(r).is(":hidden") && $(r).hasClass('jqgrow')) {
+                                                id = r.id;
+                                                break;
+                                            }
+                                        }
+                                    } else {
+                                        id = r.id;
+                                    }
+                                }
+                                $($t).jqGrid('setSelection', id, true, event);
+                            }
+                            //if key is down arrow
+                            if (event.keyCode === 40) {
+                                r = target.nextSibling;
+                                id = "";
+                                if (r) {
+                                    if ($(r).is(":hidden")) {
+                                        while (r) {
+                                            r = r.nextSibling;
+                                            if (!$(r).is(":hidden") && $(r).hasClass('jqgrow')) {
+                                                id = r.id;
+                                                break;
+                                            }
+                                        }
+                                    } else {
+                                        id = r.id;
+                                    }
+                                }
+                                $($t).jqGrid('setSelection', id, true, event);
+                            }
+                            // left
+                            if (event.keyCode === 37) {
+                                if ($t.p.treeGrid && $t.p.data[mind][expanded]) {
+                                    $(target).find("div.treeclick").trigger('click');
+                                }
+                                $($t).triggerHandler("jqGridKeyLeft", [$t.p.selrow]);
+                                if ($.isFunction(o.onLeftKey)) {
+                                    o.onLeftKey.call($t, $t.p.selrow);
+                                }
+                            }
+                            // right
+                            if (event.keyCode === 39) {
+                                if ($t.p.treeGrid && !$t.p.data[mind][expanded]) {
+                                    $(target).find("div.treeclick").trigger('click');
+                                }
+                                $($t).triggerHandler("jqGridKeyRight", [$t.p.selrow]);
+                                if ($.isFunction(o.onRightKey)) {
+                                    o.onRightKey.call($t, $t.p.selrow);
+                                }
+                            }
+                        }
+                        //check if enter was pressed on a grid or treegrid node
+                        else if (event.keyCode === 13) {
+                            $($t).triggerHandler("jqGridKeyEnter", [$t.p.selrow]);
+                            if ($.isFunction(o.onEnter)) {
+                                o.onEnter.call($t, $t.p.selrow);
+                            }
+                        } else if (event.keyCode === 32) {
+                            $($t).triggerHandler("jqGridKeySpace", [$t.p.selrow]);
+                            if ($.isFunction(o.onSpace)) {
+                                o.onSpace.call($t, $t.p.selrow);
+                            }
+                        }
+                    }
+                });
+            });
+        },
+        unbindKeys: function () {
+            return this.each(function () {
+                $(this).unbind('keydown');
+            });
+        },
+        getLocalRow: function (rowid) {
+            var ret = false, ind;
+            this.each(function () {
+                if (typeof(rowid) !== "undefined") {
+                    ind = this.p._index[rowid];
+                    if (ind >= 0) {
+                        ret = this.p.data[ind];
+                    }
+                }
+            });
+            return ret;
+        }
+    });
+})(jQuery);
+(function ($) {
+    /**
+     * jqGrid extension for custom methods
+     * Tony Tomov tony@trirand.com
+     * http://trirand.com/blog/
+     *
+     * Wildraid wildraid@mail.ru
+     * Oleg Kiriljuk oleg.kiriljuk@ok-soft-gmbh.com
+     * Dual licensed under the MIT and GPL licenses:
+     * http://www.opensource.org/licenses/mit-license.php
+     * http://www.gnu.org/licenses/gpl-2.0.html
+     **/
+    /*global jQuery, $ */
+    "use strict";
+    $.jgrid.extend({
+        getColProp: function (colname) {
+            var ret = {}, $t = this[0];
+            if (!$t.grid) {
+                return false;
+            }
+            var cM = $t.p.colModel;
+            for (var i = 0; i < cM.length; i++) {
+                if (cM[i].name == colname) {
+                    ret = cM[i];
+                    break;
+                }
+            }
+            return ret;
+        },
+        setColProp: function (colname, obj) {
+            //do not set width will not work
+            return this.each(function () {
+                if (this.grid) {
+                    if (obj) {
+                        var cM = this.p.colModel;
+                        for (var i = 0; i < cM.length; i++) {
+                            if (cM[i].name == colname) {
+                                $.extend(this.p.colModel[i], obj);
+                                break;
+                            }
+                        }
+                    }
+                }
+            });
+        },
+        sortGrid: function (colname, reload, sor) {
+            return this.each(function () {
+                var $t = this, idx = -1;
+                if (!$t.grid) {
+                    return;
+                }
+                if (!colname) {
+                    colname = $t.p.sortname;
+                }
+                for (var i = 0; i < $t.p.colModel.length; i++) {
+                    if ($t.p.colModel[i].index == colname || $t.p.colModel[i].name == colname) {
+                        idx = i;
+                        break;
+                    }
+                }
+                if (idx != -1) {
+                    var sort = $t.p.colModel[idx].sortable;
+                    if (typeof sort !== 'boolean') {
+                        sort = true;
+                    }
+                    if (typeof reload !== 'boolean') {
+                        reload = false;
+                    }
+                    if (sort) {
+                        $t.sortData("jqgh_" + $t.p.id + "_" + colname, idx, reload, sor);
+                    }
+                }
+            });
+        },
+        GridDestroy: function () {
+            return this.each(function () {
+                if (this.grid) {
+                    if (this.p.pager) { // if not part of grid
+                        $(this.p.pager).remove();
+                    }
+                    try {
+                        $("#gbox_" + $.jgrid.jqID(this.id)).remove();
+                    } catch (_) {
+                    }
+                }
+            });
+        },
+        GridUnload: function () {
+            return this.each(function () {
+                if (!this.grid) {
+                    return;
+                }
+                var defgrid = {id: $(this).attr('id'), cl: $(this).attr('class')};
+                if (this.p.pager) {
+                    $(this.p.pager).empty().removeClass("ui-state-default ui-jqgrid-pager corner-bottom");
+                }
+                var newtable = document.createElement('table');
+                $(newtable).attr({id: defgrid.id});
+                newtable.className = defgrid.cl;
+                var gid = $.jgrid.jqID(this.id);
+                $(newtable).removeClass("ui-jqgrid-btable");
+                if ($(this.p.pager).parents("#gbox_" + gid).length === 1) {
+                    $(newtable).insertBefore("#gbox_" + gid).show();
+                    $(this.p.pager).insertBefore("#gbox_" + gid);
+                } else {
+                    $(newtable).insertBefore("#gbox_" + gid).show();
+                }
+                $("#gbox_" + gid).remove();
+            });
+        },
+        setGridState: function (state) {
+            return this.each(function () {
+                if (!this.grid) {
+                    return;
+                }
+                var $t = this;
+                if (state == 'hidden') {
+                    $(".ui-jqgrid-bdiv, .ui-jqgrid-hdiv", "#gview_" + $.jgrid.jqID($t.p.id)).slideUp("fast");
+                    if ($t.p.pager) {
+                        $($t.p.pager).slideUp("fast");
+                    }
+                    if ($t.p.toppager) {
+                        $($t.p.toppager).slideUp("fast");
+                    }
+                    if ($t.p.toolbar[0] === true) {
+                        if ($t.p.toolbar[1] == 'both') {
+                            $($t.grid.ubDiv).slideUp("fast");
+                        }
+                        $($t.grid.uDiv).slideUp("fast");
+                    }
+                    if ($t.p.footerrow) {
+                        $(".ui-jqgrid-sdiv", "#gbox_" + $.jgrid.jqID($t.p.id)).slideUp("fast");
+                    }
+                    $(".ui-jqgrid-titlebar-close span", $t.grid.cDiv).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-s");
+                    $t.p.gridstate = 'hidden';
+                } else if (state == 'visible') {
+                    $(".ui-jqgrid-hdiv, .ui-jqgrid-bdiv", "#gview_" + $.jgrid.jqID($t.p.id)).slideDown("fast");
+                    if ($t.p.pager) {
+                        $($t.p.pager).slideDown("fast");
+                    }
+                    if ($t.p.toppager) {
+                        $($t.p.toppager).slideDown("fast");
+                    }
+                    if ($t.p.toolbar[0] === true) {
+                        if ($t.p.toolbar[1] == 'both') {
+                            $($t.grid.ubDiv).slideDown("fast");
+                        }
+                        $($t.grid.uDiv).slideDown("fast");
+                    }
+                    if ($t.p.footerrow) {
+                        $(".ui-jqgrid-sdiv", "#gbox_" + $.jgrid.jqID($t.p.id)).slideDown("fast");
+                    }
+                    $(".ui-jqgrid-titlebar-close span", $t.grid.cDiv).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-n");
+                    $t.p.gridstate = 'visible';
+                }
+
+            });
+        },
+        filterToolbar: function (p) {
+            p = $.extend({
+                autosearch: true,
+                searchOnEnter: true,
+                beforeSearch: null,
+                afterSearch: null,
+                beforeClear: null,
+                afterClear: null,
+                searchurl: '',
+                stringResult: false,
+                groupOp: 'AND',
+                defaultSearch: "bw"
+            }, p || {});
+            return this.each(function () {
+                var $t = this;
+                if (this.ftoolbar) {
+                    return;
+                }
+                var triggerToolbar = function () {
+                    var sdata = {}, j = 0, v, nm, sopt = {}, so;
+                    $.each($t.p.colModel, function () {
+                        nm = this.index || this.name;
+                        so = (this.searchoptions && this.searchoptions.sopt) ? this.searchoptions.sopt[0] : this.stype == 'select' ? 'eq' : p.defaultSearch;
+                        v = $("#gs_" + $.jgrid.jqID(this.name), (this.frozen === true && $t.p.frozenColumns === true) ? $t.grid.fhDiv : $t.grid.hDiv).val();
+                        if (v) {
+                            sdata[nm] = v;
+                            sopt[nm] = so;
+                            j++;
+                        } else {
+                            try {
+                                delete $t.p.postData[nm];
+                            } catch (z) {
+                            }
+                        }
+                    });
+                    var sd = j > 0 ? true : false;
+                    if (p.stringResult === true || $t.p.datatype == "local") {
+                        var ruleGroup = "{\"groupOp\":\"" + p.groupOp + "\",\"rules\":[";
+                        var gi = 0;
+                        $.each(sdata, function (i, n) {
+                            if (gi > 0) {
+                                ruleGroup += ",";
+                            }
+                            ruleGroup += "{\"field\":\"" + i + "\",";
+                            ruleGroup += "\"op\":\"" + sopt[i] + "\",";
+                            n += "";
+                            ruleGroup += "\"data\":\"" + n.replace(/\\/g, '\\\\').replace(/\"/g, '\\"') + "\"}";
+                            gi++;
+                        });
+                        ruleGroup += "]}";
+                        $.extend($t.p.postData, {filters: ruleGroup});
+                        $.each(['searchField', 'searchString', 'searchOper'], function (i, n) {
+                            if ($t.p.postData.hasOwnProperty(n)) {
+                                delete $t.p.postData[n];
+                            }
+                        });
+                    } else {
+                        $.extend($t.p.postData, sdata);
+                    }
+                    var saveurl;
+                    if ($t.p.searchurl) {
+                        saveurl = $t.p.url;
+                        $($t).jqGrid("setGridParam", {url: $t.p.searchurl});
+                    }
+                    var bsr = $($t).triggerHandler("jqGridToolbarBeforeSearch") === 'stop' ? true : false;
+                    if (!bsr && $.isFunction(p.beforeSearch)) {
+                        bsr = p.beforeSearch.call($t);
+                    }
+                    if (!bsr) {
+                        $($t).jqGrid("setGridParam", {search: sd}).trigger("reloadGrid", [
+                            {page: 1}
+                        ]);
+                    }
+                    if (saveurl) {
+                        $($t).jqGrid("setGridParam", {url: saveurl});
+                    }
+                    $($t).triggerHandler("jqGridToolbarAfterSearch");
+                    if ($.isFunction(p.afterSearch)) {
+                        p.afterSearch.call($t);
+                    }
+                };
+                var clearToolbar = function (trigger) {
+                    var sdata = {}, j = 0, nm;
+                    trigger = (typeof trigger != 'boolean') ? true : trigger;
+                    $.each($t.p.colModel, function () {
+                        var v;
+                        if (this.searchoptions && this.searchoptions.defaultValue !== undefined) {
+                            v = this.searchoptions.defaultValue;
+                        }
+                        nm = this.index || this.name;
+                        switch (this.stype) {
+                            case 'select' :
+                                $("#gs_" + $.jgrid.jqID(this.name) + " option", (this.frozen === true && $t.p.frozenColumns === true) ? $t.grid.fhDiv : $t.grid.hDiv).each(function (i) {
+                                    if (i === 0) {
+                                        this.selected = true;
+                                    }
+                                    if ($(this).val() == v) {
+                                        this.selected = true;
+                                        return false;
+                                    }
+                                });
+                                if (v !== undefined) {
+                                    // post the key and not the text
+                                    sdata[nm] = v;
+                                    j++;
+                                } else {
+                                    try {
+                                        delete $t.p.postData[nm];
+                                    } catch (e) {
+                                    }
+                                }
+                                break;
+                            case 'text':
+                                $("#gs_" + $.jgrid.jqID(this.name), (this.frozen === true && $t.p.frozenColumns === true) ? $t.grid.fhDiv : $t.grid.hDiv).val(v);
+                                if (v !== undefined) {
+                                    sdata[nm] = v;
+                                    j++;
+                                } else {
+                                    try {
+                                        delete $t.p.postData[nm];
+                                    } catch (y) {
+                                    }
+                                }
+                                break;
+                        }
+                    });
+                    var sd = j > 0 ? true : false;
+                    if (p.stringResult === true || $t.p.datatype == "local") {
+                        var ruleGroup = "{\"groupOp\":\"" + p.groupOp + "\",\"rules\":[";
+                        var gi = 0;
+                        $.each(sdata, function (i, n) {
+                            if (gi > 0) {
+                                ruleGroup += ",";
+                            }
+                            ruleGroup += "{\"field\":\"" + i + "\",";
+                            ruleGroup += "\"op\":\"" + "eq" + "\",";
+                            n += "";
+                            ruleGroup += "\"data\":\"" + n.replace(/\\/g, '\\\\').replace(/\"/g, '\\"') + "\"}";
+                            gi++;
+                        });
+                        ruleGroup += "]}";
+                        $.extend($t.p.postData, {filters: ruleGroup});
+                        $.each(['searchField', 'searchString', 'searchOper'], function (i, n) {
+                            if ($t.p.postData.hasOwnProperty(n)) {
+                                delete $t.p.postData[n];
+                            }
+                        });
+                    } else {
+                        $.extend($t.p.postData, sdata);
+                    }
+                    var saveurl;
+                    if ($t.p.searchurl) {
+                        saveurl = $t.p.url;
+                        $($t).jqGrid("setGridParam", {url: $t.p.searchurl});
+                    }
+                    var bcv = $($t).triggerHandler("jqGridToolbarBeforeClear") === 'stop' ? true : false;
+                    if (!bcv && $.isFunction(p.beforeClear)) {
+                        bcv = p.beforeClear.call($t);
+                    }
+                    if (!bcv) {
+                        if (trigger) {
+                            $($t).jqGrid("setGridParam", {search: sd}).trigger("reloadGrid", [
+                                {page: 1}
+                            ]);
+                        }
+                    }
+                    if (saveurl) {
+                        $($t).jqGrid("setGridParam", {url: saveurl});
+                    }
+                    $($t).triggerHandler("jqGridToolbarAfterClear");
+                    if ($.isFunction(p.afterClear)) {
+                        p.afterClear();
+                    }
+                };
+                var toggleToolbar = function () {
+                    var trow = $("tr.ui-search-toolbar", $t.grid.hDiv),
+                        trow2 = $t.p.frozenColumns === true ? $("tr.ui-search-toolbar", $t.grid.fhDiv) : false;
+                    if (trow.css("display") == 'none') {
+                        trow.show();
+                        if (trow2) {
+                            trow2.show();
+                        }
+                    } else {
+                        trow.hide();
+                        if (trow2) {
+                            trow2.hide();
+                        }
+                    }
+                };
+                // create the row
+                function bindEvents(selector, events) {
+                    var jElem = $(selector);
+                    if (jElem[0]) {
+                        jQuery.each(events, function () {
+                            if (this.data !== undefined) {
+                                jElem.bind(this.type, this.data, this.fn);
+                            } else {
+                                jElem.bind(this.type, this.fn);
+                            }
+                        });
+                    }
+                }
+
+                var tr = $("<tr class='ui-search-toolbar' role='rowheader'></tr>");
+                var timeoutHnd;
+                $.each($t.p.colModel, function () {
+                    var cm = this, thd , th, soptions, surl, self;
+                    th = $("<th role='columnheader' class='ui-state-default ui-th-column ui-th-" + $t.p.direction + "'></th>");
+                    thd = $("<div style='width:100%;position:relative;height:100%;padding-right:0.3em;'></div>");
+                    if (this.hidden === true) {
+                        $(th).css("display", "none");
+                    }
+                    this.search = this.search === false ? false : true;
+                    if (typeof this.stype == 'undefined') {
+                        this.stype = 'text';
+                    }
+                    soptions = $.extend({}, this.searchoptions || {});
+                    if (this.search) {
+                        switch (this.stype) {
+                            case "select":
+                                surl = this.surl || soptions.dataUrl;
+                                if (surl) {
+                                    // data returned should have already constructed html select
+                                    // primitive jQuery load
+                                    self = thd;
+                                    $.ajax($.extend({
+                                        url: surl,
+                                        dataType: "html",
+                                        success: function (res) {
+                                            if (soptions.buildSelect !== undefined) {
+                                                var d = soptions.buildSelect(res);
+                                                if (d) {
+                                                    $(self).append(d);
+                                                }
+                                            } else {
+                                                $(self).append(res);
+                                            }
+                                            if (soptions.defaultValue !== undefined) {
+                                                $("select", self).val(soptions.defaultValue);
+                                            }
+                                            $("select", self).attr({name: cm.index || cm.name, id: "gs_" + cm.name});
+                                            if (soptions.attr) {
+                                                $("select", self).attr(soptions.attr);
+                                            }
+                                            $("select", self).css({width: "100%"});
+                                            // preserve autoserch
+                                            if (soptions.dataInit !== undefined) {
+                                                soptions.dataInit($("select", self)[0]);
+                                            }
+                                            if (soptions.dataEvents !== undefined) {
+                                                bindEvents($("select", self)[0], soptions.dataEvents);
+                                            }
+                                            if (p.autosearch === true) {
+                                                $("select", self).change(function () {
+                                                    triggerToolbar();
+                                                    return false;
+                                                });
+                                            }
+                                            res = null;
+                                        }
+                                    }, $.jgrid.ajaxOptions, $t.p.ajaxSelectOptions || {}));
+                                } else {
+                                    var oSv, sep, delim;
+                                    if (cm.searchoptions) {
+                                        oSv = cm.searchoptions.value === undefined ? "" : cm.searchoptions.value;
+                                        sep = cm.searchoptions.separator === undefined ? ":" : cm.searchoptions.separator;
+                                        delim = cm.searchoptions.delimiter === undefined ? ";" : cm.searchoptions.delimiter;
+                                    } else if (cm.editoptions) {
+                                        oSv = cm.editoptions.value === undefined ? "" : cm.editoptions.value;
+                                        sep = cm.editoptions.separator === undefined ? ":" : cm.editoptions.separator;
+                                        delim = cm.editoptions.delimiter === undefined ? ";" : cm.editoptions.delimiter;
+                                    }
+                                    if (oSv) {
+                                        var elem = document.createElement("select");
+                                        elem.style.width = "100%";
+                                        $(elem).attr({name: cm.index || cm.name, id: "gs_" + cm.name});
+                                        var so, sv, ov;
+                                        if (typeof oSv === "string") {
+                                            so = oSv.split(delim);
+                                            for (var k = 0; k < so.length; k++) {
+                                                sv = so[k].split(sep);
+                                                ov = document.createElement("option");
+                                                ov.value = sv[0];
+                                                ov.innerHTML = sv[1];
+                                                elem.appendChild(ov);
+                                            }
+                                        } else if (typeof oSv === "object") {
+                                            for (var key in oSv) {
+                                                if (oSv.hasOwnProperty(key)) {
+                                                    ov = document.createElement("option");
+                                                    ov.value = key;
+                                                    ov.innerHTML = oSv[key];
+                                                    elem.appendChild(ov);
+                                                }
+                                            }
+                                        }
+                                        if (soptions.defaultValue !== undefined) {
+                                            $(elem).val(soptions.defaultValue);
+                                        }
+                                        if (soptions.attr) {
+                                            $(elem).attr(soptions.attr);
+                                        }
+                                        if (soptions.dataInit !== undefined) {
+                                            soptions.dataInit(elem);
+                                        }
+                                        if (soptions.dataEvents !== undefined) {
+                                            bindEvents(elem, soptions.dataEvents);
+                                        }
+                                        $(thd).append(elem);
+                                        if (p.autosearch === true) {
+                                            $(elem).change(function () {
+                                                triggerToolbar();
+                                                return false;
+                                            });
+                                        }
+                                    }
+                                }
+                                break;
+                            case 'text':
+                                var df = soptions.defaultValue !== undefined ? soptions.defaultValue : "";
+                                $(thd).append("<input type='text' style='width:95%;padding:0px;' name='" + (cm.index || cm.name) + "' id='gs_" + cm.name + "' value='" + df + "'/>");
+                                if (soptions.attr) {
+                                    $("input", thd).attr(soptions.attr);
+                                }
+                                if (soptions.dataInit !== undefined) {
+                                    soptions.dataInit($("input", thd)[0]);
+                                }
+                                if (soptions.dataEvents !== undefined) {
+                                    bindEvents($("input", thd)[0], soptions.dataEvents);
+                                }
+                                if (p.autosearch === true) {
+
+                                    if (p.searchOnEnter) {
+                                        $("input", thd).keypress(function (e) {
+                                            var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
+                                            if (key == 13) {
+                                                triggerToolbar();
+                                                return false;
+                                            }
+                                            return this;
+                                        });
+                                    } else {
+                                        $("input", thd).keydown(function (e) {
+                                            var key = e.which;
+                                            switch (key) {
+                                                case 13:
+                                                    return false;
+                                                case 9 :
+                                                case 16:
+                                                case 37:
+                                                case 38:
+                                                case 39:
+                                                case 40:
+                                                case 27:
+                                                    break;
+                                                default :
+                                                    if (timeoutHnd) {
+                                                        clearTimeout(timeoutHnd);
+                                                    }
+                                                    timeoutHnd = setTimeout(function () {
+                                                        triggerToolbar();
+                                                    }, 500);
+                                            }
+                                        });
+                                    }
+                                }
+                                break;
+                        }
+                    }
+                    $(th).append(thd);
+                    $(tr).append(th);
+                });
+                $("table thead", $t.grid.hDiv).append(tr);
+                this.ftoolbar = true;
+                this.triggerToolbar = triggerToolbar;
+                this.clearToolbar = clearToolbar;
+                this.toggleToolbar = toggleToolbar;
+            });
+        },
+
+        destroyGroupHeader: function (nullHeader) {
+            if (typeof(nullHeader) == 'undefined') {
+                nullHeader = true;
+            }
+            return this.each(function () {
+                var $t = this, $tr, i, l, headers, $th, $resizing, grid = $t.grid,
+                    thead = $("table.ui-jqgrid-htable thead", grid.hDiv), cm = $t.p.colModel, hc;
+                if (!grid) {
+                    return;
+                }
+
+                $(this).unbind('.setGroupHeaders');
+                $tr = $("<tr>", {role: "rowheader"}).addClass("ui-jqgrid-labels");
+                headers = grid.headers;
+                for (i = 0, l = headers.length; i < l; i++) {
+                    hc = cm[i].hidden ? "none" : "";
+                    $th = $(headers[i].el)
+                        .width(headers[i].width)
+                        .css('display', hc);
+                    try {
+                        $th.removeAttr("rowSpan");
+                    } catch (rs) {
+                        //IE 6/7
+                        $th.attr("rowSpan", 1);
+                    }
+                    $tr.append($th);
+                    $resizing = $th.children("span.ui-jqgrid-resize");
+                    if ($resizing.length > 0) {// resizable column
+                        $resizing[0].style.height = "";
+                    }
+                    $th.children("div")[0].style.top = "";
+                }
+                $(thead).children('tr.ui-jqgrid-labels').remove();
+                $(thead).prepend($tr);
+
+                if (nullHeader === true) {
+                    $($t).jqGrid('setGridParam', { 'groupHeader': null});
+                }
+            });
+        },
+
+        setGroupHeaders: function (o) {
+            o = $.extend({
+                useColSpanStyle: false,
+                groupHeaders: []
+            }, o || {});
+            return this.each(function () {
+                this.p.groupHeader = o;
+                var ts = this,
+                    i, cmi, skip = 0, $tr, $colHeader, th, $th, thStyle,
+                    iCol,
+                    cghi,
+                //startColumnName,
+                    numberOfColumns,
+                    titleText,
+                    cVisibleColumns,
+                    colModel = ts.p.colModel,
+                    cml = colModel.length,
+                    ths = ts.grid.headers,
+                    $htable = $("table.ui-jqgrid-htable", ts.grid.hDiv),
+                    $trLabels = $htable.children("thead").children("tr.ui-jqgrid-labels:last").addClass("jqg-second-row-header"),
+                    $thead = $htable.children("thead"),
+                    $theadInTable,
+                    $firstHeaderRow = $htable.find(".jqg-first-row-header");
+                if ($firstHeaderRow.html() === null) {
+                    $firstHeaderRow = $('<tr>', {role: "row", "aria-hidden": "true"}).addClass("jqg-first-row-header").css("height", "auto");
+                } else {
+                    $firstHeaderRow.empty();
+                }
+                var $firstRow,
+                    inColumnHeader = function (text, columnHeaders) {
+                        var i = 0, length = columnHeaders.length;
+                        for (; i < length; i++) {
+                            if (columnHeaders[i].startColumnName === text) {
+                                return i;
+                            }
+                        }
+                        return -1;
+                    };
+
+                $(ts).prepend($thead);
+                $tr = $('<tr>', {role: "rowheader"}).addClass("ui-jqgrid-labels jqg-third-row-header");
+                for (i = 0; i < cml; i++) {
+                    th = ths[i].el;
+                    $th = $(th);
+                    cmi = colModel[i];
+                    // build the next cell for the first header row
+                    thStyle = { height: '0px', width: ths[i].width + 'px', display: (cmi.hidden ? 'none' : '')};
+                    $("<th>", {role: 'gridcell'}).css(thStyle).addClass("ui-first-th-" + ts.p.direction).appendTo($firstHeaderRow);
+
+                    th.style.width = ""; // remove unneeded style
+                    iCol = inColumnHeader(cmi.name, o.groupHeaders);
+                    if (iCol >= 0) {
+                        cghi = o.groupHeaders[iCol];
+                        numberOfColumns = cghi.numberOfColumns;
+                        titleText = cghi.titleText;
+
+                        // caclulate the number of visible columns from the next numberOfColumns columns
+                        for (cVisibleColumns = 0, iCol = 0; iCol < numberOfColumns && (i + iCol < cml); iCol++) {
+                            if (!colModel[i + iCol].hidden) {
+                                cVisibleColumns++;
+                            }
+                        }
+
+                        // The next numberOfColumns headers will be moved in the next row
+                        // in the current row will be placed the new column header with the titleText.
+                        // The text will be over the cVisibleColumns columns
+                        $colHeader = $('<th>').attr({role: "columnheader"})
+                            .addClass("ui-state-default ui-th-column-header ui-th-" + ts.p.direction)
+                            .css({'height': '22px', 'border-top': '0px none'})
+                            .html(titleText);
+                        if (cVisibleColumns > 0) {
+                            $colHeader.attr("colspan", String(cVisibleColumns));
+                        }
+                        if (ts.p.headertitles) {
+                            $colHeader.attr("title", $colHeader.text());
+                        }
+                        // hide if not a visible cols
+                        if (cVisibleColumns === 0) {
+                            $colHeader.hide();
+                        }
+
+                        $th.before($colHeader); // insert new column header before the current
+                        $tr.append(th);         // move the current header in the next row
+
+                        // set the coumter of headers which will be moved in the next row
+                        skip = numberOfColumns - 1;
+                    } else {
+                        if (skip === 0) {
+                            if (o.useColSpanStyle) {
+                                // expand the header height to two rows
+                                $th.attr("rowspan", "2");
+                            } else {
+                                $('<th>', {role: "columnheader"})
+                                    .addClass("ui-state-default ui-th-column-header ui-th-" + ts.p.direction)
+                                    .css({"display": cmi.hidden ? 'none' : '', 'border-top': '0px none'})
+                                    .insertBefore($th);
+                                $tr.append(th);
+                            }
+                        } else {
+                            // move the header to the next row
+                            //$th.css({"padding-top": "2px", height: "19px"});
+                            $tr.append(th);
+                            skip--;
+                        }
+                    }
+                }
+                $theadInTable = $(ts).children("thead");
+                $theadInTable.prepend($firstHeaderRow);
+                $tr.insertAfter($trLabels);
+                $htable.append($theadInTable);
+
+                if (o.useColSpanStyle) {
+                    // Increase the height of resizing span of visible headers
+                    $htable.find("span.ui-jqgrid-resize").each(function () {
+                        var $parent = $(this).parent();
+                        if ($parent.is(":visible")) {
+                            this.style.cssText = 'height: ' + $parent.height() + 'px !important; cursor: col-resize;';
+                        }
+                    });
+
+                    // Set position of the sortable div (the main lable)
+                    // with the column header text to the middle of the cell.
+                    // One should not do this for hidden headers.
+                    $htable.find("div.ui-jqgrid-sortable").each(function () {
+                        var $ts = $(this), $parent = $ts.parent();
+                        if ($parent.is(":visible") && $parent.is(":has(span.ui-jqgrid-resize)")) {
+                            $ts.css('top', ($parent.height() - $ts.outerHeight()) / 2 + 'px');
+                        }
+                    });
+                }
+
+                $firstRow = $theadInTable.find("tr.jqg-first-row-header");
+                $(ts).bind('jqGridResizeStop.setGroupHeaders', function (e, nw, idx) {
+                    $firstRow.find('th').eq(idx).width(nw);
+                });
+            });
+        },
+        setFrozenColumns: function () {
+            return this.each(function () {
+                if (!this.grid) {
+                    return;
+                }
+                var $t = this, cm = $t.p.colModel, i = 0, len = cm.length, maxfrozen = -1, frozen = false;
+                // TODO treeGrid and grouping  Support
+                if ($t.p.subGrid === true || $t.p.treeGrid === true || $t.p.cellEdit === true || $t.p.sortable || $t.p.scroll || $t.p.grouping) {
+                    return;
+                }
+                if ($t.p.rownumbers) {
+                    i++;
+                }
+                if ($t.p.multiselect) {
+                    i++;
+                }
+
+                // get the max index of frozen col
+                while (i < len) {
+                    // from left, no breaking frozen
+                    if (cm[i].frozen === true) {
+                        frozen = true;
+                        maxfrozen = i;
+                    } else {
+                        break;
+                    }
+                    i++;
+                }
+                if (maxfrozen >= 0 && frozen) {
+                    var top = $t.p.caption ? $($t.grid.cDiv).outerHeight() : 0,
+                        hth = $(".ui-jqgrid-htable", "#gview_" + $.jgrid.jqID($t.p.id)).height();
+                    //headers
+                    if ($t.p.toppager) {
+                        top = top + $($t.grid.topDiv).outerHeight();
+                    }
+                    if ($t.p.toolbar[0] === true) {
+                        if ($t.p.toolbar[1] != "bottom") {
+                            top = top + $($t.grid.uDiv).outerHeight();
+                        }
+                    }
+                    $t.grid.fhDiv = $('<div style="position:absolute;left:0px;top:' + top + 'px;height:' + hth + 'px;" class="frozen-div ui-state-default ui-jqgrid-hdiv"></div>');
+                    $t.grid.fbDiv = $('<div style="position:absolute;left:0px;top:' + (parseInt(top, 10) + parseInt(hth, 10) + 1) + 'px;overflow-y:hidden" class="frozen-bdiv ui-jqgrid-bdiv"></div>');
+                    $("#gview_" + $.jgrid.jqID($t.p.id)).append($t.grid.fhDiv);
+                    var htbl = $(".ui-jqgrid-htable", "#gview_" + $.jgrid.jqID($t.p.id)).clone(true);
+                    // groupheader support - only if useColSpanstyle is false
+                    if ($t.p.groupHeader) {
+                        $("tr.jqg-first-row-header, tr.jqg-third-row-header", htbl).each(function () {
+                            $("th:gt(" + maxfrozen + ")", this).remove();
+                        });
+                        var swapfroz = -1, fdel = -1;
+                        $("tr.jqg-second-row-header th", htbl).each(function () {
+                            var cs = parseInt($(this).attr("colspan"), 10);
+                            if (cs) {
+                                swapfroz = swapfroz + cs;
+                                fdel++;
+                            }
+                            if (swapfroz === maxfrozen) {
+                                return false;
+                            }
+                        });
+                        if (swapfroz !== maxfrozen) {
+                            fdel = maxfrozen;
+                        }
+                        $("tr.jqg-second-row-header", htbl).each(function () {
+                            $("th:gt(" + fdel + ")", this).remove();
+                        });
+                    } else {
+                        $("tr", htbl).each(function () {
+                            $("th:gt(" + maxfrozen + ")", this).remove();
+                        });
+                    }
+                    $(htbl).width(1);
+                    // resizing stuff
+                    $($t.grid.fhDiv).append(htbl)
+                        .mousemove(function (e) {
+                            if ($t.grid.resizing) {
+                                $t.grid.dragMove(e);
+                                return false;
+                            }
+                        });
+                    $($t).bind('jqGridResizeStop.setFrozenColumns', function (e, w, index) {
+                        var rhth = $(".ui-jqgrid-htable", $t.grid.fhDiv);
+                        $("th:eq(" + index + ")", rhth).width(w);
+                        var btd = $(".ui-jqgrid-btable", $t.grid.fbDiv);
+                        $("tr:first td:eq(" + index + ")", btd).width(w);
+                    });
+                    // sorting stuff
+                    $($t).bind('jqGridOnSortCol.setFrozenColumns', function (index, idxcol) {
+
+                        var previousSelectedTh = $("tr.ui-jqgrid-labels:last th:eq(" + $t.p.lastsort + ")", $t.grid.fhDiv), newSelectedTh = $("tr.ui-jqgrid-labels:last th:eq(" + idxcol + ")", $t.grid.fhDiv);
+
+                        $("span.ui-grid-ico-sort", previousSelectedTh).addClass('ui-state-disabled');
+                        $(previousSelectedTh).attr("aria-selected", "false");
+                        $("span.ui-icon-" + $t.p.sortorder, newSelectedTh).removeClass('ui-state-disabled');
+                        $(newSelectedTh).attr("aria-selected", "true");
+                        if (!$t.p.viewsortcols[0]) {
+                            if ($t.p.lastsort != idxcol) {
+                                $("span.s-ico", previousSelectedTh).hide();
+                                $("span.s-ico", newSelectedTh).show();
+                            }
+                        }
+                    });
+
+                    // data stuff
+                    //TODO support for setRowData
+                    $("#gview_" + $.jgrid.jqID($t.p.id)).append($t.grid.fbDiv);
+                    jQuery($t.grid.bDiv).scroll(function () {
+                        jQuery($t.grid.fbDiv).scrollTop(jQuery(this).scrollTop());
+                    });
+                    if ($t.p.hoverrows === true) {
+                        $("#" + $.jgrid.jqID($t.p.id)).unbind('mouseover').unbind('mouseout');
+                    }
+                    $($t).bind('jqGridAfterGridComplete.setFrozenColumns', function () {
+                        $("#" + $.jgrid.jqID($t.p.id) + "_frozen").remove();
+                        jQuery($t.grid.fbDiv).height(jQuery($t.grid.bDiv).height() - 16);
+                        var btbl = $("#" + $.jgrid.jqID($t.p.id)).clone(true);
+                        $("tr", btbl).each(function () {
+                            $("td:gt(" + maxfrozen + ")", this).remove();
+                        });
+
+                        $(btbl).width(1).attr("id", $t.p.id + "_frozen");
+                        $($t.grid.fbDiv).append(btbl);
+                        if ($t.p.hoverrows === true) {
+                            $("tr.jqgrow", btbl).hover(
+                                function () {
+                                    $(this).addClass("ui-state-hover");
+                                    $("#" + $.jgrid.jqID(this.id), "#" + $.jgrid.jqID($t.p.id)).addClass("ui-state-hover");
+                                },
+                                function () {
+                                    $(this).removeClass("ui-state-hover");
+                                    $("#" + $.jgrid.jqID(this.id), "#" + $.jgrid.jqID($t.p.id)).removeClass("ui-state-hover");
+                                }
+                            );
+                            $("tr.jqgrow", "#" + $.jgrid.jqID($t.p.id)).hover(
+                                function () {
+                                    $(this).addClass("ui-state-hover");
+                                    $("#" + $.jgrid.jqID(this.id), "#" + $.jgrid.jqID($t.p.id) + "_frozen").addClass("ui-state-hover");
+                                },
+                                function () {
+                                    $(this).removeClass("ui-state-hover");
+                                    $("#" + $.jgrid.jqID(this.id), "#" + $.jgrid.jqID($t.p.id) + "_frozen").removeClass("ui-state-hover");
+                                }
+                            );
+                        }
+                        btbl = null;
+                    });
+                    $t.p.frozenColumns = true;
+                }
+            });
+        },
+        destroyFrozenColumns: function () {
+            return this.each(function () {
+                if (!this.grid) {
+                    return;
+                }
+                if (this.p.frozenColumns === true) {
+                    var $t = this;
+                    $($t.grid.fhDiv).remove();
+                    $($t.grid.fbDiv).remove();
+                    $t.grid.fhDiv = null;
+                    $t.grid.fbDiv = null;
+                    $(this).unbind('.setFrozenColumns');
+                    if ($t.p.hoverrows === true) {
+                        var ptr;
+                        $("#" + $.jgrid.jqID($t.p.id)).bind('mouseover',function (e) {
+                            ptr = $(e.target).closest("tr.jqgrow");
+                            if ($(ptr).attr("class") !== "ui-subgrid") {
+                                $(ptr).addClass("ui-state-hover");
+                            }
+                        }).bind('mouseout', function (e) {
+                                ptr = $(e.target).closest("tr.jqgrow");
+                                $(ptr).removeClass("ui-state-hover");
+                            });
+                    }
+                    this.p.frozenColumns = false;
+                }
+            });
+        }
+    });
+})(jQuery);
+/*
+ * jqModal - Minimalist Modaling with jQuery
+ *   (http://dev.iceburg.net/jquery/jqmodal/)
+ *
+ * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
+ * Dual licensed under the MIT and GPL licenses:
+ *   http://www.opensource.org/licenses/mit-license.php
+ *   http://www.gnu.org/licenses/gpl.html
+ *
+ * $Version: 07/06/2008 +r13
+ */
+(function ($) {
+    $.fn.jqm = function (o) {
+        var p = {
+            overlay: 50,
+            closeoverlay: true,
+            overlayClass: 'jqmOverlay',
+            closeClass: 'jqmClose',
+            trigger: '.jqModal',
+            ajax: F,
+            ajaxText: '',
+            target: F,
+            modal: F,
+            toTop: F,
+            onShow: F,
+            onHide: F,
+            onLoad: F
+        };
+        return this.each(function () {
+            if (this._jqm)return H[this._jqm].c = $.extend({}, H[this._jqm].c, o);
+            s++;
+            this._jqm = s;
+            H[s] = {c: $.extend(p, $.jqm.params, o), a: F, w: $(this).addClass('jqmID' + s), s: s};
+            if (p.trigger)$(this).jqmAddTrigger(p.trigger);
+        });
+    };
+
+    $.fn.jqmAddClose = function (e) {
+        return hs(this, e, 'jqmHide');
+    };
+    $.fn.jqmAddTrigger = function (e) {
+        return hs(this, e, 'jqmShow');
+    };
+    $.fn.jqmShow = function (t) {
+        return this.each(function () {
+            $.jqm.open(this._jqm, t);
+        });
+    };
+    $.fn.jqmHide = function (t) {
+        return this.each(function () {
+            $.jqm.close(this._jqm, t)
+        });
+    };
+
+    $.jqm = {
+        hash: {},
+        open: function (s, t) {
+            var h = H[s], c = h.c, cc = '.' + c.closeClass, z = (parseInt(h.w.css('z-index')));
+            z = (z > 0) ? z : 3000;
+            var o = $('<div></div>').css({height: '100%', width: '100%', position: 'fixed', left: 0, top: 0, 'z-index': z - 1, opacity: c.overlay / 100});
+            if (h.a)return F;
+            h.t = t;
+            h.a = true;
+            h.w.css('z-index', z);
+            if (c.modal) {
+                if (!A[0])setTimeout(function () {
+                    L('bind');
+                }, 1);
+                A.push(s);
+            }
+            else if (c.overlay > 0) {
+                if (c.closeoverlay) h.w.jqmAddClose(o);
+            }
+            else o = F;
+
+            h.o = (o) ? o.addClass(c.overlayClass).prependTo('body') : F;
+            if (ie6) {
+                $('html,body').css({height: '100%', width: '100%'});
+                if (o) {
+                    o = o.css({position: 'absolute'})[0];
+                    for (var y in {Top: 1, Left: 1})o.style.setExpression(y.toLowerCase(), "(_=(document.documentElement.scroll" + y + " || document.body.scroll" + y + "))+'px'");
+                }
+            }
+
+            if (c.ajax) {
+                var r = c.target || h.w, u = c.ajax;
+                r = (typeof r == 'string') ? $(r, h.w) : $(r);
+                u = (u.substr(0, 1) == '@') ? $(t).attr(u.substring(1)) : u;
+                r.html(c.ajaxText).load(u, function () {
+                    if (c.onLoad)c.onLoad.call(this, h);
+                    if (cc)h.w.jqmAddClose($(cc, h.w));
+                    e(h);
+                });
+            }
+            else if (cc)h.w.jqmAddClose($(cc, h.w));
+
+            if (c.toTop && h.o)h.w.before('<span id="jqmP' + h.w[0]._jqm + '"></span>').insertAfter(h.o);
+            (c.onShow) ? c.onShow(h) : h.w.show();
+            e(h);
+            return F;
+        },
+        close: function (s) {
+            var h = H[s];
+            if (!h.a)return F;
+            h.a = F;
+            if (A[0]) {
+                A.pop();
+                if (!A[0])L('unbind');
+            }
+            if (h.c.toTop && h.o)$('#jqmP' + h.w[0]._jqm).after(h.w).remove();
+            if (h.c.onHide)h.c.onHide(h); else {
+                h.w.hide();
+                if (h.o)h.o.remove();
+            }
+            return F;
+        },
+        params: {}};
+    var s = 0, H = $.jqm.hash, A = [], ie6 = $.browser.msie && ($.browser.version == "6.0"), F = false,
+        e = function (h) {
+            var i = $('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity: 0});
+            if (ie6)if (h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i); else if (!$('iframe.jqm', h.w)[0])h.w.prepend(i);
+            f(h);
+        },
+        f = function (h) {
+            try {
+                $(':input:visible', h.w)[0].focus();
+            } catch (_) {
+            }
+        },
+        L = function (t) {
+            $(document)[t]("keypress", m)[t]("keydown", m)[t]("mousedown", m);
+        },
+        m = function (e) {
+            var h = H[A[A.length - 1]], r = (!$(e.target).parents('.jqmID' + h.s)[0]);
+            if (r)f(h);
+            return !r;
+        },
+        hs = function (w, t, c) {
+            return w.each(function () {
+                var s = this._jqm;
+                $(t).each(function () {
+                    if (!this[c]) {
+                        this[c] = [];
+                        $(this).click(function () {
+                            for (var i in {jqmShow: 1, jqmHide: 1})for (var s in this[i])if (H[this[i][s]])H[this[i][s]].w[i](this);
+                            return F;
+                        });
+                    }
+                    this[c].push(s);
+                });
+            });
+        };
+})(jQuery);
+/*
+ * jqDnR - Minimalistic Drag'n'Resize for jQuery.
+ *
+ * Copyright (c) 2007 Brice Burgess <bhb@iceburg.net>, http://www.iceburg.net
+ * Licensed under the MIT License:
+ * http://www.opensource.org/licenses/mit-license.php
+ *
+ * $Version: 2007.08.19 +r2
+ */
+
+(function ($) {
+    $.fn.jqDrag = function (h) {
+        return i(this, h, 'd');
+    };
+    $.fn.jqResize = function (h, ar) {
+        return i(this, h, 'r', ar);
+    };
+    $.jqDnR = {
+        dnr: {},
+        e: 0,
+        drag: function (v) {
+            if (M.k == 'd') {
+                E.css({left: M.X + v.pageX - M.pX, top: M.Y + v.pageY - M.pY});
+            }
+            else {
+                E.css({width: Math.max(v.pageX - M.pX + M.W, 0), height: Math.max(v.pageY - M.pY + M.H, 0)});
+                if (M1) {
+                    E1.css({width: Math.max(v.pageX - M1.pX + M1.W, 0), height: Math.max(v.pageY - M1.pY + M1.H, 0)});
+                }
+            }
+            return false;
+        },
+        stop: function () {
+            //E.css('opacity',M.o);
+            $(document).unbind('mousemove', J.drag).unbind('mouseup', J.stop);
+        }
+    };
+    var J = $.jqDnR, M = J.dnr, E = J.e, E1, M1,
+        i = function (e, h, k, aR) {
+            return e.each(function () {
+                h = (h) ? $(h, e) : e;
+                h.bind('mousedown', {e: e, k: k}, function (v) {
+                    var d = v.data, p = {};
+                    E = d.e;
+                    E1 = aR ? $(aR) : false;
+                    // attempt utilization of dimensions plugin to fix IE issues
+                    if (E.css('position') != 'relative') {
+                        try {
+                            E.position(p);
+                        } catch (e) {
+                        }
+                    }
+                    M = {
+                        X: p.left || f('left') || 0,
+                        Y: p.top || f('top') || 0,
+                        W: f('width') || E[0].scrollWidth || 0,
+                        H: f('height') || E[0].scrollHeight || 0,
+                        pX: v.pageX,
+                        pY: v.pageY,
+                        k: d.k
+                        //o:E.css('opacity')
+                    };
+                    // also resize
+                    if (E1 && d.k != 'd') {
+                        M1 = {
+                            X: p.left || f1('left') || 0,
+                            Y: p.top || f1('top') || 0,
+                            W: E1[0].offsetWidth || f1('width') || 0,
+                            H: E1[0].offsetHeight || f1('height') || 0,
+                            pX: v.pageX,
+                            pY: v.pageY,
+                            k: d.k
+                        };
+                    } else {
+                        M1 = false;
+                    }
+                    //E.css({opacity:0.8});
+                    if ($("input.hasDatepicker", E[0])[0]) {
+                        try {
+                            $("input.hasDatepicker", E[0]).datepicker('hide');
+                        } catch (dpe) {
+                        }
+                    }
+                    $(document).mousemove($.jqDnR.drag).mouseup($.jqDnR.stop);
+                    return false;
+                });
+            });
+        },
+        f = function (k) {
+            return parseInt(E.css(k), 10) || false;
+        },
+        f1 = function (k) {
+            return parseInt(E1.css(k), 10) || false;
+        };
+})(jQuery);
+/*
+ The below work is licensed under Creative Commons GNU LGPL License.
+
+ Original work:
+
+ License:     http://creativecommons.org/licenses/LGPL/2.1/
+ Author:      Stefan Goessner/2006
+ Web:         http://goessner.net/
+
+ Modifications made:
+
+ Version:     0.9-p5
+ Description: Restructured code, JSLint validated (no strict whitespaces),
+ added handling of empty arrays, empty strings, and int/floats values.
+ Author:      Michael Schøler/2008-01-29
+ Web:         http://michael.hinnerup.net/blog/2008/01/26/converting-json-to-xml-and-xml-to-json/
+
+ Description: json2xml added support to convert functions as CDATA
+ so it will be easy to write characters that cause some problems when convert
+ Author:      Tony Tomov
+ */
+
+/*global alert */
+var xmlJsonClass = {
+    // Param "xml": Element or document DOM node.
+    // Param "tab": Tab or indent string for pretty output formatting omit or use empty string "" to supress.
+    // Returns:     JSON string
+    xml2json: function (xml, tab) {
+        if (xml.nodeType === 9) {
+            // document node
+            xml = xml.documentElement;
+        }
+        var nws = this.removeWhite(xml);
+        var obj = this.toObj(nws);
+        var json = this.toJson(obj, xml.nodeName, "\t");
+        return "{\n" + tab + (tab ? json.replace(/\t/g, tab) : json.replace(/\t|\n/g, "")) + "\n}";
+    },
+
+    // Param "o":   JavaScript object
+    // Param "tab": tab or indent string for pretty output formatting omit or use empty string "" to supress.
+    // Returns:     XML string
+    json2xml: function (o, tab) {
+        var toXml = function (v, name, ind) {
+            var xml = "";
+            var i, n;
+            if (v instanceof Array) {
+                if (v.length === 0) {
+                    xml += ind + "<" + name + ">__EMPTY_ARRAY_</" + name + ">\n";
+                }
+                else {
+                    for (i = 0, n = v.length; i < n; i += 1) {
+                        var sXml = ind + toXml(v[i], name, ind + "\t") + "\n";
+                        xml += sXml;
+                    }
+                }
+            }
+            else if (typeof(v) === "object") {
+                var hasChild = false;
+                xml += ind + "<" + name;
+                var m;
+                for (m in v) if (v.hasOwnProperty(m)) {
+                    if (m.charAt(0) === "@") {
+                        xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
+                    }
+                    else {
+                        hasChild = true;
+                    }
+                }
+                xml += hasChild ? ">" : "/>";
+                if (hasChild) {
+                    for (m in v) if (v.hasOwnProperty(m)) {
+                        if (m === "#text") {
+                            xml += v[m];
+                        }
+                        else if (m === "#cdata") {
+                            xml += "<![CDATA[" + v[m] + "]]>";
+                        }
+                        else if (m.charAt(0) !== "@") {
+                            xml += toXml(v[m], m, ind + "\t");
+                        }
+                    }
+                    xml += (xml.charAt(xml.length - 1) === "\n" ? ind : "") + "</" + name + ">";
+                }
+            }
+            else if (typeof(v) === "function") {
+                xml += ind + "<" + name + ">" + "<![CDATA[" + v + "]]>" + "</" + name + ">";
+            }
+            else {
+                if (v === undefined) {
+                    v = "";
+                }
+                if (v.toString() === "\"\"" || v.toString().length === 0) {
+                    xml += ind + "<" + name + ">__EMPTY_STRING_</" + name + ">";
+                }
+                else {
+                    xml += ind + "<" + name + ">" + v.toString() + "</" + name + ">";
+                }
+            }
+            return xml;
+        };
+        var xml = "";
+        var m;
+        for (m in o) if (o.hasOwnProperty(m)) {
+            xml += toXml(o[m], m, "");
+        }
+        return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, "");
+    },
+    // Internal methods
+    toObj: function (xml) {
+        var o = {};
+        var FuncTest = /function/i;
+        if (xml.nodeType === 1) {
+            // element node ..
+            if (xml.attributes.length) {
+                // element with attributes ..
+                var i;
+                for (i = 0; i < xml.attributes.length; i += 1) {
+                    o["@" + xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue || "").toString();
+                }
+            }
+            if (xml.firstChild) {
+                // element has child nodes ..
+                var textChild = 0, cdataChild = 0, hasElementChild = false;
+                var n;
+                for (n = xml.firstChild; n; n = n.nextSibling) {
+                    if (n.nodeType === 1) {
+                        hasElementChild = true;
+                    }
+                    else if (n.nodeType === 3 && n.nodeValue.match(/[^ \f\n\r\t\v]/)) {
+                        // non-whitespace text
+                        textChild += 1;
+                    }
+                    else if (n.nodeType === 4) {
+                        // cdata section node
+                        cdataChild += 1;
+                    }
+                }
+                if (hasElementChild) {
+                    if (textChild < 2 && cdataChild < 2) {
+                        // structured element with evtl. a single text or/and cdata node ..
+                        this.removeWhite(xml);
+                        for (n = xml.firstChild; n; n = n.nextSibling) {
+                            if (n.nodeType === 3) {
+                                // text node
+                                o["#text"] = this.escape(n.nodeValue);
+                            }
+                            else if (n.nodeType === 4) {
+                                // cdata node
+                                if (FuncTest.test(n.nodeValue)) {
+                                    o[n.nodeName] = [o[n.nodeName], n.nodeValue];
+                                } else {
+                                    o["#cdata"] = this.escape(n.nodeValue);
+                                }
+                            }
+                            else if (o[n.nodeName]) {
+                                // multiple occurence of element ..
+                                if (o[n.nodeName] instanceof Array) {
+                                    o[n.nodeName][o[n.nodeName].length] = this.toObj(n);
+                                }
+                                else {
+                                    o[n.nodeName] = [o[n.nodeName], this.toObj(n)];
+                                }
+                            }
+                            else {
+                                // first occurence of element ..
+                                o[n.nodeName] = this.toObj(n);
+                            }
+                        }
+                    }
+                    else {
+                        // mixed content
+                        if (!xml.attributes.length) {
+                            o = this.escape(this.innerXml(xml));
+                        }
+                        else {
+                            o["#text"] = this.escape(this.innerXml(xml));
+                        }
+                    }
+                }
+                else if (textChild) {
+                    // pure text
+                    if (!xml.attributes.length) {
+                        o = this.escape(this.innerXml(xml));
+                        if (o === "__EMPTY_ARRAY_") {
+                            o = "[]";
+                        } else if (o === "__EMPTY_STRING_") {
+                            o = "";
+                        }
+                    }
+                    else {
+                        o["#text"] = this.escape(this.innerXml(xml));
+                    }
+                }
+                else if (cdataChild) {
+                    // cdata
+                    if (cdataChild > 1) {
+                        o = this.escape(this.innerXml(xml));
+                    }
+                    else {
+                        for (n = xml.firstChild; n; n = n.nextSibling) {
+                            if (FuncTest.test(xml.firstChild.nodeValue)) {
+                                o = xml.firstChild.nodeValue;
+                                break;
+                            } else {
+                                o["#cdata"] = this.escape(n.nodeValue);
+                            }
+                        }
+                    }
+                }
+            }
+            if (!xml.attributes.length && !xml.firstChild) {
+                o = null;
+            }
+        }
+        else if (xml.nodeType === 9) {
+            // document.node
+            o = this.toObj(xml.documentElement);
+        }
+        else {
+            alert("unhandled node type: " + xml.nodeType);
+        }
+        return o;
+    },
+    toJson: function (o, name, ind, wellform) {
+        if (wellform === undefined) wellform = true;
+        var json = name ? ("\"" + name + "\"") : "", tab = "\t", newline = "\n";
+        if (!wellform) {
+            tab = "";
+            newline = "";
+        }
+
+        if (o === "[]") {
+            json += (name ? ":[]" : "[]");
+        }
+        else if (o instanceof Array) {
+            var n, i, ar = [];
+            for (i = 0, n = o.length; i < n; i += 1) {
+                ar[i] = this.toJson(o[i], "", ind + tab, wellform);
+            }
+            json += (name ? ":[" : "[") + (ar.length > 1 ? (newline + ind + tab + ar.join("," + newline + ind + tab) + newline + ind) : ar.join("")) + "]";
+        }
+        else if (o === null) {
+            json += (name && ":") + "null";
+        }
+        else if (typeof(o) === "object") {
+            var arr = [], m;
+            for (m in o) {
+                if (o.hasOwnProperty(m)) {
+                    arr[arr.length] = this.toJson(o[m], m, ind + tab, wellform);
+                }
+            }
+            json += (name ? ":{" : "{") + (arr.length > 1 ? (newline + ind + tab + arr.join("," + newline + ind + tab) + newline + ind) : arr.join("")) + "}";
+        }
+        else if (typeof(o) === "string") {
+            /*
+             var objRegExp  = /(^-?\d+\.?\d*$)/;
+             var FuncTest = /function/i;
+             var os = o.toString();
+             if (objRegExp.test(os) || FuncTest.test(os) || os==="false" || os==="true") {
+             // int or float
+             json += (name && ":")  + "\"" +os + "\"";
+             }
+             else {
+             */
+            json += (name && ":") + "\"" + o.replace(/\\/g, '\\\\').replace(/\"/g, '\\"') + "\"";
+            //}
+        }
+        else {
+            json += (name && ":") + o.toString();
+        }
+        return json;
+    },
+    innerXml: function (node) {
+        var s = "";
+        if ("innerHTML" in node) {
+            s = node.innerHTML;
+        }
+        else {
+            var asXml = function (n) {
+                var s = "", i;
+                if (n.nodeType === 1) {
+                    s += "<" + n.nodeName;
+                    for (i = 0; i < n.attributes.length; i += 1) {
+                        s += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue || "").toString() + "\"";
+                    }
+                    if (n.firstChild) {
+                        s += ">";
+                        for (var c = n.firstChild; c; c = c.nextSibling) {
+                            s += asXml(c);
+                        }
+                        s += "</" + n.nodeName + ">";
+                    }
+                    else {
+                        s += "/>";
+                    }
+                }
+                else if (n.nodeType === 3) {
+                    s += n.nodeValue;
+                }
+                else if (n.nodeType === 4) {
+                    s += "<![CDATA[" + n.nodeValue + "]]>";
+                }
+                return s;
+            };
+            for (var c = node.firstChild; c; c = c.nextSibling) {
+                s += asXml(c);
+            }
+        }
+        return s;
+    },
+    escape: function (txt) {
+        return txt.replace(/[\\]/g, "\\\\").replace(/[\"]/g, '\\"').replace(/[\n]/g, '\\n').replace(/[\r]/g, '\\r');
+    },
+    removeWhite: function (e) {
+        e.normalize();
+        var n;
+        for (n = e.firstChild; n;) {
+            if (n.nodeType === 3) {
+                // text node
+                if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) {
+                    // pure whitespace text node
+                    var nxt = n.nextSibling;
+                    e.removeChild(n);
+                    n = nxt;
+                }
+                else {
+                    n = n.nextSibling;
+                }
+            }
+            else if (n.nodeType === 1) {
+                // element node
+                this.removeWhite(n);
+                n = n.nextSibling;
+            }
+            else {
+                // any other node
+                n = n.nextSibling;
+            }
+        }
+        return e;
+    }
 };
-$.jgrid.extend({
-	getGridParam : function(pName) {
-		var $t = this[0];
-		if (!$t || !$t.grid) {return;}
-		if (!pName) { return $t.p; }
-		else {return typeof($t.p[pName]) != "undefined" ? $t.p[pName] : null;}
-	},
-	setGridParam : function (newParams){
-		return this.each(function(){
-			if (this.grid && typeof(newParams) === 'object') {$.extend(true,this.p,newParams);}
-		});
-	},
-	getDataIDs : function () {
-		var ids=[], i=0, len, j=0;
-		this.each(function(){
-			len = this.rows.length;
-			if(len && len>0){
-				while(i<len) {
-					if($(this.rows[i]).hasClass('jqgrow')) {
-						ids[j] = this.rows[i].id;
-						j++;
-					}
-					i++;
-				}
-			}
-		});
-		return ids;
-	},
-	setSelection : function(selection,onsr, e) {
-		return this.each(function(){
-			var $t = this, stat,pt, ner, ia, tpsr, fid;
-			if(selection === undefined) { return; }
-			onsr = onsr === false ? false : true;
-			pt=$t.rows.namedItem(selection+"");
-			if(!pt || !pt.className || pt.className.indexOf( 'ui-state-disabled' ) > -1 ) { return; }
-			function scrGrid(iR){
-				var ch = $($t.grid.bDiv)[0].clientHeight,
-				st = $($t.grid.bDiv)[0].scrollTop,
-				rpos = $t.rows[iR].offsetTop,
-				rh = $t.rows[iR].clientHeight;
-				if(rpos+rh >= ch+st) { $($t.grid.bDiv)[0].scrollTop = rpos-(ch+st)+rh+st; }
-				else if(rpos < ch+st) {
-					if(rpos < st) {
-						$($t.grid.bDiv)[0].scrollTop = rpos;
-					}
-				}
-			}
-			if($t.p.scrollrows===true) {
-				ner = $t.rows.namedItem(selection).rowIndex;
-				if(ner >=0 ){
-					scrGrid(ner);
-				}
-			}
-			if($t.p.frozenColumns === true ) {
-				fid = $t.p.id+"_frozen";
-			}
-			if(!$t.p.multiselect) {
-				if(pt.className !== "ui-subgrid") {
-					if( $t.p.selrow != pt.id) {
-						$($t.rows.namedItem($t.p.selrow)).removeClass("ui-state-highlight").attr({"aria-selected":"false", "tabindex" : "-1"});
-						$(pt).addClass("ui-state-highlight").attr({"aria-selected":"true", "tabindex" : "0"});//.focus();
-						if(fid) {
-							$("#"+$.jgrid.jqID($t.p.selrow), "#"+$.jgrid.jqID(fid)).removeClass("ui-state-highlight");
-							$("#"+$.jgrid.jqID(selection), "#"+$.jgrid.jqID(fid)).addClass("ui-state-highlight");
-						}
-						stat = true;
-					} else {
-						stat = false;
-					}
-					$t.p.selrow = pt.id;
-					$($t).triggerHandler("jqGridSelectRow", [pt.id, stat, e]);
-					if( $t.p.onSelectRow && onsr) { $t.p.onSelectRow.call($t, pt.id, stat, e); }
-				}
-			} else {
-				//unselect selectall checkbox when deselecting a specific row
-				$t.setHeadCheckBox( false );
-				$t.p.selrow = pt.id;
-				ia = $.inArray($t.p.selrow,$t.p.selarrrow);
-				if (  ia === -1 ){
-					if(pt.className !== "ui-subgrid") { $(pt).addClass("ui-state-highlight").attr("aria-selected","true");}
-					stat = true;
-					$t.p.selarrrow.push($t.p.selrow);
-				} else {
-					if(pt.className !== "ui-subgrid") { $(pt).removeClass("ui-state-highlight").attr("aria-selected","false");}
-					stat = false;
-					$t.p.selarrrow.splice(ia,1);
-					tpsr = $t.p.selarrrow[0];
-					$t.p.selrow = (tpsr === undefined) ? null : tpsr;
-				}
-				$("#jqg_"+$.jgrid.jqID($t.p.id)+"_"+$.jgrid.jqID(pt.id))[$t.p.useProp ? 'prop': 'attr']("checked",stat);
-				if(fid) {
-					if(ia === -1) {
-						$("#"+$.jgrid.jqID(selection), "#"+$.jgrid.jqID(fid)).addClass("ui-state-highlight");
-					} else {
-						$("#"+$.jgrid.jqID(selection), "#"+$.jgrid.jqID(fid)).removeClass("ui-state-highlight");
-					}
-					$("#jqg_"+$.jgrid.jqID($t.p.id)+"_"+$.jgrid.jqID(selection), "#"+$.jgrid.jqID(fid))[$t.p.useProp ? 'prop': 'attr']("checked",stat);
-				}
-				$($t).triggerHandler("jqGridSelectRow", [pt.id, stat, e]);
-				if( $t.p.onSelectRow && onsr) { $t.p.onSelectRow.call($t, pt.id , stat, e); }
-			}
-		});
-	},
-	resetSelection : function( rowid ){
-		return this.each(function(){
-			var t = this, ind, sr, fid;
-			if( t.p.frozenColumns === true ) {
-				fid = t.p.id+"_frozen";
-			}
-			if(typeof(rowid) !== "undefined" ) {
-				sr = rowid === t.p.selrow ? t.p.selrow : rowid;
-				$("#"+$.jgrid.jqID(t.p.id)+" tbody:first tr#"+$.jgrid.jqID(sr)).removeClass("ui-state-highlight").attr("aria-selected","false");
-				if (fid) { $("#"+$.jgrid.jqID(sr), "#"+$.jgrid.jqID(fid)).removeClass("ui-state-highlight"); }
-				if(t.p.multiselect) {
-					$("#jqg_"+$.jgrid.jqID(t.p.id)+"_"+$.jgrid.jqID(sr), "#"+$.jgrid.jqID(t.p.id))[t.p.useProp ? 'prop': 'attr']("checked",false);
-					if(fid) { $("#jqg_"+$.jgrid.jqID(t.p.id)+"_"+$.jgrid.jqID(sr), "#"+$.jgrid.jqID(fid))[t.p.useProp ? 'prop': 'attr']("checked",false); }
-					t.setHeadCheckBox( false);
-				}
-				sr = null;
-			} else if(!t.p.multiselect) {
-				if(t.p.selrow) {
-					$("#"+$.jgrid.jqID(t.p.id)+" tbody:first tr#"+$.jgrid.jqID(t.p.selrow)).removeClass("ui-state-highlight").attr("aria-selected","false");
-					if(fid) { $("#"+$.jgrid.jqID(t.p.selrow), "#"+$.jgrid.jqID(fid)).removeClass("ui-state-highlight"); }
-					t.p.selrow = null;
-				}
-			} else {
-				$(t.p.selarrrow).each(function(i,n){
-					ind = t.rows.namedItem(n);
-					$(ind).removeClass("ui-state-highlight").attr("aria-selected","false");
-					$("#jqg_"+$.jgrid.jqID(t.p.id)+"_"+$.jgrid.jqID(n))[t.p.useProp ? 'prop': 'attr']("checked",false);
-					if(fid) {
-						$("#"+$.jgrid.jqID(n), "#"+$.jgrid.jqID(fid)).removeClass("ui-state-highlight");
-						$("#jqg_"+$.jgrid.jqID(t.p.id)+"_"+$.jgrid.jqID(n), "#"+$.jgrid.jqID(fid))[t.p.useProp ? 'prop': 'attr']("checked",false);
-					}
-				});
-				t.setHeadCheckBox( false );
-				t.p.selarrrow = [];
-			}
-			if(t.p.cellEdit === true) {
-				if(parseInt(t.p.iCol,10)>=0  && parseInt(t.p.iRow,10)>=0) {
-					$("td:eq("+t.p.iCol+")",t.rows[t.p.iRow]).removeClass("edit-cell ui-state-highlight");
-					$(t.rows[t.p.iRow]).removeClass("selected-row ui-state-hover");
-				}
-			}
-			t.p.savedRow = [];
-		});
-	},
-	getRowData : function( rowid ) {
-		var res = {}, resall, getall=false, len, j=0;
-		this.each(function(){
-			var $t = this,nm,ind;
-			if(typeof(rowid) == 'undefined') {
-				getall = true;
-				resall = [];
-				len = $t.rows.length;
-			} else {
-				ind = $t.rows.namedItem(rowid);
-				if(!ind) { return res; }
-				len = 2;
-			}
-			while(j<len){
-				if(getall) { ind = $t.rows[j]; }
-				if( $(ind).hasClass('jqgrow') ) {
-					$('td[role="gridcell"]',ind).each( function(i) {
-						nm = $t.p.colModel[i].name;
-						if ( nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn') {
-							if($t.p.treeGrid===true && nm == $t.p.ExpandColumn) {
-								res[nm] = $.jgrid.htmlDecode($("span:first",this).html());
-							} else {
-								try {
-									res[nm] = $.unformat.call($t,this,{rowId:ind.id, colModel:$t.p.colModel[i]},i);
-								} catch (e){
-									res[nm] = $.jgrid.htmlDecode($(this).html());
-								}
-							}
-						}
-					});
-					if(getall) { resall.push(res); res={}; }
-				}
-				j++;
-			}
-		});
-		return resall ? resall: res;
-	},
-	delRowData : function(rowid) {
-		var success = false, rowInd, ia, ri;
-		this.each(function() {
-			var $t = this;
-			rowInd = $t.rows.namedItem(rowid);
-			if(!rowInd) {return false;}
-			else {
-				ri = rowInd.rowIndex;
-				$(rowInd).remove();
-				$t.p.records--;
-				$t.p.reccount--;
-				$t.updatepager(true,false);
-				success=true;
-				if($t.p.multiselect) {
-					ia = $.inArray(rowid,$t.p.selarrrow);
-					if(ia != -1) { $t.p.selarrrow.splice(ia,1);}
-				}
-				if(rowid == $t.p.selrow) {$t.p.selrow=null;}
-			}
-			if($t.p.datatype == 'local') {
-				var id = $.jgrid.stripPref($t.p.idPrefix, rowid),
-				pos = $t.p._index[id];
-				if(typeof(pos) != 'undefined') {
-					$t.p.data.splice(pos,1);
-					$t.refreshIndex();
-				}
-			}
-			if( $t.p.altRows === true && success ) {
-				var cn = $t.p.altclass;
-				$($t.rows).each(function(i){
-					if(i % 2 ==1) { $(this).addClass(cn); }
-					else { $(this).removeClass(cn); }
-				});
-			}
-		});
-		return success;
-	},
-	setRowData : function(rowid, data, cssp) {
-		var nm, success=true, title;
-		this.each(function(){
-			if(!this.grid) {return false;}
-			var t = this, vl, ind, cp = typeof cssp, lcdata={};
-			ind = t.rows.namedItem(rowid);
-			if(!ind) { return false; }
-			if( data ) {
-				try {
-					$(this.p.colModel).each(function(i){
-						nm = this.name;
-						if( data[nm] !== undefined) {
-							lcdata[nm] = this.formatter && typeof(this.formatter) === 'string' && this.formatter == 'date' ? $.unformat.date.call(t,data[nm],this) : data[nm];
-							vl = t.formatter( rowid, data[nm], i, data, 'edit');
-							title = this.title ? {"title":$.jgrid.stripHtml(vl)} : {};
-							if(t.p.treeGrid===true && nm == t.p.ExpandColumn) {
-								$("td:eq("+i+") > span:first",ind).html(vl).attr(title);
-							} else {
-								$("td:eq("+i+")",ind).html(vl).attr(title);
-							}
-						}
-					});
-					if(t.p.datatype == 'local') {
-						var id = $.jgrid.stripPref(t.p.idPrefix, rowid),
-						pos = t.p._index[id];
-						if(t.p.treeGrid) {
-							for(var key in t.p.treeReader ){
-								if(lcdata.hasOwnProperty(t.p.treeReader[key])) {
-									delete lcdata[t.p.treeReader[key]];
-								}
-							}
-						}
-						if(typeof(pos) != 'undefined') {
-							t.p.data[pos] = $.extend(true, t.p.data[pos], lcdata);
-						}
-						lcdata = null;
-					}
-				} catch (e) {
-					success = false;
-				}
-			}
-			if(success) {
-				if(cp === 'string') {$(ind).addClass(cssp);} else if(cp === 'object') {$(ind).css(cssp);}
-				$(t).triggerHandler("jqGridAfterGridComplete");
-			}
-		});
-		return success;
-	},
-	addRowData : function(rowid,rdata,pos,src) {
-		if(!pos) {pos = "last";}
-		var success = false, nm, row, gi, si, ni,sind, i, v, prp="", aradd, cnm, cn, data, cm, id;
-		if(rdata) {
-			if($.isArray(rdata)) {
-				aradd=true;
-				pos = "last";
-				cnm = rowid;
-			} else {
-				rdata = [rdata];
-				aradd = false;
-			}
-			this.each(function() {
-				var t = this, datalen = rdata.length;
-				ni = t.p.rownumbers===true ? 1 :0;
-				gi = t.p.multiselect ===true ? 1 :0;
-				si = t.p.subGrid===true ? 1 :0;
-				if(!aradd) {
-					if(typeof(rowid) != 'undefined') { rowid = rowid+"";}
-					else {
-						rowid = $.jgrid.randId();
-						if(t.p.keyIndex !== false) {
-							cnm = t.p.colModel[t.p.keyIndex+gi+si+ni].name;
-							if(typeof rdata[0][cnm] != "undefined") { rowid = rdata[0][cnm]; }
-						}
-					}
-				}
-				cn = t.p.altclass;
-				var k = 0, cna ="", lcdata = {},
-				air = $.isFunction(t.p.afterInsertRow) ? true : false;
-				while(k < datalen) {
-					data = rdata[k];
-					row=[];
-					if(aradd) {
-						try {rowid = data[cnm];}
-						catch (e) {rowid = $.jgrid.randId();}
-						cna = t.p.altRows === true ?  (t.rows.length-1)%2 === 0 ? cn : "" : "";
-					}
-					id = rowid;
-					rowid  = t.p.idPrefix + rowid;
-					if(ni){
-						prp = t.formatCol(0,1,'',null,rowid, true);
-						row[row.length] = "<td role=\"gridcell\" class=\"ui-state-default jqgrid-rownum\" "+prp+">0</td>";
-					}
-					if(gi) {
-						v = "<input role=\"checkbox\" type=\"checkbox\""+" id=\"jqg_"+t.p.id+"_"+rowid+"\" class=\"cbox\"/>";
-						prp = t.formatCol(ni,1,'', null, rowid, true);
-						row[row.length] = "<td role=\"gridcell\" "+prp+">"+v+"</td>";
-					}
-					if(si) {
-						row[row.length] = $(t).jqGrid("addSubGridCell",gi+ni,1);
-					}
-					for(i = gi+si+ni; i < t.p.colModel.length;i++){
-						cm = t.p.colModel[i];
-						nm = cm.name;
-						lcdata[nm] = data[nm];
-						v = t.formatter( rowid, $.jgrid.getAccessor(data,nm), i, data );
-						prp = t.formatCol(i,1,v, data, rowid, true);
-						row[row.length] = "<td role=\"gridcell\" "+prp+">"+v+"</td>";
-					}
-					row.unshift( t.constructTr(rowid, false, cna, lcdata, lcdata ) );
-					row[row.length] = "</tr>";
-					if(t.rows.length === 0){
-						$("table:first",t.grid.bDiv).append(row.join(''));
-					} else {
-					switch (pos) {
-						case 'last':
-							$(t.rows[t.rows.length-1]).after(row.join(''));
-							sind = t.rows.length-1;
-							break;
-						case 'first':
-							$(t.rows[0]).after(row.join(''));
-							sind = 1;
-							break;
-						case 'after':
-							sind = t.rows.namedItem(src);
-							if (sind) {
-								if($(t.rows[sind.rowIndex+1]).hasClass("ui-subgrid")) { $(t.rows[sind.rowIndex+1]).after(row); }
-								else { $(sind).after(row.join('')); }
-							}
-							sind++;
-							break;
-						case 'before':
-							sind = t.rows.namedItem(src);
-							if(sind) {$(sind).before(row.join(''));sind=sind.rowIndex;}
-							sind--;
-							break;
-					}
-					}
-					if(t.p.subGrid===true) {
-						$(t).jqGrid("addSubGrid",gi+ni, sind);
-					}
-					t.p.records++;
-					t.p.reccount++;
-					$(t).triggerHandler("jqGridAfterInsertRow", [rowid,data,data]);
-					if(air) { t.p.afterInsertRow.call(t,rowid,data,data); }
-					k++;
-					if(t.p.datatype == 'local') {
-						lcdata[t.p.localReader.id] = id;
-						t.p._index[id] = t.p.data.length;
-						t.p.data.push(lcdata);
-						lcdata = {};
-					}
-				}
-				if( t.p.altRows === true && !aradd) {
-					if (pos == "last") {
-						if ((t.rows.length-1)%2 == 1)  {$(t.rows[t.rows.length-1]).addClass(cn);}
-					} else {
-						$(t.rows).each(function(i){
-							if(i % 2 ==1) { $(this).addClass(cn); }
-							else { $(this).removeClass(cn); }
-						});
-					}
-				}
-				t.updatepager(true,true);
-				success = true;
-			});
-		}
-		return success;
-	},
-	footerData : function(action,data, format) {
-		var nm, success=false, res={}, title;
-		function isEmpty(obj) {
-			for(var i in obj) {
-				if (obj.hasOwnProperty(i)) { return false; }
-			}
-			return true;
-		}
-		if(typeof(action) == "undefined") { action = "get"; }
-		if(typeof(format) != "boolean") { format  = true; }
-		action = action.toLowerCase();
-		this.each(function(){
-			var t = this, vl;
-			if(!t.grid || !t.p.footerrow) {return false;}
-			if(action == "set") { if(isEmpty(data)) { return false; } }
-			success=true;
-			$(this.p.colModel).each(function(i){
-				nm = this.name;
-				if(action == "set") {
-					if( data[nm] !== undefined) {
-						vl = format ? t.formatter( "", data[nm], i, data, 'edit') : data[nm];
-						title = this.title ? {"title":$.jgrid.stripHtml(vl)} : {};
-						$("tr.footrow td:eq("+i+")",t.grid.sDiv).html(vl).attr(title);
-						success = true;
-					}
-				} else if(action == "get") {
-					res[nm] = $("tr.footrow td:eq("+i+")",t.grid.sDiv).html();
-				}
-			});
-		});
-		return action == "get" ? res : success;
-	},
-	showHideCol : function(colname,show) {
-		return this.each(function() {
-			var $t = this, fndh=false, brd=$.jgrid.cellWidth()? 0: $t.p.cellLayout, cw;
-			if (!$t.grid ) {return;}
-			if( typeof colname === 'string') {colname=[colname];}
-			show = show != "none" ? "" : "none";
-			var sw = show === "" ? true :false,
-			gh = $t.p.groupHeader && (typeof $t.p.groupHeader === 'object' || $.isFunction($t.p.groupHeader) );
-			if(gh) { $($t).jqGrid('destroyGroupHeader', false); }
-			$(this.p.colModel).each(function(i) {
-				if ($.inArray(this.name,colname) !== -1 && this.hidden === sw) {
-					if($t.p.frozenColumns === true && this.frozen === true) {
-						return true;
-					}
-					$("tr",$t.grid.hDiv).each(function(){
-						$(this.cells[i]).css("display", show);
-					});
-					$($t.rows).each(function(){
-						if (!$(this).hasClass("jqgroup")) {
-							$(this.cells[i]).css("display", show);
-						}
-					});
-					if($t.p.footerrow) { $("tr.footrow td:eq("+i+")", $t.grid.sDiv).css("display", show); }
-					cw =  parseInt(this.width,10);
-					if(show === "none") {
-						$t.p.tblwidth -= cw+brd;
-					} else {
-						$t.p.tblwidth += cw+brd;
-					}
-					this.hidden = !sw;
-					fndh=true;
-					$($t).triggerHandler("jqGridShowHideCol", [sw,this.name,i]);
-				}
-			});
-			if(fndh===true) {
-				if($t.p.shrinkToFit === true && !isNaN($t.p.height)) { $t.p.tblwidth += parseInt($t.p.scrollOffset,10);}
-				$($t).jqGrid("setGridWidth",$t.p.shrinkToFit === true ? $t.p.tblwidth : $t.p.width );
-			}
-			if( gh )  {
-				$($t).jqGrid('setGroupHeaders',$t.p.groupHeader);
-			}
-		});
-	},
-	hideCol : function (colname) {
-		return this.each(function(){$(this).jqGrid("showHideCol",colname,"none");});
-	},
-	showCol : function(colname) {
-		return this.each(function(){$(this).jqGrid("showHideCol",colname,"");});
-	},
-	remapColumns : function(permutation, updateCells, keepHeader)
-	{
-		function resortArray(a) {
-			var ac;
-			if (a.length) {
-				ac = $.makeArray(a);
-			} else {
-				ac = $.extend({}, a);
-			}
-			$.each(permutation, function(i) {
-				a[i] = ac[this];
-			});
-		}
-		var ts = this.get(0);
-		function resortRows(parent, clobj) {
-			$(">tr"+(clobj||""), parent).each(function() {
-				var row = this;
-				var elems = $.makeArray(row.cells);
-				$.each(permutation, function() {
-					var e = elems[this];
-					if (e) {
-						row.appendChild(e);
-					}
-				});
-			});
-		}
-		resortArray(ts.p.colModel);
-		resortArray(ts.p.colNames);
-		resortArray(ts.grid.headers);
-		resortRows($("thead:first", ts.grid.hDiv), keepHeader && ":not(.ui-jqgrid-labels)");
-		if (updateCells) {
-			resortRows($("#"+$.jgrid.jqID(ts.p.id)+" tbody:first"), ".jqgfirstrow, tr.jqgrow, tr.jqfoot");
-		}
-		if (ts.p.footerrow) {
-			resortRows($("tbody:first", ts.grid.sDiv));
-		}
-		if (ts.p.remapColumns) {
-			if (!ts.p.remapColumns.length){
-				ts.p.remapColumns = $.makeArray(permutation);
-			} else {
-				resortArray(ts.p.remapColumns);
-			}
-		}
-		ts.p.lastsort = $.inArray(ts.p.lastsort, permutation);
-		if(ts.p.treeGrid) { ts.p.expColInd = $.inArray(ts.p.expColInd, permutation); }
-		$(ts).triggerHandler("jqGridRemapColumns", [permutation, updateCells, keepHeader]);
-	},
-	setGridWidth : function(nwidth, shrink) {
-		return this.each(function(){
-			if (!this.grid ) {return;}
-			var $t = this, cw,
-			initwidth = 0, brd=$.jgrid.cellWidth() ? 0: $t.p.cellLayout, lvc, vc=0, hs=false, scw=$t.p.scrollOffset, aw, gw=0,
-			cl = 0,cr;
-			if(typeof shrink != 'boolean') {
-				shrink=$t.p.shrinkToFit;
-			}
-			if(isNaN(nwidth)) {return;}
-			nwidth = parseInt(nwidth,10);
-			$t.grid.width = $t.p.width = nwidth;
-			$("#gbox_"+$.jgrid.jqID($t.p.id)).css("width",nwidth+"px");
-			$("#gview_"+$.jgrid.jqID($t.p.id)).css("width",nwidth+"px");
-			$($t.grid.bDiv).css("width",nwidth+"px");
-			$($t.grid.hDiv).css("width",nwidth+"px");
-			if($t.p.pager ) {$($t.p.pager).css("width",nwidth+"px");}
-			if($t.p.toppager ) {$($t.p.toppager).css("width",nwidth+"px");}
-			if($t.p.toolbar[0] === true){
-				$($t.grid.uDiv).css("width",nwidth+"px");
-				if($t.p.toolbar[1]=="both") {$($t.grid.ubDiv).css("width",nwidth+"px");}
-			}
-			if($t.p.footerrow) { $($t.grid.sDiv).css("width",nwidth+"px"); }
-			if(shrink ===false && $t.p.forceFit === true) {$t.p.forceFit=false;}
-			if(shrink===true) {
-				$.each($t.p.colModel, function() {
-					if(this.hidden===false){
-						cw = this.widthOrg;
-						initwidth += cw+brd;
-						if(this.fixed) {
-							gw += cw+brd;
-						} else {
-							vc++;
-						}
-						cl++;
-					}
-				});
-				if(vc  === 0) { return; }
-				$t.p.tblwidth = initwidth;
-				aw = nwidth-brd*vc-gw;
-				if(!isNaN($t.p.height)) {
-					if($($t.grid.bDiv)[0].clientHeight < $($t.grid.bDiv)[0].scrollHeight || $t.rows.length === 1){
-						hs = true;
-						aw -= scw;
-					}
-				}
-				initwidth =0;
-				var cle = $t.grid.cols.length >0;
-				$.each($t.p.colModel, function(i) {
-					if(this.hidden === false && !this.fixed){
-						cw = this.widthOrg;
-						cw = Math.round(aw*cw/($t.p.tblwidth-brd*vc-gw));
-						if (cw < 0) { return; }
-						this.width =cw;
-						initwidth += cw;
-						$t.grid.headers[i].width=cw;
-						$t.grid.headers[i].el.style.width=cw+"px";
-						if($t.p.footerrow) { $t.grid.footers[i].style.width = cw+"px"; }
-						if(cle) { $t.grid.cols[i].style.width = cw+"px"; }
-						lvc = i;
-					}
-				});
-
-				if (!lvc) { return; }
-
-				cr =0;
-				if (hs) {
-					if(nwidth-gw-(initwidth+brd*vc) !== scw){
-						cr = nwidth-gw-(initwidth+brd*vc)-scw;
-					}
-				} else if( Math.abs(nwidth-gw-(initwidth+brd*vc)) !== 1) {
-					cr = nwidth-gw-(initwidth+brd*vc);
-				}
-				$t.p.colModel[lvc].width += cr;
-				$t.p.tblwidth = initwidth+cr+brd*vc+gw;
-				if($t.p.tblwidth > nwidth) {
-					var delta = $t.p.tblwidth - parseInt(nwidth,10);
-					$t.p.tblwidth = nwidth;
-					cw = $t.p.colModel[lvc].width = $t.p.colModel[lvc].width-delta;
-				} else {
-					cw= $t.p.colModel[lvc].width;
-				}
-				$t.grid.headers[lvc].width = cw;
-				$t.grid.headers[lvc].el.style.width=cw+"px";
-				if(cle) { $t.grid.cols[lvc].style.width = cw+"px"; }
-				if($t.p.footerrow) {
-					$t.grid.footers[lvc].style.width = cw+"px";
-				}
-			}
-			if($t.p.tblwidth) {
-				$('table:first',$t.grid.bDiv).css("width",$t.p.tblwidth+"px");
-				$('table:first',$t.grid.hDiv).css("width",$t.p.tblwidth+"px");
-				$t.grid.hDiv.scrollLeft = $t.grid.bDiv.scrollLeft;
-				if($t.p.footerrow) {
-					$('table:first',$t.grid.sDiv).css("width",$t.p.tblwidth+"px");
-				}
-			}
-		});
-	},
-	setGridHeight : function (nh) {
-		return this.each(function (){
-			var $t = this;
-			if(!$t.grid) {return;}
-			var bDiv = $($t.grid.bDiv);
-			bDiv.css({height: nh+(isNaN(nh)?"":"px")});
-			if($t.p.frozenColumns === true){
-				//follow the original set height to use 16, better scrollbar width detection
-				$('#'+$.jgrid.jqID($t.p.id)+"_frozen").parent().height(bDiv.height() - 16);
-			}
-			$t.p.height = nh;
-			if ($t.p.scroll) { $t.grid.populateVisible(); }
-		});
-	},
-	setCaption : function (newcap){
-		return this.each(function(){
-			this.p.caption=newcap;
-			$("span.ui-jqgrid-title, span.ui-jqgrid-title-rtl",this.grid.cDiv).html(newcap);
-			$(this.grid.cDiv).show();
-		});
-	},
-	setLabel : function(colname, nData, prop, attrp ){
-		return this.each(function(){
-			var $t = this, pos=-1;
-			if(!$t.grid) {return;}
-			if(typeof(colname) != "undefined") {
-				$($t.p.colModel).each(function(i){
-					if (this.name == colname) {
-						pos = i;return false;
-					}
-				});
-			} else { return; }
-			if(pos>=0) {
-				var thecol = $("tr.ui-jqgrid-labels th:eq("+pos+")",$t.grid.hDiv);
-				if (nData){
-					var ico = $(".s-ico",thecol);
-					$("[id^=jqgh_]",thecol).empty().html(nData).append(ico);
-					$t.p.colNames[pos] = nData;
-				}
-				if (prop) {
-					if(typeof prop === 'string') {$(thecol).addClass(prop);} else {$(thecol).css(prop);}
-				}
-				if(typeof attrp === 'object') {$(thecol).attr(attrp);}
-			}
-		});
-	},
-	setCell : function(rowid,colname,nData,cssp,attrp, forceupd) {
-		return this.each(function(){
-			var $t = this, pos =-1,v, title;
-			if(!$t.grid) {return;}
-			if(isNaN(colname)) {
-				$($t.p.colModel).each(function(i){
-					if (this.name == colname) {
-						pos = i;return false;
-					}
-				});
-			} else {pos = parseInt(colname,10);}
-			if(pos>=0) {
-				var ind = $t.rows.namedItem(rowid);
-				if (ind){
-					var tcell = $("td:eq("+pos+")",ind);
-					if(nData !== "" || forceupd === true) {
-						v = $t.formatter(rowid, nData, pos,ind,'edit');
-						title = $t.p.colModel[pos].title ? {"title":$.jgrid.stripHtml(v)} : {};
-						if($t.p.treeGrid && $(".tree-wrap",$(tcell)).length>0) {
-							$("span",$(tcell)).html(v).attr(title);
-						} else {
-							$(tcell).html(v).attr(title);
-						}
-						if($t.p.datatype == "local") {
-							var cm = $t.p.colModel[pos], index;
-							nData = cm.formatter && typeof(cm.formatter) === 'string' && cm.formatter == 'date' ? $.unformat.date.call($t,nData,cm) : nData;
-							index = $t.p._index[rowid];
-							if(typeof index  != "undefined") {
-								$t.p.data[index][cm.name] = nData;
-							}
-						}
-					}
-					if(typeof cssp === 'string'){
-						$(tcell).addClass(cssp);
-					} else if(cssp) {
-						$(tcell).css(cssp);
-					}
-					if(typeof attrp === 'object') {$(tcell).attr(attrp);}
-				}
-			}
-		});
-	},
-	getCell : function(rowid,col) {
-		var ret = false;
-		this.each(function(){
-			var $t=this, pos=-1;
-			if(!$t.grid) {return;}
-			if(isNaN(col)) {
-				$($t.p.colModel).each(function(i){
-					if (this.name === col) {
-						pos = i;return false;
-					}
-				});
-			} else {pos = parseInt(col,10);}
-			if(pos>=0) {
-				var ind = $t.rows.namedItem(rowid);
-				if(ind) {
-					try {
-						ret = $.unformat.call($t,$("td:eq("+pos+")",ind),{rowId:ind.id, colModel:$t.p.colModel[pos]},pos);
-					} catch (e){
-						ret = $.jgrid.htmlDecode($("td:eq("+pos+")",ind).html());
-					}
-				}
-			}
-		});
-		return ret;
-	},
-	getCol : function (col, obj, mathopr) {
-		var ret = [], val, sum=0, min, max, v;
-		obj = typeof (obj) != 'boolean' ? false : obj;
-		if(typeof mathopr == 'undefined') { mathopr = false; }
-		this.each(function(){
-			var $t=this, pos=-1;
-			if(!$t.grid) {return;}
-			if(isNaN(col)) {
-				$($t.p.colModel).each(function(i){
-					if (this.name === col) {
-						pos = i;return false;
-					}
-				});
-			} else {pos = parseInt(col,10);}
-			if(pos>=0) {
-				var ln = $t.rows.length, i =0;
-				if (ln && ln>0){
-					while(i<ln){
-						if($($t.rows[i]).hasClass('jqgrow')) {
-							try {
-								val = $.unformat.call($t,$($t.rows[i].cells[pos]),{rowId:$t.rows[i].id, colModel:$t.p.colModel[pos]},pos);
-							} catch (e) {
-								val = $.jgrid.htmlDecode($t.rows[i].cells[pos].innerHTML);
-							}
-							if(mathopr) {
-								v = parseFloat(val);
-								sum += v;
-								if(i===0) {
-									min = v;
-									max = v;
-								} else {
-									min = Math.min(min, v);
-									max = Math.max(max, v);
-								}
-							}
-							else if(obj) { ret.push( {id:$t.rows[i].id,value:val} ); }
-							else { ret.push( val ); }
-						}
-						i++;
-					}
-					if(mathopr) {
-						switch(mathopr.toLowerCase()){
-							case 'sum': ret =sum; break;
-							case 'avg': ret = sum/ln; break;
-							case 'count': ret = ln; break;
-							case 'min': ret = min; break;
-							case 'max': ret = max; break;
-						}
-					}
-				}
-			}
-		});
-		return ret;
-	},
-	clearGridData : function(clearfooter) {
-		return this.each(function(){
-			var $t = this;
-			if(!$t.grid) {return;}
-			if(typeof clearfooter != 'boolean') { clearfooter = false; }
-			if($t.p.deepempty) {$("#"+$.jgrid.jqID($t.p.id)+" tbody:first tr:gt(0)").remove();}
-			else {
-				var trf = $("#"+$.jgrid.jqID($t.p.id)+" tbody:first tr:first")[0];
-				$("#"+$.jgrid.jqID($t.p.id)+" tbody:first").empty().append(trf);
-			}
-			if($t.p.footerrow && clearfooter) { $(".ui-jqgrid-ftable td",$t.grid.sDiv).html("&#160;"); }
-			$t.p.selrow = null; $t.p.selarrrow= []; $t.p.savedRow = [];
-			$t.p.records = 0;$t.p.page=1;$t.p.lastpage=0;$t.p.reccount=0;
-			$t.p.data = []; $t.p._index = {};
-			$t.updatepager(true,false);
-		});
-	},
-	getInd : function(rowid,rc){
-		var ret =false,rw;
-		this.each(function(){
-			rw = this.rows.namedItem(rowid);
-			if(rw) {
-				ret = rc===true ? rw: rw.rowIndex;
-			}
-		});
-		return ret;
-	},
-	bindKeys : function( settings ){
-		var o = $.extend({
-			onEnter: null,
-			onSpace: null,
-			onLeftKey: null,
-			onRightKey: null,
-			scrollingRows : true
-		},settings || {});
-		return this.each(function(){
-			var $t = this;
-			if( !$('body').is('[role]') ){$('body').attr('role','application');}
-			$t.p.scrollrows = o.scrollingRows;
-			$($t).keydown(function(event){
-				var target = $($t).find('tr[tabindex=0]')[0], id, r, mind,
-				expanded = $t.p.treeReader.expanded_field;
-				//check for arrow keys
-				if(target) {
-					mind = $t.p._index[target.id];
-					if(event.keyCode === 37 || event.keyCode === 38 || event.keyCode === 39 || event.keyCode === 40){
-						// up key
-						if(event.keyCode === 38 ){
-							r = target.previousSibling;
-							id = "";
-							if(r) {
-								if($(r).is(":hidden")) {
-									while(r) {
-										r = r.previousSibling;
-										if(!$(r).is(":hidden") && $(r).hasClass('jqgrow')) {id = r.id;break;}
-									}
-								} else {
-									id = r.id;
-								}
-							}
-							$($t).jqGrid('setSelection', id, true, event);
-						}
-						//if key is down arrow
-						if(event.keyCode === 40){
-							r = target.nextSibling;
-							id ="";
-							if(r) {
-								if($(r).is(":hidden")) {
-									while(r) {
-										r = r.nextSibling;
-										if(!$(r).is(":hidden") && $(r).hasClass('jqgrow') ) {id = r.id;break;}
-									}
-								} else {
-									id = r.id;
-								}
-							}
-							$($t).jqGrid('setSelection', id, true, event);
-						}
-						// left
-						if(event.keyCode === 37 ){
-							if($t.p.treeGrid && $t.p.data[mind][expanded]) {
-								$(target).find("div.treeclick").trigger('click');
-							}
-							$($t).triggerHandler("jqGridKeyLeft", [$t.p.selrow]);
-							if($.isFunction(o.onLeftKey)) {
-								o.onLeftKey.call($t, $t.p.selrow);
-							}
-						}
-						// right
-						if(event.keyCode === 39 ){
-							if($t.p.treeGrid && !$t.p.data[mind][expanded]) {
-								$(target).find("div.treeclick").trigger('click');
-							}
-							$($t).triggerHandler("jqGridKeyRight", [$t.p.selrow]);
-							if($.isFunction(o.onRightKey)) {
-								o.onRightKey.call($t, $t.p.selrow);
-							}
-						}
-					}
-					//check if enter was pressed on a grid or treegrid node
-					else if( event.keyCode === 13 ){
-						$($t).triggerHandler("jqGridKeyEnter", [$t.p.selrow]);
-						if($.isFunction(o.onEnter)) {
-							o.onEnter.call($t, $t.p.selrow);
-						}
-					} else if(event.keyCode === 32) {
-						$($t).triggerHandler("jqGridKeySpace", [$t.p.selrow]);
-						if($.isFunction(o.onSpace)) {
-							o.onSpace.call($t, $t.p.selrow);
-						}
-					}
-				}
-			});
-		});
-	},
-	unbindKeys : function(){
-		return this.each(function(){
-			$(this).unbind('keydown');
-		});
-	},
-	getLocalRow : function (rowid) {
-		var ret = false, ind;
-		this.each(function(){
-			if(typeof(rowid) !== "undefined") {
-				ind = this.p._index[rowid];
-				if(ind >= 0 ) {
-					ret = this.p.data[ind];
-				}
-			}
-		});
-		return ret;
-	}
-});
+/*
+ **
+ * formatter for values but most of the values if for jqGrid
+ * Some of this was inspired and based on how YUI does the table datagrid but in jQuery fashion
+ * we are trying to keep it as light as possible
+ * Joshua Burnett josh@9ci.com
+ * http://www.greenbill.com
+ *
+ * Changes from Tony Tomov tony@trirand.com
+ * Dual licensed under the MIT and GPL licenses:
+ * http://www.opensource.org/licenses/mit-license.php
+ * http://www.gnu.org/licenses/gpl-2.0.html
+ *
+ **/
+
+;
+(function ($) {
+    "use strict";
+    $.fmatter = {};
+    //opts can be id:row id for the row, rowdata:the data for the row, colmodel:the column model for this column
+    //example {id:1234,}
+    $.extend($.fmatter, {
+        isBoolean: function (o) {
+            return typeof o === 'boolean';
+        },
+        isObject: function (o) {
+            return (o && (typeof o === 'object' || $.isFunction(o))) || false;
+        },
+        isString: function (o) {
+            return typeof o === 'string';
+        },
+        isNumber: function (o) {
+            return typeof o === 'number' && isFinite(o);
+        },
+        isNull: function (o) {
+            return o === null;
+        },
+        isUndefined: function (o) {
+            return typeof o === 'undefined';
+        },
+        isValue: function (o) {
+            return (this.isObject(o) || this.isString(o) || this.isNumber(o) || this.isBoolean(o));
+        },
+        isEmpty: function (o) {
+            if (!this.isString(o) && this.isValue(o)) {
+                return false;
+            } else if (!this.isValue(o)) {
+                return true;
+            }
+            o = $.trim(o).replace(/\&nbsp\;/ig, '').replace(/\&#160\;/ig, '');
+            return o === "";
+        }
+    });
+    $.fn.fmatter = function (formatType, cellval, opts, rwd, act) {
+        // build main options before element iteration
+        var v = cellval;
+        opts = $.extend({}, $.jgrid.formatter, opts);
+
+        try {
+            v = $.fn.fmatter[formatType].call(this, cellval, opts, rwd, act);
+        } catch (fe) {
+        }
+        return v;
+    };
+    $.fmatter.util = {
+        // Taken from YAHOO utils
+        NumberFormat: function (nData, opts) {
+            if (!$.fmatter.isNumber(nData)) {
+                nData *= 1;
+            }
+            if ($.fmatter.isNumber(nData)) {
+                var bNegative = (nData < 0);
+                var sOutput = nData + "";
+                var sDecimalSeparator = (opts.decimalSeparator) ? opts.decimalSeparator : ".";
+                var nDotIndex;
+                if ($.fmatter.isNumber(opts.decimalPlaces)) {
+                    // Round to the correct decimal place
+                    var nDecimalPlaces = opts.decimalPlaces;
+                    var nDecimal = Math.pow(10, nDecimalPlaces);
+                    sOutput = Math.round(nData * nDecimal) / nDecimal + "";
+                    nDotIndex = sOutput.lastIndexOf(".");
+                    if (nDecimalPlaces > 0) {
+                        // Add the decimal separator
+                        if (nDotIndex < 0) {
+                            sOutput += sDecimalSeparator;
+                            nDotIndex = sOutput.length - 1;
+                        }
+                        // Replace the "."
+                        else if (sDecimalSeparator !== ".") {
+                            sOutput = sOutput.replace(".", sDecimalSeparator);
+                        }
+                        // Add missing zeros
+                        while ((sOutput.length - 1 - nDotIndex) < nDecimalPlaces) {
+                            sOutput += "0";
+                        }
+                    }
+                }
+                if (opts.thousandsSeparator) {
+                    var sThousandsSeparator = opts.thousandsSeparator;
+                    nDotIndex = sOutput.lastIndexOf(sDecimalSeparator);
+                    nDotIndex = (nDotIndex > -1) ? nDotIndex : sOutput.length;
+                    var sNewOutput = sOutput.substring(nDotIndex);
+                    var nCount = -1;
+                    for (var i = nDotIndex; i > 0; i--) {
+                        nCount++;
+                        if ((nCount % 3 === 0) && (i !== nDotIndex) && (!bNegative || (i > 1))) {
+                            sNewOutput = sThousandsSeparator + sNewOutput;
+                        }
+                        sNewOutput = sOutput.charAt(i - 1) + sNewOutput;
+                    }
+                    sOutput = sNewOutput;
+                }
+                // Prepend prefix
+                sOutput = (opts.prefix) ? opts.prefix + sOutput : sOutput;
+                // Append suffix
+                sOutput = (opts.suffix) ? sOutput + opts.suffix : sOutput;
+                return sOutput;
+
+            } else {
+                return nData;
+            }
+        },
+        // Tony Tomov
+        // PHP implementation. Sorry not all options are supported.
+        // Feel free to add them if you want
+        DateFormat: function (format, date, newformat, opts) {
+            var token = /\\.|[dDjlNSwzWFmMntLoYyaABgGhHisueIOPTZcrU]/g,
+                timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
+                timezoneClip = /[^-+\dA-Z]/g,
+                msDateRegExp = new RegExp("^\/Date\\((([-+])?[0-9]+)(([-+])([0-9]{2})([0-9]{2}))?\\)\/$"),
+                msMatch = ((typeof date === 'string') ? date.match(msDateRegExp) : null),
+                pad = function (value, length) {
+                    value = String(value);
+                    length = parseInt(length, 10) || 2;
+                    while (value.length < length) {
+                        value = '0' + value;
+                    }
+                    return value;
+                },
+                ts = {m: 1, d: 1, y: 1970, h: 0, i: 0, s: 0, u: 0},
+                timestamp = 0, dM, k, hl,
+                dateFormat = ["i18n"];
+            // Internationalization strings
+            dateFormat.i18n = {
+                dayNames: opts.dayNames,
+                monthNames: opts.monthNames
+            };
+            if (format in opts.masks) {
+                format = opts.masks[format];
+            }
+            if (!isNaN(date - 0) && String(format).toLowerCase() == "u") {
+                //Unix timestamp
+                timestamp = new Date(parseFloat(date) * 1000);
+            } else if (date.constructor === Date) {
+                timestamp = date;
+                // Microsoft date format support
+            } else if (msMatch !== null) {
+                timestamp = new Date(parseInt(msMatch[1], 10));
+                if (msMatch[3]) {
+                    var offset = Number(msMatch[5]) * 60 + Number(msMatch[6]);
+                    offset *= ((msMatch[4] == '-') ? 1 : -1);
+                    offset -= timestamp.getTimezoneOffset();
+                    timestamp.setTime(Number(Number(timestamp) + (offset * 60 * 1000)));
+                }
+            } else {
+                date = String(date).split(/[\\\/:_;.,\t\T\s-]/);
+                format = format.split(/[\\\/:_;.,\t\T\s-]/);
+                // parsing for month names
+                for (k = 0, hl = format.length; k < hl; k++) {
+                    if (format[k] == 'M') {
+                        dM = $.inArray(date[k], dateFormat.i18n.monthNames);
+                        if (dM !== -1 && dM < 12) {
+                            date[k] = dM + 1;
+                        }
+                    }
+                    if (format[k] == 'F') {
+                        dM = $.inArray(date[k], dateFormat.i18n.monthNames);
+                        if (dM !== -1 && dM > 11) {
+                            date[k] = dM + 1 - 12;
+                        }
+                    }
+                    if (date[k]) {
+                        ts[format[k].toLowerCase()] = parseInt(date[k], 10);
+                    }
+                }
+                if (ts.f) {
+                    ts.m = ts.f;
+                }
+                if (ts.m === 0 && ts.y === 0 && ts.d === 0) {
+                    return "&#160;";
+                }
+                ts.m = parseInt(ts.m, 10) - 1;
+                var ty = ts.y;
+                if (ty >= 70 && ty <= 99) {
+                    ts.y = 1900 + ts.y;
+                }
+                else if (ty >= 0 && ty <= 69) {
+                    ts.y = 2000 + ts.y;
+                }
+                timestamp = new Date(ts.y, ts.m, ts.d, ts.h, ts.i, ts.s, ts.u);
+            }
+
+            if (newformat in opts.masks) {
+                newformat = opts.masks[newformat];
+            } else if (!newformat) {
+                newformat = 'Y-m-d';
+            }
+            var
+                G = timestamp.getHours(),
+                i = timestamp.getMinutes(),
+                j = timestamp.getDate(),
+                n = timestamp.getMonth() + 1,
+                o = timestamp.getTimezoneOffset(),
+                s = timestamp.getSeconds(),
+                u = timestamp.getMilliseconds(),
+                w = timestamp.getDay(),
+                Y = timestamp.getFullYear(),
+                N = (w + 6) % 7 + 1,
+                z = (new Date(Y, n - 1, j) - new Date(Y, 0, 1)) / 86400000,
+                flags = {
+                    // Day
+                    d: pad(j),
+                    D: dateFormat.i18n.dayNames[w],
+                    j: j,
+                    l: dateFormat.i18n.dayNames[w + 7],
+                    N: N,
+                    S: opts.S(j),
+                    //j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th',
+                    w: w,
+                    z: z,
+                    // Week
+                    W: N < 5 ? Math.floor((z + N - 1) / 7) + 1 : Math.floor((z + N - 1) / 7) || ((new Date(Y - 1, 0, 1).getDay() + 6) % 7 < 4 ? 53 : 52),
+                    // Month
+                    F: dateFormat.i18n.monthNames[n - 1 + 12],
+                    m: pad(n),
+                    M: dateFormat.i18n.monthNames[n - 1],
+                    n: n,
+                    t: '?',
+                    // Year
+                    L: '?',
+                    o: '?',
+                    Y: Y,
+                    y: String(Y).substring(2),
+                    // Time
+                    a: G < 12 ? opts.AmPm[0] : opts.AmPm[1],
+                    A: G < 12 ? opts.AmPm[2] : opts.AmPm[3],
+                    B: '?',
+                    g: G % 12 || 12,
+                    G: G,
+                    h: pad(G % 12 || 12),
+                    H: pad(G),
+                    i: pad(i),
+                    s: pad(s),
+                    u: u,
+                    // Timezone
+                    e: '?',
+                    I: '?',
+                    O: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
+                    P: '?',
+                    T: (String(timestamp).match(timezone) || [""]).pop().replace(timezoneClip, ""),
+                    Z: '?',
+                    // Full Date/Time
+                    c: '?',
+                    r: '?',
+                    U: Math.floor(timestamp / 1000)
+                };
+            return newformat.replace(token, function ($0) {
+                return $0 in flags ? flags[$0] : $0.substring(1);
+            });
+        }
+    };
+    $.fn.fmatter.defaultFormat = function (cellval, opts) {
+        return ($.fmatter.isValue(cellval) && cellval !== "" ) ? cellval : opts.defaultValue ? opts.defaultValue : "&#160;";
+    };
+    $.fn.fmatter.email = function (cellval, opts) {
+        if (!$.fmatter.isEmpty(cellval)) {
+            return "<a href=\"mailto:" + cellval + "\">" + cellval + "</a>";
+        } else {
+            return $.fn.fmatter.defaultFormat(cellval, opts);
+        }
+    };
+    $.fn.fmatter.checkbox = function (cval, opts) {
+        var op = $.extend({}, opts.checkbox), ds;
+        if (opts.colModel !== undefined && !$.fmatter.isUndefined(opts.colModel.formatoptions)) {
+            op = $.extend({}, op, opts.colModel.formatoptions);
+        }
+        if (op.disabled === true) {
+            ds = "disabled=\"disabled\"";
+        } else {
+            ds = "";
+        }
+        if ($.fmatter.isEmpty(cval) || $.fmatter.isUndefined(cval)) {
+            cval = $.fn.fmatter.defaultFormat(cval, op);
+        }
+        cval = cval + "";
+        cval = cval.toLowerCase();
+        var bchk = cval.search(/(false|0|no|off)/i) < 0 ? " checked='checked' " : "";
+        return "<input type=\"checkbox\" " + bchk + " value=\"" + cval + "\" offval=\"no\" " + ds + "/>";
+    };
+    $.fn.fmatter.link = function (cellval, opts) {
+        var op = {target: opts.target};
+        var target = "";
+        if (opts.colModel !== undefined && !$.fmatter.isUndefined(opts.colModel.formatoptions)) {
+            op = $.extend({}, op, opts.colModel.formatoptions);
+        }
+        if (op.target) {
+            target = 'target=' + op.target;
+        }
+        if (!$.fmatter.isEmpty(cellval)) {
+            return "<a " + target + " href=\"" + cellval + "\">" + cellval + "</a>";
+        } else {
+            return $.fn.fmatter.defaultFormat(cellval, opts);
+        }
+    };
+    $.fn.fmatter.showlink = function (cellval, opts) {
+        var op = {baseLinkUrl: opts.baseLinkUrl, showAction: opts.showAction, addParam: opts.addParam || "", target: opts.target, idName: opts.idName},
+            target = "", idUrl;
+        if (opts.colModel !== undefined && !$.fmatter.isUndefined(opts.colModel.formatoptions)) {
+            op = $.extend({}, op, opts.colModel.formatoptions);
+        }
+        if (op.target) {
+            target = 'target=' + op.target;
+        }
+        idUrl = op.baseLinkUrl + op.showAction + '?' + op.idName + '=' + opts.rowId + op.addParam;
+        if ($.fmatter.isString(cellval) || $.fmatter.isNumber(cellval)) {	//add this one even if its blank string
+            return "<a " + target + " href=\"" + idUrl + "\">" + cellval + "</a>";
+        } else {
+            return $.fn.fmatter.defaultFormat(cellval, opts);
+        }
+    };
+    $.fn.fmatter.integer = function (cellval, opts) {
+        var op = $.extend({}, opts.integer);
+        if (opts.colModel !== undefined && !$.fmatter.isUndefined(opts.colModel.formatoptions)) {
+            op = $.extend({}, op, opts.colModel.formatoptions);
+        }
+        if ($.fmatter.isEmpty(cellval)) {
+            return op.defaultValue;
+        }
+        return $.fmatter.util.NumberFormat(cellval, op);
+    };
+    $.fn.fmatter.number = function (cellval, opts) {
+        var op = $.extend({}, opts.number);
+        if (opts.colModel !== undefined && !$.fmatter.isUndefined(opts.colModel.formatoptions)) {
+            op = $.extend({}, op, opts.colModel.formatoptions);
+        }
+        if ($.fmatter.isEmpty(cellval)) {
+            return op.defaultValue;
+        }
+        return $.fmatter.util.NumberFormat(cellval, op);
+    };
+    $.fn.fmatter.currency = function (cellval, opts) {
+        var op = $.extend({}, opts.currency);
+        if (opts.colModel !== undefined && !$.fmatter.isUndefined(opts.colModel.formatoptions)) {
+            op = $.extend({}, op, opts.colModel.formatoptions);
+        }
+        if ($.fmatter.isEmpty(cellval)) {
+            return op.defaultValue;
+        }
+        return $.fmatter.util.NumberFormat(cellval, op);
+    };
+    $.fn.fmatter.date = function (cellval, opts, rwd, act) {
+        var op = $.extend({}, opts.date);
+        if (opts.colModel !== undefined && !$.fmatter.isUndefined(opts.colModel.formatoptions)) {
+            op = $.extend({}, op, opts.colModel.formatoptions);
+        }
+        if (!op.reformatAfterEdit && act == 'edit') {
+            return $.fn.fmatter.defaultFormat(cellval, opts);
+        } else if (!$.fmatter.isEmpty(cellval)) {
+            return  $.fmatter.util.DateFormat(op.srcformat, cellval, op.newformat, op);
+        } else {
+            return $.fn.fmatter.defaultFormat(cellval, opts);
+        }
+    };
+    $.fn.fmatter.select = function (cellval, opts) {
+        // jqGrid specific
+        cellval = cellval + "";
+        var oSelect = false, ret = [], sep, delim;
+        if (!$.fmatter.isUndefined(opts.colModel.formatoptions)) {
+            oSelect = opts.colModel.formatoptions.value;
+            sep = opts.colModel.formatoptions.separator === undefined ? ":" : opts.colModel.formatoptions.separator;
+            delim = opts.colModel.formatoptions.delimiter === undefined ? ";" : opts.colModel.formatoptions.delimiter;
+        } else if (!$.fmatter.isUndefined(opts.colModel.editoptions)) {
+            oSelect = opts.colModel.editoptions.value;
+            sep = opts.colModel.editoptions.separator === undefined ? ":" : opts.colModel.editoptions.separator;
+            delim = opts.colModel.editoptions.delimiter === undefined ? ";" : opts.colModel.editoptions.delimiter;
+        }
+        if (oSelect) {
+            var msl = opts.colModel.editoptions.multiple === true ? true : false,
+                scell = [], sv;
+            if (msl) {
+                scell = cellval.split(",");
+                scell = $.map(scell, function (n) {
+                    return $.trim(n);
+                });
+            }
+            if ($.fmatter.isString(oSelect)) {
+                // mybe here we can use some caching with care ????
+                var so = oSelect.split(delim), j = 0;
+                for (var i = 0; i < so.length; i++) {
+                    sv = so[i].split(sep);
+                    if (sv.length > 2) {
+                        sv[1] = $.map(sv,function (n, i) {
+                            if (i > 0) {
+                                return n;
+                            }
+                        }).join(sep);
+                    }
+                    if (msl) {
+                        if ($.inArray(sv[0], scell) > -1) {
+                            ret[j] = sv[1];
+                            j++;
+                        }
+                    } else if ($.trim(sv[0]) == $.trim(cellval)) {
+                        ret[0] = sv[1];
+                        break;
+                    }
+                }
+            } else if ($.fmatter.isObject(oSelect)) {
+                // this is quicker
+                if (msl) {
+                    ret = $.map(scell, function (n) {
+                        return oSelect[n];
+                    });
+                } else {
+                    ret[0] = oSelect[cellval] || "";
+                }
+            }
+        }
+        cellval = ret.join(", ");
+        return  cellval === "" ? $.fn.fmatter.defaultFormat(cellval, opts) : cellval;
+    };
+    $.fn.fmatter.rowactions = function (rid, gid, act, pos) {
+        var op = {
+            keys: false,
+            onEdit: null,
+            onSuccess: null,
+            afterSave: null,
+            onError: null,
+            afterRestore: null,
+            extraparam: {},
+            url: null,
+            restoreAfterError: true,
+            mtype: "POST",
+            delOptions: {},
+            editOptions: {}
+        };
+        rid = $.jgrid.jqID(rid);
+        gid = $.jgrid.jqID(gid);
+        var cm = $('#' + gid)[0].p.colModel[pos];
+        if (!$.fmatter.isUndefined(cm.formatoptions)) {
+            op = $.extend(op, cm.formatoptions);
+        }
+        if (!$.fmatter.isUndefined($('#' + gid)[0].p.editOptions)) {
+            op.editOptions = $('#' + gid)[0].p.editOptions;
+        }
+        if (!$.fmatter.isUndefined($('#' + gid)[0].p.delOptions)) {
+            op.delOptions = $('#' + gid)[0].p.delOptions;
+        }
+        var $t = $("#" + gid)[0];
+        var saverow = function (rowid, res) {
+                if ($.isFunction(op.afterSave)) {
+                    op.afterSave.call($t, rowid, res);
+                }
+                $("tr#" + rid + " div.ui-inline-edit, " + "tr#" + rid + " div.ui-inline-del", "#" + gid + ".ui-jqgrid-btable:first").show();
+                $("tr#" + rid + " div.ui-inline-save, " + "tr#" + rid + " div.ui-inline-cancel", "#" + gid + ".ui-jqgrid-btable:first").hide();
+            },
+            restorerow = function (rowid) {
+                if ($.isFunction(op.afterRestore)) {
+                    op.afterRestore.call($t, rowid);
+                }
+                $("tr#" + rid + " div.ui-inline-edit, " + "tr#" + rid + " div.ui-inline-del", "#" + gid + ".ui-jqgrid-btable:first").show();
+                $("tr#" + rid + " div.ui-inline-save, " + "tr#" + rid + " div.ui-inline-cancel", "#" + gid + ".ui-jqgrid-btable:first").hide();
+            };
+        if ($("#" + rid, "#" + gid).hasClass("jqgrid-new-row")) {
+            var opers = $t.p.prmNames,
+                oper = opers.oper;
+            op.extraparam[oper] = opers.addoper;
+        }
+        var actop = {
+            keys: op.keys,
+            oneditfunc: op.onEdit,
+            successfunc: op.onSuccess,
+            url: op.url,
+            extraparam: op.extraparam,
+            aftersavefunc: saverow,
+            errorfunc: op.onError,
+            afterrestorefunc: restorerow,
+            restoreAfterError: op.restoreAfterError,
+            mtype: op.mtype
+        };
+        switch (act) {
+            case 'edit':
+                $('#' + gid).jqGrid('editRow', rid, actop);
+                $("tr#" + rid + " div.ui-inline-edit, " + "tr#" + rid + " div.ui-inline-del", "#" + gid + ".ui-jqgrid-btable:first").hide();
+                $("tr#" + rid + " div.ui-inline-save, " + "tr#" + rid + " div.ui-inline-cancel", "#" + gid + ".ui-jqgrid-btable:first").show();
+                $($t).triggerHandler("jqGridAfterGridComplete");
+                break;
+            case 'save':
+                if ($('#' + gid).jqGrid('saveRow', rid, actop)) {
+                    $("tr#" + rid + " div.ui-inline-edit, " + "tr#" + rid + " div.ui-inline-del", "#" + gid + ".ui-jqgrid-btable:first").show();
+                    $("tr#" + rid + " div.ui-inline-save, " + "tr#" + rid + " div.ui-inline-cancel", "#" + gid + ".ui-jqgrid-btable:first").hide();
+                    $($t).triggerHandler("jqGridAfterGridComplete");
+                }
+                break;
+            case 'cancel' :
+                $('#' + gid).jqGrid('restoreRow', rid, restorerow);
+                $("tr#" + rid + " div.ui-inline-edit, " + "tr#" + rid + " div.ui-inline-del", "#" + gid + ".ui-jqgrid-btable:first").show();
+                $("tr#" + rid + " div.ui-inline-save, " + "tr#" + rid + " div.ui-inline-cancel", "#" + gid + ".ui-jqgrid-btable:first").hide();
+                $($t).triggerHandler("jqGridAfterGridComplete");
+                break;
+            case 'del':
+                $('#' + gid).jqGrid('delGridRow', rid, op.delOptions);
+                break;
+            case 'formedit':
+                $('#' + gid).jqGrid('setSelection', rid);
+                $('#' + gid).jqGrid('editGridRow', rid, op.editOptions);
+                break;
+        }
+    };
+    $.fn.fmatter.actions = function (cellval, opts) {
+        var op = {keys: false, editbutton: true, delbutton: true, editformbutton: false};
+        if (!$.fmatter.isUndefined(opts.colModel.formatoptions)) {
+            op = $.extend(op, opts.colModel.formatoptions);
+        }
+        var rowid = opts.rowId, str = "", ocl;
+        if (typeof(rowid) == 'undefined' || $.fmatter.isEmpty(rowid)) {
+            return "";
+        }
+        if (op.editformbutton) {
+            ocl = "onclick=jQuery.fn.fmatter.rowactions('" + rowid + "','" + opts.gid + "','formedit'," + opts.pos + "); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); ";
+            str = str + "<div title='" + $.jgrid.nav.edittitle + "' style='float:left;cursor:pointer;' class='ui-pg-div ui-inline-edit' " + ocl + "><span class='ui-icon ui-icon-pencil'></span></div>";
+        } else if (op.editbutton) {
+            ocl = "onclick=jQuery.fn.fmatter.rowactions('" + rowid + "','" + opts.gid + "','edit'," + opts.pos + "); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover') ";
+            str = str + "<div title='" + $.jgrid.nav.edittitle + "' style='float:left;cursor:pointer;' class='ui-pg-div ui-inline-edit' " + ocl + "><span class='ui-icon ui-icon-pencil'></span></div>";
+        }
+        if (op.delbutton) {
+            ocl = "onclick=jQuery.fn.fmatter.rowactions('" + rowid + "','" + opts.gid + "','del'," + opts.pos + "); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); ";
+            str = str + "<div title='" + $.jgrid.nav.deltitle + "' style='float:left;margin-left:5px;' class='ui-pg-div ui-inline-del' " + ocl + "><span class='ui-icon ui-icon-trash'></span></div>";
+        }
+        ocl = "onclick=jQuery.fn.fmatter.rowactions('" + rowid + "','" + opts.gid + "','save'," + opts.pos + "); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); ";
+        str = str + "<div title='" + $.jgrid.edit.bSubmit + "' style='float:left;display:none' class='ui-pg-div ui-inline-save' " + ocl + "><span class='ui-icon ui-icon-disk'></span></div>";
+        ocl = "onclick=jQuery.fn.fmatter.rowactions('" + rowid + "','" + opts.gid + "','cancel'," + opts.pos + "); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); ";
+        str = str + "<div title='" + $.jgrid.edit.bCancel + "' style='float:left;display:none;margin-left:5px;' class='ui-pg-div ui-inline-cancel' " + ocl + "><span class='ui-icon ui-icon-cancel'></span></div>";
+        return "<div style='margin-left:8px;'>" + str + "</div>";
+    };
+    $.unformat = function (cellval, options, pos, cnt) {
+        // specific for jqGrid only
+        var ret, formatType = options.colModel.formatter,
+            op = options.colModel.formatoptions || {}, sep,
+            re = /([\.\*\_\'\(\)\{\}\+\?\\])/g,
+            unformatFunc = options.colModel.unformat || ($.fn.fmatter[formatType] && $.fn.fmatter[formatType].unformat);
+        if (typeof unformatFunc !== 'undefined' && $.isFunction(unformatFunc)) {
+            ret = unformatFunc.call(this, $(cellval).text(), options, cellval);
+        } else if (!$.fmatter.isUndefined(formatType) && $.fmatter.isString(formatType)) {
+            var opts = $.jgrid.formatter || {}, stripTag;
+            switch (formatType) {
+                case 'integer' :
+                    op = $.extend({}, opts.integer, op);
+                    sep = op.thousandsSeparator.replace(re, "\\$1");
+                    stripTag = new RegExp(sep, "g");
+                    ret = $(cellval).text().replace(stripTag, '');
+                    break;
+                case 'number' :
+                    op = $.extend({}, opts.number, op);
+                    sep = op.thousandsSeparator.replace(re, "\\$1");
+                    stripTag = new RegExp(sep, "g");
+                    ret = $(cellval).text().replace(stripTag, "").replace(op.decimalSeparator, '.');
+                    break;
+                case 'currency':
+                    op = $.extend({}, opts.currency, op);
+                    sep = op.thousandsSeparator.replace(re, "\\$1");
+                    stripTag = new RegExp(sep, "g");
+                    ret = $(cellval).text();
+                    if (op.prefix && op.prefix.length) {
+                        ret = ret.substr(op.prefix.length);
+                    }
+                    if (op.suffix && op.suffix.length) {
+                        ret = ret.substr(0, ret.length - op.suffix.length);
+                    }
+                    ret = ret.replace(stripTag, '').replace(op.decimalSeparator, '.');
+                    break;
+                case 'checkbox':
+                    var cbv = (options.colModel.editoptions) ? options.colModel.editoptions.value.split(":") : ["Yes", "No"];
+                    ret = $('input', cellval).is(":checked") ? cbv[0] : cbv[1];
+                    break;
+                case 'select' :
+                    ret = $.unformat.select(cellval, options, pos, cnt);
+                    break;
+                case 'actions':
+                    return "";
+                default:
+                    ret = $(cellval).text();
+            }
+        }
+        return ret !== undefined ? ret : cnt === true ? $(cellval).text() : $.jgrid.htmlDecode($(cellval).html());
+    };
+    $.unformat.select = function (cellval, options, pos, cnt) {
+        // Spacial case when we have local data and perform a sort
+        // cnt is set to true only in sortDataArray
+        var ret = [];
+        var cell = $(cellval).text();
+        if (cnt === true) {
+            return cell;
+        }
+        var op = $.extend({}, !$.fmatter.isUndefined(options.colModel.formatoptions) ? options.colModel.formatoptions : options.colModel.editoptions),
+            sep = op.separator === undefined ? ":" : op.separator,
+            delim = op.delimiter === undefined ? ";" : op.delimiter;
+
+        if (op.value) {
+            var oSelect = op.value,
+                msl = op.multiple === true ? true : false,
+                scell = [], sv;
+            if (msl) {
+                scell = cell.split(",");
+                scell = $.map(scell, function (n) {
+                    return $.trim(n);
+                });
+            }
+            if ($.fmatter.isString(oSelect)) {
+                var so = oSelect.split(delim), j = 0;
+                for (var i = 0; i < so.length; i++) {
+                    sv = so[i].split(sep);
+                    if (sv.length > 2) {
+                        sv[1] = $.map(sv,function (n, i) {
+                            if (i > 0) {
+                                return n;
+                            }
+                        }).join(sep);
+                    }
+                    if (msl) {
+                        if ($.inArray(sv[1], scell) > -1) {
+                            ret[j] = sv[0];
+                            j++;
+                        }
+                    } else if ($.trim(sv[1]) == $.trim(cell)) {
+                        ret[0] = sv[0];
+                        break;
+                    }
+                }
+            } else if ($.fmatter.isObject(oSelect) || $.isArray(oSelect)) {
+                if (!msl) {
+                    scell[0] = cell;
+                }
+                ret = $.map(scell, function (n) {
+                    var rv;
+                    $.each(oSelect, function (i, val) {
+                        if (val == n) {
+                            rv = i;
+                            return false;
+                        }
+                    });
+                    if (typeof(rv) != 'undefined') {
+                        return rv;
+                    }
+                });
+            }
+            return ret.join(", ");
+        } else {
+            return cell || "";
+        }
+    };
+    $.unformat.date = function (cellval, opts) {
+        var op = $.jgrid.formatter.date || {};
+        if (!$.fmatter.isUndefined(opts.formatoptions)) {
+            op = $.extend({}, op, opts.formatoptions);
+        }
+        if (!$.fmatter.isEmpty(cellval)) {
+            return $.fmatter.util.DateFormat(op.newformat, cellval, op.srcformat, op);
+        } else {
+            return $.fn.fmatter.defaultFormat(cellval, opts);
+        }
+    };
+})(jQuery);
+;
+(function ($) {
+    /*
+     * jqGrid common function
+     * Tony Tomov tony@trirand.com
+     * http://trirand.com/blog/
+     * Dual licensed under the MIT and GPL licenses:
+     * http://www.opensource.org/licenses/mit-license.php
+     * http://www.gnu.org/licenses/gpl-2.0.html
+     */
+    /*global jQuery, $ */
+
+    $.extend($.jgrid, {
+// Modal functions
+        showModal: function (h) {
+            h.w.show();
+        },
+        closeModal: function (h) {
+            h.w.hide().attr("aria-hidden", "true");
+            if (h.o) {
+                h.o.remove();
+            }
+        },
+        hideModal: function (selector, o) {
+            o = $.extend({jqm: true, gb: ''}, o || {});
+            if (o.onClose) {
+                var oncret = o.onClose(selector);
+                if (typeof oncret == 'boolean' && !oncret) {
+                    return;
+                }
+            }
+            if ($.fn.jqm && o.jqm === true) {
+                $(selector).attr("aria-hidden", "true").jqmHide();
+            } else {
+                if (o.gb !== '') {
+                    try {
+                        $(".jqgrid-overlay:first", o.gb).hide();
+                    } catch (e) {
+                    }
+                }
+                $(selector).hide().attr("aria-hidden", "true");
+            }
+        },
+//Helper functions
+        findPos: function (obj) {
+            var curleft = 0, curtop = 0;
+            if (obj.offsetParent) {
+                do {
+                    curleft += obj.offsetLeft;
+                    curtop += obj.offsetTop;
+                } while (obj = obj.offsetParent);
+                //do not change obj == obj.offsetParent
+            }
+            return [curleft, curtop];
+        },
+        createModal: function (aIDs, content, p, insertSelector, posSelector, appendsel, css) {
+            var mw = document.createElement('div'), rtlsup, self = this;
+            css = $.extend({}, css || {});
+            rtlsup = $(p.gbox).attr("dir") == "rtl" ? true : false;
+            mw.className = "ui-widget ui-widget-content ui-corner-all ui-jqdialog";
+            mw.id = aIDs.themodal;
+            var mh = document.createElement('div');
+            mh.className = "ui-jqdialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix";
+            mh.id = aIDs.modalhead;
+            $(mh).append("<span class='ui-jqdialog-title'>" + p.caption + "</span>");
+            var ahr = $("<a href='javascript:void(0)' class='ui-jqdialog-titlebar-close ui-corner-all'></a>")
+                .hover(function () {
+                    ahr.addClass('ui-state-hover');
+                },
+                function () {
+                    ahr.removeClass('ui-state-hover');
+                })
+                .append("<span class='ui-icon ui-icon-closethick'></span>");
+            $(mh).append(ahr);
+            if (rtlsup) {
+                mw.dir = "rtl";
+                $(".ui-jqdialog-title", mh).css("float", "right");
+                $(".ui-jqdialog-titlebar-close", mh).css("left", 0.3 + "em");
+            } else {
+                mw.dir = "ltr";
+                $(".ui-jqdialog-title", mh).css("float", "left");
+                $(".ui-jqdialog-titlebar-close", mh).css("right", 0.3 + "em");
+            }
+            var mc = document.createElement('div');
+            $(mc).addClass("ui-jqdialog-content ui-widget-content").attr("id", aIDs.modalcontent);
+            $(mc).append(content);
+            mw.appendChild(mc);
+            $(mw).prepend(mh);
+            if (appendsel === true) {
+                $('body').append(mw);
+            } //append as first child in body -for alert dialog
+            else if (typeof appendsel == "string")
+                $(appendsel).append(mw);
+            else {
+                $(mw).insertBefore(insertSelector);
+            }
+            $(mw).css(css);
+            if (typeof p.jqModal === 'undefined') {
+                p.jqModal = true;
+            } // internal use
+            var coord = {};
+            if ($.fn.jqm && p.jqModal === true) {
+                if (p.left === 0 && p.top === 0 && p.overlay) {
+                    var pos = [];
+                    pos = $.jgrid.findPos(posSelector);
+                    p.left = pos[0] + 4;
+                    p.top = pos[1] + 4;
+                }
+                coord.top = p.top + "px";
+                coord.left = p.left;
+            } else if (p.left !== 0 || p.top !== 0) {
+                coord.left = p.left;
+                coord.top = p.top + "px";
+            }
+            $("a.ui-jqdialog-titlebar-close", mh).click(function () {
+                var oncm = $("#" + $.jgrid.jqID(aIDs.themodal)).data("onClose") || p.onClose;
+                var gboxclose = $("#" + $.jgrid.jqID(aIDs.themodal)).data("gbox") || p.gbox;
+                self.hideModal("#" + $.jgrid.jqID(aIDs.themodal), {gb: gboxclose, jqm: p.jqModal, onClose: oncm});
+                return false;
+            });
+            if (p.width === 0 || !p.width) {
+                p.width = 300;
+            }
+            if (p.height === 0 || !p.height) {
+                p.height = 200;
+            }
+            if (!p.zIndex) {
+                var parentZ = $(insertSelector).parents("*[role=dialog]").filter(':first').css("z-index");
+                if (parentZ) {
+                    p.zIndex = parseInt(parentZ, 10) + 2;
+                } else {
+                    p.zIndex = 950;
+                }
+            }
+            var rtlt = 0;
+            if (rtlsup && coord.left && !appendsel) {
+                rtlt = $(p.gbox).width() - (!isNaN(p.width) ? parseInt(p.width, 10) : 0) - 8; // to do
+                // just in case
+                coord.left = parseInt(coord.left, 10) + parseInt(rtlt, 10);
+            }
+            if (coord.left) {
+                coord.left += "px";
+            }
+            $(mw).css($.extend({
+                    width: isNaN(p.width) ? "auto" : p.width + "px",
+                    height: isNaN(p.height) ? "auto" : p.height + "px",
+                    zIndex: p.zIndex,
+                    overflow: 'hidden'
+                }, coord))
+                .attr({tabIndex: "-1", "role": "dialog", "aria-labelledby": aIDs.modalhead, "aria-hidden": "true"});
+            if (typeof p.drag == 'undefined') {
+                p.drag = true;
+            }
+            if (typeof p.resize == 'undefined') {
+                p.resize = true;
+            }
+            if (p.drag) {
+                $(mh).css('cursor', 'move');
+                if ($.fn.jqDrag) {
+                    $(mw).jqDrag(mh);
+                } else {
+                    try {
+                        $(mw).draggable({handle: $("#" + $.jgrid.jqID(mh.id))});
+                    } catch (e) {
+                    }
+                }
+            }
+            if (p.resize) {
+                if ($.fn.jqResize) {
+                    $(mw).append("<div class='jqResize ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se ui-icon-grip-diagonal-se'></div>");
+                    $("#" + $.jgrid.jqID(aIDs.themodal)).jqResize(".jqResize", aIDs.scrollelm ? "#" + $.jgrid.jqID(aIDs.scrollelm) : false);
+                } else {
+                    try {
+                        $(mw).resizable({handles: 'se, sw', alsoResize: aIDs.scrollelm ? "#" + $.jgrid.jqID(aIDs.scrollelm) : false});
+                    } catch (r) {
+                    }
+                }
+            }
+            if (p.closeOnEscape === true) {
+                $(mw).keydown(function (e) {
+                    if (e.which == 27) {
+                        var cone = $("#" + $.jgrid.jqID(aIDs.themodal)).data("onClose") || p.onClose;
+                        self.hideModal(this, {gb: p.gbox, jqm: p.jqModal, onClose: cone});
+                    }
+                });
+            }
+        },
+        viewModal: function (selector, o) {
+            o = $.extend({
+                toTop: true,
+                overlay: 10,
+                modal: false,
+                overlayClass: 'ui-widget-overlay',
+                onShow: $.jgrid.showModal,
+                onHide: $.jgrid.closeModal,
+                gbox: '',
+                jqm: true,
+                jqM: true
+            }, o || {});
+            if ($.fn.jqm && o.jqm === true) {
+                if (o.jqM) {
+                    $(selector).attr("aria-hidden", "false").jqm(o).jqmShow();
+                }
+                else {
+                    $(selector).attr("aria-hidden", "false").jqmShow();
+                }
+            } else {
+                if (o.gbox !== '') {
+                    $(".jqgrid-overlay:first", o.gbox).show();
+                    $(selector).data("gbox", o.gbox);
+                }
+                $(selector).show().attr("aria-hidden", "false");
+                try {
+                    $(':input:visible', selector)[0].focus();
+                } catch (_) {
+                }
+            }
+        },
+
+        info_dialog: function (caption, content, c_b, modalopt) {
+            var mopt = {
+                width: 290,
+                height: 'auto',
+                dataheight: 'auto',
+                drag: true,
+                resize: false,
+                caption: "<b>" + caption + "</b>",
+                left: 250,
+                top: 170,
+                zIndex: 1000,
+                jqModal: true,
+                modal: false,
+                closeOnEscape: true,
+                align: 'center',
+                buttonalign: 'center',
+                buttons: []
+                // {text:'textbutt', id:"buttid", onClick : function(){...}}
+                // if the id is not provided we set it like info_button_+ the index in the array - i.e info_button_0,info_button_1...
+            };
+            $.extend(mopt, modalopt || {});
+            var jm = mopt.jqModal, self = this;
+            if ($.fn.jqm && !jm) {
+                jm = false;
+            }
+            // in case there is no jqModal
+            var buttstr = "";
+            if (mopt.buttons.length > 0) {
+                for (var i = 0; i < mopt.buttons.length; i++) {
+                    if (typeof mopt.buttons[i].id == "undefined") {
+                        mopt.buttons[i].id = "info_button_" + i;
+                    }
+                    buttstr += "<a href='javascript:void(0)' id='" + mopt.buttons[i].id + "' class='fm-button ui-state-default ui-corner-all'>" + mopt.buttons[i].text + "</a>";
+                }
+            }
+            var dh = isNaN(mopt.dataheight) ? mopt.dataheight : mopt.dataheight + "px",
+                cn = "text-align:" + mopt.align + ";";
+            var cnt = "<div id='info_id'>";
+            cnt += "<div id='infocnt' style='margin:0px;padding-bottom:1em;width:100%;overflow:auto;position:relative;height:" + dh + ";" + cn + "'>" + content + "</div>";
+            cnt += c_b ? "<div class='ui-widget-content ui-helper-clearfix' style='text-align:" + mopt.buttonalign + ";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'><a href='javascript:void(0)' id='closedialog' class='fm-button ui-state-default ui-corner-all'>" + c_b + "</a>" + buttstr + "</div>" :
+                buttstr !== "" ? "<div class='ui-widget-content ui-helper-clearfix' style='text-align:" + mopt.buttonalign + ";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'>" + buttstr + "</div>" : "";
+            cnt += "</div>";
+
+            try {
+                if ($("#info_dialog").attr("aria-hidden") == "false") {
+                    $.jgrid.hideModal("#info_dialog", {jqm: jm});
+                }
+                $("#info_dialog").remove();
+            } catch (e) {
+            }
+            $.jgrid.createModal({
+                    themodal: 'info_dialog',
+                    modalhead: 'info_head',
+                    modalcontent: 'info_content',
+                    scrollelm: 'infocnt'},
+                cnt,
+                mopt,
+                '', '', true
+            );
+            // attach onclick after inserting into the dom
+            if (buttstr) {
+                $.each(mopt.buttons, function (i) {
+                    $("#" + $.jgrid.jqID(this.id), "#info_id").bind('click', function () {
+                        mopt.buttons[i].onClick.call($("#info_dialog"));
+                        return false;
+                    });
+                });
+            }
+            $("#closedialog", "#info_id").click(function () {
+                self.hideModal("#info_dialog", {jqm: jm});
+                return false;
+            });
+            $(".fm-button", "#info_dialog").hover(
+                function () {
+                    $(this).addClass('ui-state-hover');
+                },
+                function () {
+                    $(this).removeClass('ui-state-hover');
+                }
+            );
+            if ($.isFunction(mopt.beforeOpen)) {
+                mopt.beforeOpen();
+            }
+            $.jgrid.viewModal("#info_dialog", {
+                onHide: function (h) {
+                    h.w.hide().remove();
+                    if (h.o) {
+                        h.o.remove();
+                    }
+                },
+                modal: mopt.modal,
+                jqm: jm
+            });
+            if ($.isFunction(mopt.afterOpen)) {
+                mopt.afterOpen();
+            }
+            try {
+                $("#info_dialog").focus();
+            } catch (m) {
+            }
+        },
+// Form Functions
+        createEl: function (eltype, options, vl, autowidth, ajaxso) {
+            var elem = "", $t = this;
+
+            function bindEv(el, opt) {
+                if ($.isFunction(opt.dataInit)) {
+                    opt.dataInit.call($t, el);
+                }
+                if (opt.dataEvents) {
+                    $.each(opt.dataEvents, function () {
+                        if (this.data !== undefined) {
+                            $(el).bind(this.type, this.data, this.fn);
+                        } else {
+                            $(el).bind(this.type, this.fn);
+                        }
+                    });
+                }
+                return opt;
+            }
+
+            function setAttributes(elm, atr, exl) {
+                var exclude = ['dataInit', 'dataEvents', 'dataUrl', 'buildSelect', 'sopt', 'searchhidden', 'defaultValue', 'attr'];
+                if (typeof(exl) != "undefined" && $.isArray(exl)) {
+                    $.merge(exclude, exl);
+                }
+                $.each(atr, function (key, value) {
+                    if ($.inArray(key, exclude) === -1) {
+                        $(elm).attr(key, value);
+                    }
+                });
+                if (!atr.hasOwnProperty('id')) {
+                    $(elm).attr('id', $.jgrid.randId());
+                }
+            }
+
+            switch (eltype) {
+                case "textarea" :
+                    elem = document.createElement("textarea");
+                    if (autowidth) {
+                        if (!options.cols) {
+                            $(elem).css({width: "98%"});
+                        }
+                    } else if (!options.cols) {
+                        options.cols = 20;
+                    }
+                    if (!options.rows) {
+                        options.rows = 2;
+                    }
+                    if (vl == '&nbsp;' || vl == '&#160;' || (vl.length == 1 && vl.charCodeAt(0) == 160)) {
+                        vl = "";
+                    }
+                    elem.value = vl;
+                    setAttributes(elem, options);
+                    options = bindEv(elem, options);
+                    $(elem).attr({"role": "textbox", "multiline": "true"});
+                    break;
+                case "checkbox" : //what code for simple checkbox
+                    elem = document.createElement("input");
+                    elem.type = "checkbox";
+                    if (!options.value) {
+                        var vl1 = vl.toLowerCase();
+                        if (vl1.search(/(false|0|no|off|undefined)/i) < 0 && vl1 !== "") {
+                            elem.checked = true;
+                            elem.defaultChecked = true;
+                            elem.value = vl;
+                        } else {
+                            elem.value = "on";
+                        }
+                        $(elem).attr("offval", "off");
+                    } else {
+                        var cbval = options.value.split(":");
+                        if (vl === cbval[0]) {
+                            elem.checked = true;
+                            elem.defaultChecked = true;
+                        }
+                        elem.value = cbval[0];
+                        $(elem).attr("offval", cbval[1]);
+                    }
+                    setAttributes(elem, options, ['value']);
+                    options = bindEv(elem, options);
+                    $(elem).attr("role", "checkbox");
+                    break;
+                case "select" :
+                    elem = document.createElement("select");
+                    elem.setAttribute("role", "select");
+                    var msl, ovm = [];
+                    if (options.multiple === true) {
+                        msl = true;
+                        elem.multiple = "multiple";
+                        $(elem).attr("aria-multiselectable", "true");
+                    } else {
+                        msl = false;
+                    }
+                    if (typeof(options.dataUrl) != "undefined") {
+                        $.ajax($.extend({
+                            url: options.dataUrl,
+                            type: "GET",
+                            dataType: "html",
+                            context: {elem: elem, options: options, vl: vl},
+                            success: function (data) {
+                                var a, ovm = [], elem = this.elem, vl = this.vl,
+                                    options = $.extend({}, this.options),
+                                    msl = options.multiple === true;
+                                if ($.isFunction(options.buildSelect)) {
+                                    var b = options.buildSelect.call($t, data);
+                                    a = $(b).html();
+                                } else {
+                                    a = $(data).html();
+                                }
+                                if (a) {
+                                    $(elem).append(a);
+                                    setAttributes(elem, options);
+                                    options = bindEv(elem, options);
+                                    if (typeof options.size === 'undefined') {
+                                        options.size = msl ? 3 : 1;
+                                    }
+                                    if (msl) {
+                                        ovm = vl.split(",");
+                                        ovm = $.map(ovm, function (n) {
+                                            return $.trim(n);
+                                        });
+                                    } else {
+                                        ovm[0] = $.trim(vl);
+                                    }
+                                    //$(elem).attr(options);
+                                    setTimeout(function () {
+                                        $("option", elem).each(function (i) {
+                                            //if(i===0) { this.selected = ""; }
+                                            // fix IE8/IE7 problem with selecting of the first item on multiple=true
+                                            if (i === 0 && elem.multiple) {
+                                                this.selected = false;
+                                            }
+                                            $(this).attr("role", "option");
+                                            if ($.inArray($.trim($(this).text()), ovm) > -1 || $.inArray($.trim($(this).val()), ovm) > -1) {
+                                                this.selected = "selected";
+                                            }
+                                        });
+                                    }, 0);
+                                }
+                            }
+                        }, ajaxso || {}));
+                    } else if (options.value) {
+                        var i;
+                        if (typeof options.size === 'undefined') {
+                            options.size = msl ? 3 : 1;
+                        }
+                        if (msl) {
+                            ovm = vl.split(",");
+                            ovm = $.map(ovm, function (n) {
+                                return $.trim(n);
+                            });
+                        }
+                        if (typeof options.value === 'function') {
+                            options.value = options.value();
+                        }
+                        var so, sv, ov,
+                            sep = options.separator === undefined ? ":" : options.separator,
+                            delim = options.delimiter === undefined ? ";" : options.delimiter;
+                        if (typeof options.value === 'string') {
+                            so = options.value.split(delim);
+                            for (i = 0; i < so.length; i++) {
+                                sv = so[i].split(sep);
+                                if (sv.length > 2) {
+                                    sv[1] = $.map(sv,function (n, ii) {
+                                        if (ii > 0) {
+                                            return n;
+                                        }
+                                    }).join(sep);
+                                }
+                                ov = document.createElement("option");
+                                ov.setAttribute("role", "option");
+                                ov.value = sv[0];
+                                ov.innerHTML = sv[1];
+                                elem.appendChild(ov);
+                                if (!msl && ($.trim(sv[0]) == $.trim(vl) || $.trim(sv[1]) == $.trim(vl))) {
+                                    ov.selected = "selected";
+                                }
+                                if (msl && ($.inArray($.trim(sv[1]), ovm) > -1 || $.inArray($.trim(sv[0]), ovm) > -1)) {
+                                    ov.selected = "selected";
+                                }
+                            }
+                        } else if (typeof options.value === 'object') {
+                            var oSv = options.value;
+                            for (var key in oSv) {
+                                if (oSv.hasOwnProperty(key)) {
+                                    ov = document.createElement("option");
+                                    ov.setAttribute("role", "option");
+                                    ov.value = key;
+                                    ov.innerHTML = oSv[key];
+                                    elem.appendChild(ov);
+                                    if (!msl && ( $.trim(key) == $.trim(vl) || $.trim(oSv[key]) == $.trim(vl))) {
+                                        ov.selected = "selected";
+                                    }
+                                    if (msl && ($.inArray($.trim(oSv[key]), ovm) > -1 || $.inArray($.trim(key), ovm) > -1)) {
+                                        ov.selected = "selected";
+                                    }
+                                }
+                            }
+                        }
+                        setAttributes(elem, options, ['value']);
+                        options = bindEv(elem, options);
+                    }
+                    break;
+                case "text" :
+                case "password" :
+                case "button" :
+                    var role;
+                    if (eltype == "button") {
+                        role = "button";
+                    }
+                    else {
+                        role = "textbox";
+                    }
+                    elem = document.createElement("input");
+                    elem.type = eltype;
+                    elem.value = vl;
+                    setAttributes(elem, options);
+                    options = bindEv(elem, options);
+                    if (eltype != "button") {
+                        if (autowidth) {
+                            if (!options.size) {
+                                $(elem).css({width: "98%"});
+                            }
+                        } else if (!options.size) {
+                            options.size = 20;
+                        }
+                    }
+                    $(elem).attr("role", role);
+                    break;
+                case "image" :
+                case "file" :
+                    elem = document.createElement("input");
+                    elem.type = eltype;
+                    setAttributes(elem, options);
+                    options = bindEv(elem, options);
+                    break;
+                case "custom" :
+                    elem = document.createElement("span");
+                    try {
+                        if ($.isFunction(options.custom_element)) {
+                            var celm = options.custom_element.call($t, vl, options);
+                            if (celm) {
+                                celm = $(celm).addClass("customelement").attr({id: options.id, name: options.name});
+                                $(elem).empty().append(celm);
+                            } else {
+                                throw "e2";
+                            }
+                        } else {
+                            throw "e1";
+                        }
+                    } catch (e) {
+                        if (e == "e1") {
+                            $.jgrid.info_dialog($.jgrid.errors.errcap, "function 'custom_element' " + $.jgrid.edit.msg.nodefined, $.jgrid.edit.bClose);
+                        }
+                        if (e == "e2") {
+                            $.jgrid.info_dialog($.jgrid.errors.errcap, "function 'custom_element' " + $.jgrid.edit.msg.novalue, $.jgrid.edit.bClose);
+                        }
+                        else {
+                            $.jgrid.info_dialog($.jgrid.errors.errcap, typeof(e) === "string" ? e : e.message, $.jgrid.edit.bClose);
+                        }
+                    }
+                    break;
+            }
+            return elem;
+        },
+// Date Validation Javascript
+        checkDate: function (format, date) {
+            var daysInFebruary = function (year) {
+                    // February has 29 days in any year evenly divisible by four,
+                    // EXCEPT for centurial years which are not also divisible by 400.
+                    return (((year % 4 === 0) && ( year % 100 !== 0 || (year % 400 === 0))) ? 29 : 28 );
+                },
+                DaysArray = function (n) {
+                    for (var i = 1; i <= n; i++) {
+                        this[i] = 31;
+                        if (i == 4 || i == 6 || i == 9 || i == 11) {
+                            this[i] = 30;
+                        }
+                        if (i == 2) {
+                            this[i] = 29;
+                        }
+                    }
+                    return this;
+                };
+
+            var tsp = {}, sep;
+            format = format.toLowerCase();
+            //we search for /,-,. for the date separator
+            if (format.indexOf("/") != -1) {
+                sep = "/";
+            } else if (format.indexOf("-") != -1) {
+                sep = "-";
+            } else if (format.indexOf(".") != -1) {
+                sep = ".";
+            } else {
+                sep = "/";
+            }
+            format = format.split(sep);
+            date = date.split(sep);
+            if (date.length != 3) {
+                return false;
+            }
+            var j = -1, yln, dln = -1, mln = -1;
+            for (var i = 0; i < format.length; i++) {
+                var dv = isNaN(date[i]) ? 0 : parseInt(date[i], 10);
+                tsp[format[i]] = dv;
+                yln = format[i];
+                if (yln.indexOf("y") != -1) {
+                    j = i;
+                }
+                if (yln.indexOf("m") != -1) {
+                    mln = i;
+                }
+                if (yln.indexOf("d") != -1) {
+                    dln = i;
+                }
+            }
+            if (format[j] == "y" || format[j] == "yyyy") {
+                yln = 4;
+            } else if (format[j] == "yy") {
+                yln = 2;
+            } else {
+                yln = -1;
+            }
+            var daysInMonth = DaysArray(12),
+                strDate;
+            if (j === -1) {
+                return false;
+            } else {
+                strDate = tsp[format[j]].toString();
+                if (yln == 2 && strDate.length == 1) {
+                    yln = 1;
+                }
+                if (strDate.length != yln || (tsp[format[j]] === 0 && date[j] != "00")) {
+                    return false;
+                }
+            }
+            if (mln === -1) {
+                return false;
+            } else {
+                strDate = tsp[format[mln]].toString();
+                if (strDate.length < 1 || tsp[format[mln]] < 1 || tsp[format[mln]] > 12) {
+                    return false;
+                }
+            }
+            if (dln === -1) {
+                return false;
+            } else {
+                strDate = tsp[format[dln]].toString();
+                if (strDate.length < 1 || tsp[format[dln]] < 1 || tsp[format[dln]] > 31 || (tsp[format[mln]] == 2 && tsp[format[dln]] > daysInFebruary(tsp[format[j]])) || tsp[format[dln]] > daysInMonth[tsp[format[mln]]]) {
+                    return false;
+                }
+            }
+            return true;
+        },
+        isEmpty: function (val) {
+            if (val.match(/^\s+$/) || val === "") {
+                return true;
+            } else {
+                return false;
+            }
+        },
+        checkTime: function (time) {
+            // checks only hh:ss (and optional am/pm)
+            var re = /^(\d{1,2}):(\d{2})([ap]m)?$/, regs;
+            if (!$.jgrid.isEmpty(time)) {
+                regs = time.match(re);
+                if (regs) {
+                    if (regs[3]) {
+                        if (regs[1] < 1 || regs[1] > 12) {
+                            return false;
+                        }
+                    } else {
+                        if (regs[1] > 23) {
+                            return false;
+                        }
+                    }
+                    if (regs[2] > 59) {
+                        return false;
+                    }
+                } else {
+                    return false;
+                }
+            }
+            return true;
+        },
+        checkValues: function (val, valref, g, customobject, nam) {
+            var edtrul, i, nm, dft, len;
+            if (typeof(customobject) === "undefined") {
+                if (typeof(valref) == 'string') {
+                    for (i = 0, len = g.p.colModel.length; i < len; i++) {
+                        if (g.p.colModel[i].name == valref) {
+                            edtrul = g.p.colModel[i].editrules;
+                            valref = i;
+                            try {
+                                nm = g.p.colModel[i].formoptions.label;
+                            } catch (e) {
+                            }
+                            break;
+                        }
+                    }
+                } else if (valref >= 0) {
+                    edtrul = g.p.colModel[valref].editrules;
+                }
+            } else {
+                edtrul = customobject;
+                nm = nam === undefined ? "_" : nam;
+            }
+            if (edtrul) {
+                if (!nm) {
+                    nm = g.p.colNames[valref];
+                }
+                if (edtrul.required === true) {
+                    if ($.jgrid.isEmpty(val)) {
+                        return [false, nm + ": " + $.jgrid.edit.msg.required, ""];
+                    }
+                }
+                // force required
+                var rqfield = edtrul.required === false ? false : true;
+                if (edtrul.number === true) {
+                    if (!(rqfield === false && $.jgrid.isEmpty(val))) {
+                        if (isNaN(val)) {
+                            return [false, nm + ": " + $.jgrid.edit.msg.number, ""];
+                        }
+                    }
+                }
+                if (typeof edtrul.minValue != 'undefined' && !isNaN(edtrul.minValue)) {
+                    if (parseFloat(val) < parseFloat(edtrul.minValue)) {
+                        return [false, nm + ": " + $.jgrid.edit.msg.minValue + " " + edtrul.minValue, ""];
+                    }
+                }
+                if (typeof edtrul.maxValue != 'undefined' && !isNaN(edtrul.maxValue)) {
+                    if (parseFloat(val) > parseFloat(edtrul.maxValue)) {
+                        return [false, nm + ": " + $.jgrid.edit.msg.maxValue + " " + edtrul.maxValue, ""];
+                    }
+                }
+                var filter;
+                if (edtrul.email === true) {
+                    if (!(rqfield === false && $.jgrid.isEmpty(val))) {
+                        // taken from $ Validate plugin
+                        filter = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
+                        if (!filter.test(val)) {
+                            return [false, nm + ": " + $.jgrid.edit.msg.email, ""];
+                        }
+                    }
+                }
+                if (edtrul.integer === true) {
+                    if (!(rqfield === false && $.jgrid.isEmpty(val))) {
+                        if (isNaN(val)) {
+                            return [false, nm + ": " + $.jgrid.edit.msg.integer, ""];
+                        }
+                        if ((val % 1 !== 0) || (val.indexOf('.') != -1)) {
+                            return [false, nm + ": " + $.jgrid.edit.msg.integer, ""];
+                        }
+                    }
+                }
+                if (edtrul.date === true) {
+                    if (!(rqfield === false && $.jgrid.isEmpty(val))) {
+                        if (g.p.colModel[valref].formatoptions && g.p.colModel[valref].formatoptions.newformat) {
+                            dft = g.p.colModel[valref].formatoptions.newformat;
+                        } else {
+                            dft = g.p.colModel[valref].datefmt || "Y-m-d";
+                        }
+                        if (!$.jgrid.checkDate(dft, val)) {
+                            return [false, nm + ": " + $.jgrid.edit.msg.date + " - " + dft, ""];
+                        }
+                    }
+                }
+                if (edtrul.time === true) {
+                    if (!(rqfield === false && $.jgrid.isEmpty(val))) {
+                        if (!$.jgrid.checkTime(val)) {
+                            return [false, nm + ": " + $.jgrid.edit.msg.date + " - hh:mm (am/pm)", ""];
+                        }
+                    }
+                }
+                if (edtrul.url === true) {
+                    if (!(rqfield === false && $.jgrid.isEmpty(val))) {
+                        filter = /^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
+                        if (!filter.test(val)) {
+                            return [false, nm + ": " + $.jgrid.edit.msg.url, ""];
+                        }
+                    }
+                }
+                if (edtrul.custom === true) {
+                    if (!(rqfield === false && $.jgrid.isEmpty(val))) {
+                        if ($.isFunction(edtrul.custom_func)) {
+                            var ret = edtrul.custom_func.call(g, val, nm);
+                            if ($.isArray(ret)) {
+                                return ret;
+                            } else {
+                                return [false, $.jgrid.edit.msg.customarray, ""];
+                            }
+                        } else {
+                            return [false, $.jgrid.edit.msg.customfcheck, ""];
+                        }
+                    }
+                }
+            }
+            return [true, "", ""];
+        }
+    });
+})(jQuery);
+/*
+ * jqFilter  jQuery jqGrid filter addon.
+ * Copyright (c) 2011, Tony Tomov, tony@trirand.com
+ * Dual licensed under the MIT and GPL licenses
+ * http://www.opensource.org/licenses/mit-license.php
+ * http://www.gnu.org/licenses/gpl-2.0.html
+ *
+ * The work is inspired from this Stefan Pirvu
+ * http://www.codeproject.com/KB/scripting/json-filtering.aspx
+ *
+ * The filter uses JSON entities to hold filter rules and groups. Here is an example of a filter:
+
+ { "groupOp": "AND",
+ "groups" : [
+ { "groupOp": "OR",
+ "rules": [
+ { "field": "name", "op": "eq", "data": "England" },
+ { "field": "id", "op": "le", "data": "5"}
+ ]
+ }
+ ],
+ "rules": [
+ { "field": "name", "op": "eq", "data": "Romania" },
+ { "field": "id", "op": "le", "data": "1"}
+ ]
+ }
+ */
+/*global jQuery, $, window, navigator */
+
+(function ($) {
+
+    $.fn.jqFilter = function (arg) {
+        if (typeof arg === 'string') {
+
+            var fn = $.fn.jqFilter[arg];
+            if (!fn) {
+                throw ("jqFilter - No such method: " + arg);
+            }
+            var args = $.makeArray(arguments).slice(1);
+            return fn.apply(this, args);
+        }
+
+        var p = $.extend(true, {
+            filter: null,
+            columns: [],
+            onChange: null,
+            afterRedraw: null,
+            checkValues: null,
+            error: false,
+            errmsg: "",
+            errorcheck: true,
+            showQuery: true,
+            sopt: null,
+            ops: [
+                {"name": "eq", "description": "equal", "operator": "="},
+                {"name": "ne", "description": "not equal", "operator": "<>"},
+                {"name": "lt", "description": "less", "operator": "<"},
+                {"name": "le", "description": "less or equal", "operator": "<="},
+                {"name": "gt", "description": "greater", "operator": ">"},
+                {"name": "ge", "description": "greater or equal", "operator": ">="},
+                {"name": "bw", "description": "begins with", "operator": "LIKE"},
+                {"name": "bn", "description": "does not begin with", "operator": "NOT LIKE"},
+                {"name": "in", "description": "in", "operator": "IN"},
+                {"name": "ni", "description": "not in", "operator": "NOT IN"},
+                {"name": "ew", "description": "ends with", "operator": "LIKE"},
+                {"name": "en", "description": "does not end with", "operator": "NOT LIKE"},
+                {"name": "cn", "description": "contains", "operator": "LIKE"},
+                {"name": "nc", "description": "does not contain", "operator": "NOT LIKE"},
+                {"name": "nu", "description": "is null", "operator": "IS NULL"},
+                {"name": "nn", "description": "is not null", "operator": "IS NOT NULL"}
+            ],
+            numopts: ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn', 'in', 'ni'],
+            stropts: ['eq', 'ne', 'bw', 'bn', 'ew', 'en', 'cn', 'nc', 'nu', 'nn', 'in', 'ni'],
+            _gridsopt: [], // grid translated strings, do not tuch
+            groupOps: [
+                { op: "AND", text: "AND" },
+                { op: "OR", text: "OR" }
+            ],
+            groupButton: true,
+            ruleButtons: true,
+            direction: "ltr"
+        }, $.jgrid.filter, arg || {});
+        return this.each(function () {
+            if (this.filter) {
+                return;
+            }
+            this.p = p;
+            // setup filter in case if they is not defined
+            if (this.p.filter === null || this.p.filter === undefined) {
+                this.p.filter = {
+                    groupOp: this.p.groupOps[0].op,
+                    rules: [],
+                    groups: []
+                };
+            }
+            var i, len = this.p.columns.length, cl,
+                isIE = /msie/i.test(navigator.userAgent) && !window.opera;
+
+            // translating the options
+            if (this.p._gridsopt.length) {
+                // ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
+                for (i = 0; i < this.p._gridsopt.length; i++) {
+                    this.p.ops[i].description = this.p._gridsopt[i];
+                }
+            }
+            this.p.initFilter = $.extend(true, {}, this.p.filter);
+
+            // set default values for the columns if they are not set
+            if (!len) {
+                return;
+            }
+            for (i = 0; i < len; i++) {
+                cl = this.p.columns[i];
+                if (cl.stype) {
+                    // grid compatibility
+                    cl.inputtype = cl.stype;
+                } else if (!cl.inputtype) {
+                    cl.inputtype = 'text';
+                }
+                if (cl.sorttype) {
+                    // grid compatibility
+                    cl.searchtype = cl.sorttype;
+                } else if (!cl.searchtype) {
+                    cl.searchtype = 'string';
+                }
+                if (cl.hidden === undefined) {
+                    // jqGrid compatibility
+                    cl.hidden = false;
+                }
+                if (!cl.label) {
+                    cl.label = cl.name;
+                }
+                if (cl.index) {
+                    cl.name = cl.index;
+                }
+                if (!cl.hasOwnProperty('searchoptions')) {
+                    cl.searchoptions = {};
+                }
+                if (!cl.hasOwnProperty('searchrules')) {
+                    cl.searchrules = {};
+                }
+
+            }
+            if (this.p.showQuery) {
+                $(this).append("<table class='queryresult ui-widget ui-widget-content' style='display:block;max-width:440px;border:0px none;' dir='" + this.p.direction + "'><tbody><tr><td class='query'></td></tr></tbody></table>");
+            }
+            /*
+             *Perform checking.
+             *
+             */
+            var checkData = function (val, colModelItem) {
+                var ret = [true, ""];
+                if ($.isFunction(colModelItem.searchrules)) {
+                    ret = colModelItem.searchrules(val, colModelItem);
+                } else if ($.jgrid && $.jgrid.checkValues) {
+                    try {
+                        ret = $.jgrid.checkValues(val, -1, null, colModelItem.searchrules, colModelItem.label);
+                    } catch (e) {
+                    }
+                }
+                if (ret && ret.length && ret[0] === false) {
+                    p.error = !ret[0];
+                    p.errmsg = ret[1];
+                }
+            };
+            /* moving to common
+             randId = function() {
+             return Math.floor(Math.random()*10000).toString();
+             };
+             */
+
+            this.onchange = function () {
+                // clear any error
+                this.p.error = false;
+                this.p.errmsg = "";
+                return $.isFunction(this.p.onChange) ? this.p.onChange.call(this, this.p) : false;
+            };
+            /*
+             * Redraw the filter every time when new field is added/deleted
+             * and field is  changed
+             */
+            this.reDraw = function () {
+                $("table.group:first", this).remove();
+                var t = this.createTableForGroup(p.filter, null);
+                $(this).append(t);
+                if ($.isFunction(this.p.afterRedraw)) {
+                    this.p.afterRedraw.call(this, this.p);
+                }
+            };
+            /*
+             * Creates a grouping data for the filter
+             * @param group - object
+             * @param parentgroup - object
+             */
+            this.createTableForGroup = function (group, parentgroup) {
+                var that = this, i;
+                // this table will hold all the group (tables) and rules (rows)
+                var table = $("<table class='group ui-widget ui-widget-content' style='border:0px none;'><tbody></tbody></table>"),
+                // create error message row
+                    align = "left";
+                if (this.p.direction == "rtl") {
+                    align = "right";
+                    table.attr("dir", "rtl");
+                }
+                if (parentgroup === null) {
+                    table.append("<tr class='error' style='display:none;'><th colspan='5' class='ui-state-error' align='" + align + "'></th></tr>");
+                }
+
+                var tr = $("<tr></tr>");
+                table.append(tr);
+                // this header will hold the group operator type and group action buttons for
+                // creating subgroup "+ {}", creating rule "+" or deleting the group "-"
+                var th = $("<th colspan='5' align='" + align + "'></th>");
+                tr.append(th);
+
+                if (this.p.ruleButtons === true) {
+                    // dropdown for: choosing group operator type
+                    var groupOpSelect = $("<select class='opsel'></select>");
+                    th.append(groupOpSelect);
+                    // populate dropdown with all posible group operators: or, and
+                    var str = "", selected;
+                    for (i = 0; i < p.groupOps.length; i++) {
+                        selected = group.groupOp === that.p.groupOps[i].op ? " selected='selected'" : "";
+                        str += "<option value='" + that.p.groupOps[i].op + "'" + selected + ">" + that.p.groupOps[i].text + "</option>";
+                    }
+
+                    groupOpSelect
+                        .append(str)
+                        .bind('change', function () {
+                            group.groupOp = $(groupOpSelect).val();
+                            that.onchange(); // signals that the filter has changed
+                        });
+                }
+                // button for adding a new subgroup
+                var inputAddSubgroup = "<span></span>";
+                if (this.p.groupButton) {
+                    inputAddSubgroup = $("<input type='button' value='+ {}' title='Add subgroup' class='add-group'/>");
+                    inputAddSubgroup.bind('click', function () {
+                        if (group.groups === undefined) {
+                            group.groups = [];
+                        }
+
+                        group.groups.push({
+                            groupOp: p.groupOps[0].op,
+                            rules: [],
+                            groups: []
+                        }); // adding a new group
+
+                        that.reDraw(); // the html has changed, force reDraw
+
+                        that.onchange(); // signals that the filter has changed
+                        return false;
+                    });
+                }
+                th.append(inputAddSubgroup);
+                if (this.p.ruleButtons === true) {
+                    // button for adding a new rule
+                    var inputAddRule = $("<input type='button' value='+' title='Add rule' class='add-rule ui-add'/>"), cm;
+                    inputAddRule.bind('click', function () {
+                        //if(!group) { group = {};}
+                        if (group.rules === undefined) {
+                            group.rules = [];
+                        }
+                        for (i = 0; i < that.p.columns.length; i++) {
+                            // but show only serchable and serchhidden = true fields
+                            var searchable = (typeof that.p.columns[i].search === 'undefined') ? true : that.p.columns[i].search ,
+                                hidden = (that.p.columns[i].hidden === true),
+                                ignoreHiding = (that.p.columns[i].searchoptions.searchhidden === true);
+                            if ((ignoreHiding && searchable) || (searchable && !hidden)) {
+                                cm = that.p.columns[i];
+                                break;
+                            }
+                        }
+
+                        var opr;
+                        if (cm.searchoptions.sopt) {
+                            opr = cm.searchoptions.sopt;
+                        }
+                        else if (that.p.sopt) {
+                            opr = that.p.sopt;
+                        }
+                        else if (cm.searchtype === 'string') {
+                            opr = that.p.stropts;
+                        }
+                        else {
+                            opr = that.p.numopts;
+                        }
+
+                        group.rules.push({
+                            field: cm.name,
+                            op: opr[0],
+                            data: ""
+                        }); // adding a new rule
+
+                        that.reDraw(); // the html has changed, force reDraw
+                        // for the moment no change have been made to the rule, so
+                        // this will not trigger onchange event
+                        return false;
+                    });
+                    th.append(inputAddRule);
+                }
+
+                // button for delete the group
+                if (parentgroup !== null) { // ignore the first group
+                    var inputDeleteGroup = $("<input type='button' value='-' title='Delete group' class='delete-group'/>");
+                    th.append(inputDeleteGroup);
+                    inputDeleteGroup.bind('click', function () {
+                        // remove group from parent
+                        for (i = 0; i < parentgroup.groups.length; i++) {
+                            if (parentgroup.groups[i] === group) {
+                                parentgroup.groups.splice(i, 1);
+                                break;
+                            }
+                        }
+
+                        that.reDraw(); // the html has changed, force reDraw
+
+                        that.onchange(); // signals that the filter has changed
+                        return false;
+                    });
+                }
+
+                // append subgroup rows
+                if (group.groups !== undefined) {
+                    for (i = 0; i < group.groups.length; i++) {
+                        var trHolderForSubgroup = $("<tr></tr>");
+                        table.append(trHolderForSubgroup);
+
+                        var tdFirstHolderForSubgroup = $("<td class='first'></td>");
+                        trHolderForSubgroup.append(tdFirstHolderForSubgroup);
+
+                        var tdMainHolderForSubgroup = $("<td colspan='4'></td>");
+                        tdMainHolderForSubgroup.append(this.createTableForGroup(group.groups[i], group));
+                        trHolderForSubgroup.append(tdMainHolderForSubgroup);
+                    }
+                }
+                if (group.groupOp === undefined) {
+                    group.groupOp = that.p.groupOps[0].op;
+                }
+
+                // append rules rows
+                if (group.rules !== undefined) {
+                    for (i = 0; i < group.rules.length; i++) {
+                        table.append(
+                            this.createTableRowForRule(group.rules[i], group)
+                        );
+                    }
+                }
+
+                return table;
+            };
+            /*
+             * Create the rule data for the filter
+             */
+            this.createTableRowForRule = function (rule, group) {
+                // save current entity in a variable so that it could
+                // be referenced in anonimous method calls
+
+                var that = this, tr = $("<tr></tr>"),
+                //document.createElement("tr"),
+
+                // first column used for padding
+                //tdFirstHolderForRule = document.createElement("td"),
+                    i, op, trpar, cm, str = "", selected;
+                //tdFirstHolderForRule.setAttribute("class", "first");
+                tr.append("<td class='first'></td>");
+
+
+                // create field container
+                var ruleFieldTd = $("<td class='columns'></td>");
+                tr.append(ruleFieldTd);
+
+
+                // dropdown for: choosing field
+                var ruleFieldSelect = $("<select></select>"), ina, aoprs = [];
+                ruleFieldTd.append(ruleFieldSelect);
+                ruleFieldSelect.bind('change', function () {
+                    rule.field = $(ruleFieldSelect).val();
+
+                    trpar = $(this).parents("tr:first");
+                    for (i = 0; i < that.p.columns.length; i++) {
+                        if (that.p.columns[i].name === rule.field) {
+                            cm = that.p.columns[i];
+                            break;
+                        }
+                    }
+                    if (!cm) {
+                        return;
+                    }
+                    cm.searchoptions.id = $.jgrid.randId();
+                    if (isIE && cm.inputtype === "text") {
+                        if (!cm.searchoptions.size) {
+                            cm.searchoptions.size = 10;
+                        }
+                    }
+                    var elm = $.jgrid.createEl(cm.inputtype, cm.searchoptions, "", true, that.p.ajaxSelectOptions, true);
+                    $(elm).addClass("input-elm");
+                    //that.createElement(rule, "");
+
+                    if (cm.searchoptions.sopt) {
+                        op = cm.searchoptions.sopt;
+                    }
+                    else if (that.p.sopt) {
+                        op = that.p.sopt;
+                    }
+                    else if (cm.searchtype === 'string') {
+                        op = that.p.stropts;
+                    }
+                    else {
+                        op = that.p.numopts;
+                    }
+                    // operators
+                    var s = "", so = 0;
+                    aoprs = [];
+                    $.each(that.p.ops, function () {
+                        aoprs.push(this.name)
+                    });
+                    for (i = 0; i < op.length; i++) {
+                        ina = $.inArray(op[i], aoprs);
+                        if (ina !== -1) {
+                            if (so === 0) {
+                                rule.op = that.p.ops[ina].name;
+                            }
+                            s += "<option value='" + that.p.ops[ina].name + "'>" + that.p.ops[ina].description + "</option>";
+                            so++;
+                        }
+                    }
+                    $(".selectopts", trpar).empty().append(s);
+                    $(".selectopts", trpar)[0].selectedIndex = 0;
+                    if ($.browser.msie && $.browser.version < 9) {
+                        var sw = parseInt($("select.selectopts", trpar)[0].offsetWidth) + 1;
+                        $(".selectopts", trpar).width(sw);
+                        $(".selectopts", trpar).css("width", "auto");
+                    }
+                    // data
+                    $(".data", trpar).empty().append(elm);
+                    $(".input-elm", trpar).bind('change', function (e) {
+                        var tmo = $(this).hasClass("ui-autocomplete-input") ? 200 : 0;
+                        setTimeout(function () {
+                            var elem = e.target;
+                            rule.data = elem.nodeName.toUpperCase() === "SPAN" && cm.searchoptions && $.isFunction(cm.searchoptions.custom_value) ?
+                                cm.searchoptions.custom_value($(elem).children(".customelement:first"), 'get') : elem.value;
+                            that.onchange(); // signals that the filter has changed
+                        }, tmo);
+                    });
+                    setTimeout(function () { //IE, Opera, Chrome
+                        rule.data = $(elm).val();
+                        that.onchange();  // signals that the filter has changed
+                    }, 0);
+                });
+
+                // populate drop down with user provided column definitions
+                var j = 0;
+                for (i = 0; i < that.p.columns.length; i++) {
+                    // but show only serchable and serchhidden = true fields
+                    var searchable = (typeof that.p.columns[i].search === 'undefined') ? true : that.p.columns[i].search ,
+                        hidden = (that.p.columns[i].hidden === true),
+                        ignoreHiding = (that.p.columns[i].searchoptions.searchhidden === true);
+                    if ((ignoreHiding && searchable) || (searchable && !hidden)) {
+                        selected = "";
+                        if (rule.field === that.p.columns[i].name) {
+                            selected = " selected='selected'";
+                            j = i;
+                        }
+                        str += "<option value='" + that.p.columns[i].name + "'" + selected + ">" + that.p.columns[i].label + "</option>";
+                    }
+                }
+                ruleFieldSelect.append(str);
+
+
+                // create operator container
+                var ruleOperatorTd = $("<td class='operators'></td>");
+                tr.append(ruleOperatorTd);
+                cm = p.columns[j];
+                // create it here so it can be referentiated in the onchange event
+                //var RD = that.createElement(rule, rule.data);
+                cm.searchoptions.id = $.jgrid.randId();
+                if (isIE && cm.inputtype === "text") {
+                    if (!cm.searchoptions.size) {
+                        cm.searchoptions.size = 10;
+                    }
+                }
+                var ruleDataInput = $.jgrid.createEl(cm.inputtype, cm.searchoptions, rule.data, true, that.p.ajaxSelectOptions, true);
+
+                // dropdown for: choosing operator
+                var ruleOperatorSelect = $("<select class='selectopts'></select>");
+                ruleOperatorTd.append(ruleOperatorSelect);
+                ruleOperatorSelect.bind('change', function () {
+                    rule.op = $(ruleOperatorSelect).val();
+                    trpar = $(this).parents("tr:first");
+                    var rd = $(".input-elm", trpar)[0];
+                    if (rule.op === "nu" || rule.op === "nn") { // disable for operator "is null" and "is not null"
+                        rule.data = "";
+                        rd.value = "";
+                        rd.setAttribute("readonly", "true");
+                        rd.setAttribute("disabled", "true");
+                    } else {
+                        rd.removeAttribute("readonly");
+                        rd.removeAttribute("disabled");
+                    }
+
+                    that.onchange();  // signals that the filter has changed
+                });
+
+                // populate drop down with all available operators
+                if (cm.searchoptions.sopt) {
+                    op = cm.searchoptions.sopt;
+                }
+                else if (that.p.sopt) {
+                    op = that.p.sopt;
+                }
+                else if (cm.searchtype === 'string') {
+                    op = p.stropts;
+                }
+                else {
+                    op = that.p.numopts;
+                }
+                str = "";
+                $.each(that.p.ops, function () {
+                    aoprs.push(this.name)
+                });
+                for (i = 0; i < op.length; i++) {
+                    ina = $.inArray(op[i], aoprs);
+                    if (ina !== -1) {
+                        selected = rule.op === that.p.ops[ina].name ? " selected='selected'" : "";
+                        str += "<option value='" + that.p.ops[ina].name + "'" + selected + ">" + that.p.ops[ina].description + "</option>";
+                    }
+                }
+                ruleOperatorSelect.append(str);
+                // create data container
+                var ruleDataTd = $("<td class='data'></td>");
+                tr.append(ruleDataTd);
+
+                // textbox for: data
+                // is created previously
+                //ruleDataInput.setAttribute("type", "text");
+                ruleDataTd.append(ruleDataInput);
+
+                $(ruleDataInput)
+                    .addClass("input-elm")
+                    .bind('change', function () {
+                        rule.data = cm.inputtype === 'custom' ? cm.searchoptions.custom_value($(this).children(".customelement:first"), 'get') : $(this).val();
+                        that.onchange(); // signals that the filter has changed
+                    });
+
+                // create action container
+                var ruleDeleteTd = $("<td></td>");
+                tr.append(ruleDeleteTd);
+
+                // create button for: delete rule
+                if (this.p.ruleButtons === true) {
+                    var ruleDeleteInput = $("<input type='button' value='-' title='Delete rule' class='delete-rule ui-del'/>");
+                    ruleDeleteTd.append(ruleDeleteInput);
+                    //$(ruleDeleteInput).html("").height(20).width(30).button({icons: {  primary: "ui-icon-minus", text:false}});
+                    ruleDeleteInput.bind('click', function () {
+                        // remove rule from group
+                        for (i = 0; i < group.rules.length; i++) {
+                            if (group.rules[i] === rule) {
+                                group.rules.splice(i, 1);
+                                break;
+                            }
+                        }
+
+                        that.reDraw(); // the html has changed, force reDraw
+
+                        that.onchange(); // signals that the filter has changed
+                        return false;
+                    });
+                }
+                return tr;
+            };
+
+            this.getStringForGroup = function (group) {
+                var s = "(", index;
+                if (group.groups !== undefined) {
+                    for (index = 0; index < group.groups.length; index++) {
+                        if (s.length > 1) {
+                            s += " " + group.groupOp + " ";
+                        }
+                        try {
+                            s += this.getStringForGroup(group.groups[index]);
+                        } catch (eg) {
+                            alert(eg);
+                        }
+                    }
+                }
+
+                if (group.rules !== undefined) {
+                    try {
+                        for (index = 0; index < group.rules.length; index++) {
+                            if (s.length > 1) {
+                                s += " " + group.groupOp + " ";
+                            }
+                            s += this.getStringForRule(group.rules[index]);
+                        }
+                    } catch (e) {
+                        alert(e);
+                    }
+                }
+
+                s += ")";
+
+                if (s === "()") {
+                    return ""; // ignore groups that don't have rules
+                } else {
+                    return s;
+                }
+            };
+            this.getStringForRule = function (rule) {
+                var opUF = "", opC = "", i, cm, ret, val,
+                    numtypes = ['int', 'integer', 'float', 'number', 'currency']; // jqGrid
+                for (i = 0; i < this.p.ops.length; i++) {
+                    if (this.p.ops[i].name === rule.op) {
+                        opUF = this.p.ops[i].operator;
+                        opC = this.p.ops[i].name;
+                        break;
+                    }
+                }
+                for (i = 0; i < this.p.columns.length; i++) {
+                    if (this.p.columns[i].name === rule.field) {
+                        cm = this.p.columns[i];
+                        break;
+                    }
+                }
+                val = rule.data;
+                if (opC === 'bw' || opC === 'bn') {
+                    val = val + "%";
+                }
+                if (opC === 'ew' || opC === 'en') {
+                    val = "%" + val;
+                }
+                if (opC === 'cn' || opC === 'nc') {
+                    val = "%" + val + "%";
+                }
+                if (opC === 'in' || opC === 'ni') {
+                    val = " (" + val + ")";
+                }
+                if (p.errorcheck) {
+                    checkData(rule.data, cm);
+                }
+                if ($.inArray(cm.searchtype, numtypes) !== -1 || opC === 'nn' || opC === 'nu') {
+                    ret = rule.field + " " + opUF + " " + val;
+                }
+                else {
+                    ret = rule.field + " " + opUF + " \"" + val + "\"";
+                }
+                return ret;
+            };
+            this.resetFilter = function () {
+                this.p.filter = $.extend(true, {}, this.p.initFilter);
+                this.reDraw();
+                this.onchange();
+            };
+            this.hideError = function () {
+                $("th.ui-state-error", this).html("");
+                $("tr.error", this).hide();
+            };
+            this.showError = function () {
+                $("th.ui-state-error", this).html(this.p.errmsg);
+                $("tr.error", this).show();
+            };
+            this.toUserFriendlyString = function () {
+                return this.getStringForGroup(p.filter);
+            };
+            this.toString = function () {
+                // this will obtain a string that can be used to match an item.
+                var that = this;
+
+                function getStringRule(rule) {
+                    if (that.p.errorcheck) {
+                        var i, cm;
+                        for (i = 0; i < that.p.columns.length; i++) {
+                            if (that.p.columns[i].name === rule.field) {
+                                cm = that.p.columns[i];
+                                break;
+                            }
+                        }
+                        if (cm) {
+                            checkData(rule.data, cm);
+                        }
+                    }
+                    return rule.op + "(item." + rule.field + ",'" + rule.data + "')";
+                }
+
+                function getStringForGroup(group) {
+                    var s = "(", index;
+
+                    if (group.groups !== undefined) {
+                        for (index = 0; index < group.groups.length; index++) {
+                            if (s.length > 1) {
+                                if (group.groupOp === "OR") {
+                                    s += " || ";
+                                }
+                                else {
+                                    s += " && ";
+                                }
+                            }
+                            s += getStringForGroup(group.groups[index]);
+                        }
+                    }
+
+                    if (group.rules !== undefined) {
+                        for (index = 0; index < group.rules.length; index++) {
+                            if (s.length > 1) {
+                                if (group.groupOp === "OR") {
+                                    s += " || ";
+                                }
+                                else {
+                                    s += " && ";
+                                }
+                            }
+                            s += getStringRule(group.rules[index]);
+                        }
+                    }
+
+                    s += ")";
+
+                    if (s === "()") {
+                        return ""; // ignore groups that don't have rules
+                    } else {
+                        return s;
+                    }
+                }
+
+                return getStringForGroup(this.p.filter);
+            };
+
+            // Here we init the filter
+            this.reDraw();
+
+            if (this.p.showQuery) {
+                this.onchange();
+            }
+            // mark is as created so that it will not be created twice on this element
+            this.filter = true;
+        });
+    };
+    $.extend($.fn.jqFilter, {
+        /*
+         * Return SQL like string. Can be used directly
+         */
+        toSQLString: function () {
+            var s = "";
+            this.each(function () {
+                s = this.toUserFriendlyString();
+            });
+            return s;
+        },
+        /*
+         * Return filter data as object.
+         */
+        filterData: function () {
+            var s;
+            this.each(function () {
+                s = this.p.filter;
+            });
+            return s;
+
+        },
+        getParameter: function (param) {
+            if (param !== undefined) {
+                if (this.p.hasOwnProperty(param)) {
+                    return this.p[param];
+                }
+            }
+            return this.p;
+        },
+        resetFilter: function () {
+            return this.each(function () {
+                this.resetFilter();
+            });
+        },
+        addFilter: function (pfilter) {
+            if (typeof pfilter === "string") {
+                pfilter = jQuery.jgrid.parse(pfilter);
+            }
+            this.each(function () {
+                this.p.filter = pfilter;
+                this.reDraw();
+                this.onchange();
+            });
+        }
+
+    });
+})(jQuery);
+
+(function ($) {
+    /**
+     * jqGrid extension for form editing Grid Data
+     * Tony Tomov tony@trirand.com
+     * http://trirand.com/blog/
+     * Dual licensed under the MIT and GPL licenses:
+     * http://www.opensource.org/licenses/mit-license.php
+     * http://www.gnu.org/licenses/gpl-2.0.html
+     **/
+    "use strict";
+    /*global xmlJsonClass, jQuery, $  */
+    var rp_ge = {};
+    $.jgrid.extend({
+        searchGrid: function (p) {
+            p = $.extend({
+                recreateFilter: false,
+                drag: true,
+                sField: 'searchField',
+                sValue: 'searchString',
+                sOper: 'searchOper',
+                sFilter: 'filters',
+                loadDefaults: true, // this options activates loading of default filters from grid's postData for Multipe Search only.
+                beforeShowSearch: null,
+                afterShowSearch: null,
+                onInitializeSearch: null,
+                afterRedraw: null,
+                afterChange: null,
+                closeAfterSearch: false,
+                closeAfterReset: false,
+                closeOnEscape: false,
+                searchOnEnter: false,
+                multipleSearch: false,
+                multipleGroup: false,
+                //cloneSearchRowOnAdd: true,
+                top: 0,
+                left: 0,
+                jqModal: true,
+                modal: false,
+                resize: true,
+                width: 450,
+                height: 'auto',
+                dataheight: 'auto',
+                showQuery: false,
+                errorcheck: true,
+                // translation
+                // if you want to change or remove the order change it in sopt
+                // ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc'],
+                sopt: null,
+                stringResult: undefined,
+                onClose: null,
+                onSearch: null,
+                onReset: null,
+                toTop: true,
+                overlay: 30,
+                columns: [],
+                tmplNames: null,
+                tmplFilters: null,
+                // translations - later in lang file
+                tmplLabel: ' Template: ',
+                showOnLoad: false,
+                layer: null,
+                ops: null
+            }, $.jgrid.search, p || {});
+            return this.each(function () {
+                var $t = this;
+                if (!$t.grid) {
+                    return;
+                }
+                var fid = "fbox_" + $t.p.id,
+                    showFrm = true,
+                    IDs = {themodal: 'searchmod' + fid, modalhead: 'searchhd' + fid, modalcontent: 'searchcnt' + fid, scrollelm: fid},
+                    defaultFilters = $t.p.postData[p.sFilter];
+                if (typeof(defaultFilters) === "string") {
+                    defaultFilters = $.jgrid.parse(defaultFilters);
+                }
+                if (p.recreateFilter === true) {
+                    $("#" + $.jgrid.jqID(IDs.themodal)).remove();
+                }
+                function showFilter(_filter) {
+                    showFrm = $($t).triggerHandler("jqGridFilterBeforeShow", [_filter]);
+                    if (typeof(showFrm) === "undefined") {
+                        showFrm = true;
+                    }
+                    if (showFrm && $.isFunction(p.beforeShowSearch)) {
+                        showFrm = p.beforeShowSearch.call($t, _filter);
+                    }
+                    if (showFrm) {
+                        $.jgrid.viewModal("#" + $.jgrid.jqID(IDs.themodal), {gbox: "#gbox_" + $.jgrid.jqID(fid), jqm: p.jqModal, modal: p.modal, overlay: p.overlay, toTop: p.toTop});
+                        $($t).triggerHandler("jqGridFilterAfterShow", [_filter]);
+                        if ($.isFunction(p.afterShowSearch)) {
+                            p.afterShowSearch.call($t, _filter);
+                        }
+                    }
+                }
+
+                if ($("#" + $.jgrid.jqID(IDs.themodal)).html() !== null) {
+                    showFilter($("#fbox_" + $.jgrid.jqID(+$t.p.id)));
+                } else {
+                    var fil = $("<div><div id='" + fid + "' class='searchFilter' style='overflow:auto'></div></div>").insertBefore("#gview_" + $.jgrid.jqID($t.p.id)),
+                        align = "left", butleft = "";
+                    if ($t.p.direction == "rtl") {
+                        align = "right";
+                        butleft = " style='text-align:left'";
+                        fil.attr("dir", "rtl");
+                    }
+                    var columns = $.extend([], $t.p.colModel),
+                        bS = "<a href='javascript:void(0)' id='" + fid + "_search' class='fm-button ui-state-default ui-corner-all fm-button-icon-right ui-reset'><span class='ui-icon ui-icon-search'></span>" + p.Find + "</a>",
+                        bC = "<a href='javascript:void(0)' id='" + fid + "_reset' class='fm-button ui-state-default ui-corner-all fm-button-icon-left ui-search'><span class='ui-icon ui-icon-arrowreturnthick-1-w'></span>" + p.Reset + "</a>",
+                        bQ = "", tmpl = "", colnm, found = false, bt, cmi = -1;
+                    if (p.showQuery) {
+                        bQ = "<a href='javascript:void(0)' id='" + fid + "_query' class='fm-button ui-state-default ui-corner-all fm-button-icon-left'><span class='ui-icon ui-icon-comment'></span>Query</a>";
+                    }
+                    if (!p.columns.length) {
+                        $.each(columns, function (i, n) {
+                            if (!n.label) {
+                                n.label = $t.p.colNames[i];
+                            }
+                            // find first searchable column and set it if no default filter
+                            if (!found) {
+                                var searchable = (typeof n.search === 'undefined') ? true : n.search ,
+                                    hidden = (n.hidden === true),
+                                    ignoreHiding = (n.searchoptions && n.searchoptions.searchhidden === true);
+                                if ((ignoreHiding && searchable) || (searchable && !hidden)) {
+                                    found = true;
+                                    colnm = n.index || n.name;
+                                    cmi = i;
+                                }
+                            }
+                        });
+                    } else {
+                        columns = p.columns;
+                    }
+                    // old behaviour
+                    if ((!defaultFilters && colnm) || p.multipleSearch === false) {
+                        var cmop = "eq";
+                        if (cmi >= 0 && columns[cmi].searchoptions && columns[cmi].searchoptions.sopt) {
+                            cmop = columns[cmi].searchoptions.sopt[0];
+                        } else if (p.sopt && p.sopt.length) {
+                            cmop = p.sopt[0];
+                        }
+                        defaultFilters = {"groupOp": "AND", rules: [
+                            {"field": colnm, "op": cmop, "data": ""}
+                        ]};
+                    }
+                    found = false;
+                    if (p.tmplNames && p.tmplNames.length) {
+                        found = true;
+                        tmpl = p.tmplLabel;
+                        tmpl += "<select class='ui-template'>";
+                        tmpl += "<option value='default'>Default</option>";
+                        $.each(p.tmplNames, function (i, n) {
+                            tmpl += "<option value='" + i + "'>" + n + "</option>";
+                        });
+                        tmpl += "</select>";
+                    }
+
+                    bt = "<table class='EditTable' style='border:0px none;margin-top:5px' id='" + fid + "_2'><tbody><tr><td colspan='2'><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr><td class='EditButton' style='text-align:" + align + "'>" + bC + tmpl + "</td><td class='EditButton' " + butleft + ">" + bQ + bS + "</td></tr></tbody></table>";
+                    fid = $.jgrid.jqID(fid);
+                    $("#" + fid).jqFilter({
+                        columns: columns,
+                        filter: p.loadDefaults ? defaultFilters : null,
+                        showQuery: p.showQuery,
+                        errorcheck: p.errorcheck,
+                        sopt: p.sopt,
+                        groupButton: p.multipleGroup,
+                        ruleButtons: p.multipleSearch,
+                        afterRedraw: p.afterRedraw,
+                        _gridsopt: $.jgrid.search.odata,
+                        ajaxSelectOptions: $t.p.ajaxSelectOptions,
+                        groupOps: p.groupOps,
+                        onChange: function () {
+                            if (this.p.showQuery) {
+                                $('.query', this).html(this.toUserFriendlyString());
+                            }
+                            if ($.isFunction(p.afterChange)) {
+                                p.afterChange.call($t, $("#" + fid), p);
+                            }
+                        },
+                        direction: $t.p.direction,
+                        ops: p.ops
+                    });
+                    fil.append(bt);
+                    if (found && p.tmplFilters && p.tmplFilters.length) {
+                        $(".ui-template", fil).bind('change', function () {
+                            var curtempl = $(this).val();
+                            if (curtempl == "default") {
+                                $("#" + fid).jqFilter('addFilter', defaultFilters);
+                            } else {
+                                $("#" + fid).jqFilter('addFilter', p.tmplFilters[parseInt(curtempl, 10)]);
+                            }
+                            return false;
+                        });
+                    }
+                    if (p.multipleGroup === true) {
+                        p.multipleSearch = true;
+                    }
+                    $($t).triggerHandler("jqGridFilterInitialize", [$("#" + fid)]);
+                    if ($.isFunction(p.onInitializeSearch)) {
+                        p.onInitializeSearch.call($t, $("#" + fid));
+                    }
+                    p.gbox = "#gbox_" + fid;
+                    if (p.layer) {
+                        $.jgrid.createModal(IDs, fil, p, "#gview_" + $.jgrid.jqID($t.p.id), $("#gbox_" + $.jgrid.jqID($t.p.id))[0], "#" + $.jgrid.jqID(p.layer), {position: "relative"});
+                    } else {
+                        $.jgrid.createModal(IDs, fil, p, "#gview_" + $.jgrid.jqID($t.p.id), $("#gbox_" + $.jgrid.jqID($t.p.id))[0]);
+                    }
+                    if (p.searchOnEnter || p.closeOnEscape) {
+                        $("#" + $.jgrid.jqID(IDs.themodal)).keydown(function (e) {
+                            var $target = $(e.target);
+                            if (p.searchOnEnter && e.which === 13 && // 13 === $.ui.keyCode.ENTER
+                                !$target.hasClass('add-group') && !$target.hasClass('add-rule') && !$target.hasClass('delete-group') && !$target.hasClass('delete-rule') &&
+                                (!$target.hasClass("fm-button") || !$target.is("[id$=_query]"))) {
+                                $("#" + fid + "_search").focus().click();
+                                return false;
+                            }
+                            if (p.closeOnEscape && e.which === 27) { // 27 === $.ui.keyCode.ESCAPE
+                                $("#" + $.jgrid.jqID(IDs.modalhead)).find(".ui-jqdialog-titlebar-close").focus().click();
+                                return false;
+                            }
+                        });
+                    }
+                    if (bQ) {
+                        $("#" + fid + "_query").bind('click', function () {
+                            $(".queryresult", fil).toggle();
+                            return false;
+                        });
+                    }
+                    if (p.stringResult === undefined) {
+                        // to provide backward compatibility, inferring stringResult value from multipleSearch
+                        p.stringResult = p.multipleSearch;
+                    }
+                    $("#" + fid + "_search").bind('click', function () {
+                        var fl = $("#" + fid),
+                            sdata = {}, res ,
+                            filters = fl.jqFilter('filterData');
+                        if (p.errorcheck) {
+                            fl[0].hideError();
+                            if (!p.showQuery) {
+                                fl.jqFilter('toSQLString');
+                            }
+                            if (fl[0].p.error) {
+                                fl[0].showError();
+                                return false;
+                            }
+                        }
+
+                        if (p.stringResult) {
+                            try {
+                                // xmlJsonClass or JSON.stringify
+                                res = xmlJsonClass.toJson(filters, '', '', false);
+                            } catch (e) {
+                                try {
+                                    res = JSON.stringify(filters);
+                                } catch (e2) {
+                                }
+                            }
+                            if (typeof(res) === "string") {
+                                sdata[p.sFilter] = res;
+                                $.each([p.sField, p.sValue, p.sOper], function () {
+                                    sdata[this] = "";
+                                });
+                            }
+                        } else {
+                            if (p.multipleSearch) {
+                                sdata[p.sFilter] = filters;
+                                $.each([p.sField, p.sValue, p.sOper], function () {
+                                    sdata[this] = "";
+                                });
+                            } else {
+                                sdata[p.sField] = filters.rules[0].field;
+                                sdata[p.sValue] = filters.rules[0].data;
+                                sdata[p.sOper] = filters.rules[0].op;
+                                sdata[p.sFilter] = "";
+                            }
+                        }
+                        $t.p.search = true;
+                        $.extend($t.p.postData, sdata);
+                        $($t).triggerHandler("jqGridFilterSearch");
+                        if ($.isFunction(p.onSearch)) {
+                            p.onSearch.call($t);
+                        }
+                        $($t).trigger("reloadGrid", [
+                            {page: 1}
+                        ]);
+                        if (p.closeAfterSearch) {
+                            $.jgrid.hideModal("#" + $.jgrid.jqID(IDs.themodal), {gb: "#gbox_" + $.jgrid.jqID($t.p.id), jqm: p.jqModal, onClose: p.onClose});
+                        }
+                        return false;
+                    });
+                    $("#" + fid + "_reset").bind('click', function () {
+                        var sdata = {},
+                            fl = $("#" + fid);
+                        $t.p.search = false;
+                        if (p.multipleSearch === false) {
+                            sdata[p.sField] = sdata[p.sValue] = sdata[p.sOper] = "";
+                        } else {
+                            sdata[p.sFilter] = "";
+                        }
+                        fl[0].resetFilter();
+                        if (found) {
+                            $(".ui-template", fil).val("default");
+                        }
+                        $.extend($t.p.postData, sdata);
+                        $($t).triggerHandler("jqGridFilterReset");
+                        if ($.isFunction(p.onReset)) {
+                            p.onReset.call($t);
+                        }
+                        $($t).trigger("reloadGrid", [
+                            {page: 1}
+                        ]);
+                        return false;
+                    });
+                    showFilter($("#" + fid));
+                    $(".fm-button:not(.ui-state-disabled)", fil).hover(
+                        function () {
+                            $(this).addClass('ui-state-hover');
+                        },
+                        function () {
+                            $(this).removeClass('ui-state-hover');
+                        }
+                    );
+                }
+            });
+        },
+        editGridRow: function (rowid, p) {
+            p = $.extend({
+                top: 0,
+                left: 0,
+                width: 300,
+                height: 'auto',
+                dataheight: 'auto',
+                modal: false,
+                overlay: 30,
+                drag: true,
+                resize: true,
+                url: null,
+                mtype: "POST",
+                clearAfterAdd: true,
+                closeAfterEdit: false,
+                reloadAfterSubmit: true,
+                onInitializeForm: null,
+                beforeInitData: null,
+                beforeShowForm: null,
+                afterShowForm: null,
+                beforeSubmit: null,
+                afterSubmit: null,
+                onclickSubmit: null,
+                afterComplete: null,
+                onclickPgButtons: null,
+                afterclickPgButtons: null,
+                editData: {},
+                recreateForm: false,
+                jqModal: true,
+                closeOnEscape: false,
+                addedrow: "first",
+                topinfo: '',
+                bottominfo: '',
+                saveicon: [],
+                closeicon: [],
+                savekey: [false, 13],
+                navkeys: [false, 38, 40],
+                checkOnSubmit: false,
+                checkOnUpdate: false,
+                _savedData: {},
+                processing: false,
+                onClose: null,
+                ajaxEditOptions: {},
+                serializeEditData: null,
+                viewPagerButtons: true
+            }, $.jgrid.edit, p || {});
+            rp_ge[$(this)[0].p.id] = p;
+            return this.each(function () {
+                var $t = this;
+                if (!$t.grid || !rowid) {
+                    return;
+                }
+                var gID = $t.p.id,
+                    frmgr = "FrmGrid_" + gID, frmtborg = "TblGrid_" + gID, frmtb = "#" + $.jgrid.jqID(frmtborg),
+                    IDs = {themodal: 'editmod' + gID, modalhead: 'edithd' + gID, modalcontent: 'editcnt' + gID, scrollelm: frmgr},
+                    onBeforeShow = $.isFunction(rp_ge[$t.p.id].beforeShowForm) ? rp_ge[$t.p.id].beforeShowForm : false,
+                    onAfterShow = $.isFunction(rp_ge[$t.p.id].afterShowForm) ? rp_ge[$t.p.id].afterShowForm : false,
+                    onBeforeInit = $.isFunction(rp_ge[$t.p.id].beforeInitData) ? rp_ge[$t.p.id].beforeInitData : false,
+                    onInitializeForm = $.isFunction(rp_ge[$t.p.id].onInitializeForm) ? rp_ge[$t.p.id].onInitializeForm : false,
+                    showFrm = true,
+                    maxCols = 1, maxRows = 0, postdata, extpost, newData, diff, frmoper;
+                frmgr = $.jgrid.jqID(frmgr);
+                if (rowid === "new") {
+                    rowid = "_empty";
+                    frmoper = "add";
+                    p.caption = rp_ge[$t.p.id].addCaption;
+                } else {
+                    p.caption = rp_ge[$t.p.id].editCaption;
+                    frmoper = "edit";
+                }
+                if (p.recreateForm === true && $("#" + $.jgrid.jqID(IDs.themodal)).html() !== null) {
+                    $("#" + $.jgrid.jqID(IDs.themodal)).remove();
+                }
+                var closeovrl = true;
+                if (p.checkOnUpdate && p.jqModal && !p.modal) {
+                    closeovrl = false;
+                }
+                function getFormData() {
+                    $(frmtb + " > tbody > tr > td > .FormElement").each(function () {
+                        var celm = $(".customelement", this);
+                        if (celm.length) {
+                            var elem = celm[0], nm = $(elem).attr('name');
+                            $.each($t.p.colModel, function () {
+                                if (this.name === nm && this.editoptions && $.isFunction(this.editoptions.custom_value)) {
+                                    try {
+                                        postdata[nm] = this.editoptions.custom_value.call($t, $("#" + $.jgrid.jqID(nm), frmtb), 'get');
+                                        if (postdata[nm] === undefined) {
+                                            throw "e1";
+                                        }
+                                    } catch (e) {
+                                        if (e === "e1") {
+                                            $.jgrid.info_dialog(jQuery.jgrid.errors.errcap, "function 'custom_value' " + $.jgrid.edit.msg.novalue, jQuery.jgrid.edit.bClose);
+                                        }
+                                        else {
+                                            $.jgrid.info_dialog(jQuery.jgrid.errors.errcap, e.message, jQuery.jgrid.edit.bClose);
+                                        }
+                                    }
+                                    return true;
+                                }
+                            });
+                        } else {
+                            switch ($(this).get(0).type) {
+                                case "checkbox":
+                                    if ($(this).is(":checked")) {
+                                        postdata[this.name] = $(this).val();
+                                    } else {
+                                        var ofv = $(this).attr("offval");
+                                        postdata[this.name] = ofv;
+                                    }
+                                    break;
+                                case "select-one":
+                                    postdata[this.name] = $("option:selected", this).val();
+                                    extpost[this.name] = $("option:selected", this).text();
+                                    break;
+                                case "select-multiple":
+                                    postdata[this.name] = $(this).val();
+                                    if (postdata[this.name]) {
+                                        postdata[this.name] = postdata[this.name].join(",");
+                                    }
+                                    else {
+                                        postdata[this.name] = "";
+                                    }
+                                    var selectedText = [];
+                                    $("option:selected", this).each(
+                                        function (i, selected) {
+                                            selectedText[i] = $(selected).text();
+                                        }
+                                    );
+                                    extpost[this.name] = selectedText.join(",");
+                                    break;
+                                case "password":
+                                case "text":
+                                case "textarea":
+                                case "button":
+                                    postdata[this.name] = $(this).val();
+
+                                    break;
+                            }
+                            if ($t.p.autoencode) {
+                                postdata[this.name] = $.jgrid.htmlEncode(postdata[this.name]);
+                            }
+                        }
+                    });
+                    return true;
+                }
+
+                function createData(rowid, obj, tb, maxcols) {
+                    var nm, hc, trdata, cnt = 0, tmp, dc, elc, retpos = [], ind = false,
+                        tdtmpl = "<td class='CaptionTD'>&#160;</td><td class='DataTD'>&#160;</td>", tmpl = "", i; //*2
+                    for (i = 1; i <= maxcols; i++) {
+                        tmpl += tdtmpl;
+                    }
+                    if (rowid != '_empty') {
+                        ind = $(obj).jqGrid("getInd", rowid);
+                    }
+                    $(obj.p.colModel).each(function (i) {
+                        nm = this.name;
+                        // hidden fields are included in the form
+                        if (this.editrules && this.editrules.edithidden === true) {
+                            hc = false;
+                        } else {
+                            hc = this.hidden === true ? true : false;
+                        }
+                        dc = hc ? "style='display:none'" : "";
+                        if (nm !== 'cb' && nm !== 'subgrid' && this.editable === true && nm !== 'rn') {
+                            if (ind === false) {
+                                tmp = "";
+                            } else {
+                                if (nm == obj.p.ExpandColumn && obj.p.treeGrid === true) {
+                                    tmp = $("td:eq(" + i + ")", obj.rows[ind]).text();
+                                } else {
+                                    try {
+                                        tmp = $.unformat.call(obj, $("td:eq(" + i + ")", obj.rows[ind]), {rowId: rowid, colModel: this}, i);
+                                    } catch (_) {
+                                        tmp = (this.edittype && this.edittype == "textarea") ? $("td:eq(" + i + ")", obj.rows[ind]).text() : $("td:eq(" + i + ")", obj.rows[ind]).html();
+                                    }
+                                    if (!tmp || tmp == "&nbsp;" || tmp == "&#160;" || (tmp.length == 1 && tmp.charCodeAt(0) == 160)) {
+                                        tmp = '';
+                                    }
+                                }
+                            }
+                            var opt = $.extend({}, this.editoptions || {}, {id: nm, name: nm}),
+                                frmopt = $.extend({}, {elmprefix: '', elmsuffix: '', rowabove: false, rowcontent: ''}, this.formoptions || {}),
+                                rp = parseInt(frmopt.rowpos, 10) || cnt + 1,
+                                cp = parseInt((parseInt(frmopt.colpos, 10) || 1) * 2, 10);
+                            if (rowid == "_empty" && opt.defaultValue) {
+                                tmp = $.isFunction(opt.defaultValue) ? opt.defaultValue.call($t) : opt.defaultValue;
+                            }
+                            if (!this.edittype) {
+                                this.edittype = "text";
+                            }
+                            if ($t.p.autoencode) {
+                                tmp = $.jgrid.htmlDecode(tmp);
+                            }
+                            elc = $.jgrid.createEl.call($t, this.edittype, opt, tmp, false, $.extend({}, $.jgrid.ajaxOptions, obj.p.ajaxSelectOptions || {}));
+                            if (tmp === "" && this.edittype == "checkbox") {
+                                tmp = $(elc).attr("offval");
+                            }
+                            if (tmp === "" && this.edittype == "select") {
+                                tmp = $("option:eq(0)", elc).text();
+                            }
+                            if (rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) {
+                                rp_ge[$t.p.id]._savedData[nm] = tmp;
+                            }
+                            $(elc).addClass("FormElement");
+                            if (this.edittype == 'text' || this.edittype == 'textarea') {
+                                $(elc).addClass("ui-widget-content ui-corner-all");
+                            }
+                            trdata = $(tb).find("tr[rowpos=" + rp + "]");
+                            if (frmopt.rowabove) {
+                                var newdata = $("<tr><td class='contentinfo' colspan='" + (maxcols * 2) + "'>" + frmopt.rowcontent + "</td></tr>");
+                                $(tb).append(newdata);
+                                newdata[0].rp = rp;
+                            }
+                            if (trdata.length === 0) {
+                                trdata = $("<tr " + dc + " rowpos='" + rp + "'></tr>").addClass("FormData").attr("id", "tr_" + nm);
+                                $(trdata).append(tmpl);
+                                $(tb).append(trdata);
+                                trdata[0].rp = rp;
+                            }
+                            $("td:eq(" + (cp - 2) + ")", trdata[0]).html(typeof frmopt.label === 'undefined' ? obj.p.colNames[i] : frmopt.label);
+                            $("td:eq(" + (cp - 1) + ")", trdata[0]).append(frmopt.elmprefix).append(elc).append(frmopt.elmsuffix);
+                            retpos[cnt] = i;
+                            cnt++;
+                        }
+                    });
+                    if (cnt > 0) {
+                        var idrow = $("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='" + (maxcols * 2 - 1) + "' class='DataTD'><input class='FormElement' id='id_g' type='text' name='" + obj.p.id + "_id' value='" + rowid + "'/></td></tr>");
+                        idrow[0].rp = cnt + 999;
+                        $(tb).append(idrow);
+                        if (rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) {
+                            rp_ge[$t.p.id]._savedData[obj.p.id + "_id"] = rowid;
+                        }
+                    }
+                    return retpos;
+                }
+
+                function fillData(rowid, obj, fmid) {
+                    var nm, cnt = 0, tmp, fld, opt, vl, vlc;
+                    if (rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) {
+                        rp_ge[$t.p.id]._savedData = {};
+                        rp_ge[$t.p.id]._savedData[obj.p.id + "_id"] = rowid;
+                    }
+                    var cm = obj.p.colModel;
+                    if (rowid == '_empty') {
+                        $(cm).each(function () {
+                            nm = this.name;
+                            opt = $.extend({}, this.editoptions || {});
+                            fld = $("#" + $.jgrid.jqID(nm), "#" + fmid);
+                            if (fld && fld.length && fld[0] !== null) {
+                                vl = "";
+                                if (opt.defaultValue) {
+                                    vl = $.isFunction(opt.defaultValue) ? opt.defaultValue.call($t) : opt.defaultValue;
+                                    if (fld[0].type == 'checkbox') {
+                                        vlc = vl.toLowerCase();
+                                        if (vlc.search(/(false|0|no|off|undefined)/i) < 0 && vlc !== "") {
+                                            fld[0].checked = true;
+                                            fld[0].defaultChecked = true;
+                                            fld[0].value = vl;
+                                        } else {
+                                            fld[0].checked = false;
+                                            fld[0].defaultChecked = false;
+                                        }
+                                    } else {
+                                        fld.val(vl);
+                                    }
+                                } else {
+                                    if (fld[0].type == 'checkbox') {
+                                        fld[0].checked = false;
+                                        fld[0].defaultChecked = false;
+                                        vl = $(fld).attr("offval");
+                                    } else if (fld[0].type && fld[0].type.substr(0, 6) == 'select') {
+                                        fld[0].selectedIndex = 0;
+                                    } else {
+                                        fld.val(vl);
+                                    }
+                                }
+                                if (rp_ge[$t.p.id].checkOnSubmit === true || rp_ge[$t.p.id].checkOnUpdate) {
+                                    rp_ge[$t.p.id]._savedData[nm] = vl;
+                                }
+                            }
+                        });
+                        $("#id_g", "#" + fmid).val(rowid);
+                        return;
+                    }
+                    var tre = $(obj).jqGrid("getInd", rowid, true);
+                    if (!tre) {
+                        return;
+                    }
+                    $('td[role="gridcell"]', tre).each(function (i) {
+                        nm = cm[i].name;
+                        // hidden fields are included in the form
+                        if (nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn' && cm[i].editable === true) {
+                            if (nm == obj.p.ExpandColumn && obj.p.treeGrid === true) {
+                                tmp = $(this).text();
+                            } else {
+                                try {
+                                    tmp = $.unformat.call(obj, $(this), {rowId: rowid, colModel: cm[i]}, i);
+                                } catch (_) {
+                                    tmp = cm[i].edittype == "textarea" ? $(this).text() : $(this).html();
+                                }
+                            }
+                            if ($t.p.autoencode) {
+                                tmp = $.jgrid.htmlDecode(tmp);
+                            }
+                            if (rp_ge[$t.p.id].checkOnSubmit === true || rp_ge[$t.p.id].checkOnUpdate) {
+                                rp_ge[$t.p.id]._savedData[nm] = tmp;
+                            }
+                            nm = $.jgrid.jqID(nm);
+                            switch (cm[i].edittype) {
+                                case "password":
+                                case "text":
+                                case "button" :
+                                case "image":
+                                case "textarea":
+                                    if (tmp == "&nbsp;" || tmp == "&#160;" || (tmp.length == 1 && tmp.charCodeAt(0) == 160)) {
+                                        tmp = '';
+                                    }
+                                    $("#" + nm, "#" + fmid).val(tmp);
+                                    break;
+                                case "select":
+                                    var opv = tmp.split(",");
+                                    opv = $.map(opv, function (n) {
+                                        return $.trim(n);
+                                    });
+                                    $("#" + nm + " option", "#" + fmid).each(function () {
+                                        if (!cm[i].editoptions.multiple && ($.trim(tmp) == $.trim($(this).text()) || opv[0] == $.trim($(this).text()) || opv[0] == $.trim($(this).val()))) {
+                                            this.selected = true;
+                                        } else if (cm[i].editoptions.multiple) {
+                                            if ($.inArray($.trim($(this).text()), opv) > -1 || $.inArray($.trim($(this).val()), opv) > -1) {
+                                                this.selected = true;
+                                            } else {
+                                                this.selected = false;
+                                            }
+                                        } else {
+                                            this.selected = false;
+                                        }
+                                    });
+                                    break;
+                                case "checkbox":
+                                    tmp = tmp + "";
+                                    if (cm[i].editoptions && cm[i].editoptions.value) {
+                                        var cb = cm[i].editoptions.value.split(":");
+                                        if (cb[0] == tmp) {
+                                            $("#" + nm, "#" + fmid)[$t.p.useProp ? 'prop' : 'attr']("checked", true);
+                                            $("#" + nm, "#" + fmid)[$t.p.useProp ? 'prop' : 'attr']("defaultChecked", true); //ie
+                                        } else {
+                                            $("#" + nm, "#" + fmid)[$t.p.useProp ? 'prop' : 'attr']("checked", false);
+                                            $("#" + nm, "#" + fmid)[$t.p.useProp ? 'prop' : 'attr']("defaultChecked", false); //ie
+                                        }
+                                    } else {
+                                        tmp = tmp.toLowerCase();
+                                        if (tmp.search(/(false|0|no|off|undefined)/i) < 0 && tmp !== "") {
+                                            $("#" + nm, "#" + fmid)[$t.p.useProp ? 'prop' : 'attr']("checked", true);
+                                            $("#" + nm, "#" + fmid)[$t.p.useProp ? 'prop' : 'attr']("defaultChecked", true); //ie
+                                        } else {
+                                            $("#" + nm, "#" + fmid)[$t.p.useProp ? 'prop' : 'attr']("checked", false);
+                                            $("#" + nm, "#" + fmid)[$t.p.useProp ? 'prop' : 'attr']("defaultChecked", false); //ie
+                                        }
+                                    }
+                                    break;
+                                case 'custom' :
+                                    try {
+                                        if (cm[i].editoptions && $.isFunction(cm[i].editoptions.custom_value)) {
+                                            cm[i].editoptions.custom_value.call($t, $("#" + nm, "#" + fmid), 'set', tmp);
+                                        } else {
+                                            throw "e1";
+                                        }
+                                    } catch (e) {
+                                        if (e == "e1") {
+                                            $.jgrid.info_dialog(jQuery.jgrid.errors.errcap, "function 'custom_value' " + $.jgrid.edit.msg.nodefined, jQuery.jgrid.edit.bClose);
+                                        }
+                                        else {
+                                            $.jgrid.info_dialog(jQuery.jgrid.errors.errcap, e.message, jQuery.jgrid.edit.bClose);
+                                        }
+                                    }
+                                    break;
+                            }
+                            cnt++;
+                        }
+                    });
+                    if (cnt > 0) {
+                        $("#id_g", frmtb).val(rowid);
+                    }
+                }
+
+                function setNulls() {
+                    $.each($t.p.colModel, function (i, n) {
+                        if (n.editoptions && n.editoptions.NullIfEmpty === true) {
+                            if (postdata.hasOwnProperty(n.name) && postdata[n.name] === "") {
+                                postdata[n.name] = 'null';
+                            }
+                        }
+                    });
+                }
+
+                function postIt() {
+                    var copydata, ret = [true, "", ""], onCS = {}, opers = $t.p.prmNames, idname, oper, key, selr, i;
+
+                    var retvals = $($t).triggerHandler("jqGridAddEditBeforeCheckValues", [$("#" + frmgr), frmoper]);
+                    if (retvals && typeof(retvals) === 'object') {
+                        postdata = retvals;
+                    }
+
+                    if ($.isFunction(rp_ge[$t.p.id].beforeCheckValues)) {
+                        retvals = rp_ge[$t.p.id].beforeCheckValues.call($t, postdata, $("#" + frmgr), postdata[$t.p.id + "_id"] == "_empty" ? opers.addoper : opers.editoper);
+                        if (retvals && typeof(retvals) === 'object') {
+                            postdata = retvals;
+                        }
+                    }
+                    for (key in postdata) {
+                        if (postdata.hasOwnProperty(key)) {
+                            ret = $.jgrid.checkValues.call($t, postdata[key], key, $t);
+                            if (ret[0] === false) {
+                                break;
+                            }
+                        }
+                    }
+                    setNulls();
+                    if (ret[0]) {
+                        onCS = $($t).triggerHandler("jqGridAddEditClickSubmit", [rp_ge[$t.p.id], postdata, frmoper]);
+                        if (onCS === undefined && $.isFunction(rp_ge[$t.p.id].onclickSubmit)) {
+                            onCS = rp_ge[$t.p.id].onclickSubmit.call($t, rp_ge[$t.p.id], postdata) || {};
+                        }
+                        ret = $($t).triggerHandler("jqGridAddEditBeforeSubmit", [postdata, $("#" + frmgr), frmoper]);
+                        if (ret === undefined) {
+                            ret = [true, "", ""];
+                        }
+                        if (ret[0] && $.isFunction(rp_ge[$t.p.id].beforeSubmit)) {
+                            ret = rp_ge[$t.p.id].beforeSubmit.call($t, postdata, $("#" + frmgr));
+                        }
+                    }
+
+                    if (ret[0] && !rp_ge[$t.p.id].processing) {
+                        rp_ge[$t.p.id].processing = true;
+                        $("#sData", frmtb + "_2").addClass('ui-state-active');
+                        oper = opers.oper;
+                        idname = opers.id;
+                        // we add to pos data array the action - the name is oper
+                        postdata[oper] = ($.trim(postdata[$t.p.id + "_id"]) == "_empty") ? opers.addoper : opers.editoper;
+                        if (postdata[oper] != opers.addoper) {
+                            postdata[idname] = postdata[$t.p.id + "_id"];
+                        } else {
+                            // check to see if we have allredy this field in the form and if yes lieve it
+                            if (postdata[idname] === undefined) {
+                                postdata[idname] = postdata[$t.p.id + "_id"];
+                            }
+                        }
+                        delete postdata[$t.p.id + "_id"];
+                        postdata = $.extend(postdata, rp_ge[$t.p.id].editData, onCS);
+                        if ($t.p.treeGrid === true) {
+                            if (postdata[oper] == opers.addoper) {
+                                selr = $($t).jqGrid("getGridParam", 'selrow');
+                                var tr_par_id = $t.p.treeGridModel == 'adjacency' ? $t.p.treeReader.parent_id_field : 'parent_id';
+                                postdata[tr_par_id] = selr;
+                            }
+                            for (i in $t.p.treeReader) {
+                                if ($t.p.treeReader.hasOwnProperty(i)) {
+                                    var itm = $t.p.treeReader[i];
+                                    if (postdata.hasOwnProperty(itm)) {
+                                        if (postdata[oper] == opers.addoper && i === 'parent_id_field') {
+                                            continue;
+                                        }
+                                        delete postdata[itm];
+                                    }
+                                }
+                            }
+                        }
+
+                        postdata[idname] = $.jgrid.stripPref($t.p.idPrefix, postdata[idname]);
+                        var ajaxOptions = $.extend({
+                            url: rp_ge[$t.p.id].url ? rp_ge[$t.p.id].url : $($t).jqGrid('getGridParam', 'editurl'),
+                            type: rp_ge[$t.p.id].mtype,
+                            data: $.isFunction(rp_ge[$t.p.id].serializeEditData) ? rp_ge[$t.p.id].serializeEditData.call($t, postdata) : postdata,
+                            complete: function (data, Status) {
+                                postdata[idname] = $t.p.idPrefix + postdata[idname];
+                                if (Status != "success") {
+                                    ret[0] = false;
+                                    ret[1] = $($t).triggerHandler("jqGridAddEditErrorTextFormat", [data, frmoper]);
+                                    if ($.isFunction(rp_ge[$t.p.id].errorTextFormat)) {
+                                        ret[1] = rp_ge[$t.p.id].errorTextFormat.call($t, data);
+                                    } else {
+                                        ret[1] = Status + " Status: '" + data.statusText + "'. Error code: " + data.status;
+                                    }
+                                } else {
+                                    // data is posted successful
+                                    // execute aftersubmit with the returned data from server
+                                    ret = $($t).triggerHandler("jqGridAddEditAfterSubmit", [data, postdata, frmoper]);
+                                    if (ret === undefined) {
+                                        ret = [true, "", ""];
+                                    }
+                                    if (ret[0] && $.isFunction(rp_ge[$t.p.id].afterSubmit)) {
+                                        ret = rp_ge[$t.p.id].afterSubmit.call($t, data, postdata);
+                                    }
+                                }
+                                if (ret[0] === false) {
+                                    $("#FormError>td", frmtb).html(ret[1]);
+                                    $("#FormError", frmtb).show();
+                                } else {
+                                    // remove some values if formattaer select or checkbox
+                                    $.each($t.p.colModel, function () {
+                                        if (extpost[this.name] && this.formatter && this.formatter == 'select') {
+                                            try {
+                                                delete extpost[this.name];
+                                            } catch (e) {
+                                            }
+                                        }
+                                    });
+                                    postdata = $.extend(postdata, extpost);
+                                    if ($t.p.autoencode) {
+                                        $.each(postdata, function (n, v) {
+                                            postdata[n] = $.jgrid.htmlDecode(v);
+                                        });
+                                    }
+                                    //rp_ge[$t.p.id].reloadAfterSubmit = rp_ge[$t.p.id].reloadAfterSubmit && $t.p.datatype != "local";
+                                    // the action is add
+                                    if (postdata[oper] == opers.addoper) {
+                                        //id processing
+                                        // user not set the id ret[2]
+                                        if (!ret[2]) {
+                                            ret[2] = $.jgrid.randId();
+                                        }
+                                        postdata[idname] = ret[2];
+                                        if (rp_ge[$t.p.id].closeAfterAdd) {
+                                            if (rp_ge[$t.p.id].reloadAfterSubmit) {
+                                                $($t).trigger("reloadGrid");
+                                            }
+                                            else {
+                                                if ($t.p.treeGrid === true) {
+                                                    $($t).jqGrid("addChildNode", ret[2], selr, postdata);
+                                                } else {
+                                                    $($t).jqGrid("addRowData", ret[2], postdata, p.addedrow);
+                                                    $($t).jqGrid("setSelection", ret[2]);
+                                                }
+                                            }
+                                            $.jgrid.hideModal("#" + $.jgrid.jqID(IDs.themodal), {gb: "#gbox_" + $.jgrid.jqID(gID), jqm: p.jqModal, onClose: rp_ge[$t.p.id].onClose});
+                                        } else if (rp_ge[$t.p.id].clearAfterAdd) {
+                                            if (rp_ge[$t.p.id].reloadAfterSubmit) {
+                                                $($t).trigger("reloadGrid");
+                                            }
+                                            else {
+                                                if ($t.p.treeGrid === true) {
+                                                    $($t).jqGrid("addChildNode", ret[2], selr, postdata);
+                                                } else {
+                                                    $($t).jqGrid("addRowData", ret[2], postdata, p.addedrow);
+                                                }
+                                            }
+                                            fillData("_empty", $t, frmgr);
+                                        } else {
+                                            if (rp_ge[$t.p.id].reloadAfterSubmit) {
+                                                $($t).trigger("reloadGrid");
+                                            }
+                                            else {
+                                                if ($t.p.treeGrid === true) {
+                                                    $($t).jqGrid("addChildNode", ret[2], selr, postdata);
+                                                } else {
+                                                    $($t).jqGrid("addRowData", ret[2], postdata, p.addedrow);
+                                                }
+                                            }
+                                        }
+                                    } else {
+                                        // the action is update
+                                        if (rp_ge[$t.p.id].reloadAfterSubmit) {
+                                            $($t).trigger("reloadGrid");
+                                            if (!rp_ge[$t.p.id].closeAfterEdit) {
+                                                setTimeout(function () {
+                                                    $($t).jqGrid("setSelection", postdata[idname]);
+                                                }, 1000);
+                                            }
+                                        } else {
+                                            if ($t.p.treeGrid === true) {
+                                                $($t).jqGrid("setTreeRow", postdata[idname], postdata);
+                                            } else {
+                                                $($t).jqGrid("setRowData", postdata[idname], postdata);
+                                            }
+                                        }
+                                        if (rp_ge[$t.p.id].closeAfterEdit) {
+                                            $.jgrid.hideModal("#" + $.jgrid.jqID(IDs.themodal), {gb: "#gbox_" + $.jgrid.jqID(gID), jqm: p.jqModal, onClose: rp_ge[$t.p.id].onClose});
+                                        }
+                                    }
+                                    if ($.isFunction(rp_ge[$t.p.id].afterComplete)) {
+                                        copydata = data;
+                                        setTimeout(function () {
+                                            $($t).triggerHandler("jqGridAddEditAfterComplete", [copydata, postdata, $("#" + frmgr), frmoper]);
+                                            rp_ge[$t.p.id].afterComplete.call($t, copydata, postdata, $("#" + frmgr));
+                                            copydata = null;
+                                        }, 500);
+                                    }
+                                    if (rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) {
+                                        $("#" + frmgr).data("disabled", false);
+                                        if (rp_ge[$t.p.id]._savedData[$t.p.id + "_id"] != "_empty") {
+                                            for (var key in rp_ge[$t.p.id]._savedData) {
+                                                if (postdata[key]) {
+                                                    rp_ge[$t.p.id]._savedData[key] = postdata[key];
+                                                }
+                                            }
+                                        }
+                                    }
+                                }
+                                rp_ge[$t.p.id].processing = false;
+                                $("#sData", frmtb + "_2").removeClass('ui-state-active');
+                                try {
+                                    $(':input:visible', "#" + frmgr)[0].focus();
+                                } catch (e) {
+                                }
+                            }
+                        }, $.jgrid.ajaxOptions, rp_ge[$t.p.id].ajaxEditOptions);
+
+                        if (!ajaxOptions.url && !rp_ge[$t.p.id].useDataProxy) {
+                            if ($.isFunction($t.p.dataProxy)) {
+                                rp_ge[$t.p.id].useDataProxy = true;
+                            } else {
+                                ret[0] = false;
+                                ret[1] += " " + $.jgrid.errors.nourl;
+                            }
+                        }
+                        if (ret[0]) {
+                            if (rp_ge[$t.p.id].useDataProxy) {
+                                var dpret = $t.p.dataProxy.call($t, ajaxOptions, "set_" + $t.p.id);
+                                if (typeof(dpret) == "undefined") {
+                                    dpret = [true, ""];
+                                }
+                                if (dpret[0] === false) {
+                                    ret[0] = false;
+                                    ret[1] = dpret[1] || "Error deleting the selected row!";
+                                } else {
+                                    if (ajaxOptions.data.oper == opers.addoper && rp_ge[$t.p.id].closeAfterAdd) {
+                                        $.jgrid.hideModal("#" + $.jgrid.jqID(IDs.themodal), {gb: "#gbox_" + $.jgrid.jqID(gID), jqm: p.jqModal, onClose: rp_ge[$t.p.id].onClose});
+                                    }
+                                    if (ajaxOptions.data.oper == opers.editoper && rp_ge[$t.p.id].closeAfterEdit) {
+                                        $.jgrid.hideModal("#" + $.jgrid.jqID(IDs.themodal), {gb: "#gbox_" + $.jgrid.jqID(gID), jqm: p.jqModal, onClose: rp_ge[$t.p.id].onClose});
+                                    }
+                                }
+                            } else {
+                                $.ajax(ajaxOptions);
+                            }
+                        }
+                    }
+                    if (ret[0] === false) {
+                        $("#FormError>td", frmtb).html(ret[1]);
+                        $("#FormError", frmtb).show();
+                        // return;
+                    }
+                }
+
+                function compareData(nObj, oObj) {
+                    var ret = false, key;
+                    for (key in nObj) {
+                        if (nObj[key] != oObj[key]) {
+                            ret = true;
+                            break;
+                        }
+                    }
+                    return ret;
+                }
+
+                function checkUpdates() {
+                    var stat = true;
+                    $("#FormError", frmtb).hide();
+                    if (rp_ge[$t.p.id].checkOnUpdate) {
+                        postdata = {};
+                        extpost = {};
+                        getFormData();
+                        newData = $.extend({}, postdata, extpost);
+                        diff = compareData(newData, rp_ge[$t.p.id]._savedData);
+                        if (diff) {
+                            $("#" + frmgr).data("disabled", true);
+                            $(".confirm", "#" + IDs.themodal).show();
+                            stat = false;
+                        }
+                    }
+                    return stat;
+                }
+
+                function restoreInline() {
+                    if (rowid !== "_empty" && typeof($t.p.savedRow) !== "undefined" && $t.p.savedRow.length > 0 && $.isFunction($.fn.jqGrid.restoreRow)) {
+                        for (var i = 0; i < $t.p.savedRow.length; i++) {
+                            if ($t.p.savedRow[i].id == rowid) {
+                                $($t).jqGrid('restoreRow', rowid);
+                                break;
+                            }
+                        }
+                    }
+                }
+
+                function updateNav(cr, totr) {
+                    if (cr === 0) {
+                        $("#pData", frmtb + "_2").addClass('ui-state-disabled');
+                    } else {
+                        $("#pData", frmtb + "_2").removeClass('ui-state-disabled');
+                    }
+                    if (cr == totr) {
+                        $("#nData", frmtb + "_2").addClass('ui-state-disabled');
+                    } else {
+                        $("#nData", frmtb + "_2").removeClass('ui-state-disabled');
+                    }
+                }
+
+                function getCurrPos() {
+                    var rowsInGrid = $($t).jqGrid("getDataIDs"),
+                        selrow = $("#id_g", frmtb).val(),
+                        pos = $.inArray(selrow, rowsInGrid);
+                    return [pos, rowsInGrid];
+                }
+
+                if ($("#" + $.jgrid.jqID(IDs.themodal)).html() !== null) {
+                    showFrm = $($t).triggerHandler("jqGridAddEditBeforeInitData", [$("#" + $.jgrid.jqID(frmgr))]);
+                    if (typeof(showFrm) == "undefined") {
+                        showFrm = true;
+                    }
+                    if (showFrm && onBeforeInit) {
+                        showFrm = onBeforeInit.call($t, $("#" + frmgr));
+                    }
+                    if (showFrm === false) {
+                        return;
+                    }
+                    restoreInline();
+                    $(".ui-jqdialog-title", "#" + $.jgrid.jqID(IDs.modalhead)).html(p.caption);
+                    $("#FormError", frmtb).hide();
+                    if (rp_ge[$t.p.id].topinfo) {
+                        $(".topinfo", frmtb).html(rp_ge[$t.p.id].topinfo);
+                        $(".tinfo", frmtb).show();
+                    } else {
+                        $(".tinfo", frmtb).hide();
+                    }
+                    if (rp_ge[$t.p.id].bottominfo) {
+                        $(".bottominfo", frmtb + "_2").html(rp_ge[$t.p.id].bottominfo);
+                        $(".binfo", frmtb + "_2").show();
+                    } else {
+                        $(".binfo", frmtb + "_2").hide();
+                    }
+                    // filldata
+                    fillData(rowid, $t, frmgr);
+                    ///
+                    if (rowid == "_empty" || !rp_ge[$t.p.id].viewPagerButtons) {
+                        $("#pData, #nData", frmtb + "_2").hide();
+                    } else {
+                        $("#pData, #nData", frmtb + "_2").show();
+                    }
+                    if (rp_ge[$t.p.id].processing === true) {
+                        rp_ge[$t.p.id].processing = false;
+                        $("#sData", frmtb + "_2").removeClass('ui-state-active');
+                    }
+                    if ($("#" + frmgr).data("disabled") === true) {
+                        $(".confirm", "#" + $.jgrid.jqID(IDs.themodal)).hide();
+                        $("#" + frmgr).data("disabled", false);
+                    }
+                    $($t).triggerHandler("jqGridAddEditBeforeShowForm", [$("#" + frmgr), frmoper]);
+                    if (onBeforeShow) {
+                        onBeforeShow.call($t, $("#" + frmgr));
+                    }
+                    $("#" + $.jgrid.jqID(IDs.themodal)).data("onClose", rp_ge[$t.p.id].onClose);
+                    $.jgrid.viewModal("#" + $.jgrid.jqID(IDs.themodal), {gbox: "#gbox_" + $.jgrid.jqID(gID), jqm: p.jqModal, jqM: false, overlay: p.overlay, modal: p.modal});
+                    if (!closeovrl) {
+                        $(".jqmOverlay").click(function () {
+                            if (!checkUpdates()) {
+                                return false;
+                            }
+                            $.jgrid.hideModal("#" + $.jgrid.jqID(IDs.themodal), {gb: "#gbox_" + $.jgrid.jqID(gID), jqm: p.jqModal, onClose: rp_ge[$t.p.id].onClose});
+                            return false;
+                        });
+                    }
+                    $($t).triggerHandler("jqGridAddEditAfterShowForm", [$("#" + frmgr), frmoper]);
+                    if (onAfterShow) {
+                        onAfterShow.call($t, $("#" + frmgr));
+                    }
+                } else {
+                    var dh = isNaN(p.dataheight) ? p.dataheight : p.dataheight + "px",
+                        frm = $("<form name='FormPost' id='" + frmgr + "' class='FormGrid' onSubmit='return false;' style='width:100%;overflow:auto;position:relative;height:" + dh + ";'></form>").data("disabled", false),
+                        tbl = $("<table id='" + frmtborg + "' class='EditTable' cellspacing='0' cellpadding='0' border='0'><tbody></tbody></table>");
+                    showFrm = $($t).triggerHandler("jqGridAddEditBeforeInitData", [$("#" + frmgr), frmoper]);
+                    if (typeof(showFrm) == "undefined") {
+                        showFrm = true;
+                    }
+                    if (showFrm && onBeforeInit) {
+                        showFrm = onBeforeInit.call($t, $("#" + frmgr));
+                    }
+                    if (showFrm === false) {
+                        return;
+                    }
+                    restoreInline();
+                    $($t.p.colModel).each(function () {
+                        var fmto = this.formoptions;
+                        maxCols = Math.max(maxCols, fmto ? fmto.colpos || 0 : 0);
+                        maxRows = Math.max(maxRows, fmto ? fmto.rowpos || 0 : 0);
+                    });
+                    $(frm).append(tbl);
+                    var flr = $("<tr id='FormError' style='display:none'><td class='ui-state-error' colspan='" + (maxCols * 2) + "'></td></tr>");
+                    flr[0].rp = 0;
+                    $(tbl).append(flr);
+                    //topinfo
+                    flr = $("<tr style='display:none' class='tinfo'><td class='topinfo' colspan='" + (maxCols * 2) + "'>" + rp_ge[$t.p.id].topinfo + "</td></tr>");
+                    flr[0].rp = 0;
+                    $(tbl).append(flr);
+                    // set the id.
+                    // use carefull only to change here colproperties.
+                    // create data
+                    var rtlb = $t.p.direction == "rtl" ? true : false,
+                        bp = rtlb ? "nData" : "pData",
+                        bn = rtlb ? "pData" : "nData";
+                    createData(rowid, $t, tbl, maxCols);
+                    // buttons at footer
+                    var bP = "<a href='javascript:void(0)' id='" + bp + "' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></a>",
+                        bN = "<a href='javascript:void(0)' id='" + bn + "' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></a>",
+                        bS = "<a href='javascript:void(0)' id='sData' class='fm-button ui-state-default ui-corner-all'>" + p.bSubmit + "</a>",
+                        bC = "<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>" + p.bCancel + "</a>";
+                    var bt = "<table border='0' cellspacing='0' cellpadding='0' class='EditTable' id='" + frmtborg + "_2'><tbody><tr><td colspan='2'><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr id='Act_Buttons'><td class='navButton'>" + (rtlb ? bN + bP : bP + bN) + "</td><td class='EditButton'>" + bS + bC + "</td></tr>";
+                    bt += "<tr style='display:none' class='binfo'><td class='bottominfo' colspan='2'>" + rp_ge[$t.p.id].bottominfo + "</td></tr>";
+                    bt += "</tbody></table>";
+                    if (maxRows > 0) {
+                        var sd = [];
+                        $.each($(tbl)[0].rows, function (i, r) {
+                            sd[i] = r;
+                        });
+                        sd.sort(function (a, b) {
+                            if (a.rp > b.rp) {
+                                return 1;
+                            }
+                            if (a.rp < b.rp) {
+                                return -1;
+                            }
+                            return 0;
+                        });
+                        $.each(sd, function (index, row) {
+                            $('tbody', tbl).append(row);
+                        });
+                    }
+                    p.gbox = "#gbox_" + $.jgrid.jqID(gID);
+                    var cle = false;
+                    if (p.closeOnEscape === true) {
+                        p.closeOnEscape = false;
+                        cle = true;
+                    }
+                    var tms = $("<span></span>").append(frm).append(bt);
+                    $.jgrid.createModal(IDs, tms, p, "#gview_" + $.jgrid.jqID($t.p.id), $("#gbox_" + $.jgrid.jqID($t.p.id))[0]);
+                    if (rtlb) {
+                        $("#pData, #nData", frmtb + "_2").css("float", "right");
+                        $(".EditButton", frmtb + "_2").css("text-align", "left");
+                    }
+                    if (rp_ge[$t.p.id].topinfo) {
+                        $(".tinfo", frmtb).show();
+                    }
+                    if (rp_ge[$t.p.id].bottominfo) {
+                        $(".binfo", frmtb + "_2").show();
+                    }
+                    tms = null;
+                    bt = null;
+                    $("#" + $.jgrid.jqID(IDs.themodal)).keydown(function (e) {
+                        var wkey = e.target;
+                        if ($("#" + frmgr).data("disabled") === true) {
+                            return false;
+                        }//??
+                        if (rp_ge[$t.p.id].savekey[0] === true && e.which == rp_ge[$t.p.id].savekey[1]) { // save
+                            if (wkey.tagName != "TEXTAREA") {
+                                $("#sData", frmtb + "_2").trigger("click");
+                                return false;
+                            }
+                        }
+                        if (e.which === 27) {
+                            if (!checkUpdates()) {
+                                return false;
+                            }
+                            if (cle) {
+                                $.jgrid.hideModal(this, {gb: p.gbox, jqm: p.jqModal, onClose: rp_ge[$t.p.id].onClose});
+                            }
+                            return false;
+                        }
+                        if (rp_ge[$t.p.id].navkeys[0] === true) {
+                            if ($("#id_g", frmtb).val() == "_empty") {
+                                return true;
+                            }
+                            if (e.which == rp_ge[$t.p.id].navkeys[1]) { //up
+                                $("#pData", frmtb + "_2").trigger("click");
+                                return false;
+                            }
+                            if (e.which == rp_ge[$t.p.id].navkeys[2]) { //down
+                                $("#nData", frmtb + "_2").trigger("click");
+                                return false;
+                            }
+                        }
+                    });
+                    if (p.checkOnUpdate) {
+                        $("a.ui-jqdialog-titlebar-close span", "#" + $.jgrid.jqID(IDs.themodal)).removeClass("jqmClose");
+                        $("a.ui-jqdialog-titlebar-close", "#" + $.jgrid.jqID(IDs.themodal)).unbind("click")
+                            .click(function () {
+                                if (!checkUpdates()) {
+                                    return false;
+                                }
+                                $.jgrid.hideModal("#" + $.jgrid.jqID(IDs.themodal), {gb: "#gbox_" + $.jgrid.jqID(gID), jqm: p.jqModal, onClose: rp_ge[$t.p.id].onClose});
+                                return false;
+                            });
+                    }
+                    p.saveicon = $.extend([true, "left", "ui-icon-disk"], p.saveicon);
+                    p.closeicon = $.extend([true, "left", "ui-icon-close"], p.closeicon);
+                    // beforeinitdata after creation of the form
+                    if (p.saveicon[0] === true) {
+                        $("#sData", frmtb + "_2").addClass(p.saveicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left')
+                            .append("<span class='ui-icon " + p.saveicon[2] + "'></span>");
+                    }
+                    if (p.closeicon[0] === true) {
+                        $("#cData", frmtb + "_2").addClass(p.closeicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left')
+                            .append("<span class='ui-icon " + p.closeicon[2] + "'></span>");
+                    }
+                    if (rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) {
+                        bS = "<a href='javascript:void(0)' id='sNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>" + p.bYes + "</a>";
+                        bN = "<a href='javascript:void(0)' id='nNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>" + p.bNo + "</a>";
+                        bC = "<a href='javascript:void(0)' id='cNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>" + p.bExit + "</a>";
+                        var ii, zI = p.zIndex || 999;
+                        zI++;
+                        if ($.browser.msie && $.browser.version == 6) {
+                            ii = '<iframe style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=\'0\');" src="javascript:false;"></iframe>';
+                        } else {
+                            ii = "";
+                        }
+                        $("<div class='ui-widget-overlay jqgrid-overlay confirm' style='z-index:" + zI + ";display:none;'>&#160;" + ii + "</div><div class='confirm ui-widget-content ui-jqconfirm' style='z-index:" + (zI + 1) + "'>" + p.saveData + "<br/><br/>" + bS + bN + bC + "</div>").insertAfter("#" + frmgr);
+                        $("#sNew", "#" + $.jgrid.jqID(IDs.themodal)).click(function () {
+                            postIt();
+                            $("#" + frmgr).data("disabled", false);
+                            $(".confirm", "#" + $.jgrid.jqID(IDs.themodal)).hide();
+                            return false;
+                        });
+                        $("#nNew", "#" + $.jgrid.jqID(IDs.themodal)).click(function () {
+                            $(".confirm", "#" + $.jgrid.jqID(IDs.themodal)).hide();
+                            $("#" + frmgr).data("disabled", false);
+                            setTimeout(function () {
+                                $(":input", "#" + frmgr)[0].focus();
+                            }, 0);
+                            return false;
+                        });
+                        $("#cNew", "#" + $.jgrid.jqID(IDs.themodal)).click(function () {
+                            $(".confirm", "#" + $.jgrid.jqID(IDs.themodal)).hide();
+                            $("#" + frmgr).data("disabled", false);
+                            $.jgrid.hideModal("#" + $.jgrid.jqID(IDs.themodal), {gb: "#gbox_" + $.jgrid.jqID(gID), jqm: p.jqModal, onClose: rp_ge[$t.p.id].onClose});
+                            return false;
+                        });
+                    }
+                    // here initform - only once
+                    $($t).triggerHandler("jqGridAddEditInitializeForm", [$("#" + frmgr), frmoper]);
+                    if (onInitializeForm) {
+                        onInitializeForm.call($t, $("#" + frmgr));
+                    }
+                    if (rowid == "_empty" || !rp_ge[$t.p.id].viewPagerButtons) {
+                        $("#pData,#nData", frmtb + "_2").hide();
+                    } else {
+                        $("#pData,#nData", frmtb + "_2").show();
+                    }
+                    $($t).triggerHandler("jqGridAddEditBeforeShowForm", [$("#" + frmgr), frmoper]);
+                    if (onBeforeShow) {
+                        onBeforeShow.call($t, $("#" + frmgr));
+                    }
+                    $("#" + $.jgrid.jqID(IDs.themodal)).data("onClose", rp_ge[$t.p.id].onClose);
+                    $.jgrid.viewModal("#" + $.jgrid.jqID(IDs.themodal), {gbox: "#gbox_" + $.jgrid.jqID(gID), jqm: p.jqModal, overlay: p.overlay, modal: p.modal});
+                    if (!closeovrl) {
+                        $(".jqmOverlay").click(function () {
+                            if (!checkUpdates()) {
+                                return false;
+                            }
+                            $.jgrid.hideModal("#" + $.jgrid.jqID(IDs.themodal), {gb: "#gbox_" + $.jgrid.jqID(gID), jqm: p.jqModal, onClose: rp_ge[$t.p.id].onClose});
+                            return false;
+                        });
+                    }
+                    $($t).triggerHandler("jqGridAddEditAfterShowForm", [$("#" + frmgr), frmoper]);
+                    if (onAfterShow) {
+                        onAfterShow.call($t, $("#" + frmgr));
+                    }
+                    $(".fm-button", "#" + $.jgrid.jqID(IDs.themodal)).hover(
+                        function () {
+                            $(this).addClass('ui-state-hover');
+                        },
+                        function () {
+                            $(this).removeClass('ui-state-hover');
+                        }
+                    );
+                    $("#sData", frmtb + "_2").click(function () {
+                        postdata = {};
+                        extpost = {};
+                        $("#FormError", frmtb).hide();
+                        // all depend on ret array
+                        //ret[0] - succes
+                        //ret[1] - msg if not succes
+                        //ret[2] - the id  that will be set if reload after submit false
+                        getFormData();
+                        if (postdata[$t.p.id + "_id"] == "_empty") {
+                            postIt();
+                        }
+                        else if (p.checkOnSubmit === true) {
+                            newData = $.extend({}, postdata, extpost);
+                            diff = compareData(newData, rp_ge[$t.p.id]._savedData);
+                            if (diff) {
+                                $("#" + frmgr).data("disabled", true);
+                                $(".confirm", "#" + $.jgrid.jqID(IDs.themodal)).show();
+                            } else {
+                                postIt();
+                            }
+                        } else {
+                            postIt();
+                        }
+                        return false;
+                    });
+                    $("#cData", frmtb + "_2").click(function () {
+                        if (!checkUpdates()) {
+                            return false;
+                        }
+                        $.jgrid.hideModal("#" + $.jgrid.jqID(IDs.themodal), {gb: "#gbox_" + $.jgrid.jqID(gID), jqm: p.jqModal, onClose: rp_ge[$t.p.id].onClose});
+                        return false;
+                    });
+                    $("#nData", frmtb + "_2").click(function () {
+                        if (!checkUpdates()) {
+                            return false;
+                        }
+                        $("#FormError", frmtb).hide();
+                        var npos = getCurrPos();
+                        npos[0] = parseInt(npos[0], 10);
+                        if (npos[0] != -1 && npos[1][npos[0] + 1]) {
+                            $($t).triggerHandler("jqGridAddEditClickPgButtons", ['next', $("#" + frmgr), npos[1][npos[0]]]);
+                            if ($.isFunction(p.onclickPgButtons)) {
+                                p.onclickPgButtons.call($t, 'next', $("#" + frmgr), npos[1][npos[0]]);
+                            }
+                            fillData(npos[1][npos[0] + 1], $t, frmgr);
+                            $($t).jqGrid("setSelection", npos[1][npos[0] + 1]);
+                            $($t).triggerHandler("jqGridAddEditAfterClickPgButtons", ['next', $("#" + frmgr), npos[1][npos[0]]]);
+                            if ($.isFunction(p.afterclickPgButtons)) {
+                                p.afterclickPgButtons.call($t, 'next', $("#" + frmgr), npos[1][npos[0] + 1]);
+                            }
+                            updateNav(npos[0] + 1, npos[1].length - 1);
+                        }
+                        return false;
+                    });
+                    $("#pData", frmtb + "_2").click(function () {
+                        if (!checkUpdates()) {
+                            return false;
+                        }
+                        $("#FormError", frmtb).hide();
+                        var ppos = getCurrPos();
+                        if (ppos[0] != -1 && ppos[1][ppos[0] - 1]) {
+                            $($t).triggerHandler("jqGridAddEditClickPgButtons", ['prev', $("#" + frmgr), ppos[1][ppos[0]]]);
+                            if ($.isFunction(p.onclickPgButtons)) {
+                                p.onclickPgButtons.call($t, 'prev', $("#" + frmgr), ppos[1][ppos[0]]);
+                            }
+                            fillData(ppos[1][ppos[0] - 1], $t, frmgr);
+                            $($t).jqGrid("setSelection", ppos[1][ppos[0] - 1]);
+                            $($t).triggerHandler("jqGridAddEditAfterClickPgButtons", ['prev', $("#" + frmgr), ppos[1][ppos[0]]]);
+                            if ($.isFunction(p.afterclickPgButtons)) {
+                                p.afterclickPgButtons.call($t, 'prev', $("#" + frmgr), ppos[1][ppos[0] - 1]);
+                            }
+                            updateNav(ppos[0] - 1, ppos[1].length - 1);
+                        }
+                        return false;
+                    });
+                }
+                var posInit = getCurrPos();
+                updateNav(posInit[0], posInit[1].length - 1);
+
+            });
+        },
+        viewGridRow: function (rowid, p) {
+            p = $.extend({
+                top: 0,
+                left: 0,
+                width: 0,
+                height: 'auto',
+                dataheight: 'auto',
+                modal: false,
+                overlay: 30,
+                drag: true,
+                resize: true,
+                jqModal: true,
+                closeOnEscape: false,
+                labelswidth: '30%',
+                closeicon: [],
+                navkeys: [false, 38, 40],
+                onClose: null,
+                beforeShowForm: null,
+                beforeInitData: null,
+                viewPagerButtons: true
+            }, $.jgrid.view, p || {});
+            return this.each(function () {
+                var $t = this;
+                if (!$t.grid || !rowid) {
+                    return;
+                }
+                var gID = $t.p.id,
+                    frmgr = "ViewGrid_" + $.jgrid.jqID(gID), frmtb = "ViewTbl_" + $.jgrid.jqID(gID),
+                    frmgr_id = "ViewGrid_" + gID, frmtb_id = "ViewTbl_" + gID,
+                    IDs = {themodal: 'viewmod' + gID, modalhead: 'viewhd' + gID, modalcontent: 'viewcnt' + gID, scrollelm: frmgr},
+                    onBeforeInit = $.isFunction(p.beforeInitData) ? p.beforeInitData : false,
+                    showFrm = true,
+                    maxCols = 1, maxRows = 0;
+
+                function focusaref() { //Sfari 3 issues
+                    if (p.closeOnEscape === true || p.navkeys[0] === true) {
+                        setTimeout(function () {
+                            $(".ui-jqdialog-titlebar-close", "#" + $.jgrid.jqID(IDs.modalhead)).focus();
+                        }, 0);
+                    }
+                }
+
+                function createData(rowid, obj, tb, maxcols) {
+                    var nm, hc, trdata, cnt = 0, tmp, dc, retpos = [], ind = false,
+                        tdtmpl = "<td class='CaptionTD form-view-label ui-widget-content' width='" + p.labelswidth + "'>&#160;</td><td class='DataTD form-view-data ui-helper-reset ui-widget-content'>&#160;</td>", tmpl = "",
+                        tdtmpl2 = "<td class='CaptionTD form-view-label ui-widget-content'>&#160;</td><td class='DataTD form-view-data ui-widget-content'>&#160;</td>",
+                        fmtnum = ['integer', 'number', 'currency'], max1 = 0, max2 = 0 , maxw, setme, viewfld;
+                    for (var i = 1; i <= maxcols; i++) {
+                        tmpl += i == 1 ? tdtmpl : tdtmpl2;
+                    }
+                    // find max number align rigth with property formatter
+                    $(obj.p.colModel).each(function () {
+                        if (this.editrules && this.editrules.edithidden === true) {
+                            hc = false;
+                        } else {
+                            hc = this.hidden === true ? true : false;
+                        }
+                        if (!hc && this.align === 'right') {
+                            if (this.formatter && $.inArray(this.formatter, fmtnum) !== -1) {
+                                max1 = Math.max(max1, parseInt(this.width, 10));
+                            } else {
+                                max2 = Math.max(max2, parseInt(this.width, 10));
+                            }
+                        }
+                    });
+                    maxw = max1 !== 0 ? max1 : max2 !== 0 ? max2 : 0;
+                    ind = $(obj).jqGrid("getInd", rowid);
+                    $(obj.p.colModel).each(function (i) {
+                        nm = this.name;
+                        setme = false;
+                        // hidden fields are included in the form
+                        if (this.editrules && this.editrules.edithidden === true) {
+                            hc = false;
+                        } else {
+                            hc = this.hidden === true ? true : false;
+                        }
+                        dc = hc ? "style='display:none'" : "";
+                        viewfld = (typeof this.viewable != 'boolean') ? true : this.viewable;
+                        if (nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn' && viewfld) {
+                            if (ind === false) {
+                                tmp = "";
+                            } else {
+                                if (nm == obj.p.ExpandColumn && obj.p.treeGrid === true) {
+                                    tmp = $("td:eq(" + i + ")", obj.rows[ind]).text();
+                                } else {
+                                    tmp = $("td:eq(" + i + ")", obj.rows[ind]).html();
+                                }
+                            }
+                            setme = this.align === 'right' && maxw !== 0 ? true : false;
+                            var opt = $.extend({}, this.editoptions || {}, {id: nm, name: nm}),
+                                frmopt = $.extend({}, {rowabove: false, rowcontent: ''}, this.formoptions || {}),
+                                rp = parseInt(frmopt.rowpos, 10) || cnt + 1,
+                                cp = parseInt((parseInt(frmopt.colpos, 10) || 1) * 2, 10);
+                            if (frmopt.rowabove) {
+                                var newdata = $("<tr><td class='contentinfo' colspan='" + (maxcols * 2) + "'>" + frmopt.rowcontent + "</td></tr>");
+                                $(tb).append(newdata);
+                                newdata[0].rp = rp;
+                            }
+                            trdata = $(tb).find("tr[rowpos=" + rp + "]");
+                            if (trdata.length === 0) {
+                                trdata = $("<tr " + dc + " rowpos='" + rp + "'></tr>").addClass("FormData").attr("id", "trv_" + nm);
+                                $(trdata).append(tmpl);
+                                $(tb).append(trdata);
+                                trdata[0].rp = rp;
+                            }
+                            $("td:eq(" + (cp - 2) + ")", trdata[0]).html('<b>' + (typeof frmopt.label === 'undefined' ? obj.p.colNames[i] : frmopt.label) + '</b>');
+                            $("td:eq(" + (cp - 1) + ")", trdata[0]).append("<span>" + tmp + "</span>").attr("id", "v_" + nm);
+                            if (setme) {
+                                $("td:eq(" + (cp - 1) + ") span", trdata[0]).css({'text-align': 'right', width: maxw + "px"});
+                            }
+                            retpos[cnt] = i;
+                            cnt++;
+                        }
+                    });
+                    if (cnt > 0) {
+                        var idrow = $("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='" + (maxcols * 2 - 1) + "' class='DataTD'><input class='FormElement' id='id_g' type='text' name='id' value='" + rowid + "'/></td></tr>");
+                        idrow[0].rp = cnt + 99;
+                        $(tb).append(idrow);
+                    }
+                    return retpos;
+                }
+
+                function fillData(rowid, obj) {
+                    var nm, hc, cnt = 0, tmp, opt, trv;
+                    trv = $(obj).jqGrid("getInd", rowid, true);
+                    if (!trv) {
+                        return;
+                    }
+                    $('td', trv).each(function (i) {
+                        nm = obj.p.colModel[i].name;
+                        // hidden fields are included in the form
+                        if (obj.p.colModel[i].editrules && obj.p.colModel[i].editrules.edithidden === true) {
+                            hc = false;
+                        } else {
+                            hc = obj.p.colModel[i].hidden === true ? true : false;
+                        }
+                        if (nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn') {
+                            if (nm == obj.p.ExpandColumn && obj.p.treeGrid === true) {
+                                tmp = $(this).text();
+                            } else {
+                                tmp = $(this).html();
+                            }
+                            opt = $.extend({}, obj.p.colModel[i].editoptions || {});
+                            nm = $.jgrid.jqID("v_" + nm);
+                            $("#" + nm + " span", "#" + frmtb).html(tmp);
+                            if (hc) {
+                                $("#" + nm, "#" + frmtb).parents("tr:first").hide();
+                            }
+                            cnt++;
+                        }
+                    });
+                    if (cnt > 0) {
+                        $("#id_g", "#" + frmtb).val(rowid);
+                    }
+                }
+
+                function updateNav(cr, totr) {
+                    if (cr === 0) {
+                        $("#pData", "#" + frmtb + "_2").addClass('ui-state-disabled');
+                    } else {
+                        $("#pData", "#" + frmtb + "_2").removeClass('ui-state-disabled');
+                    }
+                    if (cr == totr) {
+                        $("#nData", "#" + frmtb + "_2").addClass('ui-state-disabled');
+                    } else {
+                        $("#nData", "#" + frmtb + "_2").removeClass('ui-state-disabled');
+                    }
+                }
+
+                function getCurrPos() {
+                    var rowsInGrid = $($t).jqGrid("getDataIDs"),
+                        selrow = $("#id_g", "#" + frmtb).val(),
+                        pos = $.inArray(selrow, rowsInGrid);
+                    return [pos, rowsInGrid];
+                }
+
+                if ($("#" + $.jgrid.jqID(IDs.themodal)).html() !== null) {
+                    if (onBeforeInit) {
+                        showFrm = onBeforeInit.call($t, $("#" + frmgr));
+                        if (typeof(showFrm) == "undefined") {
+                            showFrm = true;
+                        }
+                    }
+                    if (showFrm === false) {
+                        return;
+                    }
+                    $(".ui-jqdialog-title", "#" + $.jgrid.jqID(IDs.modalhead)).html(p.caption);
+                    $("#FormError", "#" + frmtb).hide();
+                    fillData(rowid, $t);
+                    if ($.isFunction(p.beforeShowForm)) {
+                        p.beforeShowForm.call($t, $("#" + frmgr));
+                    }
+                    $.jgrid.viewModal("#" + $.jgrid.jqID(IDs.themodal), {gbox: "#gbox_" + $.jgrid.jqID(gID), jqm: p.jqModal, jqM: false, overlay: p.overlay, modal: p.modal});
+                    focusaref();
+                } else {
+                    var dh = isNaN(p.dataheight) ? p.dataheight : p.dataheight + "px";
+                    var frm = $("<form name='FormPost' id='" + frmgr_id + "' class='FormGrid' style='width:100%;overflow:auto;position:relative;height:" + dh + ";'></form>"),
+                        tbl = $("<table id='" + frmtb_id + "' class='EditTable' cellspacing='1' cellpadding='2' border='0' style='table-layout:fixed'><tbody></tbody></table>");
+                    if (onBeforeInit) {
+                        showFrm = onBeforeInit.call($t, $("#" + frmgr));
+                        if (typeof(showFrm) == "undefined") {
+                            showFrm = true;
+                        }
+                    }
+                    if (showFrm === false) {
+                        return;
+                    }
+                    $($t.p.colModel).each(function () {
+                        var fmto = this.formoptions;
+                        maxCols = Math.max(maxCols, fmto ? fmto.colpos || 0 : 0);
+                        maxRows = Math.max(maxRows, fmto ? fmto.rowpos || 0 : 0);
+                    });
+                    // set the id.
+                    $(frm).append(tbl);
+                    createData(rowid, $t, tbl, maxCols);
+                    var rtlb = $t.p.direction == "rtl" ? true : false,
+                        bp = rtlb ? "nData" : "pData",
+                        bn = rtlb ? "pData" : "nData",
+
+                    // buttons at footer
+                        bP = "<a href='javascript:void(0)' id='" + bp + "' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></a>",
+                        bN = "<a href='javascript:void(0)' id='" + bn + "' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></a>",
+                        bC = "<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>" + p.bClose + "</a>";
+                    if (maxRows > 0) {
+                        var sd = [];
+                        $.each($(tbl)[0].rows, function (i, r) {
+                            sd[i] = r;
+                        });
+                        sd.sort(function (a, b) {
+                            if (a.rp > b.rp) {
+                                return 1;
+                            }
+                            if (a.rp < b.rp) {
+                                return -1;
+                            }
+                            return 0;
+                        });
+                        $.each(sd, function (index, row) {
+                            $('tbody', tbl).append(row);
+                        });
+                    }
+                    p.gbox = "#gbox_" + $.jgrid.jqID(gID);
+                    var cle = false;
+                    if (p.closeOnEscape === true) {
+                        p.closeOnEscape = false;
+                        cle = true;
+                    }
+                    var bt = $("<span></span>").append(frm).append("<table border='0' class='EditTable' id='" + frmtb + "_2'><tbody><tr id='Act_Buttons'><td class='navButton' width='" + p.labelswidth + "'>" + (rtlb ? bN + bP : bP + bN) + "</td><td class='EditButton'>" + bC + "</td></tr></tbody></table>");
+                    $.jgrid.createModal(IDs, bt, p, "#gview_" + $.jgrid.jqID($t.p.id), $("#gview_" + $.jgrid.jqID($t.p.id))[0]);
+                    if (rtlb) {
+                        $("#pData, #nData", "#" + frmtb + "_2").css("float", "right");
+                        $(".EditButton", "#" + frmtb + "_2").css("text-align", "left");
+                    }
+                    if (!p.viewPagerButtons) {
+                        $("#pData, #nData", "#" + frmtb + "_2").hide();
+                    }
+                    bt = null;
+                    $("#" + IDs.themodal).keydown(function (e) {
+                        if (e.which === 27) {
+                            if (cle) {
+                                $.jgrid.hideModal(this, {gb: p.gbox, jqm: p.jqModal, onClose: p.onClose});
+                            }
+                            return false;
+                        }
+                        if (p.navkeys[0] === true) {
+                            if (e.which === p.navkeys[1]) { //up
+                                $("#pData", "#" + frmtb + "_2").trigger("click");
+                                return false;
+                            }
+                            if (e.which === p.navkeys[2]) { //down
+                                $("#nData", "#" + frmtb + "_2").trigger("click");
+                                return false;
+                            }
+                        }
+                    });
+                    p.closeicon = $.extend([true, "left", "ui-icon-close"], p.closeicon);
+                    if (p.closeicon[0] === true) {
+                        $("#cData", "#" + frmtb + "_2").addClass(p.closeicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left')
+                            .append("<span class='ui-icon " + p.closeicon[2] + "'></span>");
+                    }
+                    if ($.isFunction(p.beforeShowForm)) {
+                        p.beforeShowForm.call($t, $("#" + frmgr));
+                    }
+                    $.jgrid.viewModal("#" + $.jgrid.jqID(IDs.themodal), {gbox: "#gbox_" + $.jgrid.jqID(gID), jqm: p.jqModal, modal: p.modal});
+                    $(".fm-button:not(.ui-state-disabled)", "#" + frmtb + "_2").hover(
+                        function () {
+                            $(this).addClass('ui-state-hover');
+                        },
+                        function () {
+                            $(this).removeClass('ui-state-hover');
+                        }
+                    );
+                    focusaref();
+                    $("#cData", "#" + frmtb + "_2").click(function () {
+                        $.jgrid.hideModal("#" + $.jgrid.jqID(IDs.themodal), {gb: "#gbox_" + $.jgrid.jqID(gID), jqm: p.jqModal, onClose: p.onClose});
+                        return false;
+                    });
+                    $("#nData", "#" + frmtb + "_2").click(function () {
+                        $("#FormError", "#" + frmtb).hide();
+                        var npos = getCurrPos();
+                        npos[0] = parseInt(npos[0], 10);
+                        if (npos[0] != -1 && npos[1][npos[0] + 1]) {
+                            if ($.isFunction(p.onclickPgButtons)) {
+                                p.onclickPgButtons.call($t, 'next', $("#" + frmgr), npos[1][npos[0]]);
+                            }
+                            fillData(npos[1][npos[0] + 1], $t);
+                            $($t).jqGrid("setSelection", npos[1][npos[0] + 1]);
+                            if ($.isFunction(p.afterclickPgButtons)) {
+                                p.afterclickPgButtons.call($t, 'next', $("#" + frmgr), npos[1][npos[0] + 1]);
+                            }
+                            updateNav(npos[0] + 1, npos[1].length - 1);
+                        }
+                        focusaref();
+                        return false;
+                    });
+                    $("#pData", "#" + frmtb + "_2").click(function () {
+                        $("#FormError", "#" + frmtb).hide();
+                        var ppos = getCurrPos();
+                        if (ppos[0] != -1 && ppos[1][ppos[0] - 1]) {
+                            if ($.isFunction(p.onclickPgButtons)) {
+                                p.onclickPgButtons.call($t, 'prev', $("#" + frmgr), ppos[1][ppos[0]]);
+                            }
+                            fillData(ppos[1][ppos[0] - 1], $t);
+                            $($t).jqGrid("setSelection", ppos[1][ppos[0] - 1]);
+                            if ($.isFunction(p.afterclickPgButtons)) {
+                                p.afterclickPgButtons.call($t, 'prev', $("#" + frmgr), ppos[1][ppos[0] - 1]);
+                            }
+                            updateNav(ppos[0] - 1, ppos[1].length - 1);
+                        }
+                        focusaref();
+                        return false;
+                    });
+                }
+                var posInit = getCurrPos();
+                updateNav(posInit[0], posInit[1].length - 1);
+            });
+        },
+        delGridRow: function (rowids, p) {
+            p = $.extend({
+                top: 0,
+                left: 0,
+                width: 240,
+                height: 'auto',
+                dataheight: 'auto',
+                modal: false,
+                overlay: 30,
+                drag: true,
+                resize: true,
+                url: '',
+                mtype: "POST",
+                reloadAfterSubmit: true,
+                beforeShowForm: null,
+                beforeInitData: null,
+                afterShowForm: null,
+                beforeSubmit: null,
+                onclickSubmit: null,
+                afterSubmit: null,
+                jqModal: true,
+                closeOnEscape: false,
+                delData: {},
+                delicon: [],
+                cancelicon: [],
+                onClose: null,
+                ajaxDelOptions: {},
+                processing: false,
+                serializeDelData: null,
+                useDataProxy: false
+            }, $.jgrid.del, p || {});
+            rp_ge[$(this)[0].p.id] = p;
+            return this.each(function () {
+                var $t = this;
+                if (!$t.grid) {
+                    return;
+                }
+                if (!rowids) {
+                    return;
+                }
+                var onBeforeShow = $.isFunction(rp_ge[$t.p.id].beforeShowForm),
+                    onAfterShow = $.isFunction(rp_ge[$t.p.id].afterShowForm),
+                    onBeforeInit = $.isFunction(rp_ge[$t.p.id].beforeInitData) ? rp_ge[$t.p.id].beforeInitData : false,
+                    gID = $t.p.id, onCS = {},
+                    showFrm = true,
+                    dtbl = "DelTbl_" + $.jgrid.jqID(gID), postd, idname, opers, oper,
+                    dtbl_id = "DelTbl_" + gID,
+                    IDs = {themodal: 'delmod' + gID, modalhead: 'delhd' + gID, modalcontent: 'delcnt' + gID, scrollelm: dtbl};
+                if (jQuery.isArray(rowids)) {
+                    rowids = rowids.join();
+                }
+                if ($("#" + $.jgrid.jqID(IDs.themodal)).html() !== null) {
+                    if (onBeforeInit) {
+                        showFrm = onBeforeInit.call($t, $("#" + dtbl));
+                        if (typeof(showFrm) == "undefined") {
+                            showFrm = true;
+                        }
+                    }
+                    if (showFrm === false) {
+                        return;
+                    }
+                    $("#DelData>td", "#" + dtbl).text(rowids);
+                    $("#DelError", "#" + dtbl).hide();
+                    if (rp_ge[$t.p.id].processing === true) {
+                        rp_ge[$t.p.id].processing = false;
+                        $("#dData", "#" + dtbl).removeClass('ui-state-active');
+                    }
+                    if (onBeforeShow) {
+                        rp_ge[$t.p.id].beforeShowForm.call($t, $("#" + dtbl));
+                    }
+                    $.jgrid.viewModal("#" + $.jgrid.jqID(IDs.themodal), {gbox: "#gbox_" + $.jgrid.jqID(gID), jqm: rp_ge[$t.p.id].jqModal, jqM: false, overlay: rp_ge[$t.p.id].overlay, modal: rp_ge[$t.p.id].modal});
+                    if (onAfterShow) {
+                        rp_ge[$t.p.id].afterShowForm.call($t, $("#" + dtbl));
+                    }
+                } else {
+                    var dh = isNaN(rp_ge[$t.p.id].dataheight) ? rp_ge[$t.p.id].dataheight : rp_ge[$t.p.id].dataheight + "px";
+                    var tbl = "<div id='" + dtbl_id + "' class='formdata' style='width:100%;overflow:auto;position:relative;height:" + dh + ";'>";
+                    tbl += "<table class='DelTable'><tbody>";
+                    // error data
+                    tbl += "<tr id='DelError' style='display:none'><td class='ui-state-error'></td></tr>";
+                    tbl += "<tr id='DelData' style='display:none'><td >" + rowids + "</td></tr>";
+                    tbl += "<tr><td class=\"delmsg\" style=\"white-space:pre;\">" + rp_ge[$t.p.id].msg + "</td></tr><tr><td >&#160;</td></tr>";
+                    // buttons at footer
+                    tbl += "</tbody></table></div>";
+                    var bS = "<a href='javascript:void(0)' id='dData' class='fm-button ui-state-default ui-corner-all'>" + p.bSubmit + "</a>",
+                        bC = "<a href='javascript:void(0)' id='eData' class='fm-button ui-state-default ui-corner-all'>" + p.bCancel + "</a>";
+                    tbl += "<table cellspacing='0' cellpadding='0' border='0' class='EditTable' id='" + dtbl + "_2'><tbody><tr><td><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr><td class='DelButton EditButton'>" + bS + "&#160;" + bC + "</td></tr></tbody></table>";
+                    p.gbox = "#gbox_" + $.jgrid.jqID(gID);
+                    $.jgrid.createModal(IDs, tbl, p, "#gview_" + $.jgrid.jqID($t.p.id), $("#gview_" + $.jgrid.jqID($t.p.id))[0]);
+
+                    if (onBeforeInit) {
+                        showFrm = onBeforeInit.call($t, $("#" + dtbl));
+                        if (typeof(showFrm) == "undefined") {
+                            showFrm = true;
+                        }
+                    }
+                    if (showFrm === false) {
+                        return;
+                    }
+
+                    $(".fm-button", "#" + dtbl + "_2").hover(
+                        function () {
+                            $(this).addClass('ui-state-hover');
+                        },
+                        function () {
+                            $(this).removeClass('ui-state-hover');
+                        }
+                    );
+                    p.delicon = $.extend([true, "left", "ui-icon-scissors"], rp_ge[$t.p.id].delicon);
+                    p.cancelicon = $.extend([true, "left", "ui-icon-cancel"], rp_ge[$t.p.id].cancelicon);
+                    if (p.delicon[0] === true) {
+                        $("#dData", "#" + dtbl + "_2").addClass(p.delicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left')
+                            .append("<span class='ui-icon " + p.delicon[2] + "'></span>");
+                    }
+                    if (p.cancelicon[0] === true) {
+                        $("#eData", "#" + dtbl + "_2").addClass(p.cancelicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left')
+                            .append("<span class='ui-icon " + p.cancelicon[2] + "'></span>");
+                    }
+                    $("#dData", "#" + dtbl + "_2").click(function () {
+                        var ret = [true, ""];
+                        onCS = {};
+                        var postdata = $("#DelData>td", "#" + dtbl).text(); //the pair is name=val1,val2,...
+                        if ($.isFunction(rp_ge[$t.p.id].onclickSubmit)) {
+                            onCS = rp_ge[$t.p.id].onclickSubmit.call($t, rp_ge[$t.p.id], postdata) || {};
+                        }
+                        if ($.isFunction(rp_ge[$t.p.id].beforeSubmit)) {
+                            ret = rp_ge[$t.p.id].beforeSubmit.call($t, postdata);
+                        }
+                        if (ret[0] && !rp_ge[$t.p.id].processing) {
+                            rp_ge[$t.p.id].processing = true;
+                            opers = $t.p.prmNames;
+                            postd = $.extend({}, rp_ge[$t.p.id].delData, onCS);
+                            oper = opers.oper;
+                            postd[oper] = opers.deloper;
+                            idname = opers.id;
+                            postdata = String(postdata).split(",");
+                            if (!postdata.length) {
+                                return false;
+                            }
+                            for (var pk in postdata) {
+                                if (postdata.hasOwnProperty(pk)) {
+                                    postdata[pk] = $.jgrid.stripPref($t.p.idPrefix, postdata[pk]);
+                                }
+                            }
+                            postd[idname] = postdata.join();
+                            $(this).addClass('ui-state-active');
+                            var ajaxOptions = $.extend({
+                                url: rp_ge[$t.p.id].url ? rp_ge[$t.p.id].url : $($t).jqGrid('getGridParam', 'editurl'),
+                                type: rp_ge[$t.p.id].mtype,
+                                data: $.isFunction(rp_ge[$t.p.id].serializeDelData) ? rp_ge[$t.p.id].serializeDelData.call($t, postd) : postd,
+                                complete: function (data, Status) {
+                                    if (Status != "success") {
+                                        ret[0] = false;
+                                        if ($.isFunction(rp_ge[$t.p.id].errorTextFormat)) {
+                                            ret[1] = rp_ge[$t.p.id].errorTextFormat.call($t, data);
+                                        } else {
+                                            ret[1] = Status + " Status: '" + data.statusText + "'. Error code: " + data.status;
+                                        }
+                                    } else {
+                                        // data is posted successful
+                                        // execute aftersubmit with the returned data from server
+                                        if ($.isFunction(rp_ge[$t.p.id].afterSubmit)) {
+                                            ret = rp_ge[$t.p.id].afterSubmit.call($t, data, postd);
+                                        }
+                                    }
+                                    if (ret[0] === false) {
+                                        $("#DelError>td", "#" + dtbl).html(ret[1]);
+                                        $("#DelError", "#" + dtbl).show();
+                                    } else {
+                                        if (rp_ge[$t.p.id].reloadAfterSubmit && $t.p.datatype != "local") {
+                                            $($t).trigger("reloadGrid");
+                                        } else {
+                                            if ($t.p.treeGrid === true) {
+                                                try {
+                                                    $($t).jqGrid("delTreeNode", $t.p.idPrefix + postdata[0]);
+                                                } catch (e) {
+                                                }
+                                            } else {
+                                                for (var i = 0; i < postdata.length; i++) {
+                                                    $($t).jqGrid("delRowData", $t.p.idPrefix + postdata[i]);
+                                                }
+                                            }
+                                            $t.p.selrow = null;
+                                            $t.p.selarrrow = [];
+                                        }
+                                        if ($.isFunction(rp_ge[$t.p.id].afterComplete)) {
+                                            setTimeout(function () {
+                                                rp_ge[$t.p.id].afterComplete.call($t, data, postdata);
+                                            }, 500);
+                                        }
+                                    }
+                                    rp_ge[$t.p.id].processing = false;
+                                    $("#dData", "#" + dtbl + "_2").removeClass('ui-state-active');
+                                    if (ret[0]) {
+                                        $.jgrid.hideModal("#" + $.jgrid.jqID(IDs.themodal), {gb: "#gbox_" + $.jgrid.jqID(gID), jqm: p.jqModal, onClose: rp_ge[$t.p.id].onClose});
+                                    }
+                                }
+                            }, $.jgrid.ajaxOptions, rp_ge[$t.p.id].ajaxDelOptions);
+
+
+                            if (!ajaxOptions.url && !rp_ge[$t.p.id].useDataProxy) {
+                                if ($.isFunction($t.p.dataProxy)) {
+                                    rp_ge[$t.p.id].useDataProxy = true;
+                                } else {
+                                    ret[0] = false;
+                                    ret[1] += " " + $.jgrid.errors.nourl;
+                                }
+                            }
+                            if (ret[0]) {
+                                if (rp_ge[$t.p.id].useDataProxy) {
+                                    var dpret = $t.p.dataProxy.call($t, ajaxOptions, "del_" + $t.p.id);
+                                    if (typeof(dpret) == "undefined") {
+                                        dpret = [true, ""];
+                                    }
+                                    if (dpret[0] === false) {
+                                        ret[0] = false;
+                                        ret[1] = dpret[1] || "Error deleting the selected row!";
+                                    } else {
+                                        $.jgrid.hideModal("#" + $.jgrid.jqID(IDs.themodal), {gb: "#gbox_" + $.jgrid.jqID(gID), jqm: p.jqModal, onClose: rp_ge[$t.p.id].onClose});
+                                    }
+                                }
+                                else {
+                                    $.ajax(ajaxOptions);
+                                }
+                            }
+                        }
+
+                        if (ret[0] === false) {
+                            $("#DelError>td", "#" + dtbl).html(ret[1]);
+                            $("#DelError", "#" + dtbl).show();
+                        }
+                        return false;
+                    });
+                    $("#eData", "#" + dtbl + "_2").click(function () {
+                        $.jgrid.hideModal("#" + $.jgrid.jqID(IDs.themodal), {gb: "#gbox_" + $.jgrid.jqID(gID), jqm: rp_ge[$t.p.id].jqModal, onClose: rp_ge[$t.p.id].onClose});
+                        return false;
+                    });
+                    if (onBeforeShow) {
+                        rp_ge[$t.p.id].beforeShowForm.call($t, $("#" + dtbl));
+                    }
+                    $.jgrid.viewModal("#" + $.jgrid.jqID(IDs.themodal), {gbox: "#gbox_" + $.jgrid.jqID(gID), jqm: rp_ge[$t.p.id].jqModal, overlay: rp_ge[$t.p.id].overlay, modal: rp_ge[$t.p.id].modal});
+                    if (onAfterShow) {
+                        rp_ge[$t.p.id].afterShowForm.call($t, $("#" + dtbl));
+                    }
+                }
+                if (rp_ge[$t.p.id].closeOnEscape === true) {
+                    setTimeout(function () {
+                        $(".ui-jqdialog-titlebar-close", "#" + $.jgrid.jqID(IDs.modalhead)).focus();
+                    }, 0);
+                }
+            });
+        },
+        navGrid: function (elem, o, pEdit, pAdd, pDel, pSearch, pView) {
+            o = $.extend({
+                edit: true,
+                editicon: "ui-icon-pencil",
+                add: true,
+                addicon: "ui-icon-plus",
+                del: true,
+                delicon: "ui-icon-trash",
+                search: true,
+                searchicon: "ui-icon-search",
+                refresh: true,
+                refreshicon: "ui-icon-refresh",
+                refreshstate: 'firstpage',
+                view: false,
+                viewicon: "ui-icon-document",
+                position: "left",
+                closeOnEscape: true,
+                beforeRefresh: null,
+                afterRefresh: null,
+                cloneToTop: false,
+                alertwidth: 200,
+                alertheight: 'auto',
+                alerttop: null,
+                alertleft: null,
+                alertzIndex: null
+            }, $.jgrid.nav, o || {});
+            return this.each(function () {
+                if (this.nav) {
+                    return;
+                }
+                var alertIDs = {themodal: 'alertmod', modalhead: 'alerthd', modalcontent: 'alertcnt'},
+                    $t = this, twd, tdw;
+                if (!$t.grid || typeof elem != 'string') {
+                    return;
+                }
+                if ($("#" + alertIDs.themodal).html() === null) {
+                    if (!o.alerttop && !o.alertleft) {
+                        if (typeof window.innerWidth != 'undefined') {
+                            o.alertleft = window.innerWidth;
+                            o.alerttop = window.innerHeight;
+                        } else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth !== 0) {
+                            o.alertleft = document.documentElement.clientWidth;
+                            o.alerttop = document.documentElement.clientHeight;
+                        } else {
+                            o.alertleft = 1024;
+                            o.alerttop = 768;
+                        }
+                        o.alertleft = o.alertleft / 2 - parseInt(o.alertwidth, 10) / 2;
+                        o.alerttop = o.alerttop / 2 - 25;
+                    }
+                    $.jgrid.createModal(alertIDs, "<div>" + o.alerttext + "</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>", {gbox: "#gbox_" + $.jgrid.jqID($t.p.id), jqModal: true, drag: true, resize: true, caption: o.alertcap, top: o.alerttop, left: o.alertleft, width: o.alertwidth, height: o.alertheight, closeOnEscape: o.closeOnEscape, zIndex: o.alertzIndex}, "", "", true);
+                }
+                var clone = 1;
+                if (o.cloneToTop && $t.p.toppager) {
+                    clone = 2;
+                }
+                for (var i = 0; i < clone; i++) {
+                    var tbd,
+                        navtbl = $("<table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table navtable' style='float:left;table-layout:auto;'><tbody><tr></tr></tbody></table>"),
+                        sep = "<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>",
+                        pgid, elemids;
+                    if (i === 0) {
+                        pgid = elem;
+                        elemids = $t.p.id;
+                        if (pgid == $t.p.toppager) {
+                            elemids += "_top";
+                            clone = 1;
+                        }
+                    } else {
+                        pgid = $t.p.toppager;
+                        elemids = $t.p.id + "_top";
+                    }
+                    if ($t.p.direction == "rtl") {
+                        $(navtbl).attr("dir", "rtl").css("float", "right");
+                    }
+                    if (o.add) {
+                        pAdd = pAdd || {};
+                        tbd = $("<td class='ui-pg-button ui-corner-all'></td>");
+                        $(tbd).append("<div class='ui-pg-div'><span class='ui-icon " + o.addicon + "'></span>" + o.addtext + "</div>");
+                        $("tr", navtbl).append(tbd);
+                        $(tbd, navtbl)
+                            .attr({"title": o.addtitle || "", id: pAdd.id || "add_" + elemids})
+                            .click(function () {
+                                if (!$(this).hasClass('ui-state-disabled')) {
+                                    if ($.isFunction(o.addfunc)) {
+                                        o.addfunc.call($t);
+                                    } else {
+                                        $($t).jqGrid("editGridRow", "new", pAdd);
+                                    }
+                                }
+                                return false;
+                            }).hover(
+                            function () {
+                                if (!$(this).hasClass('ui-state-disabled')) {
+                                    $(this).addClass("ui-state-hover");
+                                }
+                            },
+                            function () {
+                                $(this).removeClass("ui-state-hover");
+                            }
+                        );
+                        tbd = null;
+                    }
+                    if (o.edit) {
+                        tbd = $("<td class='ui-pg-button ui-corner-all'></td>");
+                        pEdit = pEdit || {};
+                        $(tbd).append("<div class='ui-pg-div'><span class='ui-icon " + o.editicon + "'></span>" + o.edittext + "</div>");
+                        $("tr", navtbl).append(tbd);
+                        $(tbd, navtbl)
+                            .attr({"title": o.edittitle || "", id: pEdit.id || "edit_" + elemids})
+                            .click(function () {
+                                if (!$(this).hasClass('ui-state-disabled')) {
+                                    var sr = $t.p.selrow;
+                                    if (sr) {
+                                        if ($.isFunction(o.editfunc)) {
+                                            o.editfunc.call($t, sr);
+                                        } else {
+                                            $($t).jqGrid("editGridRow", sr, pEdit);
+                                        }
+                                    } else {
+                                        $.jgrid.viewModal("#" + alertIDs.themodal, {gbox: "#gbox_" + $.jgrid.jqID($t.p.id), jqm: true});
+                                        $("#jqg_alrt").focus();
+                                    }
+                                }
+                                return false;
+                            }).hover(
+                            function () {
+                                if (!$(this).hasClass('ui-state-disabled')) {
+                                    $(this).addClass("ui-state-hover");
+                                }
+                            },
+                            function () {
+                                $(this).removeClass("ui-state-hover");
+                            }
+                        );
+                        tbd = null;
+                    }
+                    if (o.view) {
+                        tbd = $("<td class='ui-pg-button ui-corner-all'></td>");
+                        pView = pView || {};
+                        $(tbd).append("<div class='ui-pg-div'><span class='ui-icon " + o.viewicon + "'></span>" + o.viewtext + "</div>");
+                        $("tr", navtbl).append(tbd);
+                        $(tbd, navtbl)
+                            .attr({"title": o.viewtitle || "", id: pView.id || "view_" + elemids})
+                            .click(function () {
+                                if (!$(this).hasClass('ui-state-disabled')) {
+                                    var sr = $t.p.selrow;
+                                    if (sr) {
+                                        if ($.isFunction(o.viewfunc)) {
+                                            o.viewfunc.call($t, sr);
+                                        } else {
+                                            $($t).jqGrid("viewGridRow", sr, pView);
+                                        }
+                                    } else {
+                                        $.jgrid.viewModal("#" + alertIDs.themodal, {gbox: "#gbox_" + $.jgrid.jqID($t.p.id), jqm: true});
+                                        $("#jqg_alrt").focus();
+                                    }
+                                }
+                                return false;
+                            }).hover(
+                            function () {
+                                if (!$(this).hasClass('ui-state-disabled')) {
+                                    $(this).addClass("ui-state-hover");
+                                }
+                            },
+                            function () {
+                                $(this).removeClass("ui-state-hover");
+                            }
+                        );
+                        tbd = null;
+                    }
+                    if (o.del) {
+                        tbd = $("<td class='ui-pg-button ui-corner-all'></td>");
+                        pDel = pDel || {};
+                        $(tbd).append("<div class='ui-pg-div'><span class='ui-icon " + o.delicon + "'></span>" + o.deltext + "</div>");
+                        $("tr", navtbl).append(tbd);
+                        $(tbd, navtbl)
+                            .attr({"title": o.deltitle || "", id: pDel.id || "del_" + elemids})
+                            .click(function () {
+                                if (!$(this).hasClass('ui-state-disabled')) {
+                                    var dr;
+                                    if ($t.p.multiselect) {
+                                        dr = $t.p.selarrrow;
+                                        if (dr.length === 0) {
+                                            dr = null;
+                                        }
+                                    } else {
+                                        dr = $t.p.selrow;
+                                    }
+                                    if (dr) {
+                                        if ($.isFunction(o.delfunc)) {
+                                            o.delfunc.call($t, dr);
+                                        } else {
+                                            $($t).jqGrid("delGridRow", dr, pDel);
+                                        }
+                                    } else {
+                                        $.jgrid.viewModal("#" + alertIDs.themodal, {gbox: "#gbox_" + $.jgrid.jqID($t.p.id), jqm: true});
+                                        $("#jqg_alrt").focus();
+                                    }
+                                }
+                                return false;
+                            }).hover(
+                            function () {
+                                if (!$(this).hasClass('ui-state-disabled')) {
+                                    $(this).addClass("ui-state-hover");
+                                }
+                            },
+                            function () {
+                                $(this).removeClass("ui-state-hover");
+                            }
+                        );
+                        tbd = null;
+                    }
+                    if (o.add || o.edit || o.del || o.view) {
+                        $("tr", navtbl).append(sep);
+                    }
+                    if (o.search) {
+                        tbd = $("<td class='ui-pg-button ui-corner-all'></td>");
+                        pSearch = pSearch || {};
+                        $(tbd).append("<div class='ui-pg-div'><span class='ui-icon " + o.searchicon + "'></span>" + o.searchtext + "</div>");
+                        $("tr", navtbl).append(tbd);
+                        $(tbd, navtbl)
+                            .attr({"title": o.searchtitle || "", id: pSearch.id || "search_" + elemids})
+                            .click(function () {
+                                if (!$(this).hasClass('ui-state-disabled')) {
+                                    if ($.isFunction(o.searchfunc)) {
+                                        o.searchfunc.call($t, pSearch);
+                                    } else {
+                                        $($t).jqGrid("searchGrid", pSearch);
+                                    }
+                                }
+                                return false;
+                            }).hover(
+                            function () {
+                                if (!$(this).hasClass('ui-state-disabled')) {
+                                    $(this).addClass("ui-state-hover");
+                                }
+                            },
+                            function () {
+                                $(this).removeClass("ui-state-hover");
+                            }
+                        );
+                        if (pSearch.showOnLoad && pSearch.showOnLoad === true) {
+                            $(tbd, navtbl).click();
+                        }
+                        tbd = null;
+                    }
+                    if (o.refresh) {
+                        tbd = $("<td class='ui-pg-button ui-corner-all'></td>");
+                        $(tbd).append("<div class='ui-pg-div'><span class='ui-icon " + o.refreshicon + "'></span>" + o.refreshtext + "</div>");
+                        $("tr", navtbl).append(tbd);
+                        $(tbd, navtbl)
+                            .attr({"title": o.refreshtitle || "", id: "refresh_" + elemids})
+                            .click(function () {
+                                if (!$(this).hasClass('ui-state-disabled')) {
+                                    if ($.isFunction(o.beforeRefresh)) {
+                                        o.beforeRefresh.call($t);
+                                    }
+                                    $t.p.search = false;
+                                    try {
+                                        var gID = $t.p.id;
+                                        $t.p.postData.filters = "";
+                                        $("#fbox_" + $.jgrid.jqID(gID)).jqFilter('resetFilter');
+                                        if ($.isFunction($t.clearToolbar)) {
+                                            $t.clearToolbar.call($t, false);
+                                        }
+                                    } catch (e) {
+                                    }
+                                    switch (o.refreshstate) {
+                                        case 'firstpage':
+                                            $($t).trigger("reloadGrid", [
+                                                {page: 1}
+                                            ]);
+                                            break;
+                                        case 'current':
+                                            $($t).trigger("reloadGrid", [
+                                                {current: true}
+                                            ]);
+                                            break;
+                                    }
+                                    if ($.isFunction(o.afterRefresh)) {
+                                        o.afterRefresh.call($t);
+                                    }
+                                }
+                                return false;
+                            }).hover(
+                            function () {
+                                if (!$(this).hasClass('ui-state-disabled')) {
+                                    $(this).addClass("ui-state-hover");
+                                }
+                            },
+                            function () {
+                                $(this).removeClass("ui-state-hover");
+                            }
+                        );
+                        tbd = null;
+                    }
+                    tdw = $(".ui-jqgrid").css("font-size") || "11px";
+                    $('body').append("<div id='testpg2' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:" + tdw + ";visibility:hidden;' ></div>");
+                    twd = $(navtbl).clone().appendTo("#testpg2").width();
+                    $("#testpg2").remove();
+                    $(pgid + "_" + o.position, pgid).append(navtbl);
+                    if ($t.p._nvtd) {
+                        if (twd > $t.p._nvtd[0]) {
+                            $(pgid + "_" + o.position, pgid).width(twd);
+                            $t.p._nvtd[0] = twd;
+                        }
+                        $t.p._nvtd[1] = twd;
+                    }
+                    tdw = null;
+                    twd = null;
+                    navtbl = null;
+                    this.nav = true;
+                }
+            });
+        },
+        navButtonAdd: function (elem, p) {
+            p = $.extend({
+                caption: "newButton",
+                title: '',
+                buttonicon: 'ui-icon-newwin',
+                onClickButton: null,
+                position: "last",
+                cursor: 'pointer'
+            }, p || {});
+            return this.each(function () {
+                if (!this.grid) {
+                    return;
+                }
+                if (typeof elem === "string" && elem.indexOf("#") !== 0) {
+                    elem = "#" + $.jgrid.jqID(elem);
+                }
+                var findnav = $(".navtable", elem)[0], $t = this;
+                if (findnav) {
+                    if (p.id && $("#" + $.jgrid.jqID(p.id), findnav).html() !== null) {
+                        return;
+                    }
+                    var tbd = $("<td></td>");
+                    if (p.buttonicon.toString().toUpperCase() == "NONE") {
+                        $(tbd).addClass('ui-pg-button ui-corner-all').append("<div class='ui-pg-div'>" + p.caption + "</div>");
+                    } else {
+                        $(tbd).addClass('ui-pg-button ui-corner-all').append("<div class='ui-pg-div'><span class='ui-icon " + p.buttonicon + "'></span>" + p.caption + "</div>");
+                    }
+                    if (p.id) {
+                        $(tbd).attr("id", p.id);
+                    }
+                    if (p.position == 'first') {
+                        if (findnav.rows[0].cells.length === 0) {
+                            $("tr", findnav).append(tbd);
+                        } else {
+                            $("tr td:eq(0)", findnav).before(tbd);
+                        }
+                    } else {
+                        $("tr", findnav).append(tbd);
+                    }
+                    $(tbd, findnav)
+                        .attr("title", p.title || "")
+                        .click(function (e) {
+                            if (!$(this).hasClass('ui-state-disabled')) {
+                                if ($.isFunction(p.onClickButton)) {
+                                    p.onClickButton.call($t, e);
+                                }
+                            }
+                            return false;
+                        })
+                        .hover(
+                        function () {
+                            if (!$(this).hasClass('ui-state-disabled')) {
+                                $(this).addClass('ui-state-hover');
+                            }
+                        },
+                        function () {
+                            $(this).removeClass("ui-state-hover");
+                        }
+                    );
+                }
+            });
+        },
+        navSeparatorAdd: function (elem, p) {
+            p = $.extend({
+                sepclass: "ui-separator",
+                sepcontent: ''
+            }, p || {});
+            return this.each(function () {
+                if (!this.grid) {
+                    return;
+                }
+                if (typeof elem === "string" && elem.indexOf("#") !== 0) {
+                    elem = "#" + $.jgrid.jqID(elem);
+                }
+                var findnav = $(".navtable", elem)[0];
+                if (findnav) {
+                    var sep = "<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='" + p.sepclass + "'></span>" + p.sepcontent + "</td>";
+                    $("tr", findnav).append(sep);
+                }
+            });
+        },
+        GridToForm: function (rowid, formid) {
+            return this.each(function () {
+                var $t = this;
+                if (!$t.grid) {
+                    return;
+                }
+                var rowdata = $($t).jqGrid("getRowData", rowid);
+                if (rowdata) {
+                    for (var i in rowdata) {
+                        if ($("[name=" + $.jgrid.jqID(i) + "]", formid).is("input:radio") || $("[name=" + $.jgrid.jqID(i) + "]", formid).is("input:checkbox")) {
+                            $("[name=" + $.jgrid.jqID(i) + "]", formid).each(function () {
+                                if ($(this).val() == rowdata[i]) {
+                                    $(this)[$t.p.useProp ? 'prop' : 'attr']("checked", true);
+                                } else {
+                                    $(this)[$t.p.useProp ? 'prop' : 'attr']("checked", false);
+                                }
+                            });
+                        } else {
+                            // this is very slow on big table and form.
+                            $("[name=" + $.jgrid.jqID(i) + "]", formid).val(rowdata[i]);
+                        }
+                    }
+                }
+            });
+        },
+        FormToGrid: function (rowid, formid, mode, position) {
+            return this.each(function () {
+                var $t = this;
+                if (!$t.grid) {
+                    return;
+                }
+                if (!mode) {
+                    mode = 'set';
+                }
+                if (!position) {
+                    position = 'first';
+                }
+                var fields = $(formid).serializeArray();
+                var griddata = {};
+                $.each(fields, function (i, field) {
+                    griddata[field.name] = field.value;
+                });
+                if (mode == 'add') {
+                    $($t).jqGrid("addRowData", rowid, griddata, position);
+                }
+                else if (mode == 'set') {
+                    $($t).jqGrid("setRowData", rowid, griddata);
+                }
+            });
+        }
+    });
+})(jQuery);
+;
+(function ($) {
+    /**
+     * jqGrid extension for manipulating Grid Data
+     * Tony Tomov tony@trirand.com
+     * http://trirand.com/blog/
+     * Dual licensed under the MIT and GPL licenses:
+     * http://www.opensource.org/licenses/mit-license.php
+     * http://www.gnu.org/licenses/gpl-2.0.html
+     **/
+//jsHint options
+    /*global alert, $, jQuery */
+    "use strict";
+    $.jgrid.inlineEdit = $.jgrid.inlineEdit || {};
+    $.jgrid.extend({
+//Editing
+        editRow: function (rowid, keys, oneditfunc, successfunc, url, extraparam, aftersavefunc, errorfunc, afterrestorefunc) {
+            // Compatible mode old versions
+            var o = {}, args = $.makeArray(arguments).slice(1);
+
+            if ($.type(args[0]) === "object") {
+                o = args[0];
+            } else {
+                if (typeof keys !== "undefined") {
+                    o.keys = keys;
+                }
+                if ($.isFunction(oneditfunc)) {
+                    o.oneditfunc = oneditfunc;
+                }
+                if ($.isFunction(successfunc)) {
+                    o.successfunc = successfunc;
+                }
+                if (typeof url !== "undefined") {
+                    o.url = url;
+                }
+                if (typeof extraparam !== "undefined") {
+                    o.extraparam = extraparam;
+                }
+                if ($.isFunction(aftersavefunc)) {
+                    o.aftersavefunc = aftersavefunc;
+                }
+                if ($.isFunction(errorfunc)) {
+                    o.errorfunc = errorfunc;
+                }
+                if ($.isFunction(afterrestorefunc)) {
+                    o.afterrestorefunc = afterrestorefunc;
+                }
+                // last two not as param, but as object (sorry)
+                //if (typeof restoreAfterError !== "undefined") { o.restoreAfterError = restoreAfterError; }
+                //if (typeof mtype !== "undefined") { o.mtype = mtype || "POST"; }
+            }
+            o = $.extend(true, {
+                keys: false,
+                oneditfunc: null,
+                successfunc: null,
+                url: null,
+                extraparam: {},
+                aftersavefunc: null,
+                errorfunc: null,
+                afterrestorefunc: null,
+                restoreAfterError: true,
+                mtype: "POST"
+            }, $.jgrid.inlineEdit, o);
+
+            // End compatible
+            return this.each(function () {
+                var $t = this, nm, tmp, editable, cnt = 0, focus = null, svr = {}, ind, cm;
+                if (!$t.grid) {
+                    return;
+                }
+                ind = $($t).jqGrid("getInd", rowid, true);
+                if (ind === false) {
+                    return;
+                }
+                editable = $(ind).attr("editable") || "0";
+                if (editable == "0" && !$(ind).hasClass("not-editable-row")) {
+                    cm = $t.p.colModel;
+                    $('td[role="gridcell"]', ind).each(function (i) {
+                        nm = cm[i].name;
+                        var treeg = $t.p.treeGrid === true && nm == $t.p.ExpandColumn;
+                        if (treeg) {
+                            tmp = $("span:first", this).html();
+                        }
+                        else {
+                            try {
+                                tmp = $.unformat.call($t, this, {rowId: rowid, colModel: cm[i]}, i);
+                            } catch (_) {
+                                tmp = ( cm[i].edittype && cm[i].edittype == 'textarea' ) ? $(this).text() : $(this).html();
+                            }
+                        }
+                        if (nm != 'cb' && nm != 'subgrid' && nm != 'rn') {
+                            if ($t.p.autoencode) {
+                                tmp = $.jgrid.htmlDecode(tmp);
+                            }
+                            svr[nm] = tmp;
+                            if (cm[i].editable === true) {
+                                if (focus === null) {
+                                    focus = i;
+                                }
+                                if (treeg) {
+                                    $("span:first", this).html("");
+                                }
+                                else {
+                                    $(this).html("");
+                                }
+                                var opt = $.extend({}, cm[i].editoptions || {}, {id: rowid + "_" + nm, name: nm});
+                                if (!cm[i].edittype) {
+                                    cm[i].edittype = "text";
+                                }
+                                if (tmp == "&nbsp;" || tmp == "&#160;" || (tmp.length == 1 && tmp.charCodeAt(0) == 160)) {
+                                    tmp = '';
+                                }
+                                var elc = $.jgrid.createEl.call($t, cm[i].edittype, opt, tmp, true, $.extend({}, $.jgrid.ajaxOptions, $t.p.ajaxSelectOptions || {}));
+                                $(elc).addClass("editable");
+                                if (treeg) {
+                                    $("span:first", this).append(elc);
+                                }
+                                else {
+                                    $(this).append(elc);
+                                }
+                                //Again IE
+                                if (cm[i].edittype == "select" && typeof(cm[i].editoptions) !== "undefined" && cm[i].editoptions.multiple === true && typeof(cm[i].editoptions.dataUrl) === "undefined" && $.browser.msie) {
+                                    $(elc).width($(elc).width());
+                                }
+                                cnt++;
+                            }
+                        }
+                    });
+                    if (cnt > 0) {
+                        svr.id = rowid;
+                        $t.p.savedRow.push(svr);
+                        $(ind).attr("editable", "1");
+                        $("td:eq(" + focus + ") input", ind).focus();
+                        if (o.keys === true) {
+                            $(ind).bind("keydown", function (e) {
+                                if (e.keyCode === 27) {
+                                    $($t).jqGrid("restoreRow", rowid, o.afterrestorefunc);
+                                    if ($t.p._inlinenav) {
+                                        try {
+                                            $($t).jqGrid('showAddEditButtons');
+                                        } catch (eer1) {
+                                        }
+                                    }
+                                    return false;
+                                }
+                                if (e.keyCode === 13) {
+                                    var ta = e.target;
+                                    if (ta.tagName == 'TEXTAREA') {
+                                        return true;
+                                    }
+                                    if ($($t).jqGrid("saveRow", rowid, o)) {
+                                        if ($t.p._inlinenav) {
+                                            try {
+                                                $($t).jqGrid('showAddEditButtons');
+                                            } catch (eer2) {
+                                            }
+                                        }
+                                    }
+                                    return false;
+                                }
+                            });
+                        }
+                        $($t).triggerHandler("jqGridInlineEditRow", [rowid, o]);
+                        if ($.isFunction(o.oneditfunc)) {
+                            o.oneditfunc.call($t, rowid);
+                        }
+                    }
+                }
+            });
+        },
+        saveRow: function (rowid, successfunc, url, extraparam, aftersavefunc, errorfunc, afterrestorefunc) {
+            // Compatible mode old versions
+            var args = $.makeArray(arguments).slice(1), o = {};
+
+            if ($.type(args[0]) === "object") {
+                o = args[0];
+            } else {
+                if ($.isFunction(successfunc)) {
+                    o.successfunc = successfunc;
+                }
+                if (typeof url !== "undefined") {
+                    o.url = url;
+                }
+                if (typeof extraparam !== "undefined") {
+                    o.extraparam = extraparam;
+                }
+                if ($.isFunction(aftersavefunc)) {
+                    o.aftersavefunc = aftersavefunc;
+                }
+                if ($.isFunction(errorfunc)) {
+                    o.errorfunc = errorfunc;
+                }
+                if ($.isFunction(afterrestorefunc)) {
+                    o.afterrestorefunc = afterrestorefunc;
+                }
+            }
+            o = $.extend(true, {
+                successfunc: null,
+                url: null,
+                extraparam: {},
+                aftersavefunc: null,
+                errorfunc: null,
+                afterrestorefunc: null,
+                restoreAfterError: true,
+                mtype: "POST"
+            }, $.jgrid.inlineEdit, o);
+            // End compatible
+
+            var success = false;
+            var $t = this[0], nm, tmp = {}, tmp2 = {}, tmp3 = {}, editable, fr, cv, ind;
+            if (!$t.grid) {
+                return success;
+            }
+            ind = $($t).jqGrid("getInd", rowid, true);
+            if (ind === false) {
+                return success;
+            }
+            editable = $(ind).attr("editable");
+            o.url = o.url ? o.url : $t.p.editurl;
+            if (editable === "1") {
+                var cm;
+                $('td[role="gridcell"]', ind).each(function (i) {
+                    cm = $t.p.colModel[i];
+                    nm = cm.name;
+                    if (nm != 'cb' && nm != 'subgrid' && cm.editable === true && nm != 'rn' && !$(this).hasClass('not-editable-cell')) {
+                        switch (cm.edittype) {
+                            case "checkbox":
+                                var cbv = ["Yes", "No"];
+                                if (cm.editoptions) {
+                                    cbv = cm.editoptions.value.split(":");
+                                }
+                                tmp[nm] = $("input", this).is(":checked") ? cbv[0] : cbv[1];
+                                break;
+                            case 'text':
+                            case 'password':
+                            case 'textarea':
+                            case "button" :
+                                tmp[nm] = $("input, textarea", this).val();
+                                break;
+                            case 'select':
+                                if (!cm.editoptions.multiple) {
+                                    tmp[nm] = $("select option:selected", this).val();
+                                    tmp2[nm] = $("select option:selected", this).text();
+                                } else {
+                                    var sel = $("select", this), selectedText = [];
+                                    tmp[nm] = $(sel).val();
+                                    if (tmp[nm]) {
+                                        tmp[nm] = tmp[nm].join(",");
+                                    } else {
+                                        tmp[nm] = "";
+                                    }
+                                    $("select option:selected", this).each(
+                                        function (i, selected) {
+                                            selectedText[i] = $(selected).text();
+                                        }
+                                    );
+                                    tmp2[nm] = selectedText.join(",");
+                                }
+                                if (cm.formatter && cm.formatter == 'select') {
+                                    tmp2 = {};
+                                }
+                                break;
+                            case 'custom' :
+                                try {
+                                    if (cm.editoptions && $.isFunction(cm.editoptions.custom_value)) {
+                                        tmp[nm] = cm.editoptions.custom_value.call($t, $(".customelement", this), 'get');
+                                        if (tmp[nm] === undefined) {
+                                            throw "e2";
+                                        }
+                                    } else {
+                                        throw "e1";
+                                    }
+                                } catch (e) {
+                                    if (e == "e1") {
+                                        $.jgrid.info_dialog($.jgrid.errors.errcap, "function 'custom_value' " + $.jgrid.edit.msg.nodefined, $.jgrid.edit.bClose);
+                                    }
+                                    if (e == "e2") {
+                                        $.jgrid.info_dialog($.jgrid.errors.errcap, "function 'custom_value' " + $.jgrid.edit.msg.novalue, $.jgrid.edit.bClose);
+                                    }
+                                    else {
+                                        $.jgrid.info_dialog($.jgrid.errors.errcap, e.message, $.jgrid.edit.bClose);
+                                    }
+                                }
+                                break;
+                        }
+                        cv = $.jgrid.checkValues(tmp[nm], i, $t);
+                        if (cv[0] === false) {
+                            cv[1] = tmp[nm] + " " + cv[1];
+                            return false;
+                        }
+                        if ($t.p.autoencode) {
+                            tmp[nm] = $.jgrid.htmlEncode(tmp[nm]);
+                        }
+                        if (o.url !== 'clientArray' && cm.editoptions && cm.editoptions.NullIfEmpty === true) {
+                            if (tmp[nm] === "") {
+                                tmp3[nm] = 'null';
+                            }
+                        }
+                    }
+                });
+                if (cv[0] === false) {
+                    try {
+                        var positions = $.jgrid.findPos($("#" + $.jgrid.jqID(rowid), $t.grid.bDiv)[0]);
+                        $.jgrid.info_dialog($.jgrid.errors.errcap, cv[1], $.jgrid.edit.bClose, {left: positions[0], top: positions[1]});
+                    } catch (e) {
+                        alert(cv[1]);
+                    }
+                    return success;
+                }
+                var idname, opers, oper;
+                opers = $t.p.prmNames;
+                oper = opers.oper;
+                idname = opers.id;
+                if (tmp) {
+                    tmp[oper] = opers.editoper;
+                    tmp[idname] = rowid;
+                    if (typeof($t.p.inlineData) == 'undefined') {
+                        $t.p.inlineData = {};
+                    }
+                    tmp = $.extend({}, tmp, $t.p.inlineData, o.extraparam);
+                }
+                if (o.url == 'clientArray') {
+                    tmp = $.extend({}, tmp, tmp2);
+                    if ($t.p.autoencode) {
+                        $.each(tmp, function (n, v) {
+                            tmp[n] = $.jgrid.htmlDecode(v);
+                        });
+                    }
+                    var resp = $($t).jqGrid("setRowData", rowid, tmp);
+                    $(ind).attr("editable", "0");
+                    for (var k = 0; k < $t.p.savedRow.length; k++) {
+                        if ($t.p.savedRow[k].id == rowid) {
+                            fr = k;
+                            break;
+                        }
+                    }
+                    if (fr >= 0) {
+                        $t.p.savedRow.splice(fr, 1);
+                    }
+                    $($t).triggerHandler("jqGridInlineAfterSaveRow", [rowid, resp, tmp, o]);
+                    if ($.isFunction(o.aftersavefunc)) {
+                        o.aftersavefunc.call($t, rowid, resp);
+                    }
+                    success = true;
+                    $(ind).unbind("keydown");
+                } else {
+                    $("#lui_" + $.jgrid.jqID($t.p.id)).show();
+                    tmp3 = $.extend({}, tmp, tmp3);
+                    tmp3[idname] = $.jgrid.stripPref($t.p.idPrefix, tmp3[idname]);
+                    $.ajax($.extend({
+                        url: o.url,
+                        data: $.isFunction($t.p.serializeRowData) ? $t.p.serializeRowData.call($t, tmp3) : tmp3,
+                        type: o.mtype,
+                        async: false, //?!?
+                        complete: function (res, stat) {
+                            $("#lui_" + $.jgrid.jqID($t.p.id)).hide();
+                            if (stat === "success") {
+                                var ret = true, sucret;
+                                sucret = $($t).triggerHandler("jqGridInlineSuccessSaveRow", [res, rowid, o]);
+                                if (!$.isArray(sucret)) {
+                                    sucret = [true, tmp];
+                                }
+                                if (sucret[0] && $.isFunction(o.successfunc)) {
+                                    sucret = o.successfunc.call($t, res);
+                                }
+                                if ($.isArray(sucret)) {
+                                    // expect array - status, data, rowid
+                                    ret = sucret[0];
+                                    tmp = sucret[1] ? sucret[1] : tmp;
+                                } else {
+                                    ret = sucret;
+                                }
+                                if (ret === true) {
+                                    if ($t.p.autoencode) {
+                                        $.each(tmp, function (n, v) {
+                                            tmp[n] = $.jgrid.htmlDecode(v);
+                                        });
+                                    }
+                                    tmp = $.extend({}, tmp, tmp2);
+                                    $($t).jqGrid("setRowData", rowid, tmp);
+                                    $(ind).attr("editable", "0");
+                                    for (var k = 0; k < $t.p.savedRow.length; k++) {
+                                        if ($t.p.savedRow[k].id == rowid) {
+                                            fr = k;
+                                            break;
+                                        }
+                                    }
+                                    if (fr >= 0) {
+                                        $t.p.savedRow.splice(fr, 1);
+                                    }
+                                    $($t).triggerHandler("jqGridInlineAfterSaveRow", [rowid, res, tmp, o]);
+                                    if ($.isFunction(o.aftersavefunc)) {
+                                        o.aftersavefunc.call($t, rowid, res);
+                                    }
+                                    success = true;
+                                    $(ind).unbind("keydown");
+                                } else {
+                                    $($t).triggerHandler("jqGridInlineErrorSaveRow", [rowid, res, stat, null, o]);
+                                    if ($.isFunction(o.errorfunc)) {
+                                        o.errorfunc.call($t, rowid, res, stat, null);
+                                    }
+                                    if (o.restoreAfterError === true) {
+                                        $($t).jqGrid("restoreRow", rowid, o.afterrestorefunc);
+                                    }
+                                }
+                            }
+                        },
+                        error: function (res, stat, err) {
+                            $("#lui_" + $.jgrid.jqID($t.p.id)).hide();
+                            $($t).triggerHandler("jqGridInlineErrorSaveRow", [rowid, res, stat, err, o]);
+                            if ($.isFunction(o.errorfunc)) {
+                                o.errorfunc.call($t, rowid, res, stat, err);
+                            } else {
+                                try {
+                                    $.jgrid.info_dialog($.jgrid.errors.errcap, '<div class="ui-state-error">' + res.responseText + '</div>', $.jgrid.edit.bClose, {buttonalign: 'right'});
+                                } catch (e) {
+                                    alert(res.responseText);
+                                }
+                            }
+                            if (o.restoreAfterError === true) {
+                                $($t).jqGrid("restoreRow", rowid, o.afterrestorefunc);
+                            }
+                        }
+                    }, $.jgrid.ajaxOptions, $t.p.ajaxRowOptions || {}));
+                }
+            }
+            return success;
+        },
+        restoreRow: function (rowid, afterrestorefunc) {
+            // Compatible mode old versions
+            var args = $.makeArray(arguments).slice(1), o = {};
+
+            if ($.type(args[0]) === "object") {
+                o = args[0];
+            } else {
+                if ($.isFunction(afterrestorefunc)) {
+                    o.afterrestorefunc = afterrestorefunc;
+                }
+            }
+            o = $.extend(true, $.jgrid.inlineEdit, o);
+
+            // End compatible
+
+            return this.each(function () {
+                var $t = this, fr, ind, ares = {};
+                if (!$t.grid) {
+                    return;
+                }
+                ind = $($t).jqGrid("getInd", rowid, true);
+                if (ind === false) {
+                    return;
+                }
+                for (var k = 0; k < $t.p.savedRow.length; k++) {
+                    if ($t.p.savedRow[k].id == rowid) {
+                        fr = k;
+                        break;
+                    }
+                }
+                if (fr >= 0) {
+                    if ($.isFunction($.fn.datepicker)) {
+                        try {
+                            $("input.hasDatepicker", "#" + $.jgrid.jqID(ind.id)).datepicker('hide');
+                        } catch (e) {
+                        }
+                    }
+                    $.each($t.p.colModel, function () {
+                        if (this.editable === true && this.name in $t.p.savedRow[fr]) {
+                            ares[this.name] = $t.p.savedRow[fr][this.name];
+                        }
+                    });
+                    $($t).jqGrid("setRowData", rowid, ares);
+                    $(ind).attr("editable", "0").unbind("keydown");
+                    $t.p.savedRow.splice(fr, 1);
+                    if ($("#" + $.jgrid.jqID(rowid), "#" + $.jgrid.jqID($t.p.id)).hasClass("jqgrid-new-row")) {
+                        setTimeout(function () {
+                            $($t).jqGrid("delRowData", rowid);
+                        }, 0);
+                    }
+                }
+                $($t).triggerHandler("jqGridInlineAfterRestoreRow", [rowid]);
+                if ($.isFunction(o.afterrestorefunc)) {
+                    o.afterrestorefunc.call($t, rowid);
+                }
+            });
+        },
+        addRow: function (p) {
+            p = $.extend(true, {
+                rowID: "new_row",
+                initdata: {},
+                position: "first",
+                useDefValues: true,
+                useFormatter: false,
+                addRowParams: {extraparam: {}}
+            }, p || {});
+            return this.each(function () {
+                if (!this.grid) {
+                    return;
+                }
+                var $t = this;
+                if (p.useDefValues === true) {
+                    $($t.p.colModel).each(function () {
+                        if (this.editoptions && this.editoptions.defaultValue) {
+                            var opt = this.editoptions.defaultValue,
+                                tmp = $.isFunction(opt) ? opt.call($t) : opt;
+                            p.initdata[this.name] = tmp;
+                        }
+                    });
+                }
+                $($t).jqGrid('addRowData', p.rowID, p.initdata, p.position);
+                p.rowID = $t.p.idPrefix + p.rowID;
+                $("#" + $.jgrid.jqID(p.rowID), "#" + $.jgrid.jqID($t.p.id)).addClass("jqgrid-new-row");
+                if (p.useFormatter) {
+                    $("#" + $.jgrid.jqID(p.rowID) + " .ui-inline-edit", "#" + $.jgrid.jqID($t.p.id)).click();
+                } else {
+                    var opers = $t.p.prmNames,
+                        oper = opers.oper;
+                    p.addRowParams.extraparam[oper] = opers.addoper;
+                    $($t).jqGrid('editRow', p.rowID, p.addRowParams);
+                    $($t).jqGrid('setSelection', p.rowID);
+                }
+            });
+        },
+        inlineNav: function (elem, o) {
+            o = $.extend({
+                edit: true,
+                editicon: "ui-icon-pencil",
+                add: true,
+                addicon: "ui-icon-plus",
+                save: true,
+                saveicon: "ui-icon-disk",
+                cancel: true,
+                cancelicon: "ui-icon-cancel",
+                addParams: {useFormatter: false, rowID: "new_row"},
+                editParams: {},
+                restoreAfterSelect: true
+            }, $.jgrid.nav, o || {});
+            return this.each(function () {
+                if (!this.grid) {
+                    return;
+                }
+                var $t = this, onSelect, gID = $.jgrid.jqID($t.p.id);
+                $t.p._inlinenav = true;
+                // detect the formatactions column
+                if (o.addParams.useFormatter === true) {
+                    var cm = $t.p.colModel, i;
+                    for (i = 0; i < cm.length; i++) {
+                        if (cm[i].formatter && cm[i].formatter === "actions") {
+                            if (cm[i].formatoptions) {
+                                var defaults = {
+                                        keys: false,
+                                        onEdit: null,
+                                        onSuccess: null,
+                                        afterSave: null,
+                                        onError: null,
+                                        afterRestore: null,
+                                        extraparam: {},
+                                        url: null
+                                    },
+                                    ap = $.extend(defaults, cm[i].formatoptions);
+                                o.addParams.addRowParams = {
+                                    "keys": ap.keys,
+                                    "oneditfunc": ap.onEdit,
+                                    "successfunc": ap.onSuccess,
+                                    "url": ap.url,
+                                    "extraparam": ap.extraparam,
+                                    "aftersavefunc": ap.afterSavef,
+                                    "errorfunc": ap.onError,
+                                    "afterrestorefunc": ap.afterRestore
+                                };
+                            }
+                            break;
+                        }
+                    }
+                }
+                if (o.add) {
+                    $($t).jqGrid('navButtonAdd', elem, {
+                        caption: o.addtext,
+                        title: o.addtitle,
+                        buttonicon: o.addicon,
+                        id: $t.p.id + "_iladd",
+                        onClickButton: function () {
+                            $($t).jqGrid('addRow', o.addParams);
+                            if (!o.addParams.useFormatter) {
+                                $("#" + gID + "_ilsave").removeClass('ui-state-disabled');
+                                $("#" + gID + "_ilcancel").removeClass('ui-state-disabled');
+                                $("#" + gID + "_iladd").addClass('ui-state-disabled');
+                                $("#" + gID + "_iledit").addClass('ui-state-disabled');
+                            }
+                        }
+                    });
+                }
+                if (o.edit) {
+                    $($t).jqGrid('navButtonAdd', elem, {
+                        caption: o.edittext,
+                        title: o.edittitle,
+                        buttonicon: o.editicon,
+                        id: $t.p.id + "_iledit",
+                        onClickButton: function () {
+                            var sr = $($t).jqGrid('getGridParam', 'selrow');
+                            if (sr) {
+                                $($t).jqGrid('editRow', sr, o.editParams);
+                                $("#" + gID + "_ilsave").removeClass('ui-state-disabled');
+                                $("#" + gID + "_ilcancel").removeClass('ui-state-disabled');
+                                $("#" + gID + "_iladd").addClass('ui-state-disabled');
+                                $("#" + gID + "_iledit").addClass('ui-state-disabled');
+                            } else {
+                                $.jgrid.viewModal("#alertmod", {gbox: "#gbox_" + gID, jqm: true});
+                                $("#jqg_alrt").focus();
+                            }
+                        }
+                    });
+                }
+                if (o.save) {
+                    $($t).jqGrid('navButtonAdd', elem, {
+                        caption: o.savetext || '',
+                        title: o.savetitle || 'Save row',
+                        buttonicon: o.saveicon,
+                        id: $t.p.id + "_ilsave",
+                        onClickButton: function () {
+                            var sr = $t.p.savedRow[0].id;
+                            if (sr) {
+                                var opers = $t.p.prmNames,
+                                    oper = opers.oper;
+                                if (!o.editParams.extraparam) {
+                                    o.editParams.extraparam = {};
+                                }
+                                if ($("#" + $.jgrid.jqID(sr), "#" + gID).hasClass("jqgrid-new-row")) {
+                                    o.editParams.extraparam[oper] = opers.addoper;
+                                } else {
+                                    o.editParams.extraparam[oper] = opers.editoper;
+                                }
+                                if ($($t).jqGrid('saveRow', sr, o.editParams)) {
+                                    $($t).jqGrid('showAddEditButtons');
+                                }
+                            } else {
+                                $.jgrid.viewModal("#alertmod", {gbox: "#gbox_" + gID, jqm: true});
+                                $("#jqg_alrt").focus();
+                            }
+                        }
+                    });
+                    $("#" + gID + "_ilsave").addClass('ui-state-disabled');
+                }
+                if (o.cancel) {
+                    $($t).jqGrid('navButtonAdd', elem, {
+                        caption: o.canceltext || '',
+                        title: o.canceltitle || 'Cancel row editing',
+                        buttonicon: o.cancelicon,
+                        id: $t.p.id + "_ilcancel",
+                        onClickButton: function () {
+                            var sr = $t.p.savedRow[0].id;
+                            if (sr) {
+                                $($t).jqGrid('restoreRow', sr, o.editParams);
+                                $($t).jqGrid('showAddEditButtons');
+                            } else {
+                                $.jgrid.viewModal("#alertmod", {gbox: "#gbox_" + gID, jqm: true});
+                                $("#jqg_alrt").focus();
+                            }
+                        }
+                    });
+                    $("#" + gID + "_ilcancel").addClass('ui-state-disabled');
+                }
+                if (o.restoreAfterSelect === true) {
+                    if ($.isFunction($t.p.beforeSelectRow)) {
+                        onSelect = $t.p.beforeSelectRow;
+                    } else {
+                        onSelect = false;
+                    }
+                    $t.p.beforeSelectRow = function (id, stat) {
+                        var ret = true;
+                        if ($t.p.savedRow.length > 0 && $t.p._inlinenav === true && ( id !== $t.p.selrow && $t.p.selrow !== null)) {
+                            if ($t.p.selrow == o.addParams.rowID) {
+                                $($t).jqGrid('delRowData', $t.p.selrow);
+                            } else {
+                                $($t).jqGrid('restoreRow', $t.p.selrow, o.editParams);
+                            }
+                            $($t).jqGrid('showAddEditButtons');
+                        }
+                        if (onSelect) {
+                            ret = onSelect.call($t, id, stat);
+                        }
+                        return ret;
+                    };
+                }
+
+            });
+        },
+        showAddEditButtons: function () {
+            return this.each(function () {
+                if (!this.grid) {
+                    return;
+                }
+                var gID = $.jgrid.jqID(this.p.id);
+                $("#" + gID + "_ilsave").addClass('ui-state-disabled');
+                $("#" + gID + "_ilcancel").addClass('ui-state-disabled');
+                $("#" + gID + "_iladd").removeClass('ui-state-disabled');
+                $("#" + gID + "_iledit").removeClass('ui-state-disabled');
+            });
+        }
+//end inline edit
+    });
+})(jQuery);
+;
+(function ($) {
+    /*
+     **
+     * jqGrid extension for cellediting Grid Data
+     * Tony Tomov tony@trirand.com
+     * http://trirand.com/blog/
+     * Dual licensed under the MIT and GPL licenses:
+     * http://www.opensource.org/licenses/mit-license.php
+     * http://www.gnu.org/licenses/gpl-2.0.html
+     **/
+    /**
+     * all events and options here are aded anonynous and not in the base grid
+     * since the array is to big. Here is the order of execution.
+     * From this point we use jQuery isFunction
+     * formatCell
+     * beforeEditCell,
+     * onSelectCell (used only for noneditable cels)
+     * afterEditCell,
+
+     * beforeSaveCell, (called before validation of values if any)
+     * beforeSubmitCell (if cellsubmit remote (ajax))
+     * afterSubmitCell(if cellsubmit remote (ajax)),
+     * afterSaveCell,
+     * errorCell,
+     * serializeCellData - new
+     * Options
+     * cellsubmit (remote,clientArray) (added in grid options)
+     * cellurl
+     * ajaxCellOptions
+     * */
+    "use strict";
+    $.jgrid.extend({
+        editCell: function (iRow, iCol, ed) {
+            return this.each(function () {
+                var $t = this, nm, tmp, cc, cm;
+                if (!$t.grid || $t.p.cellEdit !== true) {
+                    return;
+                }
+                iCol = parseInt(iCol, 10);
+                // select the row that can be used for other methods
+                $t.p.selrow = $t.rows[iRow].id;
+                if (!$t.p.knv) {
+                    $($t).jqGrid("GridNav");
+                }
+                // check to see if we have already edited cell
+                if ($t.p.savedRow.length > 0) {
+                    // prevent second click on that field and enable selects
+                    if (ed === true) {
+                        if (iRow == $t.p.iRow && iCol == $t.p.iCol) {
+                            return;
+                        }
+                    }
+                    // save the cell
+                    $($t).jqGrid("saveCell", $t.p.savedRow[0].id, $t.p.savedRow[0].ic);
+                } else {
+                    window.setTimeout(function () {
+                        $("#" + $.jgrid.jqID($t.p.knv)).attr("tabindex", "-1").focus();
+                    }, 0);
+                }
+                cm = $t.p.colModel[iCol];
+                nm = cm.name;
+                if (nm == 'subgrid' || nm == 'cb' || nm == 'rn') {
+                    return;
+                }
+                cc = $("td:eq(" + iCol + ")", $t.rows[iRow]);
+                if (cm.editable === true && ed === true && !cc.hasClass("not-editable-cell")) {
+                    if (parseInt($t.p.iCol, 10) >= 0 && parseInt($t.p.iRow, 10) >= 0) {
+                        $("td:eq(" + $t.p.iCol + ")", $t.rows[$t.p.iRow]).removeClass("edit-cell ui-state-highlight");
+                        $($t.rows[$t.p.iRow]).removeClass("selected-row ui-state-hover");
+                    }
+                    $(cc).addClass("edit-cell ui-state-highlight");
+                    $($t.rows[iRow]).addClass("selected-row ui-state-hover");
+                    try {
+                        tmp = $.unformat.call($t, cc, {rowId: $t.rows[iRow].id, colModel: cm}, iCol);
+                    } catch (_) {
+                        tmp = ( cm.edittype && cm.edittype == 'textarea' ) ? $(cc).text() : $(cc).html();
+                    }
+                    if ($t.p.autoencode) {
+                        tmp = $.jgrid.htmlDecode(tmp);
+                    }
+                    if (!cm.edittype) {
+                        cm.edittype = "text";
+                    }
+                    $t.p.savedRow.push({id: iRow, ic: iCol, name: nm, v: tmp});
+                    if (tmp === "&nbsp;" || tmp === "&#160;" || (tmp.length === 1 && tmp.charCodeAt(0) === 160)) {
+                        tmp = '';
+                    }
+                    if ($.isFunction($t.p.formatCell)) {
+                        var tmp2 = $t.p.formatCell.call($t, $t.rows[iRow].id, nm, tmp, iRow, iCol);
+                        if (tmp2 !== undefined) {
+                            tmp = tmp2;
+                        }
+                    }
+                    var opt = $.extend({}, cm.editoptions || {}, {id: iRow + "_" + nm, name: nm});
+                    var elc = $.jgrid.createEl.call($t, cm.edittype, opt, tmp, true, $.extend({}, $.jgrid.ajaxOptions, $t.p.ajaxSelectOptions || {}));
+                    $($t).triggerHandler("jqGridBeforeEditCell", [$t.rows[iRow].id, nm, tmp, iRow, iCol]);
+                    if ($.isFunction($t.p.beforeEditCell)) {
+                        $t.p.beforeEditCell.call($t, $t.rows[iRow].id, nm, tmp, iRow, iCol);
+                    }
+                    $(cc).html("").append(elc).attr("tabindex", "0");
+                    window.setTimeout(function () {
+                        $(elc).focus();
+                    }, 0);
+                    $("input, select, textarea", cc).bind("keydown", function (e) {
+                        if (e.keyCode === 27) {
+                            if ($("input.hasDatepicker", cc).length > 0) {
+                                if ($(".ui-datepicker").is(":hidden")) {
+                                    $($t).jqGrid("restoreCell", iRow, iCol);
+                                }
+                                else {
+                                    $("input.hasDatepicker", cc).datepicker('hide');
+                                }
+                            } else {
+                                $($t).jqGrid("restoreCell", iRow, iCol);
+                            }
+                        } //ESC
+                        if (e.keyCode === 13) {
+                            $($t).jqGrid("saveCell", iRow, iCol);
+                            // Prevent default action
+                            return false;
+                        } //Enter
+                        if (e.keyCode === 9) {
+                            if (!$t.grid.hDiv.loading) {
+                                if (e.shiftKey) {
+                                    $($t).jqGrid("prevCell", iRow, iCol);
+                                } //Shift TAb
+                                else {
+                                    $($t).jqGrid("nextCell", iRow, iCol);
+                                } //Tab
+                            } else {
+                                return false;
+                            }
+                        }
+                        e.stopPropagation();
+                    });
+                    $($t).triggerHandler("jqGridAfterEditCell", [$t.rows[iRow].id, nm, tmp, iRow, iCol]);
+                    if ($.isFunction($t.p.afterEditCell)) {
+                        $t.p.afterEditCell.call($t, $t.rows[iRow].id, nm, tmp, iRow, iCol);
+                    }
+                } else {
+                    if (parseInt($t.p.iCol, 10) >= 0 && parseInt($t.p.iRow, 10) >= 0) {
+                        $("td:eq(" + $t.p.iCol + ")", $t.rows[$t.p.iRow]).removeClass("edit-cell ui-state-highlight");
+                        $($t.rows[$t.p.iRow]).removeClass("selected-row ui-state-hover");
+                    }
+                    cc.addClass("edit-cell ui-state-highlight");
+                    $($t.rows[iRow]).addClass("selected-row ui-state-hover");
+                    tmp = cc.html().replace(/\&#160\;/ig, '');
+                    $($t).triggerHandler("jqGridSelectCell", [$t.rows[iRow].id, nm, tmp, iRow, iCol]);
+                    if ($.isFunction($t.p.onSelectCell)) {
+                        $t.p.onSelectCell.call($t, $t.rows[iRow].id, nm, tmp, iRow, iCol);
+                    }
+                }
+                $t.p.iCol = iCol;
+                $t.p.iRow = iRow;
+            });
+        },
+        saveCell: function (iRow, iCol) {
+            return this.each(function () {
+                var $t = this, fr;
+                if (!$t.grid || $t.p.cellEdit !== true) {
+                    return;
+                }
+                if ($t.p.savedRow.length >= 1) {
+                    fr = 0;
+                } else {
+                    fr = null;
+                }
+                if (fr !== null) {
+                    var cc = $("td:eq(" + iCol + ")", $t.rows[iRow]), v, v2,
+                        cm = $t.p.colModel[iCol], nm = cm.name, nmjq = $.jgrid.jqID(nm);
+                    switch (cm.edittype) {
+                        case "select":
+                            if (!cm.editoptions.multiple) {
+                                v = $("#" + iRow + "_" + nmjq + " option:selected", $t.rows[iRow]).val();
+                                v2 = $("#" + iRow + "_" + nmjq + " option:selected", $t.rows[iRow]).text();
+                            } else {
+                                var sel = $("#" + iRow + "_" + nmjq, $t.rows[iRow]), selectedText = [];
+                                v = $(sel).val();
+                                if (v) {
+                                    v.join(",");
+                                } else {
+                                    v = "";
+                                }
+                                $("option:selected", sel).each(
+                                    function (i, selected) {
+                                        selectedText[i] = $(selected).text();
+                                    }
+                                );
+                                v2 = selectedText.join(",");
+                            }
+                            if (cm.formatter) {
+                                v2 = v;
+                            }
+                            break;
+                        case "checkbox":
+                            var cbv = ["Yes", "No"];
+                            if (cm.editoptions) {
+                                cbv = cm.editoptions.value.split(":");
+                            }
+                            v = $("#" + iRow + "_" + nmjq, $t.rows[iRow]).is(":checked") ? cbv[0] : cbv[1];
+                            v2 = v;
+                            break;
+                        case "password":
+                        case "text":
+                        case "textarea":
+                        case "button" :
+                            v = $("#" + iRow + "_" + nmjq, $t.rows[iRow]).val();
+                            v2 = v;
+                            break;
+                        case 'custom' :
+                            try {
+                                if (cm.editoptions && $.isFunction(cm.editoptions.custom_value)) {
+                                    v = cm.editoptions.custom_value.call($t, $(".customelement", cc), 'get');
+                                    if (v === undefined) {
+                                        throw "e2";
+                                    } else {
+                                        v2 = v;
+                                    }
+                                } else {
+                                    throw "e1";
+                                }
+                            } catch (e) {
+                                if (e == "e1") {
+                                    $.jgrid.info_dialog(jQuery.jgrid.errors.errcap, "function 'custom_value' " + $.jgrid.edit.msg.nodefined, jQuery.jgrid.edit.bClose);
+                                }
+                                if (e == "e2") {
+                                    $.jgrid.info_dialog(jQuery.jgrid.errors.errcap, "function 'custom_value' " + $.jgrid.edit.msg.novalue, jQuery.jgrid.edit.bClose);
+                                }
+                                else {
+                                    $.jgrid.info_dialog(jQuery.jgrid.errors.errcap, e.message, jQuery.jgrid.edit.bClose);
+                                }
+                            }
+                            break;
+                    }
+                    // The common approach is if nothing changed do not do anything
+                    if (v2 !== $t.p.savedRow[fr].v) {
+                        var vvv = $($t).triggerHandler("jqGridBeforeSaveCell", [$t.rows[iRow].id, nm, v, iRow, iCol]);
+                        if (vvv) {
+                            v = vvv;
+                            v2 = vvv;
+                        }
+                        if ($.isFunction($t.p.beforeSaveCell)) {
+                            var vv = $t.p.beforeSaveCell.call($t, $t.rows[iRow].id, nm, v, iRow, iCol);
+                            if (vv) {
+                                v = vv;
+                                v2 = vv;
+                            }
+                        }
+                        var cv = $.jgrid.checkValues(v, iCol, $t);
+                        if (cv[0] === true) {
+                            var addpost = $($t).triggerHandler("jqGridBeforeSubmitCell", [$t.rows[iRow].id, nm, v, iRow, iCol]) || {};
+                            if ($.isFunction($t.p.beforeSubmitCell)) {
+                                addpost = $t.p.beforeSubmitCell.call($t, $t.rows[iRow].id, nm, v, iRow, iCol);
+                                if (!addpost) {
+                                    addpost = {};
+                                }
+                            }
+                            if ($("input.hasDatepicker", cc).length > 0) {
+                                $("input.hasDatepicker", cc).datepicker('hide');
+                            }
+                            if ($t.p.cellsubmit == 'remote') {
+                                if ($t.p.cellurl) {
+                                    var postdata = {};
+                                    if ($t.p.autoencode) {
+                                        v = $.jgrid.htmlEncode(v);
+                                    }
+                                    postdata[nm] = v;
+                                    var idname, oper, opers;
+                                    opers = $t.p.prmNames;
+                                    idname = opers.id;
+                                    oper = opers.oper;
+                                    postdata[idname] = $.jgrid.stripPref($t.p.idPrefix, $t.rows[iRow].id);
+                                    postdata[oper] = opers.editoper;
+                                    postdata = $.extend(addpost, postdata);
+                                    $("#lui_" + $.jgrid.jqID($t.p.id)).show();
+                                    $t.grid.hDiv.loading = true;
+                                    $.ajax($.extend({
+                                        url: $t.p.cellurl,
+                                        data: $.isFunction($t.p.serializeCellData) ? $t.p.serializeCellData.call($t, postdata) : postdata,
+                                        type: "POST",
+                                        complete: function (result, stat) {
+                                            $("#lui_" + $t.p.id).hide();
+                                            $t.grid.hDiv.loading = false;
+                                            if (stat == 'success') {
+                                                var ret = $($t).triggerHandler("jqGridAfterSubmitCell", [$t, result, postdata.id, nm, v, iRow, iCol]) || [true, ''];
+                                                if (ret[0] === true && $.isFunction($t.p.afterSubmitCell)) {
+                                                    ret = $t.p.afterSubmitCell.call($t, result, postdata.id, nm, v, iRow, iCol);
+                                                }
+                                                if (ret[0] === true) {
+                                                    $(cc).empty();
+                                                    $($t).jqGrid("setCell", $t.rows[iRow].id, iCol, v2, false, false, true);
+                                                    $(cc).addClass("dirty-cell");
+                                                    $($t.rows[iRow]).addClass("edited");
+                                                    $($t).triggerHandler("jqGridAfterSaveCell", [$t.rows[iRow].id, nm, v, iRow, iCol]);
+                                                    if ($.isFunction($t.p.afterSaveCell)) {
+                                                        $t.p.afterSaveCell.call($t, $t.rows[iRow].id, nm, v, iRow, iCol);
+                                                    }
+                                                    $t.p.savedRow.splice(0, 1);
+                                                } else {
+                                                    $.jgrid.info_dialog($.jgrid.errors.errcap, ret[1], $.jgrid.edit.bClose);
+                                                    $($t).jqGrid("restoreCell", iRow, iCol);
+                                                }
+                                            }
+                                        },
+                                        error: function (res, stat, err) {
+                                            $("#lui_" + $.jgrid.jqID($t.p.id)).hide();
+                                            $t.grid.hDiv.loading = false;
+                                            $($t).triggerHandler("jqGridErrorCell", [res, stat, err]);
+                                            if ($.isFunction($t.p.errorCell)) {
+                                                $t.p.errorCell.call($t, res, stat, err);
+                                                $($t).jqGrid("restoreCell", iRow, iCol);
+                                            } else {
+                                                $.jgrid.info_dialog($.jgrid.errors.errcap, res.status + " : " + res.statusText + "<br/>" + stat, $.jgrid.edit.bClose);
+                                                $($t).jqGrid("restoreCell", iRow, iCol);
+                                            }
+                                        }
+                                    }, $.jgrid.ajaxOptions, $t.p.ajaxCellOptions || {}));
+                                } else {
+                                    try {
+                                        $.jgrid.info_dialog($.jgrid.errors.errcap, $.jgrid.errors.nourl, $.jgrid.edit.bClose);
+                                        $($t).jqGrid("restoreCell", iRow, iCol);
+                                    } catch (e) {
+                                    }
+                                }
+                            }
+                            if ($t.p.cellsubmit == 'clientArray') {
+                                $(cc).empty();
+                                $($t).jqGrid("setCell", $t.rows[iRow].id, iCol, v2, false, false, true);
+                                $(cc).addClass("dirty-cell");
+                                $($t.rows[iRow]).addClass("edited");
+                                $($t).triggerHandler("jqGridAfterSaveCell", [$t.rows[iRow].id, nm, v, iRow, iCol]);
+                                if ($.isFunction($t.p.afterSaveCell)) {
+                                    $t.p.afterSaveCell.call($t, $t.rows[iRow].id, nm, v, iRow, iCol);
+                                }
+                                $t.p.savedRow.splice(0, 1);
+                            }
+                        } else {
+                            try {
+                                window.setTimeout(function () {
+                                    $.jgrid.info_dialog($.jgrid.errors.errcap, v + " " + cv[1], $.jgrid.edit.bClose);
+                                }, 100);
+                                $($t).jqGrid("restoreCell", iRow, iCol);
+                            } catch (e) {
+                            }
+                        }
+                    } else {
+                        $($t).jqGrid("restoreCell", iRow, iCol);
+                    }
+                }
+                if ($.browser.opera) {
+                    $("#" + $.jgrid.jqID($t.p.knv)).attr("tabindex", "-1").focus();
+                } else {
+                    window.setTimeout(function () {
+                        $("#" + $.jgrid.jqID($t.p.knv)).attr("tabindex", "-1").focus();
+                    }, 0);
+                }
+            });
+        },
+        restoreCell: function (iRow, iCol) {
+            return this.each(function () {
+                var $t = this, fr;
+                if (!$t.grid || $t.p.cellEdit !== true) {
+                    return;
+                }
+                if ($t.p.savedRow.length >= 1) {
+                    fr = 0;
+                } else {
+                    fr = null;
+                }
+                if (fr !== null) {
+                    var cc = $("td:eq(" + iCol + ")", $t.rows[iRow]);
+                    // datepicker fix
+                    if ($.isFunction($.fn.datepicker)) {
+                        try {
+                            $("input.hasDatepicker", cc).datepicker('hide');
+                        } catch (e) {
+                        }
+                    }
+                    $(cc).empty().attr("tabindex", "-1");
+                    $($t).jqGrid("setCell", $t.rows[iRow].id, iCol, $t.p.savedRow[fr].v, false, false, true);
+                    $($t).triggerHandler("jqGridAfterRestoreCell", [$t.rows[iRow].id, $t.p.savedRow[fr].v, iRow, iCol]);
+                    if ($.isFunction($t.p.afterRestoreCell)) {
+                        $t.p.afterRestoreCell.call($t, $t.rows[iRow].id, $t.p.savedRow[fr].v, iRow, iCol);
+                    }
+                    $t.p.savedRow.splice(0, 1);
+                }
+                window.setTimeout(function () {
+                    $("#" + $t.p.knv).attr("tabindex", "-1").focus();
+                }, 0);
+            });
+        },
+        nextCell: function (iRow, iCol) {
+            return this.each(function () {
+                var $t = this, nCol = false;
+                if (!$t.grid || $t.p.cellEdit !== true) {
+                    return;
+                }
+                // try to find next editable cell
+                for (var i = iCol + 1; i < $t.p.colModel.length; i++) {
+                    if ($t.p.colModel[i].editable === true) {
+                        nCol = i;
+                        break;
+                    }
+                }
+                if (nCol !== false) {
+                    $($t).jqGrid("editCell", iRow, nCol, true);
+                } else {
+                    if ($t.p.savedRow.length > 0) {
+                        $($t).jqGrid("saveCell", iRow, iCol);
+                    }
+                }
+            });
+        },
+        prevCell: function (iRow, iCol) {
+            return this.each(function () {
+                var $t = this, nCol = false;
+                if (!$t.grid || $t.p.cellEdit !== true) {
+                    return;
+                }
+                // try to find next editable cell
+                for (var i = iCol - 1; i >= 0; i--) {
+                    if ($t.p.colModel[i].editable === true) {
+                        nCol = i;
+                        break;
+                    }
+                }
+                if (nCol !== false) {
+                    $($t).jqGrid("editCell", iRow, nCol, true);
+                } else {
+                    if ($t.p.savedRow.length > 0) {
+                        $($t).jqGrid("saveCell", iRow, iCol);
+                    }
+                }
+            });
+        },
+        GridNav: function () {
+            return this.each(function () {
+                var $t = this;
+                if (!$t.grid || $t.p.cellEdit !== true) {
+                    return;
+                }
+                // trick to process keydown on non input elements
+                $t.p.knv = $t.p.id + "_kn";
+                var selection = $("<span style='width:0px;height:0px;background-color:black;' tabindex='0'><span tabindex='-1' style='width:0px;height:0px;background-color:grey' id='" + $t.p.knv + "'></span></span>"),
+                    i, kdir;
+
+                function scrollGrid(iR, iC, tp) {
+                    if (tp.substr(0, 1) == 'v') {
+                        var ch = $($t.grid.bDiv)[0].clientHeight,
+                            st = $($t.grid.bDiv)[0].scrollTop,
+                            nROT = $t.rows[iR].offsetTop + $t.rows[iR].clientHeight,
+                            pROT = $t.rows[iR].offsetTop;
+                        if (tp == 'vd') {
+                            if (nROT >= ch) {
+                                $($t.grid.bDiv)[0].scrollTop = $($t.grid.bDiv)[0].scrollTop + $t.rows[iR].clientHeight;
+                            }
+                        }
+                        if (tp == 'vu') {
+                            if (pROT < st) {
+                                $($t.grid.bDiv)[0].scrollTop = $($t.grid.bDiv)[0].scrollTop - $t.rows[iR].clientHeight;
+                            }
+                        }
+                    }
+                    if (tp == 'h') {
+                        var cw = $($t.grid.bDiv)[0].clientWidth,
+                            sl = $($t.grid.bDiv)[0].scrollLeft,
+                            nCOL = $t.rows[iR].cells[iC].offsetLeft + $t.rows[iR].cells[iC].clientWidth,
+                            pCOL = $t.rows[iR].cells[iC].offsetLeft;
+                        if (nCOL >= cw + parseInt(sl, 10)) {
+                            $($t.grid.bDiv)[0].scrollLeft = $($t.grid.bDiv)[0].scrollLeft + $t.rows[iR].cells[iC].clientWidth;
+                        } else if (pCOL < sl) {
+                            $($t.grid.bDiv)[0].scrollLeft = $($t.grid.bDiv)[0].scrollLeft - $t.rows[iR].cells[iC].clientWidth;
+                        }
+                    }
+                }
+
+                function findNextVisible(iC, act) {
+                    var ind, i;
+                    if (act == 'lft') {
+                        ind = iC + 1;
+                        for (i = iC; i >= 0; i--) {
+                            if ($t.p.colModel[i].hidden !== true) {
+                                ind = i;
+                                break;
+                            }
+                        }
+                    }
+                    if (act == 'rgt') {
+                        ind = iC - 1;
+                        for (i = iC; i < $t.p.colModel.length; i++) {
+                            if ($t.p.colModel[i].hidden !== true) {
+                                ind = i;
+                                break;
+                            }
+                        }
+                    }
+                    return ind;
+                }
+
+                $(selection).insertBefore($t.grid.cDiv);
+                $("#" + $t.p.knv)
+                    .focus()
+                    .keydown(function (e) {
+                        kdir = e.keyCode;
+                        if ($t.p.direction == "rtl") {
+                            if (kdir === 37) {
+                                kdir = 39;
+                            }
+                            else if (kdir === 39) {
+                                kdir = 37;
+                            }
+                        }
+                        switch (kdir) {
+                            case 38:
+                                if ($t.p.iRow - 1 > 0) {
+                                    scrollGrid($t.p.iRow - 1, $t.p.iCol, 'vu');
+                                    $($t).jqGrid("editCell", $t.p.iRow - 1, $t.p.iCol, false);
+                                }
+                                break;
+                            case 40 :
+                                if ($t.p.iRow + 1 <= $t.rows.length - 1) {
+                                    scrollGrid($t.p.iRow + 1, $t.p.iCol, 'vd');
+                                    $($t).jqGrid("editCell", $t.p.iRow + 1, $t.p.iCol, false);
+                                }
+                                break;
+                            case 37 :
+                                if ($t.p.iCol - 1 >= 0) {
+                                    i = findNextVisible($t.p.iCol - 1, 'lft');
+                                    scrollGrid($t.p.iRow, i, 'h');
+                                    $($t).jqGrid("editCell", $t.p.iRow, i, false);
+                                }
+                                break;
+                            case 39 :
+                                if ($t.p.iCol + 1 <= $t.p.colModel.length - 1) {
+                                    i = findNextVisible($t.p.iCol + 1, 'rgt');
+                                    scrollGrid($t.p.iRow, i, 'h');
+                                    $($t).jqGrid("editCell", $t.p.iRow, i, false);
+                                }
+                                break;
+                            case 13:
+                                if (parseInt($t.p.iCol, 10) >= 0 && parseInt($t.p.iRow, 10) >= 0) {
+                                    $($t).jqGrid("editCell", $t.p.iRow, $t.p.iCol, true);
+                                }
+                                break;
+                            default :
+                                return true;
+                        }
+                        return false;
+                    });
+            });
+        },
+        getChangedCells: function (mthd) {
+            var ret = [];
+            if (!mthd) {
+                mthd = 'all';
+            }
+            this.each(function () {
+                var $t = this, nm;
+                if (!$t.grid || $t.p.cellEdit !== true) {
+                    return;
+                }
+                $($t.rows).each(function (j) {
+                    var res = {};
+                    if ($(this).hasClass("edited")) {
+                        $('td', this).each(function (i) {
+                            nm = $t.p.colModel[i].name;
+                            if (nm !== 'cb' && nm !== 'subgrid') {
+                                if (mthd == 'dirty') {
+                                    if ($(this).hasClass('dirty-cell')) {
+                                        try {
+                                            res[nm] = $.unformat.call($t, this, {rowId: $t.rows[j].id, colModel: $t.p.colModel[i]}, i);
+                                        } catch (e) {
+                                            res[nm] = $.jgrid.htmlDecode($(this).html());
+                                        }
+                                    }
+                                } else {
+                                    try {
+                                        res[nm] = $.unformat.call($t, this, {rowId: $t.rows[j].id, colModel: $t.p.colModel[i]}, i);
+                                    } catch (e) {
+                                        res[nm] = $.jgrid.htmlDecode($(this).html());
+                                    }
+                                }
+                            }
+                        });
+                        res.id = this.id;
+                        ret.push(res);
+                    }
+                });
+            });
+            return ret;
+        }
+/// end  cell editing
+    });
+})(jQuery);
+;
+(function ($) {
+    /**
+     * jqGrid extension for SubGrid Data
+     * Tony Tomov tony@trirand.com
+     * http://trirand.com/blog/
+     * Dual licensed under the MIT and GPL licenses:
+     * http://www.opensource.org/licenses/mit-license.php
+     * http://www.gnu.org/licenses/gpl-2.0.html
+     **/
+    "use strict";
+    $.jgrid.extend({
+        setSubGrid: function () {
+            return this.each(function () {
+                var $t = this, cm,
+                    suboptions = {
+                        plusicon: "ui-icon-plus",
+                        minusicon: "ui-icon-minus",
+                        openicon: "ui-icon-carat-1-sw",
+                        expandOnLoad: false,
+                        delayOnLoad: 50,
+                        selectOnExpand: false,
+                        reloadOnExpand: true
+                    };
+                $t.p.subGridOptions = $.extend(suboptions, $t.p.subGridOptions || {});
+                $t.p.colNames.unshift("");
+                $t.p.colModel.unshift({name: 'subgrid', width: $.browser.safari ? $t.p.subGridWidth + $t.p.cellLayout : $t.p.subGridWidth, sortable: false, resizable: false, hidedlg: true, search: false, fixed: true});
+                cm = $t.p.subGridModel;
+                if (cm[0]) {
+                    cm[0].align = $.extend([], cm[0].align || []);
+                    for (var i = 0; i < cm[0].name.length; i++) {
+                        cm[0].align[i] = cm[0].align[i] || 'left';
+                    }
+                }
+            });
+        },
+        addSubGridCell: function (pos, iRow) {
+            var prp = '', ic, sid;
+            this.each(function () {
+                prp = this.formatCol(pos, iRow);
+                sid = this.p.id;
+                ic = this.p.subGridOptions.plusicon;
+            });
+            return "<td role=\"gridcell\" aria-describedby=\"" + sid + "_subgrid\" class=\"ui-sgcollapsed sgcollapsed\" " + prp + "><a href='javascript:void(0);'><span class='ui-icon " + ic + "'></span></a></td>";
+        },
+        addSubGrid: function (pos, sind) {
+            return this.each(function () {
+                var ts = this;
+                if (!ts.grid) {
+                    return;
+                }
+                //-------------------------
+                var subGridCell = function (trdiv, cell, pos) {
+                    var tddiv = $("<td align='" + ts.p.subGridModel[0].align[pos] + "'></td>").html(cell);
+                    $(trdiv).append(tddiv);
+                };
+                var subGridXml = function (sjxml, sbid) {
+                    var tddiv, i, sgmap,
+                        dummy = $("<table cellspacing='0' cellpadding='0' border='0'><tbody></tbody></table>"),
+                        trdiv = $("<tr></tr>");
+                    for (i = 0; i < ts.p.subGridModel[0].name.length; i++) {
+                        tddiv = $("<th class='ui-state-default ui-th-subgrid ui-th-column ui-th-" + ts.p.direction + "'></th>");
+                        $(tddiv).html(ts.p.subGridModel[0].name[i]);
+                        $(tddiv).width(ts.p.subGridModel[0].width[i]);
+                        $(trdiv).append(tddiv);
+                    }
+                    $(dummy).append(trdiv);
+                    if (sjxml) {
+                        sgmap = ts.p.xmlReader.subgrid;
+                        $(sgmap.root + " " + sgmap.row, sjxml).each(function () {
+                            trdiv = $("<tr class='ui-widget-content ui-subtblcell'></tr>");
+                            if (sgmap.repeatitems === true) {
+                                $(sgmap.cell, this).each(function (i) {
+                                    subGridCell(trdiv, $(this).text() || '&#160;', i);
+                                });
+                            } else {
+                                var f = ts.p.subGridModel[0].mapping || ts.p.subGridModel[0].name;
+                                if (f) {
+                                    for (i = 0; i < f.length; i++) {
+                                        subGridCell(trdiv, $(f[i], this).text() || '&#160;', i);
+                                    }
+                                }
+                            }
+                            $(dummy).append(trdiv);
+                        });
+                    }
+                    var pID = $("table:first", ts.grid.bDiv).attr("id") + "_";
+                    $("#" + $.jgrid.jqID(pID + sbid)).append(dummy);
+                    ts.grid.hDiv.loading = false;
+                    $("#load_" + $.jgrid.jqID(ts.p.id)).hide();
+                    return false;
+                };
+                var subGridJson = function (sjxml, sbid) {
+                    var tddiv, result , i, cur, sgmap, j,
+                        dummy = $("<table cellspacing='0' cellpadding='0' border='0'><tbody></tbody></table>"),
+                        trdiv = $("<tr></tr>");
+                    for (i = 0; i < ts.p.subGridModel[0].name.length; i++) {
+                        tddiv = $("<th class='ui-state-default ui-th-subgrid ui-th-column ui-th-" + ts.p.direction + "'></th>");
+                        $(tddiv).html(ts.p.subGridModel[0].name[i]);
+                        $(tddiv).width(ts.p.subGridModel[0].width[i]);
+                        $(trdiv).append(tddiv);
+                    }
+                    $(dummy).append(trdiv);
+                    if (sjxml) {
+                        sgmap = ts.p.jsonReader.subgrid;
+                        result = sjxml[sgmap.root];
+                        if (typeof result !== 'undefined') {
+                            for (i = 0; i < result.length; i++) {
+                                cur = result[i];
+                                trdiv = $("<tr class='ui-widget-content ui-subtblcell'></tr>");
+                                if (sgmap.repeatitems === true) {
+                                    if (sgmap.cell) {
+                                        cur = cur[sgmap.cell];
+                                    }
+                                    for (j = 0; j < cur.length; j++) {
+                                        subGridCell(trdiv, cur[j] || '&#160;', j);
+                                    }
+                                } else {
+                                    var f = ts.p.subGridModel[0].mapping || ts.p.subGridModel[0].name;
+                                    if (f.length) {
+                                        for (j = 0; j < f.length; j++) {
+                                            subGridCell(trdiv, cur[f[j]] || '&#160;', j);
+                                        }
+                                    }
+                                }
+                                $(dummy).append(trdiv);
+                            }
+                        }
+                    }
+                    var pID = $("table:first", ts.grid.bDiv).attr("id") + "_";
+                    $("#" + $.jgrid.jqID(pID + sbid)).append(dummy);
+                    ts.grid.hDiv.loading = false;
+                    $("#load_" + $.jgrid.jqID(ts.p.id)).hide();
+                    return false;
+                };
+                var populatesubgrid = function (rd) {
+                    var sid, dp, i, j;
+                    sid = $(rd).attr("id");
+                    dp = {nd_: (new Date().getTime())};
+                    dp[ts.p.prmNames.subgridid] = sid;
+                    if (!ts.p.subGridModel[0]) {
+                        return false;
+                    }
+                    if (ts.p.subGridModel[0].params) {
+                        for (j = 0; j < ts.p.subGridModel[0].params.length; j++) {
+                            for (i = 0; i < ts.p.colModel.length; i++) {
+                                if (ts.p.colModel[i].name === ts.p.subGridModel[0].params[j]) {
+                                    dp[ts.p.colModel[i].name] = $("td:eq(" + i + ")", rd).text().replace(/\&#160\;/ig, '');
+                                }
+                            }
+                        }
+                    }
+                    if (!ts.grid.hDiv.loading) {
+                        ts.grid.hDiv.loading = true;
+                        $("#load_" + $.jgrid.jqID(ts.p.id)).show();
+                        if (!ts.p.subgridtype) {
+                            ts.p.subgridtype = ts.p.datatype;
+                        }
+                        if ($.isFunction(ts.p.subgridtype)) {
+                            ts.p.subgridtype.call(ts, dp);
+                        } else {
+                            ts.p.subgridtype = ts.p.subgridtype.toLowerCase();
+                        }
+                        switch (ts.p.subgridtype) {
+                            case "xml":
+                            case "json":
+                                $.ajax($.extend({
+                                    type: ts.p.mtype,
+                                    url: ts.p.subGridUrl,
+                                    dataType: ts.p.subgridtype,
+                                    data: $.isFunction(ts.p.serializeSubGridData) ? ts.p.serializeSubGridData.call(ts, dp) : dp,
+                                    complete: function (sxml) {
+                                        if (ts.p.subgridtype === "xml") {
+                                            subGridXml(sxml.responseXML, sid);
+                                        } else {
+                                            subGridJson($.jgrid.parse(sxml.responseText), sid);
+                                        }
+                                        sxml = null;
+                                    }
+                                }, $.jgrid.ajaxOptions, ts.p.ajaxSubgridOptions || {}));
+                                break;
+                        }
+                    }
+                    return false;
+                };
+                var _id, pID, atd, nhc = 0, bfsc, r;
+                $.each(ts.p.colModel, function () {
+                    if (this.hidden === true || this.name === 'rn' || this.name === 'cb') {
+                        nhc++;
+                    }
+                });
+                var len = ts.rows.length, i = 1;
+                if (sind !== undefined && sind > 0) {
+                    i = sind;
+                    len = sind + 1;
+                }
+                while (i < len) {
+                    if ($(ts.rows[i]).hasClass('jqgrow')) {
+                        $(ts.rows[i].cells[pos]).bind('click', function () {
+                            var tr = $(this).parent("tr")[0];
+                            r = tr.nextSibling;
+                            if ($(this).hasClass("sgcollapsed")) {
+                                pID = ts.p.id;
+                                _id = tr.id;
+                                if (ts.p.subGridOptions.reloadOnExpand === true || ( ts.p.subGridOptions.reloadOnExpand === false && !$(r).hasClass('ui-subgrid') )) {
+                                    atd = pos >= 1 ? "<td colspan='" + pos + "'>&#160;</td>" : "";
+                                    bfsc = $(ts).triggerHandler("jqGridSubGridBeforeExpand", [pID + "_" + _id, _id]);
+                                    bfsc = (bfsc === false || bfsc === 'stop') ? false : true;
+                                    if (bfsc && $.isFunction(ts.p.subGridBeforeExpand)) {
+                                        bfsc = ts.p.subGridBeforeExpand.call(ts, pID + "_" + _id, _id);
+                                    }
+                                    if (bfsc === false) {
+                                        return false;
+                                    }
+                                    $(tr).after("<tr role='row' class='ui-subgrid'>" + atd + "<td class='ui-widget-content subgrid-cell'><span class='ui-icon " + ts.p.subGridOptions.openicon + "'></span></td><td colspan='" + parseInt(ts.p.colNames.length - 1 - nhc, 10) + "' class='ui-widget-content subgrid-data'><div id=" + pID + "_" + _id + " class='tablediv'></div></td></tr>");
+                                    $(ts).triggerHandler("jqGridSubGridRowExpanded", [pID + "_" + _id, _id]);
+                                    if ($.isFunction(ts.p.subGridRowExpanded)) {
+                                        ts.p.subGridRowExpanded.call(ts, pID + "_" + _id, _id);
+                                    } else {
+                                        populatesubgrid(tr);
+                                    }
+                                } else {
+                                    $(r).show();
+                                }
+                                $(this).html("<a href='javascript:void(0);'><span class='ui-icon " + ts.p.subGridOptions.minusicon + "'></span></a>").removeClass("sgcollapsed").addClass("sgexpanded");
+                                if (ts.p.subGridOptions.selectOnExpand) {
+                                    $(ts).jqGrid('setSelection', _id);
+                                }
+                            } else if ($(this).hasClass("sgexpanded")) {
+                                bfsc = $(ts).triggerHandler("jqGridSubGridRowColapsed", [pID + "_" + _id, _id]);
+                                bfsc = (bfsc === false || bfsc === 'stop') ? false : true;
+                                if (bfsc && $.isFunction(ts.p.subGridRowColapsed)) {
+                                    _id = tr.id;
+                                    bfsc = ts.p.subGridRowColapsed.call(ts, pID + "_" + _id, _id);
+                                }
+                                if (bfsc === false) {
+                                    return false;
+                                }
+                                if (ts.p.subGridOptions.reloadOnExpand === true) {
+                                    $(r).remove(".ui-subgrid");
+                                } else if ($(r).hasClass('ui-subgrid')) { // incase of dynamic deleting
+                                    $(r).hide();
+                                }
+                                $(this).html("<a href='javascript:void(0);'><span class='ui-icon " + ts.p.subGridOptions.plusicon + "'></span></a>").removeClass("sgexpanded").addClass("sgcollapsed");
+                            }
+                            return false;
+                        });
+                    }
+                    i++;
+                }
+                if (ts.p.subGridOptions.expandOnLoad === true) {
+                    $(ts.rows).filter('.jqgrow').each(function (index, row) {
+                        $(row.cells[0]).click();
+                    });
+                }
+                ts.subGridXml = function (xml, sid) {
+                    subGridXml(xml, sid);
+                };
+                ts.subGridJson = function (json, sid) {
+                    subGridJson(json, sid);
+                };
+            });
+        },
+        expandSubGridRow: function (rowid) {
+            return this.each(function () {
+                var $t = this;
+                if (!$t.grid && !rowid) {
+                    return;
+                }
+                if ($t.p.subGrid === true) {
+                    var rc = $(this).jqGrid("getInd", rowid, true);
+                    if (rc) {
+                        var sgc = $("td.sgcollapsed", rc)[0];
+                        if (sgc) {
+                            $(sgc).trigger("click");
+                        }
+                    }
+                }
+            });
+        },
+        collapseSubGridRow: function (rowid) {
+            return this.each(function () {
+                var $t = this;
+                if (!$t.grid && !rowid) {
+                    return;
+                }
+                if ($t.p.subGrid === true) {
+                    var rc = $(this).jqGrid("getInd", rowid, true);
+                    if (rc) {
+                        var sgc = $("td.sgexpanded", rc)[0];
+                        if (sgc) {
+                            $(sgc).trigger("click");
+                        }
+                    }
+                }
+            });
+        },
+        toggleSubGridRow: function (rowid) {
+            return this.each(function () {
+                var $t = this;
+                if (!$t.grid && !rowid) {
+                    return;
+                }
+                if ($t.p.subGrid === true) {
+                    var rc = $(this).jqGrid("getInd", rowid, true);
+                    if (rc) {
+                        var sgc = $("td.sgcollapsed", rc)[0];
+                        if (sgc) {
+                            $(sgc).trigger("click");
+                        } else {
+                            sgc = $("td.sgexpanded", rc)[0];
+                            if (sgc) {
+                                $(sgc).trigger("click");
+                            }
+                        }
+                    }
+                }
+            });
+        }
+    });
+})(jQuery);
+/**
+ * jqGrid extension - Tree Grid
+ * Tony Tomov tony@trirand.com
+ * http://trirand.com/blog/
+ * Dual licensed under the MIT and GPL licenses:
+ * http://www.opensource.org/licenses/mit-license.php
+ * http://www.gnu.org/licenses/gpl.html
+ **/
+
+/*global document, jQuery, $ */
+(function ($) {
+    "use strict";
+    $.jgrid.extend({
+        setTreeNode: function (i, len) {
+            return this.each(function () {
+                var $t = this;
+                if (!$t.grid || !$t.p.treeGrid) {
+                    return;
+                }
+                var expCol = $t.p.expColInd,
+                    expanded = $t.p.treeReader.expanded_field,
+                    isLeaf = $t.p.treeReader.leaf_field,
+                    level = $t.p.treeReader.level_field,
+                    icon = $t.p.treeReader.icon_field,
+                    loaded = $t.p.treeReader.loaded, lft, rgt, curLevel, ident, lftpos, twrap,
+                    ldat, lf;
+                while (i < len) {
+                    var ind = $t.rows[i].id, dind = $t.p._index[ind], expan;
+                    ldat = $t.p.data[dind];
+                    //$t.rows[i].level = ldat[level];
+                    if ($t.p.treeGridModel == 'nested') {
+                        if (!ldat[isLeaf]) {
+                            lft = parseInt(ldat[$t.p.treeReader.left_field], 10);
+                            rgt = parseInt(ldat[$t.p.treeReader.right_field], 10);
+                            // NS Model
+                            ldat[isLeaf] = (rgt === lft + 1) ? 'true' : 'false';
+                            $t.rows[i].cells[$t.p._treeleafpos].innerHTML = ldat[isLeaf];
+                        }
+                    }
+                    //else {
+                    //row.parent_id = rd[$t.p.treeReader.parent_id_field];
+                    //}
+                    curLevel = parseInt(ldat[level], 10);
+                    if ($t.p.tree_root_level === 0) {
+                        ident = curLevel + 1;
+                        lftpos = curLevel;
+                    } else {
+                        ident = curLevel;
+                        lftpos = curLevel - 1;
+                    }
+                    twrap = "<div class='tree-wrap tree-wrap-" + $t.p.direction + "' style='width:" + (ident * 18) + "px;'>";
+                    twrap += "<div style='" + ($t.p.direction == "rtl" ? "right:" : "left:") + (lftpos * 18) + "px;' class='ui-icon ";
+
+
+                    if (ldat[loaded] !== undefined) {
+                        if (ldat[loaded] == "true" || ldat[loaded] === true) {
+                            ldat[loaded] = true;
+                        } else {
+                            ldat[loaded] = false;
+                        }
+                    }
+                    if (ldat[isLeaf] == "true" || ldat[isLeaf] === true) {
+                        twrap += ((ldat[icon] !== undefined && ldat[icon] !== "") ? ldat[icon] : $t.p.treeIcons.leaf) + " tree-leaf treeclick";
+                        ldat[isLeaf] = true;
+                        lf = "leaf";
+                    } else {
+                        ldat[isLeaf] = false;
+                        lf = "";
+                    }
+                    ldat[expanded] = ((ldat[expanded] == "true" || ldat[expanded] === true) ? true : false) && ldat[loaded];
+                    if (ldat[expanded] === false) {
+                        twrap += ((ldat[isLeaf] === true) ? "'" : $t.p.treeIcons.plus + " tree-plus treeclick'");
+                    } else {
+                        twrap += ((ldat[isLeaf] === true) ? "'" : $t.p.treeIcons.minus + " tree-minus treeclick'");
+                    }
+
+                    twrap += "></div></div>";
+                    $($t.rows[i].cells[expCol]).wrapInner("<span class='cell-wrapper" + lf + "'></span>").prepend(twrap);
+
+                    if (curLevel !== parseInt($t.p.tree_root_level, 10)) {
+                        var pn = $($t).jqGrid('getNodeParent', ldat);
+                        expan = pn && pn.hasOwnProperty(expanded) ? pn[expanded] : true;
+                        if (!expan) {
+                            $($t.rows[i]).css("display", "none");
+                        }
+                    }
+                    $($t.rows[i].cells[expCol])
+                        .find("div.treeclick")
+                        .bind("click", function (e) {
+                            var target = e.target || e.srcElement,
+                                ind2 = $(target, $t.rows).closest("tr.jqgrow")[0].id,
+                                pos = $t.p._index[ind2];
+                            if (!$t.p.data[pos][isLeaf]) {
+                                if ($t.p.data[pos][expanded]) {
+                                    $($t).jqGrid("collapseRow", $t.p.data[pos]);
+                                    $($t).jqGrid("collapseNode", $t.p.data[pos]);
+                                } else {
+                                    $($t).jqGrid("expandRow", $t.p.data[pos]);
+                                    $($t).jqGrid("expandNode", $t.p.data[pos]);
+                                }
+                            }
+                            return false;
+                        });
+                    if ($t.p.ExpandColClick === true) {
+                        $($t.rows[i].cells[expCol])
+                            .find("span.cell-wrapper")
+                            .css("cursor", "pointer")
+                            .bind("click", function (e) {
+                                var target = e.target || e.srcElement,
+                                    ind2 = $(target, $t.rows).closest("tr.jqgrow")[0].id,
+                                    pos = $t.p._index[ind2];
+                                if (!$t.p.data[pos][isLeaf]) {
+                                    if ($t.p.data[pos][expanded]) {
+                                        $($t).jqGrid("collapseRow", $t.p.data[pos]);
+                                        $($t).jqGrid("collapseNode", $t.p.data[pos]);
+                                    } else {
+                                        $($t).jqGrid("expandRow", $t.p.data[pos]);
+                                        $($t).jqGrid("expandNode", $t.p.data[pos]);
+                                    }
+                                }
+                                $($t).jqGrid("setSelection", ind2);
+                                return false;
+                            });
+                    }
+                    i++;
+                }
+
+            });
+        },
+        setTreeGrid: function () {
+            return this.each(function () {
+                var $t = this, i = 0, pico, ecol = false, nm, key, dupcols = [];
+                if (!$t.p.treeGrid) {
+                    return;
+                }
+                if (!$t.p.treedatatype) {
+                    $.extend($t.p, {treedatatype: $t.p.datatype});
+                }
+                $t.p.subGrid = false;
+                $t.p.altRows = false;
+                $t.p.pgbuttons = false;
+                $t.p.pginput = false;
+                $t.p.gridview = true;
+                if ($t.p.rowTotal === null) {
+                    $t.p.rowNum = 10000;
+                }
+                $t.p.multiselect = false;
+                $t.p.rowList = [];
+                $t.p.expColInd = 0;
+                pico = 'ui-icon-triangle-1-' + ($t.p.direction == "rtl" ? 'w' : 'e');
+                $t.p.treeIcons = $.extend({plus: pico, minus: 'ui-icon-triangle-1-s', leaf: 'ui-icon-radio-off'}, $t.p.treeIcons || {});
+                if ($t.p.treeGridModel == 'nested') {
+                    $t.p.treeReader = $.extend({
+                        level_field: "level",
+                        left_field: "lft",
+                        right_field: "rgt",
+                        leaf_field: "isLeaf",
+                        expanded_field: "expanded",
+                        loaded: "loaded",
+                        icon_field: "icon"
+                    }, $t.p.treeReader);
+                } else if ($t.p.treeGridModel == 'adjacency') {
+                    $t.p.treeReader = $.extend({
+                        level_field: "level",
+                        parent_id_field: "parent",
+                        leaf_field: "isLeaf",
+                        expanded_field: "expanded",
+                        loaded: "loaded",
+                        icon_field: "icon"
+                    }, $t.p.treeReader);
+                }
+                for (key in $t.p.colModel) {
+                    if ($t.p.colModel.hasOwnProperty(key)) {
+                        nm = $t.p.colModel[key].name;
+                        if (nm == $t.p.ExpandColumn && !ecol) {
+                            ecol = true;
+                            $t.p.expColInd = i;
+                        }
+                        i++;
+                        //
+                        for (var tkey in $t.p.treeReader) {
+                            if ($t.p.treeReader[tkey] == nm) {
+                                dupcols.push(nm);
+                            }
+                        }
+                    }
+                }
+                $.each($t.p.treeReader, function (j, n) {
+                    if (n && $.inArray(n, dupcols) === -1) {
+                        if (j === 'leaf_field') {
+                            $t.p._treeleafpos = i;
+                        }
+                        i++;
+                        $t.p.colNames.push(n);
+                        $t.p.colModel.push({name: n, width: 1, hidden: true, sortable: false, resizable: false, hidedlg: true, editable: true, search: false});
+                    }
+                });
+            });
+        },
+        expandRow: function (record) {
+            this.each(function () {
+                var $t = this;
+                if (!$t.grid || !$t.p.treeGrid) {
+                    return;
+                }
+                var childern = $($t).jqGrid("getNodeChildren", record),
+                //if ($($t).jqGrid("isVisibleNode",record)) {
+                    expanded = $t.p.treeReader.expanded_field,
+                    rows = $t.rows;
+                $(childern).each(function () {
+                    var id = $.jgrid.getAccessor(this, $t.p.localReader.id);
+                    $(rows.namedItem(id)).css("display", "");
+                    if (this[expanded]) {
+                        $($t).jqGrid("expandRow", this);
+                    }
+                });
+                //}
+            });
+        },
+        collapseRow: function (record) {
+            this.each(function () {
+                var $t = this;
+                if (!$t.grid || !$t.p.treeGrid) {
+                    return;
+                }
+                var childern = $($t).jqGrid("getNodeChildren", record),
+                    expanded = $t.p.treeReader.expanded_field,
+                    rows = $t.rows;
+                $(childern).each(function () {
+                    var id = $.jgrid.getAccessor(this, $t.p.localReader.id);
+                    $(rows.namedItem(id)).css("display", "none");
+                    if (this[expanded]) {
+                        $($t).jqGrid("collapseRow", this);
+                    }
+                });
+            });
+        },
+        // NS ,adjacency models
+        getRootNodes: function () {
+            var result = [];
+            this.each(function () {
+                var $t = this;
+                if (!$t.grid || !$t.p.treeGrid) {
+                    return;
+                }
+                switch ($t.p.treeGridModel) {
+                    case 'nested' :
+                        var level = $t.p.treeReader.level_field;
+                        $($t.p.data).each(function () {
+                            if (parseInt(this[level], 10) === parseInt($t.p.tree_root_level, 10)) {
+                                result.push(this);
+                            }
+                        });
+                        break;
+                    case 'adjacency' :
+                        var parent_id = $t.p.treeReader.parent_id_field;
+                        $($t.p.data).each(function () {
+                            if (this[parent_id] === null || String(this[parent_id]).toLowerCase() == "null") {
+                                result.push(this);
+                            }
+                        });
+                        break;
+                }
+            });
+            return result;
+        },
+        getNodeDepth: function (rc) {
+            var ret = null;
+            this.each(function () {
+                if (!this.grid || !this.p.treeGrid) {
+                    return;
+                }
+                var $t = this;
+                switch ($t.p.treeGridModel) {
+                    case 'nested' :
+                        var level = $t.p.treeReader.level_field;
+                        ret = parseInt(rc[level], 10) - parseInt($t.p.tree_root_level, 10);
+                        break;
+                    case 'adjacency' :
+                        ret = $($t).jqGrid("getNodeAncestors", rc).length;
+                        break;
+                }
+            });
+            return ret;
+        },
+        getNodeParent: function (rc) {
+            var result = null;
+            this.each(function () {
+                var $t = this;
+                if (!$t.grid || !$t.p.treeGrid) {
+                    return;
+                }
+                switch ($t.p.treeGridModel) {
+                    case 'nested' :
+                        var lftc = $t.p.treeReader.left_field,
+                            rgtc = $t.p.treeReader.right_field,
+                            levelc = $t.p.treeReader.level_field,
+                            lft = parseInt(rc[lftc], 10), rgt = parseInt(rc[rgtc], 10), level = parseInt(rc[levelc], 10);
+                        $(this.p.data).each(function () {
+                            if (parseInt(this[levelc], 10) === level - 1 && parseInt(this[lftc], 10) < lft && parseInt(this[rgtc], 10) > rgt) {
+                                result = this;
+                                return false;
+                            }
+                        });
+                        break;
+                    case 'adjacency' :
+                        var parent_id = $t.p.treeReader.parent_id_field,
+                            dtid = $t.p.localReader.id;
+                        $(this.p.data).each(function () {
+                            if (this[dtid] == rc[parent_id]) {
+                                result = this;
+                                return false;
+                            }
+                        });
+                        break;
+                }
+            });
+            return result;
+        },
+        getNodeChildren: function (rc) {
+            var result = [];
+            this.each(function () {
+                var $t = this;
+                if (!$t.grid || !$t.p.treeGrid) {
+                    return;
+                }
+                switch ($t.p.treeGridModel) {
+                    case 'nested' :
+                        var lftc = $t.p.treeReader.left_field,
+                            rgtc = $t.p.treeReader.right_field,
+                            levelc = $t.p.treeReader.level_field,
+                            lft = parseInt(rc[lftc], 10), rgt = parseInt(rc[rgtc], 10), level = parseInt(rc[levelc], 10);
+                        $(this.p.data).each(function () {
+                            if (parseInt(this[levelc], 10) === level + 1 && parseInt(this[lftc], 10) > lft && parseInt(this[rgtc], 10) < rgt) {
+                                result.push(this);
+                            }
+                        });
+                        break;
+                    case 'adjacency' :
+                        var parent_id = $t.p.treeReader.parent_id_field,
+                            dtid = $t.p.localReader.id;
+                        $(this.p.data).each(function () {
+                            if (this[parent_id] == rc[dtid]) {
+                                result.push(this);
+                            }
+                        });
+                        break;
+                }
+            });
+            return result;
+        },
+        getFullTreeNode: function (rc) {
+            var result = [];
+            this.each(function () {
+                var $t = this, len;
+                if (!$t.grid || !$t.p.treeGrid) {
+                    return;
+                }
+                switch ($t.p.treeGridModel) {
+                    case 'nested' :
+                        var lftc = $t.p.treeReader.left_field,
+                            rgtc = $t.p.treeReader.right_field,
+                            levelc = $t.p.treeReader.level_field,
+                            lft = parseInt(rc[lftc], 10), rgt = parseInt(rc[rgtc], 10), level = parseInt(rc[levelc], 10);
+                        $(this.p.data).each(function () {
+                            if (parseInt(this[levelc], 10) >= level && parseInt(this[lftc], 10) >= lft && parseInt(this[lftc], 10) <= rgt) {
+                                result.push(this);
+                            }
+                        });
+                        break;
+                    case 'adjacency' :
+                        if (rc) {
+                            result.push(rc);
+                            var parent_id = $t.p.treeReader.parent_id_field,
+                                dtid = $t.p.localReader.id;
+                            $(this.p.data).each(function (i) {
+                                len = result.length;
+                                for (i = 0; i < len; i++) {
+                                    if (result[i][dtid] == this[parent_id]) {
+                                        result.push(this);
+                                        break;
+                                    }
+                                }
+                            });
+                        }
+                        break;
+                }
+            });
+            return result;
+        },
+        // End NS, adjacency Model
+        getNodeAncestors: function (rc) {
+            var ancestors = [];
+            this.each(function () {
+                if (!this.grid || !this.p.treeGrid) {
+                    return;
+                }
+                var parent = $(this).jqGrid("getNodeParent", rc);
+                while (parent) {
+                    ancestors.push(parent);
+                    parent = $(this).jqGrid("getNodeParent", parent);
+                }
+            });
+            return ancestors;
+        },
+        isVisibleNode: function (rc) {
+            var result = true;
+            this.each(function () {
+                var $t = this;
+                if (!$t.grid || !$t.p.treeGrid) {
+                    return;
+                }
+                var ancestors = $($t).jqGrid("getNodeAncestors", rc),
+                    expanded = $t.p.treeReader.expanded_field;
+                $(ancestors).each(function () {
+                    result = result && this[expanded];
+                    if (!result) {
+                        return false;
+                    }
+                });
+            });
+            return result;
+        },
+        isNodeLoaded: function (rc) {
+            var result;
+            this.each(function () {
+                var $t = this;
+                if (!$t.grid || !$t.p.treeGrid) {
+                    return;
+                }
+                var isLeaf = $t.p.treeReader.leaf_field;
+                if (rc !== undefined) {
+                    if (rc.loaded !== undefined) {
+                        result = rc.loaded;
+                    } else if (rc[isLeaf] || $($t).jqGrid("getNodeChildren", rc).length > 0) {
+                        result = true;
+                    } else {
+                        result = false;
+                    }
+                } else {
+                    result = false;
+                }
+            });
+            return result;
+        },
+        expandNode: function (rc) {
+            return this.each(function () {
+                if (!this.grid || !this.p.treeGrid) {
+                    return;
+                }
+                var expanded = this.p.treeReader.expanded_field,
+                    parent = this.p.treeReader.parent_id_field,
+                    loaded = this.p.treeReader.loaded,
+                    level = this.p.treeReader.level_field,
+                    lft = this.p.treeReader.left_field,
+                    rgt = this.p.treeReader.right_field;
+
+                if (!rc[expanded]) {
+                    var id = $.jgrid.getAccessor(rc, this.p.localReader.id);
+                    var rc1 = $("#" + $.jgrid.jqID(id), this.grid.bDiv)[0];
+                    var position = this.p._index[id];
+                    if ($(this).jqGrid("isNodeLoaded", this.p.data[position])) {
+                        rc[expanded] = true;
+                        $("div.treeclick", rc1).removeClass(this.p.treeIcons.plus + " tree-plus").addClass(this.p.treeIcons.minus + " tree-minus");
+                    } else if (!this.grid.hDiv.loading) {
+                        rc[expanded] = true;
+                        $("div.treeclick", rc1).removeClass(this.p.treeIcons.plus + " tree-plus").addClass(this.p.treeIcons.minus + " tree-minus");
+                        this.p.treeANode = rc1.rowIndex;
+                        this.p.datatype = this.p.treedatatype;
+                        if (this.p.treeGridModel == 'nested') {
+                            $(this).jqGrid("setGridParam", {postData: {nodeid: id, n_left: rc[lft], n_right: rc[rgt], n_level: rc[level]}});
+                        } else {
+                            $(this).jqGrid("setGridParam", {postData: {nodeid: id, parentid: rc[parent], n_level: rc[level]}});
+                        }
+                        $(this).trigger("reloadGrid");
+                        rc[loaded] = true;
+                        if (this.p.treeGridModel == 'nested') {
+                            $(this).jqGrid("setGridParam", {postData: {nodeid: '', n_left: '', n_right: '', n_level: ''}});
+                        } else {
+                            $(this).jqGrid("setGridParam", {postData: {nodeid: '', parentid: '', n_level: ''}});
+                        }
+                    }
+                }
+            });
+        },
+        collapseNode: function (rc) {
+            return this.each(function () {
+                if (!this.grid || !this.p.treeGrid) {
+                    return;
+                }
+                var expanded = this.p.treeReader.expanded_field;
+                if (rc[expanded]) {
+                    rc[expanded] = false;
+                    var id = $.jgrid.getAccessor(rc, this.p.localReader.id);
+                    var rc1 = $("#" + $.jgrid.jqID(id), this.grid.bDiv)[0];
+                    $("div.treeclick", rc1).removeClass(this.p.treeIcons.minus + " tree-minus").addClass(this.p.treeIcons.plus + " tree-plus");
+                }
+            });
+        },
+        SortTree: function (sortname, newDir, st, datefmt) {
+            return this.each(function () {
+                if (!this.grid || !this.p.treeGrid) {
+                    return;
+                }
+                var i, len,
+                    rec, records = [], $t = this, query, roots,
+                    rt = $(this).jqGrid("getRootNodes");
+                // Sorting roots
+                query = $.jgrid.from(rt);
+                query.orderBy(sortname, newDir, st, datefmt);
+                roots = query.select();
+
+                // Sorting children
+                for (i = 0, len = roots.length; i < len; i++) {
+                    rec = roots[i];
+                    records.push(rec);
+                    $(this).jqGrid("collectChildrenSortTree", records, rec, sortname, newDir, st, datefmt);
+                }
+                $.each(records, function (index) {
+                    var id = $.jgrid.getAccessor(this, $t.p.localReader.id);
+                    $('#' + $.jgrid.jqID($t.p.id) + ' tbody tr:eq(' + index + ')').after($('tr#' + $.jgrid.jqID(id), $t.grid.bDiv));
+                });
+                query = null;
+                roots = null;
+                records = null;
+            });
+        },
+        collectChildrenSortTree: function (records, rec, sortname, newDir, st, datefmt) {
+            return this.each(function () {
+                if (!this.grid || !this.p.treeGrid) {
+                    return;
+                }
+                var i, len,
+                    child, ch, query, children;
+                ch = $(this).jqGrid("getNodeChildren", rec);
+                query = $.jgrid.from(ch);
+                query.orderBy(sortname, newDir, st, datefmt);
+                children = query.select();
+                for (i = 0, len = children.length; i < len; i++) {
+                    child = children[i];
+                    records.push(child);
+                    $(this).jqGrid("collectChildrenSortTree", records, child, sortname, newDir, st, datefmt);
+                }
+            });
+        },
+        // experimental
+        setTreeRow: function (rowid, data) {
+            var success = false;
+            this.each(function () {
+                var t = this;
+                if (!t.grid || !t.p.treeGrid) {
+                    return;
+                }
+                success = $(t).jqGrid("setRowData", rowid, data);
+            });
+            return success;
+        },
+        delTreeNode: function (rowid) {
+            return this.each(function () {
+                var $t = this, rid = $t.p.localReader.id,
+                    left = $t.p.treeReader.left_field,
+                    right = $t.p.treeReader.right_field, myright, width, res, key;
+                if (!$t.grid || !$t.p.treeGrid) {
+                    return;
+                }
+                var rc = $t.p._index[rowid];
+                if (rc !== undefined) {
+                    // nested
+                    myright = parseInt($t.p.data[rc][right], 10);
+                    width = myright - parseInt($t.p.data[rc][left], 10) + 1;
+                    var dr = $($t).jqGrid("getFullTreeNode", $t.p.data[rc]);
+                    if (dr.length > 0) {
+                        for (var i = 0; i < dr.length; i++) {
+                            $($t).jqGrid("delRowData", dr[i][rid]);
+                        }
+                    }
+                    if ($t.p.treeGridModel === "nested") {
+                        // ToDo - update grid data
+                        res = $.jgrid.from($t.p.data)
+                            .greater(left, myright, {stype: 'integer'})
+                            .select();
+                        if (res.length) {
+                            for (key in res) {
+                                if (res.hasOwnProperty(key)) {
+                                    res[key][left] = parseInt(res[key][left], 10) - width;
+                                }
+                            }
+                        }
+                        res = $.jgrid.from($t.p.data)
+                            .greater(right, myright, {stype: 'integer'})
+                            .select();
+                        if (res.length) {
+                            for (key in res) {
+                                if (res.hasOwnProperty(key)) {
+                                    res[key][right] = parseInt(res[key][right], 10) - width;
+                                }
+                            }
+                        }
+                    }
+                }
+            });
+        },
+        addChildNode: function (nodeid, parentid, data) {
+            //return this.each(function(){
+            var $t = this[0];
+            if (data) {
+                // we suppose tha the id is autoincremet and
+                var expanded = $t.p.treeReader.expanded_field,
+                    isLeaf = $t.p.treeReader.leaf_field,
+                    level = $t.p.treeReader.level_field,
+                //icon = $t.p.treeReader.icon_field,
+                    parent = $t.p.treeReader.parent_id_field,
+                    left = $t.p.treeReader.left_field,
+                    right = $t.p.treeReader.right_field,
+                    loaded = $t.p.treeReader.loaded,
+                    method, parentindex, parentdata, parentlevel, i, len, max = 0, rowind = parentid, leaf, maxright;
+
+                if (typeof nodeid === 'undefined' || nodeid === null) {
+                    i = $t.p.data.length - 1;
+                    if (i >= 0) {
+                        while (i >= 0) {
+                            max = Math.max(max, parseInt($t.p.data[i][$t.p.localReader.id], 10));
+                            i--;
+                        }
+                    }
+                    nodeid = max + 1;
+                }
+                var prow = $($t).jqGrid('getInd', parentid);
+                leaf = false;
+                // if not a parent we assume root
+                if (parentid === undefined || parentid === null || parentid === "") {
+                    parentid = null;
+                    rowind = null;
+                    method = 'last';
+                    parentlevel = $t.p.tree_root_level;
+                    i = $t.p.data.length + 1;
+                } else {
+                    method = 'after';
+                    parentindex = $t.p._index[parentid];
+                    parentdata = $t.p.data[parentindex];
+                    parentid = parentdata[$t.p.localReader.id];
+                    parentlevel = parseInt(parentdata[level], 10) + 1;
+                    var childs = $($t).jqGrid('getFullTreeNode', parentdata);
+                    // if there are child nodes get the last index of it
+                    if (childs.length) {
+                        i = childs[childs.length - 1][$t.p.localReader.id];
+                        rowind = i;
+                        i = $($t).jqGrid('getInd', rowind) + 1;
+                    } else {
+                        i = $($t).jqGrid('getInd', parentid) + 1;
+                    }
+                    // if the node is leaf
+                    if (parentdata[isLeaf]) {
+                        leaf = true;
+                        parentdata[expanded] = true;
+                        //var prow = $($t).jqGrid('getInd', parentid);
+                        $($t.rows[prow])
+                            .find("span.cell-wrapperleaf").removeClass("cell-wrapperleaf").addClass("cell-wrapper")
+                            .end()
+                            .find("div.tree-leaf").removeClass($t.p.treeIcons.leaf + " tree-leaf").addClass($t.p.treeIcons.minus + " tree-minus");
+                        $t.p.data[parentindex][isLeaf] = false;
+                        parentdata[loaded] = true;
+                    }
+                }
+                len = i + 1;
+
+                data[expanded] = false;
+                data[loaded] = true;
+                data[level] = parentlevel;
+                data[isLeaf] = true;
+                if ($t.p.treeGridModel === "adjacency") {
+                    data[parent] = parentid;
+                }
+                if ($t.p.treeGridModel === "nested") {
+                    // this method requiere more attention
+                    var query, res, key;
+                    //maxright = parseInt(maxright,10);
+                    // ToDo - update grid data
+                    if (parentid !== null) {
+                        maxright = parseInt(parentdata[right], 10);
+                        query = $.jgrid.from($t.p.data);
+                        query = query.greaterOrEquals(right, maxright, {stype: 'integer'});
+                        res = query.select();
+                        if (res.length) {
+                            for (key in res) {
+                                if (res.hasOwnProperty(key)) {
+                                    res[key][left] = res[key][left] > maxright ? parseInt(res[key][left], 10) + 2 : res[key][left];
+                                    res[key][right] = res[key][right] >= maxright ? parseInt(res[key][right], 10) + 2 : res[key][right];
+                                }
+                            }
+                        }
+                        data[left] = maxright;
+                        data[right] = maxright + 1;
+                    } else {
+                        maxright = parseInt($($t).jqGrid('getCol', right, false, 'max'), 10);
+                        res = $.jgrid.from($t.p.data)
+                            .greater(left, maxright, {stype: 'integer'})
+                            .select();
+                        if (res.length) {
+                            for (key in res) {
+                                if (res.hasOwnProperty(key)) {
+                                    res[key][left] = parseInt(res[key][left], 10) + 2;
+                                }
+                            }
+                        }
+                        res = $.jgrid.from($t.p.data)
+                            .greater(right, maxright, {stype: 'integer'})
+                            .select();
+                        if (res.length) {
+                            for (key in res) {
+                                if (res.hasOwnProperty(key)) {
+                                    res[key][right] = parseInt(res[key][right], 10) + 2;
+                                }
+                            }
+                        }
+                        data[left] = maxright + 1;
+                        data[right] = maxright + 2;
+                    }
+                }
+                if (parentid === null || $($t).jqGrid("isNodeLoaded", parentdata) || leaf) {
+                    $($t).jqGrid('addRowData', nodeid, data, method, rowind);
+                    $($t).jqGrid('setTreeNode', i, len);
+                }
+                if (parentdata && !parentdata[expanded]) {
+                    $($t.rows[prow])
+                        .find("div.treeclick")
+                        .click();
+                }
+            }
+            //});
+        }
+    });
 })(jQuery);
-(function($){
-/**
- * jqGrid extension for custom methods
- * Tony Tomov tony@trirand.com
- * http://trirand.com/blog/
- *
- * Wildraid wildraid@mail.ru
- * Oleg Kiriljuk oleg.kiriljuk@ok-soft-gmbh.com
- * Dual licensed under the MIT and GPL licenses:
- * http://www.opensource.org/licenses/mit-license.php
- * http://www.gnu.org/licenses/gpl-2.0.html
-**/
-/*global jQuery, $ */
-"use strict";
-$.jgrid.extend({
-	getColProp : function(colname){
-		var ret ={}, $t = this[0];
-		if ( !$t.grid ) { return false; }
-		var cM = $t.p.colModel;
-		for ( var i =0;i<cM.length;i++ ) {
-			if ( cM[i].name == colname ) {
-				ret = cM[i];
-				break;
-			}
-		}
-		return ret;
-	},
-	setColProp : function(colname, obj){
-		//do not set width will not work
-		return this.each(function(){
-			if ( this.grid ) {
-				if ( obj ) {
-					var cM = this.p.colModel;
-					for ( var i =0;i<cM.length;i++ ) {
-						if ( cM[i].name == colname ) {
-							$.extend(this.p.colModel[i],obj);
-							break;
-						}
-					}
-				}
-			}
-		});
-	},
-	sortGrid : function(colname,reload, sor){
-		return this.each(function(){
-			var $t=this,idx=-1;
-			if ( !$t.grid ) { return;}
-			if ( !colname ) { colname = $t.p.sortname; }
-			for ( var i=0;i<$t.p.colModel.length;i++ ) {
-				if ( $t.p.colModel[i].index == colname || $t.p.colModel[i].name==colname ) {
-					idx = i;
-					break;
-				}
-			}
-			if ( idx!=-1 ){
-				var sort = $t.p.colModel[idx].sortable;
-				if ( typeof sort !== 'boolean' ) { sort =  true; }
-				if ( typeof reload !=='boolean' ) { reload = false; }
-				if ( sort ) { $t.sortData("jqgh_"+$t.p.id+"_" + colname, idx, reload, sor); }
-			}
-		});
-	},
-	GridDestroy : function () {
-		return this.each(function(){
-			if ( this.grid ) {
-				if ( this.p.pager ) { // if not part of grid
-					$(this.p.pager).remove();
-				}
-				try {
-					$("#gbox_"+$.jgrid.jqID(this.id)).remove();
-				} catch (_) {}
-			}
-		});
-	},
-	GridUnload : function(){
-		return this.each(function(){
-			if ( !this.grid ) {return;}
-			var defgrid = {id: $(this).attr('id'),cl: $(this).attr('class')};
-			if (this.p.pager) {
-				$(this.p.pager).empty().removeClass("ui-state-default ui-jqgrid-pager corner-bottom");
-			}
-			var newtable = document.createElement('table');
-			$(newtable).attr({id:defgrid.id});
-			newtable.className = defgrid.cl;
-			var gid = $.jgrid.jqID(this.id);
-			$(newtable).removeClass("ui-jqgrid-btable");
-			if( $(this.p.pager).parents("#gbox_"+gid).length === 1 ) {
-				$(newtable).insertBefore("#gbox_"+gid).show();
-				$(this.p.pager).insertBefore("#gbox_"+gid);
-			} else {
-				$(newtable).insertBefore("#gbox_"+gid).show();
-			}
-			$("#gbox_"+gid).remove();
-		});
-	},
-    setGridState : function(state) {
-		return this.each(function(){
-			if ( !this.grid ) {return;}
-			var $t = this;
-			if(state == 'hidden'){
-				$(".ui-jqgrid-bdiv, .ui-jqgrid-hdiv","#gview_"+$.jgrid.jqID($t.p.id)).slideUp("fast");
-				if($t.p.pager) {$($t.p.pager).slideUp("fast");}
-				if($t.p.toppager) {$($t.p.toppager).slideUp("fast");}
-				if($t.p.toolbar[0]===true) {
-					if( $t.p.toolbar[1]=='both') {
-						$($t.grid.ubDiv).slideUp("fast");
-					}
-					$($t.grid.uDiv).slideUp("fast");
-				}
-				if($t.p.footerrow) { $(".ui-jqgrid-sdiv","#gbox_"+$.jgrid.jqID($t.p.id)).slideUp("fast"); }
-				$(".ui-jqgrid-titlebar-close span",$t.grid.cDiv).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-s");
-				$t.p.gridstate = 'hidden';
-			} else if(state=='visible') {
-				$(".ui-jqgrid-hdiv, .ui-jqgrid-bdiv","#gview_"+$.jgrid.jqID($t.p.id)).slideDown("fast");
-				if($t.p.pager) {$($t.p.pager).slideDown("fast");}
-				if($t.p.toppager) {$($t.p.toppager).slideDown("fast");}
-				if($t.p.toolbar[0]===true) {
-					if( $t.p.toolbar[1]=='both') {
-						$($t.grid.ubDiv).slideDown("fast");
-					}
-					$($t.grid.uDiv).slideDown("fast");
-				}
-				if($t.p.footerrow) { $(".ui-jqgrid-sdiv","#gbox_"+$.jgrid.jqID($t.p.id)).slideDown("fast"); }
-				$(".ui-jqgrid-titlebar-close span",$t.grid.cDiv).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-n");
-				$t.p.gridstate = 'visible';
-			}
-
-		});
-	},
-	filterToolbar : function(p){
-		p = $.extend({
-			autosearch: true,
-			searchOnEnter : true,
-			beforeSearch: null,
-			afterSearch: null,
-			beforeClear: null,
-			afterClear: null,
-			searchurl : '',
-			stringResult: false,
-			groupOp: 'AND',
-			defaultSearch : "bw"
-		},p  || {});
-		return this.each(function(){
-			var $t = this;
-			if(this.ftoolbar) { return; }
-			var triggerToolbar = function() {
-				var sdata={}, j=0, v, nm, sopt={},so;
-				$.each($t.p.colModel,function(){
-					nm = this.index || this.name;
-					so  = (this.searchoptions && this.searchoptions.sopt) ? this.searchoptions.sopt[0] : this.stype=='select'?  'eq' : p.defaultSearch;
-					v = $("#gs_"+$.jgrid.jqID(this.name), (this.frozen===true && $t.p.frozenColumns === true) ?  $t.grid.fhDiv : $t.grid.hDiv).val();
-					if(v) {
-						sdata[nm] = v;
-						sopt[nm] = so;
-						j++;
-					} else {
-						try {
-							delete $t.p.postData[nm];
-						} catch (z) {}
-					}
-				});
-				var sd =  j>0 ? true : false;
-				if(p.stringResult === true || $t.p.datatype == "local") {
-					var ruleGroup = "{\"groupOp\":\"" + p.groupOp + "\",\"rules\":[";
-					var gi=0;
-					$.each(sdata,function(i,n){
-						if (gi > 0) {ruleGroup += ",";}
-						ruleGroup += "{\"field\":\"" + i + "\",";
-						ruleGroup += "\"op\":\"" + sopt[i] + "\",";
-						n+="";
-						ruleGroup += "\"data\":\"" + n.replace(/\\/g,'\\\\').replace(/\"/g,'\\"') + "\"}";
-						gi++;
-					});
-					ruleGroup += "]}";
-					$.extend($t.p.postData,{filters:ruleGroup});
-					$.each(['searchField', 'searchString', 'searchOper'], function(i, n){
-						if($t.p.postData.hasOwnProperty(n)) { delete $t.p.postData[n];}
-					});
-				} else {
-					$.extend($t.p.postData,sdata);
-				}
-				var saveurl;
-				if($t.p.searchurl) {
-					saveurl = $t.p.url;
-					$($t).jqGrid("setGridParam",{url:$t.p.searchurl});
-				}
-				var bsr = $($t).triggerHandler("jqGridToolbarBeforeSearch") === 'stop' ? true : false;
-				if(!bsr && $.isFunction(p.beforeSearch)){bsr = p.beforeSearch.call($t);}
-				if(!bsr) { $($t).jqGrid("setGridParam",{search:sd}).trigger("reloadGrid",[{page:1}]); }
-				if(saveurl) {$($t).jqGrid("setGridParam",{url:saveurl});}
-				$($t).triggerHandler("jqGridToolbarAfterSearch");
-				if($.isFunction(p.afterSearch)){p.afterSearch.call($t);}
-			};
-			var clearToolbar = function(trigger){
-				var sdata={}, j=0, nm;
-				trigger = (typeof trigger != 'boolean') ? true : trigger;
-				$.each($t.p.colModel,function(){
-					var v;
-					if(this.searchoptions && this.searchoptions.defaultValue !== undefined) { v = this.searchoptions.defaultValue; }
-					nm = this.index || this.name;
-					switch (this.stype) {
-						case 'select' :
-							$("#gs_"+$.jgrid.jqID(this.name)+" option",(this.frozen===true && $t.p.frozenColumns === true) ?  $t.grid.fhDiv : $t.grid.hDiv).each(function (i){
-								if(i===0) { this.selected = true; }
-								if ($(this).val() == v) {
-									this.selected = true;
-									return false;
-								}
-							});
-							if ( v !== undefined ) {
-								// post the key and not the text
-								sdata[nm] = v;
-								j++;
-							} else {
-								try {
-									delete $t.p.postData[nm];
-								} catch(e) {}
-							}
-							break;
-						case 'text':
-							$("#gs_"+$.jgrid.jqID(this.name),(this.frozen===true && $t.p.frozenColumns === true) ?  $t.grid.fhDiv : $t.grid.hDiv).val(v);
-							if(v !== undefined) {
-								sdata[nm] = v;
-								j++;
-							} else {
-								try {
-									delete $t.p.postData[nm];
-								} catch (y){}
-							}
-							break;
-					}
-				});
-				var sd =  j>0 ? true : false;
-				if(p.stringResult === true || $t.p.datatype == "local") {
-					var ruleGroup = "{\"groupOp\":\"" + p.groupOp + "\",\"rules\":[";
-					var gi=0;
-					$.each(sdata,function(i,n){
-						if (gi > 0) {ruleGroup += ",";}
-						ruleGroup += "{\"field\":\"" + i + "\",";
-						ruleGroup += "\"op\":\"" + "eq" + "\",";
-						n+="";
-						ruleGroup += "\"data\":\"" + n.replace(/\\/g,'\\\\').replace(/\"/g,'\\"') + "\"}";
-						gi++;
-					});
-					ruleGroup += "]}";
-					$.extend($t.p.postData,{filters:ruleGroup});
-					$.each(['searchField', 'searchString', 'searchOper'], function(i, n){
-						if($t.p.postData.hasOwnProperty(n)) { delete $t.p.postData[n];}
-					});
-				} else {
-					$.extend($t.p.postData,sdata);
-				}
-				var saveurl;
-				if($t.p.searchurl) {
-					saveurl = $t.p.url;
-					$($t).jqGrid("setGridParam",{url:$t.p.searchurl});
-				}
-				var bcv = $($t).triggerHandler("jqGridToolbarBeforeClear") === 'stop' ? true : false;
-				if(!bcv && $.isFunction(p.beforeClear)){bcv = p.beforeClear.call($t);}
-				if(!bcv) {
-					if(trigger) {
-						$($t).jqGrid("setGridParam",{search:sd}).trigger("reloadGrid",[{page:1}]);
-					}
-				}
-				if(saveurl) {$($t).jqGrid("setGridParam",{url:saveurl});}
-				$($t).triggerHandler("jqGridToolbarAfterClear");
-				if($.isFunction(p.afterClear)){p.afterClear();}
-			};
-			var toggleToolbar = function(){
-				var trow = $("tr.ui-search-toolbar",$t.grid.hDiv),
-				trow2 = $t.p.frozenColumns === true ?  $("tr.ui-search-toolbar",$t.grid.fhDiv) : false;
-				if(trow.css("display")=='none') {
-					trow.show();
-					if(trow2) {
-						trow2.show();
-					}
-				} else {
-					trow.hide();
-					if(trow2) {
-						trow2.hide();
-					}
-				}
-			};
-			// create the row
-			function bindEvents(selector, events) {
-				var jElem = $(selector);
-				if (jElem[0]) {
-					jQuery.each(events, function() {
-						if (this.data !== undefined) {
-							jElem.bind(this.type, this.data, this.fn);
-						} else {
-							jElem.bind(this.type, this.fn);
-						}
-					});
-				}
-			}
-			var tr = $("<tr class='ui-search-toolbar' role='rowheader'></tr>");
-			var timeoutHnd;
-			$.each($t.p.colModel,function(){
-				var cm=this, thd , th, soptions,surl,self;
-				th = $("<th role='columnheader' class='ui-state-default ui-th-column ui-th-"+$t.p.direction+"'></th>");
-				thd = $("<div style='width:100%;position:relative;height:100%;padding-right:0.3em;'></div>");
-				if(this.hidden===true) { $(th).css("display","none");}
-				this.search = this.search === false ? false : true;
-				if(typeof this.stype == 'undefined' ) {this.stype='text';}
-				soptions = $.extend({},this.searchoptions || {});
-				if(this.search){
-					switch (this.stype)
-					{
-					case "select":
-						surl = this.surl || soptions.dataUrl;
-						if(surl) {
-							// data returned should have already constructed html select
-							// primitive jQuery load
-							self = thd;
-							$.ajax($.extend({
-								url: surl,
-								dataType: "html",
-								success: function(res) {
-									if(soptions.buildSelect !== undefined) {
-										var d = soptions.buildSelect(res);
-										if (d) { $(self).append(d); }
-									} else {
-										$(self).append(res);
-									}
-									if(soptions.defaultValue !== undefined) { $("select",self).val(soptions.defaultValue); }
-									$("select",self).attr({name:cm.index || cm.name, id: "gs_"+cm.name});
-									if(soptions.attr) {$("select",self).attr(soptions.attr);}
-									$("select",self).css({width: "100%"});
-									// preserve autoserch
-									if(soptions.dataInit !== undefined) { soptions.dataInit($("select",self)[0]); }
-									if(soptions.dataEvents !== undefined) { bindEvents($("select",self)[0],soptions.dataEvents); }
-									if(p.autosearch===true){
-										$("select",self).change(function(){
-											triggerToolbar();
-											return false;
-										});
-									}
-									res=null;
-								}
-							}, $.jgrid.ajaxOptions, $t.p.ajaxSelectOptions || {} ));
-						} else {
-							var oSv, sep, delim;
-							if(cm.searchoptions) {
-								oSv = cm.searchoptions.value === undefined ? "" : cm.searchoptions.value;
-								sep = cm.searchoptions.separator === undefined ? ":" : cm.searchoptions.separator;
-								delim = cm.searchoptions.delimiter === undefined ? ";" : cm.searchoptions.delimiter;
-							} else if(cm.editoptions) {
-								oSv = cm.editoptions.value === undefined ? "" : cm.editoptions.value;
-								sep = cm.editoptions.separator === undefined ? ":" : cm.editoptions.separator;
-								delim = cm.editoptions.delimiter === undefined ? ";" : cm.editoptions.delimiter;
-							}
-							if (oSv) {
-								var elem = document.createElement("select");
-								elem.style.width = "100%";
-								$(elem).attr({name:cm.index || cm.name, id: "gs_"+cm.name});
-								var so, sv, ov;
-								if(typeof oSv === "string") {
-									so = oSv.split(delim);
-									for(var k=0; k<so.length;k++){
-										sv = so[k].split(sep);
-										ov = document.createElement("option");
-										ov.value = sv[0]; ov.innerHTML = sv[1];
-										elem.appendChild(ov);
-									}
-								} else if(typeof oSv === "object" ) {
-									for ( var key in oSv) {
-										if(oSv.hasOwnProperty(key)) {
-											ov = document.createElement("option");
-											ov.value = key; ov.innerHTML = oSv[key];
-											elem.appendChild(ov);
-										}
-									}
-								}
-								if(soptions.defaultValue !== undefined) { $(elem).val(soptions.defaultValue); }
-								if(soptions.attr) {$(elem).attr(soptions.attr);}
-								if(soptions.dataInit !== undefined) { soptions.dataInit(elem); }
-								if(soptions.dataEvents !== undefined) { bindEvents(elem, soptions.dataEvents); }
-								$(thd).append(elem);
-								if(p.autosearch===true){
-									$(elem).change(function(){
-										triggerToolbar();
-										return false;
-									});
-								}
-							}
-						}
-						break;
-					case 'text':
-						var df = soptions.defaultValue !== undefined ? soptions.defaultValue: "";
-						$(thd).append("<input type='text' style='width:95%;padding:0px;' name='"+(cm.index || cm.name)+"' id='gs_"+cm.name+"' value='"+df+"'/>");
-						if(soptions.attr) {$("input",thd).attr(soptions.attr);}
-						if(soptions.dataInit !== undefined) { soptions.dataInit($("input",thd)[0]); }
-						if(soptions.dataEvents !== undefined) { bindEvents($("input",thd)[0], soptions.dataEvents); }
-						if(p.autosearch===true){
-
-							if(p.searchOnEnter) {
-								$("input",thd).keypress(function(e){
-									var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
-									if(key == 13){
-										triggerToolbar();
-										return false;
-									}
-									return this;
-								});
-							} else {
-								$("input",thd).keydown(function(e){
-									var key = e.which;
-									switch (key) {
-										case 13:
-											return false;
-										case 9 :
-										case 16:
-										case 37:
-										case 38:
-										case 39:
-										case 40:
-										case 27:
-											break;
-										default :
-											if(timeoutHnd) { clearTimeout(timeoutHnd); }
-											timeoutHnd = setTimeout(function(){triggerToolbar();},500);
-									}
-								});
-							}
-						}
-						break;
-					}
-				}
-				$(th).append(thd);
-				$(tr).append(th);
-			});
-			$("table thead",$t.grid.hDiv).append(tr);
-			this.ftoolbar = true;
-			this.triggerToolbar = triggerToolbar;
-			this.clearToolbar = clearToolbar;
-			this.toggleToolbar = toggleToolbar;
-		});
-	},
-
-	destroyGroupHeader : function(nullHeader)
-	{
-		if(typeof(nullHeader) == 'undefined') {
-			nullHeader = true;
-		}
-		return this.each(function()
-		{
-			var $t = this, $tr, i, l, headers, $th, $resizing, grid = $t.grid,
-			thead = $("table.ui-jqgrid-htable thead", grid.hDiv), cm = $t.p.colModel, hc;
-			if(!grid) { return; }
-
-			$(this).unbind('.setGroupHeaders');
-			$tr = $("<tr>", {role: "rowheader"}).addClass("ui-jqgrid-labels");
-			headers = grid.headers;
-			for (i = 0, l = headers.length; i < l; i++) {
-				hc = cm[i].hidden ? "none" : "";
-				$th = $(headers[i].el)
-					.width(headers[i].width)
-					.css('display',hc);
-				try {
-					$th.removeAttr("rowSpan");
-				} catch (rs) {
-					//IE 6/7
-					$th.attr("rowSpan",1);
-				}
-				$tr.append($th);
-				$resizing = $th.children("span.ui-jqgrid-resize");
-				if ($resizing.length>0) {// resizable column
-					$resizing[0].style.height = "";
-				}
-				$th.children("div")[0].style.top = "";
-			}
-			$(thead).children('tr.ui-jqgrid-labels').remove();
-			$(thead).prepend($tr);
-
-			if(nullHeader === true) {
-				$($t).jqGrid('setGridParam',{ 'groupHeader': null});
-			}
-		});
-	},
-
-	setGroupHeaders : function ( o ) {
-		o = $.extend({
-			useColSpanStyle :  false,
-			groupHeaders: []
-		},o  || {});
-		return this.each(function(){
-			this.p.groupHeader = o;
-			var ts = this,
-			i, cmi, skip = 0, $tr, $colHeader, th, $th, thStyle,
-			iCol,
-			cghi,
-			//startColumnName,
-			numberOfColumns,
-			titleText,
-			cVisibleColumns,
-			colModel = ts.p.colModel,
-			cml = colModel.length,
-			ths = ts.grid.headers,
-			$htable = $("table.ui-jqgrid-htable", ts.grid.hDiv),
-			$trLabels = $htable.children("thead").children("tr.ui-jqgrid-labels:last").addClass("jqg-second-row-header"),
-			$thead = $htable.children("thead"),
-			$theadInTable,
-			$firstHeaderRow = $htable.find(".jqg-first-row-header");
-			if($firstHeaderRow.html() === null) {
-				$firstHeaderRow = $('<tr>', {role: "row", "aria-hidden": "true"}).addClass("jqg-first-row-header").css("height", "auto");
-			} else {
-				$firstHeaderRow.empty();
-			}
-			var $firstRow,
-			inColumnHeader = function (text, columnHeaders) {
-				var i = 0, length = columnHeaders.length;
-				for (; i < length; i++) {
-					if (columnHeaders[i].startColumnName === text) {
-						return i;
-					}
-				}
-				return -1;
-			};
-
-			$(ts).prepend($thead);
-			$tr = $('<tr>', {role: "rowheader"}).addClass("ui-jqgrid-labels jqg-third-row-header");
-			for (i = 0; i < cml; i++) {
-				th = ths[i].el;
-				$th = $(th);
-				cmi = colModel[i];
-				// build the next cell for the first header row
-				thStyle = { height: '0px', width: ths[i].width + 'px', display: (cmi.hidden ? 'none' : '')};
-				$("<th>", {role: 'gridcell'}).css(thStyle).addClass("ui-first-th-"+ts.p.direction).appendTo($firstHeaderRow);
-
-				th.style.width = ""; // remove unneeded style
-				iCol = inColumnHeader(cmi.name, o.groupHeaders);
-				if (iCol >= 0) {
-					cghi = o.groupHeaders[iCol];
-					numberOfColumns = cghi.numberOfColumns;
-					titleText = cghi.titleText;
-
-					// caclulate the number of visible columns from the next numberOfColumns columns
-					for (cVisibleColumns = 0, iCol = 0; iCol < numberOfColumns && (i + iCol < cml); iCol++) {
-						if (!colModel[i + iCol].hidden) {
-							cVisibleColumns++;
-						}
-					}
-
-					// The next numberOfColumns headers will be moved in the next row
-					// in the current row will be placed the new column header with the titleText.
-					// The text will be over the cVisibleColumns columns
-					$colHeader = $('<th>').attr({role: "columnheader"})
-						.addClass("ui-state-default ui-th-column-header ui-th-"+ts.p.direction)
-						.css({'height':'22px', 'border-top': '0px none'})
-						.html(titleText);
-					if(cVisibleColumns > 0) {
-						$colHeader.attr("colspan", String(cVisibleColumns));
-					}
-					if (ts.p.headertitles) {
-						$colHeader.attr("title", $colHeader.text());
-					}
-					// hide if not a visible cols
-					if( cVisibleColumns === 0) {
-						$colHeader.hide();
-					}
-
-					$th.before($colHeader); // insert new column header before the current
-					$tr.append(th);         // move the current header in the next row
-
-					// set the coumter of headers which will be moved in the next row
-					skip = numberOfColumns - 1;
-				} else {
-					if (skip === 0) {
-						if (o.useColSpanStyle) {
-							// expand the header height to two rows
-							$th.attr("rowspan", "2");
-						} else {
-							$('<th>', {role: "columnheader"})
-								.addClass("ui-state-default ui-th-column-header ui-th-"+ts.p.direction)
-								.css({"display": cmi.hidden ? 'none' : '', 'border-top': '0px none'})
-								.insertBefore($th);
-							$tr.append(th);
-						}
-					} else {
-						// move the header to the next row
-						//$th.css({"padding-top": "2px", height: "19px"});
-						$tr.append(th);
-						skip--;
-					}
-				}
-			}
-			$theadInTable = $(ts).children("thead");
-			$theadInTable.prepend($firstHeaderRow);
-			$tr.insertAfter($trLabels);
-			$htable.append($theadInTable);
-
-			if (o.useColSpanStyle) {
-				// Increase the height of resizing span of visible headers
-				$htable.find("span.ui-jqgrid-resize").each(function () {
-					var $parent = $(this).parent();
-					if ($parent.is(":visible")) {
-						this.style.cssText = 'height: ' + $parent.height() + 'px !important; cursor: col-resize;';
-					}
-				});
-
-				// Set position of the sortable div (the main lable)
-				// with the column header text to the middle of the cell.
-				// One should not do this for hidden headers.
-				$htable.find("div.ui-jqgrid-sortable").each(function () {
-					var $ts = $(this), $parent = $ts.parent();
-					if ($parent.is(":visible") && $parent.is(":has(span.ui-jqgrid-resize)")) {
-						$ts.css('top', ($parent.height() - $ts.outerHeight()) / 2 + 'px');
-					}
-				});
-			}
-
-			$firstRow = $theadInTable.find("tr.jqg-first-row-header");
-			$(ts).bind('jqGridResizeStop.setGroupHeaders', function (e, nw, idx) {
-				$firstRow.find('th').eq(idx).width(nw);
-			});
-		});
-	},
-	setFrozenColumns : function () {
-		return this.each(function() {
-			if ( !this.grid ) {return;}
-			var $t = this, cm = $t.p.colModel,i=0, len = cm.length, maxfrozen = -1, frozen= false;
-			// TODO treeGrid and grouping  Support
-			if($t.p.subGrid === true || $t.p.treeGrid === true || $t.p.cellEdit === true || $t.p.sortable || $t.p.scroll || $t.p.grouping )
-			{
-				return;
-			}
-			if($t.p.rownumbers) { i++; }
-			if($t.p.multiselect) { i++; }
-
-			// get the max index of frozen col
-			while(i<len)
-			{
-				// from left, no breaking frozen
-				if(cm[i].frozen === true)
-				{
-					frozen = true;
-					maxfrozen = i;
-				} else {
-					break;
-				}
-				i++;
-			}
-			if( maxfrozen>=0 && frozen) {
-				var top = $t.p.caption ? $($t.grid.cDiv).outerHeight() : 0,
-				hth = $(".ui-jqgrid-htable","#gview_"+$.jgrid.jqID($t.p.id)).height();
-				//headers
-				if($t.p.toppager) {
-					top = top + $($t.grid.topDiv).outerHeight();
-				}
-				if($t.p.toolbar[0] === true) {
-					if($t.p.toolbar[1] != "bottom") {
-						top = top + $($t.grid.uDiv).outerHeight();
-					}
-				}
-				$t.grid.fhDiv = $('<div style="position:absolute;left:0px;top:'+top+'px;height:'+hth+'px;" class="frozen-div ui-state-default ui-jqgrid-hdiv"></div>');
-				$t.grid.fbDiv = $('<div style="position:absolute;left:0px;top:'+(parseInt(top,10)+parseInt(hth,10) + 1)+'px;overflow-y:hidden" class="frozen-bdiv ui-jqgrid-bdiv"></div>');
-				$("#gview_"+$.jgrid.jqID($t.p.id)).append($t.grid.fhDiv);
-				var htbl = $(".ui-jqgrid-htable","#gview_"+$.jgrid.jqID($t.p.id)).clone(true);
-				// groupheader support - only if useColSpanstyle is false
-				if($t.p.groupHeader) {
-					$("tr.jqg-first-row-header, tr.jqg-third-row-header", htbl).each(function(){
-						$("th:gt("+maxfrozen+")",this).remove();
-					});
-					var swapfroz = -1, fdel = -1;
-					$("tr.jqg-second-row-header th", htbl).each(function(){
-						var cs= parseInt($(this).attr("colspan"),10);
-						if(cs) {
-							swapfroz = swapfroz+cs;
-							fdel++;
-						}
-						if(swapfroz === maxfrozen) {
-							return false;
-						}
-					});
-					if(swapfroz !== maxfrozen) {
-						fdel = maxfrozen;
-					}
-					$("tr.jqg-second-row-header", htbl).each(function(){
-						$("th:gt("+fdel+")",this).remove();
-					});
-				} else {
-					$("tr",htbl).each(function(){
-						$("th:gt("+maxfrozen+")",this).remove();
-					});
-				}
-				$(htbl).width(1);
-				// resizing stuff
-				$($t.grid.fhDiv).append(htbl)
-				.mousemove(function (e) {
-					if($t.grid.resizing){ $t.grid.dragMove(e);return false; }
-				});
-				$($t).bind('jqGridResizeStop.setFrozenColumns', function (e, w, index) {
-					var rhth = $(".ui-jqgrid-htable",$t.grid.fhDiv);
-					$("th:eq("+index+")",rhth).width( w );
-					var btd = $(".ui-jqgrid-btable",$t.grid.fbDiv);
-					$("tr:first td:eq("+index+")",btd).width( w );
-				});
-				// sorting stuff
-				$($t).bind('jqGridOnSortCol.setFrozenColumns', function (index, idxcol) {
-
-					var previousSelectedTh = $("tr.ui-jqgrid-labels:last th:eq("+$t.p.lastsort+")",$t.grid.fhDiv), newSelectedTh = $("tr.ui-jqgrid-labels:last th:eq("+idxcol+")",$t.grid.fhDiv);
-
-					$("span.ui-grid-ico-sort",previousSelectedTh).addClass('ui-state-disabled');
-					$(previousSelectedTh).attr("aria-selected","false");
-					$("span.ui-icon-"+$t.p.sortorder,newSelectedTh).removeClass('ui-state-disabled');
-					$(newSelectedTh).attr("aria-selected","true");
-					if(!$t.p.viewsortcols[0]) {
-						if($t.p.lastsort != idxcol) {
-							$("span.s-ico",previousSelectedTh).hide();
-							$("span.s-ico",newSelectedTh).show();
-						}
-					}
-				});
-
-				// data stuff
-				//TODO support for setRowData
-				$("#gview_"+$.jgrid.jqID($t.p.id)).append($t.grid.fbDiv);
-				jQuery($t.grid.bDiv).scroll(function () {
-					jQuery($t.grid.fbDiv).scrollTop(jQuery(this).scrollTop());
-				});
-				if($t.p.hoverrows === true) {
-					$("#"+$.jgrid.jqID($t.p.id)).unbind('mouseover').unbind('mouseout');
-				}
-				$($t).bind('jqGridAfterGridComplete.setFrozenColumns', function () {
-					$("#"+$.jgrid.jqID($t.p.id)+"_frozen").remove();
-					jQuery($t.grid.fbDiv).height( jQuery($t.grid.bDiv).height()-16);
-					var btbl = $("#"+$.jgrid.jqID($t.p.id)).clone(true);
-					$("tr",btbl).each(function(){
-						$("td:gt("+maxfrozen+")",this).remove();
-					});
-
-					$(btbl).width(1).attr("id",$t.p.id+"_frozen");
-					$($t.grid.fbDiv).append(btbl);
-					if($t.p.hoverrows === true) {
-						$("tr.jqgrow", btbl).hover(
-							function(){ $(this).addClass("ui-state-hover"); $("#"+$.jgrid.jqID(this.id), "#"+$.jgrid.jqID($t.p.id)).addClass("ui-state-hover"); },
-							function(){ $(this).removeClass("ui-state-hover"); $("#"+$.jgrid.jqID(this.id), "#"+$.jgrid.jqID($t.p.id)).removeClass("ui-state-hover"); }
-						);
-						$("tr.jqgrow", "#"+$.jgrid.jqID($t.p.id)).hover(
-							function(){ $(this).addClass("ui-state-hover"); $("#"+$.jgrid.jqID(this.id), "#"+$.jgrid.jqID($t.p.id)+"_frozen").addClass("ui-state-hover");},
-							function(){ $(this).removeClass("ui-state-hover"); $("#"+$.jgrid.jqID(this.id), "#"+$.jgrid.jqID($t.p.id)+"_frozen").removeClass("ui-state-hover"); }
-						);
-					}
-					btbl=null;
-				});
-				$t.p.frozenColumns = true;
-			}
-		});
-	},
-	destroyFrozenColumns :  function() {
-		return this.each(function() {
-			if ( !this.grid ) {return;}
-			if(this.p.frozenColumns === true) {
-				var $t = this;
-				$($t.grid.fhDiv).remove();
-				$($t.grid.fbDiv).remove();
-				$t.grid.fhDiv = null; $t.grid.fbDiv=null;
-				$(this).unbind('.setFrozenColumns');
-				if($t.p.hoverrows === true) {
-					var ptr;
-					$("#"+$.jgrid.jqID($t.p.id)).bind('mouseover',function(e) {
-						ptr = $(e.target).closest("tr.jqgrow");
-						if($(ptr).attr("class") !== "ui-subgrid") {
-						$(ptr).addClass("ui-state-hover");
-					}
-					}).bind('mouseout',function(e) {
-						ptr = $(e.target).closest("tr.jqgrow");
-						$(ptr).removeClass("ui-state-hover");
-					});
-				}
-				this.p.frozenColumns = false;
-			}
-		});
-	}
-});
-})(jQuery);/*
- * jqModal - Minimalist Modaling with jQuery
- *   (http://dev.iceburg.net/jquery/jqmodal/)
- *
- * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
- * Dual licensed under the MIT and GPL licenses:
- *   http://www.opensource.org/licenses/mit-license.php
- *   http://www.gnu.org/licenses/gpl.html
- *
- * $Version: 07/06/2008 +r13
- */
-(function($) {
-$.fn.jqm=function(o){
-var p={
-overlay: 50,
-closeoverlay : true,
-overlayClass: 'jqmOverlay',
-closeClass: 'jqmClose',
-trigger: '.jqModal',
-ajax: F,
-ajaxText: '',
-target: F,
-modal: F,
-toTop: F,
-onShow: F,
-onHide: F,
-onLoad: F
-};
-return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;
-H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};
-if(p.trigger)$(this).jqmAddTrigger(p.trigger);
-});};
-
-$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};
-$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};
-$.fn.jqmShow=function(t){return this.each(function(){$.jqm.open(this._jqm,t);});};
-$.fn.jqmHide=function(t){return this.each(function(){$.jqm.close(this._jqm,t)});};
-
-$.jqm = {
-hash:{},
-open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index')));z=(z>0)?z:3000;var o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);
- if(c.modal) {if(!A[0])setTimeout(function(){L('bind');},1);A.push(s);}
- else if(c.overlay > 0) {if(c.closeoverlay) h.w.jqmAddClose(o);}
- else o=F;
-
- h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;
- if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}
-
- if(c.ajax) {var r=c.target||h.w,u=c.ajax;r=(typeof r == 'string')?$(r,h.w):$(r);u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
-  r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
- else if(cc)h.w.jqmAddClose($(cc,h.w));
-
- if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);
- (c.onShow)?c.onShow(h):h.w.show();e(h);return F;
-},
-close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
- if(A[0]){A.pop();if(!A[0])L('unbind');}
- if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
- if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
-},
-params:{}};
-var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false,
-e=function(h){var i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0});if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
-f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},
-L=function(t){$(document)[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
-m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
-hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() {
- if(!this[c]){this[c]=[];$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};
-})(jQuery);/*
- * jqDnR - Minimalistic Drag'n'Resize for jQuery.
- *
- * Copyright (c) 2007 Brice Burgess <bhb@iceburg.net>, http://www.iceburg.net
- * Licensed under the MIT License:
- * http://www.opensource.org/licenses/mit-license.php
- *
- * $Version: 2007.08.19 +r2
- */
+// Grouping module
+;
+(function ($) {
+    "use strict";
+    $.extend($.jgrid, {
+        template: function (format) { //jqgformat
+            var args = $.makeArray(arguments).slice(1), j = 1;
+            if (format === undefined) {
+                format = "";
+            }
+            return format.replace(/\{([\w\-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g, function (m, i) {
+                if (!isNaN(parseInt(i, 10))) {
+                    j++;
+                    return args[parseInt(i, 10)];
+                } else {
+                    var nmarr = args[ j ],
+                        k = nmarr.length;
+                    while (k--) {
+                        if (i === nmarr[k].nm) {
+                            return nmarr[k].v;
+                            break;
+                        }
+                    }
+                    j++;
+                }
+            });
+        }
+    });
+    $.jgrid.extend({
+        groupingSetup: function () {
+            return this.each(function () {
+                var $t = this,
+                    grp = $t.p.groupingView;
+                if (grp !== null && ( (typeof grp === 'object') || $.isFunction(grp) )) {
+                    if (!grp.groupField.length) {
+                        $t.p.grouping = false;
+                    } else {
+                        if (typeof(grp.visibiltyOnNextGrouping) === 'undefined') {
+                            grp.visibiltyOnNextGrouping = [];
+                        }
 
-(function($){
-$.fn.jqDrag=function(h){return i(this,h,'d');};
-$.fn.jqResize=function(h,ar){return i(this,h,'r',ar);};
-$.jqDnR={
-	dnr:{},
-	e:0,
-	drag:function(v){
-		if(M.k == 'd'){E.css({left:M.X+v.pageX-M.pX,top:M.Y+v.pageY-M.pY});}
-		else {
-			E.css({width:Math.max(v.pageX-M.pX+M.W,0),height:Math.max(v.pageY-M.pY+M.H,0)});
-			if(M1){E1.css({width:Math.max(v.pageX-M1.pX+M1.W,0),height:Math.max(v.pageY-M1.pY+M1.H,0)});}
-		}
-		return false;
-	},
-	stop:function(){
-		//E.css('opacity',M.o);
-		$(document).unbind('mousemove',J.drag).unbind('mouseup',J.stop);
-	}
-};
-var J=$.jqDnR,M=J.dnr,E=J.e,E1,M1,
-i=function(e,h,k,aR){
-	return e.each(function(){
-		h=(h)?$(h,e):e;
-		h.bind('mousedown',{e:e,k:k},function(v){
-			var d=v.data,p={};E=d.e;E1 = aR ? $(aR) : false;
-			// attempt utilization of dimensions plugin to fix IE issues
-			if(E.css('position') != 'relative'){try{E.position(p);}catch(e){}}
-			M={
-				X:p.left||f('left')||0,
-				Y:p.top||f('top')||0,
-				W:f('width')||E[0].scrollWidth||0,
-				H:f('height')||E[0].scrollHeight||0,
-				pX:v.pageX,
-				pY:v.pageY,
-				k:d.k
-				//o:E.css('opacity')
-			};
-			// also resize
-			if(E1 && d.k != 'd'){
-				M1={
-					X:p.left||f1('left')||0,
-					Y:p.top||f1('top')||0,
-					W:E1[0].offsetWidth||f1('width')||0,
-					H:E1[0].offsetHeight||f1('height')||0,
-					pX:v.pageX,
-					pY:v.pageY,
-					k:d.k
-				};
-			} else {M1 = false;}
-			//E.css({opacity:0.8});
-			if($("input.hasDatepicker",E[0])[0]) {
-			try {$("input.hasDatepicker",E[0]).datepicker('hide');}catch (dpe){}
-			}
-			$(document).mousemove($.jqDnR.drag).mouseup($.jqDnR.stop);
-			return false;
-		});
-	});
-},
-f=function(k){return parseInt(E.css(k),10)||false;},
-f1=function(k){return parseInt(E1.css(k),10)||false;};
-})(jQuery);/*
-	The below work is licensed under Creative Commons GNU LGPL License.
-
-	Original work:
-
-	License:     http://creativecommons.org/licenses/LGPL/2.1/
-	Author:      Stefan Goessner/2006
-	Web:         http://goessner.net/
-
-	Modifications made:
-
-	Version:     0.9-p5
-	Description: Restructured code, JSLint validated (no strict whitespaces),
-	             added handling of empty arrays, empty strings, and int/floats values.
-	Author:      Michael Schøler/2008-01-29
-	Web:         http://michael.hinnerup.net/blog/2008/01/26/converting-json-to-xml-and-xml-to-json/
-
-	Description: json2xml added support to convert functions as CDATA
-	             so it will be easy to write characters that cause some problems when convert
-	Author:      Tony Tomov
-*/
+                        grp.lastvalues = [];
+                        grp.groups = [];
+                        grp.counters = [];
+                        for (var i = 0; i < grp.groupField.length; i++) {
+                            if (!grp.groupOrder[i]) {
+                                grp.groupOrder[i] = 'asc';
+                            }
+                            if (!grp.groupText[i]) {
+                                grp.groupText[i] = '{0}';
+                            }
+                            if (typeof(grp.groupColumnShow[i]) !== 'boolean') {
+                                grp.groupColumnShow[i] = true;
+                            }
+                            if (typeof(grp.groupSummary[i]) !== 'boolean') {
+                                grp.groupSummary[i] = false;
+                            }
+                            if (grp.groupColumnShow[i] === true) {
+                                grp.visibiltyOnNextGrouping[i] = true;
+                                $($t).jqGrid('showCol', grp.groupField[i]);
+                            } else {
+                                grp.visibiltyOnNextGrouping[i] = $("#" + $.jgrid.jqID($t.p.id + "_" + grp.groupField[i])).is(":visible");
+                                $($t).jqGrid('hideCol', grp.groupField[i]);
+                            }
+                        }
+                        grp.summary = [];
+                        var cm = $t.p.colModel;
+                        for (var j = 0, cml = cm.length; j < cml; j++) {
+                            if (cm[j].summaryType) {
+                                grp.summary.push({nm: cm[j].name, st: cm[j].summaryType, v: '', sr: cm[j].summaryRound, srt: cm[j].summaryRoundType || 'round'});
+                            }
+                        }
+                    }
+                } else {
+                    $t.p.grouping = false;
+                }
+            });
+        },
+        groupingPrepare: function (rData, gdata, record, irow) {
+            this.each(function () {
+                var grp = this.p.groupingView, $t = this;
+                var grlen = grp.groupField.length,
+                    fieldName,
+                    v,
+                    changed = 0;
+                for (var i = 0; i < grlen; i++) {
+                    fieldName = grp.groupField[i];
+                    v = record[fieldName];
+                    if (v !== undefined) {
+                        if (irow === 0) {
+                            // First record always starts a new group
+                            grp.groups.push({idx: i, dataIndex: fieldName, value: v, startRow: irow, cnt: 1, summary: [] });
+                            grp.lastvalues[i] = v;
+                            grp.counters[i] = {cnt: 1, pos: grp.groups.length - 1, summary: $.extend(true, [], grp.summary)};
+                            $.each(grp.counters[i].summary, function () {
+                                if ($.isFunction(this.st)) {
+                                    this.v = this.st.call($t, this.v, this.nm, record);
+                                } else {
+                                    this.v = $($t).jqGrid('groupingCalculations.handler', this.st, this.v, this.nm, this.sr, this.srt, record);
+                                }
+                            });
+                            grp.groups[grp.counters[i].pos].summary = grp.counters[i].summary;
+                        } else {
+                            if ((typeof(v) !== "object" && (grp.lastvalues[i] !== v) )) {
+                                // This record is not in same group as previous one
+                                grp.groups.push({idx: i, dataIndex: fieldName, value: v, startRow: irow, cnt: 1, summary: [] });
+                                grp.lastvalues[i] = v;
+                                changed = 1;
+                                grp.counters[i] = {cnt: 1, pos: grp.groups.length - 1, summary: $.extend(true, [], grp.summary)};
+                                $.each(grp.counters[i].summary, function () {
+                                    if ($.isFunction(this.st)) {
+                                        this.v = this.st.call($t, this.v, this.nm, record);
+                                    } else {
+                                        this.v = $($t).jqGrid('groupingCalculations.handler', this.st, this.v, this.nm, this.sr, this.srt, record);
+                                    }
+                                });
+                                grp.groups[grp.counters[i].pos].summary = grp.counters[i].summary;
+                            } else {
+                                if (changed === 1) {
+                                    // This group has changed because an earlier group changed.
+                                    grp.groups.push({idx: i, dataIndex: fieldName, value: v, startRow: irow, cnt: 1, summary: [] });
+                                    grp.lastvalues[i] = v;
+                                    grp.counters[i] = {cnt: 1, pos: grp.groups.length - 1, summary: $.extend(true, [], grp.summary)};
+                                    $.each(grp.counters[i].summary, function () {
+                                        if ($.isFunction(this.st)) {
+                                            this.v = this.st.call($t, this.v, this.nm, record);
+                                        } else {
+                                            this.v = $($t).jqGrid('groupingCalculations.handler', this.st, this.v, this.nm, this.sr, this.srt, record);
+                                        }
+                                    });
+                                    grp.groups[grp.counters[i].pos].summary = grp.counters[i].summary;
+                                } else {
+                                    grp.counters[i].cnt += 1;
+                                    grp.groups[grp.counters[i].pos].cnt = grp.counters[i].cnt;
+                                    $.each(grp.counters[i].summary, function () {
+                                        if ($.isFunction(this.st)) {
+                                            this.v = this.st.call($t, this.v, this.nm, record);
+                                        } else {
+                                            this.v = $($t).jqGrid('groupingCalculations.handler', this.st, this.v, this.nm, this.sr, this.srt, record);
+                                        }
+                                    });
+                                    grp.groups[grp.counters[i].pos].summary = grp.counters[i].summary;
+                                }
+                            }
+                        }
+                    }
+                }
+                gdata.push(rData);
+            });
+            return gdata;
+        },
+        groupingToggle: function (hid) {
+            this.each(function () {
+                var $t = this,
+                    grp = $t.p.groupingView,
+                    strpos = hid.split('_'),
+                //uid = hid.substring(0,strpos+1),
+                    num = parseInt(strpos[strpos.length - 2], 10);
+                strpos.splice(strpos.length - 2, 2);
+                var uid = strpos.join("_"),
+                    minus = grp.minusicon,
+                    plus = grp.plusicon,
+                    tar = $("#" + $.jgrid.jqID(hid)),
+                    r = tar.length ? tar[0].nextSibling : null,
+                    tarspan = $("#" + $.jgrid.jqID(hid) + " span." + "tree-wrap-" + $t.p.direction),
+                    collapsed = false;
+                if (tarspan.hasClass(minus)) {
+                    if (grp.showSummaryOnHide) {
+                        if (r) {
+                            while (r) {
+                                if ($(r).hasClass('jqfoot')) {
+                                    break;
+                                }
+                                $(r).hide();
+                                r = r.nextSibling;
+                            }
+                        }
+                    } else {
+                        if (r) {
+                            while (r) {
+                                if ($(r).hasClass(uid + "_" + String(num)) || $(r).hasClass(uid + "_" + String(num - 1))) {
+                                    break;
+                                }
+                                $(r).hide();
+                                r = r.nextSibling;
+                            }
+                        }
+                    }
+                    tarspan.removeClass(minus).addClass(plus);
+                    collapsed = true;
+                } else {
+                    if (r) {
+                        while (r) {
+                            if ($(r).hasClass(uid + "_" + String(num)) || $(r).hasClass(uid + "_" + String(num - 1))) {
+                                break;
+                            }
+                            $(r).show();
+                            r = r.nextSibling;
+                        }
+                    }
+                    tarspan.removeClass(plus).addClass(minus);
+                }
+                $($t).triggerHandler("jqGridGroupingClickGroup", [hid , collapsed]);
+                if ($.isFunction($t.p.onClickGroup)) {
+                    $t.p.onClickGroup.call($t, hid, collapsed);
+                }
 
-/*global alert */
-var xmlJsonClass = {
-	// Param "xml": Element or document DOM node.
-	// Param "tab": Tab or indent string for pretty output formatting omit or use empty string "" to supress.
-	// Returns:     JSON string
-	xml2json: function(xml, tab) {
-		if (xml.nodeType === 9) {
-			// document node
-			xml = xml.documentElement;
-		}
-		var nws = this.removeWhite(xml);
-		var obj = this.toObj(nws);
-		var json = this.toJson(obj, xml.nodeName, "\t");
-		return "{\n" + tab + (tab ? json.replace(/\t/g, tab) : json.replace(/\t|\n/g, "")) + "\n}";
-	},
-
-	// Param "o":   JavaScript object
-	// Param "tab": tab or indent string for pretty output formatting omit or use empty string "" to supress.
-	// Returns:     XML string
-	json2xml: function(o, tab) {
-		var toXml = function(v, name, ind) {
-			var xml = "";
-			var i, n;
-			if (v instanceof Array) {
-				if (v.length === 0) {
-					xml += ind + "<"+name+">__EMPTY_ARRAY_</"+name+">\n";
-				}
-				else {
-					for (i = 0, n = v.length; i < n; i += 1) {
-						var sXml = ind + toXml(v[i], name, ind+"\t") + "\n";
-						xml += sXml;
-					}
-				}
-			}
-			else if (typeof(v) === "object") {
-				var hasChild = false;
-				xml += ind + "<" + name;
-				var m;
-				for (m in v) if (v.hasOwnProperty(m)) {
-					if (m.charAt(0) === "@") {
-						xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
-					}
-					else {
-						hasChild = true;
-					}
-				}
-				xml += hasChild ? ">" : "/>";
-				if (hasChild) {
-					for (m in v) if (v.hasOwnProperty(m)) {
-						if (m === "#text") {
-							xml += v[m];
-						}
-						else if (m === "#cdata") {
-							xml += "<![CDATA[" + v[m] + "]]>";
-						}
-						else if (m.charAt(0) !== "@") {
-							xml += toXml(v[m], m, ind+"\t");
-						}
-					}
-					xml += (xml.charAt(xml.length - 1) === "\n" ? ind : "") + "</" + name + ">";
-				}
-			}
-			else if (typeof(v) === "function") {
-				xml += ind + "<" + name + ">" + "<![CDATA[" + v + "]]>" + "</" + name + ">";
-			}
-			else {
-				if (v === undefined ) { v = ""; }
-				if (v.toString() === "\"\"" || v.toString().length === 0) {
-					xml += ind + "<" + name + ">__EMPTY_STRING_</" + name + ">";
-				}
-				else {
-					xml += ind + "<" + name + ">" + v.toString() + "</" + name + ">";
-				}
-			}
-			return xml;
-		};
-		var xml = "";
-		var m;
-		for (m in o) if (o.hasOwnProperty(m)) {
-			xml += toXml(o[m], m, "");
-		}
-		return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, "");
-	},
-	// Internal methods
-	toObj: function(xml) {
-		var o = {};
-		var FuncTest = /function/i;
-		if (xml.nodeType === 1) {
-			// element node ..
-			if (xml.attributes.length) {
-				// element with attributes ..
-				var i;
-				for (i = 0; i < xml.attributes.length; i += 1) {
-					o["@" + xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue || "").toString();
-				}
-			}
-			if (xml.firstChild) {
-				// element has child nodes ..
-				var textChild = 0, cdataChild = 0, hasElementChild = false;
-				var n;
-				for (n = xml.firstChild; n; n = n.nextSibling) {
-					if (n.nodeType === 1) {
-						hasElementChild = true;
-					}
-					else if (n.nodeType === 3 && n.nodeValue.match(/[^ \f\n\r\t\v]/)) {
-						// non-whitespace text
-						textChild += 1;
-					}
-					else if (n.nodeType === 4) {
-						// cdata section node
-						cdataChild += 1;
-					}
-				}
-				if (hasElementChild) {
-					if (textChild < 2 && cdataChild < 2) {
-						// structured element with evtl. a single text or/and cdata node ..
-						this.removeWhite(xml);
-						for (n = xml.firstChild; n; n = n.nextSibling) {
-							if (n.nodeType === 3) {
-								// text node
-								o["#text"] = this.escape(n.nodeValue);
-							}
-							else if (n.nodeType === 4) {
-								// cdata node
-								if (FuncTest.test(n.nodeValue)) {
-									o[n.nodeName] = [o[n.nodeName], n.nodeValue];
-								} else {
-									o["#cdata"] = this.escape(n.nodeValue);
-								}
-							}
-							else if (o[n.nodeName]) {
-								// multiple occurence of element ..
-								if (o[n.nodeName] instanceof Array) {
-									o[n.nodeName][o[n.nodeName].length] = this.toObj(n);
-								}
-								else {
-									o[n.nodeName] = [o[n.nodeName], this.toObj(n)];
-								}
-							}
-							else {
-								// first occurence of element ..
-								o[n.nodeName] = this.toObj(n);
-							}
-						}
-					}
-					else {
-						// mixed content
-						if (!xml.attributes.length) {
-							o = this.escape(this.innerXml(xml));
-						}
-						else {
-							o["#text"] = this.escape(this.innerXml(xml));
-						}
-					}
-				}
-				else if (textChild) {
-					// pure text
-					if (!xml.attributes.length) {
-						o = this.escape(this.innerXml(xml));
-						if (o === "__EMPTY_ARRAY_") {
-							o = "[]";
-						} else if (o === "__EMPTY_STRING_") {
-							o = "";
-						}
-					}
-					else {
-						o["#text"] = this.escape(this.innerXml(xml));
-					}
-				}
-				else if (cdataChild) {
-					// cdata
-					if (cdataChild > 1) {
-						o = this.escape(this.innerXml(xml));
-					}
-					else {
-						for (n = xml.firstChild; n; n = n.nextSibling) {
-							if(FuncTest.test(xml.firstChild.nodeValue)) {
-								o = xml.firstChild.nodeValue;
-								break;
-							} else {
-								o["#cdata"] = this.escape(n.nodeValue);
-							}
-						}
-					}
-				}
-			}
-			if (!xml.attributes.length && !xml.firstChild) {
-				o = null;
-			}
-		}
-		else if (xml.nodeType === 9) {
-			// document.node
-			o = this.toObj(xml.documentElement);
-		}
-		else {
-			alert("unhandled node type: " + xml.nodeType);
-		}
-		return o;
-	},
-	toJson: function(o, name, ind, wellform) {
-		if(wellform === undefined) wellform = true;
-		var json = name ? ("\"" + name + "\"") : "", tab = "\t", newline = "\n";
-		if(!wellform) {
-			tab= ""; newline= "";
-		}
-
-		if (o === "[]") {
-			json += (name ? ":[]" : "[]");
-		}
-		else if (o instanceof Array) {
-			var n, i, ar=[];
-			for (i = 0, n = o.length; i < n; i += 1) {
-				ar[i] = this.toJson(o[i], "", ind + tab, wellform);
-			}
-			json += (name ? ":[" : "[") + (ar.length > 1 ? (newline + ind + tab + ar.join(","+newline + ind + tab) + newline + ind) : ar.join("")) + "]";
-		}
-		else if (o === null) {
-			json += (name && ":") + "null";
-		}
-		else if (typeof(o) === "object") {
-			var arr = [], m;
-			for (m in o) {
-				if (o.hasOwnProperty(m)) {
-					arr[arr.length] = this.toJson(o[m], m, ind + tab, wellform);
-			}
-		}
-			json += (name ? ":{" : "{") + (arr.length > 1 ? (newline + ind + tab + arr.join(","+newline + ind + tab) + newline + ind) : arr.join("")) + "}";
-		}
-		else if (typeof(o) === "string") {
-			/*
-			var objRegExp  = /(^-?\d+\.?\d*$)/;
-			var FuncTest = /function/i;
-			var os = o.toString();
-			if (objRegExp.test(os) || FuncTest.test(os) || os==="false" || os==="true") {
-				// int or float
-				json += (name && ":")  + "\"" +os + "\"";
-			}
-			else {
-			*/
-				json += (name && ":") + "\"" + o.replace(/\\/g,'\\\\').replace(/\"/g,'\\"') + "\"";
-			//}
-			}
-		else {
-			json += (name && ":") +  o.toString();
-		}
-		return json;
-	},
-	innerXml: function(node) {
-		var s = "";
-		if ("innerHTML" in node) {
-			s = node.innerHTML;
-		}
-		else {
-			var asXml = function(n) {
-				var s = "", i;
-				if (n.nodeType === 1) {
-					s += "<" + n.nodeName;
-					for (i = 0; i < n.attributes.length; i += 1) {
-						s += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue || "").toString() + "\"";
-					}
-					if (n.firstChild) {
-						s += ">";
-						for (var c = n.firstChild; c; c = c.nextSibling) {
-							s += asXml(c);
-						}
-						s += "</" + n.nodeName + ">";
-					}
-					else {
-						s += "/>";
-					}
-				}
-				else if (n.nodeType === 3) {
-					s += n.nodeValue;
-				}
-				else if (n.nodeType === 4) {
-					s += "<![CDATA[" + n.nodeValue + "]]>";
-				}
-				return s;
-			};
-			for (var c = node.firstChild; c; c = c.nextSibling) {
-				s += asXml(c);
-			}
-		}
-		return s;
-	},
-	escape: function(txt) {
-		return txt.replace(/[\\]/g, "\\\\").replace(/[\"]/g, '\\"').replace(/[\n]/g, '\\n').replace(/[\r]/g, '\\r');
-	},
-	removeWhite: function(e) {
-		e.normalize();
-		var n;
-		for (n = e.firstChild; n; ) {
-			if (n.nodeType === 3) {
-				// text node
-				if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) {
-					// pure whitespace text node
-					var nxt = n.nextSibling;
-					e.removeChild(n);
-					n = nxt;
-				}
-				else {
-					n = n.nextSibling;
-				}
-			}
-			else if (n.nodeType === 1) {
-				// element node
-				this.removeWhite(n);
-				n = n.nextSibling;
-			}
-			else {
-				// any other node
-				n = n.nextSibling;
-			}
-		}
-		return e;
-	}
-};/*
-**
- * formatter for values but most of the values if for jqGrid
- * Some of this was inspired and based on how YUI does the table datagrid but in jQuery fashion
- * we are trying to keep it as light as possible
- * Joshua Burnett josh@9ci.com
- * http://www.greenbill.com
- *
- * Changes from Tony Tomov tony@trirand.com
- * Dual licensed under the MIT and GPL licenses:
- * http://www.opensource.org/licenses/mit-license.php
- * http://www.gnu.org/licenses/gpl-2.0.html
- *
-**/
-
-;(function($) {
-"use strict";
-	$.fmatter = {};
-	//opts can be id:row id for the row, rowdata:the data for the row, colmodel:the column model for this column
-	//example {id:1234,}
-	$.extend($.fmatter,{
-		isBoolean : function(o) {
-			return typeof o === 'boolean';
-		},
-		isObject : function(o) {
-			return (o && (typeof o === 'object' || $.isFunction(o))) || false;
-		},
-		isString : function(o) {
-			return typeof o === 'string';
-		},
-		isNumber : function(o) {
-			return typeof o === 'number' && isFinite(o);
-		},
-		isNull : function(o) {
-			return o === null;
-		},
-		isUndefined : function(o) {
-			return typeof o === 'undefined';
-		},
-		isValue : function (o) {
-			return (this.isObject(o) || this.isString(o) || this.isNumber(o) || this.isBoolean(o));
-		},
-		isEmpty : function(o) {
-			if(!this.isString(o) && this.isValue(o)) {
-				return false;
-			}else if (!this.isValue(o)){
-				return true;
-			}
-			o = $.trim(o).replace(/\&nbsp\;/ig,'').replace(/\&#160\;/ig,'');
-			return o==="";
-		}
-	});
-	$.fn.fmatter = function(formatType, cellval, opts, rwd, act) {
-		// build main options before element iteration
-		var v=cellval;
-		opts = $.extend({}, $.jgrid.formatter, opts);
-
-		try {
-			v = $.fn.fmatter[formatType].call(this, cellval, opts, rwd, act);
-		} catch(fe){}
-		return v;
-	};
-	$.fmatter.util = {
-		// Taken from YAHOO utils
-		NumberFormat : function(nData,opts) {
-			if(!$.fmatter.isNumber(nData)) {
-				nData *= 1;
-			}
-			if($.fmatter.isNumber(nData)) {
-				var bNegative = (nData < 0);
-				var sOutput = nData + "";
-				var sDecimalSeparator = (opts.decimalSeparator) ? opts.decimalSeparator : ".";
-				var nDotIndex;
-				if($.fmatter.isNumber(opts.decimalPlaces)) {
-					// Round to the correct decimal place
-					var nDecimalPlaces = opts.decimalPlaces;
-					var nDecimal = Math.pow(10, nDecimalPlaces);
-					sOutput = Math.round(nData*nDecimal)/nDecimal + "";
-					nDotIndex = sOutput.lastIndexOf(".");
-					if(nDecimalPlaces > 0) {
-					// Add the decimal separator
-						if(nDotIndex < 0) {
-							sOutput += sDecimalSeparator;
-							nDotIndex = sOutput.length-1;
-						}
-						// Replace the "."
-						else if(sDecimalSeparator !== "."){
-							sOutput = sOutput.replace(".",sDecimalSeparator);
-						}
-					// Add missing zeros
-						while((sOutput.length - 1 - nDotIndex) < nDecimalPlaces) {
-							sOutput += "0";
-						}
-					}
-				}
-				if(opts.thousandsSeparator) {
-					var sThousandsSeparator = opts.thousandsSeparator;
-					nDotIndex = sOutput.lastIndexOf(sDecimalSeparator);
-					nDotIndex = (nDotIndex > -1) ? nDotIndex : sOutput.length;
-					var sNewOutput = sOutput.substring(nDotIndex);
-					var nCount = -1;
-					for (var i=nDotIndex; i>0; i--) {
-						nCount++;
-						if ((nCount%3 === 0) && (i !== nDotIndex) && (!bNegative || (i > 1))) {
-							sNewOutput = sThousandsSeparator + sNewOutput;
-						}
-						sNewOutput = sOutput.charAt(i-1) + sNewOutput;
-					}
-					sOutput = sNewOutput;
-				}
-				// Prepend prefix
-				sOutput = (opts.prefix) ? opts.prefix + sOutput : sOutput;
-				// Append suffix
-				sOutput = (opts.suffix) ? sOutput + opts.suffix : sOutput;
-				return sOutput;
-
-			} else {
-				return nData;
-			}
-		},
-		// Tony Tomov
-		// PHP implementation. Sorry not all options are supported.
-		// Feel free to add them if you want
-		DateFormat : function (format, date, newformat, opts)  {
-			var	token = /\\.|[dDjlNSwzWFmMntLoYyaABgGhHisueIOPTZcrU]/g,
-			timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
-			timezoneClip = /[^-+\dA-Z]/g,
-			msDateRegExp = new RegExp("^\/Date\\((([-+])?[0-9]+)(([-+])([0-9]{2})([0-9]{2}))?\\)\/$"),
-			msMatch = ((typeof date === 'string') ? date.match(msDateRegExp): null),
-			pad = function (value, length) {
-				value = String(value);
-				length = parseInt(length,10) || 2;
-				while (value.length < length)  { value = '0' + value; }
-				return value;
-			},
-			ts = {m : 1, d : 1, y : 1970, h : 0, i : 0, s : 0, u:0},
-			timestamp=0, dM, k,hl,
-			dateFormat=["i18n"];
-			// Internationalization strings
-			dateFormat.i18n = {
-				dayNames: opts.dayNames,
-				monthNames: opts.monthNames
-			};
-			if( format in opts.masks ) { format = opts.masks[format]; }
-			if( !isNaN( date - 0 ) && String(format).toLowerCase() == "u") {
-				//Unix timestamp
-				timestamp = new Date( parseFloat(date)*1000 );
-			} else if(date.constructor === Date) {
-				timestamp = date;
-				// Microsoft date format support
-			} else if( msMatch !== null ) {
-				timestamp = new Date(parseInt(msMatch[1], 10));
-				if (msMatch[3]) {
-					var offset = Number(msMatch[5]) * 60 + Number(msMatch[6]);
-					offset *= ((msMatch[4] == '-') ? 1 : -1);
-					offset -= timestamp.getTimezoneOffset();
-					timestamp.setTime(Number(Number(timestamp) + (offset * 60 * 1000)));
-				}
-			} else {
-				date = String(date).split(/[\\\/:_;.,\t\T\s-]/);
-				format = format.split(/[\\\/:_;.,\t\T\s-]/);
-				// parsing for month names
-				for(k=0,hl=format.length;k<hl;k++){
-					if(format[k] == 'M') {
-						dM = $.inArray(date[k],dateFormat.i18n.monthNames);
-						if(dM !== -1 && dM < 12){date[k] = dM+1;}
-					}
-					if(format[k] == 'F') {
-						dM = $.inArray(date[k],dateFormat.i18n.monthNames);
-						if(dM !== -1 && dM > 11){date[k] = dM+1-12;}
-					}
-					if(date[k]) {
-						ts[format[k].toLowerCase()] = parseInt(date[k],10);
-					}
-				}
-				if(ts.f) {ts.m = ts.f;}
-				if( ts.m === 0 && ts.y === 0 && ts.d === 0) {
-					return "&#160;" ;
-				}
-				ts.m = parseInt(ts.m,10)-1;
-				var ty = ts.y;
-				if (ty >= 70 && ty <= 99) {ts.y = 1900+ts.y;}
-				else if (ty >=0 && ty <=69) {ts.y= 2000+ts.y;}
-				timestamp = new Date(ts.y, ts.m, ts.d, ts.h, ts.i, ts.s, ts.u);
-			}
-
-			if( newformat in opts.masks )  {
-				newformat = opts.masks[newformat];
-			} else if ( !newformat ) {
-				newformat = 'Y-m-d';
-			}
-			var
-				G = timestamp.getHours(),
-				i = timestamp.getMinutes(),
-				j = timestamp.getDate(),
-				n = timestamp.getMonth() + 1,
-				o = timestamp.getTimezoneOffset(),
-				s = timestamp.getSeconds(),
-				u = timestamp.getMilliseconds(),
-				w = timestamp.getDay(),
-				Y = timestamp.getFullYear(),
-				N = (w + 6) % 7 + 1,
-				z = (new Date(Y, n - 1, j) - new Date(Y, 0, 1)) / 86400000,
-				flags = {
-					// Day
-					d: pad(j),
-					D: dateFormat.i18n.dayNames[w],
-					j: j,
-					l: dateFormat.i18n.dayNames[w + 7],
-					N: N,
-					S: opts.S(j),
-					//j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th',
-					w: w,
-					z: z,
-					// Week
-					W: N < 5 ? Math.floor((z + N - 1) / 7) + 1 : Math.floor((z + N - 1) / 7) || ((new Date(Y - 1, 0, 1).getDay() + 6) % 7 < 4 ? 53 : 52),
-					// Month
-					F: dateFormat.i18n.monthNames[n - 1 + 12],
-					m: pad(n),
-					M: dateFormat.i18n.monthNames[n - 1],
-					n: n,
-					t: '?',
-					// Year
-					L: '?',
-					o: '?',
-					Y: Y,
-					y: String(Y).substring(2),
-					// Time
-					a: G < 12 ? opts.AmPm[0] : opts.AmPm[1],
-					A: G < 12 ? opts.AmPm[2] : opts.AmPm[3],
-					B: '?',
-					g: G % 12 || 12,
-					G: G,
-					h: pad(G % 12 || 12),
-					H: pad(G),
-					i: pad(i),
-					s: pad(s),
-					u: u,
-					// Timezone
-					e: '?',
-					I: '?',
-					O: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
-					P: '?',
-					T: (String(timestamp).match(timezone) || [""]).pop().replace(timezoneClip, ""),
-					Z: '?',
-					// Full Date/Time
-					c: '?',
-					r: '?',
-					U: Math.floor(timestamp / 1000)
-				};
-			return newformat.replace(token, function ($0) {
-				return $0 in flags ? flags[$0] : $0.substring(1);
-			});
-		}
-	};
-	$.fn.fmatter.defaultFormat = function(cellval, opts) {
-		return ($.fmatter.isValue(cellval) && cellval!=="" ) ?  cellval : opts.defaultValue ? opts.defaultValue : "&#160;";
-	};
-	$.fn.fmatter.email = function(cellval, opts) {
-		if(!$.fmatter.isEmpty(cellval)) {
-			return "<a href=\"mailto:" + cellval + "\">" + cellval + "</a>";
-		}else {
-			return $.fn.fmatter.defaultFormat(cellval,opts );
-		}
-	};
-	$.fn.fmatter.checkbox =function(cval, opts) {
-		var op = $.extend({},opts.checkbox), ds;
-		if(opts.colModel !== undefined && !$.fmatter.isUndefined(opts.colModel.formatoptions)) {
-			op = $.extend({},op,opts.colModel.formatoptions);
-		}
-		if(op.disabled===true) {ds = "disabled=\"disabled\"";} else {ds="";}
-		if($.fmatter.isEmpty(cval) || $.fmatter.isUndefined(cval) ) {cval = $.fn.fmatter.defaultFormat(cval,op);}
-		cval=cval+"";cval=cval.toLowerCase();
-		var bchk = cval.search(/(false|0|no|off)/i)<0 ? " checked='checked' " : "";
-		return "<input type=\"checkbox\" " + bchk  + " value=\""+ cval+"\" offval=\"no\" "+ds+ "/>";
-	};
-	$.fn.fmatter.link = function(cellval, opts) {
-		var op = {target:opts.target};
-		var target = "";
-		if(opts.colModel !== undefined && !$.fmatter.isUndefined(opts.colModel.formatoptions)) {
-			op = $.extend({},op,opts.colModel.formatoptions);
-		}
-		if(op.target) {target = 'target=' + op.target;}
-		if(!$.fmatter.isEmpty(cellval)) {
-			return "<a "+target+" href=\"" + cellval + "\">" + cellval + "</a>";
-		}else {
-			return $.fn.fmatter.defaultFormat(cellval,opts);
-		}
-	};
-	$.fn.fmatter.showlink = function(cellval, opts) {
-		var op = {baseLinkUrl: opts.baseLinkUrl,showAction:opts.showAction, addParam: opts.addParam || "", target: opts.target, idName: opts.idName},
-		target = "", idUrl;
-		if(opts.colModel !== undefined && !$.fmatter.isUndefined(opts.colModel.formatoptions)) {
-			op = $.extend({},op,opts.colModel.formatoptions);
-		}
-		if(op.target) {target = 'target=' + op.target;}
-		idUrl = op.baseLinkUrl+op.showAction + '?'+ op.idName+'='+opts.rowId+op.addParam;
-		if($.fmatter.isString(cellval) || $.fmatter.isNumber(cellval)) {	//add this one even if its blank string
-			return "<a "+target+" href=\"" + idUrl + "\">" + cellval + "</a>";
-		}else {
-			return $.fn.fmatter.defaultFormat(cellval,opts);
-		}
-	};
-	$.fn.fmatter.integer = function(cellval, opts) {
-		var op = $.extend({},opts.integer);
-		if(opts.colModel !== undefined && !$.fmatter.isUndefined(opts.colModel.formatoptions)) {
-			op = $.extend({},op,opts.colModel.formatoptions);
-		}
-		if($.fmatter.isEmpty(cellval)) {
-			return op.defaultValue;
-		}
-		return $.fmatter.util.NumberFormat(cellval,op);
-	};
-	$.fn.fmatter.number = function (cellval, opts) {
-		var op = $.extend({},opts.number);
-		if(opts.colModel !== undefined && !$.fmatter.isUndefined(opts.colModel.formatoptions)) {
-			op = $.extend({},op,opts.colModel.formatoptions);
-		}
-		if($.fmatter.isEmpty(cellval)) {
-			return op.defaultValue;
-		}
-		return $.fmatter.util.NumberFormat(cellval,op);
-	};
-	$.fn.fmatter.currency = function (cellval, opts) {
-		var op = $.extend({},opts.currency);
-		if(opts.colModel !== undefined && !$.fmatter.isUndefined(opts.colModel.formatoptions)) {
-			op = $.extend({},op,opts.colModel.formatoptions);
-		}
-		if($.fmatter.isEmpty(cellval)) {
-			return op.defaultValue;
-		}
-		return $.fmatter.util.NumberFormat(cellval,op);
-	};
-	$.fn.fmatter.date = function (cellval, opts, rwd, act) {
-		var op = $.extend({},opts.date);
-		if(opts.colModel !== undefined && !$.fmatter.isUndefined(opts.colModel.formatoptions)) {
-			op = $.extend({},op,opts.colModel.formatoptions);
-		}
-		if(!op.reformatAfterEdit && act=='edit'){
-			return $.fn.fmatter.defaultFormat(cellval, opts);
-		} else if(!$.fmatter.isEmpty(cellval)) {
-			return  $.fmatter.util.DateFormat(op.srcformat,cellval,op.newformat,op);
-		} else {
-			return $.fn.fmatter.defaultFormat(cellval, opts);
-		}
-	};
-	$.fn.fmatter.select = function (cellval,opts) {
-		// jqGrid specific
-		cellval = cellval + "";
-		var oSelect = false, ret=[], sep, delim;
-		if(!$.fmatter.isUndefined(opts.colModel.formatoptions)){
-			oSelect= opts.colModel.formatoptions.value;
-			sep = opts.colModel.formatoptions.separator === undefined ? ":" : opts.colModel.formatoptions.separator;
-			delim = opts.colModel.formatoptions.delimiter === undefined ? ";" : opts.colModel.formatoptions.delimiter;
-		} else if(!$.fmatter.isUndefined(opts.colModel.editoptions)){
-			oSelect= opts.colModel.editoptions.value;
-			sep = opts.colModel.editoptions.separator === undefined ? ":" : opts.colModel.editoptions.separator;
-			delim = opts.colModel.editoptions.delimiter === undefined ? ";" : opts.colModel.editoptions.delimiter;
-		}
-		if (oSelect) {
-			var	msl =  opts.colModel.editoptions.multiple === true ? true : false,
-			scell = [], sv;
-			if(msl) {scell = cellval.split(",");scell = $.map(scell,function(n){return $.trim(n);});}
-			if ($.fmatter.isString(oSelect)) {
-				// mybe here we can use some caching with care ????
-				var so = oSelect.split(delim), j=0;
-				for(var i=0; i<so.length;i++){
-					sv = so[i].split(sep);
-					if(sv.length > 2 ) {
-						sv[1] = $.map(sv,function(n,i){if(i>0) {return n;}}).join(sep);
-					}
-					if(msl) {
-						if($.inArray(sv[0],scell)>-1) {
-							ret[j] = sv[1];
-							j++;
-						}
-					} else if($.trim(sv[0])==$.trim(cellval)) {
-						ret[0] = sv[1];
-						break;
-					}
-				}
-			} else if($.fmatter.isObject(oSelect)) {
-				// this is quicker
-				if(msl) {
-					ret = $.map(scell, function(n){
-						return oSelect[n];
-					});
-				} else {
-					ret[0] = oSelect[cellval] || "";
-				}
-			}
-		}
-		cellval = ret.join(", ");
-		return  cellval === "" ? $.fn.fmatter.defaultFormat(cellval,opts) : cellval;
-	};
-	$.fn.fmatter.rowactions = function(rid,gid,act,pos) {
-		var op ={
-			keys:false,
-			onEdit : null,
-			onSuccess: null,
-			afterSave:null,
-			onError: null,
-			afterRestore: null,
-			extraparam: {},
-			url: null,
-			restoreAfterError: true,
-			mtype: "POST",
-			delOptions: {},
-			editOptions : {}
-		};
-		rid = $.jgrid.jqID( rid );
-		gid = $.jgrid.jqID( gid );
-		var cm = $('#'+gid)[0].p.colModel[pos];
-		if(!$.fmatter.isUndefined(cm.formatoptions)) {
-			op = $.extend(op,cm.formatoptions);
-		}
-		if( !$.fmatter.isUndefined($('#'+gid)[0].p.editOptions) ) {
-			op.editOptions = $('#'+gid)[0].p.editOptions;
-		}
-		if( !$.fmatter.isUndefined($('#'+gid)[0].p.delOptions) ) {
-			op.delOptions = $('#'+gid)[0].p.delOptions;
-		}
-		var $t = $("#"+gid)[0];
-		var saverow = function( rowid, res)	{
-			if($.isFunction(op.afterSave)) { op.afterSave.call($t, rowid, res); }
-			$("tr#"+rid+" div.ui-inline-edit, "+"tr#"+rid+" div.ui-inline-del","#"+gid + ".ui-jqgrid-btable:first").show();
-			$("tr#"+rid+" div.ui-inline-save, "+"tr#"+rid+" div.ui-inline-cancel","#"+gid+ ".ui-jqgrid-btable:first").hide();
-		},
-		restorerow = function( rowid)	{
-			if($.isFunction(op.afterRestore) ) { op.afterRestore.call($t, rowid); }
-			$("tr#"+rid+" div.ui-inline-edit, "+"tr#"+rid+" div.ui-inline-del","#"+gid+ ".ui-jqgrid-btable:first").show();
-			$("tr#"+rid+" div.ui-inline-save, "+"tr#"+rid+" div.ui-inline-cancel","#"+gid+ ".ui-jqgrid-btable:first").hide();
-		};
-		if( $("#"+rid,"#"+gid).hasClass("jqgrid-new-row") ){
-			var opers = $t.p.prmNames,
-			oper = opers.oper;
-			op.extraparam[oper] = opers.addoper;
-		}
-		var actop = {
-			keys : op.keys,
-			oneditfunc: op.onEdit,
-			successfunc: op.onSuccess,
-			url: op.url,
-			extraparam: op.extraparam,
-			aftersavefunc: saverow,
-			errorfunc: op.onError,
-			afterrestorefunc: restorerow,
-			restoreAfterError: op.restoreAfterError,
-			mtype: op.mtype
-		};
-		switch(act)
-		{
-			case 'edit':
-				$('#'+gid).jqGrid('editRow', rid, actop);
-				$("tr#"+rid+" div.ui-inline-edit, "+"tr#"+rid+" div.ui-inline-del","#"+gid+ ".ui-jqgrid-btable:first").hide();
-				$("tr#"+rid+" div.ui-inline-save, "+"tr#"+rid+" div.ui-inline-cancel","#"+gid+ ".ui-jqgrid-btable:first").show();
-				$($t).triggerHandler("jqGridAfterGridComplete");
-				break;
-			case 'save':
-				if ( $('#'+gid).jqGrid('saveRow', rid, actop) ) {
-				$("tr#"+rid+" div.ui-inline-edit, "+"tr#"+rid+" div.ui-inline-del","#"+gid+ ".ui-jqgrid-btable:first").show();
-				$("tr#"+rid+" div.ui-inline-save, "+"tr#"+rid+" div.ui-inline-cancel","#"+gid+ ".ui-jqgrid-btable:first").hide();
-				$($t).triggerHandler("jqGridAfterGridComplete");
-				}
-				break;
-			case 'cancel' :
-				$('#'+gid).jqGrid('restoreRow',rid, restorerow);
-				$("tr#"+rid+" div.ui-inline-edit, "+"tr#"+rid+" div.ui-inline-del","#"+gid+ ".ui-jqgrid-btable:first").show();
-				$("tr#"+rid+" div.ui-inline-save, "+"tr#"+rid+" div.ui-inline-cancel","#"+gid+ ".ui-jqgrid-btable:first").hide();
-				$($t).triggerHandler("jqGridAfterGridComplete");
-				break;
-			case 'del':
-				$('#'+gid).jqGrid('delGridRow',rid, op.delOptions);
-				break;
-			case 'formedit':
-				$('#'+gid).jqGrid('setSelection',rid);
-				$('#'+gid).jqGrid('editGridRow',rid, op.editOptions);
-				break;
-		}
-	};
-	$.fn.fmatter.actions = function(cellval,opts) {
-		var op ={keys:false, editbutton:true, delbutton:true, editformbutton: false};
-		if(!$.fmatter.isUndefined(opts.colModel.formatoptions)) {
-			op = $.extend(op,opts.colModel.formatoptions);
-		}
-		var rowid = opts.rowId, str="",ocl;
-		if(typeof(rowid) =='undefined' || $.fmatter.isEmpty(rowid)) {return "";}
-		if(op.editformbutton){
-			ocl = "onclick=jQuery.fn.fmatter.rowactions('"+rowid+"','"+opts.gid+"','formedit',"+opts.pos+"); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); ";
-			str =str+ "<div title='"+$.jgrid.nav.edittitle+"' style='float:left;cursor:pointer;' class='ui-pg-div ui-inline-edit' "+ocl+"><span class='ui-icon ui-icon-pencil'></span></div>";
-		} else if(op.editbutton){
-			ocl = "onclick=jQuery.fn.fmatter.rowactions('"+rowid+"','"+opts.gid+"','edit',"+opts.pos+"); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover') ";
-			str =str+ "<div title='"+$.jgrid.nav.edittitle+"' style='float:left;cursor:pointer;' class='ui-pg-div ui-inline-edit' "+ocl+"><span class='ui-icon ui-icon-pencil'></span></div>";
-		}
-		if(op.delbutton) {
-			ocl = "onclick=jQuery.fn.fmatter.rowactions('"+rowid+"','"+opts.gid+"','del',"+opts.pos+"); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); ";
-			str = str+"<div title='"+$.jgrid.nav.deltitle+"' style='float:left;margin-left:5px;' class='ui-pg-div ui-inline-del' "+ocl+"><span class='ui-icon ui-icon-trash'></span></div>";
-		}
-		ocl = "onclick=jQuery.fn.fmatter.rowactions('"+rowid+"','"+opts.gid+"','save',"+opts.pos+"); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); ";
-		str = str+"<div title='"+$.jgrid.edit.bSubmit+"' style='float:left;display:none' class='ui-pg-div ui-inline-save' "+ocl+"><span class='ui-icon ui-icon-disk'></span></div>";
-		ocl = "onclick=jQuery.fn.fmatter.rowactions('"+rowid+"','"+opts.gid+"','cancel',"+opts.pos+"); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); ";
-		str = str+"<div title='"+$.jgrid.edit.bCancel+"' style='float:left;display:none;margin-left:5px;' class='ui-pg-div ui-inline-cancel' "+ocl+"><span class='ui-icon ui-icon-cancel'></span></div>";
-		return "<div style='margin-left:8px;'>" + str + "</div>";
-	};
-	$.unformat = function (cellval,options,pos,cnt) {
-		// specific for jqGrid only
-		var ret, formatType = options.colModel.formatter,
-		op =options.colModel.formatoptions || {}, sep,
-		re = /([\.\*\_\'\(\)\{\}\+\?\\])/g,
-		unformatFunc = options.colModel.unformat||($.fn.fmatter[formatType] && $.fn.fmatter[formatType].unformat);
-		if(typeof unformatFunc !== 'undefined' && $.isFunction(unformatFunc) ) {
-			ret = unformatFunc.call(this, $(cellval).text(), options, cellval);
-		} else if(!$.fmatter.isUndefined(formatType) && $.fmatter.isString(formatType) ) {
-			var opts = $.jgrid.formatter || {}, stripTag;
-			switch(formatType) {
-				case 'integer' :
-					op = $.extend({},opts.integer,op);
-					sep = op.thousandsSeparator.replace(re,"\\$1");
-					stripTag = new RegExp(sep, "g");
-					ret = $(cellval).text().replace(stripTag,'');
-					break;
-				case 'number' :
-					op = $.extend({},opts.number,op);
-					sep = op.thousandsSeparator.replace(re,"\\$1");
-					stripTag = new RegExp(sep, "g");
-					ret = $(cellval).text().replace(stripTag,"").replace(op.decimalSeparator,'.');
-					break;
-				case 'currency':
-					op = $.extend({},opts.currency,op);
-					sep = op.thousandsSeparator.replace(re,"\\$1");
-					stripTag = new RegExp(sep, "g");
-					ret = $(cellval).text();
-					if (op.prefix && op.prefix.length) {
-						ret = ret.substr(op.prefix.length);
-					}
-					if (op.suffix && op.suffix.length) {
-						ret = ret.substr(0, ret.length - op.suffix.length);
-					}
-					ret = ret.replace(stripTag,'').replace(op.decimalSeparator,'.');
-					break;
-				case 'checkbox':
-					var cbv = (options.colModel.editoptions) ? options.colModel.editoptions.value.split(":") : ["Yes","No"];
-					ret = $('input',cellval).is(":checked") ? cbv[0] : cbv[1];
-					break;
-				case 'select' :
-					ret = $.unformat.select(cellval,options,pos,cnt);
-					break;
-				case 'actions':
-					return "";
-				default:
-					ret= $(cellval).text();
-			}
-		}
-		return ret !== undefined ? ret : cnt===true ? $(cellval).text() : $.jgrid.htmlDecode($(cellval).html());
-	};
-	$.unformat.select = function (cellval,options,pos,cnt) {
-		// Spacial case when we have local data and perform a sort
-		// cnt is set to true only in sortDataArray
-		var ret = [];
-		var cell = $(cellval).text();
-		if(cnt===true) {return cell;}
-		var op = $.extend({}, !$.fmatter.isUndefined(options.colModel.formatoptions) ? options.colModel.formatoptions: options.colModel.editoptions),
-		sep = op.separator === undefined ? ":" : op.separator,
-		delim = op.delimiter === undefined ? ";" : op.delimiter;
-
-		if(op.value){
-			var oSelect = op.value,
-			msl =  op.multiple === true ? true : false,
-			scell = [], sv;
-			if(msl) {scell = cell.split(",");scell = $.map(scell,function(n){return $.trim(n);});}
-			if ($.fmatter.isString(oSelect)) {
-				var so = oSelect.split(delim), j=0;
-				for(var i=0; i<so.length;i++){
-					sv = so[i].split(sep);
-					if(sv.length > 2 ) {
-						sv[1] = $.map(sv,function(n,i){if(i>0) {return n;}}).join(sep);
-					}
-					if(msl) {
-						if($.inArray(sv[1],scell)>-1) {
-							ret[j] = sv[0];
-							j++;
-						}
-					} else if($.trim(sv[1])==$.trim(cell)) {
-						ret[0] = sv[0];
-						break;
-					}
-				}
-			} else if($.fmatter.isObject(oSelect) || $.isArray(oSelect) ){
-				if(!msl) {scell[0] =  cell;}
-				ret = $.map(scell, function(n){
-					var rv;
-					$.each(oSelect, function(i,val){
-						if (val == n) {
-							rv = i;
-							return false;
-						}
-					});
-					if( typeof(rv) != 'undefined' ) {return rv;}
-				});
-			}
-			return ret.join(", ");
-		} else {
-			return cell || "";
-		}
-	};
-	$.unformat.date = function (cellval, opts) {
-		var op = $.jgrid.formatter.date || {};
-		if(!$.fmatter.isUndefined(opts.formatoptions)) {
-			op = $.extend({},op,opts.formatoptions);
-		}
-		if(!$.fmatter.isEmpty(cellval)) {
-			return $.fmatter.util.DateFormat(op.newformat,cellval,op.srcformat,op);
-		} else {
-			return $.fn.fmatter.defaultFormat(cellval, opts);
-		}
-	};
-})(jQuery);
-;(function($){
-/*
- * jqGrid common function
- * Tony Tomov tony@trirand.com
- * http://trirand.com/blog/
- * Dual licensed under the MIT and GPL licenses:
- * http://www.opensource.org/licenses/mit-license.php
- * http://www.gnu.org/licenses/gpl-2.0.html
-*/
-/*global jQuery, $ */
+            });
+            return false;
+        },
+        groupingRender: function (grdata, colspans) {
+            return this.each(function () {
+                var $t = this,
+                    grp = $t.p.groupingView,
+                    str = "", icon = "", hid, clid, pmrtl = grp.groupCollapse ? grp.plusicon : grp.minusicon, gv, cp = [], ii, len = grp.groupField.length;
+                pmrtl += " tree-wrap-" + $t.p.direction;
+                ii = 0;
+                $.each($t.p.colModel, function (i, n) {
+                    for (var ii = 0; ii < len; ii++) {
+                        if (grp.groupField[ii] === n.name) {
+                            cp[ii] = i;
+                            break;
+                        }
+                    }
+                });
+                var toEnd = 0;
+
+                function findGroupIdx(ind, offset, grp) {
+                    if (offset === 0) {
+                        return grp[ind];
+                    } else {
+                        var id = grp[ind].idx;
+                        if (id === 0) {
+                            return grp[ind];
+                        }
+                        for (var i = ind; i >= 0; i--) {
+                            if (grp[i].idx === id - offset) {
+                                return grp[i];
+                            }
+                        }
+                    }
+                }
+
+                var sumreverse = grp.groupSummary;
+                sumreverse.reverse();
+                $.each(grp.groups, function (i, n) {
+                    toEnd++;
+                    clid = $t.p.id + "ghead_" + n.idx;
+                    hid = clid + "_" + i;
+                    icon = "<span style='cursor:pointer;' class='ui-icon " + pmrtl + "' onclick=\"jQuery('#" + $.jgrid.jqID($t.p.id) + "').jqGrid('groupingToggle','" + hid + "');return false;\"></span>";
+                    try {
+                        gv = $t.formatter(hid, n.value, cp[n.idx], n.value);
+                    } catch (egv) {
+                        gv = n.value;
+                    }
+                    str += "<tr id=\"" + hid + "\" role=\"row\" class= \"ui-widget-content jqgroup ui-row-" + $t.p.direction + " " + clid + "\"><td style=\"padding-left:" + (n.idx * 12) + "px;" + "\" colspan=\"" + colspans + "\">" + icon + $.jgrid.template(grp.groupText[n.idx], gv, n.cnt, n.summary) + "</td></tr>";
+                    var leaf = len - 1 === n.idx;
+                    if (leaf) {
+                        var gg = grp.groups[i + 1];
+                        var end = gg !== undefined ? grp.groups[i + 1].startRow : grdata.length;
+                        for (var kk = n.startRow; kk < end; kk++) {
+                            str += grdata[kk].join('');
+                        }
+                        var jj;
+                        if (gg !== undefined) {
+                            for (jj = 0; jj < grp.groupField.length; jj++) {
+                                if (gg.dataIndex === grp.groupField[jj]) {
+                                    break;
+                                }
+                            }
+                            toEnd = grp.groupField.length - jj;
+                        }
+                        for (var ik = 0; ik < toEnd; ik++) {
+                            if (!sumreverse[ik]) {
+                                continue;
+                            }
+                            var hhdr = "";
+                            if (grp.groupCollapse && !grp.showSummaryOnHide) {
+                                hhdr = " style=\"display:none;\"";
+                            }
+                            str += "<tr" + hhdr + " role=\"row\" class=\"ui-widget-content jqfoot ui-row-" + $t.p.direction + "\">";
+                            var fdata = findGroupIdx(i, ik, grp.groups),
+                                cm = $t.p.colModel,
+                                vv, grlen = fdata.cnt;
+                            for (var k = 0; k < colspans; k++) {
+                                var tmpdata = "<td " + $t.formatCol(k, 1, '') + ">&#160;</td>",
+                                    tplfld = "{0}";
+                                $.each(fdata.summary, function () {
+                                    if (this.nm === cm[k].name) {
+                                        if (cm[k].summaryTpl) {
+                                            tplfld = cm[k].summaryTpl;
+                                        }
+                                        if (this.st.toLowerCase() === 'avg') {
+                                            if (this.v && grlen > 0) {
+                                                this.v = (this.v / grlen);
+                                            }
+                                        }
+                                        try {
+                                            vv = $t.formatter('', this.v, k, this);
+                                        } catch (ef) {
+                                            vv = this.v;
+                                        }
+                                        tmpdata = "<td " + $t.formatCol(k, 1, '') + ">" + $.jgrid.format(tplfld, vv) + "</td>";
+                                        return false;
+                                    }
+                                });
+                                str += tmpdata;
+                            }
+                            str += "</tr>";
+                        }
+                        toEnd = jj;
+                    }
+                });
+                $("#" + $.jgrid.jqID($t.p.id) + " tbody:first").append(str);
+                // free up memory
+                str = null;
+            });
+        },
+        groupingGroupBy: function (name, options) {
+            return this.each(function () {
+                var $t = this;
+                if (typeof(name) === "string") {
+                    name = [name];
+                }
+                var grp = $t.p.groupingView;
+                $t.p.grouping = true;
+
+                //Set default, in case visibilityOnNextGrouping is undefined
+                if (typeof grp.visibiltyOnNextGrouping === "undefined") {
+                    grp.visibiltyOnNextGrouping = [];
+                }
+                var i;
+                // show previous hidden groups if they are hidden and weren't removed yet
+                for (i = 0; i < grp.groupField.length; i++) {
+                    if (!grp.groupColumnShow[i] && grp.visibiltyOnNextGrouping[i]) {
+                        $($t).jqGrid('showCol', grp.groupField[i]);
+                    }
+                }
+                // set visibility status of current group columns on next grouping
+                for (i = 0; i < name.length; i++) {
+                    grp.visibiltyOnNextGrouping[i] = $("#" + $.jgrid.jqID($t.p.id) + "_" + $.jgrid.jqID(name[i])).is(":visible");
+                }
+                $t.p.groupingView = $.extend($t.p.groupingView, options || {});
+                grp.groupField = name;
+                $($t).trigger("reloadGrid");
+            });
+        },
+        groupingRemove: function (current) {
+            return this.each(function () {
+                var $t = this;
+                if (typeof(current) === 'undefined') {
+                    current = true;
+                }
+                $t.p.grouping = false;
+                if (current === true) {
+                    var grp = $t.p.groupingView;
+                    // show previous hidden groups if they are hidden and weren't removed yet
+                    for (var i = 0; i < grp.groupField.length; i++) {
+                        if (!grp.groupColumnShow[i] && grp.visibiltyOnNextGrouping[i]) {
+                            $($t).jqGrid('showCol', grp.groupField);
+                        }
+                    }
+                    $("tr.jqgroup, tr.jqfoot", "#" + $.jgrid.jqID($t.p.id) + " tbody:first").remove();
+                    $("tr.jqgrow:hidden", "#" + $.jgrid.jqID($t.p.id) + " tbody:first").show();
+                } else {
+                    $($t).trigger("reloadGrid");
+                }
+            });
+        },
+        groupingCalculations: {
+            handler: function (fn, v, field, round, roundType, rc) {
+                var funcs = {
+                    sum: function () {
+                        return parseFloat(v || 0) + parseFloat((rc[field] || 0));
+                    },
 
-$.extend($.jgrid,{
-// Modal functions
-	showModal : function(h) {
-		h.w.show();
-	},
-	closeModal : function(h) {
-		h.w.hide().attr("aria-hidden","true");
-		if(h.o) {h.o.remove();}
-	},
-	hideModal : function (selector,o) {
-		o = $.extend({jqm : true, gb :''}, o || {});
-		if(o.onClose) {
-			var oncret =  o.onClose(selector);
-			if (typeof oncret == 'boolean'  && !oncret ) { return; }
-		}
-		if ($.fn.jqm && o.jqm === true) {
-			$(selector).attr("aria-hidden","true").jqmHide();
-		} else {
-			if(o.gb !== '') {
-				try {$(".jqgrid-overlay:first",o.gb).hide();} catch (e){}
-			}
-			$(selector).hide().attr("aria-hidden","true");
-		}
-	},
-//Helper functions
-	findPos : function(obj) {
-		var curleft = 0, curtop = 0;
-		if (obj.offsetParent) {
-			do {
-				curleft += obj.offsetLeft;
-				curtop += obj.offsetTop;
-			} while (obj = obj.offsetParent);
-			//do not change obj == obj.offsetParent
-		}
-		return [curleft,curtop];
-	},
-	createModal : function(aIDs, content, p, insertSelector, posSelector, appendsel, css) {
-		var mw  = document.createElement('div'), rtlsup, self = this;
-		css = $.extend({}, css || {});
-		rtlsup = $(p.gbox).attr("dir") == "rtl" ? true : false;
-		mw.className= "ui-widget ui-widget-content ui-corner-all ui-jqdialog";
-		mw.id = aIDs.themodal;
-		var mh = document.createElement('div');
-		mh.className = "ui-jqdialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix";
-		mh.id = aIDs.modalhead;
-		$(mh).append("<span class='ui-jqdialog-title'>"+p.caption+"</span>");
-		var ahr= $("<a href='javascript:void(0)' class='ui-jqdialog-titlebar-close ui-corner-all'></a>")
-		.hover(function(){ahr.addClass('ui-state-hover');},
-			   function(){ahr.removeClass('ui-state-hover');})
-		.append("<span class='ui-icon ui-icon-closethick'></span>");
-		$(mh).append(ahr);
-		if(rtlsup) {
-			mw.dir = "rtl";
-			$(".ui-jqdialog-title",mh).css("float","right");
-			$(".ui-jqdialog-titlebar-close",mh).css("left",0.3+"em");
-		} else {
-			mw.dir = "ltr";
-			$(".ui-jqdialog-title",mh).css("float","left");
-			$(".ui-jqdialog-titlebar-close",mh).css("right",0.3+"em");
-		}
-		var mc = document.createElement('div');
-		$(mc).addClass("ui-jqdialog-content ui-widget-content").attr("id",aIDs.modalcontent);
-		$(mc).append(content);
-		mw.appendChild(mc);
-		$(mw).prepend(mh);
-		if(appendsel===true) { $('body').append(mw); } //append as first child in body -for alert dialog
-		else if (typeof appendsel == "string")
-			$(appendsel).append(mw);
-		else {$(mw).insertBefore(insertSelector);}
-		$(mw).css(css);
-		if(typeof p.jqModal === 'undefined') {p.jqModal = true;} // internal use
-		var coord = {};
-		if ( $.fn.jqm && p.jqModal === true) {
-			if(p.left ===0 && p.top===0 && p.overlay) {
-				var pos = [];
-				pos = $.jgrid.findPos(posSelector);
-				p.left = pos[0] + 4;
-				p.top = pos[1] + 4;
-			}
-			coord.top = p.top+"px";
-			coord.left = p.left;
-		} else if(p.left !==0 || p.top!==0) {
-			coord.left = p.left;
-			coord.top = p.top+"px";
-		}
-		$("a.ui-jqdialog-titlebar-close",mh).click(function(){
-			var oncm = $("#"+$.jgrid.jqID(aIDs.themodal)).data("onClose") || p.onClose;
-			var gboxclose = $("#"+$.jgrid.jqID(aIDs.themodal)).data("gbox") || p.gbox;
-			self.hideModal("#"+$.jgrid.jqID(aIDs.themodal),{gb:gboxclose,jqm:p.jqModal,onClose:oncm});
-			return false;
-		});
-		if (p.width === 0 || !p.width) {p.width = 300;}
-		if(p.height === 0 || !p.height) {p.height =200;}
-		if(!p.zIndex) {
-			var parentZ = $(insertSelector).parents("*[role=dialog]").filter(':first').css("z-index");
-			if(parentZ) {
-				p.zIndex = parseInt(parentZ,10)+2;
-			} else {
-				p.zIndex = 950;
-			}
-		}
-		var rtlt = 0;
-		if( rtlsup && coord.left && !appendsel) {
-			rtlt = $(p.gbox).width()- (!isNaN(p.width) ? parseInt(p.width,10) :0) - 8; // to do
-		// just in case
-			coord.left = parseInt(coord.left,10) + parseInt(rtlt,10);
-		}
-		if(coord.left) { coord.left += "px"; }
-		$(mw).css($.extend({
-			width: isNaN(p.width) ? "auto": p.width+"px",
-			height:isNaN(p.height) ? "auto" : p.height + "px",
-			zIndex:p.zIndex,
-			overflow: 'hidden'
-		},coord))
-		.attr({tabIndex: "-1","role":"dialog","aria-labelledby":aIDs.modalhead,"aria-hidden":"true"});
-		if(typeof p.drag == 'undefined') { p.drag=true;}
-		if(typeof p.resize == 'undefined') {p.resize=true;}
-		if (p.drag) {
-			$(mh).css('cursor','move');
-			if($.fn.jqDrag) {
-				$(mw).jqDrag(mh);
-			} else {
-				try {
-					$(mw).draggable({handle: $("#"+$.jgrid.jqID(mh.id))});
-				} catch (e) {}
-			}
-		}
-		if(p.resize) {
-			if($.fn.jqResize) {
-				$(mw).append("<div class='jqResize ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se ui-icon-grip-diagonal-se'></div>");
-				$("#"+$.jgrid.jqID(aIDs.themodal)).jqResize(".jqResize",aIDs.scrollelm ? "#"+$.jgrid.jqID(aIDs.scrollelm) : false);
-			} else {
-				try {
-					$(mw).resizable({handles: 'se, sw',alsoResize: aIDs.scrollelm ? "#"+$.jgrid.jqID(aIDs.scrollelm) : false});
-				} catch (r) {}
-			}
-		}
-		if(p.closeOnEscape === true){
-			$(mw).keydown( function( e ) {
-				if( e.which == 27 ) {
-					var cone = $("#"+$.jgrid.jqID(aIDs.themodal)).data("onClose") || p.onClose;
-					self.hideModal(this,{gb:p.gbox,jqm:p.jqModal,onClose: cone});
-				}
-			});
-		}
-	},
-	viewModal : function (selector,o){
-		o = $.extend({
-			toTop: true,
-			overlay: 10,
-			modal: false,
-			overlayClass : 'ui-widget-overlay',
-			onShow: $.jgrid.showModal,
-			onHide: $.jgrid.closeModal,
-			gbox: '',
-			jqm : true,
-			jqM : true
-		}, o || {});
-		if ($.fn.jqm && o.jqm === true) {
-			if(o.jqM) { $(selector).attr("aria-hidden","false").jqm(o).jqmShow(); }
-			else {$(selector).attr("aria-hidden","false").jqmShow();}
-		} else {
-			if(o.gbox !== '') {
-				$(".jqgrid-overlay:first",o.gbox).show();
-				$(selector).data("gbox",o.gbox);
-			}
-			$(selector).show().attr("aria-hidden","false");
-			try{$(':input:visible',selector)[0].focus();}catch(_){}
-		}
-	},
-
-	info_dialog : function(caption, content,c_b, modalopt) {
-		var mopt = {
-			width:290,
-			height:'auto',
-			dataheight: 'auto',
-			drag: true,
-			resize: false,
-			caption:"<b>"+caption+"</b>",
-			left:250,
-			top:170,
-			zIndex : 1000,
-			jqModal : true,
-			modal : false,
-			closeOnEscape : true,
-			align: 'center',
-			buttonalign : 'center',
-			buttons : []
-		// {text:'textbutt', id:"buttid", onClick : function(){...}}
-		// if the id is not provided we set it like info_button_+ the index in the array - i.e info_button_0,info_button_1...
-		};
-		$.extend(mopt,modalopt || {});
-		var jm = mopt.jqModal, self = this;
-		if($.fn.jqm && !jm) { jm = false; }
-		// in case there is no jqModal
-		var buttstr ="";
-		if(mopt.buttons.length > 0) {
-			for(var i=0;i<mopt.buttons.length;i++) {
-				if(typeof mopt.buttons[i].id == "undefined") { mopt.buttons[i].id = "info_button_"+i; }
-				buttstr += "<a href='javascript:void(0)' id='"+mopt.buttons[i].id+"' class='fm-button ui-state-default ui-corner-all'>"+mopt.buttons[i].text+"</a>";
-			}
-		}
-		var dh = isNaN(mopt.dataheight) ? mopt.dataheight : mopt.dataheight+"px",
-		cn = "text-align:"+mopt.align+";";
-		var cnt = "<div id='info_id'>";
-		cnt += "<div id='infocnt' style='margin:0px;padding-bottom:1em;width:100%;overflow:auto;position:relative;height:"+dh+";"+cn+"'>"+content+"</div>";
-		cnt += c_b ? "<div class='ui-widget-content ui-helper-clearfix' style='text-align:"+mopt.buttonalign+";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'><a href='javascript:void(0)' id='closedialog' class='fm-button ui-state-default ui-corner-all'>"+c_b+"</a>"+buttstr+"</div>" :
-			buttstr !== ""  ? "<div class='ui-widget-content ui-helper-clearfix' style='text-align:"+mopt.buttonalign+";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'>"+buttstr+"</div>" : "";
-		cnt += "</div>";
-
-		try {
-			if($("#info_dialog").attr("aria-hidden") == "false") {
-				$.jgrid.hideModal("#info_dialog",{jqm:jm});
-			}
-			$("#info_dialog").remove();
-		} catch (e){}
-		$.jgrid.createModal({
-			themodal:'info_dialog',
-			modalhead:'info_head',
-			modalcontent:'info_content',
-			scrollelm: 'infocnt'},
-			cnt,
-			mopt,
-			'','',true
-		);
-		// attach onclick after inserting into the dom
-		if(buttstr) {
-			$.each(mopt.buttons,function(i){
-				$("#"+$.jgrid.jqID(this.id),"#info_id").bind('click',function(){mopt.buttons[i].onClick.call($("#info_dialog")); return false;});
-			});
-		}
-		$("#closedialog", "#info_id").click(function(){
-			self.hideModal("#info_dialog",{jqm:jm});
-			return false;
-		});
-		$(".fm-button","#info_dialog").hover(
-			function(){$(this).addClass('ui-state-hover');},
-			function(){$(this).removeClass('ui-state-hover');}
-		);
-		if($.isFunction(mopt.beforeOpen) ) { mopt.beforeOpen(); }
-		$.jgrid.viewModal("#info_dialog",{
-			onHide: function(h) {
-				h.w.hide().remove();
-				if(h.o) { h.o.remove(); }
-			},
-			modal :mopt.modal,
-			jqm:jm
-		});
-		if($.isFunction(mopt.afterOpen) ) { mopt.afterOpen(); }
-		try{ $("#info_dialog").focus();} catch (m){}
-	},
-// Form Functions
-	createEl : function(eltype,options,vl,autowidth, ajaxso) {
-		var elem = "", $t = this;
-		function bindEv (el, opt) {
-			if($.isFunction(opt.dataInit)) {
-				opt.dataInit.call($t,el);
-			}
-			if(opt.dataEvents) {
-				$.each(opt.dataEvents, function() {
-					if (this.data !== undefined) {
-						$(el).bind(this.type, this.data, this.fn);
-					} else {
-						$(el).bind(this.type, this.fn);
-					}
-				});
-			}
-			return opt;
-		}
-		function setAttributes(elm, atr, exl ) {
-			var exclude = ['dataInit','dataEvents','dataUrl', 'buildSelect','sopt', 'searchhidden', 'defaultValue', 'attr'];
-			if(typeof(exl) != "undefined" && $.isArray(exl)) {
-				$.merge(exclude, exl);
-			}
-			$.each(atr, function(key, value){
-				if($.inArray(key, exclude) === -1) {
-					$(elm).attr(key,value);
-				}
-			});
-			if(!atr.hasOwnProperty('id')) {
-				$(elm).attr('id', $.jgrid.randId());
-			}
-		}
-		switch (eltype)
-		{
-			case "textarea" :
-				elem = document.createElement("textarea");
-				if(autowidth) {
-					if(!options.cols) { $(elem).css({width:"98%"});}
-				} else if (!options.cols) { options.cols = 20; }
-				if(!options.rows) { options.rows = 2; }
-				if(vl=='&nbsp;' || vl=='&#160;' || (vl.length==1 && vl.charCodeAt(0)==160)) {vl="";}
-				elem.value = vl;
-				setAttributes(elem, options);
-				options = bindEv(elem,options);
-				$(elem).attr({"role":"textbox","multiline":"true"});
-			break;
-			case "checkbox" : //what code for simple checkbox
-				elem = document.createElement("input");
-				elem.type = "checkbox";
-				if( !options.value ) {
-					var vl1 = vl.toLowerCase();
-					if(vl1.search(/(false|0|no|off|undefined)/i)<0 && vl1!=="") {
-						elem.checked=true;
-						elem.defaultChecked=true;
-						elem.value = vl;
-					} else {
-						elem.value = "on";
-					}
-					$(elem).attr("offval","off");
-				} else {
-					var cbval = options.value.split(":");
-					if(vl === cbval[0]) {
-						elem.checked=true;
-						elem.defaultChecked=true;
-					}
-					elem.value = cbval[0];
-					$(elem).attr("offval",cbval[1]);
-				}
-				setAttributes(elem, options, ['value']);
-				options = bindEv(elem,options);
-				$(elem).attr("role","checkbox");
-			break;
-			case "select" :
-				elem = document.createElement("select");
-				elem.setAttribute("role","select");
-				var msl, ovm = [];
-				if(options.multiple===true) {
-					msl = true;
-					elem.multiple="multiple";
-					$(elem).attr("aria-multiselectable","true");
-				} else { msl = false; }
-				if(typeof(options.dataUrl) != "undefined") {
-					$.ajax($.extend({
-						url: options.dataUrl,
-						type : "GET",
-						dataType: "html",
-						context: {elem:elem, options:options, vl:vl},
-						success: function(data){
-							var a,	ovm = [], elem = this.elem, vl = this.vl,
-							options = $.extend({},this.options),
-							msl = options.multiple===true;
-							if($.isFunction(options.buildSelect)) {
-								var b = options.buildSelect.call($t,data);
-								a = $(b).html();
-							} else {
-								a = $(data).html();
-							}
-							if(a) {
-								$(elem).append(a);
-								setAttributes(elem, options);
-								options = bindEv(elem,options);
-								if(typeof options.size === 'undefined') { options.size =  msl ? 3 : 1;}
-								if(msl) {
-									ovm = vl.split(",");
-									ovm = $.map(ovm,function(n){return $.trim(n);});
-								} else {
-									ovm[0] = $.trim(vl);
-								}
-								//$(elem).attr(options);
-								setTimeout(function(){
-									$("option",elem).each(function(i){
-										//if(i===0) { this.selected = ""; }
-										// fix IE8/IE7 problem with selecting of the first item on multiple=true
-										if (i === 0 && elem.multiple) { this.selected = false; }
-										$(this).attr("role","option");
-										if($.inArray($.trim($(this).text()),ovm) > -1 || $.inArray($.trim($(this).val()),ovm) > -1 ) {
-											this.selected= "selected";
-										}
-									});
-								},0);
-							}
-						}
-					},ajaxso || {}));
-				} else if(options.value) {
-					var i;
-					if(typeof options.size === 'undefined') {
-						options.size = msl ? 3 : 1;
-					}
-					if(msl) {
-						ovm = vl.split(",");
-						ovm = $.map(ovm,function(n){return $.trim(n);});
-					}
-					if(typeof options.value === 'function') { options.value = options.value(); }
-					var so,sv, ov,
-					sep = options.separator === undefined ? ":" : options.separator,
-					delim = options.delimiter === undefined ? ";" : options.delimiter;
-					if(typeof options.value === 'string') {
-						so = options.value.split(delim);
-						for(i=0; i<so.length;i++){
-							sv = so[i].split(sep);
-							if(sv.length > 2 ) {
-								sv[1] = $.map(sv,function(n,ii){if(ii>0) { return n;} }).join(sep);
-							}
-							ov = document.createElement("option");
-							ov.setAttribute("role","option");
-							ov.value = sv[0]; ov.innerHTML = sv[1];
-							elem.appendChild(ov);
-							if (!msl &&  ($.trim(sv[0]) == $.trim(vl) || $.trim(sv[1]) == $.trim(vl))) { ov.selected ="selected"; }
-							if (msl && ($.inArray($.trim(sv[1]), ovm)>-1 || $.inArray($.trim(sv[0]), ovm)>-1)) {ov.selected ="selected";}
-						}
-					} else if (typeof options.value === 'object') {
-						var oSv = options.value;
-						for ( var key in oSv) {
-							if (oSv.hasOwnProperty(key ) ){
-								ov = document.createElement("option");
-								ov.setAttribute("role","option");
-								ov.value = key; ov.innerHTML = oSv[key];
-								elem.appendChild(ov);
-								if (!msl &&  ( $.trim(key) == $.trim(vl) || $.trim(oSv[key]) == $.trim(vl)) ) { ov.selected ="selected"; }
-								if (msl && ($.inArray($.trim(oSv[key]),ovm)>-1 || $.inArray($.trim(key),ovm)>-1)) { ov.selected ="selected"; }
-							}
-						}
-					}
-					setAttributes(elem, options, ['value']);
-					options = bindEv(elem,options);
-				}
-			break;
-			case "text" :
-			case "password" :
-			case "button" :
-				var role;
-				if(eltype=="button") { role = "button"; }
-				else { role = "textbox"; }
-				elem = document.createElement("input");
-				elem.type = eltype;
-				elem.value = vl;
-				setAttributes(elem, options);
-				options = bindEv(elem,options);
-				if(eltype != "button"){
-					if(autowidth) {
-						if(!options.size) { $(elem).css({width:"98%"}); }
-					} else if (!options.size) { options.size = 20; }
-				}
-				$(elem).attr("role",role);
-			break;
-			case "image" :
-			case "file" :
-				elem = document.createElement("input");
-				elem.type = eltype;
-				setAttributes(elem, options);
-				options = bindEv(elem,options);
-				break;
-			case "custom" :
-				elem = document.createElement("span");
-				try {
-					if($.isFunction(options.custom_element)) {
-						var celm = options.custom_element.call($t,vl,options);
-						if(celm) {
-							celm = $(celm).addClass("customelement").attr({id:options.id,name:options.name});
-							$(elem).empty().append(celm);
-						} else {
-							throw "e2";
-						}
-					} else {
-						throw "e1";
-					}
-				} catch (e) {
-					if (e=="e1") { $.jgrid.info_dialog($.jgrid.errors.errcap,"function 'custom_element' "+$.jgrid.edit.msg.nodefined, $.jgrid.edit.bClose);}
-					if (e=="e2") { $.jgrid.info_dialog($.jgrid.errors.errcap,"function 'custom_element' "+$.jgrid.edit.msg.novalue,$.jgrid.edit.bClose);}
-					else { $.jgrid.info_dialog($.jgrid.errors.errcap,typeof(e)==="string"?e:e.message,$.jgrid.edit.bClose); }
-				}
-			break;
-		}
-		return elem;
-	},
-// Date Validation Javascript
-	checkDate : function (format, date) {
-		var daysInFebruary = function(year){
-		// February has 29 days in any year evenly divisible by four,
-		// EXCEPT for centurial years which are not also divisible by 400.
-			return (((year % 4 === 0) && ( year % 100 !== 0 || (year % 400 === 0))) ? 29 : 28 );
-		},
-		DaysArray = function(n) {
-			for (var i = 1; i <= n; i++) {
-				this[i] = 31;
-				if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
-				if (i==2) {this[i] = 29;}
-			}
-			return this;
-		};
-
-		var tsp = {}, sep;
-		format = format.toLowerCase();
-		//we search for /,-,. for the date separator
-		if(format.indexOf("/") != -1) {
-			sep = "/";
-		} else if(format.indexOf("-") != -1) {
-			sep = "-";
-		} else if(format.indexOf(".") != -1) {
-			sep = ".";
-		} else {
-			sep = "/";
-		}
-		format = format.split(sep);
-		date = date.split(sep);
-		if (date.length != 3) { return false; }
-		var j=-1,yln, dln=-1, mln=-1;
-		for(var i=0;i<format.length;i++){
-			var dv =  isNaN(date[i]) ? 0 : parseInt(date[i],10);
-			tsp[format[i]] = dv;
-			yln = format[i];
-			if(yln.indexOf("y") != -1) { j=i; }
-			if(yln.indexOf("m") != -1) { mln=i; }
-			if(yln.indexOf("d") != -1) { dln=i; }
-		}
-		if (format[j] == "y" || format[j] == "yyyy") {
-			yln=4;
-		} else if(format[j] =="yy"){
-			yln = 2;
-		} else {
-			yln = -1;
-		}
-		var daysInMonth = DaysArray(12),
-		strDate;
-		if (j === -1) {
-			return false;
-		} else {
-			strDate = tsp[format[j]].toString();
-			if(yln == 2 && strDate.length == 1) {yln = 1;}
-			if (strDate.length != yln || (tsp[format[j]]===0 && date[j]!="00")){
-				return false;
-			}
-		}
-		if(mln === -1) {
-			return false;
-		} else {
-			strDate = tsp[format[mln]].toString();
-			if (strDate.length<1 || tsp[format[mln]]<1 || tsp[format[mln]]>12){
-				return false;
-			}
-		}
-		if(dln === -1) {
-			return false;
-		} else {
-			strDate = tsp[format[dln]].toString();
-			if (strDate.length<1 || tsp[format[dln]]<1 || tsp[format[dln]]>31 || (tsp[format[mln]]==2 && tsp[format[dln]]>daysInFebruary(tsp[format[j]])) || tsp[format[dln]] > daysInMonth[tsp[format[mln]]]){
-				return false;
-			}
-		}
-		return true;
-	},
-	isEmpty : function(val)
-	{
-		if (val.match(/^\s+$/) || val === "")	{
-			return true;
-		} else {
-			return false;
-		}
-	},
-	checkTime : function(time){
-	// checks only hh:ss (and optional am/pm)
-		var re = /^(\d{1,2}):(\d{2})([ap]m)?$/,regs;
-		if(!$.jgrid.isEmpty(time))
-		{
-			regs = time.match(re);
-			if(regs) {
-				if(regs[3]) {
-					if(regs[1] < 1 || regs[1] > 12) { return false; }
-				} else {
-					if(regs[1] > 23) { return false; }
-				}
-				if(regs[2] > 59) {
-					return false;
-				}
-			} else {
-				return false;
-			}
-		}
-		return true;
-	},
-	checkValues : function(val, valref,g, customobject, nam) {
-		var edtrul,i, nm, dft, len;
-		if(typeof(customobject) === "undefined") {
-			if(typeof(valref)=='string'){
-				for( i =0, len=g.p.colModel.length;i<len; i++){
-					if(g.p.colModel[i].name==valref) {
-						edtrul = g.p.colModel[i].editrules;
-						valref = i;
-						try { nm = g.p.colModel[i].formoptions.label; } catch (e) {}
-						break;
-					}
-				}
-			} else if(valref >=0) {
-				edtrul = g.p.colModel[valref].editrules;
-			}
-		} else {
-			edtrul = customobject;
-			nm = nam===undefined ? "_" : nam;
-		}
-		if(edtrul) {
-			if(!nm) { nm = g.p.colNames[valref]; }
-			if(edtrul.required === true) {
-				if( $.jgrid.isEmpty(val) )  { return [false,nm+": "+$.jgrid.edit.msg.required,""]; }
-			}
-			// force required
-			var rqfield = edtrul.required === false ? false : true;
-			if(edtrul.number === true) {
-				if( !(rqfield === false && $.jgrid.isEmpty(val)) ) {
-					if(isNaN(val)) { return [false,nm+": "+$.jgrid.edit.msg.number,""]; }
-				}
-			}
-			if(typeof edtrul.minValue != 'undefined' && !isNaN(edtrul.minValue)) {
-				if (parseFloat(val) < parseFloat(edtrul.minValue) ) { return [false,nm+": "+$.jgrid.edit.msg.minValue+" "+edtrul.minValue,""];}
-			}
-			if(typeof edtrul.maxValue != 'undefined' && !isNaN(edtrul.maxValue)) {
-				if (parseFloat(val) > parseFloat(edtrul.maxValue) ) { return [false,nm+": "+$.jgrid.edit.msg.maxValue+" "+edtrul.maxValue,""];}
-			}
-			var filter;
-			if(edtrul.email === true) {
-				if( !(rqfield === false && $.jgrid.isEmpty(val)) ) {
-				// taken from $ Validate plugin
-					filter = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
-					if(!filter.test(val)) {return [false,nm+": "+$.jgrid.edit.msg.email,""];}
-				}
-			}
-			if(edtrul.integer === true) {
-				if( !(rqfield === false && $.jgrid.isEmpty(val)) ) {
-					if(isNaN(val)) { return [false,nm+": "+$.jgrid.edit.msg.integer,""]; }
-					if ((val % 1 !== 0) || (val.indexOf('.') != -1)) { return [false,nm+": "+$.jgrid.edit.msg.integer,""];}
-				}
-			}
-			if(edtrul.date === true) {
-				if( !(rqfield === false && $.jgrid.isEmpty(val)) ) {
-					if(g.p.colModel[valref].formatoptions && g.p.colModel[valref].formatoptions.newformat) {
-						dft = g.p.colModel[valref].formatoptions.newformat;
-					} else {
-						dft = g.p.colModel[valref].datefmt || "Y-m-d";
-					}
-					if(!$.jgrid.checkDate (dft, val)) { return [false,nm+": "+$.jgrid.edit.msg.date+" - "+dft,""]; }
-				}
-			}
-			if(edtrul.time === true) {
-				if( !(rqfield === false && $.jgrid.isEmpty(val)) ) {
-					if(!$.jgrid.checkTime (val)) { return [false,nm+": "+$.jgrid.edit.msg.date+" - hh:mm (am/pm)",""]; }
-				}
-			}
-			if(edtrul.url === true) {
-				if( !(rqfield === false && $.jgrid.isEmpty(val)) ) {
-					filter = /^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
-					if(!filter.test(val)) {return [false,nm+": "+$.jgrid.edit.msg.url,""];}
-				}
-			}
-			if(edtrul.custom === true) {
-				if( !(rqfield === false && $.jgrid.isEmpty(val)) ) {
-					if($.isFunction(edtrul.custom_func)) {
-						var ret = edtrul.custom_func.call(g,val,nm);
-						if($.isArray(ret)) {
-							return ret;
-						} else {
-							return [false,$.jgrid.edit.msg.customarray,""];
-						}
-					} else {
-						return [false,$.jgrid.edit.msg.customfcheck,""];
-					}
-				}
-			}
-		}
-		return [true,"",""];
-	}
-});
-})(jQuery);/*
- * jqFilter  jQuery jqGrid filter addon.
- * Copyright (c) 2011, Tony Tomov, tony@trirand.com
- * Dual licensed under the MIT and GPL licenses
- * http://www.opensource.org/licenses/mit-license.php
- * http://www.gnu.org/licenses/gpl-2.0.html
- *
- * The work is inspired from this Stefan Pirvu
- * http://www.codeproject.com/KB/scripting/json-filtering.aspx
- *
- * The filter uses JSON entities to hold filter rules and groups. Here is an example of a filter:
+                    min: function () {
+                        if (v === "") {
+                            return parseFloat(rc[field] || 0);
+                        }
+                        return Math.min(parseFloat(v), parseFloat(rc[field] || 0));
+                    },
 
-{ "groupOp": "AND",
-      "groups" : [
-        { "groupOp": "OR",
-            "rules": [
-                { "field": "name", "op": "eq", "data": "England" },
-                { "field": "id", "op": "le", "data": "5"}
-             ]
-        }
-      ],
-      "rules": [
-        { "field": "name", "op": "eq", "data": "Romania" },
-        { "field": "id", "op": "le", "data": "1"}
-      ]
-}
-*/
-/*global jQuery, $, window, navigator */
+                    max: function () {
+                        if (v === "") {
+                            return parseFloat(rc[field] || 0);
+                        }
+                        return Math.max(parseFloat(v), parseFloat(rc[field] || 0));
+                    },
 
-(function ($) {
+                    count: function () {
+                        if (v === "") {
+                            v = 0;
+                        }
+                        if (rc.hasOwnProperty(field)) {
+                            return v + 1;
+                        } else {
+                            return 0;
+                        }
+                    },
 
-$.fn.jqFilter = function( arg ) {
-	if (typeof arg === 'string') {
-
-		var fn = $.fn.jqFilter[arg];
-		if (!fn) {
-			throw ("jqFilter - No such method: " + arg);
-		}
-		var args = $.makeArray(arguments).slice(1);
-		return fn.apply(this,args);
-	}
-
-	var p = $.extend(true,{
-		filter: null,
-		columns: [],
-		onChange : null,
-		afterRedraw : null,
-		checkValues : null,
-		error: false,
-		errmsg : "",
-		errorcheck : true,
-		showQuery : true,
-		sopt : null,
-		ops : [
-			{"name": "eq", "description": "equal", "operator":"="},
-			{"name": "ne", "description": "not equal", "operator":"<>"},
-			{"name": "lt", "description": "less", "operator":"<"},
-			{"name": "le", "description": "less or equal","operator":"<="},
-			{"name": "gt", "description": "greater", "operator":">"},
-			{"name": "ge", "description": "greater or equal", "operator":">="},
-			{"name": "bw", "description": "begins with", "operator":"LIKE"},
-			{"name": "bn", "description": "does not begin with", "operator":"NOT LIKE"},
-			{"name": "in", "description": "in", "operator":"IN"},
-			{"name": "ni", "description": "not in", "operator":"NOT IN"},
-			{"name": "ew", "description": "ends with", "operator":"LIKE"},
-			{"name": "en", "description": "does not end with", "operator":"NOT LIKE"},
-			{"name": "cn", "description": "contains", "operator":"LIKE"},
-			{"name": "nc", "description": "does not contain", "operator":"NOT LIKE"},
-			{"name": "nu", "description": "is null", "operator":"IS NULL"},
-			{"name": "nn", "description": "is not null", "operator":"IS NOT NULL"}
-		],
-		numopts : ['eq','ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn', 'in', 'ni'],
-		stropts : ['eq', 'ne', 'bw', 'bn', 'ew', 'en', 'cn', 'nc', 'nu', 'nn', 'in', 'ni'],
-		_gridsopt : [], // grid translated strings, do not tuch
-		groupOps : [{ op: "AND", text: "AND" },	{ op: "OR",  text: "OR" }],
-		groupButton : true,
-		ruleButtons : true,
-		direction : "ltr"
-	}, $.jgrid.filter, arg || {});
-	return this.each( function() {
-		if (this.filter) {return;}
-		this.p = p;
-		// setup filter in case if they is not defined
-		if (this.p.filter === null || this.p.filter === undefined) {
-			this.p.filter = {
-				groupOp: this.p.groupOps[0].op,
-				rules: [],
-				groups: []
-			};
-		}
-		var i, len = this.p.columns.length, cl,
-		isIE = /msie/i.test(navigator.userAgent) && !window.opera;
-
-		// translating the options
-		if(this.p._gridsopt.length) {
-			// ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
-			for(i=0;i<this.p._gridsopt.length;i++) {
-				this.p.ops[i].description = this.p._gridsopt[i];
-			}
-		}
-		this.p.initFilter = $.extend(true,{},this.p.filter);
-
-		// set default values for the columns if they are not set
-		if( !len ) {return;}
-		for(i=0; i < len; i++) {
-			cl = this.p.columns[i];
-			if( cl.stype ) {
-				// grid compatibility
-				cl.inputtype = cl.stype;
-			} else if(!cl.inputtype) {
-				cl.inputtype = 'text';
-			}
-			if( cl.sorttype ) {
-				// grid compatibility
-				cl.searchtype = cl.sorttype;
-			} else if (!cl.searchtype) {
-				cl.searchtype = 'string';
-			}
-			if(cl.hidden === undefined) {
-				// jqGrid compatibility
-				cl.hidden = false;
-			}
-			if(!cl.label) {
-				cl.label = cl.name;
-			}
-			if(cl.index) {
-				cl.name = cl.index;
-			}
-			if(!cl.hasOwnProperty('searchoptions')) {
-				cl.searchoptions = {};
-			}
-			if(!cl.hasOwnProperty('searchrules')) {
-				cl.searchrules = {};
-			}
-
-		}
-		if(this.p.showQuery) {
-			$(this).append("<table class='queryresult ui-widget ui-widget-content' style='display:block;max-width:440px;border:0px none;' dir='"+this.p.direction+"'><tbody><tr><td class='query'></td></tr></tbody></table>");
-		}
-		/*
-		 *Perform checking.
-		 *
-		*/
-		var checkData = function(val, colModelItem) {
-			var ret = [true,""];
-			if($.isFunction(colModelItem.searchrules)) {
-				ret = colModelItem.searchrules(val, colModelItem);
-			} else if($.jgrid && $.jgrid.checkValues) {
-				try {
-					ret = $.jgrid.checkValues(val, -1, null, colModelItem.searchrules, colModelItem.label);
-				} catch (e) {}
-			}
-			if(ret && ret.length && ret[0] === false) {
-				p.error = !ret[0];
-				p.errmsg = ret[1];
-			}
-		};
-		/* moving to common
-		randId = function() {
-			return Math.floor(Math.random()*10000).toString();
-		};
-		*/
-
-		this.onchange = function (  ){
-			// clear any error
-			this.p.error = false;
-			this.p.errmsg="";
-			return $.isFunction(this.p.onChange) ? this.p.onChange.call( this, this.p ) : false;
-		};
-		/*
-		 * Redraw the filter every time when new field is added/deleted
-		 * and field is  changed
-		 */
-		this.reDraw = function() {
-			$("table.group:first",this).remove();
-			var t = this.createTableForGroup(p.filter, null);
-			$(this).append(t);
-			if($.isFunction(this.p.afterRedraw) ) {
-				this.p.afterRedraw.call(this, this.p);
-			}
-		};
-		/*
-		 * Creates a grouping data for the filter
-		 * @param group - object
-		 * @param parentgroup - object
-		 */
-		this.createTableForGroup = function(group, parentgroup) {
-			var that = this,  i;
-			// this table will hold all the group (tables) and rules (rows)
-			var table = $("<table class='group ui-widget ui-widget-content' style='border:0px none;'><tbody></tbody></table>"),
-			// create error message row
-			align = "left";
-			if(this.p.direction == "rtl") {
-				align = "right";
-				table.attr("dir","rtl");
-			}
-			if(parentgroup === null) {
-				table.append("<tr class='error' style='display:none;'><th colspan='5' class='ui-state-error' align='"+align+"'></th></tr>");
-			}
-
-			var tr = $("<tr></tr>");
-			table.append(tr);
-			// this header will hold the group operator type and group action buttons for
-			// creating subgroup "+ {}", creating rule "+" or deleting the group "-"
-			var th = $("<th colspan='5' align='"+align+"'></th>");
-			tr.append(th);
-
-			if(this.p.ruleButtons === true) {
-			// dropdown for: choosing group operator type
-			var groupOpSelect = $("<select class='opsel'></select>");
-			th.append(groupOpSelect);
-			// populate dropdown with all posible group operators: or, and
-			var str= "", selected;
-			for (i = 0; i < p.groupOps.length; i++) {
-				selected =  group.groupOp === that.p.groupOps[i].op ? " selected='selected'" :"";
-				str += "<option value='"+that.p.groupOps[i].op+"'" + selected+">"+that.p.groupOps[i].text+"</option>";
-			}
-
-			groupOpSelect
-			.append(str)
-			.bind('change',function() {
-				group.groupOp = $(groupOpSelect).val();
-				that.onchange(); // signals that the filter has changed
-			});
-			}
-			// button for adding a new subgroup
-			var inputAddSubgroup ="<span></span>";
-			if(this.p.groupButton) {
-				inputAddSubgroup = $("<input type='button' value='+ {}' title='Add subgroup' class='add-group'/>");
-				inputAddSubgroup.bind('click',function() {
-					if (group.groups === undefined ) {
-						group.groups = [];
-					}
-
-					group.groups.push({
-						groupOp: p.groupOps[0].op,
-						rules: [],
-						groups: []
-					}); // adding a new group
-
-					that.reDraw(); // the html has changed, force reDraw
-
-					that.onchange(); // signals that the filter has changed
-					return false;
-				});
-			}
-			th.append(inputAddSubgroup);
-			if(this.p.ruleButtons === true) {
-			// button for adding a new rule
-			var inputAddRule = $("<input type='button' value='+' title='Add rule' class='add-rule ui-add'/>"), cm;
-			inputAddRule.bind('click',function() {
-				//if(!group) { group = {};}
-				if (group.rules === undefined) {
-					group.rules = [];
-				}
-				for (i = 0; i < that.p.columns.length; i++) {
-				// but show only serchable and serchhidden = true fields
-					var searchable = (typeof that.p.columns[i].search === 'undefined') ?  true: that.p.columns[i].search ,
-					hidden = (that.p.columns[i].hidden === true),
-					ignoreHiding = (that.p.columns[i].searchoptions.searchhidden === true);
-					if ((ignoreHiding && searchable) || (searchable && !hidden)) {
-						cm = that.p.columns[i];
-						break;
-					}
-				}
-
-				var opr;
-				if( cm.searchoptions.sopt ) {opr = cm.searchoptions.sopt;}
-				else if(that.p.sopt) { opr= that.p.sopt; }
-				else if  (cm.searchtype === 'string') {opr = that.p.stropts;}
-				else {opr = that.p.numopts;}
-
-				group.rules.push({
-					field: cm.name,
-					op: opr[0],
-					data: ""
-				}); // adding a new rule
-
-				that.reDraw(); // the html has changed, force reDraw
-				// for the moment no change have been made to the rule, so
-				// this will not trigger onchange event
-				return false;
-			});
-			th.append(inputAddRule);
-			}
-
-			// button for delete the group
-			if (parentgroup !== null) { // ignore the first group
-				var inputDeleteGroup = $("<input type='button' value='-' title='Delete group' class='delete-group'/>");
-				th.append(inputDeleteGroup);
-				inputDeleteGroup.bind('click',function() {
-				// remove group from parent
-					for (i = 0; i < parentgroup.groups.length; i++) {
-						if (parentgroup.groups[i] === group) {
-							parentgroup.groups.splice(i, 1);
-							break;
-						}
-					}
-
-					that.reDraw(); // the html has changed, force reDraw
-
-					that.onchange(); // signals that the filter has changed
-					return false;
-				});
-			}
-
-			// append subgroup rows
-			if (group.groups !== undefined) {
-				for (i = 0; i < group.groups.length; i++) {
-					var trHolderForSubgroup = $("<tr></tr>");
-					table.append(trHolderForSubgroup);
-
-					var tdFirstHolderForSubgroup = $("<td class='first'></td>");
-					trHolderForSubgroup.append(tdFirstHolderForSubgroup);
-
-					var tdMainHolderForSubgroup = $("<td colspan='4'></td>");
-					tdMainHolderForSubgroup.append(this.createTableForGroup(group.groups[i], group));
-					trHolderForSubgroup.append(tdMainHolderForSubgroup);
-				}
-			}
-			if(group.groupOp === undefined) {
-				group.groupOp = that.p.groupOps[0].op;
-			}
-
-			// append rules rows
-			if (group.rules !== undefined) {
-				for (i = 0; i < group.rules.length; i++) {
-					table.append(
-                       this.createTableRowForRule(group.rules[i], group)
-					);
-				}
-			}
-
-			return table;
-		};
-		/*
-		 * Create the rule data for the filter
-		 */
-		this.createTableRowForRule = function(rule, group ) {
-			// save current entity in a variable so that it could
-			// be referenced in anonimous method calls
-
-			var that=this, tr = $("<tr></tr>"),
-			//document.createElement("tr"),
-
-			// first column used for padding
-			//tdFirstHolderForRule = document.createElement("td"),
-			i, op, trpar, cm, str="", selected;
-			//tdFirstHolderForRule.setAttribute("class", "first");
-			tr.append("<td class='first'></td>");
-
-
-			// create field container
-			var ruleFieldTd = $("<td class='columns'></td>");
-			tr.append(ruleFieldTd);
-
-
-			// dropdown for: choosing field
-			var ruleFieldSelect = $("<select></select>"), ina, aoprs = [];
-			ruleFieldTd.append(ruleFieldSelect);
-			ruleFieldSelect.bind('change',function() {
-				rule.field = $(ruleFieldSelect).val();
-
-				trpar = $(this).parents("tr:first");
-				for (i=0;i<that.p.columns.length;i++) {
-					if(that.p.columns[i].name ===  rule.field) {
-						cm = that.p.columns[i];
-						break;
-					}
-				}
-				if(!cm) {return;}
-				cm.searchoptions.id = $.jgrid.randId();
-				if(isIE && cm.inputtype === "text") {
-					if(!cm.searchoptions.size) {
-						cm.searchoptions.size = 10;
-					}
-				}
-				var elm = $.jgrid.createEl(cm.inputtype,cm.searchoptions, "", true, that.p.ajaxSelectOptions, true);
-				$(elm).addClass("input-elm");
-				//that.createElement(rule, "");
-
-				if( cm.searchoptions.sopt ) {op = cm.searchoptions.sopt;}
-				else if(that.p.sopt) { op= that.p.sopt; }
-				else if  (cm.searchtype === 'string') {op = that.p.stropts;}
-				else {op = that.p.numopts;}
-				// operators
-				var s ="", so = 0;
-				aoprs = [];
-				$.each(that.p.ops, function() { aoprs.push(this.name) });
-				for ( i = 0 ; i < op.length; i++) {
-					ina = $.inArray(op[i],aoprs);
-					if(ina !== -1) {
-						if(so===0) {
-							rule.op = that.p.ops[ina].name;
-						}
-						s += "<option value='"+that.p.ops[ina].name+"'>"+that.p.ops[ina].description+"</option>";
-						so++;
-					}
-				}
-				$(".selectopts",trpar).empty().append( s );
-				$(".selectopts",trpar)[0].selectedIndex = 0;
-				if( $.browser.msie && $.browser.version < 9) {
-					var sw = parseInt($("select.selectopts",trpar)[0].offsetWidth) + 1;
-					$(".selectopts",trpar).width( sw );
-					$(".selectopts",trpar).css("width","auto");
-				}
-				// data
-				$(".data",trpar).empty().append( elm );
-				$(".input-elm",trpar).bind('change',function( e ) {
-					var tmo = $(this).hasClass("ui-autocomplete-input") ? 200 :0;
-					setTimeout(function(){
-						var elem = e.target;
-						rule.data = elem.nodeName.toUpperCase() === "SPAN" && cm.searchoptions && $.isFunction(cm.searchoptions.custom_value) ?
-							cm.searchoptions.custom_value($(elem).children(".customelement:first"), 'get') : elem.value;
-						that.onchange(); // signals that the filter has changed
-					}, tmo);
-				});
-				setTimeout(function(){ //IE, Opera, Chrome
-				rule.data = $(elm).val();
-				that.onchange();  // signals that the filter has changed
-				}, 0);
-			});
-
-			// populate drop down with user provided column definitions
-			var j=0;
-			for (i = 0; i < that.p.columns.length; i++) {
-				// but show only serchable and serchhidden = true fields
-		        var searchable = (typeof that.p.columns[i].search === 'undefined') ?  true: that.p.columns[i].search ,
-		        hidden = (that.p.columns[i].hidden === true),
-				ignoreHiding = (that.p.columns[i].searchoptions.searchhidden === true);
-				if ((ignoreHiding && searchable) || (searchable && !hidden)) {
-					selected = "";
-					if(rule.field === that.p.columns[i].name) {
-						selected = " selected='selected'";
-						j=i;
-					}
-					str += "<option value='"+that.p.columns[i].name+"'" +selected+">"+that.p.columns[i].label+"</option>";
-				}
-			}
-			ruleFieldSelect.append( str );
-
-
-			// create operator container
-			var ruleOperatorTd = $("<td class='operators'></td>");
-			tr.append(ruleOperatorTd);
-			cm = p.columns[j];
-			// create it here so it can be referentiated in the onchange event
-			//var RD = that.createElement(rule, rule.data);
-			cm.searchoptions.id = $.jgrid.randId();
-			if(isIE && cm.inputtype === "text") {
-				if(!cm.searchoptions.size) {
-					cm.searchoptions.size = 10;
-				}
-			}
-			var ruleDataInput = $.jgrid.createEl(cm.inputtype,cm.searchoptions, rule.data, true, that.p.ajaxSelectOptions, true);
-
-			// dropdown for: choosing operator
-			var ruleOperatorSelect = $("<select class='selectopts'></select>");
-			ruleOperatorTd.append(ruleOperatorSelect);
-			ruleOperatorSelect.bind('change',function() {
-				rule.op = $(ruleOperatorSelect).val();
-				trpar = $(this).parents("tr:first");
-				var rd = $(".input-elm",trpar)[0];
-				if (rule.op === "nu" || rule.op === "nn") { // disable for operator "is null" and "is not null"
-					rule.data = "";
-					rd.value = "";
-					rd.setAttribute("readonly", "true");
-					rd.setAttribute("disabled", "true");
-				} else {
-					rd.removeAttribute("readonly");
-					rd.removeAttribute("disabled");
-				}
-
-				that.onchange();  // signals that the filter has changed
-			});
-
-			// populate drop down with all available operators
-			if( cm.searchoptions.sopt ) {op = cm.searchoptions.sopt;}
-			else if(that.p.sopt) { op= that.p.sopt; }
-			else if  (cm.searchtype === 'string') {op = p.stropts;}
-			else {op = that.p.numopts;}
-			str="";
-			$.each(that.p.ops, function() { aoprs.push(this.name) });
-			for ( i = 0; i < op.length; i++) {
-				ina = $.inArray(op[i],aoprs);
-				if(ina !== -1) {
-					selected = rule.op === that.p.ops[ina].name ? " selected='selected'" : "";
-					str += "<option value='"+that.p.ops[ina].name+"'"+selected+">"+that.p.ops[ina].description+"</option>";
-				}
-			}
-			ruleOperatorSelect.append( str );
-			// create data container
-			var ruleDataTd = $("<td class='data'></td>");
-			tr.append(ruleDataTd);
-
-			// textbox for: data
-			// is created previously
-			//ruleDataInput.setAttribute("type", "text");
-			ruleDataTd.append(ruleDataInput);
-
-			$(ruleDataInput)
-			.addClass("input-elm")
-			.bind('change', function() {
-				rule.data = cm.inputtype === 'custom' ? cm.searchoptions.custom_value($(this).children(".customelement:first"),'get') : $(this).val();
-				that.onchange(); // signals that the filter has changed
-			});
-
-			// create action container
-			var ruleDeleteTd = $("<td></td>");
-			tr.append(ruleDeleteTd);
-
-			// create button for: delete rule
-			if(this.p.ruleButtons === true) {
-			var ruleDeleteInput = $("<input type='button' value='-' title='Delete rule' class='delete-rule ui-del'/>");
-			ruleDeleteTd.append(ruleDeleteInput);
-			//$(ruleDeleteInput).html("").height(20).width(30).button({icons: {  primary: "ui-icon-minus", text:false}});
-			ruleDeleteInput.bind('click',function() {
-				// remove rule from group
-				for (i = 0; i < group.rules.length; i++) {
-					if (group.rules[i] === rule) {
-						group.rules.splice(i, 1);
-						break;
-					}
-				}
-
-				that.reDraw(); // the html has changed, force reDraw
-
-				that.onchange(); // signals that the filter has changed
-				return false;
-			});
-			}
-			return tr;
-		};
-
-		this.getStringForGroup = function(group) {
-			var s = "(", index;
-			if (group.groups !== undefined) {
-				for (index = 0; index < group.groups.length; index++) {
-					if (s.length > 1) {
-						s += " " + group.groupOp + " ";
-					}
-					try {
-						s += this.getStringForGroup(group.groups[index]);
-					} catch (eg) {alert(eg);}
-				}
-			}
-
-			if (group.rules !== undefined) {
-				try{
-					for (index = 0; index < group.rules.length; index++) {
-						if (s.length > 1) {
-							s += " " + group.groupOp + " ";
-						}
-						s += this.getStringForRule(group.rules[index]);
-					}
-				} catch (e) {alert(e);}
-			}
-
-			s += ")";
-
-			if (s === "()") {
-				return ""; // ignore groups that don't have rules
-			} else {
-				return s;
-			}
-		};
-		this.getStringForRule = function(rule) {
-			var opUF = "",opC="", i, cm, ret, val,
-			numtypes = ['int', 'integer', 'float', 'number', 'currency']; // jqGrid
-			for (i = 0; i < this.p.ops.length; i++) {
-				if (this.p.ops[i].name === rule.op) {
-					opUF = this.p.ops[i].operator;
-					opC = this.p.ops[i].name;
-					break;
-				}
-			}
-			for (i=0; i<this.p.columns.length; i++) {
-				if(this.p.columns[i].name === rule.field) {
-					cm = this.p.columns[i];
-					break;
-				}
-			}
-			val = rule.data;
-			if(opC === 'bw' || opC === 'bn') { val = val+"%"; }
-			if(opC === 'ew' || opC === 'en') { val = "%"+val; }
-			if(opC === 'cn' || opC === 'nc') { val = "%"+val+"%"; }
-			if(opC === 'in' || opC === 'ni') { val = " ("+val+")"; }
-			if(p.errorcheck) { checkData(rule.data, cm); }
-			if($.inArray(cm.searchtype, numtypes) !== -1 || opC === 'nn' || opC === 'nu') { ret = rule.field + " " + opUF + " " + val; }
-			else { ret = rule.field + " " + opUF + " \"" + val + "\""; }
-			return ret;
-		};
-		this.resetFilter = function () {
-			this.p.filter = $.extend(true,{},this.p.initFilter);
-			this.reDraw();
-			this.onchange();
-		};
-		this.hideError = function() {
-			$("th.ui-state-error", this).html("");
-			$("tr.error", this).hide();
-		};
-		this.showError = function() {
-			$("th.ui-state-error", this).html(this.p.errmsg);
-			$("tr.error", this).show();
-		};
-		this.toUserFriendlyString = function() {
-			return this.getStringForGroup(p.filter);
-		};
-		this.toString = function() {
-			// this will obtain a string that can be used to match an item.
-			var that = this;
-			function getStringRule(rule) {
-				if(that.p.errorcheck) {
-					var i, cm;
-					for (i=0; i<that.p.columns.length; i++) {
-						if(that.p.columns[i].name === rule.field) {
-							cm = that.p.columns[i];
-							break;
-						}
-					}
-					if(cm) {checkData(rule.data, cm);}
-				}
-				return rule.op + "(item." + rule.field + ",'" + rule.data + "')";
-			}
-
-			function getStringForGroup(group) {
-				var s = "(", index;
-
-				if (group.groups !== undefined) {
-					for (index = 0; index < group.groups.length; index++) {
-						if (s.length > 1) {
-							if (group.groupOp === "OR") {
-								s += " || ";
-							}
-							else {
-								s += " && ";
-							}
-						}
-						s += getStringForGroup(group.groups[index]);
-					}
-				}
-
-				if (group.rules !== undefined) {
-					for (index = 0; index < group.rules.length; index++) {
-						if (s.length > 1) {
-							if (group.groupOp === "OR") {
-								s += " || ";
-							}
-							else  {
-								s += " && ";
-							}
-						}
-						s += getStringRule(group.rules[index]);
-					}
-				}
-
-				s += ")";
-
-				if (s === "()") {
-					return ""; // ignore groups that don't have rules
-				} else {
-					return s;
-				}
-			}
-
-			return getStringForGroup(this.p.filter);
-		};
-
-		// Here we init the filter
-		this.reDraw();
-
-		if(this.p.showQuery) {
-			this.onchange();
-		}
-		// mark is as created so that it will not be created twice on this element
-		this.filter = true;
-	});
-};
-$.extend($.fn.jqFilter,{
-	/*
-	 * Return SQL like string. Can be used directly
-	 */
-	toSQLString : function()
-	{
-		var s ="";
-		this.each(function(){
-			s = this.toUserFriendlyString();
-		});
-		return s;
-	},
-	/*
-	 * Return filter data as object.
-	 */
-	filterData : function()
-	{
-		var s;
-		this.each(function(){
-			s = this.p.filter;
-		});
-		return s;
-
-	},
-	getParameter : function (param) {
-		if(param !== undefined) {
-			if (this.p.hasOwnProperty(param) ) {
-				return this.p[param];
-			}
-		}
-		return this.p;
-	},
-	resetFilter: function() {
-		return this.each(function(){
-			this.resetFilter();
-		});
-	},
-	addFilter: function (pfilter) {
-		if (typeof pfilter === "string") {
-			pfilter = jQuery.jgrid.parse( pfilter );
-	}
-		this.each(function(){
-			this.p.filter = pfilter;
-			this.reDraw();
-			this.onchange();
-		});
-	}
-
-});
-})(jQuery);
+                    avg: function () {
+                        // the same as sum, but at end we divide it
+                        // so use sum instead of duplicating the code (?)
+                        return funcs.sum();
+                    }
+                }
 
-(function($){
-/**
- * jqGrid extension for form editing Grid Data
- * Tony Tomov tony@trirand.com
- * http://trirand.com/blog/
- * Dual licensed under the MIT and GPL licenses:
- * http://www.opensource.org/licenses/mit-license.php
- * http://www.gnu.org/licenses/gpl-2.0.html
-**/
-"use strict";
-/*global xmlJsonClass, jQuery, $  */
-var rp_ge = {};
-$.jgrid.extend({
-	searchGrid : function (p) {
-		p = $.extend({
-			recreateFilter: false,
-			drag: true,
-			sField:'searchField',
-			sValue:'searchString',
-			sOper: 'searchOper',
-			sFilter: 'filters',
-			loadDefaults: true, // this options activates loading of default filters from grid's postData for Multipe Search only.
-			beforeShowSearch: null,
-			afterShowSearch : null,
-			onInitializeSearch: null,
-			afterRedraw : null,
-			afterChange: null,
-			closeAfterSearch : false,
-			closeAfterReset: false,
-			closeOnEscape : false,
-			searchOnEnter : false,
-			multipleSearch : false,
-			multipleGroup : false,
-			//cloneSearchRowOnAdd: true,
-			top : 0,
-			left: 0,
-			jqModal : true,
-			modal: false,
-			resize : true,
-			width: 450,
-			height: 'auto',
-			dataheight: 'auto',
-			showQuery: false,
-			errorcheck : true,
-			// translation
-			// if you want to change or remove the order change it in sopt
-			// ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc'],
-			sopt: null,
-			stringResult: undefined,
-			onClose : null,
-			onSearch : null,
-			onReset : null,
-			toTop : true,
-			overlay : 30,
-			columns : [],
-			tmplNames : null,
-			tmplFilters : null,
-			// translations - later in lang file
-			tmplLabel : ' Template: ',
-			showOnLoad: false,
-			layer: null,
-			ops: null
-		}, $.jgrid.search, p || {});
-		return this.each(function() {
-			var $t = this;
-			if(!$t.grid) {return;}
-			var fid = "fbox_"+$t.p.id,
-			showFrm = true,
-			IDs = {themodal:'searchmod'+fid,modalhead:'searchhd'+fid,modalcontent:'searchcnt'+fid, scrollelm : fid},
-			defaultFilters  = $t.p.postData[p.sFilter];
-			if(typeof(defaultFilters) === "string") {
-				defaultFilters = $.jgrid.parse( defaultFilters );
-			}
-			if(p.recreateFilter === true) {
-				$("#"+$.jgrid.jqID(IDs.themodal)).remove();
-			}
-			function showFilter(_filter) {
-				showFrm = $($t).triggerHandler("jqGridFilterBeforeShow", [_filter]);
-				if(typeof(showFrm) === "undefined") {
-					showFrm = true;
-				}
-				if(showFrm && $.isFunction(p.beforeShowSearch)) {
-					showFrm = p.beforeShowSearch.call($t,_filter);
-				}
-				if(showFrm) {
-					$.jgrid.viewModal("#"+$.jgrid.jqID(IDs.themodal),{gbox:"#gbox_"+$.jgrid.jqID(fid),jqm:p.jqModal, modal:p.modal, overlay: p.overlay, toTop: p.toTop});
-					$($t).triggerHandler("jqGridFilterAfterShow", [_filter]);
-					if($.isFunction(p.afterShowSearch)) {
-						p.afterShowSearch.call($t, _filter);
-					}
-				}
-			}
-			if ( $("#"+$.jgrid.jqID(IDs.themodal)).html() !== null ) {
-				showFilter($("#fbox_"+$.jgrid.jqID(+$t.p.id)));
-			} else {
-				var fil = $("<div><div id='"+fid+"' class='searchFilter' style='overflow:auto'></div></div>").insertBefore("#gview_"+$.jgrid.jqID($t.p.id)),
-				align = "left", butleft ="";
-				if($t.p.direction == "rtl") {
-					align = "right";
-					butleft = " style='text-align:left'";
-					fil.attr("dir","rtl");
-				}
-				var columns = $.extend([],$t.p.colModel),
-				bS  ="<a href='javascript:void(0)' id='"+fid+"_search' class='fm-button ui-state-default ui-corner-all fm-button-icon-right ui-reset'><span class='ui-icon ui-icon-search'></span>"+p.Find+"</a>",
-				bC  ="<a href='javascript:void(0)' id='"+fid+"_reset' class='fm-button ui-state-default ui-corner-all fm-button-icon-left ui-search'><span class='ui-icon ui-icon-arrowreturnthick-1-w'></span>"+p.Reset+"</a>",
-				bQ = "", tmpl="", colnm, found = false, bt, cmi=-1;
-				if(p.showQuery) {
-					bQ ="<a href='javascript:void(0)' id='"+fid+"_query' class='fm-button ui-state-default ui-corner-all fm-button-icon-left'><span class='ui-icon ui-icon-comment'></span>Query</a>";
-				}
-				if(!p.columns.length) {
-					$.each(columns, function(i,n){
-						if(!n.label) {
-							n.label = $t.p.colNames[i];
-						}
-						// find first searchable column and set it if no default filter
-						if(!found) {
-							var searchable = (typeof n.search === 'undefined') ?  true: n.search ,
-							hidden = (n.hidden === true),
-							ignoreHiding = (n.searchoptions && n.searchoptions.searchhidden === true);
-							if ((ignoreHiding && searchable) || (searchable && !hidden)) {
-								found = true;
-								colnm = n.index || n.name;
-								cmi =i;
-							}
-						}
-					});
-				} else {
-					columns = p.columns;
-				}
-				// old behaviour
-				if( (!defaultFilters && colnm) || p.multipleSearch === false  ) {
-					var cmop = "eq";
-					if(cmi >=0 && columns[cmi].searchoptions && columns[cmi].searchoptions.sopt) {
-						cmop = columns[cmi].searchoptions.sopt[0];
-					} else if(p.sopt && p.sopt.length) {
-						cmop = p.sopt[0];
-					}
-					defaultFilters = {"groupOp": "AND",rules:[{"field":colnm,"op":cmop,"data":""}]};
-				}
-				found = false;
-				if(p.tmplNames && p.tmplNames.length) {
-					found = true;
-					tmpl = p.tmplLabel;
-					tmpl += "<select class='ui-template'>";
-					tmpl += "<option value='default'>Default</option>";
-					$.each(p.tmplNames, function(i,n){
-						tmpl += "<option value='"+i+"'>"+n+"</option>";
-					});
-					tmpl += "</select>";
-				}
-
-				bt = "<table class='EditTable' style='border:0px none;margin-top:5px' id='"+fid+"_2'><tbody><tr><td colspan='2'><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr><td class='EditButton' style='text-align:"+align+"'>"+bC+tmpl+"</td><td class='EditButton' "+butleft+">"+bQ+bS+"</td></tr></tbody></table>";
-				fid = $.jgrid.jqID( fid);
-				$("#"+fid).jqFilter({
-					columns : columns,
-					filter: p.loadDefaults ? defaultFilters : null,
-					showQuery: p.showQuery,
-					errorcheck : p.errorcheck,
-					sopt: p.sopt,
-					groupButton : p.multipleGroup,
-					ruleButtons : p.multipleSearch,
-					afterRedraw : p.afterRedraw,
-					_gridsopt : $.jgrid.search.odata,
-					ajaxSelectOptions: $t.p.ajaxSelectOptions,
-					groupOps: p.groupOps,
-					onChange : function() {
-						if(this.p.showQuery) {
-							$('.query',this).html(this.toUserFriendlyString());
-						}
-						if ($.isFunction(p.afterChange)) {
-							p.afterChange.call($t, $("#"+fid), p);
-						}
-					},
-					direction : $t.p.direction,
-					ops: p.ops
-				});
-				fil.append( bt );
-				if(found && p.tmplFilters && p.tmplFilters.length) {
-					$(".ui-template", fil).bind('change', function(){
-						var curtempl = $(this).val();
-						if(curtempl=="default") {
-							$("#"+fid).jqFilter('addFilter', defaultFilters);
-						} else {
-							$("#"+fid).jqFilter('addFilter', p.tmplFilters[parseInt(curtempl,10)]);
-						}
-						return false;
-					});
-				}
-				if(p.multipleGroup === true) {p.multipleSearch = true;}
-				$($t).triggerHandler("jqGridFilterInitialize", [$("#"+fid)]);
-				if($.isFunction(p.onInitializeSearch) ) {
-					p.onInitializeSearch.call($t, $("#"+fid));
-				}
-				p.gbox = "#gbox_"+fid;
-				if (p.layer) {
-					$.jgrid.createModal(IDs ,fil,p,"#gview_"+$.jgrid.jqID($t.p.id),$("#gbox_"+$.jgrid.jqID($t.p.id))[0], "#"+$.jgrid.jqID(p.layer), {position: "relative"});
-				} else {
-					$.jgrid.createModal(IDs ,fil,p,"#gview_"+$.jgrid.jqID($t.p.id),$("#gbox_"+$.jgrid.jqID($t.p.id))[0]);
-				}
-				if (p.searchOnEnter || p.closeOnEscape) {
-					$("#"+$.jgrid.jqID(IDs.themodal)).keydown(function (e) {
-						var $target = $(e.target);
-						if (p.searchOnEnter && e.which === 13 && // 13 === $.ui.keyCode.ENTER
-								!$target.hasClass('add-group') && !$target.hasClass('add-rule') &&
-								!$target.hasClass('delete-group') && !$target.hasClass('delete-rule') &&
-								(!$target.hasClass("fm-button") || !$target.is("[id$=_query]"))) {
-							$("#"+fid+"_search").focus().click();
-							return false;
-						}
-						if (p.closeOnEscape && e.which === 27) { // 27 === $.ui.keyCode.ESCAPE
-							$("#"+$.jgrid.jqID(IDs.modalhead)).find(".ui-jqdialog-titlebar-close").focus().click();
-							return false;
-						}
-					});
-				}
-				if(bQ) {
-					$("#"+fid+"_query").bind('click', function(){
-						$(".queryresult", fil).toggle();
-						return false;
-					});
-				}
-				if (p.stringResult===undefined) {
-					// to provide backward compatibility, inferring stringResult value from multipleSearch
-					p.stringResult = p.multipleSearch;
-				}
-				$("#"+fid+"_search").bind('click', function(){
-					var fl = $("#"+fid),
-					sdata={}, res ,
-					filters = fl.jqFilter('filterData');
-					if(p.errorcheck) {
-						fl[0].hideError();
-						if(!p.showQuery) {fl.jqFilter('toSQLString');}
-						if(fl[0].p.error) {
-							fl[0].showError();
-							return false;
-						}
-					}
-
-					if(p.stringResult) {
-						try {
-							// xmlJsonClass or JSON.stringify
-							res = xmlJsonClass.toJson(filters, '', '', false);
-						} catch (e) {
-							try {
-								res = JSON.stringify(filters);
-							} catch (e2) { }
-						}
-						if(typeof(res)==="string") {
-							sdata[p.sFilter] = res;
-							$.each([p.sField,p.sValue, p.sOper], function() {sdata[this] = "";});
-						}
-					} else {
-						if(p.multipleSearch) {
-							sdata[p.sFilter] = filters;
-							$.each([p.sField,p.sValue, p.sOper], function() {sdata[this] = "";});
-						} else {
-							sdata[p.sField] = filters.rules[0].field;
-							sdata[p.sValue] = filters.rules[0].data;
-							sdata[p.sOper] = filters.rules[0].op;
-							sdata[p.sFilter] = "";
-						}
-					}
-					$t.p.search = true;
-					$.extend($t.p.postData,sdata);
-					$($t).triggerHandler("jqGridFilterSearch");
-					if($.isFunction(p.onSearch) ) {
-						p.onSearch.call($t);
-					}
-					$($t).trigger("reloadGrid",[{page:1}]);
-					if(p.closeAfterSearch) {
-						$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID($t.p.id),jqm:p.jqModal,onClose: p.onClose});
-					}
-					return false;
-				});
-				$("#"+fid+"_reset").bind('click', function(){
-					var sdata={},
-					fl = $("#"+fid);
-					$t.p.search = false;
-					if(p.multipleSearch===false) {
-						sdata[p.sField] = sdata[p.sValue] = sdata[p.sOper] = "";
-					} else {
-						sdata[p.sFilter] = "";
-					}
-					fl[0].resetFilter();
-					if(found) {
-						$(".ui-template", fil).val("default");
-					}
-					$.extend($t.p.postData,sdata);
-					$($t).triggerHandler("jqGridFilterReset");
-					if($.isFunction(p.onReset) ) {
-						p.onReset.call($t);
-					}
-					$($t).trigger("reloadGrid",[{page:1}]);
-					return false;
-				});
-				showFilter($("#"+fid));
-				$(".fm-button:not(.ui-state-disabled)",fil).hover(
-					function(){$(this).addClass('ui-state-hover');},
-					function(){$(this).removeClass('ui-state-hover');}
-				);
-			}
-		});
-	},
-	editGridRow : function(rowid, p){
-		p = $.extend({
-			top : 0,
-			left: 0,
-			width: 300,
-			height: 'auto',
-			dataheight: 'auto',
-			modal: false,
-			overlay : 30,
-			drag: true,
-			resize: true,
-			url: null,
-			mtype : "POST",
-			clearAfterAdd :true,
-			closeAfterEdit : false,
-			reloadAfterSubmit : true,
-			onInitializeForm: null,
-			beforeInitData: null,
-			beforeShowForm: null,
-			afterShowForm: null,
-			beforeSubmit: null,
-			afterSubmit: null,
-			onclickSubmit: null,
-			afterComplete: null,
-			onclickPgButtons : null,
-			afterclickPgButtons: null,
-			editData : {},
-			recreateForm : false,
-			jqModal : true,
-			closeOnEscape : false,
-			addedrow : "first",
-			topinfo : '',
-			bottominfo: '',
-			saveicon : [],
-			closeicon : [],
-			savekey: [false,13],
-			navkeys: [false,38,40],
-			checkOnSubmit : false,
-			checkOnUpdate : false,
-			_savedData : {},
-			processing : false,
-			onClose : null,
-			ajaxEditOptions : {},
-			serializeEditData : null,
-			viewPagerButtons : true
-		}, $.jgrid.edit, p || {});
-		rp_ge[$(this)[0].p.id] = p;
-		return this.each(function(){
-			var $t = this;
-			if (!$t.grid || !rowid) {return;}
-			var gID = $t.p.id,
-			frmgr = "FrmGrid_"+gID, frmtborg = "TblGrid_"+gID, frmtb = "#"+$.jgrid.jqID(frmtborg),
-			IDs = {themodal:'editmod'+gID,modalhead:'edithd'+gID,modalcontent:'editcnt'+gID, scrollelm : frmgr},
-			onBeforeShow = $.isFunction(rp_ge[$t.p.id].beforeShowForm) ? rp_ge[$t.p.id].beforeShowForm : false,
-			onAfterShow = $.isFunction(rp_ge[$t.p.id].afterShowForm) ? rp_ge[$t.p.id].afterShowForm : false,
-			onBeforeInit = $.isFunction(rp_ge[$t.p.id].beforeInitData) ? rp_ge[$t.p.id].beforeInitData : false,
-			onInitializeForm = $.isFunction(rp_ge[$t.p.id].onInitializeForm) ? rp_ge[$t.p.id].onInitializeForm : false,
-			showFrm = true,
-			maxCols = 1, maxRows=0,	postdata, extpost, newData, diff, frmoper;
-			frmgr = $.jgrid.jqID(frmgr);
-			if (rowid === "new") {
-				rowid = "_empty";
-				frmoper = "add";
-				p.caption=rp_ge[$t.p.id].addCaption;
-			} else {
-				p.caption=rp_ge[$t.p.id].editCaption;
-				frmoper = "edit";
-			}
-			if(p.recreateForm===true && $("#"+$.jgrid.jqID(IDs.themodal)).html() !== null) {
-				$("#"+$.jgrid.jqID(IDs.themodal)).remove();
-			}
-			var closeovrl = true;
-			if(p.checkOnUpdate && p.jqModal && !p.modal) {
-				closeovrl = false;
-			}
-			function getFormData(){
-				$(frmtb+" > tbody > tr > td > .FormElement").each(function() {
-					var celm = $(".customelement", this);
-					if (celm.length) {
-						var  elem = celm[0], nm = $(elem).attr('name');
-						$.each($t.p.colModel, function(){
-							if(this.name === nm && this.editoptions && $.isFunction(this.editoptions.custom_value)) {
-								try {
-									postdata[nm] = this.editoptions.custom_value.call($t, $("#"+$.jgrid.jqID(nm),frmtb),'get');
-									if (postdata[nm] === undefined) {throw "e1";}
-								} catch (e) {
-									if (e==="e1") {$.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.novalue,jQuery.jgrid.edit.bClose);}
-									else {$.jgrid.info_dialog(jQuery.jgrid.errors.errcap,e.message,jQuery.jgrid.edit.bClose);}
-								}
-								return true;
-							}
-						});
-					} else {
-					switch ($(this).get(0).type) {
-						case "checkbox":
-							if($(this).is(":checked")) {
-								postdata[this.name]= $(this).val();
-							}else {
-								var ofv = $(this).attr("offval");
-								postdata[this.name]= ofv;
-							}
-						break;
-						case "select-one":
-							postdata[this.name]= $("option:selected",this).val();
-							extpost[this.name]= $("option:selected",this).text();
-						break;
-						case "select-multiple":
-							postdata[this.name]= $(this).val();
-							if(postdata[this.name]) {postdata[this.name] = postdata[this.name].join(",");}
-							else {postdata[this.name] ="";}
-							var selectedText = [];
-							$("option:selected",this).each(
-								function(i,selected){
-									selectedText[i] = $(selected).text();
-								}
-							);
-							extpost[this.name]= selectedText.join(",");
-						break;
-						case "password":
-						case "text":
-						case "textarea":
-						case "button":
-							postdata[this.name] = $(this).val();
-
-						break;
-					}
-					if($t.p.autoencode) {postdata[this.name] = $.jgrid.htmlEncode(postdata[this.name]);}
-					}
-				});
-				return true;
-			}
-			function createData(rowid,obj,tb,maxcols){
-				var nm, hc,trdata, cnt=0,tmp, dc,elc, retpos=[], ind=false,
-				tdtmpl = "<td class='CaptionTD'>&#160;</td><td class='DataTD'>&#160;</td>", tmpl="", i; //*2
-				for (i =1; i<=maxcols;i++) {
-					tmpl += tdtmpl;
-				}
-				if(rowid != '_empty') {
-					ind = $(obj).jqGrid("getInd",rowid);
-				}
-				$(obj.p.colModel).each( function(i) {
-					nm = this.name;
-					// hidden fields are included in the form
-					if(this.editrules && this.editrules.edithidden === true) {
-						hc = false;
-					} else {
-						hc = this.hidden === true ? true : false;
-					}
-					dc = hc ? "style='display:none'" : "";
-					if ( nm !== 'cb' && nm !== 'subgrid' && this.editable===true && nm !== 'rn') {
-						if(ind === false) {
-							tmp = "";
-						} else {
-							if(nm == obj.p.ExpandColumn && obj.p.treeGrid === true) {
-								tmp = $("td:eq("+i+")",obj.rows[ind]).text();
-							} else {
-								try {
-									tmp =  $.unformat.call(obj, $("td:eq("+i+")",obj.rows[ind]),{rowId:rowid, colModel:this},i);
-								} catch (_) {
-									tmp =  (this.edittype && this.edittype == "textarea") ? $("td:eq("+i+")",obj.rows[ind]).text() : $("td:eq("+i+")",obj.rows[ind]).html();
-								}
-								if(!tmp || tmp == "&nbsp;" || tmp == "&#160;" || (tmp.length==1 && tmp.charCodeAt(0)==160) ) {tmp='';}
-							}
-						}
-						var opt = $.extend({}, this.editoptions || {} ,{id:nm,name:nm}),
-						frmopt = $.extend({}, {elmprefix:'',elmsuffix:'',rowabove:false,rowcontent:''}, this.formoptions || {}),
-						rp = parseInt(frmopt.rowpos,10) || cnt+1,
-						cp = parseInt((parseInt(frmopt.colpos,10) || 1)*2,10);
-						if(rowid == "_empty" && opt.defaultValue ) {
-							tmp = $.isFunction(opt.defaultValue) ? opt.defaultValue.call($t) : opt.defaultValue;
-						}
-						if(!this.edittype) {this.edittype = "text";}
-						if($t.p.autoencode) {tmp = $.jgrid.htmlDecode(tmp);}
-						elc = $.jgrid.createEl.call($t,this.edittype,opt,tmp,false,$.extend({},$.jgrid.ajaxOptions,obj.p.ajaxSelectOptions || {}));
-						if(tmp === "" && this.edittype == "checkbox") {tmp = $(elc).attr("offval");}
-						if(tmp === "" && this.edittype == "select") {tmp = $("option:eq(0)",elc).text();}
-						if(rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) {rp_ge[$t.p.id]._savedData[nm] = tmp;}
-						$(elc).addClass("FormElement");
-						if(this.edittype == 'text' || this.edittype == 'textarea') {
-							$(elc).addClass("ui-widget-content ui-corner-all");
-						}
-						trdata = $(tb).find("tr[rowpos="+rp+"]");
-						if(frmopt.rowabove) {
-							var newdata = $("<tr><td class='contentinfo' colspan='"+(maxcols*2)+"'>"+frmopt.rowcontent+"</td></tr>");
-							$(tb).append(newdata);
-							newdata[0].rp = rp;
-						}
-						if ( trdata.length===0 ) {
-							trdata = $("<tr "+dc+" rowpos='"+rp+"'></tr>").addClass("FormData").attr("id","tr_"+nm);
-							$(trdata).append(tmpl);
-							$(tb).append(trdata);
-							trdata[0].rp = rp;
-						}
-						$("td:eq("+(cp-2)+")",trdata[0]).html( typeof frmopt.label === 'undefined' ? obj.p.colNames[i]: frmopt.label);
-						$("td:eq("+(cp-1)+")",trdata[0]).append(frmopt.elmprefix).append(elc).append(frmopt.elmsuffix);
-						retpos[cnt] = i;
-						cnt++;
-					}
-				});
-				if( cnt > 0) {
-					var idrow = $("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='"+ (maxcols*2-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='"+obj.p.id+"_id' value='"+rowid+"'/></td></tr>");
-					idrow[0].rp = cnt+999;
-					$(tb).append(idrow);
-					if(rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) {rp_ge[$t.p.id]._savedData[obj.p.id+"_id"] = rowid;}
-				}
-				return retpos;
-			}
-			function fillData(rowid,obj,fmid){
-				var nm,cnt=0,tmp, fld,opt,vl,vlc;
-				if(rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) {rp_ge[$t.p.id]._savedData = {};rp_ge[$t.p.id]._savedData[obj.p.id+"_id"]=rowid;}
-				var cm = obj.p.colModel;
-				if(rowid == '_empty') {
-					$(cm).each(function(){
-						nm = this.name;
-						opt = $.extend({}, this.editoptions || {} );
-						fld = $("#"+$.jgrid.jqID(nm),"#"+fmid);
-						if(fld && fld.length && fld[0] !== null) {
-							vl = "";
-							if(opt.defaultValue ) {
-								vl = $.isFunction(opt.defaultValue) ? opt.defaultValue.call($t) : opt.defaultValue;
-								if(fld[0].type=='checkbox') {
-									vlc = vl.toLowerCase();
-									if(vlc.search(/(false|0|no|off|undefined)/i)<0 && vlc!=="") {
-										fld[0].checked = true;
-										fld[0].defaultChecked = true;
-										fld[0].value = vl;
-									} else {
-										fld[0].checked = false;
-										fld[0].defaultChecked = false;
-									}
-								} else {fld.val(vl);}
-							} else {
-								if( fld[0].type=='checkbox' ) {
-									fld[0].checked = false;
-									fld[0].defaultChecked = false;
-									vl = $(fld).attr("offval");
-								} else if (fld[0].type && fld[0].type.substr(0,6)=='select') {
-									fld[0].selectedIndex = 0;
-								} else {
-									fld.val(vl);
-								}
-							}
-							if(rp_ge[$t.p.id].checkOnSubmit===true || rp_ge[$t.p.id].checkOnUpdate) {rp_ge[$t.p.id]._savedData[nm] = vl;}
-						}
-					});
-					$("#id_g","#"+fmid).val(rowid);
-					return;
-				}
-				var tre = $(obj).jqGrid("getInd",rowid,true);
-				if(!tre) {return;}
-				$('td[role="gridcell"]',tre).each( function(i) {
-					nm = cm[i].name;
-					// hidden fields are included in the form
-					if ( nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn' && cm[i].editable===true) {
-						if(nm == obj.p.ExpandColumn && obj.p.treeGrid === true) {
-							tmp = $(this).text();
-						} else {
-							try {
-								tmp =  $.unformat.call(obj, $(this),{rowId:rowid, colModel:cm[i]},i);
-							} catch (_) {
-								tmp = cm[i].edittype=="textarea" ? $(this).text() : $(this).html();
-							}
-						}
-						if($t.p.autoencode) {tmp = $.jgrid.htmlDecode(tmp);}
-						if(rp_ge[$t.p.id].checkOnSubmit===true || rp_ge[$t.p.id].checkOnUpdate) {rp_ge[$t.p.id]._savedData[nm] = tmp;}
-						nm = $.jgrid.jqID(nm);
-						switch (cm[i].edittype) {
-							case "password":
-							case "text":
-							case "button" :
-							case "image":
-							case "textarea":
-								if(tmp == "&nbsp;" || tmp == "&#160;" || (tmp.length==1 && tmp.charCodeAt(0)==160) ) {tmp='';}
-								$("#"+nm,"#"+fmid).val(tmp);
-								break;
-							case "select":
-								var opv = tmp.split(",");
-								opv = $.map(opv,function(n){return $.trim(n);});
-								$("#"+nm+" option","#"+fmid).each(function(){
-									if (!cm[i].editoptions.multiple && ($.trim(tmp) == $.trim($(this).text()) || opv[0] == $.trim($(this).text()) || opv[0] == $.trim($(this).val())) ){
-										this.selected= true;
-									} else if (cm[i].editoptions.multiple){
-										if(  $.inArray($.trim($(this).text()), opv ) > -1 || $.inArray($.trim($(this).val()), opv ) > -1  ){
-											this.selected = true;
-										}else{
-											this.selected = false;
-										}
-									} else {
-										this.selected = false;
-									}
-								});
-								break;
-							case "checkbox":
-								tmp = tmp+"";
-								if(cm[i].editoptions && cm[i].editoptions.value) {
-									var cb = cm[i].editoptions.value.split(":");
-									if(cb[0] == tmp) {
-										$("#"+nm,"#"+fmid)[$t.p.useProp ? 'prop': 'attr']("checked",true);
-										$("#"+nm,"#"+fmid)[$t.p.useProp ? 'prop': 'attr']("defaultChecked",true); //ie
-									} else {
-										$("#"+nm,"#"+fmid)[$t.p.useProp ? 'prop': 'attr']("checked", false);
-										$("#"+nm,"#"+fmid)[$t.p.useProp ? 'prop': 'attr']("defaultChecked", false); //ie
-									}
-								} else {
-									tmp = tmp.toLowerCase();
-									if(tmp.search(/(false|0|no|off|undefined)/i)<0 && tmp!=="") {
-										$("#"+nm,"#"+fmid)[$t.p.useProp ? 'prop': 'attr']("checked",true);
-										$("#"+nm,"#"+fmid)[$t.p.useProp ? 'prop': 'attr']("defaultChecked",true); //ie
-									} else {
-										$("#"+nm,"#"+fmid)[$t.p.useProp ? 'prop': 'attr']("checked", false);
-										$("#"+nm,"#"+fmid)[$t.p.useProp ? 'prop': 'attr']("defaultChecked", false); //ie
-									}
-								}
-								break;
-							case 'custom' :
-								try {
-									if(cm[i].editoptions && $.isFunction(cm[i].editoptions.custom_value)) {
-										cm[i].editoptions.custom_value.call($t, $("#"+nm,"#"+fmid),'set',tmp);
-									} else {throw "e1";}
-								} catch (e) {
-									if (e=="e1") {$.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.nodefined,jQuery.jgrid.edit.bClose);}
-									else {$.jgrid.info_dialog(jQuery.jgrid.errors.errcap,e.message,jQuery.jgrid.edit.bClose);}
-								}
-								break;
-						}
-						cnt++;
-					}
-				});
-				if(cnt>0) {$("#id_g",frmtb).val(rowid);}
-			}
-			function setNulls() {
-				$.each($t.p.colModel, function(i,n){
-					if(n.editoptions && n.editoptions.NullIfEmpty === true) {
-						if(postdata.hasOwnProperty(n.name) && postdata[n.name] === "") {
-							postdata[n.name] = 'null';
-						}
-					}
-				});
-			}
-			function postIt() {
-				var copydata, ret=[true,"",""], onCS = {}, opers = $t.p.prmNames, idname, oper, key, selr, i;
-
-				var retvals = $($t).triggerHandler("jqGridAddEditBeforeCheckValues", [$("#"+frmgr), frmoper]);
-				if(retvals && typeof(retvals) === 'object') {postdata = retvals;}
-
-				if($.isFunction(rp_ge[$t.p.id].beforeCheckValues)) {
-					retvals = rp_ge[$t.p.id].beforeCheckValues.call($t, postdata,$("#"+frmgr),postdata[$t.p.id+"_id"] == "_empty" ? opers.addoper : opers.editoper);
-					if(retvals && typeof(retvals) === 'object') {postdata = retvals;}
-				}
-				for( key in postdata ){
-					if(postdata.hasOwnProperty(key)) {
-						ret = $.jgrid.checkValues.call($t,postdata[key],key,$t);
-						if(ret[0] === false) {break;}
-					}
-				}
-				setNulls();
-				if(ret[0]) {
-					onCS = $($t).triggerHandler("jqGridAddEditClickSubmit", [rp_ge[$t.p.id], postdata, frmoper]);
-					if( onCS === undefined && $.isFunction( rp_ge[$t.p.id].onclickSubmit)) {
-						onCS = rp_ge[$t.p.id].onclickSubmit.call($t, rp_ge[$t.p.id], postdata) || {};
-					}
-					ret = $($t).triggerHandler("jqGridAddEditBeforeSubmit", [postdata, $("#"+frmgr), frmoper]);
-					if(ret === undefined) {
-						ret = [true,"",""];
-					}
-					if( ret[0] && $.isFunction(rp_ge[$t.p.id].beforeSubmit))  {
-						ret = rp_ge[$t.p.id].beforeSubmit.call($t,postdata,$("#"+frmgr));
-					}
-				}
-
-				if(ret[0] && !rp_ge[$t.p.id].processing) {
-					rp_ge[$t.p.id].processing = true;
-					$("#sData", frmtb+"_2").addClass('ui-state-active');
-					oper = opers.oper;
-					idname = opers.id;
-					// we add to pos data array the action - the name is oper
-					postdata[oper] = ($.trim(postdata[$t.p.id+"_id"]) == "_empty") ? opers.addoper : opers.editoper;
-					if(postdata[oper] != opers.addoper) {
-						postdata[idname] = postdata[$t.p.id+"_id"];
-					} else {
-						// check to see if we have allredy this field in the form and if yes lieve it
-						if( postdata[idname] === undefined ) {postdata[idname] = postdata[$t.p.id+"_id"];}
-					}
-					delete postdata[$t.p.id+"_id"];
-					postdata = $.extend(postdata,rp_ge[$t.p.id].editData,onCS);
-					if($t.p.treeGrid === true)  {
-						if(postdata[oper] == opers.addoper) {
-						selr = $($t).jqGrid("getGridParam", 'selrow');
-							var tr_par_id = $t.p.treeGridModel == 'adjacency' ? $t.p.treeReader.parent_id_field : 'parent_id';
-							postdata[tr_par_id] = selr;
-						}
-						for(i in $t.p.treeReader){
-							if($t.p.treeReader.hasOwnProperty(i)) {
-								var itm = $t.p.treeReader[i];
-								if(postdata.hasOwnProperty(itm)) {
-									if(postdata[oper] == opers.addoper && i === 'parent_id_field') {continue;}
-									delete postdata[itm];
-								}
-							}
-						}
-					}
-
-					postdata[idname] = $.jgrid.stripPref($t.p.idPrefix, postdata[idname]);
-					var ajaxOptions = $.extend({
-						url: rp_ge[$t.p.id].url ? rp_ge[$t.p.id].url : $($t).jqGrid('getGridParam','editurl'),
-						type: rp_ge[$t.p.id].mtype,
-						data: $.isFunction(rp_ge[$t.p.id].serializeEditData) ? rp_ge[$t.p.id].serializeEditData.call($t,postdata) :  postdata,
-						complete:function(data,Status){
-							postdata[idname] = $t.p.idPrefix + postdata[idname];
-							if(Status != "success") {
-								ret[0] = false;
-								ret[1] = $($t).triggerHandler("jqGridAddEditErrorTextFormat", [data, frmoper]);
-								if ($.isFunction(rp_ge[$t.p.id].errorTextFormat)) {
-									ret[1] = rp_ge[$t.p.id].errorTextFormat.call($t, data);
-								} else {
-									ret[1] = Status + " Status: '" + data.statusText + "'. Error code: " + data.status;
-								}
-							} else {
-								// data is posted successful
-								// execute aftersubmit with the returned data from server
-								ret = $($t).triggerHandler("jqGridAddEditAfterSubmit", [data, postdata, frmoper]);
-								if(ret === undefined) {
-									ret = [true,"",""];
-								}
-								if( ret[0] && $.isFunction(rp_ge[$t.p.id].afterSubmit) ) {
-									ret = rp_ge[$t.p.id].afterSubmit.call($t, data,postdata);
-								}
-							}
-							if(ret[0] === false) {
-								$("#FormError>td",frmtb).html(ret[1]);
-								$("#FormError",frmtb).show();
-							} else {
-								// remove some values if formattaer select or checkbox
-								$.each($t.p.colModel, function(){
-									if(extpost[this.name] && this.formatter && this.formatter=='select') {
-										try {delete extpost[this.name];} catch (e) {}
-									}
-								});
-								postdata = $.extend(postdata,extpost);
-								if($t.p.autoencode) {
-									$.each(postdata,function(n,v){
-										postdata[n] = $.jgrid.htmlDecode(v);
-									});
-								}
-								//rp_ge[$t.p.id].reloadAfterSubmit = rp_ge[$t.p.id].reloadAfterSubmit && $t.p.datatype != "local";
-								// the action is add
-								if(postdata[oper] == opers.addoper ) {
-									//id processing
-									// user not set the id ret[2]
-									if(!ret[2]) {ret[2] = $.jgrid.randId();}
-									postdata[idname] = ret[2];
-									if(rp_ge[$t.p.id].closeAfterAdd) {
-										if(rp_ge[$t.p.id].reloadAfterSubmit) {$($t).trigger("reloadGrid");}
-										else {
-											if($t.p.treeGrid === true){
-												$($t).jqGrid("addChildNode",ret[2],selr,postdata );
-											} else {
-											$($t).jqGrid("addRowData",ret[2],postdata,p.addedrow);
-											$($t).jqGrid("setSelection",ret[2]);
-										}
-										}
-										$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal,onClose: rp_ge[$t.p.id].onClose});
-									} else if (rp_ge[$t.p.id].clearAfterAdd) {
-										if(rp_ge[$t.p.id].reloadAfterSubmit) {$($t).trigger("reloadGrid");}
-										else {
-											if($t.p.treeGrid === true){
-												$($t).jqGrid("addChildNode",ret[2],selr,postdata );
-											} else {
-												$($t).jqGrid("addRowData",ret[2],postdata,p.addedrow);
-											}
-										}
-										fillData("_empty",$t,frmgr);
-									} else {
-										if(rp_ge[$t.p.id].reloadAfterSubmit) {$($t).trigger("reloadGrid");}
-										else {
-											if($t.p.treeGrid === true){
-												$($t).jqGrid("addChildNode",ret[2],selr,postdata );
-											} else {
-												$($t).jqGrid("addRowData",ret[2],postdata,p.addedrow);
-									}
-										}
-									}
-								} else {
-									// the action is update
-									if(rp_ge[$t.p.id].reloadAfterSubmit) {
-										$($t).trigger("reloadGrid");
-										if( !rp_ge[$t.p.id].closeAfterEdit ) {setTimeout(function(){$($t).jqGrid("setSelection",postdata[idname]);},1000);}
-									} else {
-										if($t.p.treeGrid === true) {
-											$($t).jqGrid("setTreeRow", postdata[idname],postdata);
-										} else {
-											$($t).jqGrid("setRowData", postdata[idname],postdata);
-										}
-									}
-									if(rp_ge[$t.p.id].closeAfterEdit) {$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal,onClose: rp_ge[$t.p.id].onClose});}
-								}
-								if($.isFunction(rp_ge[$t.p.id].afterComplete)) {
-									copydata = data;
-									setTimeout(function(){
-										$($t).triggerHandler("jqGridAddEditAfterComplete", [copydata, postdata, $("#"+frmgr), frmoper]);
-										rp_ge[$t.p.id].afterComplete.call($t, copydata, postdata, $("#"+frmgr));
-										copydata=null;
-									},500);
-								}
-							if(rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) {
-								$("#"+frmgr).data("disabled",false);
-								if(rp_ge[$t.p.id]._savedData[$t.p.id+"_id"] !="_empty"){
-									for(var key in rp_ge[$t.p.id]._savedData) {
-										if(postdata[key]) {
-											rp_ge[$t.p.id]._savedData[key] = postdata[key];
-										}
-									}
-								}
-							}
-							}
-							rp_ge[$t.p.id].processing=false;
-							$("#sData", frmtb+"_2").removeClass('ui-state-active');
-							try{$(':input:visible',"#"+frmgr)[0].focus();} catch (e){}
-						}
-					}, $.jgrid.ajaxOptions, rp_ge[$t.p.id].ajaxEditOptions );
-
-					if (!ajaxOptions.url && !rp_ge[$t.p.id].useDataProxy) {
-						if ($.isFunction($t.p.dataProxy)) {
-							rp_ge[$t.p.id].useDataProxy = true;
-						} else {
-							ret[0]=false;ret[1] += " "+$.jgrid.errors.nourl;
-						}
-					}
-					if (ret[0]) {
-						if (rp_ge[$t.p.id].useDataProxy) {
-							var dpret = $t.p.dataProxy.call($t, ajaxOptions, "set_"+$t.p.id);
-							if(typeof(dpret) == "undefined") {
-								dpret = [true, ""];
-							}
-							if(dpret[0] === false ) {
-								ret[0] = false;
-								ret[1] = dpret[1] || "Error deleting the selected row!" ;
-							} else {
-								if(ajaxOptions.data.oper == opers.addoper && rp_ge[$t.p.id].closeAfterAdd ) {
-									$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose});
-								}
-								if(ajaxOptions.data.oper == opers.editoper && rp_ge[$t.p.id].closeAfterEdit ) {
-									$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose});
-								}
-							}
-						} else {
-							$.ajax(ajaxOptions);
-						}
-					}
-				}
-				if(ret[0] === false) {
-					$("#FormError>td",frmtb).html(ret[1]);
-					$("#FormError",frmtb).show();
-					// return;
-				}
-			}
-			function compareData(nObj, oObj ) {
-				var ret = false,key;
-				for (key in nObj) {
-					if(nObj[key] != oObj[key]) {
-						ret = true;
-						break;
-					}
-				}
-				return ret;
-			}
-			function checkUpdates () {
-				var stat = true;
-				$("#FormError",frmtb).hide();
-				if(rp_ge[$t.p.id].checkOnUpdate) {
-					postdata = {};extpost={};
-					getFormData();
-					newData = $.extend({},postdata,extpost);
-					diff = compareData(newData,rp_ge[$t.p.id]._savedData);
-					if(diff) {
-						$("#"+frmgr).data("disabled",true);
-						$(".confirm","#"+IDs.themodal).show();
-						stat = false;
-					}
-				}
-				return stat;
-			}
-			function restoreInline()
-			{
-				if (rowid !== "_empty" && typeof($t.p.savedRow) !== "undefined" && $t.p.savedRow.length > 0 && $.isFunction($.fn.jqGrid.restoreRow)) {
-					for (var i=0;i<$t.p.savedRow.length;i++) {
-						if ($t.p.savedRow[i].id == rowid) {
-							$($t).jqGrid('restoreRow',rowid);
-							break;
-						}
-					}
-				}
-			}
-			function updateNav(cr,totr){
-				if (cr===0) {$("#pData",frmtb+"_2").addClass('ui-state-disabled');} else {$("#pData",frmtb+"_2").removeClass('ui-state-disabled');}
-				if (cr==totr) {$("#nData",frmtb+"_2").addClass('ui-state-disabled');} else {$("#nData",frmtb+"_2").removeClass('ui-state-disabled');}
-			}
-			function getCurrPos() {
-				var rowsInGrid = $($t).jqGrid("getDataIDs"),
-				selrow = $("#id_g",frmtb).val(),
-				pos = $.inArray(selrow,rowsInGrid);
-				return [pos,rowsInGrid];
-			}
-
-			if ( $("#"+$.jgrid.jqID(IDs.themodal)).html() !== null ) {
-				showFrm = $($t).triggerHandler("jqGridAddEditBeforeInitData", [$("#"+$.jgrid.jqID(frmgr))]);
-				if(typeof(showFrm) == "undefined") {
-					showFrm = true;
-				}
-				if(showFrm && onBeforeInit) {
-					showFrm = onBeforeInit.call($t,$("#"+frmgr));
-				}
-				if(showFrm === false) {return;}
-				restoreInline();
-				$(".ui-jqdialog-title","#"+$.jgrid.jqID(IDs.modalhead)).html(p.caption);
-				$("#FormError",frmtb).hide();
-				if(rp_ge[$t.p.id].topinfo) {
-					$(".topinfo",frmtb).html(rp_ge[$t.p.id].topinfo);
-					$(".tinfo",frmtb).show();
-				} else {
-					$(".tinfo",frmtb).hide();
-				}
-				if(rp_ge[$t.p.id].bottominfo) {
-					$(".bottominfo",frmtb+"_2").html(rp_ge[$t.p.id].bottominfo);
-					$(".binfo",frmtb+"_2").show();
-				} else {
-					$(".binfo",frmtb+"_2").hide();
-				}
-				// filldata
-				fillData(rowid,$t,frmgr);
-				///
-				if(rowid=="_empty" || !rp_ge[$t.p.id].viewPagerButtons) {
-					$("#pData, #nData",frmtb+"_2").hide();
-				} else {
-					$("#pData, #nData",frmtb+"_2").show();
-				}
-				if(rp_ge[$t.p.id].processing===true) {
-					rp_ge[$t.p.id].processing=false;
-					$("#sData", frmtb+"_2").removeClass('ui-state-active');
-				}
-				if($("#"+frmgr).data("disabled")===true) {
-					$(".confirm","#"+$.jgrid.jqID(IDs.themodal)).hide();
-					$("#"+frmgr).data("disabled",false);
-				}
-				$($t).triggerHandler("jqGridAddEditBeforeShowForm", [$("#"+frmgr), frmoper]);
-				if(onBeforeShow) { onBeforeShow.call($t, $("#"+frmgr)); }
-				$("#"+$.jgrid.jqID(IDs.themodal)).data("onClose",rp_ge[$t.p.id].onClose);
-				$.jgrid.viewModal("#"+$.jgrid.jqID(IDs.themodal),{gbox:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, jqM: false, overlay: p.overlay, modal:p.modal});
-				if(!closeovrl) {
-					$(".jqmOverlay").click(function(){
-						if(!checkUpdates()) {return false;}
-						$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose});
-						return false;
-					});
-				}
-				$($t).triggerHandler("jqGridAddEditAfterShowForm", [$("#"+frmgr), frmoper]);
-				if(onAfterShow) { onAfterShow.call($t, $("#"+frmgr)); }
-			} else {
-				var dh = isNaN(p.dataheight) ? p.dataheight : p.dataheight+"px",
-				frm = $("<form name='FormPost' id='"+frmgr+"' class='FormGrid' onSubmit='return false;' style='width:100%;overflow:auto;position:relative;height:"+dh+";'></form>").data("disabled",false),
-				tbl = $("<table id='"+frmtborg+"' class='EditTable' cellspacing='0' cellpadding='0' border='0'><tbody></tbody></table>");
-				showFrm = $($t).triggerHandler("jqGridAddEditBeforeInitData", [$("#"+frmgr), frmoper]);
-				if(typeof(showFrm) == "undefined") {
-					showFrm = true;
-				}
-				if(showFrm && onBeforeInit) {
-					showFrm = onBeforeInit.call($t,$("#"+frmgr));
-				}
-				if(showFrm === false) {return;}
-				restoreInline();
-				$($t.p.colModel).each( function() {
-					var fmto = this.formoptions;
-					maxCols = Math.max(maxCols, fmto ? fmto.colpos || 0 : 0 );
-					maxRows = Math.max(maxRows, fmto ? fmto.rowpos || 0 : 0 );
-				});
-				$(frm).append(tbl);
-				var flr = $("<tr id='FormError' style='display:none'><td class='ui-state-error' colspan='"+(maxCols*2)+"'></td></tr>");
-				flr[0].rp = 0;
-				$(tbl).append(flr);
-				//topinfo
-				flr = $("<tr style='display:none' class='tinfo'><td class='topinfo' colspan='"+(maxCols*2)+"'>"+rp_ge[$t.p.id].topinfo+"</td></tr>");
-				flr[0].rp = 0;
-				$(tbl).append(flr);
-				// set the id.
-				// use carefull only to change here colproperties.
-				// create data
-				var rtlb = $t.p.direction == "rtl" ? true :false,
-				bp = rtlb ? "nData" : "pData",
-				bn = rtlb ? "pData" : "nData";
-				createData(rowid,$t,tbl,maxCols);
-				// buttons at footer
-				var bP = "<a href='javascript:void(0)' id='"+bp+"' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></a>",
-				bN = "<a href='javascript:void(0)' id='"+bn+"' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></a>",
-				bS  ="<a href='javascript:void(0)' id='sData' class='fm-button ui-state-default ui-corner-all'>"+p.bSubmit+"</a>",
-				bC  ="<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>"+p.bCancel+"</a>";
-				var bt = "<table border='0' cellspacing='0' cellpadding='0' class='EditTable' id='"+frmtborg+"_2'><tbody><tr><td colspan='2'><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr id='Act_Buttons'><td class='navButton'>"+(rtlb ? bN+bP : bP+bN)+"</td><td class='EditButton'>"+bS+bC+"</td></tr>";
-				bt += "<tr style='display:none' class='binfo'><td class='bottominfo' colspan='2'>"+rp_ge[$t.p.id].bottominfo+"</td></tr>";
-				bt += "</tbody></table>";
-				if(maxRows >  0) {
-					var sd=[];
-					$.each($(tbl)[0].rows,function(i,r){
-						sd[i] = r;
-					});
-					sd.sort(function(a,b){
-						if(a.rp > b.rp) {return 1;}
-						if(a.rp < b.rp) {return -1;}
-						return 0;
-					});
-					$.each(sd, function(index, row) {
-						$('tbody',tbl).append(row);
-					});
-				}
-				p.gbox = "#gbox_"+$.jgrid.jqID(gID);
-				var cle = false;
-				if(p.closeOnEscape===true){
-					p.closeOnEscape = false;
-					cle = true;
-				}
-				var tms = $("<span></span>").append(frm).append(bt);
-				$.jgrid.createModal(IDs,tms,p,"#gview_"+$.jgrid.jqID($t.p.id),$("#gbox_"+$.jgrid.jqID($t.p.id))[0]);
-				if(rtlb) {
-					$("#pData, #nData",frmtb+"_2").css("float","right");
-					$(".EditButton",frmtb+"_2").css("text-align","left");
-				}
-				if(rp_ge[$t.p.id].topinfo) {$(".tinfo",frmtb).show();}
-				if(rp_ge[$t.p.id].bottominfo) {$(".binfo",frmtb+"_2").show();}
-				tms = null;bt=null;
-				$("#"+$.jgrid.jqID(IDs.themodal)).keydown( function( e ) {
-					var wkey = e.target;
-					if ($("#"+frmgr).data("disabled")===true ) {return false;}//??
-					if(rp_ge[$t.p.id].savekey[0] === true && e.which == rp_ge[$t.p.id].savekey[1]) { // save
-						if(wkey.tagName != "TEXTAREA") {
-							$("#sData", frmtb+"_2").trigger("click");
-							return false;
-						}
-					}
-					if(e.which === 27) {
-						if(!checkUpdates()) {return false;}
-						if(cle)	{$.jgrid.hideModal(this,{gb:p.gbox,jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose});}
-						return false;
-					}
-					if(rp_ge[$t.p.id].navkeys[0]===true) {
-						if($("#id_g",frmtb).val() == "_empty") {return true;}
-						if(e.which == rp_ge[$t.p.id].navkeys[1]){ //up
-							$("#pData", frmtb+"_2").trigger("click");
-							return false;
-						}
-						if(e.which == rp_ge[$t.p.id].navkeys[2]){ //down
-							$("#nData", frmtb+"_2").trigger("click");
-							return false;
-						}
-					}
-				});
-				if(p.checkOnUpdate) {
-					$("a.ui-jqdialog-titlebar-close span","#"+$.jgrid.jqID(IDs.themodal)).removeClass("jqmClose");
-					$("a.ui-jqdialog-titlebar-close","#"+$.jgrid.jqID(IDs.themodal)).unbind("click")
-					.click(function(){
-						if(!checkUpdates()) {return false;}
-						$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal,onClose: rp_ge[$t.p.id].onClose});
-						return false;
-					});
-				}
-				p.saveicon = $.extend([true,"left","ui-icon-disk"],p.saveicon);
-				p.closeicon = $.extend([true,"left","ui-icon-close"],p.closeicon);
-				// beforeinitdata after creation of the form
-				if(p.saveicon[0]===true) {
-					$("#sData",frmtb+"_2").addClass(p.saveicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left')
-					.append("<span class='ui-icon "+p.saveicon[2]+"'></span>");
-				}
-				if(p.closeicon[0]===true) {
-					$("#cData",frmtb+"_2").addClass(p.closeicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left')
-					.append("<span class='ui-icon "+p.closeicon[2]+"'></span>");
-				}
-				if(rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) {
-					bS  ="<a href='javascript:void(0)' id='sNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+p.bYes+"</a>";
-					bN  ="<a href='javascript:void(0)' id='nNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+p.bNo+"</a>";
-					bC  ="<a href='javascript:void(0)' id='cNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+p.bExit+"</a>";
-					var ii, zI = p.zIndex  || 999;zI ++;
-					if ($.browser.msie && $.browser.version ==6) {
-						ii = '<iframe style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=\'0\');" src="javascript:false;"></iframe>';
-					} else {ii="";}
-					$("<div class='ui-widget-overlay jqgrid-overlay confirm' style='z-index:"+zI+";display:none;'>&#160;"+ii+"</div><div class='confirm ui-widget-content ui-jqconfirm' style='z-index:"+(zI+1)+"'>"+p.saveData+"<br/><br/>"+bS+bN+bC+"</div>").insertAfter("#"+frmgr);
-					$("#sNew","#"+$.jgrid.jqID(IDs.themodal)).click(function(){
-						postIt();
-						$("#"+frmgr).data("disabled",false);
-						$(".confirm","#"+$.jgrid.jqID(IDs.themodal)).hide();
-						return false;
-					});
-					$("#nNew","#"+$.jgrid.jqID(IDs.themodal)).click(function(){
-						$(".confirm","#"+$.jgrid.jqID(IDs.themodal)).hide();
-						$("#"+frmgr).data("disabled",false);
-						setTimeout(function(){$(":input","#"+frmgr)[0].focus();},0);
-						return false;
-					});
-					$("#cNew","#"+$.jgrid.jqID(IDs.themodal)).click(function(){
-						$(".confirm","#"+$.jgrid.jqID(IDs.themodal)).hide();
-						$("#"+frmgr).data("disabled",false);
-						$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal,onClose: rp_ge[$t.p.id].onClose});
-						return false;
-					});
-				}
-				// here initform - only once
-				$($t).triggerHandler("jqGridAddEditInitializeForm", [$("#"+frmgr), frmoper]);
-				if(onInitializeForm) {onInitializeForm.call($t,$("#"+frmgr));}
-				if(rowid=="_empty" || !rp_ge[$t.p.id].viewPagerButtons) {$("#pData,#nData",frmtb+"_2").hide();} else {$("#pData,#nData",frmtb+"_2").show();}
-				$($t).triggerHandler("jqGridAddEditBeforeShowForm", [$("#"+frmgr), frmoper]);
-				if(onBeforeShow) { onBeforeShow.call($t, $("#"+frmgr));}
-				$("#"+$.jgrid.jqID(IDs.themodal)).data("onClose",rp_ge[$t.p.id].onClose);
-				$.jgrid.viewModal("#"+$.jgrid.jqID(IDs.themodal),{gbox:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, overlay: p.overlay,modal:p.modal});
-				if(!closeovrl) {
-					$(".jqmOverlay").click(function(){
-						if(!checkUpdates()) {return false;}
-						$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose});
-						return false;
-					});
-				}
-				$($t).triggerHandler("jqGridAddEditAfterShowForm", [$("#"+frmgr), frmoper]);
-				if(onAfterShow) { onAfterShow.call($t, $("#"+frmgr)); }
-				$(".fm-button","#"+$.jgrid.jqID(IDs.themodal)).hover(
-					function(){$(this).addClass('ui-state-hover');},
-					function(){$(this).removeClass('ui-state-hover');}
-				);
-				$("#sData", frmtb+"_2").click(function(){
-					postdata = {};extpost={};
-					$("#FormError",frmtb).hide();
-					// all depend on ret array
-					//ret[0] - succes
-					//ret[1] - msg if not succes
-					//ret[2] - the id  that will be set if reload after submit false
-					getFormData();
-					if(postdata[$t.p.id+"_id"] == "_empty")	{postIt();}
-					else if(p.checkOnSubmit===true ) {
-						newData = $.extend({},postdata,extpost);
-						diff = compareData(newData,rp_ge[$t.p.id]._savedData);
-						if(diff) {
-							$("#"+frmgr).data("disabled",true);
-							$(".confirm","#"+$.jgrid.jqID(IDs.themodal)).show();
-						} else {
-							postIt();
-						}
-					} else {
-						postIt();
-					}
-					return false;
-				});
-				$("#cData", frmtb+"_2").click(function(){
-					if(!checkUpdates()) {return false;}
-					$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal,onClose: rp_ge[$t.p.id].onClose});
-					return false;
-				});
-				$("#nData", frmtb+"_2").click(function(){
-					if(!checkUpdates()) {return false;}
-					$("#FormError",frmtb).hide();
-					var npos = getCurrPos();
-					npos[0] = parseInt(npos[0],10);
-					if(npos[0] != -1 && npos[1][npos[0]+1]) {
-						$($t).triggerHandler("jqGridAddEditClickPgButtons", ['next',$("#"+frmgr),npos[1][npos[0]]]);
-						if($.isFunction(p.onclickPgButtons)) {
-							p.onclickPgButtons.call($t, 'next',$("#"+frmgr),npos[1][npos[0]]);
-						}
-						fillData(npos[1][npos[0]+1],$t,frmgr);
-						$($t).jqGrid("setSelection",npos[1][npos[0]+1]);
-						$($t).triggerHandler("jqGridAddEditAfterClickPgButtons", ['next',$("#"+frmgr),npos[1][npos[0]]]);
-						if($.isFunction(p.afterclickPgButtons)) {
-							p.afterclickPgButtons.call($t, 'next',$("#"+frmgr),npos[1][npos[0]+1]);
-						}
-						updateNav(npos[0]+1,npos[1].length-1);
-					}
-					return false;
-				});
-				$("#pData", frmtb+"_2").click(function(){
-					if(!checkUpdates()) {return false;}
-					$("#FormError",frmtb).hide();
-					var ppos = getCurrPos();
-					if(ppos[0] != -1 && ppos[1][ppos[0]-1]) {
-						$($t).triggerHandler("jqGridAddEditClickPgButtons", ['prev',$("#"+frmgr),ppos[1][ppos[0]]]);
-						if($.isFunction(p.onclickPgButtons)) {
-							p.onclickPgButtons.call($t, 'prev',$("#"+frmgr),ppos[1][ppos[0]]);
-						}
-						fillData(ppos[1][ppos[0]-1],$t,frmgr);
-						$($t).jqGrid("setSelection",ppos[1][ppos[0]-1]);
-						$($t).triggerHandler("jqGridAddEditAfterClickPgButtons", ['prev',$("#"+frmgr),ppos[1][ppos[0]]]);
-						if($.isFunction(p.afterclickPgButtons)) {
-							p.afterclickPgButtons.call($t, 'prev',$("#"+frmgr),ppos[1][ppos[0]-1]);
-						}
-						updateNav(ppos[0]-1,ppos[1].length-1);
-					}
-					return false;
-				});
-			}
-			var posInit =getCurrPos();
-			updateNav(posInit[0],posInit[1].length-1);
-
-		});
-	},
-	viewGridRow : function(rowid, p){
-		p = $.extend({
-			top : 0,
-			left: 0,
-			width: 0,
-			height: 'auto',
-			dataheight: 'auto',
-			modal: false,
-			overlay: 30,
-			drag: true,
-			resize: true,
-			jqModal: true,
-			closeOnEscape : false,
-			labelswidth: '30%',
-			closeicon: [],
-			navkeys: [false,38,40],
-			onClose: null,
-			beforeShowForm : null,
-			beforeInitData : null,
-			viewPagerButtons : true
-		}, $.jgrid.view, p || {});
-		return this.each(function(){
-			var $t = this;
-			if (!$t.grid || !rowid) {return;}
-			var gID = $t.p.id,
-			frmgr = "ViewGrid_"+$.jgrid.jqID( gID  ), frmtb = "ViewTbl_" + $.jgrid.jqID( gID ),
-			frmgr_id = "ViewGrid_"+gID, frmtb_id = "ViewTbl_"+gID,
-			IDs = {themodal:'viewmod'+gID,modalhead:'viewhd'+gID,modalcontent:'viewcnt'+gID, scrollelm : frmgr},
-			onBeforeInit = $.isFunction(p.beforeInitData) ? p.beforeInitData : false,
-			showFrm = true,
-			maxCols = 1, maxRows=0;
-			function focusaref(){ //Sfari 3 issues
-				if(p.closeOnEscape===true || p.navkeys[0]===true) {
-					setTimeout(function(){$(".ui-jqdialog-titlebar-close","#"+$.jgrid.jqID(IDs.modalhead)).focus();},0);
-				}
-			}
-			function createData(rowid,obj,tb,maxcols){
-				var nm, hc,trdata, cnt=0,tmp, dc, retpos=[], ind=false,
-				tdtmpl = "<td class='CaptionTD form-view-label ui-widget-content' width='"+p.labelswidth+"'>&#160;</td><td class='DataTD form-view-data ui-helper-reset ui-widget-content'>&#160;</td>", tmpl="",
-				tdtmpl2 = "<td class='CaptionTD form-view-label ui-widget-content'>&#160;</td><td class='DataTD form-view-data ui-widget-content'>&#160;</td>",
-				fmtnum = ['integer','number','currency'],max1 =0, max2=0 ,maxw,setme, viewfld;
-				for (var i =1;i<=maxcols;i++) {
-					tmpl += i == 1 ? tdtmpl : tdtmpl2;
-				}
-				// find max number align rigth with property formatter
-				$(obj.p.colModel).each( function() {
-					if(this.editrules && this.editrules.edithidden === true) {
-						hc = false;
-					} else {
-						hc = this.hidden === true ? true : false;
-					}
-					if(!hc && this.align==='right') {
-						if(this.formatter && $.inArray(this.formatter,fmtnum) !== -1 ) {
-							max1 = Math.max(max1,parseInt(this.width,10));
-						} else {
-							max2 = Math.max(max2,parseInt(this.width,10));
-						}
-					}
-				});
-				maxw  = max1 !==0 ? max1 : max2 !==0 ? max2 : 0;
-				ind = $(obj).jqGrid("getInd",rowid);
-				$(obj.p.colModel).each( function(i) {
-					nm = this.name;
-					setme = false;
-					// hidden fields are included in the form
-					if(this.editrules && this.editrules.edithidden === true) {
-						hc = false;
-					} else {
-						hc = this.hidden === true ? true : false;
-					}
-					dc = hc ? "style='display:none'" : "";
-					viewfld = (typeof this.viewable != 'boolean') ? true : this.viewable;
-					if ( nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn' && viewfld) {
-						if(ind === false) {
-							tmp = "";
-						} else {
-							if(nm == obj.p.ExpandColumn && obj.p.treeGrid === true) {
-								tmp = $("td:eq("+i+")",obj.rows[ind]).text();
-							} else {
-								tmp = $("td:eq("+i+")",obj.rows[ind]).html();
-							}
-						}
-						setme = this.align === 'right' && maxw !==0 ? true : false;
-						var opt = $.extend({}, this.editoptions || {} ,{id:nm,name:nm}),
-						frmopt = $.extend({},{rowabove:false,rowcontent:''}, this.formoptions || {}),
-						rp = parseInt(frmopt.rowpos,10) || cnt+1,
-						cp = parseInt((parseInt(frmopt.colpos,10) || 1)*2,10);
-						if(frmopt.rowabove) {
-							var newdata = $("<tr><td class='contentinfo' colspan='"+(maxcols*2)+"'>"+frmopt.rowcontent+"</td></tr>");
-							$(tb).append(newdata);
-							newdata[0].rp = rp;
-						}
-						trdata = $(tb).find("tr[rowpos="+rp+"]");
-						if ( trdata.length===0 ) {
-							trdata = $("<tr "+dc+" rowpos='"+rp+"'></tr>").addClass("FormData").attr("id","trv_"+nm);
-							$(trdata).append(tmpl);
-							$(tb).append(trdata);
-							trdata[0].rp = rp;
-						}
-						$("td:eq("+(cp-2)+")",trdata[0]).html('<b>'+ (typeof frmopt.label === 'undefined' ? obj.p.colNames[i]: frmopt.label)+'</b>');
-						$("td:eq("+(cp-1)+")",trdata[0]).append("<span>"+tmp+"</span>").attr("id","v_"+nm);
-						if(setme){
-							$("td:eq("+(cp-1)+") span",trdata[0]).css({'text-align':'right',width:maxw+"px"});
-						}
-						retpos[cnt] = i;
-						cnt++;
-					}
-				});
-				if( cnt > 0) {
-					var idrow = $("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='"+ (maxcols*2-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='id' value='"+rowid+"'/></td></tr>");
-					idrow[0].rp = cnt+99;
-					$(tb).append(idrow);
-				}
-				return retpos;
-			}
-			function fillData(rowid,obj){
-				var nm, hc,cnt=0,tmp, opt,trv;
-				trv = $(obj).jqGrid("getInd",rowid,true);
-				if(!trv) {return;}
-				$('td',trv).each( function(i) {
-					nm = obj.p.colModel[i].name;
-					// hidden fields are included in the form
-					if(obj.p.colModel[i].editrules && obj.p.colModel[i].editrules.edithidden === true) {
-						hc = false;
-					} else {
-						hc = obj.p.colModel[i].hidden === true ? true : false;
-					}
-					if ( nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn') {
-						if(nm == obj.p.ExpandColumn && obj.p.treeGrid === true) {
-							tmp = $(this).text();
-						} else {
-							tmp = $(this).html();
-						}
-						opt = $.extend({},obj.p.colModel[i].editoptions || {});
-						nm = $.jgrid.jqID("v_"+nm);
-						$("#"+nm+" span","#"+frmtb).html(tmp);
-						if (hc) {$("#"+nm,"#"+frmtb).parents("tr:first").hide();}
-						cnt++;
-					}
-				});
-				if(cnt>0) {$("#id_g","#"+frmtb).val(rowid);}
-			}
-			function updateNav(cr,totr){
-				if (cr===0) {$("#pData","#"+frmtb+"_2").addClass('ui-state-disabled');} else {$("#pData","#"+frmtb+"_2").removeClass('ui-state-disabled');}
-				if (cr==totr) {$("#nData","#"+frmtb+"_2").addClass('ui-state-disabled');} else {$("#nData","#"+frmtb+"_2").removeClass('ui-state-disabled');}
-			}
-			function getCurrPos() {
-				var rowsInGrid = $($t).jqGrid("getDataIDs"),
-				selrow = $("#id_g","#"+frmtb).val(),
-				pos = $.inArray(selrow,rowsInGrid);
-				return [pos,rowsInGrid];
-			}
-
-			if ( $("#"+$.jgrid.jqID(IDs.themodal)).html() !== null ) {
-				if(onBeforeInit) {
-					showFrm = onBeforeInit.call($t,$("#"+frmgr));
-					if(typeof(showFrm) == "undefined") {
-						showFrm = true;
-					}
-				}
-				if(showFrm === false) {return;}
-				$(".ui-jqdialog-title","#"+$.jgrid.jqID(IDs.modalhead)).html(p.caption);
-				$("#FormError","#"+frmtb).hide();
-				fillData(rowid,$t);
-				if($.isFunction(p.beforeShowForm)) {p.beforeShowForm.call($t,$("#"+frmgr));}
-				$.jgrid.viewModal("#"+$.jgrid.jqID(IDs.themodal),{gbox:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, jqM: false, overlay: p.overlay, modal:p.modal});
-				focusaref();
-			} else {
-				var dh = isNaN(p.dataheight) ? p.dataheight : p.dataheight+"px";
-				var frm = $("<form name='FormPost' id='"+frmgr_id+"' class='FormGrid' style='width:100%;overflow:auto;position:relative;height:"+dh+";'></form>"),
-				tbl =$("<table id='"+frmtb_id+"' class='EditTable' cellspacing='1' cellpadding='2' border='0' style='table-layout:fixed'><tbody></tbody></table>");
-				if(onBeforeInit) {
-					showFrm = onBeforeInit.call($t,$("#"+frmgr));
-					if(typeof(showFrm) == "undefined") {
-						showFrm = true;
-					}
-				}
-				if(showFrm === false) {return;}
-				$($t.p.colModel).each( function() {
-					var fmto = this.formoptions;
-					maxCols = Math.max(maxCols, fmto ? fmto.colpos || 0 : 0 );
-					maxRows = Math.max(maxRows, fmto ? fmto.rowpos || 0 : 0 );
-				});
-				// set the id.
-				$(frm).append(tbl);
-				createData(rowid, $t, tbl, maxCols);
-				var rtlb = $t.p.direction == "rtl" ? true :false,
-				bp = rtlb ? "nData" : "pData",
-				bn = rtlb ? "pData" : "nData",
-
-				// buttons at footer
-				bP = "<a href='javascript:void(0)' id='"+bp+"' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></a>",
-				bN = "<a href='javascript:void(0)' id='"+bn+"' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></a>",
-				bC  ="<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>"+p.bClose+"</a>";
-				if(maxRows >  0) {
-					var sd=[];
-					$.each($(tbl)[0].rows,function(i,r){
-						sd[i] = r;
-					});
-					sd.sort(function(a,b){
-						if(a.rp > b.rp) {return 1;}
-						if(a.rp < b.rp) {return -1;}
-						return 0;
-					});
-					$.each(sd, function(index, row) {
-						$('tbody',tbl).append(row);
-					});
-				}
-				p.gbox = "#gbox_"+$.jgrid.jqID(gID);
-				var cle = false;
-				if(p.closeOnEscape===true){
-					p.closeOnEscape = false;
-					cle = true;
-				}
-				var bt = $("<span></span>").append(frm).append("<table border='0' class='EditTable' id='"+frmtb+"_2'><tbody><tr id='Act_Buttons'><td class='navButton' width='"+p.labelswidth+"'>"+(rtlb ? bN+bP : bP+bN)+"</td><td class='EditButton'>"+bC+"</td></tr></tbody></table>");
-				$.jgrid.createModal(IDs,bt,p,"#gview_"+$.jgrid.jqID($t.p.id),$("#gview_"+$.jgrid.jqID($t.p.id))[0]);
-				if(rtlb) {
-					$("#pData, #nData","#"+frmtb+"_2").css("float","right");
-					$(".EditButton","#"+frmtb+"_2").css("text-align","left");
-				}
-				if(!p.viewPagerButtons) {$("#pData, #nData","#"+frmtb+"_2").hide();}
-				bt = null;
-				$("#"+IDs.themodal).keydown( function( e ) {
-					if(e.which === 27) {
-						if(cle)	{$.jgrid.hideModal(this,{gb:p.gbox,jqm:p.jqModal, onClose: p.onClose});}
-						return false;
-					}
-					if(p.navkeys[0]===true) {
-						if(e.which === p.navkeys[1]){ //up
-							$("#pData", "#"+frmtb+"_2").trigger("click");
-							return false;
-						}
-						if(e.which === p.navkeys[2]){ //down
-							$("#nData", "#"+frmtb+"_2").trigger("click");
-							return false;
-						}
-					}
-				});
-				p.closeicon = $.extend([true,"left","ui-icon-close"],p.closeicon);
-				if(p.closeicon[0]===true) {
-					$("#cData","#"+frmtb+"_2").addClass(p.closeicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left')
-					.append("<span class='ui-icon "+p.closeicon[2]+"'></span>");
-				}
-				if($.isFunction(p.beforeShowForm)) {p.beforeShowForm.call($t,$("#"+frmgr));}
-				$.jgrid.viewModal("#"+$.jgrid.jqID(IDs.themodal),{gbox:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, modal:p.modal});
-				$(".fm-button:not(.ui-state-disabled)","#"+frmtb+"_2").hover(
-					function(){$(this).addClass('ui-state-hover');},
-					function(){$(this).removeClass('ui-state-hover');}
-				);
-				focusaref();
-				$("#cData", "#"+frmtb+"_2").click(function(){
-					$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: p.onClose});
-					return false;
-				});
-				$("#nData", "#"+frmtb+"_2").click(function(){
-					$("#FormError","#"+frmtb).hide();
-					var npos = getCurrPos();
-					npos[0] = parseInt(npos[0],10);
-					if(npos[0] != -1 && npos[1][npos[0]+1]) {
-						if($.isFunction(p.onclickPgButtons)) {
-							p.onclickPgButtons.call($t,'next',$("#"+frmgr),npos[1][npos[0]]);
-						}
-						fillData(npos[1][npos[0]+1],$t);
-						$($t).jqGrid("setSelection",npos[1][npos[0]+1]);
-						if($.isFunction(p.afterclickPgButtons)) {
-							p.afterclickPgButtons.call($t,'next',$("#"+frmgr),npos[1][npos[0]+1]);
-						}
-						updateNav(npos[0]+1,npos[1].length-1);
-					}
-					focusaref();
-					return false;
-				});
-				$("#pData", "#"+frmtb+"_2").click(function(){
-					$("#FormError","#"+frmtb).hide();
-					var ppos = getCurrPos();
-					if(ppos[0] != -1 && ppos[1][ppos[0]-1]) {
-						if($.isFunction(p.onclickPgButtons)) {
-							p.onclickPgButtons.call($t,'prev',$("#"+frmgr),ppos[1][ppos[0]]);
-						}
-						fillData(ppos[1][ppos[0]-1],$t);
-						$($t).jqGrid("setSelection",ppos[1][ppos[0]-1]);
-						if($.isFunction(p.afterclickPgButtons)) {
-							p.afterclickPgButtons.call($t,'prev',$("#"+frmgr),ppos[1][ppos[0]-1]);
-						}
-						updateNav(ppos[0]-1,ppos[1].length-1);
-					}
-					focusaref();
-					return false;
-				});
-			}
-			var posInit =getCurrPos();
-			updateNav(posInit[0],posInit[1].length-1);
-		});
-	},
-	delGridRow : function(rowids,p) {
-		p = $.extend({
-			top : 0,
-			left: 0,
-			width: 240,
-			height: 'auto',
-			dataheight : 'auto',
-			modal: false,
-			overlay: 30,
-			drag: true,
-			resize: true,
-			url : '',
-			mtype : "POST",
-			reloadAfterSubmit: true,
-			beforeShowForm: null,
-			beforeInitData : null,
-			afterShowForm: null,
-			beforeSubmit: null,
-			onclickSubmit: null,
-			afterSubmit: null,
-			jqModal : true,
-			closeOnEscape : false,
-			delData: {},
-			delicon : [],
-			cancelicon : [],
-			onClose : null,
-			ajaxDelOptions : {},
-			processing : false,
-			serializeDelData : null,
-			useDataProxy : false
-		}, $.jgrid.del, p ||{});
-		rp_ge[$(this)[0].p.id] = p;
-		return this.each(function(){
-			var $t = this;
-			if (!$t.grid ) {return;}
-			if(!rowids) {return;}
-			var onBeforeShow = $.isFunction( rp_ge[$t.p.id].beforeShowForm  ),
-			onAfterShow = $.isFunction( rp_ge[$t.p.id].afterShowForm ),
-			onBeforeInit = $.isFunction(rp_ge[$t.p.id].beforeInitData) ? rp_ge[$t.p.id].beforeInitData : false,
-			gID = $t.p.id, onCS = {},
-			showFrm = true,
-			dtbl = "DelTbl_"+$.jgrid.jqID(gID),postd, idname, opers, oper,
-			dtbl_id = "DelTbl_" + gID,
-			IDs = {themodal:'delmod'+gID,modalhead:'delhd'+gID,modalcontent:'delcnt'+gID, scrollelm: dtbl};
-			if (jQuery.isArray(rowids)) {rowids = rowids.join();}
-			if ( $("#"+$.jgrid.jqID(IDs.themodal)).html() !== null ) {
-				if(onBeforeInit) {
-					showFrm = onBeforeInit.call($t,$("#"+dtbl));
-					if(typeof(showFrm) == "undefined") {
-						showFrm = true;
-					}
-				}
-				if(showFrm === false) {return;}
-				$("#DelData>td","#"+dtbl).text(rowids);
-				$("#DelError","#"+dtbl).hide();
-				if( rp_ge[$t.p.id].processing === true) {
-					rp_ge[$t.p.id].processing=false;
-					$("#dData", "#"+dtbl).removeClass('ui-state-active');
-				}
-				if(onBeforeShow) {rp_ge[$t.p.id].beforeShowForm.call($t,$("#"+dtbl));}
-				$.jgrid.viewModal("#"+$.jgrid.jqID(IDs.themodal),{gbox:"#gbox_"+$.jgrid.jqID(gID),jqm:rp_ge[$t.p.id].jqModal,jqM: false, overlay: rp_ge[$t.p.id].overlay, modal:rp_ge[$t.p.id].modal});
-				if(onAfterShow) {rp_ge[$t.p.id].afterShowForm.call($t,$("#"+dtbl));}
-			} else {
-				var dh = isNaN(rp_ge[$t.p.id].dataheight) ? rp_ge[$t.p.id].dataheight : rp_ge[$t.p.id].dataheight+"px";
-				var tbl = "<div id='"+dtbl_id+"' class='formdata' style='width:100%;overflow:auto;position:relative;height:"+dh+";'>";
-				tbl += "<table class='DelTable'><tbody>";
-				// error data
-				tbl += "<tr id='DelError' style='display:none'><td class='ui-state-error'></td></tr>";
-				tbl += "<tr id='DelData' style='display:none'><td >"+rowids+"</td></tr>";
-				tbl += "<tr><td class=\"delmsg\" style=\"white-space:pre;\">"+rp_ge[$t.p.id].msg+"</td></tr><tr><td >&#160;</td></tr>";
-				// buttons at footer
-				tbl += "</tbody></table></div>";
-				var bS  = "<a href='javascript:void(0)' id='dData' class='fm-button ui-state-default ui-corner-all'>"+p.bSubmit+"</a>",
-				bC  = "<a href='javascript:void(0)' id='eData' class='fm-button ui-state-default ui-corner-all'>"+p.bCancel+"</a>";
-				tbl += "<table cellspacing='0' cellpadding='0' border='0' class='EditTable' id='"+dtbl+"_2'><tbody><tr><td><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr><td class='DelButton EditButton'>"+bS+"&#160;"+bC+"</td></tr></tbody></table>";
-				p.gbox = "#gbox_"+$.jgrid.jqID(gID);
-				$.jgrid.createModal(IDs,tbl,p,"#gview_"+$.jgrid.jqID($t.p.id),$("#gview_"+$.jgrid.jqID($t.p.id))[0]);
-
-				if(onBeforeInit) {
-					showFrm = onBeforeInit.call($t,$("#"+dtbl));
-					if(typeof(showFrm) == "undefined") {
-						showFrm = true;
-					}
-				}
-				if(showFrm === false) {return;}
-
-				$(".fm-button","#"+dtbl+"_2").hover(
-					function(){$(this).addClass('ui-state-hover');},
-					function(){$(this).removeClass('ui-state-hover');}
-				);
-				p.delicon = $.extend([true,"left","ui-icon-scissors"],rp_ge[$t.p.id].delicon);
-				p.cancelicon = $.extend([true,"left","ui-icon-cancel"],rp_ge[$t.p.id].cancelicon);
-				if(p.delicon[0]===true) {
-					$("#dData","#"+dtbl+"_2").addClass(p.delicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left')
-					.append("<span class='ui-icon "+p.delicon[2]+"'></span>");
-				}
-				if(p.cancelicon[0]===true) {
-					$("#eData","#"+dtbl+"_2").addClass(p.cancelicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left')
-					.append("<span class='ui-icon "+p.cancelicon[2]+"'></span>");
-				}
-				$("#dData","#"+dtbl+"_2").click(function(){
-					var ret=[true,""];onCS = {};
-					var postdata = $("#DelData>td","#"+dtbl).text(); //the pair is name=val1,val2,...
-					if( $.isFunction( rp_ge[$t.p.id].onclickSubmit ) ) {onCS = rp_ge[$t.p.id].onclickSubmit.call($t,rp_ge[$t.p.id], postdata) || {};}
-					if( $.isFunction( rp_ge[$t.p.id].beforeSubmit ) ) {ret = rp_ge[$t.p.id].beforeSubmit.call($t,postdata);}
-					if(ret[0] && !rp_ge[$t.p.id].processing) {
-						rp_ge[$t.p.id].processing = true;
-						opers = $t.p.prmNames;
-						postd = $.extend({},rp_ge[$t.p.id].delData, onCS);
-						oper = opers.oper;
-						postd[oper] = opers.deloper;
-						idname = opers.id;
-						postdata = String(postdata).split(",");
-						if(!postdata.length) { return false; }
-						for( var pk in postdata) {
-							if(postdata.hasOwnProperty(pk)) {
-								postdata[pk] = $.jgrid.stripPref($t.p.idPrefix, postdata[pk]);
-							}
-						}
-						postd[idname] = postdata.join();
-						$(this).addClass('ui-state-active');
-						var ajaxOptions = $.extend({
-							url: rp_ge[$t.p.id].url ? rp_ge[$t.p.id].url : $($t).jqGrid('getGridParam','editurl'),
-							type: rp_ge[$t.p.id].mtype,
-							data: $.isFunction(rp_ge[$t.p.id].serializeDelData) ? rp_ge[$t.p.id].serializeDelData.call($t,postd) : postd,
-							complete:function(data,Status){
-								if(Status != "success") {
-									ret[0] = false;
-									if ($.isFunction(rp_ge[$t.p.id].errorTextFormat)) {
-										ret[1] = rp_ge[$t.p.id].errorTextFormat.call($t,data);
-									} else {
-										ret[1] = Status + " Status: '" + data.statusText + "'. Error code: " + data.status;
-									}
-								} else {
-									// data is posted successful
-									// execute aftersubmit with the returned data from server
-									if( $.isFunction( rp_ge[$t.p.id].afterSubmit ) ) {
-										ret = rp_ge[$t.p.id].afterSubmit.call($t,data,postd);
-									}
-								}
-								if(ret[0] === false) {
-									$("#DelError>td","#"+dtbl).html(ret[1]);
-									$("#DelError","#"+dtbl).show();
-								} else {
-									if(rp_ge[$t.p.id].reloadAfterSubmit && $t.p.datatype != "local") {
-										$($t).trigger("reloadGrid");
-									} else {
-										if($t.p.treeGrid===true){
-												try {$($t).jqGrid("delTreeNode",$t.p.idPrefix+postdata[0]);} catch(e){}
-										} else {
-											for(var i=0;i<postdata.length;i++) {
-												$($t).jqGrid("delRowData",$t.p.idPrefix+ postdata[i]);
-											}
-										}
-										$t.p.selrow = null;
-										$t.p.selarrrow = [];
-									}
-									if($.isFunction(rp_ge[$t.p.id].afterComplete)) {
-										setTimeout(function(){rp_ge[$t.p.id].afterComplete.call($t,data,postdata);},500);
-									}
-								}
-								rp_ge[$t.p.id].processing=false;
-								$("#dData", "#"+dtbl+"_2").removeClass('ui-state-active');
-								if(ret[0]) {$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose});}
-							}
-						}, $.jgrid.ajaxOptions, rp_ge[$t.p.id].ajaxDelOptions);
-
-
-						if (!ajaxOptions.url && !rp_ge[$t.p.id].useDataProxy) {
-							if ($.isFunction($t.p.dataProxy)) {
-								rp_ge[$t.p.id].useDataProxy = true;
-							} else {
-								ret[0]=false;ret[1] += " "+$.jgrid.errors.nourl;
-							}
-						}
-						if (ret[0]) {
-							if (rp_ge[$t.p.id].useDataProxy) {
-								var dpret = $t.p.dataProxy.call($t, ajaxOptions, "del_"+$t.p.id);
-								if(typeof(dpret) == "undefined") {
-									dpret = [true, ""];
-								}
-								if(dpret[0] === false ) {
-									ret[0] = false;
-									ret[1] = dpret[1] || "Error deleting the selected row!" ;
-								} else {
-									$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose});
-								}
-							}
-							else {$.ajax(ajaxOptions);}
-						}
-					}
-
-					if(ret[0] === false) {
-						$("#DelError>td","#"+dtbl).html(ret[1]);
-						$("#DelError","#"+dtbl).show();
-					}
-					return false;
-				});
-				$("#eData", "#"+dtbl+"_2").click(function(){
-					$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:rp_ge[$t.p.id].jqModal, onClose: rp_ge[$t.p.id].onClose});
-					return false;
-				});
-				if(onBeforeShow) {rp_ge[$t.p.id].beforeShowForm.call($t,$("#"+dtbl));}
-				$.jgrid.viewModal("#"+$.jgrid.jqID(IDs.themodal),{gbox:"#gbox_"+$.jgrid.jqID(gID),jqm:rp_ge[$t.p.id].jqModal, overlay: rp_ge[$t.p.id].overlay, modal:rp_ge[$t.p.id].modal});
-				if(onAfterShow) {rp_ge[$t.p.id].afterShowForm.call($t,$("#"+dtbl));}
-			}
-			if(rp_ge[$t.p.id].closeOnEscape===true) {
-				setTimeout(function(){$(".ui-jqdialog-titlebar-close","#"+$.jgrid.jqID(IDs.modalhead)).focus();},0);
-			}
-		});
-	},
-	navGrid : function (elem, o, pEdit,pAdd,pDel,pSearch, pView) {
-		o = $.extend({
-			edit: true,
-			editicon: "ui-icon-pencil",
-			add: true,
-			addicon:"ui-icon-plus",
-			del: true,
-			delicon:"ui-icon-trash",
-			search: true,
-			searchicon:"ui-icon-search",
-			refresh: true,
-			refreshicon:"ui-icon-refresh",
-			refreshstate: 'firstpage',
-			view: false,
-			viewicon : "ui-icon-document",
-			position : "left",
-			closeOnEscape : true,
-			beforeRefresh : null,
-			afterRefresh : null,
-			cloneToTop : false,
-			alertwidth : 200,
-			alertheight : 'auto',
-			alerttop: null,
-			alertleft: null,
-			alertzIndex : null
-		}, $.jgrid.nav, o ||{});
-		return this.each(function() {
-			if(this.nav) {return;}
-			var alertIDs = {themodal:'alertmod',modalhead:'alerthd',modalcontent:'alertcnt'},
-			$t = this, twd, tdw;
-			if(!$t.grid || typeof elem != 'string') {return;}
-			if ($("#"+alertIDs.themodal).html() === null) {
-				if(!o.alerttop && !o.alertleft) {
-					if (typeof window.innerWidth != 'undefined') {
-						o.alertleft = window.innerWidth;
-						o.alerttop = window.innerHeight;
-					} else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth !== 0) {
-						o.alertleft = document.documentElement.clientWidth;
-						o.alerttop = document.documentElement.clientHeight;
-					} else {
-						o.alertleft=1024;
-						o.alerttop=768;
-					}
-					o.alertleft = o.alertleft/2 - parseInt(o.alertwidth,10)/2;
-					o.alerttop = o.alerttop/2-25;
-				}
-				$.jgrid.createModal(alertIDs,"<div>"+o.alerttext+"</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>",{gbox:"#gbox_"+$.jgrid.jqID($t.p.id),jqModal:true,drag:true,resize:true,caption:o.alertcap,top:o.alerttop,left:o.alertleft,width:o.alertwidth,height: o.alertheight,closeOnEscape:o.closeOnEscape, zIndex: o.alertzIndex},"","",true);
-			}
-			var clone = 1;
-			if(o.cloneToTop && $t.p.toppager) {clone = 2;}
-			for(var i = 0; i<clone; i++) {
-				var tbd,
-				navtbl = $("<table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table navtable' style='float:left;table-layout:auto;'><tbody><tr></tr></tbody></table>"),
-				sep = "<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>",
-				pgid, elemids;
-				if(i===0) {
-					pgid = elem;
-					elemids = $t.p.id;
-					if(pgid == $t.p.toppager) {
-						elemids += "_top";
-						clone = 1;
-					}
-				} else {
-					pgid = $t.p.toppager;
-					elemids = $t.p.id+"_top";
-				}
-				if($t.p.direction == "rtl") {$(navtbl).attr("dir","rtl").css("float","right");}
-				if (o.add) {
-					pAdd = pAdd || {};
-					tbd = $("<td class='ui-pg-button ui-corner-all'></td>");
-					$(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.addicon+"'></span>"+o.addtext+"</div>");
-					$("tr",navtbl).append(tbd);
-					$(tbd,navtbl)
-					.attr({"title":o.addtitle || "",id : pAdd.id || "add_"+elemids})
-					.click(function(){
-						if (!$(this).hasClass('ui-state-disabled')) {
-							if ($.isFunction( o.addfunc )) {
-								o.addfunc.call($t);
-							} else {
-								$($t).jqGrid("editGridRow","new",pAdd);
-							}
-						}
-						return false;
-					}).hover(
-						function () {
-							if (!$(this).hasClass('ui-state-disabled')) {
-								$(this).addClass("ui-state-hover");
-							}
-						},
-						function () {$(this).removeClass("ui-state-hover");}
-					);
-					tbd = null;
-				}
-				if (o.edit) {
-					tbd = $("<td class='ui-pg-button ui-corner-all'></td>");
-					pEdit = pEdit || {};
-					$(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.editicon+"'></span>"+o.edittext+"</div>");
-					$("tr",navtbl).append(tbd);
-					$(tbd,navtbl)
-					.attr({"title":o.edittitle || "",id: pEdit.id || "edit_"+elemids})
-					.click(function(){
-						if (!$(this).hasClass('ui-state-disabled')) {
-							var sr = $t.p.selrow;
-							if (sr) {
-								if($.isFunction( o.editfunc ) ) {
-									o.editfunc.call($t, sr);
-								} else {
-									$($t).jqGrid("editGridRow",sr,pEdit);
-								}
-							} else {
-								$.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID($t.p.id),jqm:true});
-								$("#jqg_alrt").focus();
-							}
-						}
-						return false;
-					}).hover(
-						function () {
-							if (!$(this).hasClass('ui-state-disabled')) {
-								$(this).addClass("ui-state-hover");
-							}
-						},
-						function () {$(this).removeClass("ui-state-hover");}
-					);
-					tbd = null;
-				}
-				if (o.view) {
-					tbd = $("<td class='ui-pg-button ui-corner-all'></td>");
-					pView = pView || {};
-					$(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.viewicon+"'></span>"+o.viewtext+"</div>");
-					$("tr",navtbl).append(tbd);
-					$(tbd,navtbl)
-					.attr({"title":o.viewtitle || "",id: pView.id || "view_"+elemids})
-					.click(function(){
-						if (!$(this).hasClass('ui-state-disabled')) {
-							var sr = $t.p.selrow;
-							if (sr) {
-								if($.isFunction( o.viewfunc ) ) {
-									o.viewfunc.call($t, sr);
-								} else {
-									$($t).jqGrid("viewGridRow",sr,pView);
-								}
-							} else {
-								$.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID($t.p.id),jqm:true});
-								$("#jqg_alrt").focus();
-							}
-						}
-						return false;
-					}).hover(
-						function () {
-							if (!$(this).hasClass('ui-state-disabled')) {
-								$(this).addClass("ui-state-hover");
-							}
-						},
-						function () {$(this).removeClass("ui-state-hover");}
-					);
-					tbd = null;
-				}
-				if (o.del) {
-					tbd = $("<td class='ui-pg-button ui-corner-all'></td>");
-					pDel = pDel || {};
-					$(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.delicon+"'></span>"+o.deltext+"</div>");
-					$("tr",navtbl).append(tbd);
-					$(tbd,navtbl)
-					.attr({"title":o.deltitle || "",id: pDel.id || "del_"+elemids})
-					.click(function(){
-						if (!$(this).hasClass('ui-state-disabled')) {
-							var dr;
-							if($t.p.multiselect) {
-								dr = $t.p.selarrrow;
-								if(dr.length===0) {dr = null;}
-							} else {
-								dr = $t.p.selrow;
-							}
-							if(dr){
-								if($.isFunction( o.delfunc )){
-									o.delfunc.call($t, dr);
-								}else{
-									$($t).jqGrid("delGridRow",dr,pDel);
-								}
-							} else  {
-								$.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID($t.p.id),jqm:true});$("#jqg_alrt").focus();
-							}
-						}
-						return false;
-					}).hover(
-						function () {
-							if (!$(this).hasClass('ui-state-disabled')) {
-								$(this).addClass("ui-state-hover");
-							}
-						},
-						function () {$(this).removeClass("ui-state-hover");}
-					);
-					tbd = null;
-				}
-				if(o.add || o.edit || o.del || o.view) {$("tr",navtbl).append(sep);}
-				if (o.search) {
-					tbd = $("<td class='ui-pg-button ui-corner-all'></td>");
-					pSearch = pSearch || {};
-					$(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.searchicon+"'></span>"+o.searchtext+"</div>");
-					$("tr",navtbl).append(tbd);
-					$(tbd,navtbl)
-					.attr({"title":o.searchtitle  || "",id:pSearch.id || "search_"+elemids})
-					.click(function(){
-						if (!$(this).hasClass('ui-state-disabled')) {
-							if($.isFunction( o.searchfunc )) {
-								o.searchfunc.call($t, pSearch);
-							} else {
-								$($t).jqGrid("searchGrid",pSearch);
-							}
-						}
-						return false;
-					}).hover(
-						function () {
-							if (!$(this).hasClass('ui-state-disabled')) {
-								$(this).addClass("ui-state-hover");
-							}
-						},
-						function () {$(this).removeClass("ui-state-hover");}
-					);
-					if (pSearch.showOnLoad && pSearch.showOnLoad === true) {
-						$(tbd,navtbl).click();
-					}
-					tbd = null;
-				}
-				if (o.refresh) {
-					tbd = $("<td class='ui-pg-button ui-corner-all'></td>");
-					$(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.refreshicon+"'></span>"+o.refreshtext+"</div>");
-					$("tr",navtbl).append(tbd);
-					$(tbd,navtbl)
-					.attr({"title":o.refreshtitle  || "",id: "refresh_"+elemids})
-					.click(function(){
-						if (!$(this).hasClass('ui-state-disabled')) {
-							if($.isFunction(o.beforeRefresh)) {o.beforeRefresh.call($t);}
-							$t.p.search = false;
-							try {
-								var gID = $t.p.id;
-								$t.p.postData.filters ="";
-								$("#fbox_"+$.jgrid.jqID(gID)).jqFilter('resetFilter');
-								if($.isFunction($t.clearToolbar)) {$t.clearToolbar.call($t,false);}
-							} catch (e) {}
-							switch (o.refreshstate) {
-								case 'firstpage':
-									$($t).trigger("reloadGrid", [{page:1}]);
-									break;
-								case 'current':
-									$($t).trigger("reloadGrid", [{current:true}]);
-									break;
-							}
-							if($.isFunction(o.afterRefresh)) {o.afterRefresh.call($t);}
-						}
-						return false;
-					}).hover(
-						function () {
-							if (!$(this).hasClass('ui-state-disabled')) {
-								$(this).addClass("ui-state-hover");
-							}
-						},
-						function () {$(this).removeClass("ui-state-hover");}
-					);
-					tbd = null;
-				}
-				tdw = $(".ui-jqgrid").css("font-size") || "11px";
-				$('body').append("<div id='testpg2' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:"+tdw+";visibility:hidden;' ></div>");
-				twd = $(navtbl).clone().appendTo("#testpg2").width();
-				$("#testpg2").remove();
-				$(pgid+"_"+o.position,pgid).append(navtbl);
-				if($t.p._nvtd) {
-					if(twd > $t.p._nvtd[0] ) {
-						$(pgid+"_"+o.position,pgid).width(twd);
-						$t.p._nvtd[0] = twd;
-					}
-					$t.p._nvtd[1] = twd;
-				}
-				tdw =null;twd=null;navtbl =null;
-				this.nav = true;
-			}
-		});
-	},
-	navButtonAdd : function (elem, p) {
-		p = $.extend({
-			caption : "newButton",
-			title: '',
-			buttonicon : 'ui-icon-newwin',
-			onClickButton: null,
-			position : "last",
-			cursor : 'pointer'
-		}, p ||{});
-		return this.each(function() {
-			if( !this.grid)  {return;}
-			if( typeof elem === "string" && elem.indexOf("#") !== 0) {elem = "#"+$.jgrid.jqID(elem);}
-			var findnav = $(".navtable",elem)[0], $t = this;
-			if (findnav) {
-				if( p.id && $("#"+$.jgrid.jqID(p.id), findnav).html() !== null )  {return;}
-				var tbd = $("<td></td>");
-				if(p.buttonicon.toString().toUpperCase() == "NONE") {
-                    $(tbd).addClass('ui-pg-button ui-corner-all').append("<div class='ui-pg-div'>"+p.caption+"</div>");
-				} else	{
-					$(tbd).addClass('ui-pg-button ui-corner-all').append("<div class='ui-pg-div'><span class='ui-icon "+p.buttonicon+"'></span>"+p.caption+"</div>");
-				}
-				if(p.id) {$(tbd).attr("id",p.id);}
-				if(p.position=='first'){
-					if(findnav.rows[0].cells.length ===0 ) {
-						$("tr",findnav).append(tbd);
-					} else {
-						$("tr td:eq(0)",findnav).before(tbd);
-					}
-				} else {
-					$("tr",findnav).append(tbd);
-				}
-				$(tbd,findnav)
-				.attr("title",p.title  || "")
-				.click(function(e){
-					if (!$(this).hasClass('ui-state-disabled')) {
-						if ($.isFunction(p.onClickButton) ) {p.onClickButton.call($t,e);}
-					}
-					return false;
-				})
-				.hover(
-					function () {
-						if (!$(this).hasClass('ui-state-disabled')) {
-							$(this).addClass('ui-state-hover');
-						}
-					},
-					function () {$(this).removeClass("ui-state-hover");}
-				);
-			}
-		});
-	},
-	navSeparatorAdd:function (elem,p) {
-		p = $.extend({
-			sepclass : "ui-separator",
-			sepcontent: ''
-		}, p ||{});
-		return this.each(function() {
-			if( !this.grid)  {return;}
-			if( typeof elem === "string" && elem.indexOf("#") !== 0) {elem = "#"+$.jgrid.jqID(elem);}
-			var findnav = $(".navtable",elem)[0];
-			if(findnav) {
-				var sep = "<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='"+p.sepclass+"'></span>"+p.sepcontent+"</td>";
-				$("tr",findnav).append(sep);
-			}
-		});
-	},
-	GridToForm : function( rowid, formid ) {
-		return this.each(function(){
-			var $t = this;
-			if (!$t.grid) {return;}
-			var rowdata = $($t).jqGrid("getRowData",rowid);
-			if (rowdata) {
-				for(var i in rowdata) {
-					if ( $("[name="+$.jgrid.jqID(i)+"]",formid).is("input:radio") || $("[name="+$.jgrid.jqID(i)+"]",formid).is("input:checkbox"))  {
-						$("[name="+$.jgrid.jqID(i)+"]",formid).each( function() {
-							if( $(this).val() == rowdata[i] ) {
-								$(this)[$t.p.useProp ? 'prop': 'attr']("checked",true);
-							} else {
-								$(this)[$t.p.useProp ? 'prop': 'attr']("checked", false);
-							}
-						});
-					} else {
-					// this is very slow on big table and form.
-						$("[name="+$.jgrid.jqID(i)+"]",formid).val(rowdata[i]);
-					}
-				}
-			}
-		});
-	},
-	FormToGrid : function(rowid, formid, mode, position){
-		return this.each(function() {
-			var $t = this;
-			if(!$t.grid) {return;}
-			if(!mode) {mode = 'set';}
-			if(!position) {position = 'first';}
-			var fields = $(formid).serializeArray();
-			var griddata = {};
-			$.each(fields, function(i, field){
-				griddata[field.name] = field.value;
-			});
-			if(mode=='add') {$($t).jqGrid("addRowData",rowid,griddata, position);}
-			else if(mode=='set') {$($t).jqGrid("setRowData",rowid,griddata);}
-		});
-	}
-});
-})(jQuery);
-;(function($){
-/**
- * jqGrid extension for manipulating Grid Data
- * Tony Tomov tony@trirand.com
- * http://trirand.com/blog/
- * Dual licensed under the MIT and GPL licenses:
- * http://www.opensource.org/licenses/mit-license.php
- * http://www.gnu.org/licenses/gpl-2.0.html
-**/
-//jsHint options
-/*global alert, $, jQuery */
-"use strict";
-$.jgrid.inlineEdit = $.jgrid.inlineEdit || {};
-$.jgrid.extend({
-//Editing
-	editRow : function(rowid,keys,oneditfunc,successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc) {
-		// Compatible mode old versions
-		var o={}, args = $.makeArray(arguments).slice(1);
-
-		if( $.type(args[0]) === "object" ) {
-			o = args[0];
-		} else {
-			if (typeof keys !== "undefined") { o.keys = keys; }
-			if ($.isFunction(oneditfunc)) { o.oneditfunc = oneditfunc; }
-			if ($.isFunction(successfunc)) { o.successfunc = successfunc; }
-			if (typeof url !== "undefined") { o.url = url; }
-			if (typeof extraparam !== "undefined") { o.extraparam = extraparam; }
-			if ($.isFunction(aftersavefunc)) { o.aftersavefunc = aftersavefunc; }
-			if ($.isFunction(errorfunc)) { o.errorfunc = errorfunc; }
-			if ($.isFunction(afterrestorefunc)) { o.afterrestorefunc = afterrestorefunc; }
-			// last two not as param, but as object (sorry)
-			//if (typeof restoreAfterError !== "undefined") { o.restoreAfterError = restoreAfterError; }
-			//if (typeof mtype !== "undefined") { o.mtype = mtype || "POST"; }
-		}
-		o = $.extend(true, {
-			keys : false,
-			oneditfunc: null,
-			successfunc: null,
-			url: null,
-			extraparam: {},
-			aftersavefunc: null,
-			errorfunc: null,
-			afterrestorefunc: null,
-			restoreAfterError: true,
-			mtype: "POST"
-		}, $.jgrid.inlineEdit, o );
-
-		// End compatible
-		return this.each(function(){
-			var $t = this, nm, tmp, editable, cnt=0, focus=null, svr={}, ind,cm;
-			if (!$t.grid ) { return; }
-			ind = $($t).jqGrid("getInd",rowid,true);
-			if( ind === false ) {return;}
-			editable = $(ind).attr("editable") || "0";
-			if (editable == "0" && !$(ind).hasClass("not-editable-row")) {
-				cm = $t.p.colModel;
-				$('td[role="gridcell"]',ind).each( function(i) {
-					nm = cm[i].name;
-					var treeg = $t.p.treeGrid===true && nm == $t.p.ExpandColumn;
-					if(treeg) { tmp = $("span:first",this).html();}
-					else {
-						try {
-							tmp = $.unformat.call($t,this,{rowId:rowid, colModel:cm[i]},i);
-						} catch (_) {
-							tmp =  ( cm[i].edittype && cm[i].edittype == 'textarea' ) ? $(this).text() : $(this).html();
-						}
-					}
-					if ( nm != 'cb' && nm != 'subgrid' && nm != 'rn') {
-						if($t.p.autoencode) { tmp = $.jgrid.htmlDecode(tmp); }
-						svr[nm]=tmp;
-						if(cm[i].editable===true) {
-							if(focus===null) { focus = i; }
-							if (treeg) { $("span:first",this).html(""); }
-							else { $(this).html(""); }
-							var opt = $.extend({},cm[i].editoptions || {},{id:rowid+"_"+nm,name:nm});
-							if(!cm[i].edittype) { cm[i].edittype = "text"; }
-							if(tmp == "&nbsp;" || tmp == "&#160;" || (tmp.length==1 && tmp.charCodeAt(0)==160) ) {tmp='';}
-							var elc = $.jgrid.createEl.call($t,cm[i].edittype,opt,tmp,true,$.extend({},$.jgrid.ajaxOptions,$t.p.ajaxSelectOptions || {}));
-							$(elc).addClass("editable");
-							if(treeg) { $("span:first",this).append(elc); }
-							else { $(this).append(elc); }
-							//Again IE
-							if(cm[i].edittype == "select" && typeof(cm[i].editoptions)!=="undefined" && cm[i].editoptions.multiple===true  && typeof(cm[i].editoptions.dataUrl)==="undefined" && $.browser.msie) {
-								$(elc).width($(elc).width());
-							}
-							cnt++;
-						}
-					}
-				});
-				if(cnt > 0) {
-					svr.id = rowid; $t.p.savedRow.push(svr);
-					$(ind).attr("editable","1");
-					$("td:eq("+focus+") input",ind).focus();
-					if(o.keys===true) {
-						$(ind).bind("keydown",function(e) {
-							if (e.keyCode === 27) {
-								$($t).jqGrid("restoreRow",rowid, o.afterrestorefunc);
-								if($t.p._inlinenav) {
-									try {
-										$($t).jqGrid('showAddEditButtons');
-									} catch (eer1) {}
-								}
-								return false;
-							}
-							if (e.keyCode === 13) {
-								var ta = e.target;
-								if(ta.tagName == 'TEXTAREA') { return true; }
-								if( $($t).jqGrid("saveRow", rowid, o ) ) {
-									if($t.p._inlinenav) {
-										try {
-											$($t).jqGrid('showAddEditButtons');
-										} catch (eer2) {}
-									}
-								}
-								return false;
-							}
-						});
-					}
-					$($t).triggerHandler("jqGridInlineEditRow", [rowid, o]);
-					if( $.isFunction(o.oneditfunc)) { o.oneditfunc.call($t, rowid); }
-				}
-			}
-		});
-	},
-	saveRow : function(rowid, successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc) {
-		// Compatible mode old versions
-		var args = $.makeArray(arguments).slice(1), o = {};
-
-		if( $.type(args[0]) === "object" ) {
-			o = args[0];
-		} else {
-			if ($.isFunction(successfunc)) { o.successfunc = successfunc; }
-			if (typeof url !== "undefined") { o.url = url; }
-			if (typeof extraparam !== "undefined") { o.extraparam = extraparam; }
-			if ($.isFunction(aftersavefunc)) { o.aftersavefunc = aftersavefunc; }
-			if ($.isFunction(errorfunc)) { o.errorfunc = errorfunc; }
-			if ($.isFunction(afterrestorefunc)) { o.afterrestorefunc = afterrestorefunc; }
-		}
-		o = $.extend(true, {
-			successfunc: null,
-			url: null,
-			extraparam: {},
-			aftersavefunc: null,
-			errorfunc: null,
-			afterrestorefunc: null,
-			restoreAfterError: true,
-			mtype: "POST"
-		}, $.jgrid.inlineEdit, o );
-		// End compatible
-
-		var success = false;
-		var $t = this[0], nm, tmp={}, tmp2={}, tmp3= {}, editable, fr, cv, ind;
-		if (!$t.grid ) { return success; }
-		ind = $($t).jqGrid("getInd",rowid,true);
-		if(ind === false) {return success;}
-		editable = $(ind).attr("editable");
-		o.url = o.url ? o.url : $t.p.editurl;
-		if (editable==="1") {
-			var cm;
-			$('td[role="gridcell"]',ind).each(function(i) {
-				cm = $t.p.colModel[i];
-				nm = cm.name;
-				if ( nm != 'cb' && nm != 'subgrid' && cm.editable===true && nm != 'rn' && !$(this).hasClass('not-editable-cell')) {
-					switch (cm.edittype) {
-						case "checkbox":
-							var cbv = ["Yes","No"];
-							if(cm.editoptions ) {
-								cbv = cm.editoptions.value.split(":");
-							}
-							tmp[nm]=  $("input",this).is(":checked") ? cbv[0] : cbv[1];
-							break;
-						case 'text':
-						case 'password':
-						case 'textarea':
-						case "button" :
-							tmp[nm]=$("input, textarea",this).val();
-							break;
-						case 'select':
-							if(!cm.editoptions.multiple) {
-								tmp[nm] = $("select option:selected",this).val();
-								tmp2[nm] = $("select option:selected", this).text();
-							} else {
-								var sel = $("select",this), selectedText = [];
-								tmp[nm] = $(sel).val();
-								if(tmp[nm]) { tmp[nm]= tmp[nm].join(","); } else { tmp[nm] =""; }
-								$("select option:selected",this).each(
-									function(i,selected){
-										selectedText[i] = $(selected).text();
-									}
-								);
-								tmp2[nm] = selectedText.join(",");
-							}
-							if(cm.formatter && cm.formatter == 'select') { tmp2={}; }
-							break;
-						case 'custom' :
-							try {
-								if(cm.editoptions && $.isFunction(cm.editoptions.custom_value)) {
-									tmp[nm] = cm.editoptions.custom_value.call($t, $(".customelement",this),'get');
-									if (tmp[nm] === undefined) { throw "e2"; }
-								} else { throw "e1"; }
-							} catch (e) {
-								if (e=="e1") { $.jgrid.info_dialog($.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.nodefined,$.jgrid.edit.bClose); }
-								if (e=="e2") { $.jgrid.info_dialog($.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.novalue,$.jgrid.edit.bClose); }
-								else { $.jgrid.info_dialog($.jgrid.errors.errcap,e.message,$.jgrid.edit.bClose); }
-							}
-							break;
-					}
-					cv = $.jgrid.checkValues(tmp[nm],i,$t);
-					if(cv[0] === false) {
-						cv[1] = tmp[nm] + " " + cv[1];
-						return false;
-					}
-					if($t.p.autoencode) { tmp[nm] = $.jgrid.htmlEncode(tmp[nm]); }
-					if(o.url !== 'clientArray' && cm.editoptions && cm.editoptions.NullIfEmpty === true) {
-						if(tmp[nm] === "") {
-							tmp3[nm] = 'null';
-						}
-					}
-				}
-			});
-			if (cv[0] === false){
-				try {
-					var positions = $.jgrid.findPos($("#"+$.jgrid.jqID(rowid), $t.grid.bDiv)[0]);
-					$.jgrid.info_dialog($.jgrid.errors.errcap,cv[1],$.jgrid.edit.bClose,{left:positions[0],top:positions[1]});
-				} catch (e) {
-					alert(cv[1]);
-				}
-				return success;
-			}
-			var idname, opers, oper;
-			opers = $t.p.prmNames;
-			oper = opers.oper;
-			idname = opers.id;
-			if(tmp) {
-				tmp[oper] = opers.editoper;
-				tmp[idname] = rowid;
-				if(typeof($t.p.inlineData) == 'undefined') { $t.p.inlineData ={}; }
-				tmp = $.extend({},tmp,$t.p.inlineData,o.extraparam);
-			}
-			if (o.url == 'clientArray') {
-				tmp = $.extend({},tmp, tmp2);
-				if($t.p.autoencode) {
-					$.each(tmp,function(n,v){
-						tmp[n] = $.jgrid.htmlDecode(v);
-					});
-				}
-				var resp = $($t).jqGrid("setRowData",rowid,tmp);
-				$(ind).attr("editable","0");
-				for( var k=0;k<$t.p.savedRow.length;k++) {
-					if( $t.p.savedRow[k].id == rowid) {fr = k; break;}
-				}
-				if(fr >= 0) { $t.p.savedRow.splice(fr,1); }
-				$($t).triggerHandler("jqGridInlineAfterSaveRow", [rowid, resp, tmp, o]);
-				if( $.isFunction(o.aftersavefunc) ) { o.aftersavefunc.call($t, rowid,resp); }
-				success = true;
-				$(ind).unbind("keydown");
-			} else {
-				$("#lui_"+$.jgrid.jqID($t.p.id)).show();
-				tmp3 = $.extend({},tmp,tmp3);
-				tmp3[idname] = $.jgrid.stripPref($t.p.idPrefix, tmp3[idname]);
-				$.ajax($.extend({
-					url:o.url,
-					data: $.isFunction($t.p.serializeRowData) ? $t.p.serializeRowData.call($t, tmp3) : tmp3,
-					type: o.mtype,
-					async : false, //?!?
-					complete: function(res,stat){
-						$("#lui_"+$.jgrid.jqID($t.p.id)).hide();
-						if (stat === "success"){
-							var ret = true, sucret;
-							sucret = $($t).triggerHandler("jqGridInlineSuccessSaveRow", [res, rowid, o]);
-							if (!$.isArray(sucret)) {sucret = [true, tmp];}
-							if (sucret[0] && $.isFunction(o.successfunc)) {sucret = o.successfunc.call($t, res);}
-							if($.isArray(sucret)) {
-								// expect array - status, data, rowid
-								ret = sucret[0];
-								tmp = sucret[1] ? sucret[1] : tmp;
-							} else {
-								ret = sucret;
-							}
-							if (ret===true) {
-								if($t.p.autoencode) {
-									$.each(tmp,function(n,v){
-										tmp[n] = $.jgrid.htmlDecode(v);
-									});
-								}
-								tmp = $.extend({},tmp, tmp2);
-								$($t).jqGrid("setRowData",rowid,tmp);
-								$(ind).attr("editable","0");
-								for( var k=0;k<$t.p.savedRow.length;k++) {
-									if( $t.p.savedRow[k].id == rowid) {fr = k; break;}
-								}
-								if(fr >= 0) { $t.p.savedRow.splice(fr,1); }
-								$($t).triggerHandler("jqGridInlineAfterSaveRow", [rowid, res, tmp, o]);
-								if( $.isFunction(o.aftersavefunc) ) { o.aftersavefunc.call($t, rowid,res); }
-								success = true;
-								$(ind).unbind("keydown");
-							} else {
-								$($t).triggerHandler("jqGridInlineErrorSaveRow", [rowid, res, stat, null, o]);
-								if($.isFunction(o.errorfunc) ) {
-									o.errorfunc.call($t, rowid, res, stat, null);
-								}
-								if(o.restoreAfterError === true) {
-									$($t).jqGrid("restoreRow",rowid, o.afterrestorefunc);
-								}
-							}
-						}
-					},
-					error:function(res,stat,err){
-						$("#lui_"+$.jgrid.jqID($t.p.id)).hide();
-						$($t).triggerHandler("jqGridInlineErrorSaveRow", [rowid, res, stat, err, o]);
-						if($.isFunction(o.errorfunc) ) {
-							o.errorfunc.call($t, rowid, res, stat, err);
-						} else {
-							try {
-								$.jgrid.info_dialog($.jgrid.errors.errcap,'<div class="ui-state-error">'+ res.responseText +'</div>', $.jgrid.edit.bClose,{buttonalign:'right'});
-							} catch(e) {
-								alert(res.responseText);
-							}
-						}
-						if(o.restoreAfterError === true) {
-							$($t).jqGrid("restoreRow",rowid, o.afterrestorefunc);
-						}
-					}
-				}, $.jgrid.ajaxOptions, $t.p.ajaxRowOptions || {}));
-			}
-		}
-		return success;
-	},
-	restoreRow : function(rowid, afterrestorefunc) {
-		// Compatible mode old versions
-		var args = $.makeArray(arguments).slice(1), o={};
-
-		if( $.type(args[0]) === "object" ) {
-			o = args[0];
-		} else {
-			if ($.isFunction(afterrestorefunc)) { o.afterrestorefunc = afterrestorefunc; }
-		}
-		o = $.extend(true, $.jgrid.inlineEdit, o );
-
-		// End compatible
-
-		return this.each(function(){
-			var $t= this, fr, ind, ares={};
-			if (!$t.grid ) { return; }
-			ind = $($t).jqGrid("getInd",rowid,true);
-			if(ind === false) {return;}
-			for( var k=0;k<$t.p.savedRow.length;k++) {
-				if( $t.p.savedRow[k].id == rowid) {fr = k; break;}
-			}
-			if(fr >= 0) {
-				if($.isFunction($.fn.datepicker)) {
-					try {
-						$("input.hasDatepicker","#"+$.jgrid.jqID(ind.id)).datepicker('hide');
-					} catch (e) {}
-				}
-				$.each($t.p.colModel, function(){
-					if(this.editable === true && this.name in $t.p.savedRow[fr] ) {
-						ares[this.name] = $t.p.savedRow[fr][this.name];
-					}
-				});
-				$($t).jqGrid("setRowData",rowid,ares);
-				$(ind).attr("editable","0").unbind("keydown");
-				$t.p.savedRow.splice(fr,1);
-				if($("#"+$.jgrid.jqID(rowid), "#"+$.jgrid.jqID($t.p.id)).hasClass("jqgrid-new-row")){
-					setTimeout(function(){$($t).jqGrid("delRowData",rowid);},0);
-				}
-			}
-			$($t).triggerHandler("jqGridInlineAfterRestoreRow", [rowid]);
-			if ($.isFunction(o.afterrestorefunc))
-			{
-				o.afterrestorefunc.call($t, rowid);
-			}
-		});
-	},
-	addRow : function ( p ) {
-		p = $.extend(true, {
-			rowID : "new_row",
-			initdata : {},
-			position :"first",
-			useDefValues : true,
-			useFormatter : false,
-			addRowParams : {extraparam:{}}
-		},p  || {});
-		return this.each(function(){
-			if (!this.grid ) { return; }
-			var $t = this;
-			if(p.useDefValues === true) {
-				$($t.p.colModel).each(function(){
-					if( this.editoptions && this.editoptions.defaultValue ) {
-						var opt = this.editoptions.defaultValue,
-						tmp = $.isFunction(opt) ? opt.call($t) : opt;
-						p.initdata[this.name] = tmp;
-					}
-				});
-			}
-			$($t).jqGrid('addRowData', p.rowID, p.initdata, p.position);
-			p.rowID = $t.p.idPrefix + p.rowID;
-			$("#"+$.jgrid.jqID(p.rowID), "#"+$.jgrid.jqID($t.p.id)).addClass("jqgrid-new-row");
-			if(p.useFormatter) {
-				$("#"+$.jgrid.jqID(p.rowID)+" .ui-inline-edit", "#"+$.jgrid.jqID($t.p.id)).click();
-			} else {
-				var opers = $t.p.prmNames,
-				oper = opers.oper;
-				p.addRowParams.extraparam[oper] = opers.addoper;
-				$($t).jqGrid('editRow', p.rowID, p.addRowParams);
-				$($t).jqGrid('setSelection', p.rowID);
-			}
-		});
-	},
-	inlineNav : function (elem, o) {
-		o = $.extend({
-			edit: true,
-			editicon: "ui-icon-pencil",
-			add: true,
-			addicon:"ui-icon-plus",
-			save: true,
-			saveicon:"ui-icon-disk",
-			cancel: true,
-			cancelicon:"ui-icon-cancel",
-			addParams : {useFormatter : false,rowID : "new_row"},
-			editParams : {},
-			restoreAfterSelect : true
-		}, $.jgrid.nav, o ||{});
-		return this.each(function(){
-			if (!this.grid ) { return; }
-			var $t = this, onSelect, gID = $.jgrid.jqID($t.p.id);
-			$t.p._inlinenav = true;
-			// detect the formatactions column
-			if(o.addParams.useFormatter === true) {
-				var cm = $t.p.colModel,i;
-				for (i = 0; i<cm.length; i++) {
-					if(cm[i].formatter && cm[i].formatter === "actions" ) {
-						if(cm[i].formatoptions) {
-							var defaults =  {
-								keys:false,
-								onEdit : null,
-								onSuccess: null,
-								afterSave:null,
-								onError: null,
-								afterRestore: null,
-								extraparam: {},
-								url: null
-							},
-							ap = $.extend( defaults, cm[i].formatoptions );
-							o.addParams.addRowParams = {
-								"keys" : ap.keys,
-								"oneditfunc" : ap.onEdit,
-								"successfunc" : ap.onSuccess,
-								"url" : ap.url,
-								"extraparam" : ap.extraparam,
-								"aftersavefunc" : ap.afterSavef,
-								"errorfunc": ap.onError,
-								"afterrestorefunc" : ap.afterRestore
-							};
-						}
-						break;
-					}
-				}
-			}
-			if(o.add) {
-				$($t).jqGrid('navButtonAdd', elem,{
-					caption : o.addtext,
-					title : o.addtitle,
-					buttonicon : o.addicon,
-					id : $t.p.id+"_iladd",
-					onClickButton : function () {
-						$($t).jqGrid('addRow', o.addParams);
-						if(!o.addParams.useFormatter) {
-							$("#"+gID+"_ilsave").removeClass('ui-state-disabled');
-							$("#"+gID+"_ilcancel").removeClass('ui-state-disabled');
-							$("#"+gID+"_iladd").addClass('ui-state-disabled');
-							$("#"+gID+"_iledit").addClass('ui-state-disabled');
-						}
-					}
-				});
-			}
-			if(o.edit) {
-				$($t).jqGrid('navButtonAdd', elem,{
-					caption : o.edittext,
-					title : o.edittitle,
-					buttonicon : o.editicon,
-					id : $t.p.id+"_iledit",
-					onClickButton : function () {
-						var sr = $($t).jqGrid('getGridParam','selrow');
-						if(sr) {
-							$($t).jqGrid('editRow', sr, o.editParams);
-							$("#"+gID+"_ilsave").removeClass('ui-state-disabled');
-							$("#"+gID+"_ilcancel").removeClass('ui-state-disabled');
-							$("#"+gID+"_iladd").addClass('ui-state-disabled');
-							$("#"+gID+"_iledit").addClass('ui-state-disabled');
-						} else {
-							$.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+gID,jqm:true});$("#jqg_alrt").focus();
-						}
-					}
-				});
-			}
-			if(o.save) {
-				$($t).jqGrid('navButtonAdd', elem,{
-					caption : o.savetext || '',
-					title : o.savetitle || 'Save row',
-					buttonicon : o.saveicon,
-					id : $t.p.id+"_ilsave",
-					onClickButton : function () {
-						var sr = $t.p.savedRow[0].id;
-						if(sr) {
-							var opers = $t.p.prmNames,
-							oper = opers.oper;
-							if(!o.editParams.extraparam) {
-								o.editParams.extraparam = {};
-							}
-							if($("#"+$.jgrid.jqID(sr), "#"+gID ).hasClass("jqgrid-new-row")) {
-								o.editParams.extraparam[oper] = opers.addoper;
-							} else {
-								o.editParams.extraparam[oper] = opers.editoper;
-							}
-							if( $($t).jqGrid('saveRow', sr, o.editParams) ) {
-								$($t).jqGrid('showAddEditButtons');
-							}
-						} else {
-							$.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+gID,jqm:true});$("#jqg_alrt").focus();
-						}
-					}
-				});
-				$("#"+gID+"_ilsave").addClass('ui-state-disabled');
-			}
-			if(o.cancel) {
-				$($t).jqGrid('navButtonAdd', elem,{
-					caption : o.canceltext || '',
-					title : o.canceltitle || 'Cancel row editing',
-					buttonicon : o.cancelicon,
-					id : $t.p.id+"_ilcancel",
-					onClickButton : function () {
-						var sr = $t.p.savedRow[0].id;
-						if(sr) {
-							$($t).jqGrid('restoreRow', sr, o.editParams);
-							$($t).jqGrid('showAddEditButtons');
-						} else {
-							$.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+gID,jqm:true});$("#jqg_alrt").focus();
-						}
-					}
-				});
-				$("#"+gID+"_ilcancel").addClass('ui-state-disabled');
-			}
-			if(o.restoreAfterSelect === true) {
-				if($.isFunction($t.p.beforeSelectRow)) {
-					onSelect = $t.p.beforeSelectRow;
-				} else {
-					onSelect =  false;
-				}
-				$t.p.beforeSelectRow = function(id, stat) {
-					var ret = true;
-					if($t.p.savedRow.length > 0 && $t.p._inlinenav===true && ( id !== $t.p.selrow && $t.p.selrow !==null) ) {
-						if($t.p.selrow == o.addParams.rowID ) {
-							$($t).jqGrid('delRowData', $t.p.selrow);
-						} else {
-							$($t).jqGrid('restoreRow', $t.p.selrow, o.editParams);
-						}
-						$($t).jqGrid('showAddEditButtons');
-					}
-					if(onSelect) {
-						ret = onSelect.call($t, id, stat);
-					}
-					return ret;
-				};
-			}
-
-		});
-	},
-	showAddEditButtons : function()  {
-		return this.each(function(){
-			if (!this.grid ) { return; }
-			var gID = $.jgrid.jqID(this.p.id);
-			$("#"+gID+"_ilsave").addClass('ui-state-disabled');
-			$("#"+gID+"_ilcancel").addClass('ui-state-disabled');
-			$("#"+gID+"_iladd").removeClass('ui-state-disabled');
-			$("#"+gID+"_iledit").removeClass('ui-state-disabled');
-		});
-	}
-//end inline edit
-});
-})(jQuery);
-;(function($){
-/*
-**
- * jqGrid extension for cellediting Grid Data
- * Tony Tomov tony@trirand.com
- * http://trirand.com/blog/
- * Dual licensed under the MIT and GPL licenses:
- * http://www.opensource.org/licenses/mit-license.php
- * http://www.gnu.org/licenses/gpl-2.0.html
-**/
-/**
- * all events and options here are aded anonynous and not in the base grid
- * since the array is to big. Here is the order of execution.
- * From this point we use jQuery isFunction
- * formatCell
- * beforeEditCell,
- * onSelectCell (used only for noneditable cels)
- * afterEditCell,
-
- * beforeSaveCell, (called before validation of values if any)
- * beforeSubmitCell (if cellsubmit remote (ajax))
- * afterSubmitCell(if cellsubmit remote (ajax)),
- * afterSaveCell,
- * errorCell,
- * serializeCellData - new
- * Options
- * cellsubmit (remote,clientArray) (added in grid options)
- * cellurl
- * ajaxCellOptions
-* */
-"use strict";
-$.jgrid.extend({
-	editCell : function (iRow,iCol, ed){
-		return this.each(function (){
-			var $t = this, nm, tmp,cc, cm;
-			if (!$t.grid || $t.p.cellEdit !== true) {return;}
-			iCol = parseInt(iCol,10);
-			// select the row that can be used for other methods
-			$t.p.selrow = $t.rows[iRow].id;
-			if (!$t.p.knv) {$($t).jqGrid("GridNav");}
-			// check to see if we have already edited cell
-			if ($t.p.savedRow.length>0) {
-				// prevent second click on that field and enable selects
-				if (ed===true ) {
-					if(iRow == $t.p.iRow && iCol == $t.p.iCol){
-						return;
-					}
-				}
-				// save the cell
-				$($t).jqGrid("saveCell",$t.p.savedRow[0].id,$t.p.savedRow[0].ic);
-			} else {
-				window.setTimeout(function () { $("#"+$.jgrid.jqID($t.p.knv)).attr("tabindex","-1").focus();},0);
-			}
-			cm = $t.p.colModel[iCol];
-			nm = cm.name;
-			if (nm=='subgrid' || nm=='cb' || nm=='rn') {return;}
-			cc = $("td:eq("+iCol+")",$t.rows[iRow]);
-			if (cm.editable===true && ed===true && !cc.hasClass("not-editable-cell")) {
-				if(parseInt($t.p.iCol,10)>=0  && parseInt($t.p.iRow,10)>=0) {
-					$("td:eq("+$t.p.iCol+")",$t.rows[$t.p.iRow]).removeClass("edit-cell ui-state-highlight");
-					$($t.rows[$t.p.iRow]).removeClass("selected-row ui-state-hover");
-				}
-				$(cc).addClass("edit-cell ui-state-highlight");
-				$($t.rows[iRow]).addClass("selected-row ui-state-hover");
-				try {
-					tmp =  $.unformat.call($t,cc,{rowId: $t.rows[iRow].id, colModel:cm},iCol);
-				} catch (_) {
-					tmp = ( cm.edittype && cm.edittype == 'textarea' ) ? $(cc).text() : $(cc).html();
-				}
-				if($t.p.autoencode) { tmp = $.jgrid.htmlDecode(tmp); }
-				if (!cm.edittype) {cm.edittype = "text";}
-				$t.p.savedRow.push({id:iRow,ic:iCol,name:nm,v:tmp});
-				if(tmp === "&nbsp;" || tmp === "&#160;" || (tmp.length===1 && tmp.charCodeAt(0)===160) ) {tmp='';}
-				if($.isFunction($t.p.formatCell)) {
-					var tmp2 = $t.p.formatCell.call($t, $t.rows[iRow].id,nm,tmp,iRow,iCol);
-					if(tmp2 !== undefined ) {tmp = tmp2;}
-				}
-				var opt = $.extend({}, cm.editoptions || {} ,{id:iRow+"_"+nm,name:nm});
-				var elc = $.jgrid.createEl.call($t,cm.edittype,opt,tmp,true,$.extend({},$.jgrid.ajaxOptions,$t.p.ajaxSelectOptions || {}));
-				$($t).triggerHandler("jqGridBeforeEditCell", [$t.rows[iRow].id, nm, tmp, iRow, iCol]);
-				if ($.isFunction($t.p.beforeEditCell)) {
-					$t.p.beforeEditCell.call($t, $t.rows[iRow].id,nm,tmp,iRow,iCol);
-				}
-				$(cc).html("").append(elc).attr("tabindex","0");
-				window.setTimeout(function () { $(elc).focus();},0);
-				$("input, select, textarea",cc).bind("keydown",function(e) {
-					if (e.keyCode === 27) {
-						if($("input.hasDatepicker",cc).length >0) {
-							if( $(".ui-datepicker").is(":hidden") )  { $($t).jqGrid("restoreCell",iRow,iCol); }
-							else { $("input.hasDatepicker",cc).datepicker('hide'); }
-						} else {
-							$($t).jqGrid("restoreCell",iRow,iCol);
-						}
-					} //ESC
-					if (e.keyCode === 13) {
-						$($t).jqGrid("saveCell",iRow,iCol);
-						// Prevent default action
-						return false;
-					} //Enter
-					if (e.keyCode === 9)  {
-						if(!$t.grid.hDiv.loading ) {
-							if (e.shiftKey) {$($t).jqGrid("prevCell",iRow,iCol);} //Shift TAb
-							else {$($t).jqGrid("nextCell",iRow,iCol);} //Tab
-						} else {
-							return false;
-						}
-					}
-					e.stopPropagation();
-				});
-				$($t).triggerHandler("jqGridAfterEditCell", [$t.rows[iRow].id, nm, tmp, iRow, iCol]);
-				if ($.isFunction($t.p.afterEditCell)) {
-					$t.p.afterEditCell.call($t, $t.rows[iRow].id,nm,tmp,iRow,iCol);
-				}
-			} else {
-				if (parseInt($t.p.iCol,10)>=0  && parseInt($t.p.iRow,10)>=0) {
-					$("td:eq("+$t.p.iCol+")",$t.rows[$t.p.iRow]).removeClass("edit-cell ui-state-highlight");
-					$($t.rows[$t.p.iRow]).removeClass("selected-row ui-state-hover");
-				}
-				cc.addClass("edit-cell ui-state-highlight");
-				$($t.rows[iRow]).addClass("selected-row ui-state-hover");
-				tmp = cc.html().replace(/\&#160\;/ig,'');
-				$($t).triggerHandler("jqGridSelectCell", [$t.rows[iRow].id, nm, tmp, iRow, iCol]);
-				if ($.isFunction($t.p.onSelectCell)) {
-					$t.p.onSelectCell.call($t, $t.rows[iRow].id,nm,tmp,iRow,iCol);
-				}
-			}
-			$t.p.iCol = iCol; $t.p.iRow = iRow;
-		});
-	},
-	saveCell : function (iRow, iCol){
-		return this.each(function(){
-			var $t= this, fr;
-			if (!$t.grid || $t.p.cellEdit !== true) {return;}
-			if ( $t.p.savedRow.length >= 1) {fr = 0;} else {fr=null;}
-			if(fr !== null) {
-				var cc = $("td:eq("+iCol+")",$t.rows[iRow]),v,v2,
-				cm = $t.p.colModel[iCol], nm = cm.name, nmjq = $.jgrid.jqID(nm) ;
-				switch (cm.edittype) {
-					case "select":
-						if(!cm.editoptions.multiple) {
-							v = $("#"+iRow+"_"+nmjq+" option:selected",$t.rows[iRow]).val();
-							v2 = $("#"+iRow+"_"+nmjq+" option:selected",$t.rows[iRow]).text();
-						} else {
-							var sel = $("#"+iRow+"_"+nmjq,$t.rows[iRow]), selectedText = [];
-							v = $(sel).val();
-							if(v) { v.join(",");} else { v=""; }
-							$("option:selected",sel).each(
-								function(i,selected){
-									selectedText[i] = $(selected).text();
-								}
-							);
-							v2 = selectedText.join(",");
-						}
-						if(cm.formatter) { v2 = v; }
-						break;
-					case "checkbox":
-						var cbv  = ["Yes","No"];
-						if(cm.editoptions){
-							cbv = cm.editoptions.value.split(":");
-						}
-						v = $("#"+iRow+"_"+nmjq,$t.rows[iRow]).is(":checked") ? cbv[0] : cbv[1];
-						v2=v;
-						break;
-					case "password":
-					case "text":
-					case "textarea":
-					case "button" :
-						v = $("#"+iRow+"_"+nmjq,$t.rows[iRow]).val();
-						v2=v;
-						break;
-					case 'custom' :
-						try {
-							if(cm.editoptions && $.isFunction(cm.editoptions.custom_value)) {
-								v = cm.editoptions.custom_value.call($t, $(".customelement",cc),'get');
-								if (v===undefined) { throw "e2";} else { v2=v; }
-							} else { throw "e1"; }
-						} catch (e) {
-							if (e=="e1") { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.nodefined,jQuery.jgrid.edit.bClose); }
-							if (e=="e2") { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.novalue,jQuery.jgrid.edit.bClose); }
-							else {$.jgrid.info_dialog(jQuery.jgrid.errors.errcap,e.message,jQuery.jgrid.edit.bClose); }
-						}
-						break;
-				}
-				// The common approach is if nothing changed do not do anything
-				if (v2 !== $t.p.savedRow[fr].v){
-					var vvv = $($t).triggerHandler("jqGridBeforeSaveCell", [$t.rows[iRow].id, nm, v, iRow, iCol]);
-					if (vvv) {v = vvv; v2=vvv;}
-					if ($.isFunction($t.p.beforeSaveCell)) {
-						var vv = $t.p.beforeSaveCell.call($t, $t.rows[iRow].id,nm, v, iRow,iCol);
-						if (vv) {v = vv; v2=vv;}
-					}
-					var cv = $.jgrid.checkValues(v,iCol,$t);
-					if(cv[0] === true) {
-						var addpost = $($t).triggerHandler("jqGridBeforeSubmitCell", [$t.rows[iRow].id, nm, v, iRow, iCol]) || {};
-						if ($.isFunction($t.p.beforeSubmitCell)) {
-							addpost = $t.p.beforeSubmitCell.call($t, $t.rows[iRow].id,nm, v, iRow,iCol);
-							if (!addpost) {addpost={};}
-						}
-						if( $("input.hasDatepicker",cc).length >0) { $("input.hasDatepicker",cc).datepicker('hide'); }
-						if ($t.p.cellsubmit == 'remote') {
-							if ($t.p.cellurl) {
-								var postdata = {};
-								if($t.p.autoencode) { v = $.jgrid.htmlEncode(v); }
-								postdata[nm] = v;
-								var idname,oper, opers;
-								opers = $t.p.prmNames;
-								idname = opers.id;
-								oper = opers.oper;
-								postdata[idname] = $.jgrid.stripPref($t.p.idPrefix, $t.rows[iRow].id);
-								postdata[oper] = opers.editoper;
-								postdata = $.extend(addpost,postdata);
-								$("#lui_"+$.jgrid.jqID($t.p.id)).show();
-								$t.grid.hDiv.loading = true;
-								$.ajax( $.extend( {
-									url: $t.p.cellurl,
-									data :$.isFunction($t.p.serializeCellData) ? $t.p.serializeCellData.call($t, postdata) : postdata,
-									type: "POST",
-									complete: function (result, stat) {
-										$("#lui_"+$t.p.id).hide();
-										$t.grid.hDiv.loading = false;
-										if (stat == 'success') {
-											var ret = $($t).triggerHandler("jqGridAfterSubmitCell", [$t, result, postdata.id, nm, v, iRow, iCol]) || [true, ''];
-											if (ret[0] === true && $.isFunction($t.p.afterSubmitCell)) {
-												ret = $t.p.afterSubmitCell.call($t, result,postdata.id,nm,v,iRow,iCol);
-											}
-											if(ret[0] === true){
-												$(cc).empty();
-												$($t).jqGrid("setCell",$t.rows[iRow].id, iCol, v2, false, false, true);
-												$(cc).addClass("dirty-cell");
-												$($t.rows[iRow]).addClass("edited");
-												$($t).triggerHandler("jqGridAfterSaveCell", [$t.rows[iRow].id, nm, v, iRow, iCol]);
-												if ($.isFunction($t.p.afterSaveCell)) {
-													$t.p.afterSaveCell.call($t, $t.rows[iRow].id,nm, v, iRow,iCol);
-												}
-												$t.p.savedRow.splice(0,1);
-											} else {
-												$.jgrid.info_dialog($.jgrid.errors.errcap,ret[1],$.jgrid.edit.bClose);
-												$($t).jqGrid("restoreCell",iRow,iCol);
-											}
-										}
-									},
-									error:function(res,stat,err) {
-										$("#lui_"+$.jgrid.jqID($t.p.id)).hide();
-										$t.grid.hDiv.loading = false;
-										$($t).triggerHandler("jqGridErrorCell", [res, stat, err]);
-										if ($.isFunction($t.p.errorCell)) {
-											$t.p.errorCell.call($t, res,stat,err);
-											$($t).jqGrid("restoreCell",iRow,iCol);
-										} else {
-											$.jgrid.info_dialog($.jgrid.errors.errcap,res.status+" : "+res.statusText+"<br/>"+stat,$.jgrid.edit.bClose);
-											$($t).jqGrid("restoreCell",iRow,iCol);
-										}
-									}
-								}, $.jgrid.ajaxOptions, $t.p.ajaxCellOptions || {}));
-							} else {
-								try {
-									$.jgrid.info_dialog($.jgrid.errors.errcap,$.jgrid.errors.nourl,$.jgrid.edit.bClose);
-									$($t).jqGrid("restoreCell",iRow,iCol);
-								} catch (e) {}
-							}
-						}
-						if ($t.p.cellsubmit == 'clientArray') {
-							$(cc).empty();
-							$($t).jqGrid("setCell",$t.rows[iRow].id,iCol, v2, false, false, true);
-							$(cc).addClass("dirty-cell");
-							$($t.rows[iRow]).addClass("edited");
-							$($t).triggerHandler("jqGridAfterSaveCell", [$t.rows[iRow].id, nm, v, iRow, iCol]);
-							if ($.isFunction($t.p.afterSaveCell)) {
-								$t.p.afterSaveCell.call($t, $t.rows[iRow].id,nm, v, iRow,iCol);
-							}
-							$t.p.savedRow.splice(0,1);
-						}
-					} else {
-						try {
-							window.setTimeout(function(){$.jgrid.info_dialog($.jgrid.errors.errcap,v+" "+cv[1],$.jgrid.edit.bClose);},100);
-							$($t).jqGrid("restoreCell",iRow,iCol);
-						} catch (e) {}
-					}
-				} else {
-					$($t).jqGrid("restoreCell",iRow,iCol);
-				}
-			}
-			if ($.browser.opera) {
-				$("#"+$.jgrid.jqID($t.p.knv)).attr("tabindex","-1").focus();
-			} else {
-				window.setTimeout(function () { $("#"+$.jgrid.jqID($t.p.knv)).attr("tabindex","-1").focus();},0);
-			}
-		});
-	},
-	restoreCell : function(iRow, iCol) {
-		return this.each(function(){
-			var $t= this, fr;
-			if (!$t.grid || $t.p.cellEdit !== true ) {return;}
-			if ( $t.p.savedRow.length >= 1) {fr = 0;} else {fr=null;}
-			if(fr !== null) {
-				var cc = $("td:eq("+iCol+")",$t.rows[iRow]);
-				// datepicker fix
-				if($.isFunction($.fn.datepicker)) {
-					try {
-						$("input.hasDatepicker",cc).datepicker('hide');
-					} catch (e) {}
-				}
-				$(cc).empty().attr("tabindex","-1");
-				$($t).jqGrid("setCell",$t.rows[iRow].id, iCol, $t.p.savedRow[fr].v, false, false, true);
-				$($t).triggerHandler("jqGridAfterRestoreCell", [$t.rows[iRow].id, $t.p.savedRow[fr].v, iRow, iCol]);
-				if ($.isFunction($t.p.afterRestoreCell)) {
-					$t.p.afterRestoreCell.call($t, $t.rows[iRow].id, $t.p.savedRow[fr].v, iRow, iCol);
-				}
-				$t.p.savedRow.splice(0,1);
-			}
-			window.setTimeout(function () { $("#"+$t.p.knv).attr("tabindex","-1").focus();},0);
-		});
-	},
-	nextCell : function (iRow,iCol) {
-		return this.each(function (){
-			var $t = this, nCol=false;
-			if (!$t.grid || $t.p.cellEdit !== true) {return;}
-			// try to find next editable cell
-			for (var i=iCol+1; i<$t.p.colModel.length; i++) {
-				if ( $t.p.colModel[i].editable ===true) {
-					nCol = i; break;
-				}
-			}
-			if(nCol !== false) {
-				$($t).jqGrid("editCell",iRow,nCol,true);
-			} else {
-				if ($t.p.savedRow.length >0) {
-					$($t).jqGrid("saveCell",iRow,iCol);
-				}
-			}
-		});
-	},
-	prevCell : function (iRow,iCol) {
-		return this.each(function (){
-			var $t = this, nCol=false;
-			if (!$t.grid || $t.p.cellEdit !== true) {return;}
-			// try to find next editable cell
-			for (var i=iCol-1; i>=0; i--) {
-				if ( $t.p.colModel[i].editable ===true) {
-					nCol = i; break;
-				}
-			}
-			if(nCol !== false) {
-				$($t).jqGrid("editCell",iRow,nCol,true);
-			} else {
-				if ($t.p.savedRow.length >0) {
-					$($t).jqGrid("saveCell",iRow,iCol);
-				}
-			}
-		});
-	},
-	GridNav : function() {
-		return this.each(function () {
-			var  $t = this;
-			if (!$t.grid || $t.p.cellEdit !== true ) {return;}
-			// trick to process keydown on non input elements
-			$t.p.knv = $t.p.id + "_kn";
-			var selection = $("<span style='width:0px;height:0px;background-color:black;' tabindex='0'><span tabindex='-1' style='width:0px;height:0px;background-color:grey' id='"+$t.p.knv+"'></span></span>"),
-			i, kdir;
-			function scrollGrid(iR, iC, tp){
-				if (tp.substr(0,1)=='v') {
-					var ch = $($t.grid.bDiv)[0].clientHeight,
-					st = $($t.grid.bDiv)[0].scrollTop,
-					nROT = $t.rows[iR].offsetTop+$t.rows[iR].clientHeight,
-					pROT = $t.rows[iR].offsetTop;
-					if(tp == 'vd') {
-						if(nROT >= ch) {
-							$($t.grid.bDiv)[0].scrollTop = $($t.grid.bDiv)[0].scrollTop + $t.rows[iR].clientHeight;
-						}
-					}
-					if(tp == 'vu'){
-						if (pROT < st ) {
-							$($t.grid.bDiv)[0].scrollTop = $($t.grid.bDiv)[0].scrollTop - $t.rows[iR].clientHeight;
-						}
-					}
-				}
-				if(tp=='h') {
-					var cw = $($t.grid.bDiv)[0].clientWidth,
-					sl = $($t.grid.bDiv)[0].scrollLeft,
-					nCOL = $t.rows[iR].cells[iC].offsetLeft+$t.rows[iR].cells[iC].clientWidth,
-					pCOL = $t.rows[iR].cells[iC].offsetLeft;
-					if(nCOL >= cw+parseInt(sl,10)) {
-						$($t.grid.bDiv)[0].scrollLeft = $($t.grid.bDiv)[0].scrollLeft + $t.rows[iR].cells[iC].clientWidth;
-					} else if (pCOL < sl) {
-						$($t.grid.bDiv)[0].scrollLeft = $($t.grid.bDiv)[0].scrollLeft - $t.rows[iR].cells[iC].clientWidth;
-					}
-				}
-			}
-			function findNextVisible(iC,act){
-				var ind, i;
-				if(act == 'lft') {
-					ind = iC+1;
-					for (i=iC;i>=0;i--){
-						if ($t.p.colModel[i].hidden !== true) {
-							ind = i;
-							break;
-						}
-					}
-				}
-				if(act == 'rgt') {
-					ind = iC-1;
-					for (i=iC; i<$t.p.colModel.length;i++){
-						if ($t.p.colModel[i].hidden !== true) {
-							ind = i;
-							break;
-						}
-					}
-				}
-				return ind;
-			}
-
-			$(selection).insertBefore($t.grid.cDiv);
-			$("#"+$t.p.knv)
-			.focus()
-			.keydown(function (e){
-				kdir = e.keyCode;
-				if($t.p.direction == "rtl") {
-					if(kdir===37) { kdir = 39;}
-					else if (kdir===39) { kdir = 37; }
-				}
-				switch (kdir) {
-					case 38:
-						if ($t.p.iRow-1 >0 ) {
-							scrollGrid($t.p.iRow-1,$t.p.iCol,'vu');
-							$($t).jqGrid("editCell",$t.p.iRow-1,$t.p.iCol,false);
-						}
-					break;
-					case 40 :
-						if ($t.p.iRow+1 <=  $t.rows.length-1) {
-							scrollGrid($t.p.iRow+1,$t.p.iCol,'vd');
-							$($t).jqGrid("editCell",$t.p.iRow+1,$t.p.iCol,false);
-						}
-					break;
-					case 37 :
-						if ($t.p.iCol -1 >=  0) {
-							i = findNextVisible($t.p.iCol-1,'lft');
-							scrollGrid($t.p.iRow, i,'h');
-							$($t).jqGrid("editCell",$t.p.iRow, i,false);
-						}
-					break;
-					case 39 :
-						if ($t.p.iCol +1 <=  $t.p.colModel.length-1) {
-							i = findNextVisible($t.p.iCol+1,'rgt');
-							scrollGrid($t.p.iRow,i,'h');
-							$($t).jqGrid("editCell",$t.p.iRow,i,false);
-						}
-					break;
-					case 13:
-						if (parseInt($t.p.iCol,10)>=0 && parseInt($t.p.iRow,10)>=0) {
-							$($t).jqGrid("editCell",$t.p.iRow,$t.p.iCol,true);
-						}
-					break;
-					default :
-						return true;
-				}
-				return false;
-			});
-		});
-	},
-	getChangedCells : function (mthd) {
-		var ret=[];
-		if (!mthd) {mthd='all';}
-		this.each(function(){
-			var $t= this,nm;
-			if (!$t.grid || $t.p.cellEdit !== true ) {return;}
-			$($t.rows).each(function(j){
-				var res = {};
-				if ($(this).hasClass("edited")) {
-					$('td',this).each( function(i) {
-						nm = $t.p.colModel[i].name;
-						if ( nm !== 'cb' && nm !== 'subgrid') {
-							if (mthd=='dirty') {
-								if ($(this).hasClass('dirty-cell')) {
-									try {
-										res[nm] = $.unformat.call($t,this,{rowId:$t.rows[j].id, colModel:$t.p.colModel[i]},i);
-									} catch (e){
-										res[nm] = $.jgrid.htmlDecode($(this).html());
-									}
-								}
-							} else {
-								try {
-									res[nm] = $.unformat.call($t,this,{rowId:$t.rows[j].id,colModel:$t.p.colModel[i]},i);
-								} catch (e) {
-									res[nm] = $.jgrid.htmlDecode($(this).html());
-								}
-							}
-						}
-					});
-					res.id = this.id;
-					ret.push(res);
-				}
-			});
-		});
-		return ret;
-	}
-/// end  cell editing
-});
-})(jQuery);
-;(function($){
-/**
- * jqGrid extension for SubGrid Data
- * Tony Tomov tony@trirand.com
- * http://trirand.com/blog/
- * Dual licensed under the MIT and GPL licenses:
- * http://www.opensource.org/licenses/mit-license.php
- * http://www.gnu.org/licenses/gpl-2.0.html
-**/
-"use strict";
-$.jgrid.extend({
-setSubGrid : function () {
-	return this.each(function (){
-		var $t = this, cm,
-		suboptions = {
-			plusicon : "ui-icon-plus",
-			minusicon : "ui-icon-minus",
-			openicon: "ui-icon-carat-1-sw",
-			expandOnLoad:  false,
-			delayOnLoad : 50,
-			selectOnExpand : false,
-			reloadOnExpand : true
-		};
-		$t.p.subGridOptions = $.extend(suboptions, $t.p.subGridOptions || {});
-		$t.p.colNames.unshift("");
-		$t.p.colModel.unshift({name:'subgrid',width: $.browser.safari ?  $t.p.subGridWidth+$t.p.cellLayout : $t.p.subGridWidth,sortable: false,resizable:false,hidedlg:true,search:false,fixed:true});
-		cm = $t.p.subGridModel;
-		if(cm[0]) {
-			cm[0].align = $.extend([],cm[0].align || []);
-			for(var i=0;i<cm[0].name.length;i++) { cm[0].align[i] = cm[0].align[i] || 'left';}
-		}
-	});
-},
-addSubGridCell :function (pos,iRow) {
-	var prp='',ic,sid;
-	this.each(function(){
-		prp = this.formatCol(pos,iRow);
-		sid= this.p.id;
-		ic = this.p.subGridOptions.plusicon;
-	});
-	return "<td role=\"gridcell\" aria-describedby=\""+sid+"_subgrid\" class=\"ui-sgcollapsed sgcollapsed\" "+prp+"><a href='javascript:void(0);'><span class='ui-icon "+ic+"'></span></a></td>";
-},
-addSubGrid : function( pos, sind ) {
-	return this.each(function(){
-		var ts = this;
-		if (!ts.grid ) { return; }
-		//-------------------------
-		var subGridCell = function(trdiv,cell,pos)
-		{
-			var tddiv = $("<td align='"+ts.p.subGridModel[0].align[pos]+"'></td>").html(cell);
-			$(trdiv).append(tddiv);
-		};
-		var subGridXml = function(sjxml, sbid){
-			var tddiv, i,  sgmap,
-			dummy = $("<table cellspacing='0' cellpadding='0' border='0'><tbody></tbody></table>"),
-			trdiv = $("<tr></tr>");
-			for (i = 0; i<ts.p.subGridModel[0].name.length; i++) {
-				tddiv = $("<th class='ui-state-default ui-th-subgrid ui-th-column ui-th-"+ts.p.direction+"'></th>");
-				$(tddiv).html(ts.p.subGridModel[0].name[i]);
-				$(tddiv).width( ts.p.subGridModel[0].width[i]);
-				$(trdiv).append(tddiv);
-			}
-			$(dummy).append(trdiv);
-			if (sjxml){
-				sgmap = ts.p.xmlReader.subgrid;
-				$(sgmap.root+" "+sgmap.row, sjxml).each( function(){
-					trdiv = $("<tr class='ui-widget-content ui-subtblcell'></tr>");
-					if(sgmap.repeatitems === true) {
-						$(sgmap.cell,this).each( function(i) {
-							subGridCell(trdiv, $(this).text() || '&#160;',i);
-						});
-					} else {
-						var f = ts.p.subGridModel[0].mapping || ts.p.subGridModel[0].name;
-						if (f) {
-							for (i=0;i<f.length;i++) {
-								subGridCell(trdiv, $(f[i],this).text() || '&#160;',i);
-							}
-						}
-					}
-					$(dummy).append(trdiv);
-				});
-			}
-			var pID = $("table:first",ts.grid.bDiv).attr("id")+"_";
-			$("#"+$.jgrid.jqID(pID+sbid)).append(dummy);
-			ts.grid.hDiv.loading = false;
-			$("#load_"+$.jgrid.jqID(ts.p.id)).hide();
-			return false;
-		};
-		var subGridJson = function(sjxml, sbid){
-			var tddiv,result , i,cur, sgmap,j,
-			dummy = $("<table cellspacing='0' cellpadding='0' border='0'><tbody></tbody></table>"),
-			trdiv = $("<tr></tr>");
-			for (i = 0; i<ts.p.subGridModel[0].name.length; i++) {
-				tddiv = $("<th class='ui-state-default ui-th-subgrid ui-th-column ui-th-"+ts.p.direction+"'></th>");
-				$(tddiv).html(ts.p.subGridModel[0].name[i]);
-				$(tddiv).width( ts.p.subGridModel[0].width[i]);
-				$(trdiv).append(tddiv);
-			}
-			$(dummy).append(trdiv);
-			if (sjxml){
-				sgmap = ts.p.jsonReader.subgrid;
-				result = sjxml[sgmap.root];
-				if ( typeof result !== 'undefined' ) {
-					for (i=0;i<result.length;i++) {
-						cur = result[i];
-						trdiv = $("<tr class='ui-widget-content ui-subtblcell'></tr>");
-						if(sgmap.repeatitems === true) {
-							if(sgmap.cell) { cur=cur[sgmap.cell]; }
-							for (j=0;j<cur.length;j++) {
-								subGridCell(trdiv, cur[j] || '&#160;',j);
-							}
-						} else {
-							var f = ts.p.subGridModel[0].mapping || ts.p.subGridModel[0].name;
-							if(f.length) {
-								for (j=0;j<f.length;j++) {
-									subGridCell(trdiv, cur[f[j]] || '&#160;',j);
-								}
-							}
-						}
-						$(dummy).append(trdiv);
-					}
-				}
-			}
-			var pID = $("table:first",ts.grid.bDiv).attr("id")+"_";
-			$("#"+$.jgrid.jqID(pID+sbid)).append(dummy);
-			ts.grid.hDiv.loading = false;
-			$("#load_"+$.jgrid.jqID(ts.p.id)).hide();
-			return false;
-		};
-		var populatesubgrid = function( rd )
-		{
-			var sid,dp, i, j;
-			sid = $(rd).attr("id");
-			dp = {nd_: (new Date().getTime())};
-			dp[ts.p.prmNames.subgridid]=sid;
-			if(!ts.p.subGridModel[0]) { return false; }
-			if(ts.p.subGridModel[0].params) {
-				for(j=0; j < ts.p.subGridModel[0].params.length; j++) {
-					for(i=0; i<ts.p.colModel.length; i++) {
-						if(ts.p.colModel[i].name === ts.p.subGridModel[0].params[j]) {
-							dp[ts.p.colModel[i].name]= $("td:eq("+i+")",rd).text().replace(/\&#160\;/ig,'');
-						}
-					}
-				}
-			}
-			if(!ts.grid.hDiv.loading) {
-				ts.grid.hDiv.loading = true;
-				$("#load_"+$.jgrid.jqID(ts.p.id)).show();
-				if(!ts.p.subgridtype) { ts.p.subgridtype = ts.p.datatype; }
-				if($.isFunction(ts.p.subgridtype)) {
-					ts.p.subgridtype.call(ts, dp);
-				} else {
-					ts.p.subgridtype = ts.p.subgridtype.toLowerCase();
-				}
-				switch(ts.p.subgridtype) {
-					case "xml":
-					case "json":
-					$.ajax($.extend({
-						type:ts.p.mtype,
-						url: ts.p.subGridUrl,
-						dataType:ts.p.subgridtype,
-						data: $.isFunction(ts.p.serializeSubGridData)? ts.p.serializeSubGridData.call(ts, dp) : dp,
-						complete: function(sxml) {
-							if(ts.p.subgridtype === "xml") {
-								subGridXml(sxml.responseXML, sid);
-							} else {
-								subGridJson($.jgrid.parse(sxml.responseText),sid);
-							}
-							sxml=null;
-						}
-					}, $.jgrid.ajaxOptions, ts.p.ajaxSubgridOptions || {}));
-					break;
-				}
-			}
-			return false;
-		};
-		var _id, pID,atd, nhc=0, bfsc, r;
-		$.each(ts.p.colModel,function(){
-			if(this.hidden === true || this.name === 'rn' || this.name === 'cb') {
-				nhc++;
-			}
-		});
-		var len = ts.rows.length, i=1;
-		if( sind !== undefined && sind > 0) {
-			i = sind;
-			len = sind+1;
-		}
-		while(i < len) {
-			if($(ts.rows[i]).hasClass('jqgrow')) {
-				$(ts.rows[i].cells[pos]).bind('click', function() {
-					var tr = $(this).parent("tr")[0];
-					r = tr.nextSibling;
-					if($(this).hasClass("sgcollapsed")) {
-						pID = ts.p.id;
-						_id = tr.id;
-						if(ts.p.subGridOptions.reloadOnExpand === true || ( ts.p.subGridOptions.reloadOnExpand === false && !$(r).hasClass('ui-subgrid') ) ) {
-							atd = pos >=1 ? "<td colspan='"+pos+"'>&#160;</td>":"";
-							bfsc = $(ts).triggerHandler("jqGridSubGridBeforeExpand", [pID + "_" + _id, _id]);
-							bfsc = (bfsc === false || bfsc === 'stop') ? false : true;
-							if(bfsc && $.isFunction(ts.p.subGridBeforeExpand)) {
-								bfsc = ts.p.subGridBeforeExpand.call(ts, pID+"_"+_id,_id);
-							}
-							if(bfsc === false) {return false;}
-							$(tr).after( "<tr role='row' class='ui-subgrid'>"+atd+"<td class='ui-widget-content subgrid-cell'><span class='ui-icon "+ts.p.subGridOptions.openicon+"'></span></td><td colspan='"+parseInt(ts.p.colNames.length-1-nhc,10)+"' class='ui-widget-content subgrid-data'><div id="+pID+"_"+_id+" class='tablediv'></div></td></tr>" );
-							$(ts).triggerHandler("jqGridSubGridRowExpanded", [pID + "_" + _id, _id]);
-							if( $.isFunction(ts.p.subGridRowExpanded)) {
-								ts.p.subGridRowExpanded.call(ts, pID+"_"+ _id,_id);
-							} else {
-								populatesubgrid(tr);
-							}
-						} else {
-							$(r).show();
-						}
-						$(this).html("<a href='javascript:void(0);'><span class='ui-icon "+ts.p.subGridOptions.minusicon+"'></span></a>").removeClass("sgcollapsed").addClass("sgexpanded");
-						if(ts.p.subGridOptions.selectOnExpand) {
-							$(ts).jqGrid('setSelection',_id);
-						}
-					} else if($(this).hasClass("sgexpanded")) {
-						bfsc = $(ts).triggerHandler("jqGridSubGridRowColapsed", [pID + "_" + _id, _id]);
-						bfsc = (bfsc === false || bfsc === 'stop') ? false : true;
-						if( bfsc &&  $.isFunction(ts.p.subGridRowColapsed)) {
-							_id = tr.id;
-							bfsc = ts.p.subGridRowColapsed.call(ts, pID+"_"+_id,_id );
-						}
-						if(bfsc===false) {return false;}
-						if(ts.p.subGridOptions.reloadOnExpand === true) {
-							$(r).remove(".ui-subgrid");
-						} else if($(r).hasClass('ui-subgrid')) { // incase of dynamic deleting
-							$(r).hide();
-						}
-						$(this).html("<a href='javascript:void(0);'><span class='ui-icon "+ts.p.subGridOptions.plusicon+"'></span></a>").removeClass("sgexpanded").addClass("sgcollapsed");
-					}
-					return false;
-				});
-			}
-			i++;
-		}
-		if(ts.p.subGridOptions.expandOnLoad === true) {
-			$(ts.rows).filter('.jqgrow').each(function(index,row){
-				$(row.cells[0]).click();
-			});
-		}
-		ts.subGridXml = function(xml,sid) {subGridXml(xml,sid);};
-		ts.subGridJson = function(json,sid) {subGridJson(json,sid);};
-	});
-},
-expandSubGridRow : function(rowid) {
-	return this.each(function () {
-		var $t = this;
-		if(!$t.grid && !rowid) {return;}
-		if($t.p.subGrid===true) {
-			var rc = $(this).jqGrid("getInd",rowid,true);
-			if(rc) {
-				var sgc = $("td.sgcollapsed",rc)[0];
-				if(sgc) {
-					$(sgc).trigger("click");
-				}
-			}
-		}
-	});
-},
-collapseSubGridRow : function(rowid) {
-	return this.each(function () {
-		var $t = this;
-		if(!$t.grid && !rowid) {return;}
-		if($t.p.subGrid===true) {
-			var rc = $(this).jqGrid("getInd",rowid,true);
-			if(rc) {
-				var sgc = $("td.sgexpanded",rc)[0];
-				if(sgc) {
-					$(sgc).trigger("click");
-				}
-			}
-		}
-	});
-},
-toggleSubGridRow : function(rowid) {
-	return this.each(function () {
-		var $t = this;
-		if(!$t.grid && !rowid) {return;}
-		if($t.p.subGrid===true) {
-			var rc = $(this).jqGrid("getInd",rowid,true);
-			if(rc) {
-				var sgc = $("td.sgcollapsed",rc)[0];
-				if(sgc) {
-					$(sgc).trigger("click");
-				} else {
-					sgc = $("td.sgexpanded",rc)[0];
-					if(sgc) {
-						$(sgc).trigger("click");
-					}
-				}
-			}
-		}
-	});
-}
-});
-})(jQuery);
-/**
- * jqGrid extension - Tree Grid
- * Tony Tomov tony@trirand.com
- * http://trirand.com/blog/
- * Dual licensed under the MIT and GPL licenses:
- * http://www.opensource.org/licenses/mit-license.php
- * http://www.gnu.org/licenses/gpl.html
-**/
+                if (!funcs[fn]) {
+                    throw ("jqGrid Grouping No such method: " + fn);
+                }
+                var res = funcs[fn]();
 
-/*global document, jQuery, $ */
-(function($) {
-"use strict";
-$.jgrid.extend({
-	setTreeNode : function(i, len){
-		return this.each(function(){
-			var $t = this;
-			if( !$t.grid || !$t.p.treeGrid ) {return;}
-			var expCol = $t.p.expColInd,
-			expanded = $t.p.treeReader.expanded_field,
-			isLeaf = $t.p.treeReader.leaf_field,
-			level = $t.p.treeReader.level_field,
-			icon = $t.p.treeReader.icon_field,
-			loaded = $t.p.treeReader.loaded,  lft, rgt, curLevel, ident,lftpos, twrap,
-			ldat, lf;
-			while(i<len) {
-				var ind = $t.rows[i].id, dind = $t.p._index[ind], expan;
-				ldat = $t.p.data[dind];
-				//$t.rows[i].level = ldat[level];
-				if($t.p.treeGridModel == 'nested') {
-					if(!ldat[isLeaf]) {
-					lft = parseInt(ldat[$t.p.treeReader.left_field],10);
-					rgt = parseInt(ldat[$t.p.treeReader.right_field],10);
-					// NS Model
-						ldat[isLeaf] = (rgt === lft+1) ? 'true' : 'false';
-						$t.rows[i].cells[$t.p._treeleafpos].innerHTML = ldat[isLeaf];
-					}
-				}
-				//else {
-					//row.parent_id = rd[$t.p.treeReader.parent_id_field];
-				//}
-				curLevel = parseInt(ldat[level],10);
-				if($t.p.tree_root_level === 0) {
-					ident = curLevel+1;
-					lftpos = curLevel;
-				} else {
-					ident = curLevel;
-					lftpos = curLevel -1;
-				}
-				twrap = "<div class='tree-wrap tree-wrap-"+$t.p.direction+"' style='width:"+(ident*18)+"px;'>";
-				twrap += "<div style='"+($t.p.direction=="rtl" ? "right:" : "left:")+(lftpos*18)+"px;' class='ui-icon ";
-
-
-				if(ldat[loaded] !== undefined) {
-					if(ldat[loaded]=="true" || ldat[loaded]===true) {
-						ldat[loaded] = true;
-					} else {
-						ldat[loaded] = false;
-					}
-				}
-				if(ldat[isLeaf] == "true" || ldat[isLeaf] === true) {
-					twrap += ((ldat[icon] !== undefined && ldat[icon] !== "") ? ldat[icon] : $t.p.treeIcons.leaf)+" tree-leaf treeclick";
-					ldat[isLeaf] = true;
-					lf="leaf";
-				} else {
-					ldat[isLeaf] = false;
-					lf="";
-				}
-				ldat[expanded] = ((ldat[expanded] == "true" || ldat[expanded] === true) ? true : false) && ldat[loaded];
-				if(ldat[expanded] === false) {
-					twrap += ((ldat[isLeaf] === true) ? "'" : $t.p.treeIcons.plus+" tree-plus treeclick'");
-				} else {
-					twrap += ((ldat[isLeaf] === true) ? "'" : $t.p.treeIcons.minus+" tree-minus treeclick'");
-				}
-
-				twrap += "></div></div>";
-				$($t.rows[i].cells[expCol]).wrapInner("<span class='cell-wrapper"+lf+"'></span>").prepend(twrap);
-
-				if(curLevel !== parseInt($t.p.tree_root_level,10)) {
-					var pn = $($t).jqGrid('getNodeParent',ldat);
-					expan = pn && pn.hasOwnProperty(expanded) ? pn[expanded] : true;
-					if( !expan ){
-						$($t.rows[i]).css("display","none");
-					}
-				}
-				$($t.rows[i].cells[expCol])
-					.find("div.treeclick")
-					.bind("click",function(e){
-						var target = e.target || e.srcElement,
-						ind2 =$(target,$t.rows).closest("tr.jqgrow")[0].id,
-						pos = $t.p._index[ind2];
-						if(!$t.p.data[pos][isLeaf]){
-							if($t.p.data[pos][expanded]){
-								$($t).jqGrid("collapseRow",$t.p.data[pos]);
-								$($t).jqGrid("collapseNode",$t.p.data[pos]);
-							} else {
-								$($t).jqGrid("expandRow",$t.p.data[pos]);
-								$($t).jqGrid("expandNode",$t.p.data[pos]);
-							}
-						}
-						return false;
-					});
-				if($t.p.ExpandColClick === true) {
-					$($t.rows[i].cells[expCol])
-						.find("span.cell-wrapper")
-						.css("cursor","pointer")
-						.bind("click",function(e) {
-							var target = e.target || e.srcElement,
-							ind2 =$(target,$t.rows).closest("tr.jqgrow")[0].id,
-							pos = $t.p._index[ind2];
-							if(!$t.p.data[pos][isLeaf]){
-								if($t.p.data[pos][expanded]){
-									$($t).jqGrid("collapseRow",$t.p.data[pos]);
-									$($t).jqGrid("collapseNode",$t.p.data[pos]);
-								} else {
-									$($t).jqGrid("expandRow",$t.p.data[pos]);
-									$($t).jqGrid("expandNode",$t.p.data[pos]);
-								}
-							}
-							$($t).jqGrid("setSelection",ind2);
-							return false;
-						});
-				}
-				i++;
-			}
-
-		});
-	},
-	setTreeGrid : function() {
-		return this.each(function (){
-			var $t = this, i=0, pico, ecol = false, nm, key, dupcols=[];
-			if(!$t.p.treeGrid) {return;}
-			if(!$t.p.treedatatype ) {$.extend($t.p,{treedatatype: $t.p.datatype});}
-			$t.p.subGrid = false;$t.p.altRows =false;
-			$t.p.pgbuttons = false;$t.p.pginput = false;
-			$t.p.gridview =  true;
-			if($t.p.rowTotal === null ) { $t.p.rowNum = 10000; }
-			$t.p.multiselect = false;$t.p.rowList = [];
-			$t.p.expColInd = 0;
-			pico = 'ui-icon-triangle-1-' + ($t.p.direction=="rtl" ? 'w' : 'e');
-			$t.p.treeIcons = $.extend({plus:pico,minus:'ui-icon-triangle-1-s',leaf:'ui-icon-radio-off'},$t.p.treeIcons || {});
-			if($t.p.treeGridModel == 'nested') {
-				$t.p.treeReader = $.extend({
-					level_field: "level",
-					left_field:"lft",
-					right_field: "rgt",
-					leaf_field: "isLeaf",
-					expanded_field: "expanded",
-					loaded: "loaded",
-					icon_field: "icon"
-				},$t.p.treeReader);
-			} else if($t.p.treeGridModel == 'adjacency') {
-				$t.p.treeReader = $.extend({
-						level_field: "level",
-						parent_id_field: "parent",
-						leaf_field: "isLeaf",
-						expanded_field: "expanded",
-						loaded: "loaded",
-						icon_field: "icon"
-				},$t.p.treeReader );
-			}
-			for ( key in $t.p.colModel){
-				if($t.p.colModel.hasOwnProperty(key)) {
-					nm = $t.p.colModel[key].name;
-					if( nm == $t.p.ExpandColumn && !ecol ) {
-						ecol = true;
-						$t.p.expColInd = i;
-					}
-					i++;
-					//
-					for(var tkey in $t.p.treeReader) {
-						if($t.p.treeReader[tkey] == nm) {
-							dupcols.push(nm);
-						}
-					}
-				}
-			}
-			$.each($t.p.treeReader,function(j,n){
-				if(n && $.inArray(n, dupcols) === -1){
-					if(j==='leaf_field') { $t.p._treeleafpos= i; }
-				i++;
-					$t.p.colNames.push(n);
-					$t.p.colModel.push({name:n,width:1,hidden:true,sortable:false,resizable:false,hidedlg:true,editable:true,search:false});
-				}
-			});
-		});
-	},
-	expandRow: function (record){
-		this.each(function(){
-			var $t = this;
-			if(!$t.grid || !$t.p.treeGrid) {return;}
-			var childern = $($t).jqGrid("getNodeChildren",record),
-			//if ($($t).jqGrid("isVisibleNode",record)) {
-			expanded = $t.p.treeReader.expanded_field,
-			rows = $t.rows;
-			$(childern).each(function(){
-				var id  = $.jgrid.getAccessor(this,$t.p.localReader.id);
-				$(rows.namedItem(id)).css("display","");
-				if(this[expanded]) {
-					$($t).jqGrid("expandRow",this);
-				}
-			});
-			//}
-		});
-	},
-	collapseRow : function (record) {
-		this.each(function(){
-			var $t = this;
-			if(!$t.grid || !$t.p.treeGrid) {return;}
-			var childern = $($t).jqGrid("getNodeChildren",record),
-			expanded = $t.p.treeReader.expanded_field,
-			rows = $t.rows;
-			$(childern).each(function(){
-				var id  = $.jgrid.getAccessor(this,$t.p.localReader.id);
-				$(rows.namedItem(id)).css("display","none");
-				if(this[expanded]){
-					$($t).jqGrid("collapseRow",this);
-				}
-			});
-		});
-	},
-	// NS ,adjacency models
-	getRootNodes : function() {
-		var result = [];
-		this.each(function(){
-			var $t = this;
-			if(!$t.grid || !$t.p.treeGrid) {return;}
-			switch ($t.p.treeGridModel) {
-				case 'nested' :
-					var level = $t.p.treeReader.level_field;
-					$($t.p.data).each(function(){
-						if(parseInt(this[level],10) === parseInt($t.p.tree_root_level,10)) {
-							result.push(this);
-						}
-					});
-					break;
-				case 'adjacency' :
-					var parent_id = $t.p.treeReader.parent_id_field;
-					$($t.p.data).each(function(){
-						if(this[parent_id] === null || String(this[parent_id]).toLowerCase() == "null") {
-							result.push(this);
-						}
-					});
-					break;
-			}
-		});
-		return result;
-	},
-	getNodeDepth : function(rc) {
-		var ret = null;
-		this.each(function(){
-			if(!this.grid || !this.p.treeGrid) {return;}
-			var $t = this;
-			switch ($t.p.treeGridModel) {
-				case 'nested' :
-					var level = $t.p.treeReader.level_field;
-					ret = parseInt(rc[level],10) - parseInt($t.p.tree_root_level,10);
-					break;
-				case 'adjacency' :
-					ret = $($t).jqGrid("getNodeAncestors",rc).length;
-					break;
-			}
-		});
-		return ret;
-	},
-	getNodeParent : function(rc) {
-		var result = null;
-		this.each(function(){
-			var $t = this;
-			if(!$t.grid || !$t.p.treeGrid) {return;}
-			switch ($t.p.treeGridModel) {
-				case 'nested' :
-					var lftc = $t.p.treeReader.left_field,
-					rgtc = $t.p.treeReader.right_field,
-					levelc = $t.p.treeReader.level_field,
-					lft = parseInt(rc[lftc],10), rgt = parseInt(rc[rgtc],10), level = parseInt(rc[levelc],10);
-					$(this.p.data).each(function(){
-						if(parseInt(this[levelc],10) === level-1 && parseInt(this[lftc],10) < lft && parseInt(this[rgtc],10) > rgt) {
-							result = this;
-							return false;
-						}
-					});
-					break;
-				case 'adjacency' :
-					var parent_id = $t.p.treeReader.parent_id_field,
-					dtid = $t.p.localReader.id;
-					$(this.p.data).each(function(){
-						if(this[dtid] == rc[parent_id] ) {
-							result = this;
-							return false;
-						}
-					});
-					break;
-			}
-		});
-		return result;
-	},
-	getNodeChildren : function(rc) {
-		var result = [];
-		this.each(function(){
-			var $t = this;
-			if(!$t.grid || !$t.p.treeGrid) {return;}
-			switch ($t.p.treeGridModel) {
-				case 'nested' :
-					var lftc = $t.p.treeReader.left_field,
-					rgtc = $t.p.treeReader.right_field,
-					levelc = $t.p.treeReader.level_field,
-					lft = parseInt(rc[lftc],10), rgt = parseInt(rc[rgtc],10), level = parseInt(rc[levelc],10);
-					$(this.p.data).each(function(){
-						if(parseInt(this[levelc],10) === level+1 && parseInt(this[lftc],10) > lft && parseInt(this[rgtc],10) < rgt) {
-							result.push(this);
-						}
-					});
-					break;
-				case 'adjacency' :
-					var parent_id = $t.p.treeReader.parent_id_field,
-					dtid = $t.p.localReader.id;
-					$(this.p.data).each(function(){
-						if(this[parent_id] == rc[dtid]) {
-							result.push(this);
-						}
-					});
-					break;
-			}
-		});
-		return result;
-	},
-	getFullTreeNode : function(rc) {
-		var result = [];
-		this.each(function(){
-			var $t = this, len;
-			if(!$t.grid || !$t.p.treeGrid) {return;}
-			switch ($t.p.treeGridModel) {
-				case 'nested' :
-					var lftc = $t.p.treeReader.left_field,
-					rgtc = $t.p.treeReader.right_field,
-					levelc = $t.p.treeReader.level_field,
-					lft = parseInt(rc[lftc],10), rgt = parseInt(rc[rgtc],10), level = parseInt(rc[levelc],10);
-					$(this.p.data).each(function(){
-						if(parseInt(this[levelc],10) >= level && parseInt(this[lftc],10) >= lft && parseInt(this[lftc],10) <= rgt) {
-							result.push(this);
-						}
-					});
-					break;
-				case 'adjacency' :
-					if(rc) {
-					result.push(rc);
-					var parent_id = $t.p.treeReader.parent_id_field,
-					dtid = $t.p.localReader.id;
-					$(this.p.data).each(function(i){
-						len = result.length;
-						for (i = 0; i < len; i++) {
-							if (result[i][dtid] == this[parent_id]) {
-								result.push(this);
-								break;
-							}
-						}
-					});
-					}
-					break;
-			}
-		});
-		return result;
-	},
-	// End NS, adjacency Model
-	getNodeAncestors : function(rc) {
-		var ancestors = [];
-		this.each(function(){
-			if(!this.grid || !this.p.treeGrid) {return;}
-			var parent = $(this).jqGrid("getNodeParent",rc);
-			while (parent) {
-				ancestors.push(parent);
-				parent = $(this).jqGrid("getNodeParent",parent);
-			}
-		});
-		return ancestors;
-	},
-	isVisibleNode : function(rc) {
-		var result = true;
-		this.each(function(){
-			var $t = this;
-			if(!$t.grid || !$t.p.treeGrid) {return;}
-			var ancestors = $($t).jqGrid("getNodeAncestors",rc),
-			expanded = $t.p.treeReader.expanded_field;
-			$(ancestors).each(function(){
-				result = result && this[expanded];
-				if(!result) {return false;}
-			});
-		});
-		return result;
-	},
-	isNodeLoaded : function(rc) {
-		var result;
-		this.each(function(){
-			var $t = this;
-			if(!$t.grid || !$t.p.treeGrid) {return;}
-			var isLeaf = $t.p.treeReader.leaf_field;
-			if(rc !== undefined ) {
-				if(rc.loaded !== undefined) {
-					result = rc.loaded;
-				} else if( rc[isLeaf] || $($t).jqGrid("getNodeChildren",rc).length > 0){
-					result = true;
-				} else {
-					result = false;
-				}
-			} else {
-				result = false;
-			}
-		});
-		return result;
-	},
-	expandNode : function(rc) {
-		return this.each(function(){
-			if(!this.grid || !this.p.treeGrid) {return;}
-			var expanded = this.p.treeReader.expanded_field,
-			parent = this.p.treeReader.parent_id_field,
-			loaded = this.p.treeReader.loaded,
-			level = this.p.treeReader.level_field,
-			lft = this.p.treeReader.left_field,
-			rgt = this.p.treeReader.right_field;
-
-			if(!rc[expanded]) {
-				var id = $.jgrid.getAccessor(rc,this.p.localReader.id);
-				var rc1 = $("#"+$.jgrid.jqID(id),this.grid.bDiv)[0];
-				var position = this.p._index[id];
-				if( $(this).jqGrid("isNodeLoaded",this.p.data[position]) ) {
-					rc[expanded] = true;
-					$("div.treeclick",rc1).removeClass(this.p.treeIcons.plus+" tree-plus").addClass(this.p.treeIcons.minus+" tree-minus");
-				} else if (!this.grid.hDiv.loading) {
-					rc[expanded] = true;
-					$("div.treeclick",rc1).removeClass(this.p.treeIcons.plus+" tree-plus").addClass(this.p.treeIcons.minus+" tree-minus");
-					this.p.treeANode = rc1.rowIndex;
-					this.p.datatype = this.p.treedatatype;
-					if(this.p.treeGridModel == 'nested') {
-						$(this).jqGrid("setGridParam",{postData:{nodeid:id,n_left:rc[lft],n_right:rc[rgt],n_level:rc[level]}});
-					} else {
-						$(this).jqGrid("setGridParam",{postData:{nodeid:id,parentid:rc[parent],n_level:rc[level]}} );
-					}
-					$(this).trigger("reloadGrid");
-					rc[loaded] = true;
-					if(this.p.treeGridModel == 'nested') {
-						$(this).jqGrid("setGridParam",{postData:{nodeid:'',n_left:'',n_right:'',n_level:''}});
-					} else {
-						$(this).jqGrid("setGridParam",{postData:{nodeid:'',parentid:'',n_level:''}});
-					}
-				}
-			}
-		});
-	},
-	collapseNode : function(rc) {
-		return this.each(function(){
-			if(!this.grid || !this.p.treeGrid) {return;}
-			var expanded = this.p.treeReader.expanded_field;
-			if(rc[expanded]) {
-				rc[expanded] = false;
-				var id = $.jgrid.getAccessor(rc,this.p.localReader.id);
-				var rc1 = $("#"+$.jgrid.jqID(id),this.grid.bDiv)[0];
-				$("div.treeclick",rc1).removeClass(this.p.treeIcons.minus+" tree-minus").addClass(this.p.treeIcons.plus+" tree-plus");
-			}
-		});
-	},
-	SortTree : function( sortname, newDir, st, datefmt) {
-		return this.each(function(){
-			if(!this.grid || !this.p.treeGrid) {return;}
-			var i, len,
-			rec, records = [], $t = this, query, roots,
-			rt = $(this).jqGrid("getRootNodes");
-			// Sorting roots
-			query = $.jgrid.from(rt);
-			query.orderBy(sortname,newDir,st, datefmt);
-			roots = query.select();
-
-			// Sorting children
-			for (i = 0, len = roots.length; i < len; i++) {
-				rec = roots[i];
-				records.push(rec);
-				$(this).jqGrid("collectChildrenSortTree",records, rec, sortname, newDir,st, datefmt);
-			}
-			$.each(records, function(index) {
-				var id  = $.jgrid.getAccessor(this,$t.p.localReader.id);
-				$('#'+$.jgrid.jqID($t.p.id)+ ' tbody tr:eq('+index+')').after($('tr#'+$.jgrid.jqID(id),$t.grid.bDiv));
-			});
-			query = null;roots=null;records=null;
-		});
-	},
-	collectChildrenSortTree : function(records, rec, sortname, newDir,st, datefmt) {
-		return this.each(function(){
-			if(!this.grid || !this.p.treeGrid) {return;}
-			var i, len,
-			child, ch, query, children;
-			ch = $(this).jqGrid("getNodeChildren",rec);
-			query = $.jgrid.from(ch);
-			query.orderBy(sortname, newDir, st, datefmt);
-			children = query.select();
-			for (i = 0, len = children.length; i < len; i++) {
-				child = children[i];
-				records.push(child);
-				$(this).jqGrid("collectChildrenSortTree",records, child, sortname, newDir, st, datefmt);
-			}
-		});
-	},
-	// experimental
-	setTreeRow : function(rowid, data) {
-		var success=false;
-		this.each(function(){
-			var t = this;
-			if(!t.grid || !t.p.treeGrid) {return;}
-			success = $(t).jqGrid("setRowData",rowid,data);
-		});
-		return success;
-	},
-	delTreeNode : function (rowid) {
-		return this.each(function () {
-			var $t = this, rid = $t.p.localReader.id,
-			left = $t.p.treeReader.left_field,
-			right = $t.p.treeReader.right_field, myright, width, res, key;
-			if(!$t.grid || !$t.p.treeGrid) {return;}
-			var rc = $t.p._index[rowid];
-			if (rc !== undefined) {
-				// nested
-				myright = parseInt($t.p.data[rc][right],10);
-				width = myright -  parseInt($t.p.data[rc][left],10) + 1;
-				var dr = $($t).jqGrid("getFullTreeNode",$t.p.data[rc]);
-				if(dr.length>0){
-					for (var i=0;i<dr.length;i++){
-						$($t).jqGrid("delRowData",dr[i][rid]);
-					}
-				}
-				if( $t.p.treeGridModel === "nested") {
-					// ToDo - update grid data
-					res = $.jgrid.from($t.p.data)
-						.greater(left,myright,{stype:'integer'})
-						.select();
-					if(res.length) {
-						for( key in res) {
-							if(res.hasOwnProperty(key)) {
-								res[key][left] = parseInt(res[key][left],10) - width ;
-							}
-						}
-					}
-					res = $.jgrid.from($t.p.data)
-						.greater(right,myright,{stype:'integer'})
-						.select();
-					if(res.length) {
-						for( key in res) {
-							if(res.hasOwnProperty(key)) {
-								res[key][right] = parseInt(res[key][right],10) - width ;
-							}
-						}
-					}
-				}
-			}
-		});
-	},
-	addChildNode : function( nodeid, parentid, data ) {
-		//return this.each(function(){
-		var $t = this[0];
-		if(data) {
-			// we suppose tha the id is autoincremet and
-			var expanded = $t.p.treeReader.expanded_field,
-			isLeaf = $t.p.treeReader.leaf_field,
-			level = $t.p.treeReader.level_field,
-			//icon = $t.p.treeReader.icon_field,
-			parent = $t.p.treeReader.parent_id_field,
-			left = $t.p.treeReader.left_field,
-			right = $t.p.treeReader.right_field,
-			loaded = $t.p.treeReader.loaded,
-			method, parentindex, parentdata, parentlevel, i, len, max=0, rowind = parentid, leaf, maxright;
-
-			if ( typeof nodeid === 'undefined' || nodeid === null ) {
-				i = $t.p.data.length-1;
-				if(	i>= 0 ) {
-					while(i>=0){max = Math.max(max, parseInt($t.p.data[i][$t.p.localReader.id],10)); i--;}
-				}
-				nodeid = max+1;
-			}
-			var prow = $($t).jqGrid('getInd', parentid);
-				leaf = false;
-				// if not a parent we assume root
-				if ( parentid === undefined  || parentid === null || parentid==="") {
-					parentid = null;
-					rowind = null;
-					method = 'last';
-					parentlevel = $t.p.tree_root_level;
-					i = $t.p.data.length+1;
-				} else {
-					method = 'after';
-					parentindex = $t.p._index[parentid];
-					parentdata = $t.p.data[parentindex];
-					parentid = parentdata[$t.p.localReader.id];
-					parentlevel = parseInt(parentdata[level],10)+1;
-					var childs = $($t).jqGrid('getFullTreeNode', parentdata);
-					// if there are child nodes get the last index of it
-					if(childs.length) {
-						i = childs[childs.length-1][$t.p.localReader.id];
-						rowind = i;
-						i = $($t).jqGrid('getInd',rowind)+1;
-					} else {
-						i = $($t).jqGrid('getInd', parentid)+1;
-					}
-					// if the node is leaf
-					if(parentdata[isLeaf]) {
-						leaf = true;
-						parentdata[expanded] = true;
-						//var prow = $($t).jqGrid('getInd', parentid);
-						$($t.rows[prow])
-							.find("span.cell-wrapperleaf").removeClass("cell-wrapperleaf").addClass("cell-wrapper")
-							.end()
-							.find("div.tree-leaf").removeClass($t.p.treeIcons.leaf+" tree-leaf").addClass($t.p.treeIcons.minus+" tree-minus");
-						$t.p.data[parentindex][isLeaf] = false;
-						parentdata[loaded] = true;
-					}
-				}
-				len = i+1;
-
-			data[expanded] = false;
-			data[loaded] = true;
-			data[level] = parentlevel;
-			data[isLeaf] = true;
-			if( $t.p.treeGridModel === "adjacency") {
-				data[parent] = parentid;
-			}
-			if( $t.p.treeGridModel === "nested") {
-				// this method requiere more attention
-				var query, res, key;
-				//maxright = parseInt(maxright,10);
-				// ToDo - update grid data
-				if(parentid !== null) {
-					maxright = parseInt(parentdata[right],10);
-					query = $.jgrid.from($t.p.data);
-					query = query.greaterOrEquals(right,maxright,{stype:'integer'});
-					res = query.select();
-					if(res.length) {
-						for( key in res) {
-							if(res.hasOwnProperty(key)) {
-								res[key][left] = res[key][left] > maxright ? parseInt(res[key][left],10) +2 : res[key][left];
-								res[key][right] = res[key][right] >= maxright ? parseInt(res[key][right],10) +2 : res[key][right];
-							}
-						}
-					}
-					data[left] = maxright;
-					data[right]= maxright+1;
-				} else {
-					maxright = parseInt( $($t).jqGrid('getCol', right, false, 'max'), 10);
-					res = $.jgrid.from($t.p.data)
-						.greater(left,maxright,{stype:'integer'})
-						.select();
-					if(res.length) {
-						for( key in res) {
-							if(res.hasOwnProperty(key)) {
-								res[key][left] = parseInt(res[key][left],10) +2 ;
-							}
-						}
-					}
-					res = $.jgrid.from($t.p.data)
-						.greater(right,maxright,{stype:'integer'})
-						.select();
-					if(res.length) {
-						for( key in res) {
-							if(res.hasOwnProperty(key)) {
-								res[key][right] = parseInt(res[key][right],10) +2 ;
-							}
-						}
-					}
-					data[left] = maxright+1;
-					data[right] = maxright + 2;
-				}
-			}
-			if( parentid === null || $($t).jqGrid("isNodeLoaded",parentdata) || leaf ) {
-					$($t).jqGrid('addRowData', nodeid, data, method, rowind);
-					$($t).jqGrid('setTreeNode', i, len);
-			}
-			if(parentdata && !parentdata[expanded]) {
-				$($t.rows[prow])
-					.find("div.treeclick")
-					.click();
-			}
-		}
-		//});
-	}
-});
-})(jQuery);
-// Grouping module
-;(function($){
-"use strict";
-$.extend($.jgrid,{
-	template : function(format){ //jqgformat
-		var args = $.makeArray(arguments).slice(1), j = 1;
-		if(format===undefined) { format = ""; }
-		return format.replace(/\{([\w\-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g, function(m,i){
-			if(!isNaN(parseInt(i,10))) {
-				j++;
-				return args[parseInt(i,10)];
-			} else {
-				var nmarr = args[ j ],
-				k = nmarr.length;
-				while(k--) {
-					if(i===nmarr[k].nm) {
-						return nmarr[k].v;
-						break;
-					}
-				}
-				j++;
-			}
-		});
-	}
-});
-$.jgrid.extend({
-	groupingSetup : function () {
-		return this.each(function (){
-			var $t = this,
-			grp = $t.p.groupingView;
-			if(grp !== null && ( (typeof grp === 'object') || $.isFunction(grp) ) ) {
-				if(!grp.groupField.length) {
-					$t.p.grouping = false;
-				} else {
-					if ( typeof(grp.visibiltyOnNextGrouping) === 'undefined') {
-						grp.visibiltyOnNextGrouping = [];
-					}
-
-					grp.lastvalues=[];
-					grp.groups =[];
-					grp.counters =[];
-					for(var i=0;i<grp.groupField.length;i++) {
-						if(!grp.groupOrder[i]) {
-							grp.groupOrder[i] = 'asc';
-						}
-						if(!grp.groupText[i]) {
-							grp.groupText[i] = '{0}';
-						}
-						if( typeof(grp.groupColumnShow[i]) !== 'boolean') {
-							grp.groupColumnShow[i] = true;
-						}
-						if( typeof(grp.groupSummary[i]) !== 'boolean') {
-							grp.groupSummary[i] = false;
-						}
-						if(grp.groupColumnShow[i] === true) {
-							grp.visibiltyOnNextGrouping[i] = true;
-							$($t).jqGrid('showCol',grp.groupField[i]);
-						} else {
-							grp.visibiltyOnNextGrouping[i] = $("#"+$.jgrid.jqID($t.p.id+"_"+grp.groupField[i])).is(":visible");
-							$($t).jqGrid('hideCol',grp.groupField[i]);
-						}
-					}
-					grp.summary =[];
-					var cm = $t.p.colModel;
-					for(var j=0, cml = cm.length; j < cml; j++) {
-						if(cm[j].summaryType) {
-							grp.summary.push({nm:cm[j].name,st:cm[j].summaryType, v: '', sr: cm[j].summaryRound, srt: cm[j].summaryRoundType || 'round'});
-						}
-					}
-				}
-			} else {
-				$t.p.grouping = false;
-			}
-		});
-	},
-	groupingPrepare : function (rData, gdata, record, irow) {
-		this.each(function(){
-			var grp = this.p.groupingView, $t= this;
-			var grlen = grp.groupField.length,
-			fieldName,
-			v,
-			changed = 0;
-			for(var i=0;i<grlen;i++) {
-				fieldName = grp.groupField[i];
-				v = record[fieldName];
-				if( v !== undefined ) {
-					if(irow === 0 ) {
-						// First record always starts a new group
-						grp.groups.push({idx:i,dataIndex:fieldName,value:v, startRow: irow, cnt:1, summary : [] } );
-						grp.lastvalues[i] = v;
-						grp.counters[i] = {cnt:1, pos:grp.groups.length-1, summary: $.extend(true,[],grp.summary)};
-						$.each(grp.counters[i].summary,function() {
-							if ($.isFunction(this.st)) {
-								this.v = this.st.call($t, this.v, this.nm, record);
-							} else {
-								this.v = $($t).jqGrid('groupingCalculations.handler',this.st, this.v, this.nm, this.sr, this.srt, record);
-							}
-						});
-						grp.groups[grp.counters[i].pos].summary = grp.counters[i].summary;
-					} else {
-						if( (typeof(v) !== "object" && (grp.lastvalues[i] !== v) ) ) {
-							// This record is not in same group as previous one
-							grp.groups.push({idx:i,dataIndex:fieldName,value:v, startRow: irow, cnt:1, summary : [] } );
-							grp.lastvalues[i] = v;
-							changed = 1;
-							grp.counters[i] = {cnt:1, pos:grp.groups.length-1, summary: $.extend(true,[],grp.summary)};
-							$.each(grp.counters[i].summary,function() {
-								if ($.isFunction(this.st)) {
-									this.v = this.st.call($t, this.v, this.nm, record);
-								} else {
-									this.v = $($t).jqGrid('groupingCalculations.handler',this.st, this.v, this.nm, this.sr, this.srt, record);
-								}
-							});
-							grp.groups[grp.counters[i].pos].summary = grp.counters[i].summary;
-						} else {
-							if (changed === 1) {
-								// This group has changed because an earlier group changed.
-								grp.groups.push({idx:i,dataIndex:fieldName,value:v, startRow: irow, cnt:1, summary : [] } );
-								grp.lastvalues[i] = v;
-								grp.counters[i] = {cnt:1, pos:grp.groups.length-1, summary: $.extend(true,[],grp.summary)};
-								$.each(grp.counters[i].summary,function() {
-									if ($.isFunction(this.st)) {
-										this.v = this.st.call($t, this.v, this.nm, record);
-									} else {
-										this.v = $($t).jqGrid('groupingCalculations.handler',this.st, this.v, this.nm, this.sr, this.srt, record);
-									}
-								});
-								grp.groups[grp.counters[i].pos].summary = grp.counters[i].summary;
-							} else {
-								grp.counters[i].cnt += 1;
-								grp.groups[grp.counters[i].pos].cnt = grp.counters[i].cnt;
-								$.each(grp.counters[i].summary,function() {
-									if ($.isFunction(this.st)) {
-										this.v = this.st.call($t, this.v, this.nm, record);
-									} else {
-										this.v = $($t).jqGrid('groupingCalculations.handler',this.st, this.v, this.nm, this.sr, this.srt, record);
-									}
-								});
-								grp.groups[grp.counters[i].pos].summary = grp.counters[i].summary;
-							}
-						}
-					}
-				}
-			}
-			gdata.push( rData );
-		});
-		return gdata;
-	},
-	groupingToggle : function(hid){
-		this.each(function(){
-			var $t = this,
-			grp = $t.p.groupingView,
-			strpos = hid.split('_'),
-			//uid = hid.substring(0,strpos+1),
-			num = parseInt(strpos[strpos.length-2], 10);
-			strpos.splice(strpos.length-2,2);
-			var uid = strpos.join("_"),
-			minus = grp.minusicon,
-			plus = grp.plusicon,
-			tar = $("#"+$.jgrid.jqID(hid)),
-			r = tar.length ? tar[0].nextSibling : null,
-			tarspan = $("#"+$.jgrid.jqID(hid)+" span."+"tree-wrap-"+$t.p.direction),
-			collapsed = false;
-			if( tarspan.hasClass(minus) ) {
-				if(grp.showSummaryOnHide) {
-					if(r){
-						while(r) {
-							if($(r).hasClass('jqfoot') ) { break; }
-							$(r).hide();
-							r = r.nextSibling;
-						}
-					}
-				} else  {
-					if(r){
-						while(r) {
-							if( $(r).hasClass(uid+"_"+String(num) ) || $(r).hasClass(uid+"_"+String(num-1))) { break; }
-							$(r).hide();
-							r = r.nextSibling;
-						}
-					}
-				}
-				tarspan.removeClass(minus).addClass(plus);
-				collapsed = true;
-			} else {
-				if(r){
-					while(r) {
-						if($(r).hasClass(uid+"_"+String(num)) || $(r).hasClass(uid+"_"+String(num-1)) ) { break; }
-						$(r).show();
-						r = r.nextSibling;
-					}
-				}
-				tarspan.removeClass(plus).addClass(minus);
-			}
-			$($t).triggerHandler("jqGridGroupingClickGroup", [hid , collapsed]);
-			if( $.isFunction($t.p.onClickGroup)) { $t.p.onClickGroup.call($t, hid , collapsed); }
-
-		});
-		return false;
-	},
-	groupingRender : function (grdata, colspans ) {
-		return this.each(function(){
-			var $t = this,
-			grp = $t.p.groupingView,
-			str = "", icon = "", hid, clid, pmrtl = grp.groupCollapse ? grp.plusicon : grp.minusicon, gv, cp=[], ii, len =grp.groupField.length;
-			pmrtl += " tree-wrap-"+$t.p.direction;
-			ii = 0;
-			$.each($t.p.colModel, function (i,n){
-				for(var ii=0;ii<len;ii++) {
-					if(grp.groupField[ii] === n.name ) {
-						cp[ii] = i;
-						break;
-					}
-				}
-			});
-			var toEnd = 0;
-			function findGroupIdx( ind , offset, grp) {
-				if(offset===0) {
-					return grp[ind];
-				} else {
-					var id = grp[ind].idx;
-					if(id===0) { return grp[ind]; }
-					for(var i=ind;i >= 0; i--) {
-						if(grp[i].idx === id-offset) {
-							return grp[i];
-						}
-					}
-				}
-			}
-			var sumreverse = grp.groupSummary;
-			sumreverse.reverse();
-			$.each(grp.groups,function(i,n){
-				toEnd++;
-				clid = $t.p.id+"ghead_"+n.idx;
-				hid = clid+"_"+i;
-				icon = "<span style='cursor:pointer;' class='ui-icon "+pmrtl+"' onclick=\"jQuery('#"+$.jgrid.jqID($t.p.id)+"').jqGrid('groupingToggle','"+hid+"');return false;\"></span>";
-				try {
-					gv = $t.formatter(hid, n.value, cp[n.idx], n.value );
-				} catch (egv) {
-					gv = n.value;
-				}
-				str += "<tr id=\""+hid+"\" role=\"row\" class= \"ui-widget-content jqgroup ui-row-"+$t.p.direction+" "+clid+"\"><td style=\"padding-left:"+(n.idx * 12) + "px;"+"\" colspan=\""+colspans+"\">"+icon+$.jgrid.template(grp.groupText[n.idx], gv, n.cnt, n.summary)+"</td></tr>";
-				var leaf = len-1 === n.idx;
-				if( leaf ) {
-					var gg = grp.groups[i+1];
-					var end = gg !== undefined ?  grp.groups[i+1].startRow : grdata.length;
-					for(var kk=n.startRow;kk<end;kk++) {
-						str += grdata[kk].join('');
-					}
-					var jj;
-					if (gg !== undefined) {
-						for (jj = 0; jj < grp.groupField.length; jj++) {
-							if (gg.dataIndex === grp.groupField[jj]) {
-								break;
-							}
-						}
-						toEnd = grp.groupField.length - jj;
-					}
-					for (var ik = 0; ik < toEnd; ik++) {
-						if(!sumreverse[ik]) { continue; }
-						var hhdr = "";
-						if(grp.groupCollapse && !grp.showSummaryOnHide) {
-							hhdr = " style=\"display:none;\"";
-						}
-						str += "<tr"+hhdr+" role=\"row\" class=\"ui-widget-content jqfoot ui-row-"+$t.p.direction+"\">";
-						var fdata = findGroupIdx(i, ik, grp.groups),
-						cm = $t.p.colModel,
-						vv, grlen = fdata.cnt;
-						for(var k=0; k<colspans;k++) {
-							var tmpdata = "<td "+$t.formatCol(k,1,'')+">&#160;</td>",
-							tplfld = "{0}";
-							$.each(fdata.summary,function(){
-								if(this.nm === cm[k].name) {
-									if(cm[k].summaryTpl)  {
-										tplfld = cm[k].summaryTpl;
-									}
-									if(this.st.toLowerCase() === 'avg') {
-										if(this.v && grlen > 0) {
-											this.v = (this.v/grlen);
-										}
-									}
-									try {
-										vv = $t.formatter('', this.v, k, this);
-									} catch (ef) {
-										vv = this.v;
-									}
-									tmpdata= "<td "+$t.formatCol(k,1,'')+">"+$.jgrid.format(tplfld,vv)+ "</td>";
-									return false;
-								}
-							});
-							str += tmpdata;
-						}
-						str += "</tr>";
-					}
-					toEnd = jj;
-				}
-			});
-			$("#"+$.jgrid.jqID($t.p.id)+" tbody:first").append(str);
-			// free up memory
-			str = null;
-		});
-	},
-	groupingGroupBy : function (name, options ) {
-		return this.each(function(){
-			var $t = this;
-			if(typeof(name) === "string") {
-				name = [name];
-			}
-			var grp = $t.p.groupingView;
-			$t.p.grouping = true;
-
-			//Set default, in case visibilityOnNextGrouping is undefined
-			if (typeof grp.visibiltyOnNextGrouping === "undefined") {
-				grp.visibiltyOnNextGrouping = [];
-			}
-			var i;
-			// show previous hidden groups if they are hidden and weren't removed yet
-			for(i=0;i<grp.groupField.length;i++) {
-				if(!grp.groupColumnShow[i] && grp.visibiltyOnNextGrouping[i]) {
-				$($t).jqGrid('showCol',grp.groupField[i]);
-				}
-			}
-			// set visibility status of current group columns on next grouping
-			for(i=0;i<name.length;i++) {
-				grp.visibiltyOnNextGrouping[i] = $("#"+$.jgrid.jqID($t.p.id)+"_"+$.jgrid.jqID(name[i])).is(":visible");
-			}
-			$t.p.groupingView = $.extend($t.p.groupingView, options || {});
-			grp.groupField = name;
-			$($t).trigger("reloadGrid");
-		});
-	},
-	groupingRemove : function (current) {
-		return this.each(function(){
-			var $t = this;
-			if(typeof(current) === 'undefined') {
-				current = true;
-			}
-			$t.p.grouping = false;
-			if(current===true) {
-				var grp = $t.p.groupingView;
-				// show previous hidden groups if they are hidden and weren't removed yet
-				for(var i=0;i<grp.groupField.length;i++) {
-				if (!grp.groupColumnShow[i] && grp.visibiltyOnNextGrouping[i]) {
-						$($t).jqGrid('showCol', grp.groupField);
-					}
-				}
-				$("tr.jqgroup, tr.jqfoot","#"+$.jgrid.jqID($t.p.id)+" tbody:first").remove();
-				$("tr.jqgrow:hidden","#"+$.jgrid.jqID($t.p.id)+" tbody:first").show();
-			} else {
-				$($t).trigger("reloadGrid");
-			}
-		});
-	},
-	groupingCalculations : {
-		handler: function(fn, v, field, round, roundType, rc) {
-			var funcs = {
-				sum: function() {
-					return parseFloat(v||0) + parseFloat((rc[field]||0));
-				},
-
-				min: function() {
-					if(v==="") {
-						return parseFloat(rc[field]||0);
-					}
-					return Math.min(parseFloat(v),parseFloat(rc[field]||0));
-				},
-
-				max: function() {
-					if(v==="") {
-						return parseFloat(rc[field]||0);
-					}
-					return Math.max(parseFloat(v),parseFloat(rc[field]||0));
-				},
-
-				count: function() {
-					if(v==="") {v=0;}
-					if(rc.hasOwnProperty(field)) {
-						return v+1;
-					} else {
-						return 0;
-					}
-				},
-
-				avg: function() {
-					// the same as sum, but at end we divide it
-					// so use sum instead of duplicating the code (?)
-					return funcs.sum();
-				}
-			}
-
-			if(!funcs[fn]) {
-				throw ("jqGrid Grouping No such method: " + fn);
-			}
-			var res = funcs[fn]();
-
-			if (round != null) {
-				if (roundType == 'fixed')
-					res = res.toFixed(round);
-				else {
-					var mul = Math.pow(10, round);
-
-					res = Math.round(res * mul) / mul;
-				}
-			}
-
-			return res;
-		}
-	}
-});
+                if (round != null) {
+                    if (roundType == 'fixed')
+                        res = res.toFixed(round);
+                    else {
+                        var mul = Math.pow(10, round);
+
+                        res = Math.round(res * mul) / mul;
+                    }
+                }
+
+                return res;
+            }
+        }
+    });
 })(jQuery);
-;(function($){
-/*
- * jqGrid extension for constructing Grid Data from external file
- * Tony Tomov tony@trirand.com
- * http://trirand.com/blog/
- * Dual licensed under the MIT and GPL licenses:
- * http://www.opensource.org/licenses/mit-license.php
- * http://www.gnu.org/licenses/gpl-2.0.html
-**/
+;
+(function ($) {
+    /*
+     * jqGrid extension for constructing Grid Data from external file
+     * Tony Tomov tony@trirand.com
+     * http://trirand.com/blog/
+     * Dual licensed under the MIT and GPL licenses:
+     * http://www.opensource.org/licenses/mit-license.php
+     * http://www.gnu.org/licenses/gpl-2.0.html
+     **/
 //jsHint options
-/*global jQuery, $, alert, xmlJsonClass */
+    /*global jQuery, $, alert, xmlJsonClass */
 
-"use strict";
+    "use strict";
     $.jgrid.extend({
-        jqGridImport : function(o) {
+        jqGridImport: function (o) {
             o = $.extend({
-                imptype : "xml", // xml, json, xmlstring, jsonstring
+                imptype: "xml", // xml, json, xmlstring, jsonstring
                 impstring: "",
                 impurl: "",
                 mtype: "GET",
-                impData : {},
-                xmlGrid :{
-                    config : "roots>grid",
+                impData: {},
+                xmlGrid: {
+                    config: "roots>grid",
                     data: "roots>rows"
                 },
-                jsonGrid :{
-                    config : "grid",
+                jsonGrid: {
+                    config: "grid",
                     data: "data"
                 },
-                ajaxOptions :{}
+                ajaxOptions: {}
             }, o || {});
-            return this.each(function(){
+            return this.each(function () {
                 var $t = this;
-                var xmlConvert = function (xml,o) {
-                    var cnfg = $(o.xmlGrid.config,xml)[0];
-                    var xmldata = $(o.xmlGrid.data,xml)[0], jstr, jstr1;
-                    if(xmlJsonClass.xml2json && $.jgrid.parse) {
-                        jstr = xmlJsonClass.xml2json(cnfg," ");
+                var xmlConvert = function (xml, o) {
+                    var cnfg = $(o.xmlGrid.config, xml)[0];
+                    var xmldata = $(o.xmlGrid.data, xml)[0], jstr, jstr1;
+                    if (xmlJsonClass.xml2json && $.jgrid.parse) {
+                        jstr = xmlJsonClass.xml2json(cnfg, " ");
                         jstr = $.jgrid.parse(jstr);
-                        for(var key in jstr) {
-                            if(jstr.hasOwnProperty(key)) {
-                                jstr1=jstr[key];
+                        for (var key in jstr) {
+                            if (jstr.hasOwnProperty(key)) {
+                                jstr1 = jstr[key];
                             }
                         }
-                        if(xmldata) {
-                        // save the datatype
+                        if (xmldata) {
+                            // save the datatype
                             var svdatatype = jstr.grid.datatype;
                             jstr.grid.datatype = 'xmlstring';
                             jstr.grid.datastr = xml;
-                            $($t).jqGrid( jstr1 ).jqGrid("setGridParam",{datatype:svdatatype});
+                            $($t).jqGrid(jstr1).jqGrid("setGridParam", {datatype: svdatatype});
                         } else {
-                            $($t).jqGrid( jstr1 );
+                            $($t).jqGrid(jstr1);
                         }
-                        jstr = null;jstr1=null;
+                        jstr = null;
+                        jstr1 = null;
                     } else {
                         alert("xml2json or parse are not present");
                     }
                 };
-                var jsonConvert = function (jsonstr,o){
+                var jsonConvert = function (jsonstr, o) {
                     if (jsonstr && typeof jsonstr == 'string') {
-						var _jsonparse = false;
-						if($.jgrid.useJSON) {
-							$.jgrid.useJSON = false;
-							_jsonparse = true;
-						}
+                        var _jsonparse = false;
+                        if ($.jgrid.useJSON) {
+                            $.jgrid.useJSON = false;
+                            _jsonparse = true;
+                        }
                         var json = $.jgrid.parse(jsonstr);
-						if(_jsonparse) { $.jgrid.useJSON = true; }
+                        if (_jsonparse) {
+                            $.jgrid.useJSON = true;
+                        }
                         var gprm = json[o.jsonGrid.config];
                         var jdata = json[o.jsonGrid.data];
-                        if(jdata) {
+                        if (jdata) {
                             var svdatatype = gprm.datatype;
                             gprm.datatype = 'jsonstring';
                             gprm.datastr = jdata;
-                            $($t).jqGrid( gprm ).jqGrid("setGridParam",{datatype:svdatatype});
+                            $($t).jqGrid(gprm).jqGrid("setGridParam", {datatype: svdatatype});
                         } else {
-                            $($t).jqGrid( gprm );
+                            $($t).jqGrid(gprm);
                         }
                     }
                 };
-                switch (o.imptype){
+                switch (o.imptype) {
                     case 'xml':
                         $.ajax($.extend({
-                            url:o.impurl,
-                            type:o.mtype,
+                            url: o.impurl,
+                            type: o.mtype,
                             data: o.impData,
-                            dataType:"xml",
-                            complete: function(xml,stat) {
-                                if(stat == 'success') {
-                                    xmlConvert(xml.responseXML,o);
+                            dataType: "xml",
+                            complete: function (xml, stat) {
+                                if (stat == 'success') {
+                                    xmlConvert(xml.responseXML, o);
                                     $($t).triggerHandler("jqGridImportComplete", [xml, o]);
-                                    if($.isFunction(o.importComplete)) {
+                                    if ($.isFunction(o.importComplete)) {
                                         o.importComplete(xml);
                                     }
                                 }
-                                xml=null;
+                                xml = null;
                             }
                         }, o.ajaxOptions));
                         break;
                     case 'xmlstring' :
                         // we need to make just the conversion and use the same code as xml
-                        if(o.impstring && typeof o.impstring == 'string') {
+                        if (o.impstring && typeof o.impstring == 'string') {
                             var xmld = $.jgrid.stringToDoc(o.impstring);
-                            if(xmld) {
-                                xmlConvert(xmld,o);
+                            if (xmld) {
+                                xmlConvert(xmld, o);
                                 $($t).triggerHandler("jqGridImportComplete", [xmld, o]);
-                                if($.isFunction(o.importComplete)) {
+                                if ($.isFunction(o.importComplete)) {
                                     o.importComplete(xmld);
                                 }
                                 o.impstring = null;
@@ -11469,27 +13435,28 @@ $.jgrid.extend({
                         break;
                     case 'json':
                         $.ajax($.extend({
-                            url:o.impurl,
-                            type:o.mtype,
+                            url: o.impurl,
+                            type: o.mtype,
                             data: o.impData,
-                            dataType:"json",
-                            complete: function(json) {
+                            dataType: "json",
+                            complete: function (json) {
                                 try {
-                                    jsonConvert(json.responseText,o );
+                                    jsonConvert(json.responseText, o);
                                     $($t).triggerHandler("jqGridImportComplete", [json, o]);
-                                    if($.isFunction(o.importComplete)) {
+                                    if ($.isFunction(o.importComplete)) {
                                         o.importComplete(json);
                                     }
-                                } catch (ee){}
-                                json=null;
+                                } catch (ee) {
+                                }
+                                json = null;
                             }
-                        }, o.ajaxOptions ));
+                        }, o.ajaxOptions));
                         break;
                     case 'jsonstring' :
-                        if(o.impstring && typeof o.impstring == 'string') {
-                            jsonConvert(o.impstring,o );
+                        if (o.impstring && typeof o.impstring == 'string') {
+                            jsonConvert(o.impstring, o);
                             $($t).triggerHandler("jqGridImportComplete", [o.impstring, o]);
-                            if($.isFunction(o.importComplete)) {
+                            if ($.isFunction(o.importComplete)) {
                                 o.importComplete(o.impstring);
                             }
                             o.impstring = null;
@@ -11498,689 +13465,764 @@ $.jgrid.extend({
                 }
             });
         },
-        jqGridExport : function(o) {
+        jqGridExport: function (o) {
             o = $.extend({
-                exptype : "xmlstring",
+                exptype: "xmlstring",
                 root: "grid",
                 ident: "\t"
             }, o || {});
             var ret = null;
             this.each(function () {
-                if(!this.grid) { return;}
-                var gprm = $.extend(true, {},$(this).jqGrid("getGridParam"));
+                if (!this.grid) {
+                    return;
+                }
+                var gprm = $.extend(true, {}, $(this).jqGrid("getGridParam"));
                 // we need to check for:
                 // 1.multiselect, 2.subgrid  3. treegrid and remove the unneded columns from colNames
-                if(gprm.rownumbers) {
-                    gprm.colNames.splice(0,1);
-                    gprm.colModel.splice(0,1);
+                if (gprm.rownumbers) {
+                    gprm.colNames.splice(0, 1);
+                    gprm.colModel.splice(0, 1);
                 }
-                if(gprm.multiselect) {
-                    gprm.colNames.splice(0,1);
-                    gprm.colModel.splice(0,1);
+                if (gprm.multiselect) {
+                    gprm.colNames.splice(0, 1);
+                    gprm.colModel.splice(0, 1);
                 }
-                if(gprm.subGrid) {
-                    gprm.colNames.splice(0,1);
-                    gprm.colModel.splice(0,1);
+                if (gprm.subGrid) {
+                    gprm.colNames.splice(0, 1);
+                    gprm.colModel.splice(0, 1);
                 }
                 gprm.knv = null;
-                if(gprm.treeGrid) {
+                if (gprm.treeGrid) {
                     for (var key in gprm.treeReader) {
-                        if(gprm.treeReader.hasOwnProperty(key)) {
-                            gprm.colNames.splice(gprm.colNames.length-1);
-                            gprm.colModel.splice(gprm.colModel.length-1);
+                        if (gprm.treeReader.hasOwnProperty(key)) {
+                            gprm.colNames.splice(gprm.colNames.length - 1);
+                            gprm.colModel.splice(gprm.colModel.length - 1);
                         }
                     }
                 }
                 switch (o.exptype) {
                     case 'xmlstring' :
-                        ret = "<"+o.root+">"+xmlJsonClass.json2xml(gprm,o.ident)+"</"+o.root+">";
+                        ret = "<" + o.root + ">" + xmlJsonClass.json2xml(gprm, o.ident) + "</" + o.root + ">";
                         break;
                     case 'jsonstring' :
-                        ret = "{"+ xmlJsonClass.toJson(gprm,o.root,o.ident,false)+"}";
-                        if(gprm.postData.filters !== undefined) {
-                            ret=ret.replace(/filters":"/,'filters":');
-                            ret=ret.replace(/}]}"/,'}]}');
+                        ret = "{" + xmlJsonClass.toJson(gprm, o.root, o.ident, false) + "}";
+                        if (gprm.postData.filters !== undefined) {
+                            ret = ret.replace(/filters":"/, 'filters":');
+                            ret = ret.replace(/}]}"/, '}]}');
                         }
                         break;
                 }
             });
             return ret;
         },
-        excelExport : function(o) {
+        excelExport: function (o) {
             o = $.extend({
-                exptype : "remote",
-                url : null,
+                exptype: "remote",
+                url: null,
                 oper: "oper",
                 tag: "excel",
-                exportOptions : {}
+                exportOptions: {}
             }, o || {});
-            return this.each(function(){
-                if(!this.grid) { return;}
+            return this.each(function () {
+                if (!this.grid) {
+                    return;
+                }
                 var url;
-                if(o.exptype == "remote") {
-                    var pdata = $.extend({},this.p.postData);
+                if (o.exptype == "remote") {
+                    var pdata = $.extend({}, this.p.postData);
                     pdata[o.oper] = o.tag;
                     var params = jQuery.param(pdata);
-                    if(o.url.indexOf("?") != -1) { url = o.url+"&"+params; }
-                    else { url = o.url+"?"+params; }
+                    if (o.url.indexOf("?") != -1) {
+                        url = o.url + "&" + params;
+                    }
+                    else {
+                        url = o.url + "?" + params;
+                    }
                     window.location = url;
                 }
             });
         }
     });
-})(jQuery);;(function($){
-/*
-**
- * jqGrid addons using jQuery UI
- * Author: Mark Williams
- * Dual licensed under the MIT and GPL licenses:
- * http://www.opensource.org/licenses/mit-license.php
- * http://www.gnu.org/licenses/gpl-2.0.html
- * depends on jQuery UI
-**/
-if ($.browser.msie && $.browser.version==8) {
-	$.expr[":"].hidden = function(elem) {
-		return elem.offsetWidth === 0 || elem.offsetHeight === 0 ||
-			elem.style.display == "none";
-	};
-}
+})(jQuery);
+;
+(function ($) {
+    /*
+     **
+     * jqGrid addons using jQuery UI
+     * Author: Mark Williams
+     * Dual licensed under the MIT and GPL licenses:
+     * http://www.opensource.org/licenses/mit-license.php
+     * http://www.gnu.org/licenses/gpl-2.0.html
+     * depends on jQuery UI
+     **/
+    if ($.browser.msie && $.browser.version == 8) {
+        $.expr[":"].hidden = function (elem) {
+            return elem.offsetWidth === 0 || elem.offsetHeight === 0 ||
+                elem.style.display == "none";
+        };
+    }
 // requiere load multiselect before grid
-$.jgrid._multiselect = false;
-if($.ui) {
-	if ($.ui.multiselect ) {
-		if($.ui.multiselect.prototype._setSelected) {
-			var setSelected = $.ui.multiselect.prototype._setSelected;
-		    $.ui.multiselect.prototype._setSelected = function(item,selected) {
-		        var ret = setSelected.call(this,item,selected);
-		        if (selected && this.selectedList) {
-		            var elt = this.element;
-				    this.selectedList.find('li').each(function() {
-					    if ($(this).data('optionLink')) {
-						    $(this).data('optionLink').remove().appendTo(elt);
-					    }
-				    });
-		        }
-		        return ret;
-			};
-		}
-		if($.ui.multiselect.prototype.destroy) {
-			$.ui.multiselect.prototype.destroy = function() {
-				this.element.show();
-				this.container.remove();
-				if ($.Widget === undefined) {
-					$.widget.prototype.destroy.apply(this, arguments);
-				} else {
-					$.Widget.prototype.destroy.apply(this, arguments);
-	            }
-			};
-		}
-		$.jgrid._multiselect = true;
-	}
-}
-
-$.jgrid.extend({
-	sortableColumns : function (tblrow)
-	{
-		return this.each(function (){
-			var ts = this, tid= $.jgrid.jqID( ts.p.id );
-			function start() {ts.p.disableClick = true;}
-			var sortable_opts = {
-				"tolerance" : "pointer",
-				"axis" : "x",
-				"scrollSensitivity": "1",
-				"items": '>th:not(:has(#jqgh_'+tid+'_cb'+',#jqgh_'+tid+'_rn'+',#jqgh_'+tid+'_subgrid),:hidden)',
-				"placeholder": {
-					element: function(item) {
-						var el = $(document.createElement(item[0].nodeName))
-						.addClass(item[0].className+" ui-sortable-placeholder ui-state-highlight")
-						.removeClass("ui-sortable-helper")[0];
-						return el;
-					},
-					update: function(self, p) {
-						p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop')||0, 10) - parseInt(self.currentItem.css('paddingBottom')||0, 10));
-						p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft')||0, 10) - parseInt(self.currentItem.css('paddingRight')||0, 10));
-					}
-				},
-				"update": function(event, ui) {
-					var p = $(ui.item).parent(),
-					th = $(">th", p),
-					colModel = ts.p.colModel,
-					cmMap = {}, tid= ts.p.id+"_";
-					$.each(colModel, function(i) { cmMap[this.name]=i; });
-					var permutation = [];
-					th.each(function() {
-						var id = $(">div", this).get(0).id.replace(/^jqgh_/, "").replace(tid,"");
-							if (id in cmMap) {
-								permutation.push(cmMap[id]);
-							}
-					});
-
-					$(ts).jqGrid("remapColumns",permutation, true, true);
-					if ($.isFunction(ts.p.sortable.update)) {
-						ts.p.sortable.update(permutation);
-					}
-					setTimeout(function(){ts.p.disableClick=false;}, 50);
-				}
-			};
-			if (ts.p.sortable.options) {
-				$.extend(sortable_opts, ts.p.sortable.options);
-			} else if ($.isFunction(ts.p.sortable)) {
-				ts.p.sortable = { "update" : ts.p.sortable };
-			}
-			if (sortable_opts.start) {
-				var s = sortable_opts.start;
-				sortable_opts.start = function(e,ui) {
-					start();
-					s.call(this,e,ui);
-				};
-			} else {
-				sortable_opts.start = start;
-			}
-			if (ts.p.sortable.exclude) {
-				sortable_opts.items += ":not("+ts.p.sortable.exclude+")";
-			}
-			tblrow.sortable(sortable_opts).data("sortable").floating = true;
-		});
-	},
-    columnChooser : function(opts) {
-        var self = this;
-		if($("#colchooser_"+$.jgrid.jqID(self[0].p.id)).length ) { return; }
-        var selector = $('<div id="colchooser_'+self[0].p.id+'" style="position:relative;overflow:hidden"><div><select multiple="multiple"></select></div></div>');
-        var select = $('select', selector);
-
-		function insert(perm,i,v) {
-			if(i>=0){
-				var a = perm.slice();
-				var b = a.splice(i,Math.max(perm.length-i,i));
-				if(i>perm.length) { i = perm.length; }
-				a[i] = v;
-				return a.concat(b);
-			}
-		}
-        opts = $.extend({
-            "width" : 420,
-            "height" : 240,
-            "classname" : null,
-            "done" : function(perm) { if (perm) { self.jqGrid("remapColumns", perm, true); } },
-            /* msel is either the name of a ui widget class that
-               extends a multiselect, or a function that supports
-               creating a multiselect object (with no argument,
-               or when passed an object), and destroying it (when
-               passed the string "destroy"). */
-            "msel" : "multiselect",
-            /* "msel_opts" : {}, */
-
-            /* dlog is either the name of a ui widget class that
-               behaves in a dialog-like way, or a function, that
-               supports creating a dialog (when passed dlog_opts)
-               or destroying a dialog (when passed the string
-               "destroy")
-               */
-            "dlog" : "dialog",
-			"dialog_opts" : {
-				"minWidth": 470
-			},
-            /* dlog_opts is either an option object to be passed
-               to "dlog", or (more likely) a function that creates
-               the options object.
-               The default produces a suitable options object for
-               ui.dialog */
-            "dlog_opts" : function(opts) {
-                var buttons = {};
-                buttons[opts.bSubmit] = function() {
-                    opts.apply_perm();
-                    opts.cleanup(false);
-                };
-                buttons[opts.bCancel] = function() {
-                    opts.cleanup(true);
+    $.jgrid._multiselect = false;
+    if ($.ui) {
+        if ($.ui.multiselect) {
+            if ($.ui.multiselect.prototype._setSelected) {
+                var setSelected = $.ui.multiselect.prototype._setSelected;
+                $.ui.multiselect.prototype._setSelected = function (item, selected) {
+                    var ret = setSelected.call(this, item, selected);
+                    if (selected && this.selectedList) {
+                        var elt = this.element;
+                        this.selectedList.find('li').each(function () {
+                            if ($(this).data('optionLink')) {
+                                $(this).data('optionLink').remove().appendTo(elt);
+                            }
+                        });
+                    }
+                    return ret;
                 };
-                return $.extend(true, {
-                    "buttons": buttons,
-                    "close": function() {
-                        opts.cleanup(true);
-                    },
-					"modal" : opts.modal ? opts.modal : false,
-					"resizable": opts.resizable ? opts.resizable : true,
-                    "width": opts.width+20
-                }, opts.dialog_opts || {});
-            },
-            /* Function to get the permutation array, and pass it to the
-               "done" function */
-            "apply_perm" : function() {
-                $('option',select).each(function() {
-                    if (this.selected) {
-                        self.jqGrid("showCol", colModel[this.value].name);
+            }
+            if ($.ui.multiselect.prototype.destroy) {
+                $.ui.multiselect.prototype.destroy = function () {
+                    this.element.show();
+                    this.container.remove();
+                    if ($.Widget === undefined) {
+                        $.widget.prototype.destroy.apply(this, arguments);
                     } else {
-                        self.jqGrid("hideCol", colModel[this.value].name);
+                        $.Widget.prototype.destroy.apply(this, arguments);
                     }
-                });
+                };
+            }
+            $.jgrid._multiselect = true;
+        }
+    }
 
-                var perm = [];
-				//fixedCols.slice(0);
-                $('option:selected',select).each(function() { perm.push(parseInt(this.value,10)); });
-                $.each(perm, function() { delete colMap[colModel[parseInt(this,10)].name]; });
-                $.each(colMap, function() {
-					var ti = parseInt(this,10);
-					perm = insert(perm,ti,ti);
-				});
-                if (opts.done) {
-                    opts.done.call(self, perm);
-                }
-            },
-            /* Function to cleanup the dialog, and select. Also calls the
-               done function with no permutation (to indicate that the
-               columnChooser was aborted */
-            "cleanup" : function(calldone) {
-                call(opts.dlog, selector, 'destroy');
-                call(opts.msel, select, 'destroy');
-                selector.remove();
-                if (calldone && opts.done) {
-                    opts.done.call(self);
+    $.jgrid.extend({
+        sortableColumns: function (tblrow) {
+            return this.each(function () {
+                var ts = this, tid = $.jgrid.jqID(ts.p.id);
+
+                function start() {
+                    ts.p.disableClick = true;
                 }
-            },
-			"msel_opts" : {}
-        }, $.jgrid.col, opts || {});
-		if($.ui) {
-			if ($.ui.multiselect ) {
-				if(opts.msel == "multiselect") {
-					if(!$.jgrid._multiselect) {
-						// should be in language file
-						alert("Multiselect plugin loaded after jqGrid. Please load the plugin before the jqGrid!");
-						return;
-					}
-					opts.msel_opts = $.extend($.ui.multiselect.defaults,opts.msel_opts);
-				}
-			}
-		}
-        if (opts.caption) {
-            selector.attr("title", opts.caption);
-        }
-        if (opts.classname) {
-            selector.addClass(opts.classname);
-            select.addClass(opts.classname);
-        }
-        if (opts.width) {
-            $(">div",selector).css({"width": opts.width,"margin":"0 auto"});
-            select.css("width", opts.width);
-        }
-        if (opts.height) {
-            $(">div",selector).css("height", opts.height);
-            select.css("height", opts.height - 10);
-        }
-        var colModel = self.jqGrid("getGridParam", "colModel");
-        var colNames = self.jqGrid("getGridParam", "colNames");
-        var colMap = {}, fixedCols = [];
 
-        select.empty();
-        $.each(colModel, function(i) {
-            colMap[this.name] = i;
-            if (this.hidedlg) {
-                if (!this.hidden) {
-                    fixedCols.push(i);
+                var sortable_opts = {
+                    "tolerance": "pointer",
+                    "axis": "x",
+                    "scrollSensitivity": "1",
+                    "items": '>th:not(:has(#jqgh_' + tid + '_cb' + ',#jqgh_' + tid + '_rn' + ',#jqgh_' + tid + '_subgrid),:hidden)',
+                    "placeholder": {
+                        element: function (item) {
+                            var el = $(document.createElement(item[0].nodeName))
+                                .addClass(item[0].className + " ui-sortable-placeholder ui-state-highlight")
+                                .removeClass("ui-sortable-helper")[0];
+                            return el;
+                        },
+                        update: function (self, p) {
+                            p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop') || 0, 10) - parseInt(self.currentItem.css('paddingBottom') || 0, 10));
+                            p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft') || 0, 10) - parseInt(self.currentItem.css('paddingRight') || 0, 10));
+                        }
+                    },
+                    "update": function (event, ui) {
+                        var p = $(ui.item).parent(),
+                            th = $(">th", p),
+                            colModel = ts.p.colModel,
+                            cmMap = {}, tid = ts.p.id + "_";
+                        $.each(colModel, function (i) {
+                            cmMap[this.name] = i;
+                        });
+                        var permutation = [];
+                        th.each(function () {
+                            var id = $(">div", this).get(0).id.replace(/^jqgh_/, "").replace(tid, "");
+                            if (id in cmMap) {
+                                permutation.push(cmMap[id]);
+                            }
+                        });
+
+                        $(ts).jqGrid("remapColumns", permutation, true, true);
+                        if ($.isFunction(ts.p.sortable.update)) {
+                            ts.p.sortable.update(permutation);
+                        }
+                        setTimeout(function () {
+                            ts.p.disableClick = false;
+                        }, 50);
+                    }
+                };
+                if (ts.p.sortable.options) {
+                    $.extend(sortable_opts, ts.p.sortable.options);
+                } else if ($.isFunction(ts.p.sortable)) {
+                    ts.p.sortable = { "update": ts.p.sortable };
+                }
+                if (sortable_opts.start) {
+                    var s = sortable_opts.start;
+                    sortable_opts.start = function (e, ui) {
+                        start();
+                        s.call(this, e, ui);
+                    };
+                } else {
+                    sortable_opts.start = start;
+                }
+                if (ts.p.sortable.exclude) {
+                    sortable_opts.items += ":not(" + ts.p.sortable.exclude + ")";
                 }
+                tblrow.sortable(sortable_opts).data("sortable").floating = true;
+            });
+        },
+        columnChooser: function (opts) {
+            var self = this;
+            if ($("#colchooser_" + $.jgrid.jqID(self[0].p.id)).length) {
                 return;
             }
+            var selector = $('<div id="colchooser_' + self[0].p.id + '" style="position:relative;overflow:hidden"><div><select multiple="multiple"></select></div></div>');
+            var select = $('select', selector);
+
+            function insert(perm, i, v) {
+                if (i >= 0) {
+                    var a = perm.slice();
+                    var b = a.splice(i, Math.max(perm.length - i, i));
+                    if (i > perm.length) {
+                        i = perm.length;
+                    }
+                    a[i] = v;
+                    return a.concat(b);
+                }
+            }
 
-            select.append("<option value='"+i+"' "+
-                          (this.hidden?"":"selected='selected'")+">"+jQuery.jgrid.stripHtml(colNames[i])+"</option>");
-        });
-        function call(fn, obj) {
-            if (!fn) { return; }
-            if (typeof fn == 'string') {
-                if ($.fn[fn]) {
-                    $.fn[fn].apply(obj, $.makeArray(arguments).slice(2));
+            opts = $.extend({
+                "width": 420,
+                "height": 240,
+                "classname": null,
+                "done": function (perm) {
+                    if (perm) {
+                        self.jqGrid("remapColumns", perm, true);
+                    }
+                },
+                /* msel is either the name of a ui widget class that
+                 extends a multiselect, or a function that supports
+                 creating a multiselect object (with no argument,
+                 or when passed an object), and destroying it (when
+                 passed the string "destroy"). */
+                "msel": "multiselect",
+                /* "msel_opts" : {}, */
+
+                /* dlog is either the name of a ui widget class that
+                 behaves in a dialog-like way, or a function, that
+                 supports creating a dialog (when passed dlog_opts)
+                 or destroying a dialog (when passed the string
+                 "destroy")
+                 */
+                "dlog": "dialog",
+                "dialog_opts": {
+                    "minWidth": 470
+                },
+                /* dlog_opts is either an option object to be passed
+                 to "dlog", or (more likely) a function that creates
+                 the options object.
+                 The default produces a suitable options object for
+                 ui.dialog */
+                "dlog_opts": function (opts) {
+                    var buttons = {};
+                    buttons[opts.bSubmit] = function () {
+                        opts.apply_perm();
+                        opts.cleanup(false);
+                    };
+                    buttons[opts.bCancel] = function () {
+                        opts.cleanup(true);
+                    };
+                    return $.extend(true, {
+                        "buttons": buttons,
+                        "close": function () {
+                            opts.cleanup(true);
+                        },
+                        "modal": opts.modal ? opts.modal : false,
+                        "resizable": opts.resizable ? opts.resizable : true,
+                        "width": opts.width + 20
+                    }, opts.dialog_opts || {});
+                },
+                /* Function to get the permutation array, and pass it to the
+                 "done" function */
+                "apply_perm": function () {
+                    $('option', select).each(function () {
+                        if (this.selected) {
+                            self.jqGrid("showCol", colModel[this.value].name);
+                        } else {
+                            self.jqGrid("hideCol", colModel[this.value].name);
+                        }
+                    });
+
+                    var perm = [];
+                    //fixedCols.slice(0);
+                    $('option:selected', select).each(function () {
+                        perm.push(parseInt(this.value, 10));
+                    });
+                    $.each(perm, function () {
+                        delete colMap[colModel[parseInt(this, 10)].name];
+                    });
+                    $.each(colMap, function () {
+                        var ti = parseInt(this, 10);
+                        perm = insert(perm, ti, ti);
+                    });
+                    if (opts.done) {
+                        opts.done.call(self, perm);
+                    }
+                },
+                /* Function to cleanup the dialog, and select. Also calls the
+                 done function with no permutation (to indicate that the
+                 columnChooser was aborted */
+                "cleanup": function (calldone) {
+                    call(opts.dlog, selector, 'destroy');
+                    call(opts.msel, select, 'destroy');
+                    selector.remove();
+                    if (calldone && opts.done) {
+                        opts.done.call(self);
+                    }
+                },
+                "msel_opts": {}
+            }, $.jgrid.col, opts || {});
+            if ($.ui) {
+                if ($.ui.multiselect) {
+                    if (opts.msel == "multiselect") {
+                        if (!$.jgrid._multiselect) {
+                            // should be in language file
+                            alert("Multiselect plugin loaded after jqGrid. Please load the plugin before the jqGrid!");
+                            return;
+                        }
+                        opts.msel_opts = $.extend($.ui.multiselect.defaults, opts.msel_opts);
+                    }
                 }
-            } else if ($.isFunction(fn)) {
-                fn.apply(obj, $.makeArray(arguments).slice(2));
             }
-        }
+            if (opts.caption) {
+                selector.attr("title", opts.caption);
+            }
+            if (opts.classname) {
+                selector.addClass(opts.classname);
+                select.addClass(opts.classname);
+            }
+            if (opts.width) {
+                $(">div", selector).css({"width": opts.width, "margin": "0 auto"});
+                select.css("width", opts.width);
+            }
+            if (opts.height) {
+                $(">div", selector).css("height", opts.height);
+                select.css("height", opts.height - 10);
+            }
+            var colModel = self.jqGrid("getGridParam", "colModel");
+            var colNames = self.jqGrid("getGridParam", "colNames");
+            var colMap = {}, fixedCols = [];
+
+            select.empty();
+            $.each(colModel, function (i) {
+                colMap[this.name] = i;
+                if (this.hidedlg) {
+                    if (!this.hidden) {
+                        fixedCols.push(i);
+                    }
+                    return;
+                }
 
-        var dopts = $.isFunction(opts.dlog_opts) ? opts.dlog_opts.call(self, opts) : opts.dlog_opts;
-        call(opts.dlog, selector, dopts);
-        var mopts = $.isFunction(opts.msel_opts) ? opts.msel_opts.call(self, opts) : opts.msel_opts;
-        call(opts.msel, select, mopts);
-    },
-	sortableRows : function (opts) {
-		// Can accept all sortable options and events
-		return this.each(function(){
-			var $t = this;
-			if(!$t.grid) { return; }
-			// Currently we disable a treeGrid sortable
-			if($t.p.treeGrid) { return; }
-			if($.fn.sortable) {
-				opts = $.extend({
-					"cursor":"move",
-					"axis" : "y",
-					"items": ".jqgrow"
-					},
-				opts || {});
-				if(opts.start && $.isFunction(opts.start)) {
-					opts._start_ = opts.start;
-					delete opts.start;
-				} else {opts._start_=false;}
-				if(opts.update && $.isFunction(opts.update)) {
-					opts._update_ = opts.update;
-					delete opts.update;
-				} else {opts._update_ = false;}
-				opts.start = function(ev,ui) {
-					$(ui.item).css("border-width","0px");
-					$("td",ui.item).each(function(i){
-						this.style.width = $t.grid.cols[i].style.width;
-					});
-					if($t.p.subGrid) {
-						var subgid = $(ui.item).attr("id");
-						try {
-							$($t).jqGrid('collapseSubGridRow',subgid);
-						} catch (e) {}
-					}
-					if(opts._start_) {
-						opts._start_.apply(this,[ev,ui]);
-					}
-				};
-				opts.update = function (ev,ui) {
-					$(ui.item).css("border-width","");
-					if($t.p.rownumbers === true) {
-						$("td.jqgrid-rownum",$t.rows).each(function( i ){
-							$(this).html( i+1+(parseInt($t.p.page,10)-1)*parseInt($t.p.rowNum,10) );
-						});
-					}
-					if(opts._update_) {
-						opts._update_.apply(this,[ev,ui]);
-					}
-				};
-				$("tbody:first",$t).sortable(opts);
-				$("tbody:first",$t).disableSelection();
-			}
-		});
-	},
-	gridDnD : function(opts) {
-		return this.each(function(){
-		var $t = this;
-		if(!$t.grid) { return; }
-		// Currently we disable a treeGrid drag and drop
-		if($t.p.treeGrid) { return; }
-		if(!$.fn.draggable || !$.fn.droppable) { return; }
-		function updateDnD ()
-		{
-			var datadnd = $.data($t,"dnd");
-		    $("tr.jqgrow:not(.ui-draggable)",$t).draggable($.isFunction(datadnd.drag) ? datadnd.drag.call($($t),datadnd) : datadnd.drag);
-		}
-		var appender = "<table id='jqgrid_dnd' class='ui-jqgrid-dnd'></table>";
-		if($("#jqgrid_dnd").html() === null) {
-			$('body').append(appender);
-		}
-
-		if(typeof opts == 'string' && opts == 'updateDnD' && $t.p.jqgdnd===true) {
-			updateDnD();
-			return;
-		}
-		opts = $.extend({
-			"drag" : function (opts) {
-				return $.extend({
-					start : function (ev, ui) {
-						// if we are in subgrid mode try to collapse the node
-						if($t.p.subGrid) {
-							var subgid = $(ui.helper).attr("id");
-							try {
-								$($t).jqGrid('collapseSubGridRow',subgid);
-							} catch (e) {}
-						}
-						// hack
-						// drag and drop does not insert tr in table, when the table has no rows
-						// we try to insert new empty row on the target(s)
-						for (var i=0;i<$.data($t,"dnd").connectWith.length;i++){
-							if($($.data($t,"dnd").connectWith[i]).jqGrid('getGridParam','reccount') == "0" ){
-								$($.data($t,"dnd").connectWith[i]).jqGrid('addRowData','jqg_empty_row',{});
-							}
-						}
-						ui.helper.addClass("ui-state-highlight");
-						$("td",ui.helper).each(function(i) {
-							this.style.width = $t.grid.headers[i].width+"px";
-						});
-						if(opts.onstart && $.isFunction(opts.onstart) ) { opts.onstart.call($($t),ev,ui); }
-					},
-					stop :function(ev,ui) {
-						if(ui.helper.dropped && !opts.dragcopy) {
-							var ids = $(ui.helper).attr("id");
-							if(ids === undefined) { ids = $(this).attr("id"); }
-							$($t).jqGrid('delRowData',ids );
-						}
-						// if we have a empty row inserted from start event try to delete it
-						for (var i=0;i<$.data($t,"dnd").connectWith.length;i++){
-							$($.data($t,"dnd").connectWith[i]).jqGrid('delRowData','jqg_empty_row');
-						}
-						if(opts.onstop && $.isFunction(opts.onstop) ) { opts.onstop.call($($t),ev,ui); }
-					}
-				},opts.drag_opts || {});
-			},
-			"drop" : function (opts) {
-				return $.extend({
-					accept: function(d) {
-						if (!$(d).hasClass('jqgrow')) { return d;}
-						var tid = $(d).closest("table.ui-jqgrid-btable");
-						if(tid.length > 0 && $.data(tid[0],"dnd") !== undefined) {
-						    var cn = $.data(tid[0],"dnd").connectWith;
-						    return $.inArray('#'+$.jgrid.jqID(this.id),cn) != -1 ? true : false;
-						}
-						return false;
-					},
-					drop: function(ev, ui) {
-						if (!$(ui.draggable).hasClass('jqgrow')) { return; }
-						var accept = $(ui.draggable).attr("id");
-						var getdata = ui.draggable.parent().parent().jqGrid('getRowData',accept);
-						if(!opts.dropbyname) {
-							var j =0, tmpdata = {}, nm;
-							var dropmodel = $("#"+$.jgrid.jqID(this.id)).jqGrid('getGridParam','colModel');
-							try {
-								for (var key in getdata) {
-									nm = dropmodel[j].name;
-									if( !(nm == 'cb' || nm =='rn' || nm == 'subgrid' )) {
-										if(getdata.hasOwnProperty(key) && dropmodel[j]) {
-											tmpdata[nm] = getdata[key];
-										}
-									}
-									j++;
-								}
-								getdata = tmpdata;
-							} catch (e) {}
-						}
-						ui.helper.dropped = true;
-						if(opts.beforedrop && $.isFunction(opts.beforedrop) ) {
-							//parameters to this callback - event, element, data to be inserted, sender, reciever
-							// should return object which will be inserted into the reciever
-							var datatoinsert = opts.beforedrop.call(this,ev,ui,getdata,$('#'+$.jgrid.jqID($t.p.id)),$(this));
-							if (typeof datatoinsert != "undefined" && datatoinsert !== null && typeof datatoinsert == "object") { getdata = datatoinsert; }
-						}
-						if(ui.helper.dropped) {
-							var grid;
-							if(opts.autoid) {
-								if($.isFunction(opts.autoid)) {
-									grid = opts.autoid.call(this,getdata);
-								} else {
-									grid = Math.ceil(Math.random()*1000);
-									grid = opts.autoidprefix+grid;
-								}
-							}
-							// NULL is interpreted as undefined while null as object
-							$("#"+$.jgrid.jqID(this.id)).jqGrid('addRowData',grid,getdata,opts.droppos);
-						}
-						if(opts.ondrop && $.isFunction(opts.ondrop) ) { opts.ondrop.call(this,ev,ui, getdata); }
-					}}, opts.drop_opts || {});
-			},
-			"onstart" : null,
-			"onstop" : null,
-			"beforedrop": null,
-			"ondrop" : null,
-			"drop_opts" : {
-				"activeClass": "ui-state-active",
-				"hoverClass": "ui-state-hover"
-			},
-			"drag_opts" : {
-				"revert": "invalid",
-				"helper": "clone",
-				"cursor": "move",
-				"appendTo" : "#jqgrid_dnd",
-				"zIndex": 5000
-			},
-			"dragcopy": false,
-			"dropbyname" : false,
-			"droppos" : "first",
-			"autoid" : true,
-			"autoidprefix" : "dnd_"
-		}, opts || {});
-
-		if(!opts.connectWith) { return; }
-		opts.connectWith = opts.connectWith.split(",");
-		opts.connectWith = $.map(opts.connectWith,function(n){return $.trim(n);});
-		$.data($t,"dnd",opts);
-
-		if($t.p.reccount != "0" && !$t.p.jqgdnd) {
-			updateDnD();
-		}
-		$t.p.jqgdnd = true;
-		for (var i=0;i<opts.connectWith.length;i++){
-			var cn =opts.connectWith[i];
-			$(cn).droppable($.isFunction(opts.drop) ? opts.drop.call($($t),opts) : opts.drop);
-		}
-		});
-	},
-	gridResize : function(opts) {
-		return this.each(function(){
-			var $t = this, gID = $.jgrid.jqID($t.p.id);
-			if(!$t.grid || !$.fn.resizable) { return; }
-			opts = $.extend({}, opts || {});
-			if(opts.alsoResize ) {
-				opts._alsoResize_ = opts.alsoResize;
-				delete opts.alsoResize;
-			} else {
-				opts._alsoResize_ = false;
-			}
-			if(opts.stop && $.isFunction(opts.stop)) {
-				opts._stop_ = opts.stop;
-				delete opts.stop;
-			} else {
-				opts._stop_ = false;
-			}
-			opts.stop = function (ev, ui) {
-				$($t).jqGrid('setGridParam',{height:$("#gview_"+gID+" .ui-jqgrid-bdiv").height()});
-				$($t).jqGrid('setGridWidth',ui.size.width,opts.shrinkToFit);
-				if(opts._stop_) { opts._stop_.call($t,ev,ui); }
-			};
-			if(opts._alsoResize_) {
-				var optstest = "{\'#gview_"+gID+" .ui-jqgrid-bdiv\':true,'" +opts._alsoResize_+"':true}";
-				opts.alsoResize = eval('('+optstest+')'); // the only way that I found to do this
-			} else {
-				opts.alsoResize = $(".ui-jqgrid-bdiv","#gview_"+gID);
-			}
-			delete opts._alsoResize_;
-			$("#gbox_"+gID).resizable(opts);
-		});
-	}
-});
+                select.append("<option value='" + i + "' " +
+                    (this.hidden ? "" : "selected='selected'") + ">" + jQuery.jgrid.stripHtml(colNames[i]) + "</option>");
+            });
+            function call(fn, obj) {
+                if (!fn) {
+                    return;
+                }
+                if (typeof fn == 'string') {
+                    if ($.fn[fn]) {
+                        $.fn[fn].apply(obj, $.makeArray(arguments).slice(2));
+                    }
+                } else if ($.isFunction(fn)) {
+                    fn.apply(obj, $.makeArray(arguments).slice(2));
+                }
+            }
+
+            var dopts = $.isFunction(opts.dlog_opts) ? opts.dlog_opts.call(self, opts) : opts.dlog_opts;
+            call(opts.dlog, selector, dopts);
+            var mopts = $.isFunction(opts.msel_opts) ? opts.msel_opts.call(self, opts) : opts.msel_opts;
+            call(opts.msel, select, mopts);
+        },
+        sortableRows: function (opts) {
+            // Can accept all sortable options and events
+            return this.each(function () {
+                var $t = this;
+                if (!$t.grid) {
+                    return;
+                }
+                // Currently we disable a treeGrid sortable
+                if ($t.p.treeGrid) {
+                    return;
+                }
+                if ($.fn.sortable) {
+                    opts = $.extend({
+                            "cursor": "move",
+                            "axis": "y",
+                            "items": ".jqgrow"
+                        },
+                        opts || {});
+                    if (opts.start && $.isFunction(opts.start)) {
+                        opts._start_ = opts.start;
+                        delete opts.start;
+                    } else {
+                        opts._start_ = false;
+                    }
+                    if (opts.update && $.isFunction(opts.update)) {
+                        opts._update_ = opts.update;
+                        delete opts.update;
+                    } else {
+                        opts._update_ = false;
+                    }
+                    opts.start = function (ev, ui) {
+                        $(ui.item).css("border-width", "0px");
+                        $("td", ui.item).each(function (i) {
+                            this.style.width = $t.grid.cols[i].style.width;
+                        });
+                        if ($t.p.subGrid) {
+                            var subgid = $(ui.item).attr("id");
+                            try {
+                                $($t).jqGrid('collapseSubGridRow', subgid);
+                            } catch (e) {
+                            }
+                        }
+                        if (opts._start_) {
+                            opts._start_.apply(this, [ev, ui]);
+                        }
+                    };
+                    opts.update = function (ev, ui) {
+                        $(ui.item).css("border-width", "");
+                        if ($t.p.rownumbers === true) {
+                            $("td.jqgrid-rownum", $t.rows).each(function (i) {
+                                $(this).html(i + 1 + (parseInt($t.p.page, 10) - 1) * parseInt($t.p.rowNum, 10));
+                            });
+                        }
+                        if (opts._update_) {
+                            opts._update_.apply(this, [ev, ui]);
+                        }
+                    };
+                    $("tbody:first", $t).sortable(opts);
+                    $("tbody:first", $t).disableSelection();
+                }
+            });
+        },
+        gridDnD: function (opts) {
+            return this.each(function () {
+                var $t = this;
+                if (!$t.grid) {
+                    return;
+                }
+                // Currently we disable a treeGrid drag and drop
+                if ($t.p.treeGrid) {
+                    return;
+                }
+                if (!$.fn.draggable || !$.fn.droppable) {
+                    return;
+                }
+                function updateDnD() {
+                    var datadnd = $.data($t, "dnd");
+                    $("tr.jqgrow:not(.ui-draggable)", $t).draggable($.isFunction(datadnd.drag) ? datadnd.drag.call($($t), datadnd) : datadnd.drag);
+                }
+
+                var appender = "<table id='jqgrid_dnd' class='ui-jqgrid-dnd'></table>";
+                if ($("#jqgrid_dnd").html() === null) {
+                    $('body').append(appender);
+                }
+
+                if (typeof opts == 'string' && opts == 'updateDnD' && $t.p.jqgdnd === true) {
+                    updateDnD();
+                    return;
+                }
+                opts = $.extend({
+                    "drag": function (opts) {
+                        return $.extend({
+                            start: function (ev, ui) {
+                                // if we are in subgrid mode try to collapse the node
+                                if ($t.p.subGrid) {
+                                    var subgid = $(ui.helper).attr("id");
+                                    try {
+                                        $($t).jqGrid('collapseSubGridRow', subgid);
+                                    } catch (e) {
+                                    }
+                                }
+                                // hack
+                                // drag and drop does not insert tr in table, when the table has no rows
+                                // we try to insert new empty row on the target(s)
+                                for (var i = 0; i < $.data($t, "dnd").connectWith.length; i++) {
+                                    if ($($.data($t, "dnd").connectWith[i]).jqGrid('getGridParam', 'reccount') == "0") {
+                                        $($.data($t, "dnd").connectWith[i]).jqGrid('addRowData', 'jqg_empty_row', {});
+                                    }
+                                }
+                                ui.helper.addClass("ui-state-highlight");
+                                $("td", ui.helper).each(function (i) {
+                                    this.style.width = $t.grid.headers[i].width + "px";
+                                });
+                                if (opts.onstart && $.isFunction(opts.onstart)) {
+                                    opts.onstart.call($($t), ev, ui);
+                                }
+                            },
+                            stop: function (ev, ui) {
+                                if (ui.helper.dropped && !opts.dragcopy) {
+                                    var ids = $(ui.helper).attr("id");
+                                    if (ids === undefined) {
+                                        ids = $(this).attr("id");
+                                    }
+                                    $($t).jqGrid('delRowData', ids);
+                                }
+                                // if we have a empty row inserted from start event try to delete it
+                                for (var i = 0; i < $.data($t, "dnd").connectWith.length; i++) {
+                                    $($.data($t, "dnd").connectWith[i]).jqGrid('delRowData', 'jqg_empty_row');
+                                }
+                                if (opts.onstop && $.isFunction(opts.onstop)) {
+                                    opts.onstop.call($($t), ev, ui);
+                                }
+                            }
+                        }, opts.drag_opts || {});
+                    },
+                    "drop": function (opts) {
+                        return $.extend({
+                            accept: function (d) {
+                                if (!$(d).hasClass('jqgrow')) {
+                                    return d;
+                                }
+                                var tid = $(d).closest("table.ui-jqgrid-btable");
+                                if (tid.length > 0 && $.data(tid[0], "dnd") !== undefined) {
+                                    var cn = $.data(tid[0], "dnd").connectWith;
+                                    return $.inArray('#' + $.jgrid.jqID(this.id), cn) != -1 ? true : false;
+                                }
+                                return false;
+                            },
+                            drop: function (ev, ui) {
+                                if (!$(ui.draggable).hasClass('jqgrow')) {
+                                    return;
+                                }
+                                var accept = $(ui.draggable).attr("id");
+                                var getdata = ui.draggable.parent().parent().jqGrid('getRowData', accept);
+                                if (!opts.dropbyname) {
+                                    var j = 0, tmpdata = {}, nm;
+                                    var dropmodel = $("#" + $.jgrid.jqID(this.id)).jqGrid('getGridParam', 'colModel');
+                                    try {
+                                        for (var key in getdata) {
+                                            nm = dropmodel[j].name;
+                                            if (!(nm == 'cb' || nm == 'rn' || nm == 'subgrid' )) {
+                                                if (getdata.hasOwnProperty(key) && dropmodel[j]) {
+                                                    tmpdata[nm] = getdata[key];
+                                                }
+                                            }
+                                            j++;
+                                        }
+                                        getdata = tmpdata;
+                                    } catch (e) {
+                                    }
+                                }
+                                ui.helper.dropped = true;
+                                if (opts.beforedrop && $.isFunction(opts.beforedrop)) {
+                                    //parameters to this callback - event, element, data to be inserted, sender, reciever
+                                    // should return object which will be inserted into the reciever
+                                    var datatoinsert = opts.beforedrop.call(this, ev, ui, getdata, $('#' + $.jgrid.jqID($t.p.id)), $(this));
+                                    if (typeof datatoinsert != "undefined" && datatoinsert !== null && typeof datatoinsert == "object") {
+                                        getdata = datatoinsert;
+                                    }
+                                }
+                                if (ui.helper.dropped) {
+                                    var grid;
+                                    if (opts.autoid) {
+                                        if ($.isFunction(opts.autoid)) {
+                                            grid = opts.autoid.call(this, getdata);
+                                        } else {
+                                            grid = Math.ceil(Math.random() * 1000);
+                                            grid = opts.autoidprefix + grid;
+                                        }
+                                    }
+                                    // NULL is interpreted as undefined while null as object
+                                    $("#" + $.jgrid.jqID(this.id)).jqGrid('addRowData', grid, getdata, opts.droppos);
+                                }
+                                if (opts.ondrop && $.isFunction(opts.ondrop)) {
+                                    opts.ondrop.call(this, ev, ui, getdata);
+                                }
+                            }}, opts.drop_opts || {});
+                    },
+                    "onstart": null,
+                    "onstop": null,
+                    "beforedrop": null,
+                    "ondrop": null,
+                    "drop_opts": {
+                        "activeClass": "ui-state-active",
+                        "hoverClass": "ui-state-hover"
+                    },
+                    "drag_opts": {
+                        "revert": "invalid",
+                        "helper": "clone",
+                        "cursor": "move",
+                        "appendTo": "#jqgrid_dnd",
+                        "zIndex": 5000
+                    },
+                    "dragcopy": false,
+                    "dropbyname": false,
+                    "droppos": "first",
+                    "autoid": true,
+                    "autoidprefix": "dnd_"
+                }, opts || {});
+
+                if (!opts.connectWith) {
+                    return;
+                }
+                opts.connectWith = opts.connectWith.split(",");
+                opts.connectWith = $.map(opts.connectWith, function (n) {
+                    return $.trim(n);
+                });
+                $.data($t, "dnd", opts);
+
+                if ($t.p.reccount != "0" && !$t.p.jqgdnd) {
+                    updateDnD();
+                }
+                $t.p.jqgdnd = true;
+                for (var i = 0; i < opts.connectWith.length; i++) {
+                    var cn = opts.connectWith[i];
+                    $(cn).droppable($.isFunction(opts.drop) ? opts.drop.call($($t), opts) : opts.drop);
+                }
+            });
+        },
+        gridResize: function (opts) {
+            return this.each(function () {
+                var $t = this, gID = $.jgrid.jqID($t.p.id);
+                if (!$t.grid || !$.fn.resizable) {
+                    return;
+                }
+                opts = $.extend({}, opts || {});
+                if (opts.alsoResize) {
+                    opts._alsoResize_ = opts.alsoResize;
+                    delete opts.alsoResize;
+                } else {
+                    opts._alsoResize_ = false;
+                }
+                if (opts.stop && $.isFunction(opts.stop)) {
+                    opts._stop_ = opts.stop;
+                    delete opts.stop;
+                } else {
+                    opts._stop_ = false;
+                }
+                opts.stop = function (ev, ui) {
+                    $($t).jqGrid('setGridParam', {height: $("#gview_" + gID + " .ui-jqgrid-bdiv").height()});
+                    $($t).jqGrid('setGridWidth', ui.size.width, opts.shrinkToFit);
+                    if (opts._stop_) {
+                        opts._stop_.call($t, ev, ui);
+                    }
+                };
+                if (opts._alsoResize_) {
+                    var optstest = "{\'#gview_" + gID + " .ui-jqgrid-bdiv\':true,'" + opts._alsoResize_ + "':true}";
+                    opts.alsoResize = eval('(' + optstest + ')'); // the only way that I found to do this
+                } else {
+                    opts.alsoResize = $(".ui-jqgrid-bdiv", "#gview_" + gID);
+                }
+                delete opts._alsoResize_;
+                $("#gbox_" + gID).resizable(opts);
+            });
+        }
+    });
 })(jQuery);
 /*
  Transform a table to a jqGrid.
  Peter Romianowski <peter.romianowski@optivo.de>
  If the first column of the table contains checkboxes or
  radiobuttons then the jqGrid is made selectable.
-*/
+ */
 // Addition - selector can be a class or id
 function tableToGrid(selector, options) {
-jQuery(selector).each(function() {
-	if(this.grid) {return;} //Adedd from Tony Tomov
-	// This is a small "hack" to make the width of the jqGrid 100%
-	jQuery(this).width("99%");
-	var w = jQuery(this).width();
-
-	// Text whether we have single or multi select
-	var inputCheckbox = jQuery('tr td:first-child input[type=checkbox]:first', jQuery(this));
-	var inputRadio = jQuery('tr td:first-child input[type=radio]:first', jQuery(this));
-	var selectMultiple = inputCheckbox.length > 0;
-	var selectSingle = !selectMultiple && inputRadio.length > 0;
-	var selectable = selectMultiple || selectSingle;
-	//var inputName = inputCheckbox.attr("name") || inputRadio.attr("name");
-
-	// Build up the columnModel and the data
-	var colModel = [];
-	var colNames = [];
-	jQuery('th', jQuery(this)).each(function() {
-		if (colModel.length === 0 && selectable) {
-			colModel.push({
-				name: '__selection__',
-				index: '__selection__',
-				width: 0,
-				hidden: true
-			});
-			colNames.push('__selection__');
-		} else {
-			colModel.push({
-				name: jQuery(this).attr("id") || jQuery.trim(jQuery.jgrid.stripHtml(jQuery(this).html())).split(' ').join('_'),
-				index: jQuery(this).attr("id") || jQuery.trim(jQuery.jgrid.stripHtml(jQuery(this).html())).split(' ').join('_'),
-				width: jQuery(this).width() || 150
-			});
-			colNames.push(jQuery(this).html());
-		}
-	});
-	var data = [];
-	var rowIds = [];
-	var rowChecked = [];
-	jQuery('tbody > tr', jQuery(this)).each(function() {
-		var row = {};
-		var rowPos = 0;
-		jQuery('td', jQuery(this)).each(function() {
-			if (rowPos === 0 && selectable) {
-				var input = jQuery('input', jQuery(this));
-				var rowId = input.attr("value");
-				rowIds.push(rowId || data.length);
-				if (input.is(":checked")) {
-					rowChecked.push(rowId);
-				}
-				row[colModel[rowPos].name] = input.attr("value");
-			} else {
-				row[colModel[rowPos].name] = jQuery(this).html();
-			}
-			rowPos++;
-		});
-		if(rowPos >0) { data.push(row); }
-	});
-
-	// Clear the original HTML table
-	jQuery(this).empty();
-
-	// Mark it as jqGrid
-	jQuery(this).addClass("scroll");
-
-	jQuery(this).jqGrid(jQuery.extend({
-		datatype: "local",
-		width: w,
-		colNames: colNames,
-		colModel: colModel,
-		multiselect: selectMultiple
-		//inputName: inputName,
-		//inputValueCol: imputName != null ? "__selection__" : null
-	}, options || {}));
-
-	// Add data
-	var a;
-	for (a = 0; a < data.length; a++) {
-		var id = null;
-		if (rowIds.length > 0) {
-			id = rowIds[a];
-			if (id && id.replace) {
-				// We have to do this since the value of a checkbox
-				// or radio button can be anything
-				id = encodeURIComponent(id).replace(/[.\-%]/g, "_");
-			}
-		}
-		if (id === null) {
-			id = a + 1;
-		}
-		jQuery(this).jqGrid("addRowData",id, data[a]);
-	}
-
-	// Set the selection
-	for (a = 0; a < rowChecked.length; a++) {
-		jQuery(this).jqGrid("setSelection",rowChecked[a]);
-	}
-});
+    jQuery(selector).each(function () {
+        if (this.grid) {
+            return;
+        } //Adedd from Tony Tomov
+        // This is a small "hack" to make the width of the jqGrid 100%
+        jQuery(this).width("99%");
+        var w = jQuery(this).width();
+
+        // Text whether we have single or multi select
+        var inputCheckbox = jQuery('tr td:first-child input[type=checkbox]:first', jQuery(this));
+        var inputRadio = jQuery('tr td:first-child input[type=radio]:first', jQuery(this));
+        var selectMultiple = inputCheckbox.length > 0;
+        var selectSingle = !selectMultiple && inputRadio.length > 0;
+        var selectable = selectMultiple || selectSingle;
+        //var inputName = inputCheckbox.attr("name") || inputRadio.attr("name");
+
+        // Build up the columnModel and the data
+        var colModel = [];
+        var colNames = [];
+        jQuery('th', jQuery(this)).each(function () {
+            if (colModel.length === 0 && selectable) {
+                colModel.push({
+                    name: '__selection__',
+                    index: '__selection__',
+                    width: 0,
+                    hidden: true
+                });
+                colNames.push('__selection__');
+            } else {
+                colModel.push({
+                    name: jQuery(this).attr("id") || jQuery.trim(jQuery.jgrid.stripHtml(jQuery(this).html())).split(' ').join('_'),
+                    index: jQuery(this).attr("id") || jQuery.trim(jQuery.jgrid.stripHtml(jQuery(this).html())).split(' ').join('_'),
+                    width: jQuery(this).width() || 150
+                });
+                colNames.push(jQuery(this).html());
+            }
+        });
+        var data = [];
+        var rowIds = [];
+        var rowChecked = [];
+        jQuery('tbody > tr', jQuery(this)).each(function () {
+            var row = {};
+            var rowPos = 0;
+            jQuery('td', jQuery(this)).each(function () {
+                if (rowPos === 0 && selectable) {
+                    var input = jQuery('input', jQuery(this));
+                    var rowId = input.attr("value");
+                    rowIds.push(rowId || data.length);
+                    if (input.is(":checked")) {
+                        rowChecked.push(rowId);
+                    }
+                    row[colModel[rowPos].name] = input.attr("value");
+                } else {
+                    row[colModel[rowPos].name] = jQuery(this).html();
+                }
+                rowPos++;
+            });
+            if (rowPos > 0) {
+                data.push(row);
+            }
+        });
+
+        // Clear the original HTML table
+        jQuery(this).empty();
+
+        // Mark it as jqGrid
+        jQuery(this).addClass("scroll");
+
+        jQuery(this).jqGrid(jQuery.extend({
+            datatype: "local",
+            width: w,
+            colNames: colNames,
+            colModel: colModel,
+            multiselect: selectMultiple
+            //inputName: inputName,
+            //inputValueCol: imputName != null ? "__selection__" : null
+        }, options || {}));
+
+        // Add data
+        var a;
+        for (a = 0; a < data.length; a++) {
+            var id = null;
+            if (rowIds.length > 0) {
+                id = rowIds[a];
+                if (id && id.replace) {
+                    // We have to do this since the value of a checkbox
+                    // or radio button can be anything
+                    id = encodeURIComponent(id).replace(/[.\-%]/g, "_");
+                }
+            }
+            if (id === null) {
+                id = a + 1;
+            }
+            jQuery(this).jqGrid("addRowData", id, data[a]);
+        }
+
+        // Set the selection
+        for (a = 0; a < rowChecked.length; a++) {
+            jQuery(this).jqGrid("setSelection", rowChecked[a]);
+        }
+    });
 };
diff --git a/media/js/lib/jquery.json-2.2.min.js b/media/js/lib/jquery.json-2.2.min.js
index bad4a0a..71089ea 100644
--- a/media/js/lib/jquery.json-2.2.min.js
+++ b/media/js/lib/jquery.json-2.2.min.js
@@ -1,31 +1,86 @@
-
-(function($){$.toJSON=function(o)
-{if(typeof(JSON)=='object'&&JSON.stringify)
-return JSON.stringify(o);var type=typeof(o);if(o===null)
-return"null";if(type=="undefined")
-return undefined;if(type=="number"||type=="boolean")
-return o+"";if(type=="string")
-return $.quoteString(o);if(type=='object')
-{if(typeof o.toJSON=="function")
-return $.toJSON(o.toJSON());if(o.constructor===Date)
-{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
-hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
-if(o.constructor===Array)
-{var ret=[];for(var i=0;i<o.length;i++)
-ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]";}
-var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
-name='"'+k+'"';else if(type=="string")
-name=$.quoteString(k);else
-continue;if(typeof o[k]=="function")
-continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
-return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src)
-{if(typeof(JSON)=='object'&&JSON.parse)
-return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src)
-{if(typeof(JSON)=='object'&&JSON.parse)
-return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
-return eval("("+src+")");else
-throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
-{if(string.match(_escapeable))
-{return'"'+string.replace(_escapeable,function(a)
-{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
-return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};})(jQuery);
\ No newline at end of file
+(function ($) {
+    $.toJSON = function (o) {
+        if (typeof(JSON) == 'object' && JSON.stringify)
+            return JSON.stringify(o);
+        var type = typeof(o);
+        if (o === null)
+            return"null";
+        if (type == "undefined")
+            return undefined;
+        if (type == "number" || type == "boolean")
+            return o + "";
+        if (type == "string")
+            return $.quoteString(o);
+        if (type == 'object') {
+            if (typeof o.toJSON == "function")
+                return $.toJSON(o.toJSON());
+            if (o.constructor === Date) {
+                var month = o.getUTCMonth() + 1;
+                if (month < 10)month = '0' + month;
+                var day = o.getUTCDate();
+                if (day < 10)day = '0' + day;
+                var year = o.getUTCFullYear();
+                var hours = o.getUTCHours();
+                if (hours < 10)hours = '0' + hours;
+                var minutes = o.getUTCMinutes();
+                if (minutes < 10)minutes = '0' + minutes;
+                var seconds = o.getUTCSeconds();
+                if (seconds < 10)seconds = '0' + seconds;
+                var milli = o.getUTCMilliseconds();
+                if (milli < 100)milli = '0' + milli;
+                if (milli < 10)milli = '0' + milli;
+                return'"' + year + '-' + month + '-' + day + 'T' +
+                    hours + ':' + minutes + ':' + seconds + '.' + milli + 'Z"';
+            }
+            if (o.constructor === Array) {
+                var ret = [];
+                for (var i = 0; i < o.length; i++)
+                    ret.push($.toJSON(o[i]) || "null");
+                return"[" + ret.join(",") + "]";
+            }
+            var pairs = [];
+            for (var k in o) {
+                var name;
+                var type = typeof k;
+                if (type == "number")
+                    name = '"' + k + '"'; else if (type == "string")
+                    name = $.quoteString(k); else
+                    continue;
+                if (typeof o[k] == "function")
+                    continue;
+                var val = $.toJSON(o[k]);
+                pairs.push(name + ":" + val);
+            }
+            return"{" + pairs.join(", ") + "}";
+        }
+    };
+    $.evalJSON = function (src) {
+        if (typeof(JSON) == 'object' && JSON.parse)
+            return JSON.parse(src);
+        return eval("(" + src + ")");
+    };
+    $.secureEvalJSON = function (src) {
+        if (typeof(JSON) == 'object' && JSON.parse)
+            return JSON.parse(src);
+        var filtered = src;
+        filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
+        filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
+        filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
+        if (/^[\],:{}\s]*$/.test(filtered))
+            return eval("(" + src + ")"); else
+            throw new SyntaxError("Error parsing JSON, source is not valid.");
+    };
+    $.quoteString = function (string) {
+        if (string.match(_escapeable)) {
+            return'"' + string.replace(_escapeable, function (a) {
+                var c = _meta[a];
+                if (typeof c === 'string')return c;
+                c = a.charCodeAt();
+                return'\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
+            }) + '"';
+        }
+        return'"' + string + '"';
+    };
+    var _escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
+    var _meta = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\'};
+})(jQuery);
\ No newline at end of file
diff --git a/media/js/lib/jquery.layout.min-1.2.0.js b/media/js/lib/jquery.layout.min-1.2.0.js
index bcc2f0f..f1edb88 100644
--- a/media/js/lib/jquery.layout.min-1.2.0.js
+++ b/media/js/lib/jquery.layout.min-1.2.0.js
@@ -13,68 +13,973 @@
  * 
  * NOTE: For best code readability, view this with a fixed-space font and tabs equal to 4-chars
  */
-(function($){$.fn.layout=function(opts){var
-prefix="ui-layout-",defaults={paneClass:prefix+"pane",resizerClass:prefix+"resizer",togglerClass:prefix+"toggler",togglerInnerClass:prefix+"",buttonClass:prefix+"button",contentSelector:"."+prefix+"content",contentIgnoreSelector:"."+prefix+"ignore"};var options={name:"",scrollToBookmarkOnLoad:true,defaults:{applyDefaultStyles:false,closable:true,resizable:true,slidable:true,contentSelector:defaults.contentSelector,contentIgnoreSelector:defaults.contentIgnoreSelector,paneClass:defaults.paneClass,resizerClass:defaults.resizerClass,togglerClass:defaults.togglerClass,buttonClass:defaults.buttonClass,resizerDragOpacity:1,maskIframesOnResize:true,minSize:0,maxSize:0,spacing_open:6,spacing_closed:6,togglerLength_open:50,togglerLength_closed:50,togglerAlign_open:"center",togglerAlign_closed:"center",togglerTip_open:"Close",togglerTip_closed:"Open",resizerTip:"Resize",sliderTip:"Slide Open",sliderCursor:"pointer",slideTrigger_open:"click",slideTrigger_close:"mouseout",hideTogglerOnSlide:false,togglerContent_open:"",togglerContent_closed:"",showOverflowOnHover:false,enableCursorHotkey:true,customHotkeyModifier:"SHIFT",fxName:"slide",fxSpeed:null,fxSettings:{},initClosed:false,initHidden:false},north:{paneSelector:"."+prefix+"north",size:"auto",resizerCursor:"n-resize"},south:{paneSelector:"."+prefix+"south",size:"auto",resizerCursor:"s-resize"},east:{paneSelector:"."+prefix+"east",size:200,resizerCursor:"e-resize"},west:{paneSelector:"."+prefix+"west",size:200,resizerCursor:"w-resize"},center:{paneSelector:"."+prefix+"center"}};var effects={slide:{all:{duration:"fast"},north:{direction:"up"},south:{direction:"down"},east:{direction:"right"},west:{direction:"left"}},drop:{all:{duration:"slow"},north:{direction:"up"},south:{direction:"down"},east:{direction:"right"},west:{direction:"left"}},scale:{all:{duration:"fast"}}};var config={allPanes:"north,south,east,west,center",borderPanes:"north,south,east,west",zIndex:{resizer_normal:1,pane_normal:2,mask:4,sliding:100,resizing:10000,animation:10000},resizers:{cssReq:{position:"absolute",padding:0,margin:0,fontSize:"1px",textAlign:"left",overflow:"hidden",zIndex:1},cssDef:{background:"#DDD",border:"none"}},togglers:{cssReq:{position:"absolute",display:"block",padding:0,margin:0,overflow:"hidden",textAlign:"center",fontSize:"1px",cursor:"pointer",zIndex:1},cssDef:{background:"#AAA"}},content:{cssReq:{overflow:"auto"},cssDef:{}},defaults:{cssReq:{position:"absolute",margin:0,zIndex:2},cssDef:{padding:"10px",background:"#FFF",border:"1px solid #BBB",overflow:"auto"}},north:{edge:"top",sizeType:"height",dir:"horz",cssReq:{top:0,bottom:"auto",left:0,right:0,width:"auto"}},south:{edge:"bottom",sizeType:"height",dir:"horz",cssReq:{top:"auto",bottom:0,left:0,right:0,width:"auto"}},east:{edge:"right",sizeType:"width",dir:"vert",cssReq:{left:"auto",right:0,top:"auto",bottom:"auto",height:"auto"}},west:{edge:"left",sizeType:"width",dir:"vert",cssReq:{left:0,right:"auto",top:"auto",bottom:"auto",height:"auto"}},center:{dir:"center",cssReq:{left:"auto",right:"auto",top:"auto",bottom:"auto",height:"auto",width:"auto"}}};var state={id:Math.floor(Math.random()*10000),container:{},north:{},south:{},east:{},west:{},center:{}};var
-altEdge={top:"bottom",bottom:"top",left:"right",right:"left"},altSide={north:"south",south:"north",east:"west",west:"east"};var isStr=function(o){if(typeof o=="string")return true;else if(typeof o=="object"){try{var match=o.constructor.toString().match(/string/i);return(match!==null);}catch(e){}}return false;};var str=function(o){if(typeof o=="string"||isStr(o))return $.trim(o);else return o;};var min=function(x,y){return Math.min(x,y);};var max=function(x,y){return Math.max(x,y);};var transformData=function(d){var json={defaults:{fxSettings:{}},north:{fxSettings:{}},south:{fxSettings:{}},east:{fxSettings:{}},west:{fxSettings:{}},center:{fxSettings:{}}};d=d||{};if(d.effects||d.defaults||d.north||d.south||d.west||d.east||d.center)json=$.extend(json,d);else
-$.each(d,function(key,val){a=key.split("__");json[a[1]?a[0]:"defaults"][a[1]?a[1]:a[0]]=val;});return json;};var setFlowCallback=function(action,pane,param){var
-cb=action+","+pane+","+(param?1:0),cP,cbPane;$.each(c.borderPanes.split(","),function(i,p){if(c[p].isMoving){bindCallback(p);return false;}});function bindCallback(p,test){cP=c[p];if(!cP.doCallback){cP.doCallback=true;cP.callback=cb;}else{cpPane=cP.callback.split(",")[1];if(cpPane!=p&&cpPane!=pane)bindCallback(cpPane,true);}}};var execFlowCallback=function(pane){var cP=c[pane];c.isLayoutBusy=false;delete cP.isMoving;if(!cP.doCallback||!cP.callback)return;cP.doCallback=false;var
-cb=cP.callback.split(","),param=(cb[2]>0?true:false);if(cb[0]=="open")open(cb[1],param);else if(cb[0]=="close")close(cb[1],param);if(!cP.doCallback)cP.callback=null;};var execUserCallback=function(pane,v_fn){if(!v_fn)return;var fn;try{if(typeof v_fn=="function")fn=v_fn;else if(typeof v_fn!="string")return;else if(v_fn.indexOf(",")>0){var
-args=v_fn.split(","),fn=eval(args[0]);if(typeof fn=="function"&&args.length>1)return fn(args[1]);}else
-fn=eval(v_fn);if(typeof fn=="function")return fn(pane,$Ps[pane],$.extend({},state[pane]),$.extend({},options[pane]),options.name);}catch(ex){}};var cssNum=function($E,prop){var
-val=0,hidden=false,visibility="";if(!$.browser.msie){if($.curCSS($E[0],"display",true)=="none"){hidden=true;visibility=$.curCSS($E[0],"visibility",true);$E.css({display:"block",visibility:"hidden"});}}val=parseInt($.curCSS($E[0],prop,true),10)||0;if(hidden){$E.css({display:"none"});if(visibility&&visibility!="hidden")$E.css({visibility:visibility});}return val;};var cssW=function(e,outerWidth){var $E;if(isStr(e)){e=str(e);$E=$Ps[e];}else
-$E=$(e);if(outerWidth<=0)return 0;else if(!(outerWidth>0))outerWidth=isStr(e)?getPaneSize(e):$E.outerWidth();if(!$.boxModel)return outerWidth;else
-return outerWidth
--cssNum($E,"paddingLeft")-cssNum($E,"paddingRight")-($.curCSS($E[0],"borderLeftStyle",true)=="none"?0:cssNum($E,"borderLeftWidth"))-($.curCSS($E[0],"borderRightStyle",true)=="none"?0:cssNum($E,"borderRightWidth"));};var cssH=function(e,outerHeight){var $E;if(isStr(e)){e=str(e);$E=$Ps[e];}else
-$E=$(e);if(outerHeight<=0)return 0;else if(!(outerHeight>0))outerHeight=(isStr(e))?getPaneSize(e):$E.outerHeight();if(!$.boxModel)return outerHeight;else
-return outerHeight
--cssNum($E,"paddingTop")-cssNum($E,"paddingBottom")-($.curCSS($E[0],"borderTopStyle",true)=="none"?0:cssNum($E,"borderTopWidth"))-($.curCSS($E[0],"borderBottomStyle",true)=="none"?0:cssNum($E,"borderBottomWidth"));};var cssSize=function(pane,outerSize){if(c[pane].dir=="horz")return cssH(pane,outerSize);else
-return cssW(pane,outerSize);};var getPaneSize=function(pane,inclSpace){var
-$P=$Ps[pane],o=options[pane],s=state[pane],oSp=(inclSpace?o.spacing_open:0),cSp=(inclSpace?o.spacing_closed:0);if(!$P||s.isHidden)return 0;else if(s.isClosed||(s.isSliding&&inclSpace))return cSp;else if(c[pane].dir=="horz")return $P.outerHeight()+oSp;else
-return $P.outerWidth()+oSp;};var setPaneMinMaxSizes=function(pane){var
-d=cDims,edge=c[pane].edge,dir=c[pane].dir,o=options[pane],s=state[pane],$P=$Ps[pane],$altPane=$Ps[altSide[pane]],paneSpacing=o.spacing_open,altPaneSpacing=options[altSide[pane]].spacing_open,altPaneSize=(!$altPane?0:(dir=="horz"?$altPane.outerHeight():$altPane.outerWidth())),containerSize=(dir=="horz"?d.innerHeight:d.innerWidth),limitSize=containerSize-paneSpacing-altPaneSize-altPaneSpacing,minSize=s.minSize||0,maxSize=Math.min(s.maxSize||9999,limitSize),minPos,maxPos;switch(pane){case"north":minPos=d.offsetTop+minSize;maxPos=d.offsetTop+maxSize;break;case"west":minPos=d.offsetLeft+minSize;maxPos=d.offsetLeft+maxSize;break;case"south":minPos=d.offsetTop+d.innerHeight-maxSize;maxPos=d.offsetTop+d.innerHeight-minSize;break;case"east":minPos=d.offsetLeft+d.innerWidth-maxSize;maxPos=d.offsetLeft+d.innerWidth-minSize;break;}$.extend(s,{minSize:minSize,maxSize:maxSize,minPosition:minPos,maxPosition:maxPos});};var getPaneDims=function(){var d={top:getPaneSize("north",true),bottom:getPaneSize("south",true),left:getPaneSize("west",true),right:getPaneSize("east",true),width:0,height:0};with(d){width=cDims.innerWidth-left-right;height=cDims.innerHeight-bottom-top;top+=cDims.top;bottom+=cDims.bottom;left+=cDims.left;right+=cDims.right;}return d;};var getElemDims=function($E){var
-d={},e,b,p;$.each("Left,Right,Top,Bottom".split(","),function(){e=str(this);b=d["border"+e]=cssNum($E,"border"+e+"Width");p=d["padding"+e]=cssNum($E,"padding"+e);d["offset"+e]=b+p;if($E==$Container)d[e.toLowerCase()]=($.boxModel?p:0);});d.innerWidth=d.outerWidth=$E.outerWidth();d.innerHeight=d.outerHeight=$E.outerHeight();if($.boxModel){d.innerWidth-=(d.offsetLeft+d.offsetRight);d.innerHeight-=(d.offsetTop+d.offsetBottom);}return d;};var setTimer=function(pane,action,fn,ms){var
-Layout=window.layout=window.layout||{},Timers=Layout.timers=Layout.timers||{},name="layout_"+state.id+"_"+pane+"_"+action;if(Timers[name])return;else Timers[name]=setTimeout(fn,ms);};var clearTimer=function(pane,action){var
-Layout=window.layout=window.layout||{},Timers=Layout.timers=Layout.timers||{},name="layout_"+state.id+"_"+pane+"_"+action;if(Timers[name]){clearTimeout(Timers[name]);delete Timers[name];return true;}else
-return false;};var create=function(){initOptions();initContainer();initPanes();initHandles();initResizable();sizeContent("all");if(options.scrollToBookmarkOnLoad)with(self.location)if(hash)replace(hash);initHotkeys();$(window).resize(function(){var timerID="timerLayout_"+state.id;if(window[timerID])clearTimeout(window[timerID]);window[timerID]=null;if(true||$.browser.msie)window[timerID]=setTimeout(resizeAll,100);else
-resizeAll();});};var initContainer=function(){try{if($Container[0].tagName=="BODY"){$("html").css({height:"100%",overflow:"hidden"});$("body").css({position:"relative",height:"100%",overflow:"hidden",margin:0,padding:0,border:"none"});}else{var
-CSS={overflow:"hidden"},p=$Container.css("position"),h=$Container.css("height");if(!$Container.hasClass("ui-layout-pane")){if(!p||"fixed,absolute,relative".indexOf(p)<0)CSS.position="relative";if(!h||h=="auto")CSS.height="100%";}$Container.css(CSS);}}catch(ex){}cDims=state.container=getElemDims($Container);};var initHotkeys=function(){$.each(c.borderPanes.split(","),function(i,pane){var o=options[pane];if(o.enableCursorHotkey||o.customHotkey){$(document).keydown(keyDown);return false;}});};var initOptions=function(){opts=transformData(opts);if(opts.effects){$.extend(effects,opts.effects);delete opts.effects;}$.each("name,scrollToBookmarkOnLoad".split(","),function(idx,key){if(opts[key]!==undefined)options[key]=opts[key];else if(opts.defaults[key]!==undefined){options[key]=opts.defaults[key];delete opts.defaults[key];}});$.each("paneSelector,resizerCursor,customHotkey".split(","),function(idx,key){delete opts.defaults[key];});$.extend(options.defaults,opts.defaults);c.center=$.extend(true,{},c.defaults,c.center);$.extend(options.center,opts.center);var o_Center=$.extend(true,{},options.defaults,opts.defaults,options.center);$.each("paneClass,contentSelector,contentIgnoreSelector,applyDefaultStyles,showOverflowOnHover".split(","),function(idx,key){options.center[key]=o_Center[key];});var defs=options.defaults;$.each(c.borderPanes.split(","),function(i,pane){c[pane]=$.extend(true,{},c.defaults,c[pane]);o=options[pane]=$.extend(true,{},options.defaults,options[pane],opts.defaults,opts[pane]);if(!o.paneClass)o.paneClass=defaults.paneClass;if(!o.resizerClass)o.resizerClass=defaults.resizerClass;if(!o.togglerClass)o.togglerClass=defaults.togglerClass;$.each(["_open","_close",""],function(i,n){var
-sName="fxName"+n,sSpeed="fxSpeed"+n,sSettings="fxSettings"+n;o[sName]=opts[pane][sName]||opts[pane].fxName||opts.defaults[sName]||opts.defaults.fxName||o[sName]||o.fxName||defs[sName]||defs.fxName||"none";var fxName=o[sName];if(fxName=="none"||!$.effects||!$.effects[fxName]||(!effects[fxName]&&!o[sSettings]&&!o.fxSettings))fxName=o[sName]="none";var
-fx=effects[fxName]||{},fx_all=fx.all||{},fx_pane=fx[pane]||{};o[sSettings]=$.extend({},fx_all,fx_pane,defs.fxSettings||{},defs[sSettings]||{},o.fxSettings,o[sSettings],opts.defaults.fxSettings,opts.defaults[sSettings]||{},opts[pane].fxSettings,opts[pane][sSettings]||{});o[sSpeed]=opts[pane][sSpeed]||opts[pane].fxSpeed||opts.defaults[sSpeed]||opts.defaults.fxSpeed||o[sSpeed]||o[sSettings].duration||o.fxSpeed||o.fxSettings.duration||defs.fxSpeed||defs.fxSettings.duration||fx_pane.duration||fx_all.duration||"normal";});});};var initPanes=function(){$.each(c.allPanes.split(","),function(){var
-pane=str(this),o=options[pane],s=state[pane],fx=s.fx,dir=c[pane].dir,size=o.size=="auto"||isNaN(o.size)?0:o.size,minSize=o.minSize||1,maxSize=o.maxSize||9999,spacing=o.spacing_open||0,sel=o.paneSelector,isIE6=($.browser.msie&&$.browser.version<7),CSS={},$P,$C;$Cs[pane]=false;if(sel.substr(0,1)==="#")$P=$Ps[pane]=$Container.find(sel+":first");else{$P=$Ps[pane]=$Container.children(sel+":first");if(!$P.length)$P=$Ps[pane]=$Container.children("form:first").children(sel+":first");}if(!$P.length){$Ps[pane]=false;return true;}$P.attr("pane",pane).addClass(o.paneClass+" "+o.paneClass+"-"+pane);if(pane!="center"){s.isClosed=false;s.isSliding=false;s.isResizing=false;s.isHidden=false;s.noRoom=false;c[pane].pins=[];}CSS=$.extend({visibility:"visible",display:"block"},c.defaults.cssReq,c[pane].cssReq);if(o.applyDefaultStyles)$.extend(CSS,c.defaults.cssDef,c[pane].cssDef);$P.css(CSS);CSS={};switch(pane){case"north":CSS.top=cDims.top;CSS.left=cDims.left;CSS.right=cDims.right;break;case"south":CSS.bottom=cDims.bottom;CSS.left=cDims.left;CSS.right=cDims.right;break;case"west":CSS.left=cDims.left;break;case"east":CSS.right=cDims.right;break;case"center":}if(dir=="horz"){if(size===0||size=="auto"){$P.css({height:"auto"});size=$P.outerHeight();}size=max(size,minSize);size=min(size,maxSize);size=min(size,cDims.innerHeight-spacing);CSS.height=max(1,cssH(pane,size));s.size=size;s.maxSize=maxSize;s.minSize=max(minSize,size-CSS.height+1);$P.css(CSS);}else if(dir=="vert"){if(size===0||size=="auto"){$P.css({width:"auto",float:"left"});size=$P.outerWidth();$P.css({float:"none"});}size=max(size,minSize);size=min(size,maxSize);size=min(size,cDims.innerWidth-spacing);CSS.width=max(1,cssW(pane,size));s.size=size;s.maxSize=maxSize;s.minSize=max(minSize,size-CSS.width+1);$P.css(CSS);sizeMidPanes(pane,null,true);}else if(pane=="center"){$P.css(CSS);sizeMidPanes("center",null,true);}if(o.initClosed&&o.closable){$P.hide().addClass("closed");s.isClosed=true;}else if(o.initHidden||o.initClosed){hide(pane,true);s.isHidden=true;}else
-$P.addClass("open");if(o.showOverflowOnHover)$P.hover(allowOverflow,resetOverflow);if(o.contentSelector){$C=$Cs[pane]=$P.children(o.contentSelector+":first");if(!$C.length){$Cs[pane]=false;return true;}$C.css(c.content.cssReq);if(o.applyDefaultStyles)$C.css(c.content.cssDef);$P.css({overflow:"hidden"});}});};var initHandles=function(){$.each(c.borderPanes.split(","),function(){var
-pane=str(this),o=options[pane],s=state[pane],rClass=o.resizerClass,tClass=o.togglerClass,$P=$Ps[pane];$Rs[pane]=false;$Ts[pane]=false;if(!$P||(!o.closable&&!o.resizable))return;var
-edge=c[pane].edge,isOpen=$P.is(":visible"),spacing=(isOpen?o.spacing_open:o.spacing_closed),_pane="-"+pane,_state=(isOpen?"-open":"-closed"),$R,$T;$R=$Rs[pane]=$("<span></span>");if(isOpen&&o.resizable);else if(!isOpen&&o.slidable)$R.attr("title",o.sliderTip).css("cursor",o.sliderCursor);$R.attr("id",(o.paneSelector.substr(0,1)=="#"?o.paneSelector.substr(1)+"-resizer":"")).attr("resizer",pane).css(c.resizers.cssReq).css(edge,cDims[edge]+getPaneSize(pane)).addClass(rClass+" "+rClass+_pane+" "+rClass+_state+" "+rClass+_pane+_state).appendTo($Container);if(o.applyDefaultStyles)$R.css(c.resizers.cssDef);if(o.closable){$T=$Ts[pane]=$("<div></div>");$T.attr("id",(o.paneSelector.substr(0,1)=="#"?o.paneSelector.substr(1)+"-toggler":"")).css(c.togglers.cssReq).attr("title",(isOpen?o.togglerTip_open:o.togglerTip_closed)).click(function(evt){toggle(pane);evt.stopPropagation();}).mouseover(function(evt){evt.stopPropagation();}).addClass(tClass+" "+tClass+_pane+" "+tClass+_state+" "+tClass+_pane+_state).appendTo($R);if(o.togglerContent_open)$("<span>"+o.togglerContent_open+"</span>").addClass("content content-open").css("display",s.isClosed?"none":"block").appendTo($T);if(o.togglerContent_closed)$("<span>"+o.togglerContent_closed+"</span>").addClass("content content-closed").css("display",s.isClosed?"block":"none").appendTo($T);if(o.applyDefaultStyles)$T.css(c.togglers.cssDef);if(!isOpen)bindStartSlidingEvent(pane,true);}});sizeHandles("all",true);};var initResizable=function(){var
-draggingAvailable=(typeof $.fn.draggable=="function"),minPosition,maxPosition,edge;$.each(c.borderPanes.split(","),function(){var
-pane=str(this),o=options[pane],s=state[pane];if(!draggingAvailable||!$Ps[pane]||!o.resizable){o.resizable=false;return true;}var
-rClass=o.resizerClass,dragClass=rClass+"-drag",dragPaneClass=rClass+"-"+pane+"-drag",draggingClass=rClass+"-dragging",draggingPaneClass=rClass+"-"+pane+"-dragging",draggingClassSet=false,$P=$Ps[pane],$R=$Rs[pane];if(!s.isClosed)$R.attr("title",o.resizerTip).css("cursor",o.resizerCursor);$R.draggable({containment:$Container[0],axis:(c[pane].dir=="horz"?"y":"x"),delay:200,distance:1,helper:"clone",opacity:o.resizerDragOpacity,zIndex:c.zIndex.resizing,start:function(e,ui){if(false===execUserCallback(pane,o.onresize_start))return false;s.isResizing=true;clearTimer(pane,"closeSlider");$R.addClass(dragClass+" "+dragPaneClass);draggingClassSet=false;var resizerWidth=(pane=="east"||pane=="south"?o.spacing_open:0);setPaneMinMaxSizes(pane);s.minPosition-=resizerWidth;s.maxPosition-=resizerWidth;edge=(c[pane].dir=="horz"?"top":"left");$(o.maskIframesOnResize===true?"iframe":o.maskIframesOnResize).each(function(){$('<div class="ui-layout-mask"/>').css({background:"#fff",opacity:"0.001",zIndex:9,position:"absolute",width:this.offsetWidth+"px",height:this.offsetHeight+"px"}).css($(this).offset()).appendTo(this.parentNode);});},drag:function(e,ui){if(!draggingClassSet){$(".ui-draggable-dragging").addClass(draggingClass+" "+draggingPaneClass).children().css("visibility","hidden");draggingClassSet=true;if(s.isSliding)$Ps[pane].css("zIndex",c.zIndex.sliding);}if(ui.position[edge]<s.minPosition)ui.position[edge]=s.minPosition;else if(ui.position[edge]>s.maxPosition)ui.position[edge]=s.maxPosition;},stop:function(e,ui){var
-dragPos=ui.position,resizerPos,newSize;$R.removeClass(dragClass+" "+dragPaneClass);switch(pane){case"north":resizerPos=dragPos.top;break;case"west":resizerPos=dragPos.left;break;case"south":resizerPos=cDims.outerHeight-dragPos.top-$R.outerHeight();break;case"east":resizerPos=cDims.outerWidth-dragPos.left-$R.outerWidth();break;}newSize=resizerPos-cDims[c[pane].edge];sizePane(pane,newSize);$("div.ui-layout-mask").remove();s.isResizing=false;}});});};var hide=function(pane,onInit){var
-o=options[pane],s=state[pane],$P=$Ps[pane],$R=$Rs[pane];if(!$P||s.isHidden)return;if(false===execUserCallback(pane,o.onhide_start))return;s.isSliding=false;if($R)$R.hide();if(onInit||s.isClosed){s.isClosed=true;s.isHidden=true;$P.hide();sizeMidPanes(c[pane].dir=="horz"?"all":"center");execUserCallback(pane,o.onhide_end||o.onhide);}else{s.isHiding=true;close(pane,false);}};var show=function(pane,openPane){var
-o=options[pane],s=state[pane],$P=$Ps[pane],$R=$Rs[pane];if(!$P||!s.isHidden)return;if(false===execUserCallback(pane,o.onshow_start))return;s.isSliding=false;s.isShowing=true;if($R&&o.spacing_open>0)$R.show();if(openPane===false)close(pane,true);else
-open(pane);};var toggle=function(pane){var s=state[pane];if(s.isHidden)show(pane);else if(s.isClosed)open(pane);else
-close(pane);};var close=function(pane,force,noAnimation){var
-$P=$Ps[pane],$R=$Rs[pane],$T=$Ts[pane],o=options[pane],s=state[pane],doFX=!noAnimation&&!s.isClosed&&(o.fxName_close!="none"),edge=c[pane].edge,rClass=o.resizerClass,tClass=o.togglerClass,_pane="-"+pane,_open="-open",_sliding="-sliding",_closed="-closed",isShowing=s.isShowing,isHiding=s.isHiding;delete s.isShowing;delete s.isHiding;if(!$P||(!o.resizable&&!o.closable))return;else if(!force&&s.isClosed&&!isShowing)return;if(c.isLayoutBusy){setFlowCallback("close",pane,force);return;}if(!isShowing&&false===execUserCallback(pane,o.onclose_start))return;c[pane].isMoving=true;c.isLayoutBusy=true;s.isClosed=true;if(isHiding)s.isHidden=true;else if(isShowing)s.isHidden=false;syncPinBtns(pane,false);if(!s.isSliding)sizeMidPanes(c[pane].dir=="horz"?"all":"center");if($R){$R.css(edge,cDims[edge]).removeClass(rClass+_open+" "+rClass+_pane+_open).removeClass(rClass+_sliding+" "+rClass+_pane+_sliding).addClass(rClass+_closed+" "+rClass+_pane+_closed);if(o.resizable)$R.draggable("disable").css("cursor","default").attr("title","");if($T){$T.removeClass(tClass+_open+" "+tClass+_pane+_open).addClass(tClass+_closed+" "+tClass+_pane+_closed).attr("title",o.togglerTip_closed);}sizeHandles();}if(doFX){lockPaneForFX(pane,true);$P.hide(o.fxName_close,o.fxSettings_close,o.fxSpeed_close,function(){lockPaneForFX(pane,false);if(!s.isClosed)return;close_2();});}else{$P.hide();close_2();}function close_2(){bindStartSlidingEvent(pane,true);if(!isShowing)execUserCallback(pane,o.onclose_end||o.onclose);if(isShowing)execUserCallback(pane,o.onshow_end||o.onshow);if(isHiding)execUserCallback(pane,o.onhide_end||o.onhide);execFlowCallback(pane);}};var open=function(pane,slide,noAnimation){var
-$P=$Ps[pane],$R=$Rs[pane],$T=$Ts[pane],o=options[pane],s=state[pane],doFX=!noAnimation&&s.isClosed&&(o.fxName_open!="none"),edge=c[pane].edge,rClass=o.resizerClass,tClass=o.togglerClass,_pane="-"+pane,_open="-open",_closed="-closed",_sliding="-sliding",isShowing=s.isShowing;delete s.isShowing;if(!$P||(!o.resizable&&!o.closable))return;else if(!s.isClosed&&!s.isSliding)return;if(s.isHidden&&!isShowing){show(pane,true);return;}if(c.isLayoutBusy){setFlowCallback("open",pane,slide);return;}if(false===execUserCallback(pane,o.onopen_start))return;c[pane].isMoving=true;c.isLayoutBusy=true;if(s.isSliding&&!slide)bindStopSlidingEvents(pane,false);s.isClosed=false;if(isShowing)s.isHidden=false;setPaneMinMaxSizes(pane);if(s.size>s.maxSize)$P.css(c[pane].sizeType,max(1,cssSize(pane,s.maxSize)));bindStartSlidingEvent(pane,false);if(doFX){lockPaneForFX(pane,true);$P.show(o.fxName_open,o.fxSettings_open,o.fxSpeed_open,function(){lockPaneForFX(pane,false);if(s.isClosed)return;open_2();});}else{$P.show();open_2();}function open_2(){if(!s.isSliding)sizeMidPanes(c[pane].dir=="vert"?"center":"all");if($R){$R.css(edge,cDims[edge]+getPaneSize(pane)).removeClass(rClass+_closed+" "+rClass+_pane+_closed).addClass(rClass+_open+" "+rClass+_pane+_open).addClass(!s.isSliding?"":rClass+_sliding+" "+rClass+_pane+_sliding);if(o.resizable)$R.draggable("enable").css("cursor",o.resizerCursor).attr("title",o.resizerTip);else
-$R.css("cursor","default");if($T){$T.removeClass(tClass+_closed+" "+tClass+_pane+_closed).addClass(tClass+_open+" "+tClass+_pane+_open).attr("title",o.togglerTip_open);}sizeHandles("all");}sizeContent(pane);syncPinBtns(pane,!s.isSliding);execUserCallback(pane,o.onopen_end||o.onopen);if(isShowing)execUserCallback(pane,o.onshow_end||o.onshow);execFlowCallback(pane);}};var lockPaneForFX=function(pane,doLock){var $P=$Ps[pane];if(doLock){$P.css({zIndex:c.zIndex.animation});if(pane=="south")$P.css({top:cDims.top+cDims.innerHeight-$P.outerHeight()});else if(pane=="east")$P.css({left:cDims.left+cDims.innerWidth-$P.outerWidth()});}else{if(!state[pane].isSliding)$P.css({zIndex:c.zIndex.pane_normal});if(pane=="south")$P.css({top:"auto"});else if(pane=="east")$P.css({left:"auto"});}};var bindStartSlidingEvent=function(pane,enable){var
-o=options[pane],$R=$Rs[pane],trigger=o.slideTrigger_open;if(!$R||!o.slidable)return;if(trigger!="click"&&trigger!="dblclick"&&trigger!="mouseover")trigger="click";$R
-[enable?"bind":"unbind"](trigger,slideOpen).css("cursor",(enable?o.sliderCursor:"default")).attr("title",(enable?o.sliderTip:""));};var bindStopSlidingEvents=function(pane,enable){var
-o=options[pane],s=state[pane],trigger=o.slideTrigger_close,action=(enable?"bind":"unbind"),$P=$Ps[pane],$R=$Rs[pane];s.isSliding=enable;clearTimer(pane,"closeSlider");$P.css({zIndex:(enable?c.zIndex.sliding:c.zIndex.pane_normal)});$R.css({zIndex:(enable?c.zIndex.sliding:c.zIndex.resizer_normal)});if(trigger!="click"&&trigger!="mouseout")trigger="mouseout";if(enable){$P.bind(trigger,slideClosed);$R.bind(trigger,slideClosed);if(trigger="mouseout"){$P.bind("mouseover",cancelMouseOut);$R.bind("mouseover",cancelMouseOut);}}else{$P.unbind(trigger);$R.unbind(trigger);if(trigger="mouseout"){$P.unbind("mouseover");$R.unbind("mouseover");clearTimer(pane,"closeSlider");}}function cancelMouseOut(evt){clearTimer(pane,"closeSlider");evt.stopPropagation();}};var slideOpen=function(){var pane=$(this).attr("resizer");if(state[pane].isClosed){bindStopSlidingEvents(pane,true);open(pane,true);}};var slideClosed=function(){var
-$E=$(this),pane=$E.attr("pane")||$E.attr("resizer"),o=options[pane],s=state[pane];if(s.isClosed||s.isResizing)return;else if(o.slideTrigger_close=="click")close_NOW();else
-setTimer(pane,"closeSlider",close_NOW,300);function close_NOW(){bindStopSlidingEvents(pane,false);if(!s.isClosed)close(pane);}};var sizePane=function(pane,size){var
-edge=c[pane].edge,dir=c[pane].dir,o=options[pane],s=state[pane],$P=$Ps[pane],$R=$Rs[pane];setPaneMinMaxSizes(pane);s.minSize=max(s.minSize,o.minSize);if(o.maxSize>0)s.maxSize=min(s.maxSize,o.maxSize);size=max(size,s.minSize);size=min(size,s.maxSize);s.size=size;$R.css(edge,size+cDims[edge]);$P.css(c[pane].sizeType,max(1,cssSize(pane,size)));if(!s.isSliding)sizeMidPanes(dir=="horz"?"all":"center");sizeHandles();sizeContent(pane);execUserCallback(pane,o.onresize_end||o.onresize);};var sizeMidPanes=function(panes,overrideDims,onInit){if(!panes||panes=="all")panes="east,west,center";var d=getPaneDims();if(overrideDims)$.extend(d,overrideDims);$.each(panes.split(","),function(){if(!$Ps[this])return;var
-pane=str(this),o=options[pane],s=state[pane],$P=$Ps[pane],$R=$Rs[pane],hasRoom=true,CSS={};if(pane=="center"){d=getPaneDims();CSS=$.extend({},d);CSS.width=max(1,cssW(pane,CSS.width));CSS.height=max(1,cssH(pane,CSS.height));hasRoom=(CSS.width>1&&CSS.height>1);if($.browser.msie&&(!$.boxModel||$.browser.version<7)){if($Ps.north)$Ps.north.css({width:cssW($Ps.north,cDims.innerWidth)});if($Ps.south)$Ps.south.css({width:cssW($Ps.south,cDims.innerWidth)});}}else{CSS.top=d.top;CSS.bottom=d.bottom;CSS.height=max(1,cssH(pane,d.height));hasRoom=(CSS.height>1);}if(hasRoom){$P.css(CSS);if(s.noRoom){s.noRoom=false;if(s.isHidden)return;else show(pane,!s.isClosed);}if(!onInit){sizeContent(pane);execUserCallback(pane,o.onresize_end||o.onresize);}}else if(!s.noRoom){s.noRoom=true;if(s.isHidden)return;if(onInit){$P.hide();if($R)$R.hide();}else hide(pane);}});};var sizeContent=function(panes){if(!panes||panes=="all")panes=c.allPanes;$.each(panes.split(","),function(){if(!$Cs[this])return;var
-pane=str(this),ignore=options[pane].contentIgnoreSelector,$P=$Ps[pane],$C=$Cs[pane],e_C=$C[0],height=cssH($P);;$P.children().each(function(){if(this==e_C)return;var $E=$(this);if(!ignore||!$E.is(ignore))height-=$E.outerHeight();});if(height>0)height=cssH($C,height);if(height<1)$C.hide();else
-$C.css({height:height}).show();});};var sizeHandles=function(panes,onInit){if(!panes||panes=="all")panes=c.borderPanes;$.each(panes.split(","),function(){var
-pane=str(this),o=options[pane],s=state[pane],$P=$Ps[pane],$R=$Rs[pane],$T=$Ts[pane];if(!$P||!$R||(!o.resizable&&!o.closable))return;var
-dir=c[pane].dir,_state=(s.isClosed?"_closed":"_open"),spacing=o["spacing"+_state],togAlign=o["togglerAlign"+_state],togLen=o["togglerLength"+_state],paneLen,offset,CSS={};if(spacing==0){$R.hide();return;}else if(!s.noRoom&&!s.isHidden)$R.show();if(dir=="horz"){paneLen=$P.outerWidth();$R.css({width:max(1,cssW($R,paneLen)),height:max(1,cssH($R,spacing)),left:cssNum($P,"left")});}else{paneLen=$P.outerHeight();$R.css({height:max(1,cssH($R,paneLen)),width:max(1,cssW($R,spacing)),top:cDims.top+getPaneSize("north",true)});}if($T){if(togLen==0||(s.isSliding&&o.hideTogglerOnSlide)){$T.hide();return;}else
-$T.show();if(!(togLen>0)||togLen=="100%"||togLen>paneLen){togLen=paneLen;offset=0;}else{if(typeof togAlign=="string"){switch(togAlign){case"top":case"left":offset=0;break;case"bottom":case"right":offset=paneLen-togLen;break;case"middle":case"center":default:offset=Math.floor((paneLen-togLen)/2);}}else{var x=parseInt(togAlign);if(togAlign>=0)offset=x;else offset=paneLen-togLen+x;}}var
-$TC_o=(o.togglerContent_open?$T.children(".content-open"):false),$TC_c=(o.togglerContent_closed?$T.children(".content-closed"):false),$TC=(s.isClosed?$TC_c:$TC_o);if($TC_o)$TC_o.css("display",s.isClosed?"none":"block");if($TC_c)$TC_c.css("display",s.isClosed?"block":"none");if(dir=="horz"){var width=cssW($T,togLen);$T.css({width:max(0,width),height:max(1,cssH($T,spacing)),left:offset});if($TC)$TC.css("marginLeft",Math.floor((width-$TC.outerWidth())/2));}else{var height=cssH($T,togLen);$T.css({height:max(0,height),width:max(1,cssW($T,spacing)),top:offset});if($TC)$TC.css("marginTop",Math.floor((height-$TC.outerHeight())/2));}}if(onInit&&o.initHidden){$R.hide();if($T)$T.hide();}});};var resizeAll=function(){var
-oldW=cDims.innerWidth,oldH=cDims.innerHeight;cDims=state.container=getElemDims($Container);var
-checkH=(cDims.innerHeight<oldH),checkW=(cDims.innerWidth<oldW),s,dir;if(checkH||checkW)$.each(["south","north","east","west"],function(i,pane){s=state[pane];dir=c[pane].dir;if(!s.isClosed&&((checkH&&dir=="horz")||(checkW&&dir=="vert"))){setPaneMinMaxSizes(pane);if(s.size>s.maxSize)sizePane(pane,s.maxSize);}});sizeMidPanes("all");sizeHandles("all");};function keyDown(evt){if(!evt)return true;var code=evt.keyCode;if(code<33)return true;var
-PANE={38:"north",40:"south",37:"west",39:"east"},isCursorKey=(code>=37&&code<=40),ALT=evt.altKey,SHIFT=evt.shiftKey,CTRL=evt.ctrlKey,pane=false,s,o,k,m,el;if(!CTRL&&!SHIFT)return true;else if(isCursorKey&&options[PANE[code]].enableCursorHotkey)pane=PANE[code];else
-$.each(c.borderPanes.split(","),function(i,p){o=options[p];k=o.customHotkey;m=o.customHotkeyModifier;if((SHIFT&&m=="SHIFT")||(CTRL&&m=="CTRL")||(CTRL&&SHIFT)){if(k&&code==(isNaN(k)||k<=9?k.toUpperCase().charCodeAt(0):k)){pane=p;return false;}}});if(!pane)return true;o=options[pane];s=state[pane];if(!o.enableCursorHotkey||s.isHidden||!$Ps[pane])return true;el=evt.target||evt.srcElement;if(el&&SHIFT&&isCursorKey&&(el.tagName=="TEXTAREA"||(el.tagName=="INPUT"&&(code==37||code==39))))return true;toggle(pane);evt.stopPropagation();evt.returnValue=false;return false;};function allowOverflow(elem){if(this&&this.tagName)elem=this;var $P;if(typeof elem=="string")$P=$Ps[elem];else{if($(elem).attr("pane"))$P=$(elem);else $P=$(elem).parents("div[pane]:first");}if(!$P.length)return;var
-pane=$P.attr("pane"),s=state[pane];if(s.cssSaved)resetOverflow(pane);if(s.isSliding||s.isResizing||s.isClosed){s.cssSaved=false;return;}var
-newCSS={zIndex:(c.zIndex.pane_normal+1)},curCSS={},of=$P.css("overflow"),ofX=$P.css("overflowX"),ofY=$P.css("overflowY");if(of!="visible"){curCSS.overflow=of;newCSS.overflow="visible";}if(ofX&&ofX!="visible"&&ofX!="auto"){curCSS.overflowX=ofX;newCSS.overflowX="visible";}if(ofY&&ofY!="visible"&&ofY!="auto"){curCSS.overflowY=ofX;newCSS.overflowY="visible";}s.cssSaved=curCSS;$P.css(newCSS);$.each(c.allPanes.split(","),function(i,p){if(p!=pane)resetOverflow(p);});};function resetOverflow(elem){if(this&&this.tagName)elem=this;var $P;if(typeof elem=="string")$P=$Ps[elem];else{if($(elem).hasClass("ui-layout-pane"))$P=$(elem);else $P=$(elem).parents("div[pane]:first");}if(!$P.length)return;var
-pane=$P.attr("pane"),s=state[pane],CSS=s.cssSaved||{};if(!s.isSliding&&!s.isResizing)$P.css("zIndex",c.zIndex.pane_normal);$P.css(CSS);s.cssSaved=false;};function getBtn(selector,pane,action){var
-$E=$(selector),err="Error Adding Button \n\nInvalid ";if(!$E.length)alert(err+"selector: "+selector);else if(c.borderPanes.indexOf(pane)==-1)alert(err+"pane: "+pane);else{var btn=options[pane].buttonClass+"-"+action;$E.addClass(btn+" "+btn+"-"+pane);return $E;}return false;};function addToggleBtn(selector,pane){var $E=getBtn(selector,pane,"toggle");if($E)$E.attr("title",state[pane].isClosed?"Open":"Close").click(function(evt){toggle(pane);evt.stopPropagation();});};function addOpenBtn(selector,pane){var $E=getBtn(selector,pane,"open");if($E)$E.attr("title","Open").click(function(evt){open(pane);evt.stopPropagation();});};function addCloseBtn(selector,pane){var $E=getBtn(selector,pane,"close");if($E)$E.attr("title","Close").click(function(evt){close(pane);evt.stopPropagation();});};function addPinBtn(selector,pane){var $E=getBtn(selector,pane,"pin");if($E){var s=state[pane];$E.click(function(evt){setPinState($(this),pane,(s.isSliding||s.isClosed));if(s.isSliding||s.isClosed)open(pane);else close(pane);evt.stopPropagation();});setPinState($E,pane,(!s.isClosed&&!s.isSliding));c[pane].pins.push(selector);}};function syncPinBtns(pane,doPin){$.each(c[pane].pins,function(i,selector){setPinState($(selector),pane,doPin);});};function setPinState($Pin,pane,doPin){var updown=$Pin.attr("pin");if(updown&&doPin==(updown=="down"))return;var
-root=options[pane].buttonClass,class1=root+"-pin",class2=class1+"-"+pane,UP1=class1+"-up",UP2=class2+"-up",DN1=class1+"-down",DN2=class2+"-down";$Pin.attr("pin",doPin?"down":"up").attr("title",doPin?"Un-Pin":"Pin").removeClass(doPin?UP1:DN1).removeClass(doPin?UP2:DN2).addClass(doPin?DN1:UP1).addClass(doPin?DN2:UP2);};var
-$Container=$(this).css({overflow:"hidden"}),$Ps={},$Cs={},$Rs={},$Ts={},c=config,cDims=state.container;create();return{options:options,state:state,panes:$Ps,toggle:toggle,open:open,close:close,hide:hide,show:show,resizeContent:sizeContent,sizePane:sizePane,resizeAll:resizeAll,addToggleBtn:addToggleBtn,addOpenBtn:addOpenBtn,addCloseBtn:addCloseBtn,addPinBtn:addPinBtn,allowOverflow:allowOverflow,resetOverflow:resetOverflow,cssWidth:cssW,cssHeight:cssH};}})(jQuery);
\ No newline at end of file
+(function ($) {
+    $.fn.layout = function (opts) {
+        var
+            prefix = "ui-layout-", defaults = {paneClass: prefix + "pane", resizerClass: prefix + "resizer", togglerClass: prefix + "toggler", togglerInnerClass: prefix + "", buttonClass: prefix + "button", contentSelector: "." + prefix + "content", contentIgnoreSelector: "." + prefix + "ignore"};
+        var options = {name: "", scrollToBookmarkOnLoad: true, defaults: {applyDefaultStyles: false, closable: true, resizable: true, slidable: true, contentSelector: defaults.contentSelector, contentIgnoreSelector: defaults.contentIgnoreSelector, paneClass: defaults.paneClass, resizerClass: defaults.resizerClass, togglerClass: defaults.togglerClass, buttonClass: defaults.buttonClass, resizerDragOpacity: 1, maskIframesOnResize: true, minSize: 0, maxSize: 0, spacing_open: 6, spacing_closed: 6, togglerLength_open: 50, togglerLength_closed: 50, togglerAlign_open: "center", togglerAlign_closed: "center", togglerTip_open: "Close", togglerTip_closed: "Open", resizerTip: "Resize", sliderTip: "Slide Open", sliderCursor: "pointer", slideTrigger_open: "click", slideTrigger_close: "mouseout", hideTogglerOnSlide: false, togglerContent_open: "", togglerContent_closed: "", showOverflowOnHover: false, enableCursorHotkey: true, customHotkeyModifier: "SHIFT", fxName: "slide", fxSpeed: null, fxSettings: {}, initClosed: false, initHidden: false}, north: {paneSelector: "." + prefix + "north", size: "auto", resizerCursor: "n-resize"}, south: {paneSelector: "." + prefix + "south", size: "auto", resizerCursor: "s-resize"}, east: {paneSelector: "." + prefix + "east", size: 200, resizerCursor: "e-resize"}, west: {paneSelector: "." + prefix + "west", size: 200, resizerCursor: "w-resize"}, center: {paneSelector: "." + prefix + "center"}};
+        var effects = {slide: {all: {duration: "fast"}, north: {direction: "up"}, south: {direction: "down"}, east: {direction: "right"}, west: {direction: "left"}}, drop: {all: {duration: "slow"}, north: {direction: "up"}, south: {direction: "down"}, east: {direction: "right"}, west: {direction: "left"}}, scale: {all: {duration: "fast"}}};
+        var config = {allPanes: "north,south,east,west,center", borderPanes: "north,south,east,west", zIndex: {resizer_normal: 1, pane_normal: 2, mask: 4, sliding: 100, resizing: 10000, animation: 10000}, resizers: {cssReq: {position: "absolute", padding: 0, margin: 0, fontSize: "1px", textAlign: "left", overflow: "hidden", zIndex: 1}, cssDef: {background: "#DDD", border: "none"}}, togglers: {cssReq: {position: "absolute", display: "block", padding: 0, margin: 0, overflow: "hidden", textAlign: "center", fontSize: "1px", cursor: "pointer", zIndex: 1}, cssDef: {background: "#AAA"}}, content: {cssReq: {overflow: "auto"}, cssDef: {}}, defaults: {cssReq: {position: "absolute", margin: 0, zIndex: 2}, cssDef: {padding: "10px", background: "#FFF", border: "1px solid #BBB", overflow: "auto"}}, north: {edge: "top", sizeType: "height", dir: "horz", cssReq: {top: 0, bottom: "auto", left: 0, right: 0, width: "auto"}}, south: {edge: "bottom", sizeType: "height", dir: "horz", cssReq: {top: "auto", bottom: 0, left: 0, right: 0, width: "auto"}}, east: {edge: "right", sizeType: "width", dir: "vert", cssReq: {left: "auto", right: 0, top: "auto", bottom: "auto", height: "auto"}}, west: {edge: "left", sizeType: "width", dir: "vert", cssReq: {left: 0, right: "auto", top: "auto", bottom: "auto", height: "auto"}}, center: {dir: "center", cssReq: {left: "auto", right: "auto", top: "auto", bottom: "auto", height: "auto", width: "auto"}}};
+        var state = {id: Math.floor(Math.random() * 10000), container: {}, north: {}, south: {}, east: {}, west: {}, center: {}};
+        var
+            altEdge = {top: "bottom", bottom: "top", left: "right", right: "left"}, altSide = {north: "south", south: "north", east: "west", west: "east"};
+        var isStr = function (o) {
+            if (typeof o == "string")return true; else if (typeof o == "object") {
+                try {
+                    var match = o.constructor.toString().match(/string/i);
+                    return(match !== null);
+                } catch (e) {
+                }
+            }
+            return false;
+        };
+        var str = function (o) {
+            if (typeof o == "string" || isStr(o))return $.trim(o); else return o;
+        };
+        var min = function (x, y) {
+            return Math.min(x, y);
+        };
+        var max = function (x, y) {
+            return Math.max(x, y);
+        };
+        var transformData = function (d) {
+            var json = {defaults: {fxSettings: {}}, north: {fxSettings: {}}, south: {fxSettings: {}}, east: {fxSettings: {}}, west: {fxSettings: {}}, center: {fxSettings: {}}};
+            d = d || {};
+            if (d.effects || d.defaults || d.north || d.south || d.west || d.east || d.center)json = $.extend(json, d); else
+                $.each(d, function (key, val) {
+                    a = key.split("__");
+                    json[a[1] ? a[0] : "defaults"][a[1] ? a[1] : a[0]] = val;
+                });
+            return json;
+        };
+        var setFlowCallback = function (action, pane, param) {
+            var
+                cb = action + "," + pane + "," + (param ? 1 : 0), cP, cbPane;
+            $.each(c.borderPanes.split(","), function (i, p) {
+                if (c[p].isMoving) {
+                    bindCallback(p);
+                    return false;
+                }
+            });
+            function bindCallback(p, test) {
+                cP = c[p];
+                if (!cP.doCallback) {
+                    cP.doCallback = true;
+                    cP.callback = cb;
+                } else {
+                    cpPane = cP.callback.split(",")[1];
+                    if (cpPane != p && cpPane != pane)bindCallback(cpPane, true);
+                }
+            }
+        };
+        var execFlowCallback = function (pane) {
+            var cP = c[pane];
+            c.isLayoutBusy = false;
+            delete cP.isMoving;
+            if (!cP.doCallback || !cP.callback)return;
+            cP.doCallback = false;
+            var
+                cb = cP.callback.split(","), param = (cb[2] > 0 ? true : false);
+            if (cb[0] == "open")open(cb[1], param); else if (cb[0] == "close")close(cb[1], param);
+            if (!cP.doCallback)cP.callback = null;
+        };
+        var execUserCallback = function (pane, v_fn) {
+            if (!v_fn)return;
+            var fn;
+            try {
+                if (typeof v_fn == "function")fn = v_fn; else if (typeof v_fn != "string")return; else if (v_fn.indexOf(",") > 0) {
+                    var
+                        args = v_fn.split(","), fn = eval(args[0]);
+                    if (typeof fn == "function" && args.length > 1)return fn(args[1]);
+                } else
+                    fn = eval(v_fn);
+                if (typeof fn == "function")return fn(pane, $Ps[pane], $.extend({}, state[pane]), $.extend({}, options[pane]), options.name);
+            } catch (ex) {
+            }
+        };
+        var cssNum = function ($E, prop) {
+            var
+                val = 0, hidden = false, visibility = "";
+            if (!$.browser.msie) {
+                if ($.curCSS($E[0], "display", true) == "none") {
+                    hidden = true;
+                    visibility = $.curCSS($E[0], "visibility", true);
+                    $E.css({display: "block", visibility: "hidden"});
+                }
+            }
+            val = parseInt($.curCSS($E[0], prop, true), 10) || 0;
+            if (hidden) {
+                $E.css({display: "none"});
+                if (visibility && visibility != "hidden")$E.css({visibility: visibility});
+            }
+            return val;
+        };
+        var cssW = function (e, outerWidth) {
+            var $E;
+            if (isStr(e)) {
+                e = str(e);
+                $E = $Ps[e];
+            } else
+                $E = $(e);
+            if (outerWidth <= 0)return 0; else if (!(outerWidth > 0))outerWidth = isStr(e) ? getPaneSize(e) : $E.outerWidth();
+            if (!$.boxModel)return outerWidth; else
+                return outerWidth
+                    - cssNum($E, "paddingLeft") - cssNum($E, "paddingRight") - ($.curCSS($E[0], "borderLeftStyle", true) == "none" ? 0 : cssNum($E, "borderLeftWidth")) - ($.curCSS($E[0], "borderRightStyle", true) == "none" ? 0 : cssNum($E, "borderRightWidth"));
+        };
+        var cssH = function (e, outerHeight) {
+            var $E;
+            if (isStr(e)) {
+                e = str(e);
+                $E = $Ps[e];
+            } else
+                $E = $(e);
+            if (outerHeight <= 0)return 0; else if (!(outerHeight > 0))outerHeight = (isStr(e)) ? getPaneSize(e) : $E.outerHeight();
+            if (!$.boxModel)return outerHeight; else
+                return outerHeight
+                    - cssNum($E, "paddingTop") - cssNum($E, "paddingBottom") - ($.curCSS($E[0], "borderTopStyle", true) == "none" ? 0 : cssNum($E, "borderTopWidth")) - ($.curCSS($E[0], "borderBottomStyle", true) == "none" ? 0 : cssNum($E, "borderBottomWidth"));
+        };
+        var cssSize = function (pane, outerSize) {
+            if (c[pane].dir == "horz")return cssH(pane, outerSize); else
+                return cssW(pane, outerSize);
+        };
+        var getPaneSize = function (pane, inclSpace) {
+            var
+                $P = $Ps[pane], o = options[pane], s = state[pane], oSp = (inclSpace ? o.spacing_open : 0), cSp = (inclSpace ? o.spacing_closed : 0);
+            if (!$P || s.isHidden)return 0; else if (s.isClosed || (s.isSliding && inclSpace))return cSp; else if (c[pane].dir == "horz")return $P.outerHeight() + oSp; else
+                return $P.outerWidth() + oSp;
+        };
+        var setPaneMinMaxSizes = function (pane) {
+            var
+                d = cDims, edge = c[pane].edge, dir = c[pane].dir, o = options[pane], s = state[pane], $P = $Ps[pane], $altPane = $Ps[altSide[pane]], paneSpacing = o.spacing_open, altPaneSpacing = options[altSide[pane]].spacing_open, altPaneSize = (!$altPane ? 0 : (dir == "horz" ? $altPane.outerHeight() : $altPane.outerWidth())), containerSize = (dir == "horz" ? d.innerHeight : d.innerWidth), limitSize = containerSize - paneSpacing - altPaneSize - altPaneSpacing, minSize = s.minSize || 0, maxSize = Math.min(s.maxSize || 9999, limitSize), minPos, maxPos;
+            switch (pane) {
+                case"north":
+                    minPos = d.offsetTop + minSize;
+                    maxPos = d.offsetTop + maxSize;
+                    break;
+                case"west":
+                    minPos = d.offsetLeft + minSize;
+                    maxPos = d.offsetLeft + maxSize;
+                    break;
+                case"south":
+                    minPos = d.offsetTop + d.innerHeight - maxSize;
+                    maxPos = d.offsetTop + d.innerHeight - minSize;
+                    break;
+                case"east":
+                    minPos = d.offsetLeft + d.innerWidth - maxSize;
+                    maxPos = d.offsetLeft + d.innerWidth - minSize;
+                    break;
+            }
+            $.extend(s, {minSize: minSize, maxSize: maxSize, minPosition: minPos, maxPosition: maxPos});
+        };
+        var getPaneDims = function () {
+            var d = {top: getPaneSize("north", true), bottom: getPaneSize("south", true), left: getPaneSize("west", true), right: getPaneSize("east", true), width: 0, height: 0};
+            with (d) {
+                width = cDims.innerWidth - left - right;
+                height = cDims.innerHeight - bottom - top;
+                top += cDims.top;
+                bottom += cDims.bottom;
+                left += cDims.left;
+                right += cDims.right;
+            }
+            return d;
+        };
+        var getElemDims = function ($E) {
+            var
+                d = {}, e, b, p;
+            $.each("Left,Right,Top,Bottom".split(","), function () {
+                e = str(this);
+                b = d["border" + e] = cssNum($E, "border" + e + "Width");
+                p = d["padding" + e] = cssNum($E, "padding" + e);
+                d["offset" + e] = b + p;
+                if ($E == $Container)d[e.toLowerCase()] = ($.boxModel ? p : 0);
+            });
+            d.innerWidth = d.outerWidth = $E.outerWidth();
+            d.innerHeight = d.outerHeight = $E.outerHeight();
+            if ($.boxModel) {
+                d.innerWidth -= (d.offsetLeft + d.offsetRight);
+                d.innerHeight -= (d.offsetTop + d.offsetBottom);
+            }
+            return d;
+        };
+        var setTimer = function (pane, action, fn, ms) {
+            var
+                Layout = window.layout = window.layout || {}, Timers = Layout.timers = Layout.timers || {}, name = "layout_" + state.id + "_" + pane + "_" + action;
+            if (Timers[name])return; else Timers[name] = setTimeout(fn, ms);
+        };
+        var clearTimer = function (pane, action) {
+            var
+                Layout = window.layout = window.layout || {}, Timers = Layout.timers = Layout.timers || {}, name = "layout_" + state.id + "_" + pane + "_" + action;
+            if (Timers[name]) {
+                clearTimeout(Timers[name]);
+                delete Timers[name];
+                return true;
+            } else
+                return false;
+        };
+        var create = function () {
+            initOptions();
+            initContainer();
+            initPanes();
+            initHandles();
+            initResizable();
+            sizeContent("all");
+            if (options.scrollToBookmarkOnLoad)with (self.location)if (hash)replace(hash);
+            initHotkeys();
+            $(window).resize(function () {
+                var timerID = "timerLayout_" + state.id;
+                if (window[timerID])clearTimeout(window[timerID]);
+                window[timerID] = null;
+                if (true || $.browser.msie)window[timerID] = setTimeout(resizeAll, 100); else
+                    resizeAll();
+            });
+        };
+        var initContainer = function () {
+            try {
+                if ($Container[0].tagName == "BODY") {
+                    $("html").css({height: "100%", overflow: "hidden"});
+                    $("body").css({position: "relative", height: "100%", overflow: "hidden", margin: 0, padding: 0, border: "none"});
+                } else {
+                    var
+                        CSS = {overflow: "hidden"}, p = $Container.css("position"), h = $Container.css("height");
+                    if (!$Container.hasClass("ui-layout-pane")) {
+                        if (!p || "fixed,absolute,relative".indexOf(p) < 0)CSS.position = "relative";
+                        if (!h || h == "auto")CSS.height = "100%";
+                    }
+                    $Container.css(CSS);
+                }
+            } catch (ex) {
+            }
+            cDims = state.container = getElemDims($Container);
+        };
+        var initHotkeys = function () {
+            $.each(c.borderPanes.split(","), function (i, pane) {
+                var o = options[pane];
+                if (o.enableCursorHotkey || o.customHotkey) {
+                    $(document).keydown(keyDown);
+                    return false;
+                }
+            });
+        };
+        var initOptions = function () {
+            opts = transformData(opts);
+            if (opts.effects) {
+                $.extend(effects, opts.effects);
+                delete opts.effects;
+            }
+            $.each("name,scrollToBookmarkOnLoad".split(","), function (idx, key) {
+                if (opts[key] !== undefined)options[key] = opts[key]; else if (opts.defaults[key] !== undefined) {
+                    options[key] = opts.defaults[key];
+                    delete opts.defaults[key];
+                }
+            });
+            $.each("paneSelector,resizerCursor,customHotkey".split(","), function (idx, key) {
+                delete opts.defaults[key];
+            });
+            $.extend(options.defaults, opts.defaults);
+            c.center = $.extend(true, {}, c.defaults, c.center);
+            $.extend(options.center, opts.center);
+            var o_Center = $.extend(true, {}, options.defaults, opts.defaults, options.center);
+            $.each("paneClass,contentSelector,contentIgnoreSelector,applyDefaultStyles,showOverflowOnHover".split(","), function (idx, key) {
+                options.center[key] = o_Center[key];
+            });
+            var defs = options.defaults;
+            $.each(c.borderPanes.split(","), function (i, pane) {
+                c[pane] = $.extend(true, {}, c.defaults, c[pane]);
+                o = options[pane] = $.extend(true, {}, options.defaults, options[pane], opts.defaults, opts[pane]);
+                if (!o.paneClass)o.paneClass = defaults.paneClass;
+                if (!o.resizerClass)o.resizerClass = defaults.resizerClass;
+                if (!o.togglerClass)o.togglerClass = defaults.togglerClass;
+                $.each(["_open", "_close", ""], function (i, n) {
+                    var
+                        sName = "fxName" + n, sSpeed = "fxSpeed" + n, sSettings = "fxSettings" + n;
+                    o[sName] = opts[pane][sName] || opts[pane].fxName || opts.defaults[sName] || opts.defaults.fxName || o[sName] || o.fxName || defs[sName] || defs.fxName || "none";
+                    var fxName = o[sName];
+                    if (fxName == "none" || !$.effects || !$.effects[fxName] || (!effects[fxName] && !o[sSettings] && !o.fxSettings))fxName = o[sName] = "none";
+                    var
+                        fx = effects[fxName] || {}, fx_all = fx.all || {}, fx_pane = fx[pane] || {};
+                    o[sSettings] = $.extend({}, fx_all, fx_pane, defs.fxSettings || {}, defs[sSettings] || {}, o.fxSettings, o[sSettings], opts.defaults.fxSettings, opts.defaults[sSettings] || {}, opts[pane].fxSettings, opts[pane][sSettings] || {});
+                    o[sSpeed] = opts[pane][sSpeed] || opts[pane].fxSpeed || opts.defaults[sSpeed] || opts.defaults.fxSpeed || o[sSpeed] || o[sSettings].duration || o.fxSpeed || o.fxSettings.duration || defs.fxSpeed || defs.fxSettings.duration || fx_pane.duration || fx_all.duration || "normal";
+                });
+            });
+        };
+        var initPanes = function () {
+            $.each(c.allPanes.split(","), function () {
+                var
+                    pane = str(this), o = options[pane], s = state[pane], fx = s.fx, dir = c[pane].dir, size = o.size == "auto" || isNaN(o.size) ? 0 : o.size, minSize = o.minSize || 1, maxSize = o.maxSize || 9999, spacing = o.spacing_open || 0, sel = o.paneSelector, isIE6 = ($.browser.msie && $.browser.version < 7), CSS = {}, $P, $C;
+                $Cs[pane] = false;
+                if (sel.substr(0, 1) === "#")$P = $Ps[pane] = $Container.find(sel + ":first"); else {
+                    $P = $Ps[pane] = $Container.children(sel + ":first");
+                    if (!$P.length)$P = $Ps[pane] = $Container.children("form:first").children(sel + ":first");
+                }
+                if (!$P.length) {
+                    $Ps[pane] = false;
+                    return true;
+                }
+                $P.attr("pane", pane).addClass(o.paneClass + " " + o.paneClass + "-" + pane);
+                if (pane != "center") {
+                    s.isClosed = false;
+                    s.isSliding = false;
+                    s.isResizing = false;
+                    s.isHidden = false;
+                    s.noRoom = false;
+                    c[pane].pins = [];
+                }
+                CSS = $.extend({visibility: "visible", display: "block"}, c.defaults.cssReq, c[pane].cssReq);
+                if (o.applyDefaultStyles)$.extend(CSS, c.defaults.cssDef, c[pane].cssDef);
+                $P.css(CSS);
+                CSS = {};
+                switch (pane) {
+                    case"north":
+                        CSS.top = cDims.top;
+                        CSS.left = cDims.left;
+                        CSS.right = cDims.right;
+                        break;
+                    case"south":
+                        CSS.bottom = cDims.bottom;
+                        CSS.left = cDims.left;
+                        CSS.right = cDims.right;
+                        break;
+                    case"west":
+                        CSS.left = cDims.left;
+                        break;
+                    case"east":
+                        CSS.right = cDims.right;
+                        break;
+                    case"center":
+                }
+                if (dir == "horz") {
+                    if (size === 0 || size == "auto") {
+                        $P.css({height: "auto"});
+                        size = $P.outerHeight();
+                    }
+                    size = max(size, minSize);
+                    size = min(size, maxSize);
+                    size = min(size, cDims.innerHeight - spacing);
+                    CSS.height = max(1, cssH(pane, size));
+                    s.size = size;
+                    s.maxSize = maxSize;
+                    s.minSize = max(minSize, size - CSS.height + 1);
+                    $P.css(CSS);
+                } else if (dir == "vert") {
+                    if (size === 0 || size == "auto") {
+                        $P.css({width: "auto", float: "left"});
+                        size = $P.outerWidth();
+                        $P.css({float: "none"});
+                    }
+                    size = max(size, minSize);
+                    size = min(size, maxSize);
+                    size = min(size, cDims.innerWidth - spacing);
+                    CSS.width = max(1, cssW(pane, size));
+                    s.size = size;
+                    s.maxSize = maxSize;
+                    s.minSize = max(minSize, size - CSS.width + 1);
+                    $P.css(CSS);
+                    sizeMidPanes(pane, null, true);
+                } else if (pane == "center") {
+                    $P.css(CSS);
+                    sizeMidPanes("center", null, true);
+                }
+                if (o.initClosed && o.closable) {
+                    $P.hide().addClass("closed");
+                    s.isClosed = true;
+                } else if (o.initHidden || o.initClosed) {
+                    hide(pane, true);
+                    s.isHidden = true;
+                } else
+                    $P.addClass("open");
+                if (o.showOverflowOnHover)$P.hover(allowOverflow, resetOverflow);
+                if (o.contentSelector) {
+                    $C = $Cs[pane] = $P.children(o.contentSelector + ":first");
+                    if (!$C.length) {
+                        $Cs[pane] = false;
+                        return true;
+                    }
+                    $C.css(c.content.cssReq);
+                    if (o.applyDefaultStyles)$C.css(c.content.cssDef);
+                    $P.css({overflow: "hidden"});
+                }
+            });
+        };
+        var initHandles = function () {
+            $.each(c.borderPanes.split(","), function () {
+                var
+                    pane = str(this), o = options[pane], s = state[pane], rClass = o.resizerClass, tClass = o.togglerClass, $P = $Ps[pane];
+                $Rs[pane] = false;
+                $Ts[pane] = false;
+                if (!$P || (!o.closable && !o.resizable))return;
+                var
+                    edge = c[pane].edge, isOpen = $P.is(":visible"), spacing = (isOpen ? o.spacing_open : o.spacing_closed), _pane = "-" + pane, _state = (isOpen ? "-open" : "-closed"), $R, $T;
+                $R = $Rs[pane] = $("<span></span>");
+                if (isOpen && o.resizable); else if (!isOpen && o.slidable)$R.attr("title", o.sliderTip).css("cursor", o.sliderCursor);
+                $R.attr("id", (o.paneSelector.substr(0, 1) == "#" ? o.paneSelector.substr(1) + "-resizer" : "")).attr("resizer", pane).css(c.resizers.cssReq).css(edge, cDims[edge] + getPaneSize(pane)).addClass(rClass + " " + rClass + _pane + " " + rClass + _state + " " + rClass + _pane + _state).appendTo($Container);
+                if (o.applyDefaultStyles)$R.css(c.resizers.cssDef);
+                if (o.closable) {
+                    $T = $Ts[pane] = $("<div></div>");
+                    $T.attr("id", (o.paneSelector.substr(0, 1) == "#" ? o.paneSelector.substr(1) + "-toggler" : "")).css(c.togglers.cssReq).attr("title", (isOpen ? o.togglerTip_open : o.togglerTip_closed)).click(function (evt) {
+                        toggle(pane);
+                        evt.stopPropagation();
+                    }).mouseover(function (evt) {
+                        evt.stopPropagation();
+                    }).addClass(tClass + " " + tClass + _pane + " " + tClass + _state + " " + tClass + _pane + _state).appendTo($R);
+                    if (o.togglerContent_open)$("<span>" + o.togglerContent_open + "</span>").addClass("content content-open").css("display", s.isClosed ? "none" : "block").appendTo($T);
+                    if (o.togglerContent_closed)$("<span>" + o.togglerContent_closed + "</span>").addClass("content content-closed").css("display", s.isClosed ? "block" : "none").appendTo($T);
+                    if (o.applyDefaultStyles)$T.css(c.togglers.cssDef);
+                    if (!isOpen)bindStartSlidingEvent(pane, true);
+                }
+            });
+            sizeHandles("all", true);
+        };
+        var initResizable = function () {
+            var
+                draggingAvailable = (typeof $.fn.draggable == "function"), minPosition, maxPosition, edge;
+            $.each(c.borderPanes.split(","), function () {
+                var
+                    pane = str(this), o = options[pane], s = state[pane];
+                if (!draggingAvailable || !$Ps[pane] || !o.resizable) {
+                    o.resizable = false;
+                    return true;
+                }
+                var
+                    rClass = o.resizerClass, dragClass = rClass + "-drag", dragPaneClass = rClass + "-" + pane + "-drag", draggingClass = rClass + "-dragging", draggingPaneClass = rClass + "-" + pane + "-dragging", draggingClassSet = false, $P = $Ps[pane], $R = $Rs[pane];
+                if (!s.isClosed)$R.attr("title", o.resizerTip).css("cursor", o.resizerCursor);
+                $R.draggable({containment: $Container[0], axis: (c[pane].dir == "horz" ? "y" : "x"), delay: 200, distance: 1, helper: "clone", opacity: o.resizerDragOpacity, zIndex: c.zIndex.resizing, start: function (e, ui) {
+                    if (false === execUserCallback(pane, o.onresize_start))return false;
+                    s.isResizing = true;
+                    clearTimer(pane, "closeSlider");
+                    $R.addClass(dragClass + " " + dragPaneClass);
+                    draggingClassSet = false;
+                    var resizerWidth = (pane == "east" || pane == "south" ? o.spacing_open : 0);
+                    setPaneMinMaxSizes(pane);
+                    s.minPosition -= resizerWidth;
+                    s.maxPosition -= resizerWidth;
+                    edge = (c[pane].dir == "horz" ? "top" : "left");
+                    $(o.maskIframesOnResize === true ? "iframe" : o.maskIframesOnResize).each(function () {
+                        $('<div class="ui-layout-mask"/>').css({background: "#fff", opacity: "0.001", zIndex: 9, position: "absolute", width: this.offsetWidth + "px", height: this.offsetHeight + "px"}).css($(this).offset()).appendTo(this.parentNode);
+                    });
+                }, drag: function (e, ui) {
+                    if (!draggingClassSet) {
+                        $(".ui-draggable-dragging").addClass(draggingClass + " " + draggingPaneClass).children().css("visibility", "hidden");
+                        draggingClassSet = true;
+                        if (s.isSliding)$Ps[pane].css("zIndex", c.zIndex.sliding);
+                    }
+                    if (ui.position[edge] < s.minPosition)ui.position[edge] = s.minPosition; else if (ui.position[edge] > s.maxPosition)ui.position[edge] = s.maxPosition;
+                }, stop: function (e, ui) {
+                    var
+                        dragPos = ui.position, resizerPos, newSize;
+                    $R.removeClass(dragClass + " " + dragPaneClass);
+                    switch (pane) {
+                        case"north":
+                            resizerPos = dragPos.top;
+                            break;
+                        case"west":
+                            resizerPos = dragPos.left;
+                            break;
+                        case"south":
+                            resizerPos = cDims.outerHeight - dragPos.top - $R.outerHeight();
+                            break;
+                        case"east":
+                            resizerPos = cDims.outerWidth - dragPos.left - $R.outerWidth();
+                            break;
+                    }
+                    newSize = resizerPos - cDims[c[pane].edge];
+                    sizePane(pane, newSize);
+                    $("div.ui-layout-mask").remove();
+                    s.isResizing = false;
+                }});
+            });
+        };
+        var hide = function (pane, onInit) {
+            var
+                o = options[pane], s = state[pane], $P = $Ps[pane], $R = $Rs[pane];
+            if (!$P || s.isHidden)return;
+            if (false === execUserCallback(pane, o.onhide_start))return;
+            s.isSliding = false;
+            if ($R)$R.hide();
+            if (onInit || s.isClosed) {
+                s.isClosed = true;
+                s.isHidden = true;
+                $P.hide();
+                sizeMidPanes(c[pane].dir == "horz" ? "all" : "center");
+                execUserCallback(pane, o.onhide_end || o.onhide);
+            } else {
+                s.isHiding = true;
+                close(pane, false);
+            }
+        };
+        var show = function (pane, openPane) {
+            var
+                o = options[pane], s = state[pane], $P = $Ps[pane], $R = $Rs[pane];
+            if (!$P || !s.isHidden)return;
+            if (false === execUserCallback(pane, o.onshow_start))return;
+            s.isSliding = false;
+            s.isShowing = true;
+            if ($R && o.spacing_open > 0)$R.show();
+            if (openPane === false)close(pane, true); else
+                open(pane);
+        };
+        var toggle = function (pane) {
+            var s = state[pane];
+            if (s.isHidden)show(pane); else if (s.isClosed)open(pane); else
+                close(pane);
+        };
+        var close = function (pane, force, noAnimation) {
+            var
+                $P = $Ps[pane], $R = $Rs[pane], $T = $Ts[pane], o = options[pane], s = state[pane], doFX = !noAnimation && !s.isClosed && (o.fxName_close != "none"), edge = c[pane].edge, rClass = o.resizerClass, tClass = o.togglerClass, _pane = "-" + pane, _open = "-open", _sliding = "-sliding", _closed = "-closed", isShowing = s.isShowing, isHiding = s.isHiding;
+            delete s.isShowing;
+            delete s.isHiding;
+            if (!$P || (!o.resizable && !o.closable))return; else if (!force && s.isClosed && !isShowing)return;
+            if (c.isLayoutBusy) {
+                setFlowCallback("close", pane, force);
+                return;
+            }
+            if (!isShowing && false === execUserCallback(pane, o.onclose_start))return;
+            c[pane].isMoving = true;
+            c.isLayoutBusy = true;
+            s.isClosed = true;
+            if (isHiding)s.isHidden = true; else if (isShowing)s.isHidden = false;
+            syncPinBtns(pane, false);
+            if (!s.isSliding)sizeMidPanes(c[pane].dir == "horz" ? "all" : "center");
+            if ($R) {
+                $R.css(edge, cDims[edge]).removeClass(rClass + _open + " " + rClass + _pane + _open).removeClass(rClass + _sliding + " " + rClass + _pane + _sliding).addClass(rClass + _closed + " " + rClass + _pane + _closed);
+                if (o.resizable)$R.draggable("disable").css("cursor", "default").attr("title", "");
+                if ($T) {
+                    $T.removeClass(tClass + _open + " " + tClass + _pane + _open).addClass(tClass + _closed + " " + tClass + _pane + _closed).attr("title", o.togglerTip_closed);
+                }
+                sizeHandles();
+            }
+            if (doFX) {
+                lockPaneForFX(pane, true);
+                $P.hide(o.fxName_close, o.fxSettings_close, o.fxSpeed_close, function () {
+                    lockPaneForFX(pane, false);
+                    if (!s.isClosed)return;
+                    close_2();
+                });
+            } else {
+                $P.hide();
+                close_2();
+            }
+            function close_2() {
+                bindStartSlidingEvent(pane, true);
+                if (!isShowing)execUserCallback(pane, o.onclose_end || o.onclose);
+                if (isShowing)execUserCallback(pane, o.onshow_end || o.onshow);
+                if (isHiding)execUserCallback(pane, o.onhide_end || o.onhide);
+                execFlowCallback(pane);
+            }
+        };
+        var open = function (pane, slide, noAnimation) {
+            var
+                $P = $Ps[pane], $R = $Rs[pane], $T = $Ts[pane], o = options[pane], s = state[pane], doFX = !noAnimation && s.isClosed && (o.fxName_open != "none"), edge = c[pane].edge, rClass = o.resizerClass, tClass = o.togglerClass, _pane = "-" + pane, _open = "-open", _closed = "-closed", _sliding = "-sliding", isShowing = s.isShowing;
+            delete s.isShowing;
+            if (!$P || (!o.resizable && !o.closable))return; else if (!s.isClosed && !s.isSliding)return;
+            if (s.isHidden && !isShowing) {
+                show(pane, true);
+                return;
+            }
+            if (c.isLayoutBusy) {
+                setFlowCallback("open", pane, slide);
+                return;
+            }
+            if (false === execUserCallback(pane, o.onopen_start))return;
+            c[pane].isMoving = true;
+            c.isLayoutBusy = true;
+            if (s.isSliding && !slide)bindStopSlidingEvents(pane, false);
+            s.isClosed = false;
+            if (isShowing)s.isHidden = false;
+            setPaneMinMaxSizes(pane);
+            if (s.size > s.maxSize)$P.css(c[pane].sizeType, max(1, cssSize(pane, s.maxSize)));
+            bindStartSlidingEvent(pane, false);
+            if (doFX) {
+                lockPaneForFX(pane, true);
+                $P.show(o.fxName_open, o.fxSettings_open, o.fxSpeed_open, function () {
+                    lockPaneForFX(pane, false);
+                    if (s.isClosed)return;
+                    open_2();
+                });
+            } else {
+                $P.show();
+                open_2();
+            }
+            function open_2() {
+                if (!s.isSliding)sizeMidPanes(c[pane].dir == "vert" ? "center" : "all");
+                if ($R) {
+                    $R.css(edge, cDims[edge] + getPaneSize(pane)).removeClass(rClass + _closed + " " + rClass + _pane + _closed).addClass(rClass + _open + " " + rClass + _pane + _open).addClass(!s.isSliding ? "" : rClass + _sliding + " " + rClass + _pane + _sliding);
+                    if (o.resizable)$R.draggable("enable").css("cursor", o.resizerCursor).attr("title", o.resizerTip); else
+                        $R.css("cursor", "default");
+                    if ($T) {
+                        $T.removeClass(tClass + _closed + " " + tClass + _pane + _closed).addClass(tClass + _open + " " + tClass + _pane + _open).attr("title", o.togglerTip_open);
+                    }
+                    sizeHandles("all");
+                }
+                sizeContent(pane);
+                syncPinBtns(pane, !s.isSliding);
+                execUserCallback(pane, o.onopen_end || o.onopen);
+                if (isShowing)execUserCallback(pane, o.onshow_end || o.onshow);
+                execFlowCallback(pane);
+            }
+        };
+        var lockPaneForFX = function (pane, doLock) {
+            var $P = $Ps[pane];
+            if (doLock) {
+                $P.css({zIndex: c.zIndex.animation});
+                if (pane == "south")$P.css({top: cDims.top + cDims.innerHeight - $P.outerHeight()}); else if (pane == "east")$P.css({left: cDims.left + cDims.innerWidth - $P.outerWidth()});
+            } else {
+                if (!state[pane].isSliding)$P.css({zIndex: c.zIndex.pane_normal});
+                if (pane == "south")$P.css({top: "auto"}); else if (pane == "east")$P.css({left: "auto"});
+            }
+        };
+        var bindStartSlidingEvent = function (pane, enable) {
+            var
+                o = options[pane], $R = $Rs[pane], trigger = o.slideTrigger_open;
+            if (!$R || !o.slidable)return;
+            if (trigger != "click" && trigger != "dblclick" && trigger != "mouseover")trigger = "click";
+            $R
+                [enable ? "bind" : "unbind"](trigger, slideOpen).css("cursor", (enable ? o.sliderCursor : "default")).attr("title", (enable ? o.sliderTip : ""));
+        };
+        var bindStopSlidingEvents = function (pane, enable) {
+            var
+                o = options[pane], s = state[pane], trigger = o.slideTrigger_close, action = (enable ? "bind" : "unbind"), $P = $Ps[pane], $R = $Rs[pane];
+            s.isSliding = enable;
+            clearTimer(pane, "closeSlider");
+            $P.css({zIndex: (enable ? c.zIndex.sliding : c.zIndex.pane_normal)});
+            $R.css({zIndex: (enable ? c.zIndex.sliding : c.zIndex.resizer_normal)});
+            if (trigger != "click" && trigger != "mouseout")trigger = "mouseout";
+            if (enable) {
+                $P.bind(trigger, slideClosed);
+                $R.bind(trigger, slideClosed);
+                if (trigger = "mouseout") {
+                    $P.bind("mouseover", cancelMouseOut);
+                    $R.bind("mouseover", cancelMouseOut);
+                }
+            } else {
+                $P.unbind(trigger);
+                $R.unbind(trigger);
+                if (trigger = "mouseout") {
+                    $P.unbind("mouseover");
+                    $R.unbind("mouseover");
+                    clearTimer(pane, "closeSlider");
+                }
+            }
+            function cancelMouseOut(evt) {
+                clearTimer(pane, "closeSlider");
+                evt.stopPropagation();
+            }
+        };
+        var slideOpen = function () {
+            var pane = $(this).attr("resizer");
+            if (state[pane].isClosed) {
+                bindStopSlidingEvents(pane, true);
+                open(pane, true);
+            }
+        };
+        var slideClosed = function () {
+            var
+                $E = $(this), pane = $E.attr("pane") || $E.attr("resizer"), o = options[pane], s = state[pane];
+            if (s.isClosed || s.isResizing)return; else if (o.slideTrigger_close == "click")close_NOW(); else
+                setTimer(pane, "closeSlider", close_NOW, 300);
+            function close_NOW() {
+                bindStopSlidingEvents(pane, false);
+                if (!s.isClosed)close(pane);
+            }
+        };
+        var sizePane = function (pane, size) {
+            var
+                edge = c[pane].edge, dir = c[pane].dir, o = options[pane], s = state[pane], $P = $Ps[pane], $R = $Rs[pane];
+            setPaneMinMaxSizes(pane);
+            s.minSize = max(s.minSize, o.minSize);
+            if (o.maxSize > 0)s.maxSize = min(s.maxSize, o.maxSize);
+            size = max(size, s.minSize);
+            size = min(size, s.maxSize);
+            s.size = size;
+            $R.css(edge, size + cDims[edge]);
+            $P.css(c[pane].sizeType, max(1, cssSize(pane, size)));
+            if (!s.isSliding)sizeMidPanes(dir == "horz" ? "all" : "center");
+            sizeHandles();
+            sizeContent(pane);
+            execUserCallback(pane, o.onresize_end || o.onresize);
+        };
+        var sizeMidPanes = function (panes, overrideDims, onInit) {
+            if (!panes || panes == "all")panes = "east,west,center";
+            var d = getPaneDims();
+            if (overrideDims)$.extend(d, overrideDims);
+            $.each(panes.split(","), function () {
+                if (!$Ps[this])return;
+                var
+                    pane = str(this), o = options[pane], s = state[pane], $P = $Ps[pane], $R = $Rs[pane], hasRoom = true, CSS = {};
+                if (pane == "center") {
+                    d = getPaneDims();
+                    CSS = $.extend({}, d);
+                    CSS.width = max(1, cssW(pane, CSS.width));
+                    CSS.height = max(1, cssH(pane, CSS.height));
+                    hasRoom = (CSS.width > 1 && CSS.height > 1);
+                    if ($.browser.msie && (!$.boxModel || $.browser.version < 7)) {
+                        if ($Ps.north)$Ps.north.css({width: cssW($Ps.north, cDims.innerWidth)});
+                        if ($Ps.south)$Ps.south.css({width: cssW($Ps.south, cDims.innerWidth)});
+                    }
+                } else {
+                    CSS.top = d.top;
+                    CSS.bottom = d.bottom;
+                    CSS.height = max(1, cssH(pane, d.height));
+                    hasRoom = (CSS.height > 1);
+                }
+                if (hasRoom) {
+                    $P.css(CSS);
+                    if (s.noRoom) {
+                        s.noRoom = false;
+                        if (s.isHidden)return; else show(pane, !s.isClosed);
+                    }
+                    if (!onInit) {
+                        sizeContent(pane);
+                        execUserCallback(pane, o.onresize_end || o.onresize);
+                    }
+                } else if (!s.noRoom) {
+                    s.noRoom = true;
+                    if (s.isHidden)return;
+                    if (onInit) {
+                        $P.hide();
+                        if ($R)$R.hide();
+                    } else hide(pane);
+                }
+            });
+        };
+        var sizeContent = function (panes) {
+            if (!panes || panes == "all")panes = c.allPanes;
+            $.each(panes.split(","), function () {
+                if (!$Cs[this])return;
+                var
+                    pane = str(this), ignore = options[pane].contentIgnoreSelector, $P = $Ps[pane], $C = $Cs[pane], e_C = $C[0], height = cssH($P);
+                ;
+                $P.children().each(function () {
+                    if (this == e_C)return;
+                    var $E = $(this);
+                    if (!ignore || !$E.is(ignore))height -= $E.outerHeight();
+                });
+                if (height > 0)height = cssH($C, height);
+                if (height < 1)$C.hide(); else
+                    $C.css({height: height}).show();
+            });
+        };
+        var sizeHandles = function (panes, onInit) {
+            if (!panes || panes == "all")panes = c.borderPanes;
+            $.each(panes.split(","), function () {
+                var
+                    pane = str(this), o = options[pane], s = state[pane], $P = $Ps[pane], $R = $Rs[pane], $T = $Ts[pane];
+                if (!$P || !$R || (!o.resizable && !o.closable))return;
+                var
+                    dir = c[pane].dir, _state = (s.isClosed ? "_closed" : "_open"), spacing = o["spacing" + _state], togAlign = o["togglerAlign" + _state], togLen = o["togglerLength" + _state], paneLen, offset, CSS = {};
+                if (spacing == 0) {
+                    $R.hide();
+                    return;
+                } else if (!s.noRoom && !s.isHidden)$R.show();
+                if (dir == "horz") {
+                    paneLen = $P.outerWidth();
+                    $R.css({width: max(1, cssW($R, paneLen)), height: max(1, cssH($R, spacing)), left: cssNum($P, "left")});
+                } else {
+                    paneLen = $P.outerHeight();
+                    $R.css({height: max(1, cssH($R, paneLen)), width: max(1, cssW($R, spacing)), top: cDims.top + getPaneSize("north", true)});
+                }
+                if ($T) {
+                    if (togLen == 0 || (s.isSliding && o.hideTogglerOnSlide)) {
+                        $T.hide();
+                        return;
+                    } else
+                        $T.show();
+                    if (!(togLen > 0) || togLen == "100%" || togLen > paneLen) {
+                        togLen = paneLen;
+                        offset = 0;
+                    } else {
+                        if (typeof togAlign == "string") {
+                            switch (togAlign) {
+                                case"top":
+                                case"left":
+                                    offset = 0;
+                                    break;
+                                case"bottom":
+                                case"right":
+                                    offset = paneLen - togLen;
+                                    break;
+                                case"middle":
+                                case"center":
+                                default:
+                                    offset = Math.floor((paneLen - togLen) / 2);
+                            }
+                        } else {
+                            var x = parseInt(togAlign);
+                            if (togAlign >= 0)offset = x; else offset = paneLen - togLen + x;
+                        }
+                    }
+                    var
+                        $TC_o = (o.togglerContent_open ? $T.children(".content-open") : false), $TC_c = (o.togglerContent_closed ? $T.children(".content-closed") : false), $TC = (s.isClosed ? $TC_c : $TC_o);
+                    if ($TC_o)$TC_o.css("display", s.isClosed ? "none" : "block");
+                    if ($TC_c)$TC_c.css("display", s.isClosed ? "block" : "none");
+                    if (dir == "horz") {
+                        var width = cssW($T, togLen);
+                        $T.css({width: max(0, width), height: max(1, cssH($T, spacing)), left: offset});
+                        if ($TC)$TC.css("marginLeft", Math.floor((width - $TC.outerWidth()) / 2));
+                    } else {
+                        var height = cssH($T, togLen);
+                        $T.css({height: max(0, height), width: max(1, cssW($T, spacing)), top: offset});
+                        if ($TC)$TC.css("marginTop", Math.floor((height - $TC.outerHeight()) / 2));
+                    }
+                }
+                if (onInit && o.initHidden) {
+                    $R.hide();
+                    if ($T)$T.hide();
+                }
+            });
+        };
+        var resizeAll = function () {
+            var
+                oldW = cDims.innerWidth, oldH = cDims.innerHeight;
+            cDims = state.container = getElemDims($Container);
+            var
+                checkH = (cDims.innerHeight < oldH), checkW = (cDims.innerWidth < oldW), s, dir;
+            if (checkH || checkW)$.each(["south", "north", "east", "west"], function (i, pane) {
+                s = state[pane];
+                dir = c[pane].dir;
+                if (!s.isClosed && ((checkH && dir == "horz") || (checkW && dir == "vert"))) {
+                    setPaneMinMaxSizes(pane);
+                    if (s.size > s.maxSize)sizePane(pane, s.maxSize);
+                }
+            });
+            sizeMidPanes("all");
+            sizeHandles("all");
+        };
+
+        function keyDown(evt) {
+            if (!evt)return true;
+            var code = evt.keyCode;
+            if (code < 33)return true;
+            var
+                PANE = {38: "north", 40: "south", 37: "west", 39: "east"}, isCursorKey = (code >= 37 && code <= 40), ALT = evt.altKey, SHIFT = evt.shiftKey, CTRL = evt.ctrlKey, pane = false, s, o, k, m, el;
+            if (!CTRL && !SHIFT)return true; else if (isCursorKey && options[PANE[code]].enableCursorHotkey)pane = PANE[code]; else
+                $.each(c.borderPanes.split(","), function (i, p) {
+                    o = options[p];
+                    k = o.customHotkey;
+                    m = o.customHotkeyModifier;
+                    if ((SHIFT && m == "SHIFT") || (CTRL && m == "CTRL") || (CTRL && SHIFT)) {
+                        if (k && code == (isNaN(k) || k <= 9 ? k.toUpperCase().charCodeAt(0) : k)) {
+                            pane = p;
+                            return false;
+                        }
+                    }
+                });
+            if (!pane)return true;
+            o = options[pane];
+            s = state[pane];
+            if (!o.enableCursorHotkey || s.isHidden || !$Ps[pane])return true;
+            el = evt.target || evt.srcElement;
+            if (el && SHIFT && isCursorKey && (el.tagName == "TEXTAREA" || (el.tagName == "INPUT" && (code == 37 || code == 39))))return true;
+            toggle(pane);
+            evt.stopPropagation();
+            evt.returnValue = false;
+            return false;
+        };
+        function allowOverflow(elem) {
+            if (this && this.tagName)elem = this;
+            var $P;
+            if (typeof elem == "string")$P = $Ps[elem]; else {
+                if ($(elem).attr("pane"))$P = $(elem); else $P = $(elem).parents("div[pane]:first");
+            }
+            if (!$P.length)return;
+            var
+                pane = $P.attr("pane"), s = state[pane];
+            if (s.cssSaved)resetOverflow(pane);
+            if (s.isSliding || s.isResizing || s.isClosed) {
+                s.cssSaved = false;
+                return;
+            }
+            var
+                newCSS = {zIndex: (c.zIndex.pane_normal + 1)}, curCSS = {}, of = $P.css("overflow"), ofX = $P.css("overflowX"), ofY = $P.css("overflowY");
+            if (of != "visible") {
+                curCSS.overflow = of;
+                newCSS.overflow = "visible";
+            }
+            if (ofX && ofX != "visible" && ofX != "auto") {
+                curCSS.overflowX = ofX;
+                newCSS.overflowX = "visible";
+            }
+            if (ofY && ofY != "visible" && ofY != "auto") {
+                curCSS.overflowY = ofX;
+                newCSS.overflowY = "visible";
+            }
+            s.cssSaved = curCSS;
+            $P.css(newCSS);
+            $.each(c.allPanes.split(","), function (i, p) {
+                if (p != pane)resetOverflow(p);
+            });
+        };
+        function resetOverflow(elem) {
+            if (this && this.tagName)elem = this;
+            var $P;
+            if (typeof elem == "string")$P = $Ps[elem]; else {
+                if ($(elem).hasClass("ui-layout-pane"))$P = $(elem); else $P = $(elem).parents("div[pane]:first");
+            }
+            if (!$P.length)return;
+            var
+                pane = $P.attr("pane"), s = state[pane], CSS = s.cssSaved || {};
+            if (!s.isSliding && !s.isResizing)$P.css("zIndex", c.zIndex.pane_normal);
+            $P.css(CSS);
+            s.cssSaved = false;
+        };
+        function getBtn(selector, pane, action) {
+            var
+                $E = $(selector), err = "Error Adding Button \n\nInvalid ";
+            if (!$E.length)alert(err + "selector: " + selector); else if (c.borderPanes.indexOf(pane) == -1)alert(err + "pane: " + pane); else {
+                var btn = options[pane].buttonClass + "-" + action;
+                $E.addClass(btn + " " + btn + "-" + pane);
+                return $E;
+            }
+            return false;
+        };
+        function addToggleBtn(selector, pane) {
+            var $E = getBtn(selector, pane, "toggle");
+            if ($E)$E.attr("title", state[pane].isClosed ? "Open" : "Close").click(function (evt) {
+                toggle(pane);
+                evt.stopPropagation();
+            });
+        };
+        function addOpenBtn(selector, pane) {
+            var $E = getBtn(selector, pane, "open");
+            if ($E)$E.attr("title", "Open").click(function (evt) {
+                open(pane);
+                evt.stopPropagation();
+            });
+        };
+        function addCloseBtn(selector, pane) {
+            var $E = getBtn(selector, pane, "close");
+            if ($E)$E.attr("title", "Close").click(function (evt) {
+                close(pane);
+                evt.stopPropagation();
+            });
+        };
+        function addPinBtn(selector, pane) {
+            var $E = getBtn(selector, pane, "pin");
+            if ($E) {
+                var s = state[pane];
+                $E.click(function (evt) {
+                    setPinState($(this), pane, (s.isSliding || s.isClosed));
+                    if (s.isSliding || s.isClosed)open(pane); else close(pane);
+                    evt.stopPropagation();
+                });
+                setPinState($E, pane, (!s.isClosed && !s.isSliding));
+                c[pane].pins.push(selector);
+            }
+        };
+        function syncPinBtns(pane, doPin) {
+            $.each(c[pane].pins, function (i, selector) {
+                setPinState($(selector), pane, doPin);
+            });
+        };
+        function setPinState($Pin, pane, doPin) {
+            var updown = $Pin.attr("pin");
+            if (updown && doPin == (updown == "down"))return;
+            var
+                root = options[pane].buttonClass, class1 = root + "-pin", class2 = class1 + "-" + pane, UP1 = class1 + "-up", UP2 = class2 + "-up", DN1 = class1 + "-down", DN2 = class2 + "-down";
+            $Pin.attr("pin", doPin ? "down" : "up").attr("title", doPin ? "Un-Pin" : "Pin").removeClass(doPin ? UP1 : DN1).removeClass(doPin ? UP2 : DN2).addClass(doPin ? DN1 : UP1).addClass(doPin ? DN2 : UP2);
+        };
+        var
+            $Container = $(this).css({overflow: "hidden"}), $Ps = {}, $Cs = {}, $Rs = {}, $Ts = {}, c = config, cDims = state.container;
+        create();
+        return{options: options, state: state, panes: $Ps, toggle: toggle, open: open, close: close, hide: hide, show: show, resizeContent: sizeContent, sizePane: sizePane, resizeAll: resizeAll, addToggleBtn: addToggleBtn, addOpenBtn: addOpenBtn, addCloseBtn: addCloseBtn, addPinBtn: addPinBtn, allowOverflow: allowOverflow, resetOverflow: resetOverflow, cssWidth: cssW, cssHeight: cssH};
+    }
+})(jQuery);
\ No newline at end of file
diff --git a/media/js/lib/jquery.multiselect.js b/media/js/lib/jquery.multiselect.js
index 254e31a..8aab394 100644
--- a/media/js/lib/jquery.multiselect.js
+++ b/media/js/lib/jquery.multiselect.js
@@ -17,652 +17,654 @@
  *   http://www.opensource.org/licenses/mit-license.php
  *   http://www.gnu.org/licenses/gpl.html
  *
-*/
-(function($, undefined){
-
-var multiselectID = 0;
-
-$.widget("ech.multiselect", {
-
-	// default options
-	options: {
-		header: true,
-		height: 175,
-		minWidth: 225,
-		classes: '',
-		checkAllText: 'Check all',
-		uncheckAllText: 'Uncheck all',
-		noneSelectedText: 'Select options',
-		selectedText: '# selected',
-		selectedList: 0,
-		show: '',
-		hide: '',
-		autoOpen: false,
-		multiple: true,
-		position: {}
-	},
-
-	_create: function(){
-		var el = this.element.hide(),
-			o = this.options;
-
-		this.speed = $.fx.speeds._default; // default speed for effects
-		this._isOpen = false; // assume no
-
-		var
-			button = (this.button = $('<button type="button"><span class="ui-icon ui-icon-triangle-2-n-s"></span></button>'))
-				.addClass('ui-multiselect2 ui-widget ui-state-default ui-corner-all')
-				.addClass( o.classes )
-				.attr({ 'title':el.attr('title'), 'aria-haspopup':true, 'tabIndex':el.attr('tabIndex') })
-				.insertAfter( el ),
-
-			buttonlabel = (this.buttonlabel = $('<span />'))
-				.html( o.noneSelectedText )
-				.appendTo( button ),
-
-			menu = (this.menu = $('<div />'))
-				.addClass('ui-multiselect-menu ui-widget ui-widget-content ui-corner-all')
-				.addClass( o.classes )
-				.appendTo( document.body ),
-
-			header = (this.header = $('<div />'))
-				.addClass('ui-widget-header ui-corner-all ui-multiselect-header ui-helper-clearfix')
-				.appendTo( menu ),
-
-			headerLinkContainer = (this.headerLinkContainer = $('<ul />'))
-				.addClass('ui-helper-reset')
-				.html(function(){
-					if( o.header === true ){
-						return '<li><a class="ui-multiselect-all" href="#"><span class="ui-icon ui-icon-check"></span><span>' + o.checkAllText + '</span></a></li><li><a class="ui-multiselect-none" href="#"><span class="ui-icon ui-icon-closethick"></span><span>' + o.uncheckAllText + '</span></a></li>';
-					} else if(typeof o.header === "string"){
-						return '<li>' + o.header + '</li>';
-					} else {
-						return '';
-					}
-				})
-				.append('<li class="ui-multiselect-close"><a href="#" class="ui-multiselect-close"><span class="ui-icon ui-icon-circle-close"></span></a></li>')
-				.appendTo( header ),
-
-			checkboxContainer = (this.checkboxContainer = $('<ul />'))
-				.addClass('ui-multiselect-checkboxes ui-helper-reset')
-				.appendTo( menu );
-
-		// perform event bindings
-		this._bindEvents();
-
-		// build menu
-		this.refresh( true );
-
-		// some addl. logic for single selects
-		if( !o.multiple ){
-			menu.addClass('ui-multiselect-single');
-		}
-	},
-
-	_init: function(){
-		if( this.options.header === false ){
-			this.header.hide();
-		}
-		if( !this.options.multiple ){
-			this.headerLinkContainer.find('.ui-multiselect-all, .ui-multiselect-none').hide();
-		}
-		if( this.options.autoOpen ){
-			this.open();
-		}
-		if( this.element.is(':disabled') ){
-			this.disable();
-		}
-	},
-
-	refresh: function( init ){
-		var el = this.element,
-			o = this.options,
-			menu = this.menu,
-			checkboxContainer = this.checkboxContainer,
-			optgroups = [],
-			html = [],
-			id = el.attr('id') || multiselectID++; // unique ID for the label & option tags
-
-		// build items
-		el.find('option').each(function( i ){
-			var $this = $(this),
-				parent = this.parentNode,
-				title = this.innerHTML,
-				description = this.title,
-				value = this.value,
-				inputID = this.id || 'ui-multiselect-' + id + '-option-' + i,
-				isDisabled = this.disabled,
-				isSelected = this.selected,
-				labelClasses = ['ui-corner-all'],
-				optLabel;
-
-			// is this an optgroup?
-			if( parent.tagName.toLowerCase() === 'optgroup' ){
-				optLabel = parent.getAttribute('label');
-
-				// has this optgroup been added already?
-				if( $.inArray(optLabel, optgroups) === -1 ){
-					html.push('<li class="ui-multiselect-optgroup-label"><a href="#">' + optLabel + '</a></li>');
-					optgroups.push( optLabel );
-				}
-			}
-
-			if( isDisabled ){
-				labelClasses.push('ui-state-disabled');
-			}
-
-			// browsers automatically select the first option
-			// by default with single selects
-			if( isSelected && !o.multiple ){
-				labelClasses.push('ui-state-active');
-			}
-
-			html.push('<li class="' + (isDisabled ? 'ui-multiselect-disabled' : '') + '">');
-
-			// create the label
-			html.push('<label for="' + inputID + '" title="' + description + '" class="' + labelClasses.join(' ') + '">');
-			html.push('<input id="' + inputID + '" name="multiselect_' + id + '" type="' + (o.multiple ? "checkbox" : "radio") + '" value="' + value + '" title="' + title + '"');
-
-			// pre-selected?
-			if( isSelected ){
-				html.push(' checked="checked"');
-				html.push(' aria-selected="true"');
-			}
-
-			// disabled?
-			if( isDisabled ){
-				html.push(' disabled="disabled"');
-				html.push(' aria-disabled="true"');
-			}
-
-			// add the title and close everything off
-			html.push(' /><span>' + title + '</span></label></li>');
-		});
-
-		// insert into the DOM
-		checkboxContainer.html( html.join('') );
-
-		// cache some moar useful elements
-		this.labels = menu.find('label');
-
-		// set widths
-		this._setButtonWidth();
-		this._setMenuWidth();
-
-		// remember default value
-		this.button[0].defaultValue = this.update();
-
-		// broadcast refresh event; useful for widgets
-		if( !init ){
-			this._trigger('refresh');
-		}
-	},
-
-	// updates the button text. call refresh() to rebuild
-	update: function(){
-		var o = this.options,
-			$inputs = this.labels.find('input'),
-			$checked = $inputs.filter(':checked'),
-			numChecked = $checked.length,
-			value;
-
-		if( numChecked === 0 ){
-			value = o.noneSelectedText;
-		} else {
-			if($.isFunction( o.selectedText )){
-				value = o.selectedText.call(this, numChecked, $inputs.length, $checked.get());
-			} else if( /\d/.test(o.selectedList) && o.selectedList > 0 && numChecked <= o.selectedList){
-				value = $checked.map(function(){ return $(this).next().text(); }).get().join(', ');
-			} else {
-				value = o.selectedText.replace('#', numChecked).replace('#', $inputs.length);
-			}
-		}
-
-		this.buttonlabel.html( value );
-		return value;
-	},
-
-	// binds events
-	_bindEvents: function(){
-		var self = this, button = this.button;
-
-		function clickHandler(){
-			self[ self._isOpen ? 'close' : 'open' ]();
-			return false;
-		}
-
-		// webkit doesn't like it when you click on the span :(
-		button
-			.find('span')
-			.bind('click.multiselect', clickHandler);
-
-		// button events
-		button.bind({
-			click: clickHandler,
-			keypress: function( e ){
-				switch(e.which){
-					case 27: // esc
-					case 38: // up
-					case 37: // left
-						self.close();
-						break;
-					case 39: // right
-					case 40: // down
-						self.open();
-						break;
-				}
-			},
-			mouseenter: function(){
-				if( !button.hasClass('ui-state-disabled') ){
-					$(this).addClass('ui-state-hover');
-				}
-			},
-			mouseleave: function(){
-				$(this).removeClass('ui-state-hover');
-			},
-			focus: function(){
-				if( !button.hasClass('ui-state-disabled') ){
-					$(this).addClass('ui-state-focus');
-				}
-			},
-			blur: function(){
-				$(this).removeClass('ui-state-focus');
-			}
-		});
-
-		// header links
-		this.header
-			.delegate('a', 'click.multiselect', function( e ){
-				// close link
-				if( $(this).hasClass('ui-multiselect-close') ){
-					self.close();
-
-				// check all / uncheck all
-				} else {
-					self[ $(this).hasClass('ui-multiselect-all') ? 'checkAll' : 'uncheckAll' ]();
-				}
-
-				e.preventDefault();
-			});
-
-		// optgroup label toggle support
-		this.menu
-			.delegate('li.ui-multiselect-optgroup-label a', 'click.multiselect', function( e ){
-				e.preventDefault();
-
-				var $this = $(this),
-					$inputs = $this.parent().nextUntil('li.ui-multiselect-optgroup-label').find('input:visible:not(:disabled)'),
-				    nodes = $inputs.get(),
-				    label = $this.parent().text();
-
-				// trigger event and bail if the return is false
-				if( self._trigger('beforeoptgrouptoggle', e, { inputs:nodes, label:label }) === false ){
-					return;
-				}
-
-				// toggle inputs
-				self._toggleChecked(
-					$inputs.filter('[checked]').length !== $inputs.length,
-					$inputs
-				);
-
-				self._trigger('optgrouptoggle', e, {
-				    inputs: nodes,
-				    label: label,
-				    checked: nodes[0].checked
-				});
-			})
-			.delegate('label', 'mouseenter.multiselect', function(){
-				if( !$(this).hasClass('ui-state-disabled') ){
-					self.labels.removeClass('ui-state-hover');
-					$(this).addClass('ui-state-hover').find('input').focus();
-				}
-			})
-			.delegate('label', 'keydown.multiselect', function( e ){
-				e.preventDefault();
-
-				switch(e.which){
-					case 9: // tab
-					case 27: // esc
-						self.close();
-						break;
-					case 38: // up
-					case 40: // down
-					case 37: // left
-					case 39: // right
-						self._traverse(e.which, this);
-						break;
-					case 13: // enter
-						$(this).find('input')[0].click();
-						break;
-				}
-			})
-			.delegate('input[type="checkbox"], input[type="radio"]', 'click.multiselect', function( e ){
-				var $this = $(this),
-					val = this.value,
-					checked = this.checked,
-					tags = self.element.find('option');
-
-				// bail if this input is disabled or the event is cancelled
-				if( this.disabled || self._trigger('click', e, { value: val, text: this.title, checked: checked }) === false ){
-					e.preventDefault();
-					return;
-				}
-
-				// make sure the input has focus. otherwise, the esc key
-				// won't close the menu after clicking an item.
-				$this.focus();
-
-				// toggle aria state
-				$this.attr('aria-selected', checked);
-
-				// change state on the original option tags
-				tags.each(function(){
-					if( this.value === val ){
-						this.selected = checked;
-					} else if( !self.options.multiple ){
-						this.selected = false;
-					}
-				});
-
-				// some additional single select-specific logic
-				if( !self.options.multiple ){
-					self.labels.removeClass('ui-state-active');
-					$this.closest('label').toggleClass('ui-state-active', checked );
-
-					// close menu
-					self.close();
-				}
-
-				// fire change on the select box
-				self.element.trigger("change");
-
-				// setTimeout is to fix multiselect issue #14 and #47. caused by jQuery issue #3827
-				// http://bugs.jquery.com/ticket/3827
-				setTimeout($.proxy(self.update, self), 10);
-			});
-
-		// close each widget when clicking on any other element/anywhere else on the page
-		$(document).bind('mousedown.multiselect', function( e ){
-			if(self._isOpen && !$.contains(self.menu[0], e.target) && !$.contains(self.button[0], e.target) && e.target !== self.button[0]){
-				self.close();
-			}
-		});
-
-		// deal with form resets.  the problem here is that buttons aren't
-		// restored to their defaultValue prop on form reset, and the reset
-		// handler fires before the form is actually reset.  delaying it a bit
-		// gives the form inputs time to clear.
-		$(this.element[0].form).bind('reset.multiselect', function(){
-			setTimeout($.proxy(self.refresh, self), 10);
-		});
-	},
-
-	// set button width
-	_setButtonWidth: function(){
-		var width = this.element.outerWidth(),
-			o = this.options;
-
-		if( /\d/.test(o.minWidth) && width < o.minWidth){
-			width = o.minWidth;
-		}
-
-		// set widths
-		this.button.width( width );
-	},
-
-	// set menu width
-	_setMenuWidth: function(){
-		var m = this.menu,
-			width = this.button.outerWidth()-
-				parseInt(m.css('padding-left'),10)-
-				parseInt(m.css('padding-right'),10)-
-				parseInt(m.css('border-right-width'),10)-
-				parseInt(m.css('border-left-width'),10);
-
-		m.width( width || this.button.outerWidth() );
-	},
-
-	// move up or down within the menu
-	_traverse: function( which, start ){
-		var $start = $(start),
-			moveToLast = which === 38 || which === 37,
-
-			// select the first li that isn't an optgroup label / disabled
-			$next = $start.parent()[moveToLast ? 'prevAll' : 'nextAll']('li:not(.ui-multiselect-disabled, .ui-multiselect-optgroup-label)')[ moveToLast ? 'last' : 'first']();
-
-		// if at the first/last element
-		if( !$next.length ){
-			var $container = this.menu.find('ul').last();
-
-			// move to the first/last
-			this.menu.find('label')[ moveToLast ? 'last' : 'first' ]().trigger('mouseover');
-
-			// set scroll position
-			$container.scrollTop( moveToLast ? $container.height() : 0 );
-
-		} else {
-			$next.find('label').trigger('mouseover');
-		}
-	},
-
-	// This is an internal function to toggle the checked property and
-	// other related attributes of a checkbox.
-	//
-	// The context of this function should be a checkbox; do not proxy it.
-	_toggleState: function( prop, flag ){
-		return function(){
-			if( !this.disabled ) {
-				this[ prop ] = flag;
-			}
-
-			if( flag ){
-				this.setAttribute('aria-selected', true);
-			} else {
-				this.removeAttribute('aria-selected');
-			}
-		};
-	},
-
-	_toggleChecked: function( flag, group ){
-		var $inputs = (group && group.length) ?
-			group :
-			this.labels.find('input'),
-
-			self = this;
-
-		// toggle state on inputs
-		$inputs.each(this._toggleState('checked', flag));
-
-		// give the first input focus
-		$inputs.eq(0).focus();
-
-		// update button text
-		this.update();
-
-		// gather an array of the values that actually changed
-		var values = $inputs.map(function(){
-			return this.value;
-		}).get();
-
-		// toggle state on original option tags
-		this.element
-			.find('option')
-			.each(function(){
-				if( !this.disabled && $.inArray(this.value, values) > -1 ){
-					self._toggleState('selected', flag).call( this );
-				}
-			});
-
-		// trigger the change event on the select
-		if( $inputs.length ) {
-			this.element.trigger("change");
-		}
-	},
-
-	_toggleDisabled: function( flag ){
-		this.button
-			.attr({ 'disabled':flag, 'aria-disabled':flag })[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled');
-
-		this.menu
-			.find('input')
-			.attr({ 'disabled':flag, 'aria-disabled':flag })
-			.parent()[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled');
-
-		this.element
-			.attr({ 'disabled':flag, 'aria-disabled':flag });
-	},
-
-	// open the menu
-	open: function( e ){
-		var self = this,
-			button = this.button,
-			menu = this.menu,
-			speed = this.speed,
-			o = this.options;
-
-		// bail if the multiselectopen event returns false, this widget is disabled, or is already open
-		if( this._trigger('beforeopen') === false || button.hasClass('ui-state-disabled') || this._isOpen ){
-			return;
-		}
-
-		var $container = menu.find('ul').last(),
-			effect = o.show,
-			pos = button.offset();
-
-		// figure out opening effects/speeds
-		if( $.isArray(o.show) ){
-			effect = o.show[0];
-			speed = o.show[1] || self.speed;
-		}
-
-		// set the scroll of the checkbox container
-		$container.scrollTop(0).height(o.height);
-
-		// position and show menu
-		if( $.ui.position && !$.isEmptyObject(o.position) ){
-			o.position.of = o.position.of || button;
-
-			menu
-				.show()
-				.position( o.position )
-				.hide()
-				.show( effect, speed );
-
-		// if position utility is not available...
-		} else {
-			menu.css({
-				top: pos.top + button.outerHeight(),
-				left: pos.left
-			}).show( effect, speed );
-		}
-
-		// select the first option
-		// triggering both mouseover and mouseover because 1.4.2+ has a bug where triggering mouseover
-		// will actually trigger mouseenter.  the mouseenter trigger is there for when it's eventually fixed
-		this.labels.eq(0).trigger('mouseover').trigger('mouseenter').find('input').trigger('focus');
-
-		button.addClass('ui-state-active');
-		this._isOpen = true;
-		this._trigger('open');
-	},
-
-	// close the menu
-	close: function(){
-		if(this._trigger('beforeclose') === false){
-			return;
-		}
-
-		var o = this.options, effect = o.hide, speed = this.speed;
-
-		// figure out opening effects/speeds
-		if( $.isArray(o.hide) ){
-			effect = o.hide[0];
-			speed = o.hide[1] || this.speed;
-		}
-
-		this.menu.hide(effect, speed);
-		this.button.removeClass('ui-state-active').trigger('blur').trigger('mouseleave');
-		this._isOpen = false;
-		this._trigger('close');
-	},
-
-	enable: function(){
-		this._toggleDisabled(false);
-	},
-
-	disable: function(){
-		this._toggleDisabled(true);
-	},
-
-	checkAll: function( e ){
-		this._toggleChecked(true);
-		this._trigger('checkAll');
-	},
-
-	uncheckAll: function(){
-		this._toggleChecked(false);
-		this._trigger('uncheckAll');
-	},
-
-	getChecked: function(){
-		return this.menu.find('input').filter('[checked]');
-	},
-
-	destroy: function(){
-		// remove classes + data
-		$.Widget.prototype.destroy.call( this );
-
-		this.button.remove();
-		this.menu.remove();
-		this.element.show();
-
-		return this;
-	},
-
-	isOpen: function(){
-		return this._isOpen;
-	},
-
-	widget: function(){
-		return this.menu;
-	},
-
-	// react to option changes after initialization
-	_setOption: function( key, value ){
-		var menu = this.menu;
-
-		switch(key){
-			case 'header':
-				menu.find('div.ui-multiselect-header')[ value ? 'show' : 'hide' ]();
-				break;
-			case 'checkAllText':
-				menu.find('a.ui-multiselect-all span').eq(-1).text(value);
-				break;
-			case 'uncheckAllText':
-				menu.find('a.ui-multiselect-none span').eq(-1).text(value);
-				break;
-			case 'height':
-				menu.find('ul').last().height( parseInt(value,10) );
-				break;
-			case 'minWidth':
-				this.options[ key ] = parseInt(value,10);
-				this._setButtonWidth();
-				this._setMenuWidth();
-				break;
-			case 'selectedText':
-			case 'selectedList':
-			case 'noneSelectedText':
-				this.options[key] = value; // these all needs to update immediately for the update() call
-				this.update();
-				break;
-			case 'classes':
-				menu.add(this.button).removeClass(this.options.classes).addClass(value);
-				break;
-		}
-
-		$.Widget.prototype._setOption.apply( this, arguments );
-	}
-});
+ */
+(function ($, undefined) {
+
+    var multiselectID = 0;
+
+    $.widget("ech.multiselect", {
+
+        // default options
+        options: {
+            header: true,
+            height: 175,
+            minWidth: 225,
+            classes: '',
+            checkAllText: 'Check all',
+            uncheckAllText: 'Uncheck all',
+            noneSelectedText: 'Select options',
+            selectedText: '# selected',
+            selectedList: 0,
+            show: '',
+            hide: '',
+            autoOpen: false,
+            multiple: true,
+            position: {}
+        },
+
+        _create: function () {
+            var el = this.element.hide(),
+                o = this.options;
+
+            this.speed = $.fx.speeds._default; // default speed for effects
+            this._isOpen = false; // assume no
+
+            var
+                button = (this.button = $('<button type="button"><span class="ui-icon ui-icon-triangle-2-n-s"></span></button>'))
+                    .addClass('ui-multiselect2 ui-widget ui-state-default ui-corner-all')
+                    .addClass(o.classes)
+                    .attr({ 'title': el.attr('title'), 'aria-haspopup': true, 'tabIndex': el.attr('tabIndex') })
+                    .insertAfter(el),
+
+                buttonlabel = (this.buttonlabel = $('<span />'))
+                    .html(o.noneSelectedText)
+                    .appendTo(button),
+
+                menu = (this.menu = $('<div />'))
+                    .addClass('ui-multiselect-menu ui-widget ui-widget-content ui-corner-all')
+                    .addClass(o.classes)
+                    .appendTo(document.body),
+
+                header = (this.header = $('<div />'))
+                    .addClass('ui-widget-header ui-corner-all ui-multiselect-header ui-helper-clearfix')
+                    .appendTo(menu),
+
+                headerLinkContainer = (this.headerLinkContainer = $('<ul />'))
+                    .addClass('ui-helper-reset')
+                    .html(function () {
+                        if (o.header === true) {
+                            return '<li><a class="ui-multiselect-all" href="#"><span class="ui-icon ui-icon-check"></span><span>' + o.checkAllText + '</span></a></li><li><a class="ui-multiselect-none" href="#"><span class="ui-icon ui-icon-closethick"></span><span>' + o.uncheckAllText + '</span></a></li>';
+                        } else if (typeof o.header === "string") {
+                            return '<li>' + o.header + '</li>';
+                        } else {
+                            return '';
+                        }
+                    })
+                    .append('<li class="ui-multiselect-close"><a href="#" class="ui-multiselect-close"><span class="ui-icon ui-icon-circle-close"></span></a></li>')
+                    .appendTo(header),
+
+                checkboxContainer = (this.checkboxContainer = $('<ul />'))
+                    .addClass('ui-multiselect-checkboxes ui-helper-reset')
+                    .appendTo(menu);
+
+            // perform event bindings
+            this._bindEvents();
+
+            // build menu
+            this.refresh(true);
+
+            // some addl. logic for single selects
+            if (!o.multiple) {
+                menu.addClass('ui-multiselect-single');
+            }
+        },
+
+        _init: function () {
+            if (this.options.header === false) {
+                this.header.hide();
+            }
+            if (!this.options.multiple) {
+                this.headerLinkContainer.find('.ui-multiselect-all, .ui-multiselect-none').hide();
+            }
+            if (this.options.autoOpen) {
+                this.open();
+            }
+            if (this.element.is(':disabled')) {
+                this.disable();
+            }
+        },
+
+        refresh: function (init) {
+            var el = this.element,
+                o = this.options,
+                menu = this.menu,
+                checkboxContainer = this.checkboxContainer,
+                optgroups = [],
+                html = [],
+                id = el.attr('id') || multiselectID++; // unique ID for the label & option tags
+
+            // build items
+            el.find('option').each(function (i) {
+                var $this = $(this),
+                    parent = this.parentNode,
+                    title = this.innerHTML,
+                    description = this.title,
+                    value = this.value,
+                    inputID = this.id || 'ui-multiselect-' + id + '-option-' + i,
+                    isDisabled = this.disabled,
+                    isSelected = this.selected,
+                    labelClasses = ['ui-corner-all'],
+                    optLabel;
+
+                // is this an optgroup?
+                if (parent.tagName.toLowerCase() === 'optgroup') {
+                    optLabel = parent.getAttribute('label');
+
+                    // has this optgroup been added already?
+                    if ($.inArray(optLabel, optgroups) === -1) {
+                        html.push('<li class="ui-multiselect-optgroup-label"><a href="#">' + optLabel + '</a></li>');
+                        optgroups.push(optLabel);
+                    }
+                }
+
+                if (isDisabled) {
+                    labelClasses.push('ui-state-disabled');
+                }
+
+                // browsers automatically select the first option
+                // by default with single selects
+                if (isSelected && !o.multiple) {
+                    labelClasses.push('ui-state-active');
+                }
+
+                html.push('<li class="' + (isDisabled ? 'ui-multiselect-disabled' : '') + '">');
+
+                // create the label
+                html.push('<label for="' + inputID + '" title="' + description + '" class="' + labelClasses.join(' ') + '">');
+                html.push('<input id="' + inputID + '" name="multiselect_' + id + '" type="' + (o.multiple ? "checkbox" : "radio") + '" value="' + value + '" title="' + title + '"');
+
+                // pre-selected?
+                if (isSelected) {
+                    html.push(' checked="checked"');
+                    html.push(' aria-selected="true"');
+                }
+
+                // disabled?
+                if (isDisabled) {
+                    html.push(' disabled="disabled"');
+                    html.push(' aria-disabled="true"');
+                }
+
+                // add the title and close everything off
+                html.push(' /><span>' + title + '</span></label></li>');
+            });
+
+            // insert into the DOM
+            checkboxContainer.html(html.join(''));
+
+            // cache some moar useful elements
+            this.labels = menu.find('label');
+
+            // set widths
+            this._setButtonWidth();
+            this._setMenuWidth();
+
+            // remember default value
+            this.button[0].defaultValue = this.update();
+
+            // broadcast refresh event; useful for widgets
+            if (!init) {
+                this._trigger('refresh');
+            }
+        },
+
+        // updates the button text. call refresh() to rebuild
+        update: function () {
+            var o = this.options,
+                $inputs = this.labels.find('input'),
+                $checked = $inputs.filter(':checked'),
+                numChecked = $checked.length,
+                value;
+
+            if (numChecked === 0) {
+                value = o.noneSelectedText;
+            } else {
+                if ($.isFunction(o.selectedText)) {
+                    value = o.selectedText.call(this, numChecked, $inputs.length, $checked.get());
+                } else if (/\d/.test(o.selectedList) && o.selectedList > 0 && numChecked <= o.selectedList) {
+                    value = $checked.map(function () {
+                        return $(this).next().text();
+                    }).get().join(', ');
+                } else {
+                    value = o.selectedText.replace('#', numChecked).replace('#', $inputs.length);
+                }
+            }
+
+            this.buttonlabel.html(value);
+            return value;
+        },
+
+        // binds events
+        _bindEvents: function () {
+            var self = this, button = this.button;
+
+            function clickHandler() {
+                self[ self._isOpen ? 'close' : 'open' ]();
+                return false;
+            }
+
+            // webkit doesn't like it when you click on the span :(
+            button
+                .find('span')
+                .bind('click.multiselect', clickHandler);
+
+            // button events
+            button.bind({
+                click: clickHandler,
+                keypress: function (e) {
+                    switch (e.which) {
+                        case 27: // esc
+                        case 38: // up
+                        case 37: // left
+                            self.close();
+                            break;
+                        case 39: // right
+                        case 40: // down
+                            self.open();
+                            break;
+                    }
+                },
+                mouseenter: function () {
+                    if (!button.hasClass('ui-state-disabled')) {
+                        $(this).addClass('ui-state-hover');
+                    }
+                },
+                mouseleave: function () {
+                    $(this).removeClass('ui-state-hover');
+                },
+                focus: function () {
+                    if (!button.hasClass('ui-state-disabled')) {
+                        $(this).addClass('ui-state-focus');
+                    }
+                },
+                blur: function () {
+                    $(this).removeClass('ui-state-focus');
+                }
+            });
+
+            // header links
+            this.header
+                .delegate('a', 'click.multiselect', function (e) {
+                    // close link
+                    if ($(this).hasClass('ui-multiselect-close')) {
+                        self.close();
+
+                        // check all / uncheck all
+                    } else {
+                        self[ $(this).hasClass('ui-multiselect-all') ? 'checkAll' : 'uncheckAll' ]();
+                    }
+
+                    e.preventDefault();
+                });
+
+            // optgroup label toggle support
+            this.menu
+                .delegate('li.ui-multiselect-optgroup-label a', 'click.multiselect', function (e) {
+                    e.preventDefault();
+
+                    var $this = $(this),
+                        $inputs = $this.parent().nextUntil('li.ui-multiselect-optgroup-label').find('input:visible:not(:disabled)'),
+                        nodes = $inputs.get(),
+                        label = $this.parent().text();
+
+                    // trigger event and bail if the return is false
+                    if (self._trigger('beforeoptgrouptoggle', e, { inputs: nodes, label: label }) === false) {
+                        return;
+                    }
+
+                    // toggle inputs
+                    self._toggleChecked(
+                        $inputs.filter('[checked]').length !== $inputs.length,
+                        $inputs
+                    );
+
+                    self._trigger('optgrouptoggle', e, {
+                        inputs: nodes,
+                        label: label,
+                        checked: nodes[0].checked
+                    });
+                })
+                .delegate('label', 'mouseenter.multiselect', function () {
+                    if (!$(this).hasClass('ui-state-disabled')) {
+                        self.labels.removeClass('ui-state-hover');
+                        $(this).addClass('ui-state-hover').find('input').focus();
+                    }
+                })
+                .delegate('label', 'keydown.multiselect', function (e) {
+                    e.preventDefault();
+
+                    switch (e.which) {
+                        case 9: // tab
+                        case 27: // esc
+                            self.close();
+                            break;
+                        case 38: // up
+                        case 40: // down
+                        case 37: // left
+                        case 39: // right
+                            self._traverse(e.which, this);
+                            break;
+                        case 13: // enter
+                            $(this).find('input')[0].click();
+                            break;
+                    }
+                })
+                .delegate('input[type="checkbox"], input[type="radio"]', 'click.multiselect', function (e) {
+                    var $this = $(this),
+                        val = this.value,
+                        checked = this.checked,
+                        tags = self.element.find('option');
+
+                    // bail if this input is disabled or the event is cancelled
+                    if (this.disabled || self._trigger('click', e, { value: val, text: this.title, checked: checked }) === false) {
+                        e.preventDefault();
+                        return;
+                    }
+
+                    // make sure the input has focus. otherwise, the esc key
+                    // won't close the menu after clicking an item.
+                    $this.focus();
+
+                    // toggle aria state
+                    $this.attr('aria-selected', checked);
+
+                    // change state on the original option tags
+                    tags.each(function () {
+                        if (this.value === val) {
+                            this.selected = checked;
+                        } else if (!self.options.multiple) {
+                            this.selected = false;
+                        }
+                    });
+
+                    // some additional single select-specific logic
+                    if (!self.options.multiple) {
+                        self.labels.removeClass('ui-state-active');
+                        $this.closest('label').toggleClass('ui-state-active', checked);
+
+                        // close menu
+                        self.close();
+                    }
+
+                    // fire change on the select box
+                    self.element.trigger("change");
+
+                    // setTimeout is to fix multiselect issue #14 and #47. caused by jQuery issue #3827
+                    // http://bugs.jquery.com/ticket/3827
+                    setTimeout($.proxy(self.update, self), 10);
+                });
+
+            // close each widget when clicking on any other element/anywhere else on the page
+            $(document).bind('mousedown.multiselect', function (e) {
+                if (self._isOpen && !$.contains(self.menu[0], e.target) && !$.contains(self.button[0], e.target) && e.target !== self.button[0]) {
+                    self.close();
+                }
+            });
+
+            // deal with form resets.  the problem here is that buttons aren't
+            // restored to their defaultValue prop on form reset, and the reset
+            // handler fires before the form is actually reset.  delaying it a bit
+            // gives the form inputs time to clear.
+            $(this.element[0].form).bind('reset.multiselect', function () {
+                setTimeout($.proxy(self.refresh, self), 10);
+            });
+        },
+
+        // set button width
+        _setButtonWidth: function () {
+            var width = this.element.outerWidth(),
+                o = this.options;
+
+            if (/\d/.test(o.minWidth) && width < o.minWidth) {
+                width = o.minWidth;
+            }
+
+            // set widths
+            this.button.width(width);
+        },
+
+        // set menu width
+        _setMenuWidth: function () {
+            var m = this.menu,
+                width = this.button.outerWidth() -
+                    parseInt(m.css('padding-left'), 10) -
+                    parseInt(m.css('padding-right'), 10) -
+                    parseInt(m.css('border-right-width'), 10) -
+                    parseInt(m.css('border-left-width'), 10);
+
+            m.width(width || this.button.outerWidth());
+        },
+
+        // move up or down within the menu
+        _traverse: function (which, start) {
+            var $start = $(start),
+                moveToLast = which === 38 || which === 37,
+
+            // select the first li that isn't an optgroup label / disabled
+                $next = $start.parent()[moveToLast ? 'prevAll' : 'nextAll']('li:not(.ui-multiselect-disabled, .ui-multiselect-optgroup-label)')[ moveToLast ? 'last' : 'first']();
+
+            // if at the first/last element
+            if (!$next.length) {
+                var $container = this.menu.find('ul').last();
+
+                // move to the first/last
+                this.menu.find('label')[ moveToLast ? 'last' : 'first' ]().trigger('mouseover');
+
+                // set scroll position
+                $container.scrollTop(moveToLast ? $container.height() : 0);
+
+            } else {
+                $next.find('label').trigger('mouseover');
+            }
+        },
+
+        // This is an internal function to toggle the checked property and
+        // other related attributes of a checkbox.
+        //
+        // The context of this function should be a checkbox; do not proxy it.
+        _toggleState: function (prop, flag) {
+            return function () {
+                if (!this.disabled) {
+                    this[ prop ] = flag;
+                }
+
+                if (flag) {
+                    this.setAttribute('aria-selected', true);
+                } else {
+                    this.removeAttribute('aria-selected');
+                }
+            };
+        },
+
+        _toggleChecked: function (flag, group) {
+            var $inputs = (group && group.length) ?
+                    group :
+                    this.labels.find('input'),
+
+                self = this;
+
+            // toggle state on inputs
+            $inputs.each(this._toggleState('checked', flag));
+
+            // give the first input focus
+            $inputs.eq(0).focus();
+
+            // update button text
+            this.update();
+
+            // gather an array of the values that actually changed
+            var values = $inputs.map(function () {
+                return this.value;
+            }).get();
+
+            // toggle state on original option tags
+            this.element
+                .find('option')
+                .each(function () {
+                    if (!this.disabled && $.inArray(this.value, values) > -1) {
+                        self._toggleState('selected', flag).call(this);
+                    }
+                });
+
+            // trigger the change event on the select
+            if ($inputs.length) {
+                this.element.trigger("change");
+            }
+        },
+
+        _toggleDisabled: function (flag) {
+            this.button
+                .attr({ 'disabled': flag, 'aria-disabled': flag })[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled');
+
+            this.menu
+                .find('input')
+                .attr({ 'disabled': flag, 'aria-disabled': flag })
+                .parent()[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled');
+
+            this.element
+                .attr({ 'disabled': flag, 'aria-disabled': flag });
+        },
+
+        // open the menu
+        open: function (e) {
+            var self = this,
+                button = this.button,
+                menu = this.menu,
+                speed = this.speed,
+                o = this.options;
+
+            // bail if the multiselectopen event returns false, this widget is disabled, or is already open
+            if (this._trigger('beforeopen') === false || button.hasClass('ui-state-disabled') || this._isOpen) {
+                return;
+            }
+
+            var $container = menu.find('ul').last(),
+                effect = o.show,
+                pos = button.offset();
+
+            // figure out opening effects/speeds
+            if ($.isArray(o.show)) {
+                effect = o.show[0];
+                speed = o.show[1] || self.speed;
+            }
+
+            // set the scroll of the checkbox container
+            $container.scrollTop(0).height(o.height);
+
+            // position and show menu
+            if ($.ui.position && !$.isEmptyObject(o.position)) {
+                o.position.of = o.position.of || button;
+
+                menu
+                    .show()
+                    .position(o.position)
+                    .hide()
+                    .show(effect, speed);
+
+                // if position utility is not available...
+            } else {
+                menu.css({
+                    top: pos.top + button.outerHeight(),
+                    left: pos.left
+                }).show(effect, speed);
+            }
+
+            // select the first option
+            // triggering both mouseover and mouseover because 1.4.2+ has a bug where triggering mouseover
+            // will actually trigger mouseenter.  the mouseenter trigger is there for when it's eventually fixed
+            this.labels.eq(0).trigger('mouseover').trigger('mouseenter').find('input').trigger('focus');
+
+            button.addClass('ui-state-active');
+            this._isOpen = true;
+            this._trigger('open');
+        },
+
+        // close the menu
+        close: function () {
+            if (this._trigger('beforeclose') === false) {
+                return;
+            }
+
+            var o = this.options, effect = o.hide, speed = this.speed;
+
+            // figure out opening effects/speeds
+            if ($.isArray(o.hide)) {
+                effect = o.hide[0];
+                speed = o.hide[1] || this.speed;
+            }
+
+            this.menu.hide(effect, speed);
+            this.button.removeClass('ui-state-active').trigger('blur').trigger('mouseleave');
+            this._isOpen = false;
+            this._trigger('close');
+        },
+
+        enable: function () {
+            this._toggleDisabled(false);
+        },
+
+        disable: function () {
+            this._toggleDisabled(true);
+        },
+
+        checkAll: function (e) {
+            this._toggleChecked(true);
+            this._trigger('checkAll');
+        },
+
+        uncheckAll: function () {
+            this._toggleChecked(false);
+            this._trigger('uncheckAll');
+        },
+
+        getChecked: function () {
+            return this.menu.find('input').filter('[checked]');
+        },
+
+        destroy: function () {
+            // remove classes + data
+            $.Widget.prototype.destroy.call(this);
+
+            this.button.remove();
+            this.menu.remove();
+            this.element.show();
+
+            return this;
+        },
+
+        isOpen: function () {
+            return this._isOpen;
+        },
+
+        widget: function () {
+            return this.menu;
+        },
+
+        // react to option changes after initialization
+        _setOption: function (key, value) {
+            var menu = this.menu;
+
+            switch (key) {
+                case 'header':
+                    menu.find('div.ui-multiselect-header')[ value ? 'show' : 'hide' ]();
+                    break;
+                case 'checkAllText':
+                    menu.find('a.ui-multiselect-all span').eq(-1).text(value);
+                    break;
+                case 'uncheckAllText':
+                    menu.find('a.ui-multiselect-none span').eq(-1).text(value);
+                    break;
+                case 'height':
+                    menu.find('ul').last().height(parseInt(value, 10));
+                    break;
+                case 'minWidth':
+                    this.options[ key ] = parseInt(value, 10);
+                    this._setButtonWidth();
+                    this._setMenuWidth();
+                    break;
+                case 'selectedText':
+                case 'selectedList':
+                case 'noneSelectedText':
+                    this.options[key] = value; // these all needs to update immediately for the update() call
+                    this.update();
+                    break;
+                case 'classes':
+                    menu.add(this.button).removeClass(this.options.classes).addClass(value);
+                    break;
+            }
+
+            $.Widget.prototype._setOption.apply(this, arguments);
+        }
+    });
 
 })(jQuery);
diff --git a/media/js/lib/jquery.ui.datepicker-pl.js b/media/js/lib/jquery.ui.datepicker-pl.js
index 972a398..9701980 100644
--- a/media/js/lib/jquery.ui.datepicker-pl.js
+++ b/media/js/lib/jquery.ui.datepicker-pl.js
@@ -1,23 +1,23 @@
 /* Polish initialisation for the jQuery UI date picker plugin. */
 /* Written by Jacek Wysocki (jacek.wysocki@gmail.com). */
-jQuery(function($){
-	$.datepicker.regional['pl'] = {
-		closeText: 'Zamknij',
-		prevText: '&#x3c;Poprzedni',
-		nextText: 'Następny&#x3e;',
-		currentText: 'Dziś',
-		monthNames: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec',
-		'Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
-		monthNamesShort: ['Sty','Lu','Mar','Kw','Maj','Cze',
-		'Lip','Sie','Wrz','Pa','Lis','Gru'],
-		dayNames: ['Niedziela','Poniedzialek','Wtorek','Środa','Czwartek','Piątek','Sobota'],
-		dayNamesShort: ['Nie','Pn','Wt','Śr','Czw','Pt','So'],
-		dayNamesMin: ['N','Pn','Wt','Śr','Cz','Pt','So'],
-		weekHeader: 'Tydz',
-		dateFormat: 'dd.mm.yy',
-		firstDay: 1,
-		isRTL: false,
-		showMonthAfterYear: false,
-		yearSuffix: ''};
-	$.datepicker.setDefaults($.datepicker.regional['pl']);
+jQuery(function ($) {
+    $.datepicker.regional['pl'] = {
+        closeText: 'Zamknij',
+        prevText: '&#x3c;Poprzedni',
+        nextText: 'Następny&#x3e;',
+        currentText: 'Dziś',
+        monthNames: ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec',
+            'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień'],
+        monthNamesShort: ['Sty', 'Lu', 'Mar', 'Kw', 'Maj', 'Cze',
+            'Lip', 'Sie', 'Wrz', 'Pa', 'Lis', 'Gru'],
+        dayNames: ['Niedziela', 'Poniedzialek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota'],
+        dayNamesShort: ['Nie', 'Pn', 'Wt', 'Śr', 'Czw', 'Pt', 'So'],
+        dayNamesMin: ['N', 'Pn', 'Wt', 'Śr', 'Cz', 'Pt', 'So'],
+        weekHeader: 'Tydz',
+        dateFormat: 'dd.mm.yy',
+        firstDay: 1,
+        isRTL: false,
+        showMonthAfterYear: false,
+        yearSuffix: ''};
+    $.datepicker.setDefaults($.datepicker.regional['pl']);
 });
diff --git a/media/js/lib/jquery.ui.selectmenu.js b/media/js/lib/jquery.ui.selectmenu.js
index d878ec5..8a37774 100644
--- a/media/js/lib/jquery.ui.selectmenu.js
+++ b/media/js/lib/jquery.ui.selectmenu.js
@@ -1,4 +1,4 @@
- /*
+/*
  * jQuery UI selectmenu 1.3.0pre version
  *
  * Copyright (c) 2009-2010 filament group, http://filamentgroup.com
@@ -10,862 +10,873 @@
  * https://github.com/fnagel/jquery-ui/wiki/Selectmenu
  */
 
-(function($) {
-
-$.widget("ui.selectmenu", {
-	options: {
-		appendTo: "body",
-		typeAhead: 1000,
-		style: 'dropdown',
-		positionOptions: {
-			my: "left top",
-			at: "left bottom",
-			offset: null
-		},
-		width: null,
-		menuWidth: null,
-		handleWidth: 26,
-		maxHeight: null,
-		icons: null,
-		format: null,
-		escapeHtml: false,
-		bgImage: function() {}
-	},
-
-	_create: function() {
-		var self = this, o = this.options;
-
-		// set a default id value, generate a new random one if not set by developer
-		var selectmenuId = (this.element.attr( 'id' ) || 'ui-selectmenu-' + Math.random().toString( 16 ).slice( 2, 10 )).replace(/(:|\.)/g,'')
-
-		// quick array of button and menu id's
-		this.ids = [ selectmenuId, selectmenuId + '-button', selectmenuId + '-menu' ];
-
-		// define safe mouseup for future toggling
-		this._safemouseup = true;
-		this.isOpen = false;
-
-		// create menu button wrapper
-		this.newelement = $( '<a />', {
-			'class': this.widgetBaseClass + ' ui-widget ui-state-default ui-corner-all',
-			'id' : this.ids[ 1 ],
-			'role': 'button',
-			'href': '#nogo',
-			'tabindex': this.element.attr( 'disabled' ) ? 1 : 0,
-			'aria-haspopup': true,
-			'aria-owns': this.ids[ 2 ]
-		});
-		this.newelementWrap = $( "<span />" )
-			.append( this.newelement )
-			.insertAfter( this.element );
-
-		// transfer tabindex
-		var tabindex = this.element.attr( 'tabindex' );
-		if ( tabindex ) {
-			this.newelement.attr( 'tabindex', tabindex );
-		}
-
-		// save reference to select in data for ease in calling methods
-		this.newelement.data( 'selectelement', this.element );
-
-		// menu icon
-		this.selectmenuIcon = $( '<span class="' + this.widgetBaseClass + '-icon ui-icon"></span>' )
-			.prependTo( this.newelement );
-
-		// append status span to button
-		this.newelement.prepend( '<span class="' + self.widgetBaseClass + '-status" />' );
-
-		// make associated form label trigger focus
-		this.element.bind({
-			'click.selectmenu':  function( event ) {
-				self.newelement.focus();
-				event.preventDefault();
-			}
-		});
-
-		// click toggle for menu visibility
-		this.newelement
-			.bind('mousedown.selectmenu', function(event) {
-				self._toggle(event, true);
-				// make sure a click won't open/close instantly
-				if (o.style == "popup") {
-					self._safemouseup = false;
-					setTimeout(function() { self._safemouseup = true; }, 300);
-				}
-				return false;
-			})
-			.bind('click.selectmenu', function() {
-				return false;
-			})
-			.bind("keydown.selectmenu", function(event) {
-				var ret = false;
-				switch (event.keyCode) {
-					case $.ui.keyCode.ENTER:
-						ret = true;
-						break;
-					case $.ui.keyCode.SPACE:
-						self._toggle(event);
-						break;
-					case $.ui.keyCode.UP:
-						if (event.altKey) {
-							self.open(event);
-						} else {
-							self._moveSelection(-1);
-						}
-						break;
-					case $.ui.keyCode.DOWN:
-						if (event.altKey) {
-							self.open(event);
-						} else {
-							self._moveSelection(1);
-						}
-						break;
-					case $.ui.keyCode.LEFT:
-						self._moveSelection(-1);
-						break;
-					case $.ui.keyCode.RIGHT:
-						self._moveSelection(1);
-						break;
-					case $.ui.keyCode.TAB:
-						ret = true;
-						break;
-					case $.ui.keyCode.PAGE_UP:
-					case $.ui.keyCode.HOME:
-						self.index(0);
-						break;
-					case $.ui.keyCode.PAGE_DOWN:
-					case $.ui.keyCode.END:
-						self.index(self._optionLis.length);
-						break;
-					default:
-						ret = true;
-				}
-				return ret;
-			})
-			.bind('keypress.selectmenu', function(event) {
-				if (event.which > 0) {
-					self._typeAhead(event.which, 'mouseup');
-				}
-				return true;
-			})
-			.bind('mouseover.selectmenu', function() {
-				if (!o.disabled) $(this).addClass('ui-state-hover');
-			})
-			.bind('mouseout.selectmenu', function() {
-				if (!o.disabled) $(this).removeClass('ui-state-hover');
-			})
-			.bind('focus.selectmenu', function() {
-				if (!o.disabled) $(this).addClass('ui-state-focus');
-			})
-			.bind('blur.selectmenu', function() {
-				if (!o.disabled) $(this).removeClass('ui-state-focus');
-			});
-
-		// document click closes menu
-		$(document).bind("mousedown.selectmenu-" + this.ids[0], function(event) {
-			if ( self.isOpen ) {
-				self.close( event );
-			}
-		});
-
-		// change event on original selectmenu
-		this.element
-			.bind("click.selectmenu", function() {
-				self._refreshValue();
-			})
-			// FIXME: newelement can be null under unclear circumstances in IE8
-			// TODO not sure if this is still a problem (fnagel 20.03.11)
-			.bind("focus.selectmenu", function() {
-				if (self.newelement) {
-					self.newelement[0].focus();
-				}
-			});
-
-		// set width when not set via options
-		if (!o.width) {
-			o.width = this.element.outerWidth();
-		}
-		// set menu button width
-		this.newelement.width(o.width);
-
-		// hide original selectmenu element
-		this.element.hide();
-
-		// create menu portion, append to body
-		this.list = $( '<ul />', {
-			'class': 'ui-widget ui-widget-content',
-			'aria-hidden': true,
-			'role': 'listbox',
-			'aria-labelledby': this.ids[1],
-			'id': this.ids[2]
-		});
-		this.listWrap = $( "<div />", {
-			'class': self.widgetBaseClass + '-menu'
-		}).append( this.list ).appendTo( o.appendTo );
-
-		// transfer menu click to menu button
-		this.list
-			.bind("keydown.selectmenu", function(event) {
-				var ret = false;
-				switch (event.keyCode) {
-					case $.ui.keyCode.UP:
-						if (event.altKey) {
-							self.close(event, true);
-						} else {
-							self._moveFocus(-1);
-						}
-						break;
-					case $.ui.keyCode.DOWN:
-						if (event.altKey) {
-							self.close(event, true);
-						} else {
-							self._moveFocus(1);
-						}
-						break;
-					case $.ui.keyCode.LEFT:
-						self._moveFocus(-1);
-						break;
-					case $.ui.keyCode.RIGHT:
-						self._moveFocus(1);
-						break;
-					case $.ui.keyCode.HOME:
-						self._moveFocus(':first');
-						break;
-					case $.ui.keyCode.PAGE_UP:
-						self._scrollPage('up');
-						break;
-					case $.ui.keyCode.PAGE_DOWN:
-						self._scrollPage('down');
-						break;
-					case $.ui.keyCode.END:
-						self._moveFocus(':last');
-						break;
-					case $.ui.keyCode.ENTER:
-					case $.ui.keyCode.SPACE:
-						self.close(event, true);
-						$(event.target).parents('li:eq(0)').trigger('mouseup');
-						break;
-					case $.ui.keyCode.TAB:
-						ret = true;
-						self.close(event, true);
-						$(event.target).parents('li:eq(0)').trigger('mouseup');
-						break;
-					case $.ui.keyCode.ESCAPE:
-						self.close(event, true);
-						break;
-					default:
-						ret = true;
-				}
-				return ret;
-			})
-			.bind('keypress.selectmenu', function(event) {
-				if (event.which > 0) {
-					self._typeAhead(event.which, 'focus');
-				}
-				return true;
-			})
-			// this allows for using the scrollbar in an overflowed list
-			.bind( 'mousedown.selectmenu mouseup.selectmenu', function() { return false; });
-
-		// needed when window is resized
-		$(window).bind( "resize.selectmenu-" + this.ids[0], $.proxy( self.close, this ) );
-	},
-
-	_init: function() {
-		var self = this, o = this.options;
-
-		// serialize selectmenu element options
-		var selectOptionData = [];
-		this.element.find('option').each(function() {
-			var opt = $(this);
-			selectOptionData.push({
-				value: opt.attr('value'),
-				text: self._formatText(opt.text()),
-				selected: opt.attr('selected'),
-				disabled: opt.attr('disabled'),
-				classes: opt.attr('class'),
-				typeahead: opt.attr('typeahead'),
-				parentOptGroup: opt.parent('optgroup'),
-				bgImage: o.bgImage.call(opt)
-			});
-		});
-
-		// active state class is only used in popup style
-		var activeClass = (self.options.style == "popup") ? " ui-state-active" : "";
-
-		// empty list so we can refresh the selectmenu via selectmenu()
-		this.list.html("");
-
-		// write li's
-		if (selectOptionData.length) {
-			for (var i = 0; i < selectOptionData.length; i++) {
-				var thisLiAttr = { role : 'presentation' };
-				if ( selectOptionData[ i ].disabled ) {
-					thisLiAttr[ 'class' ] = this.namespace + '-state-disabled';
-				}
-				var thisAAttr = {
-					html: selectOptionData[i].text || '&nbsp;',
-					href : '#nogo',
-					tabindex : -1,
-					role : 'option',
-					'aria-selected' : false
-				};
-				if ( selectOptionData[ i ].disabled ) {
-					thisAAttr[ 'aria-disabled' ] = selectOptionData[ i ].disabled;
-				}
-				if ( selectOptionData[ i ].typeahead ) {
-					thisAAttr[ 'typeahead' ] = selectOptionData[ i ].typeahead;
-				}
-				var thisA = $('<a/>', thisAAttr);
-				var thisLi = $('<li/>', thisLiAttr)
-					.append(thisA)
-					.data('index', i)
-					.addClass(selectOptionData[i].classes)
-					.data('optionClasses', selectOptionData[i].classes || '')
-					.bind("mouseup.selectmenu", function(event) {
-						if (self._safemouseup && !self._disabled(event.currentTarget) && !self._disabled($( event.currentTarget ).parents( "ul>li." + self.widgetBaseClass + "-group " )) ) {
-							var changed = $(this).data('index') != self._selectedIndex();
-							self.index($(this).data('index'));
-							self.select(event);
-							if (changed) {
-								self.change(event);
-							}
-							self.close(event, true);
-						}
-						return false;
-					})
-					.bind("click.selectmenu", function() {
-						return false;
-					})
-					.bind('mouseover.selectmenu focus.selectmenu', function(e) {
-						// no hover if diabled
-						if (!$(e.currentTarget).hasClass(self.namespace + '-state-disabled') && !$(e.currentTarget).parent("ul").parent("li").hasClass(self.namespace + '-state-disabled')) {
-							self._selectedOptionLi().addClass(activeClass);
-							self._focusedOptionLi().removeClass(self.widgetBaseClass + '-item-focus ui-state-hover');
-							$(this).removeClass('ui-state-active').addClass(self.widgetBaseClass + '-item-focus ui-state-hover');
-						}
-					})
-					.bind('mouseout.selectmenu blur.selectmenu', function() {
-						if ($(this).is(self._selectedOptionLi().selector)) {
-							$(this).addClass(activeClass);
-						}
-						$(this).removeClass(self.widgetBaseClass + '-item-focus ui-state-hover');
-					});
-
-				// optgroup or not...
-				if ( selectOptionData[i].parentOptGroup.length ) {
-					var optGroupName = self.widgetBaseClass + '-group-' + this.element.find( 'optgroup' ).index( selectOptionData[i].parentOptGroup );
-					if (this.list.find( 'li.' + optGroupName ).length ) {
-						this.list.find( 'li.' + optGroupName + ':last ul' ).append( thisLi );
-					} else {
-						$(' <li role="presentation" class="' + self.widgetBaseClass + '-group ' + optGroupName + (selectOptionData[i].parentOptGroup.attr("disabled") ? ' ' + this.namespace + '-state-disabled" aria-disabled="true"' : '"' ) + '><span class="' + self.widgetBaseClass + '-group-label">' + selectOptionData[i].parentOptGroup.attr('label') + '</span><ul></ul></li> ')
-							.appendTo( this.list )
-							.find( 'ul' )
-							.append( thisLi );
-					}
-				} else {
-					thisLi.appendTo(this.list);
-				}
-
-				// append icon if option is specified
-				if (o.icons) {
-					for (var j in o.icons) {
-						if (thisLi.is(o.icons[j].find)) {
-							thisLi
-								.data('optionClasses', selectOptionData[i].classes + ' ' + self.widgetBaseClass + '-hasIcon')
-								.addClass(self.widgetBaseClass + '-hasIcon');
-							var iconClass = o.icons[j].icon || "";
-							thisLi
-								.find('a:eq(0)')
-								.prepend('<span class="' + self.widgetBaseClass + '-item-icon ui-icon ' + iconClass + '"></span>');
-							if (selectOptionData[i].bgImage) {
-								thisLi.find('span').css('background-image', selectOptionData[i].bgImage);
-							}
-						}
-					}
-				}
-			}
-		} else {
-			$('<li role="presentation"><a href="#nogo" tabindex="-1" role="option"></a></li>').appendTo(this.list);
-		}
-		// we need to set and unset the CSS classes for dropdown and popup style
-		var isDropDown = ( o.style == 'dropdown' );
-		this.newelement
-			.toggleClass( self.widgetBaseClass + '-dropdown', isDropDown )
-			.toggleClass( self.widgetBaseClass + '-popup', !isDropDown );
-		this.list
-			.toggleClass( self.widgetBaseClass + '-menu-dropdown ui-corner-bottom', isDropDown )
-			.toggleClass( self.widgetBaseClass + '-menu-popup ui-corner-all', !isDropDown )
-			// add corners to top and bottom menu items
-			.find( 'li:first' )
-			.toggleClass( 'ui-corner-top', !isDropDown )
-			.end().find( 'li:last' )
-			.addClass( 'ui-corner-bottom' );
-		this.selectmenuIcon
-			.toggleClass( 'ui-icon-triangle-1-s', isDropDown )
-			.toggleClass( 'ui-icon-triangle-2-n-s', !isDropDown );
-
-		// set menu width to either menuWidth option value, width option value, or select width
-		if ( o.style == 'dropdown' ) {
-			this.list.width( o.menuWidth ? o.menuWidth : o.width );
-		} else {
-			this.list.width( o.menuWidth ? o.menuWidth : o.width - o.handleWidth );
-		}
-
-		// reset height to auto
-		this.list.css( 'height', 'auto' );
-		var listH = this.listWrap.height();
-		var winH = $( window ).height();
-		// calculate default max height
-		var maxH = o.maxHeight ? Math.min( o.maxHeight, winH ) : winH / 3;
-		if ( listH > maxH ) this.list.height( maxH );
-
-		// save reference to actionable li's (not group label li's)
-		this._optionLis = this.list.find( 'li:not(.' + self.widgetBaseClass + '-group)' );
-
-		// transfer disabled state
-		if ( this.element.attr( 'disabled' ) ) {
-			this.disable();
-		} else {
-			this.enable();
-		}
-
-		// update value
-		this.index( this._selectedIndex() );
-
-		// set selected item so movefocus has intial state
-		this._selectedOptionLi().addClass(this.widgetBaseClass + '-item-focus');
-
-		// needed when selectmenu is placed at the very bottom / top of the page
-		clearTimeout(this.refreshTimeout);
-		this.refreshTimeout = window.setTimeout(function () {
-			self._refreshPosition();
-		}, 200);
-	},
-
-	destroy: function() {
-		this.element.removeData( this.widgetName )
-			.removeClass( this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled' )
-			.removeAttr( 'aria-disabled' )
-			.unbind( ".selectmenu" );
-
-		$( window ).unbind( ".selectmenu-" + this.ids[0] );
-		$( document ).unbind( ".selectmenu-" + this.ids[0] );
-
-		this.newelementWrap.remove();
-		this.listWrap.remove();
-
-		// unbind click event and show original select
-		this.element
-			.unbind(".selectmenu")
-			.show();
-
-		// call widget destroy function
-		$.Widget.prototype.destroy.apply(this, arguments);
-	},
-
-	_typeAhead: function( code, eventType ) {
-		var self = this,
-			c = String.fromCharCode(code).toLowerCase(),
-			matchee = null,
-			nextIndex = null;
-
-		// Clear any previous timer if present
-		if ( self._typeAhead_timer ) {
-			window.clearTimeout( self._typeAhead_timer );
-			self._typeAhead_timer = undefined;
-		}
-
-		// Store the character typed
-		self._typeAhead_chars = (self._typeAhead_chars === undefined ? "" : self._typeAhead_chars).concat(c);
-
-		// Detect if we are in cyciling mode or direct selection mode
-		if ( self._typeAhead_chars.length < 2 ||
-		     (self._typeAhead_chars.substr(-2, 1) === c && self._typeAhead_cycling) ) {
-			self._typeAhead_cycling = true;
-
-			// Match only the first character and loop
-			matchee = c;
-		}
-		else {
-			// We won't be cycling anymore until the timer expires
-			self._typeAhead_cycling = false;
-
-			// Match all the characters typed
-			matchee = self._typeAhead_chars;
-		}
-
-		// We need to determine the currently active index, but it depends on
-		// the used context: if it's in the element, we want the actual
-		// selected index, if it's in the menu, just the focused one
-		// I copied this code from _moveSelection() and _moveFocus()
-		// respectively --thg2k
-		var selectedIndex = (eventType !== 'focus' ?
-			this._selectedOptionLi().data('index') :
-			this._focusedOptionLi().data('index')) || 0;
-
-		for (var i = 0; i < this._optionLis.length; i++) {
-			var thisText = this._optionLis.eq(i).text().substr(0, matchee.length).toLowerCase();
-
-			if ( thisText === matchee ) {
-				if ( self._typeAhead_cycling ) {
-					if ( nextIndex === null )
-						nextIndex = i;
-
-					if ( i > selectedIndex ) {
-						nextIndex = i;
-						break;
-					}
-				} else {
-					nextIndex = i;
-				}
-			}
-		}
-
-		if ( nextIndex !== null ) {
-			// Why using trigger() instead of a direct method to select the
-			// index? Because we don't what is the exact action to do, it
-			// depends if the user is typing on the element or on the popped
-			// up menu
-			this._optionLis.eq(nextIndex).find("a").trigger( eventType );
-		}
-
-		self._typeAhead_timer = window.setTimeout(function() {
-			self._typeAhead_timer = undefined;
-			self._typeAhead_chars = undefined;
-			self._typeAhead_cycling = undefined;
-		}, self.options.typeAhead);
-	},
-
-	// returns some usefull information, called by callbacks only
-	_uiHash: function() {
-		var index = this.index();
-		return {
-			index: index,
-			option: $("option", this.element).get(index),
-			value: this.element[0].value
-		};
-	},
-
-	open: function(event) {
-		var self = this, o = this.options;
-		if ( self.newelement.attr("aria-disabled") != 'true' ) {
-			self._closeOthers(event);
-			self.newelement.addClass('ui-state-active');
-
-			self.list.attr('aria-hidden', false);
-			self.listWrap.addClass( self.widgetBaseClass + '-open' );
-
-			var selected = this._selectedOptionLi();
-			if ( o.style == "dropdown" ) {
-				self.newelement.removeClass('ui-corner-all').addClass('ui-corner-top');
-			} else {
-				// center overflow and avoid flickering
-				this.list
-					.css("left", -5000)
-					.scrollTop( this.list.scrollTop() + selected.position().top - this.list.outerHeight()/2 + selected.outerHeight()/2 )
-					.css("left","auto");
-			}
-
-			self._refreshPosition();
-
-			var link = selected.find("a");
-			if (link.length) link[0].focus();
-
-			self.isOpen = true;
-			self._trigger("open", event, self._uiHash());
-		}
-	},
-
-	close: function(event, retainFocus) {
-		if ( this.newelement.is('.ui-state-active') ) {
-			this.newelement
-				.removeClass('ui-state-active');
-			this.listWrap.removeClass(this.widgetBaseClass + '-open');
-			this.list.attr('aria-hidden', true);
-			if ( this.options.style == "dropdown" ) {
-				this.newelement.removeClass('ui-corner-top').addClass('ui-corner-all');
-			}
-			if ( retainFocus ) {
-				this.newelement.focus();
-			}
-			this.isOpen = false;
-			this._trigger("close", event, this._uiHash());
-		}
-	},
-
-	change: function(event) {
-		this.element.trigger("change");
-		this._trigger("change", event, this._uiHash());
-	},
-
-	select: function(event) {
-		if (this._disabled(event.currentTarget)) { return false; }
-		this._trigger("select", event, this._uiHash());
-	},
-
-	widget: function() {
-		return this.listWrap.add( this.newelementWrap );
-	},
-
-	_closeOthers: function(event) {
-		$('.' + this.widgetBaseClass + '.ui-state-active').not(this.newelement).each(function() {
-			$(this).data('selectelement').selectmenu('close', event);
-		});
-		$('.' + this.widgetBaseClass + '.ui-state-hover').trigger('mouseout');
-	},
-
-	_toggle: function(event, retainFocus) {
-		if ( this.isOpen ) {
-			this.close(event, retainFocus);
-		} else {
-			this.open(event);
-		}
-	},
-
-	_formatText: function(text) {
-		if (this.options.format) {
-			text = this.options.format(text);
-		} else if (this.options.escapeHtml) {
-			text = $('<div />').text(text).html();
-		}
-		return text;
-	},
-
-	_selectedIndex: function() {
-		return this.element[0].selectedIndex;
-	},
-
-	_selectedOptionLi: function() {
-		return this._optionLis.eq(this._selectedIndex());
-	},
-
-	_focusedOptionLi: function() {
-		return this.list.find('.' + this.widgetBaseClass + '-item-focus');
-	},
-
-	_moveSelection: function(amt, recIndex) {
-		// do nothing if disabled
-		if (!this.options.disabled) {
-			var currIndex = parseInt(this._selectedOptionLi().data('index') || 0, 10);
-			var newIndex = currIndex + amt;
-			// do not loop when using up key
-
-			if (newIndex < 0) {
-				newIndex = 0;
-			}
-			if (newIndex > this._optionLis.size() - 1) {
-				newIndex = this._optionLis.size() - 1;
-			}
-			// Occurs when a full loop has been made
-			if (newIndex === recIndex) { return false; }
-
-			if (this._optionLis.eq(newIndex).hasClass( this.namespace + '-state-disabled' )) {
-				// if option at newIndex is disabled, call _moveFocus, incrementing amt by one
-				(amt > 0) ? ++amt : --amt;
-				this._moveSelection(amt, newIndex);
-			} else {
-				this._optionLis.eq(newIndex).trigger('mouseover').trigger('mouseup');
-			}
-		}
-	},
-
-	_moveFocus: function(amt, recIndex) {
-		if (!isNaN(amt)) {
-			var currIndex = parseInt(this._focusedOptionLi().data('index') || 0, 10);
-			var newIndex = currIndex + amt;
-		} else {
-			var newIndex = parseInt(this._optionLis.filter(amt).data('index'), 10);
-		}
-
-		if (newIndex < 0) {
-			newIndex = 0;
-		}
-		if (newIndex > this._optionLis.size() - 1) {
-			newIndex = this._optionLis.size() - 1;
-		}
-
-		//Occurs when a full loop has been made
-		if (newIndex === recIndex) { return false; }
-
-		var activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000);
-
-		this._focusedOptionLi().find('a:eq(0)').attr('id', '');
-
-		if (this._optionLis.eq(newIndex).hasClass( this.namespace + '-state-disabled' )) {
-			// if option at newIndex is disabled, call _moveFocus, incrementing amt by one
-			(amt > 0) ? ++amt : --amt;
-			this._moveFocus(amt, newIndex);
-		} else {
-			this._optionLis.eq(newIndex).find('a:eq(0)').attr('id',activeID).focus();
-		}
-
-		this.list.attr('aria-activedescendant', activeID);
-	},
-
-	_scrollPage: function(direction) {
-		var numPerPage = Math.floor(this.list.outerHeight() / this._optionLis.first().outerHeight());
-		numPerPage = (direction == 'up' ? -numPerPage : numPerPage);
-		this._moveFocus(numPerPage);
-	},
-
-	_setOption: function(key, value) {
-		this.options[key] = value;
-		// set
-		if (key == 'disabled') {
-			if (value) this.close();
-			this.element
-				.add(this.newelement)
-				.add(this.list)[value ? 'addClass' : 'removeClass'](
-					this.widgetBaseClass + '-disabled' + ' ' +
-					this.namespace + '-state-disabled')
-				.attr("aria-disabled", value);
-		}
-	},
-
-	disable: function(index, type){
-			// if options is not provided, call the parents disable function
-			if ( typeof( index ) == 'undefined' ) {
-				this._setOption( 'disabled', true );
-			} else {
-				if ( type == "optgroup" ) {
-					this._disableOptgroup(index);
-				} else {
-					this._disableOption(index);
-				}
-			}
-	},
-
-	enable: function(index, type) {
-			// if options is not provided, call the parents enable function
-			if ( typeof( index ) == 'undefined' ) {
-				this._setOption('disabled', false);
-			} else {
-				if ( type == "optgroup" ) {
-					this._enableOptgroup(index);
-				} else {
-					this._enableOption(index);
-				}
-			}
-	},
-
-	_disabled: function(elem) {
-			return $(elem).hasClass( this.namespace + '-state-disabled' );
-	},
-
-
-	_disableOption: function(index) {
-			var optionElem = this._optionLis.eq(index);
-			if (optionElem) {
-				optionElem.addClass(this.namespace + '-state-disabled')
-					.find("a").attr("aria-disabled", true);
-				this.element.find("option").eq(index).attr("disabled", "disabled");
-			}
-	},
-
-	_enableOption: function(index) {
-			var optionElem = this._optionLis.eq(index);
-			if (optionElem) {
-				optionElem.removeClass( this.namespace + '-state-disabled' )
-					.find("a").attr("aria-disabled", false);
-				this.element.find("option").eq(index).removeAttr("disabled");
-			}
-	},
-
-	_disableOptgroup: function(index) {
-			var optGroupElem = this.list.find( 'li.' + this.widgetBaseClass + '-group-' + index );
-			if (optGroupElem) {
-				optGroupElem.addClass(this.namespace + '-state-disabled')
-					.attr("aria-disabled", true);
-				this.element.find("optgroup").eq(index).attr("disabled", "disabled");
-			}
-	},
-
-	_enableOptgroup: function(index) {
-			var optGroupElem = this.list.find( 'li.' + this.widgetBaseClass + '-group-' + index );
-			if (optGroupElem) {
-				optGroupElem.removeClass(this.namespace + '-state-disabled')
-					.attr("aria-disabled", false);
-				this.element.find("optgroup").eq(index).removeAttr("disabled");
-			}
-	},
-
-	index: function(newValue) {
-		if (arguments.length) {
-			if (!this._disabled($(this._optionLis[newValue]))) {
-				this.element[0].selectedIndex = newValue;
-				this._refreshValue();
-			} else {
-				return false;
-			}
-		} else {
-			return this._selectedIndex();
-		}
-	},
-
-	value: function(newValue) {
-		if (arguments.length) {
-			this.element[0].value = newValue;
-			this._refreshValue();
-		} else {
-			return this.element[0].value;
-		}
-	},
-
-	_refreshValue: function() {
-		var activeClass = (this.options.style == "popup") ? " ui-state-active" : "";
-		var activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000);
-		// deselect previous
-		this.list
-			.find('.' + this.widgetBaseClass + '-item-selected')
-			.removeClass(this.widgetBaseClass + "-item-selected" + activeClass)
-			.find('a')
-			.attr('aria-selected', 'false')
-			.attr('id', '');
-		// select new
-		this._selectedOptionLi()
-			.addClass(this.widgetBaseClass + "-item-selected" + activeClass)
-			.find('a')
-			.attr('aria-selected', 'true')
-			.attr('id', activeID);
-
-		// toggle any class brought in from option
-		var currentOptionClasses = (this.newelement.data('optionClasses') ? this.newelement.data('optionClasses') : "");
-		var newOptionClasses = (this._selectedOptionLi().data('optionClasses') ? this._selectedOptionLi().data('optionClasses') : "");
-		this.newelement
-			.removeClass(currentOptionClasses)
-			.data('optionClasses', newOptionClasses)
-			.addClass( newOptionClasses )
-			.find('.' + this.widgetBaseClass + '-status')
-			.html(
-				this._selectedOptionLi()
-					.find('a:eq(0)')
-					.html()
-			);
-
-		this.list.attr('aria-activedescendant', activeID);
-	},
-
-	_refreshPosition: function() {
-		var o = this.options;
-
-		// if its a pop-up we need to calculate the position of the selected li
-		if ( o.style == "popup" && !o.positionOptions.offset ) {
-			var selected = this._selectedOptionLi();
-			var _offset = "0 " + ( this.list.offset().top  - selected.offset().top - ( this.newelement.outerHeight() + selected.outerHeight() ) / 2);
-		}
-		this.listWrap
-			.removeAttr('style')
-			.zIndex( this.element.zIndex() + 1 )
-			.position({
-				// set options for position plugin
-				of: o.positionOptions.of || this.newelement,
-				my: o.positionOptions.my,
-				at: o.positionOptions.at,
-				offset: o.positionOptions.offset || _offset,
-				collision: o.positionOptions.collision || o.style == "popup" ? 'fit' :'flip'
-			});
-	}
-});
+(function ($) {
+
+    $.widget("ui.selectmenu", {
+        options: {
+            appendTo: "body",
+            typeAhead: 1000,
+            style: 'dropdown',
+            positionOptions: {
+                my: "left top",
+                at: "left bottom",
+                offset: null
+            },
+            width: null,
+            menuWidth: null,
+            handleWidth: 26,
+            maxHeight: null,
+            icons: null,
+            format: null,
+            escapeHtml: false,
+            bgImage: function () {
+            }
+        },
+
+        _create: function () {
+            var self = this, o = this.options;
+
+            // set a default id value, generate a new random one if not set by developer
+            var selectmenuId = (this.element.attr('id') || 'ui-selectmenu-' + Math.random().toString(16).slice(2, 10)).replace(/(:|\.)/g, '')
+
+            // quick array of button and menu id's
+            this.ids = [ selectmenuId, selectmenuId + '-button', selectmenuId + '-menu' ];
+
+            // define safe mouseup for future toggling
+            this._safemouseup = true;
+            this.isOpen = false;
+
+            // create menu button wrapper
+            this.newelement = $('<a />', {
+                'class': this.widgetBaseClass + ' ui-widget ui-state-default ui-corner-all',
+                'id': this.ids[ 1 ],
+                'role': 'button',
+                'href': '#nogo',
+                'tabindex': this.element.attr('disabled') ? 1 : 0,
+                'aria-haspopup': true,
+                'aria-owns': this.ids[ 2 ]
+            });
+            this.newelementWrap = $("<span />")
+                .append(this.newelement)
+                .insertAfter(this.element);
+
+            // transfer tabindex
+            var tabindex = this.element.attr('tabindex');
+            if (tabindex) {
+                this.newelement.attr('tabindex', tabindex);
+            }
+
+            // save reference to select in data for ease in calling methods
+            this.newelement.data('selectelement', this.element);
+
+            // menu icon
+            this.selectmenuIcon = $('<span class="' + this.widgetBaseClass + '-icon ui-icon"></span>')
+                .prependTo(this.newelement);
+
+            // append status span to button
+            this.newelement.prepend('<span class="' + self.widgetBaseClass + '-status" />');
+
+            // make associated form label trigger focus
+            this.element.bind({
+                'click.selectmenu': function (event) {
+                    self.newelement.focus();
+                    event.preventDefault();
+                }
+            });
+
+            // click toggle for menu visibility
+            this.newelement
+                .bind('mousedown.selectmenu', function (event) {
+                    self._toggle(event, true);
+                    // make sure a click won't open/close instantly
+                    if (o.style == "popup") {
+                        self._safemouseup = false;
+                        setTimeout(function () {
+                            self._safemouseup = true;
+                        }, 300);
+                    }
+                    return false;
+                })
+                .bind('click.selectmenu', function () {
+                    return false;
+                })
+                .bind("keydown.selectmenu", function (event) {
+                    var ret = false;
+                    switch (event.keyCode) {
+                        case $.ui.keyCode.ENTER:
+                            ret = true;
+                            break;
+                        case $.ui.keyCode.SPACE:
+                            self._toggle(event);
+                            break;
+                        case $.ui.keyCode.UP:
+                            if (event.altKey) {
+                                self.open(event);
+                            } else {
+                                self._moveSelection(-1);
+                            }
+                            break;
+                        case $.ui.keyCode.DOWN:
+                            if (event.altKey) {
+                                self.open(event);
+                            } else {
+                                self._moveSelection(1);
+                            }
+                            break;
+                        case $.ui.keyCode.LEFT:
+                            self._moveSelection(-1);
+                            break;
+                        case $.ui.keyCode.RIGHT:
+                            self._moveSelection(1);
+                            break;
+                        case $.ui.keyCode.TAB:
+                            ret = true;
+                            break;
+                        case $.ui.keyCode.PAGE_UP:
+                        case $.ui.keyCode.HOME:
+                            self.index(0);
+                            break;
+                        case $.ui.keyCode.PAGE_DOWN:
+                        case $.ui.keyCode.END:
+                            self.index(self._optionLis.length);
+                            break;
+                        default:
+                            ret = true;
+                    }
+                    return ret;
+                })
+                .bind('keypress.selectmenu', function (event) {
+                    if (event.which > 0) {
+                        self._typeAhead(event.which, 'mouseup');
+                    }
+                    return true;
+                })
+                .bind('mouseover.selectmenu', function () {
+                    if (!o.disabled) $(this).addClass('ui-state-hover');
+                })
+                .bind('mouseout.selectmenu', function () {
+                    if (!o.disabled) $(this).removeClass('ui-state-hover');
+                })
+                .bind('focus.selectmenu', function () {
+                    if (!o.disabled) $(this).addClass('ui-state-focus');
+                })
+                .bind('blur.selectmenu', function () {
+                    if (!o.disabled) $(this).removeClass('ui-state-focus');
+                });
+
+            // document click closes menu
+            $(document).bind("mousedown.selectmenu-" + this.ids[0], function (event) {
+                if (self.isOpen) {
+                    self.close(event);
+                }
+            });
+
+            // change event on original selectmenu
+            this.element
+                .bind("click.selectmenu", function () {
+                    self._refreshValue();
+                })
+                // FIXME: newelement can be null under unclear circumstances in IE8
+                // TODO not sure if this is still a problem (fnagel 20.03.11)
+                .bind("focus.selectmenu", function () {
+                    if (self.newelement) {
+                        self.newelement[0].focus();
+                    }
+                });
+
+            // set width when not set via options
+            if (!o.width) {
+                o.width = this.element.outerWidth();
+            }
+            // set menu button width
+            this.newelement.width(o.width);
+
+            // hide original selectmenu element
+            this.element.hide();
+
+            // create menu portion, append to body
+            this.list = $('<ul />', {
+                'class': 'ui-widget ui-widget-content',
+                'aria-hidden': true,
+                'role': 'listbox',
+                'aria-labelledby': this.ids[1],
+                'id': this.ids[2]
+            });
+            this.listWrap = $("<div />", {
+                'class': self.widgetBaseClass + '-menu'
+            }).append(this.list).appendTo(o.appendTo);
+
+            // transfer menu click to menu button
+            this.list
+                .bind("keydown.selectmenu", function (event) {
+                    var ret = false;
+                    switch (event.keyCode) {
+                        case $.ui.keyCode.UP:
+                            if (event.altKey) {
+                                self.close(event, true);
+                            } else {
+                                self._moveFocus(-1);
+                            }
+                            break;
+                        case $.ui.keyCode.DOWN:
+                            if (event.altKey) {
+                                self.close(event, true);
+                            } else {
+                                self._moveFocus(1);
+                            }
+                            break;
+                        case $.ui.keyCode.LEFT:
+                            self._moveFocus(-1);
+                            break;
+                        case $.ui.keyCode.RIGHT:
+                            self._moveFocus(1);
+                            break;
+                        case $.ui.keyCode.HOME:
+                            self._moveFocus(':first');
+                            break;
+                        case $.ui.keyCode.PAGE_UP:
+                            self._scrollPage('up');
+                            break;
+                        case $.ui.keyCode.PAGE_DOWN:
+                            self._scrollPage('down');
+                            break;
+                        case $.ui.keyCode.END:
+                            self._moveFocus(':last');
+                            break;
+                        case $.ui.keyCode.ENTER:
+                        case $.ui.keyCode.SPACE:
+                            self.close(event, true);
+                            $(event.target).parents('li:eq(0)').trigger('mouseup');
+                            break;
+                        case $.ui.keyCode.TAB:
+                            ret = true;
+                            self.close(event, true);
+                            $(event.target).parents('li:eq(0)').trigger('mouseup');
+                            break;
+                        case $.ui.keyCode.ESCAPE:
+                            self.close(event, true);
+                            break;
+                        default:
+                            ret = true;
+                    }
+                    return ret;
+                })
+                .bind('keypress.selectmenu', function (event) {
+                    if (event.which > 0) {
+                        self._typeAhead(event.which, 'focus');
+                    }
+                    return true;
+                })
+                // this allows for using the scrollbar in an overflowed list
+                .bind('mousedown.selectmenu mouseup.selectmenu', function () {
+                    return false;
+                });
+
+            // needed when window is resized
+            $(window).bind("resize.selectmenu-" + this.ids[0], $.proxy(self.close, this));
+        },
+
+        _init: function () {
+            var self = this, o = this.options;
+
+            // serialize selectmenu element options
+            var selectOptionData = [];
+            this.element.find('option').each(function () {
+                var opt = $(this);
+                selectOptionData.push({
+                    value: opt.attr('value'),
+                    text: self._formatText(opt.text()),
+                    selected: opt.attr('selected'),
+                    disabled: opt.attr('disabled'),
+                    classes: opt.attr('class'),
+                    typeahead: opt.attr('typeahead'),
+                    parentOptGroup: opt.parent('optgroup'),
+                    bgImage: o.bgImage.call(opt)
+                });
+            });
+
+            // active state class is only used in popup style
+            var activeClass = (self.options.style == "popup") ? " ui-state-active" : "";
+
+            // empty list so we can refresh the selectmenu via selectmenu()
+            this.list.html("");
+
+            // write li's
+            if (selectOptionData.length) {
+                for (var i = 0; i < selectOptionData.length; i++) {
+                    var thisLiAttr = { role: 'presentation' };
+                    if (selectOptionData[ i ].disabled) {
+                        thisLiAttr[ 'class' ] = this.namespace + '-state-disabled';
+                    }
+                    var thisAAttr = {
+                        html: selectOptionData[i].text || '&nbsp;',
+                        href: '#nogo',
+                        tabindex: -1,
+                        role: 'option',
+                        'aria-selected': false
+                    };
+                    if (selectOptionData[ i ].disabled) {
+                        thisAAttr[ 'aria-disabled' ] = selectOptionData[ i ].disabled;
+                    }
+                    if (selectOptionData[ i ].typeahead) {
+                        thisAAttr[ 'typeahead' ] = selectOptionData[ i ].typeahead;
+                    }
+                    var thisA = $('<a/>', thisAAttr);
+                    var thisLi = $('<li/>', thisLiAttr)
+                        .append(thisA)
+                        .data('index', i)
+                        .addClass(selectOptionData[i].classes)
+                        .data('optionClasses', selectOptionData[i].classes || '')
+                        .bind("mouseup.selectmenu", function (event) {
+                            if (self._safemouseup && !self._disabled(event.currentTarget) && !self._disabled($(event.currentTarget).parents("ul>li." + self.widgetBaseClass + "-group "))) {
+                                var changed = $(this).data('index') != self._selectedIndex();
+                                self.index($(this).data('index'));
+                                self.select(event);
+                                if (changed) {
+                                    self.change(event);
+                                }
+                                self.close(event, true);
+                            }
+                            return false;
+                        })
+                        .bind("click.selectmenu", function () {
+                            return false;
+                        })
+                        .bind('mouseover.selectmenu focus.selectmenu', function (e) {
+                            // no hover if diabled
+                            if (!$(e.currentTarget).hasClass(self.namespace + '-state-disabled') && !$(e.currentTarget).parent("ul").parent("li").hasClass(self.namespace + '-state-disabled')) {
+                                self._selectedOptionLi().addClass(activeClass);
+                                self._focusedOptionLi().removeClass(self.widgetBaseClass + '-item-focus ui-state-hover');
+                                $(this).removeClass('ui-state-active').addClass(self.widgetBaseClass + '-item-focus ui-state-hover');
+                            }
+                        })
+                        .bind('mouseout.selectmenu blur.selectmenu', function () {
+                            if ($(this).is(self._selectedOptionLi().selector)) {
+                                $(this).addClass(activeClass);
+                            }
+                            $(this).removeClass(self.widgetBaseClass + '-item-focus ui-state-hover');
+                        });
+
+                    // optgroup or not...
+                    if (selectOptionData[i].parentOptGroup.length) {
+                        var optGroupName = self.widgetBaseClass + '-group-' + this.element.find('optgroup').index(selectOptionData[i].parentOptGroup);
+                        if (this.list.find('li.' + optGroupName).length) {
+                            this.list.find('li.' + optGroupName + ':last ul').append(thisLi);
+                        } else {
+                            $(' <li role="presentation" class="' + self.widgetBaseClass + '-group ' + optGroupName + (selectOptionData[i].parentOptGroup.attr("disabled") ? ' ' + this.namespace + '-state-disabled" aria-disabled="true"' : '"' ) + '><span class="' + self.widgetBaseClass + '-group-label">' + selectOptionData[i].parentOptGroup.attr('label') + '</span><ul></ul></li> ')
+                                .appendTo(this.list)
+                                .find('ul')
+                                .append(thisLi);
+                        }
+                    } else {
+                        thisLi.appendTo(this.list);
+                    }
+
+                    // append icon if option is specified
+                    if (o.icons) {
+                        for (var j in o.icons) {
+                            if (thisLi.is(o.icons[j].find)) {
+                                thisLi
+                                    .data('optionClasses', selectOptionData[i].classes + ' ' + self.widgetBaseClass + '-hasIcon')
+                                    .addClass(self.widgetBaseClass + '-hasIcon');
+                                var iconClass = o.icons[j].icon || "";
+                                thisLi
+                                    .find('a:eq(0)')
+                                    .prepend('<span class="' + self.widgetBaseClass + '-item-icon ui-icon ' + iconClass + '"></span>');
+                                if (selectOptionData[i].bgImage) {
+                                    thisLi.find('span').css('background-image', selectOptionData[i].bgImage);
+                                }
+                            }
+                        }
+                    }
+                }
+            } else {
+                $('<li role="presentation"><a href="#nogo" tabindex="-1" role="option"></a></li>').appendTo(this.list);
+            }
+            // we need to set and unset the CSS classes for dropdown and popup style
+            var isDropDown = ( o.style == 'dropdown' );
+            this.newelement
+                .toggleClass(self.widgetBaseClass + '-dropdown', isDropDown)
+                .toggleClass(self.widgetBaseClass + '-popup', !isDropDown);
+            this.list
+                .toggleClass(self.widgetBaseClass + '-menu-dropdown ui-corner-bottom', isDropDown)
+                .toggleClass(self.widgetBaseClass + '-menu-popup ui-corner-all', !isDropDown)
+                // add corners to top and bottom menu items
+                .find('li:first')
+                .toggleClass('ui-corner-top', !isDropDown)
+                .end().find('li:last')
+                .addClass('ui-corner-bottom');
+            this.selectmenuIcon
+                .toggleClass('ui-icon-triangle-1-s', isDropDown)
+                .toggleClass('ui-icon-triangle-2-n-s', !isDropDown);
+
+            // set menu width to either menuWidth option value, width option value, or select width
+            if (o.style == 'dropdown') {
+                this.list.width(o.menuWidth ? o.menuWidth : o.width);
+            } else {
+                this.list.width(o.menuWidth ? o.menuWidth : o.width - o.handleWidth);
+            }
+
+            // reset height to auto
+            this.list.css('height', 'auto');
+            var listH = this.listWrap.height();
+            var winH = $(window).height();
+            // calculate default max height
+            var maxH = o.maxHeight ? Math.min(o.maxHeight, winH) : winH / 3;
+            if (listH > maxH) this.list.height(maxH);
+
+            // save reference to actionable li's (not group label li's)
+            this._optionLis = this.list.find('li:not(.' + self.widgetBaseClass + '-group)');
+
+            // transfer disabled state
+            if (this.element.attr('disabled')) {
+                this.disable();
+            } else {
+                this.enable();
+            }
+
+            // update value
+            this.index(this._selectedIndex());
+
+            // set selected item so movefocus has intial state
+            this._selectedOptionLi().addClass(this.widgetBaseClass + '-item-focus');
+
+            // needed when selectmenu is placed at the very bottom / top of the page
+            clearTimeout(this.refreshTimeout);
+            this.refreshTimeout = window.setTimeout(function () {
+                self._refreshPosition();
+            }, 200);
+        },
+
+        destroy: function () {
+            this.element.removeData(this.widgetName)
+                .removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled')
+                .removeAttr('aria-disabled')
+                .unbind(".selectmenu");
+
+            $(window).unbind(".selectmenu-" + this.ids[0]);
+            $(document).unbind(".selectmenu-" + this.ids[0]);
+
+            this.newelementWrap.remove();
+            this.listWrap.remove();
+
+            // unbind click event and show original select
+            this.element
+                .unbind(".selectmenu")
+                .show();
+
+            // call widget destroy function
+            $.Widget.prototype.destroy.apply(this, arguments);
+        },
+
+        _typeAhead: function (code, eventType) {
+            var self = this,
+                c = String.fromCharCode(code).toLowerCase(),
+                matchee = null,
+                nextIndex = null;
+
+            // Clear any previous timer if present
+            if (self._typeAhead_timer) {
+                window.clearTimeout(self._typeAhead_timer);
+                self._typeAhead_timer = undefined;
+            }
+
+            // Store the character typed
+            self._typeAhead_chars = (self._typeAhead_chars === undefined ? "" : self._typeAhead_chars).concat(c);
+
+            // Detect if we are in cyciling mode or direct selection mode
+            if (self._typeAhead_chars.length < 2 ||
+                (self._typeAhead_chars.substr(-2, 1) === c && self._typeAhead_cycling)) {
+                self._typeAhead_cycling = true;
+
+                // Match only the first character and loop
+                matchee = c;
+            }
+            else {
+                // We won't be cycling anymore until the timer expires
+                self._typeAhead_cycling = false;
+
+                // Match all the characters typed
+                matchee = self._typeAhead_chars;
+            }
+
+            // We need to determine the currently active index, but it depends on
+            // the used context: if it's in the element, we want the actual
+            // selected index, if it's in the menu, just the focused one
+            // I copied this code from _moveSelection() and _moveFocus()
+            // respectively --thg2k
+            var selectedIndex = (eventType !== 'focus' ?
+                this._selectedOptionLi().data('index') :
+                this._focusedOptionLi().data('index')) || 0;
+
+            for (var i = 0; i < this._optionLis.length; i++) {
+                var thisText = this._optionLis.eq(i).text().substr(0, matchee.length).toLowerCase();
+
+                if (thisText === matchee) {
+                    if (self._typeAhead_cycling) {
+                        if (nextIndex === null)
+                            nextIndex = i;
+
+                        if (i > selectedIndex) {
+                            nextIndex = i;
+                            break;
+                        }
+                    } else {
+                        nextIndex = i;
+                    }
+                }
+            }
+
+            if (nextIndex !== null) {
+                // Why using trigger() instead of a direct method to select the
+                // index? Because we don't what is the exact action to do, it
+                // depends if the user is typing on the element or on the popped
+                // up menu
+                this._optionLis.eq(nextIndex).find("a").trigger(eventType);
+            }
+
+            self._typeAhead_timer = window.setTimeout(function () {
+                self._typeAhead_timer = undefined;
+                self._typeAhead_chars = undefined;
+                self._typeAhead_cycling = undefined;
+            }, self.options.typeAhead);
+        },
+
+        // returns some usefull information, called by callbacks only
+        _uiHash: function () {
+            var index = this.index();
+            return {
+                index: index,
+                option: $("option", this.element).get(index),
+                value: this.element[0].value
+            };
+        },
+
+        open: function (event) {
+            var self = this, o = this.options;
+            if (self.newelement.attr("aria-disabled") != 'true') {
+                self._closeOthers(event);
+                self.newelement.addClass('ui-state-active');
+
+                self.list.attr('aria-hidden', false);
+                self.listWrap.addClass(self.widgetBaseClass + '-open');
+
+                var selected = this._selectedOptionLi();
+                if (o.style == "dropdown") {
+                    self.newelement.removeClass('ui-corner-all').addClass('ui-corner-top');
+                } else {
+                    // center overflow and avoid flickering
+                    this.list
+                        .css("left", -5000)
+                        .scrollTop(this.list.scrollTop() + selected.position().top - this.list.outerHeight() / 2 + selected.outerHeight() / 2)
+                        .css("left", "auto");
+                }
+
+                self._refreshPosition();
+
+                var link = selected.find("a");
+                if (link.length) link[0].focus();
+
+                self.isOpen = true;
+                self._trigger("open", event, self._uiHash());
+            }
+        },
+
+        close: function (event, retainFocus) {
+            if (this.newelement.is('.ui-state-active')) {
+                this.newelement
+                    .removeClass('ui-state-active');
+                this.listWrap.removeClass(this.widgetBaseClass + '-open');
+                this.list.attr('aria-hidden', true);
+                if (this.options.style == "dropdown") {
+                    this.newelement.removeClass('ui-corner-top').addClass('ui-corner-all');
+                }
+                if (retainFocus) {
+                    this.newelement.focus();
+                }
+                this.isOpen = false;
+                this._trigger("close", event, this._uiHash());
+            }
+        },
+
+        change: function (event) {
+            this.element.trigger("change");
+            this._trigger("change", event, this._uiHash());
+        },
+
+        select: function (event) {
+            if (this._disabled(event.currentTarget)) {
+                return false;
+            }
+            this._trigger("select", event, this._uiHash());
+        },
+
+        widget: function () {
+            return this.listWrap.add(this.newelementWrap);
+        },
+
+        _closeOthers: function (event) {
+            $('.' + this.widgetBaseClass + '.ui-state-active').not(this.newelement).each(function () {
+                $(this).data('selectelement').selectmenu('close', event);
+            });
+            $('.' + this.widgetBaseClass + '.ui-state-hover').trigger('mouseout');
+        },
+
+        _toggle: function (event, retainFocus) {
+            if (this.isOpen) {
+                this.close(event, retainFocus);
+            } else {
+                this.open(event);
+            }
+        },
+
+        _formatText: function (text) {
+            if (this.options.format) {
+                text = this.options.format(text);
+            } else if (this.options.escapeHtml) {
+                text = $('<div />').text(text).html();
+            }
+            return text;
+        },
+
+        _selectedIndex: function () {
+            return this.element[0].selectedIndex;
+        },
+
+        _selectedOptionLi: function () {
+            return this._optionLis.eq(this._selectedIndex());
+        },
+
+        _focusedOptionLi: function () {
+            return this.list.find('.' + this.widgetBaseClass + '-item-focus');
+        },
+
+        _moveSelection: function (amt, recIndex) {
+            // do nothing if disabled
+            if (!this.options.disabled) {
+                var currIndex = parseInt(this._selectedOptionLi().data('index') || 0, 10);
+                var newIndex = currIndex + amt;
+                // do not loop when using up key
+
+                if (newIndex < 0) {
+                    newIndex = 0;
+                }
+                if (newIndex > this._optionLis.size() - 1) {
+                    newIndex = this._optionLis.size() - 1;
+                }
+                // Occurs when a full loop has been made
+                if (newIndex === recIndex) {
+                    return false;
+                }
+
+                if (this._optionLis.eq(newIndex).hasClass(this.namespace + '-state-disabled')) {
+                    // if option at newIndex is disabled, call _moveFocus, incrementing amt by one
+                    (amt > 0) ? ++amt : --amt;
+                    this._moveSelection(amt, newIndex);
+                } else {
+                    this._optionLis.eq(newIndex).trigger('mouseover').trigger('mouseup');
+                }
+            }
+        },
+
+        _moveFocus: function (amt, recIndex) {
+            if (!isNaN(amt)) {
+                var currIndex = parseInt(this._focusedOptionLi().data('index') || 0, 10);
+                var newIndex = currIndex + amt;
+            } else {
+                var newIndex = parseInt(this._optionLis.filter(amt).data('index'), 10);
+            }
+
+            if (newIndex < 0) {
+                newIndex = 0;
+            }
+            if (newIndex > this._optionLis.size() - 1) {
+                newIndex = this._optionLis.size() - 1;
+            }
+
+            //Occurs when a full loop has been made
+            if (newIndex === recIndex) {
+                return false;
+            }
+
+            var activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000);
+
+            this._focusedOptionLi().find('a:eq(0)').attr('id', '');
+
+            if (this._optionLis.eq(newIndex).hasClass(this.namespace + '-state-disabled')) {
+                // if option at newIndex is disabled, call _moveFocus, incrementing amt by one
+                (amt > 0) ? ++amt : --amt;
+                this._moveFocus(amt, newIndex);
+            } else {
+                this._optionLis.eq(newIndex).find('a:eq(0)').attr('id', activeID).focus();
+            }
+
+            this.list.attr('aria-activedescendant', activeID);
+        },
+
+        _scrollPage: function (direction) {
+            var numPerPage = Math.floor(this.list.outerHeight() / this._optionLis.first().outerHeight());
+            numPerPage = (direction == 'up' ? -numPerPage : numPerPage);
+            this._moveFocus(numPerPage);
+        },
+
+        _setOption: function (key, value) {
+            this.options[key] = value;
+            // set
+            if (key == 'disabled') {
+                if (value) this.close();
+                this.element
+                    .add(this.newelement)
+                    .add(this.list)[value ? 'addClass' : 'removeClass'](
+                        this.widgetBaseClass + '-disabled' + ' ' +
+                            this.namespace + '-state-disabled')
+                    .attr("aria-disabled", value);
+            }
+        },
+
+        disable: function (index, type) {
+            // if options is not provided, call the parents disable function
+            if (typeof( index ) == 'undefined') {
+                this._setOption('disabled', true);
+            } else {
+                if (type == "optgroup") {
+                    this._disableOptgroup(index);
+                } else {
+                    this._disableOption(index);
+                }
+            }
+        },
+
+        enable: function (index, type) {
+            // if options is not provided, call the parents enable function
+            if (typeof( index ) == 'undefined') {
+                this._setOption('disabled', false);
+            } else {
+                if (type == "optgroup") {
+                    this._enableOptgroup(index);
+                } else {
+                    this._enableOption(index);
+                }
+            }
+        },
+
+        _disabled: function (elem) {
+            return $(elem).hasClass(this.namespace + '-state-disabled');
+        },
+
+
+        _disableOption: function (index) {
+            var optionElem = this._optionLis.eq(index);
+            if (optionElem) {
+                optionElem.addClass(this.namespace + '-state-disabled')
+                    .find("a").attr("aria-disabled", true);
+                this.element.find("option").eq(index).attr("disabled", "disabled");
+            }
+        },
+
+        _enableOption: function (index) {
+            var optionElem = this._optionLis.eq(index);
+            if (optionElem) {
+                optionElem.removeClass(this.namespace + '-state-disabled')
+                    .find("a").attr("aria-disabled", false);
+                this.element.find("option").eq(index).removeAttr("disabled");
+            }
+        },
+
+        _disableOptgroup: function (index) {
+            var optGroupElem = this.list.find('li.' + this.widgetBaseClass + '-group-' + index);
+            if (optGroupElem) {
+                optGroupElem.addClass(this.namespace + '-state-disabled')
+                    .attr("aria-disabled", true);
+                this.element.find("optgroup").eq(index).attr("disabled", "disabled");
+            }
+        },
+
+        _enableOptgroup: function (index) {
+            var optGroupElem = this.list.find('li.' + this.widgetBaseClass + '-group-' + index);
+            if (optGroupElem) {
+                optGroupElem.removeClass(this.namespace + '-state-disabled')
+                    .attr("aria-disabled", false);
+                this.element.find("optgroup").eq(index).removeAttr("disabled");
+            }
+        },
+
+        index: function (newValue) {
+            if (arguments.length) {
+                if (!this._disabled($(this._optionLis[newValue]))) {
+                    this.element[0].selectedIndex = newValue;
+                    this._refreshValue();
+                } else {
+                    return false;
+                }
+            } else {
+                return this._selectedIndex();
+            }
+        },
+
+        value: function (newValue) {
+            if (arguments.length) {
+                this.element[0].value = newValue;
+                this._refreshValue();
+            } else {
+                return this.element[0].value;
+            }
+        },
+
+        _refreshValue: function () {
+            var activeClass = (this.options.style == "popup") ? " ui-state-active" : "";
+            var activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000);
+            // deselect previous
+            this.list
+                .find('.' + this.widgetBaseClass + '-item-selected')
+                .removeClass(this.widgetBaseClass + "-item-selected" + activeClass)
+                .find('a')
+                .attr('aria-selected', 'false')
+                .attr('id', '');
+            // select new
+            this._selectedOptionLi()
+                .addClass(this.widgetBaseClass + "-item-selected" + activeClass)
+                .find('a')
+                .attr('aria-selected', 'true')
+                .attr('id', activeID);
+
+            // toggle any class brought in from option
+            var currentOptionClasses = (this.newelement.data('optionClasses') ? this.newelement.data('optionClasses') : "");
+            var newOptionClasses = (this._selectedOptionLi().data('optionClasses') ? this._selectedOptionLi().data('optionClasses') : "");
+            this.newelement
+                .removeClass(currentOptionClasses)
+                .data('optionClasses', newOptionClasses)
+                .addClass(newOptionClasses)
+                .find('.' + this.widgetBaseClass + '-status')
+                .html(
+                    this._selectedOptionLi()
+                        .find('a:eq(0)')
+                        .html()
+                );
+
+            this.list.attr('aria-activedescendant', activeID);
+        },
+
+        _refreshPosition: function () {
+            var o = this.options;
+
+            // if its a pop-up we need to calculate the position of the selected li
+            if (o.style == "popup" && !o.positionOptions.offset) {
+                var selected = this._selectedOptionLi();
+                var _offset = "0 " + ( this.list.offset().top - selected.offset().top - ( this.newelement.outerHeight() + selected.outerHeight() ) / 2);
+            }
+            this.listWrap
+                .removeAttr('style')
+                .zIndex(this.element.zIndex() + 1)
+                .position({
+                    // set options for position plugin
+                    of: o.positionOptions.of || this.newelement,
+                    my: o.positionOptions.my,
+                    at: o.positionOptions.at,
+                    offset: o.positionOptions.offset || _offset,
+                    collision: o.positionOptions.collision || o.style == "popup" ? 'fit' : 'flip'
+                });
+        }
+    });
 
 })(jQuery);
diff --git a/media/js/lib/splitter.js b/media/js/lib/splitter.js
index b23bdb1..45f1838 100644
--- a/media/js/lib/splitter.js
+++ b/media/js/lib/splitter.js
@@ -30,186 +30,197 @@
  * @return jQuery
  * @author Dave Methvin (dave.methvin@gmail.com)
  */
- ;(function($){
-
- $.fn.splitter = function(args){
-	args = args || {};
-	return this.each(function() {
-		var zombie;		// left-behind splitbar for outline resizes
-		function startSplitMouse(evt) {
-			if ( opts.outline )
-				zombie = zombie || bar.clone(false).insertAfter(A);
-			panes.css("-webkit-user-select", "none");	// Safari selects A/B text on a move
-			bar.addClass(opts.activeClass);
-			A._posSplit = A[0][opts.pxSplit] - evt[opts.eventPos];
-			$(document)
-				.bind("mousemove", doSplitMouse)
-				.bind("mouseup", endSplitMouse);
-		}
-		function doSplitMouse(evt) {
-			var newPos = A._posSplit+evt[opts.eventPos];
-			if ( opts.outline ) {
-				newPos = Math.max(0, Math.min(newPos, splitter._DA - bar._DA));
-				bar.css(opts.origin, newPos);
-			} else
-				resplit(newPos);
-		}
-		function endSplitMouse(evt) {
-			bar.removeClass(opts.activeClass);
-			var newPos = A._posSplit+evt[opts.eventPos];
-			if ( opts.outline ) {
-				zombie.remove(); zombie = null;
-				resplit(newPos);
-			}
-			panes.css("-webkit-user-select", "text");	// let Safari select text again
-			$(document)
-				.unbind("mousemove", doSplitMouse)
-				.unbind("mouseup", endSplitMouse);
-		}
-		function resplit(newPos) {
-			// Constrain new splitbar position to fit pane size limits
-			newPos = Math.max(A._min, splitter._DA - B._max,
-					Math.min(newPos, A._max, splitter._DA - bar._DA - B._min));
-			// Resize/position the two panes
-			bar._DA = bar[0][opts.pxSplit];		// bar size may change during dock
-			bar.css(opts.origin, newPos).css(opts.fixed, splitter._DF);
-			A.css(opts.origin, 0).css(opts.split, newPos).css(opts.fixed,  splitter._DF);
-			B.css(opts.origin, newPos+bar._DA)
-				.css(opts.split, splitter._DA-bar._DA-newPos).css(opts.fixed,  splitter._DF);
-			// IE fires resize for us; all others pay cash
-			if ( !$.browser.msie )
-				panes.trigger("resize");
-		}
-		function dimSum(jq, dims) {
-			// Opera returns -1 for missing min/max width, turn into 0
-			var sum = 0;
-			for ( var i=1; i < arguments.length; i++ )
-				sum += Math.max(parseInt(jq.css(arguments[i])) || 0, 0);
-			return sum;
-		}
-
-		// Determine settings based on incoming opts, element classes, and defaults
-		var vh = (args.splitHorizontal? 'h' : args.splitVertical? 'v' : args.type) || 'v';
-		var opts = $.extend({
-			activeClass: 'active',	// class name for active splitter
-			pxPerKey: 8,			// splitter px moved per keypress
-			tabIndex: 0,			// tab order indicator
-			accessKey: ''			// accessKey for splitbar
-		},{
-			v: {					// Vertical splitters:
-				keyLeft: 39, keyRight: 37, cursor: "e-resize",
-				splitbarClass: "vsplitbar", outlineClass: "voutline",
-				type: 'v', eventPos: "pageX", origin: "left",
-				split: "width",  pxSplit: "offsetWidth",  side1: "Left", side2: "Right",
-				fixed: "height", pxFixed: "offsetHeight", side3: "Top",  side4: "Bottom"
-			},
-			h: {					// Horizontal splitters:
-				keyTop: 40, keyBottom: 38,  cursor: "n-resize",
-				splitbarClass: "hsplitbar", outlineClass: "houtline",
-				type: 'h', eventPos: "pageY", origin: "top",
-				split: "height", pxSplit: "offsetHeight", side1: "Top",  side2: "Bottom",
-				fixed: "width",  pxFixed: "offsetWidth",  side3: "Left", side4: "Right"
-			}
-		}[vh], args);
-
-		// Create jQuery object closures for splitter and both panes
-		var splitter = $(this).css({position: "relative"});
-		var panes = $(">*", splitter[0]).css({
-			position: "absolute", 			// positioned inside splitter container
-			"z-index": "1",					// splitbar is positioned above
-			"-moz-outline-style": "none"	// don't show dotted outline
-		});
-		var A = $(panes[0]);		// left  or top
-		var B = $(panes[1]);		// right or bottom
-
-		// Focuser element, provides keyboard support; title is shown by Opera accessKeys
-		var focuser = $('<a href="javascript:void(0)"></a>')
-			.attr({accessKey: opts.accessKey, tabIndex: opts.tabIndex, title: opts.splitbarClass})
-			.bind($.browser.opera?"click":"focus", function(){ this.focus(); bar.addClass(opts.activeClass) })
-			.bind("keydown", function(e){
-				var key = e.which || e.keyCode;
-				var dir = key==opts["key"+opts.side1]? 1 : key==opts["key"+opts.side2]? -1 : 0;
-				if ( dir )
-					resplit(A[0][opts.pxSplit]+dir*opts.pxPerKey, false);
-			})
-			.bind("blur", function(){ bar.removeClass(opts.activeClass) });
-
-		// Splitbar element, can be already in the doc or we create one
-		var bar = $(panes[2] || '<div></div>')
-			.insertAfter(A).css("z-index", "100").append(focuser)
-			.attr({"class": opts.splitbarClass, unselectable: "on"})
-			.css({position: "absolute",	"user-select": "none", "-webkit-user-select": "none",
-				"-khtml-user-select": "none", "-moz-user-select": "none"})
-			.bind("mousedown", startSplitMouse);
-		// Use our cursor unless the style specifies a non-default cursor
-		if ( /^(auto|default|)$/.test(bar.css("cursor")) )
-			bar.css("cursor", opts.cursor);
-
-		// Cache several dimensions for speed, rather than re-querying constantly
-		bar._DA = bar[0][opts.pxSplit];
-		splitter._PBF = $.boxModel? dimSum(splitter, "border"+opts.side3+"Width", "border"+opts.side4+"Width") : 0;
-		splitter._PBA = $.boxModel? dimSum(splitter, "border"+opts.side1+"Width", "border"+opts.side2+"Width") : 0;
-		A._pane = opts.side1;
-		B._pane = opts.side2;
-		$.each([A,B], function(){
-			this._min = opts["min"+this._pane] || dimSum(this, "min-"+opts.split);
-			this._max = opts["max"+this._pane] || dimSum(this, "max-"+opts.split) || 9999;
-			this._init = opts["size"+this._pane]===true ?
-				parseInt($.curCSS(this[0],opts.split)) : opts["size"+this._pane];
-		});
-
-		// Determine initial position, get from cookie if specified
-		var initPos = A._init;
-		if ( !isNaN(B._init) )	// recalc initial B size as an offset from the top or left side
-			initPos = splitter[0][opts.pxSplit] - splitter._PBA - B._init - bar._DA;
-		if ( opts.cookie ) {
-			if ( !$.cookie )
-				alert('jQuery.splitter(): jQuery cookie plugin required');
-			var ckpos = parseInt($.cookie(opts.cookie));
-			if ( !isNaN(ckpos) )
-				initPos = ckpos;
-			$(window).bind("unload", function(){
-				var state = String(bar.css(opts.origin));	// current location of splitbar
-				$.cookie(opts.cookie, state, {expires: opts.cookieExpires || 365,
-					path: opts.cookiePath || document.location.pathname});
-			});
-		}
-		if ( isNaN(initPos) )	// King Solomon's algorithm
-			initPos = Math.round((splitter[0][opts.pxSplit] - splitter._PBA - bar._DA)/2);
-
-        var resizeHandler = function(){
-            var top = splitter.offset().top;
-            var wh = $(window).height();
-            splitter.css("height", Math.max(wh-top-splitter._hadjust, splitter._hmin)+"px");
-            if ( !$.browser.msie ) splitter.trigger("resize");
-        };
-
-		// Resize event propagation and splitter sizing
-		if ( opts.anchorToWindow ) {
-			// Account for margin or border on the splitter container and enforce min height
-			splitter._hadjust = dimSum(splitter, "borderTopWidth", "borderBottomWidth", "marginBottom");
-			splitter._hmin = Math.max(dimSum(splitter, "minHeight"), 20);
-      $(window).bind("resize", resizeHandler);
-      resizeHandler();
-		}
-		else if ( opts.resizeToWidth && !$.browser.msie )
-			$(window).bind("resize", function(){
-				splitter.trigger("resize");
-			});
-
-		// Resize event handler; triggered immediately to set initial position
-		splitter.bind("resize", function(e, size){
-			// Determine new width/height of splitter container
-			splitter._DF = splitter[0][opts.pxFixed] - splitter._PBF;
-			splitter._DA = splitter[0][opts.pxSplit] - splitter._PBA;
-			// Bail if splitter isn't visible or content isn't there yet
-			if ( splitter._DF <= 0 || splitter._DA <= 0 ) return;
-			// Re-divvy the adjustable dimension; maintain size of the preferred pane
-			resplit(!isNaN(size)? size : (!(opts.sizeRight||opts.sizeBottom)? A[0][opts.pxSplit] :
-				splitter._DA-B[0][opts.pxSplit]-bar._DA));
-			e.stopPropagation();
-		}).trigger("resize" , [initPos]);
-	});
-};
+;
+(function ($) {
+
+    $.fn.splitter = function (args) {
+        args = args || {};
+        return this.each(function () {
+            var zombie;		// left-behind splitbar for outline resizes
+            function startSplitMouse(evt) {
+                if (opts.outline)
+                    zombie = zombie || bar.clone(false).insertAfter(A);
+                panes.css("-webkit-user-select", "none");	// Safari selects A/B text on a move
+                bar.addClass(opts.activeClass);
+                A._posSplit = A[0][opts.pxSplit] - evt[opts.eventPos];
+                $(document)
+                    .bind("mousemove", doSplitMouse)
+                    .bind("mouseup", endSplitMouse);
+            }
+
+            function doSplitMouse(evt) {
+                var newPos = A._posSplit + evt[opts.eventPos];
+                if (opts.outline) {
+                    newPos = Math.max(0, Math.min(newPos, splitter._DA - bar._DA));
+                    bar.css(opts.origin, newPos);
+                } else
+                    resplit(newPos);
+            }
+
+            function endSplitMouse(evt) {
+                bar.removeClass(opts.activeClass);
+                var newPos = A._posSplit + evt[opts.eventPos];
+                if (opts.outline) {
+                    zombie.remove();
+                    zombie = null;
+                    resplit(newPos);
+                }
+                panes.css("-webkit-user-select", "text");	// let Safari select text again
+                $(document)
+                    .unbind("mousemove", doSplitMouse)
+                    .unbind("mouseup", endSplitMouse);
+            }
+
+            function resplit(newPos) {
+                // Constrain new splitbar position to fit pane size limits
+                newPos = Math.max(A._min, splitter._DA - B._max,
+                    Math.min(newPos, A._max, splitter._DA - bar._DA - B._min));
+                // Resize/position the two panes
+                bar._DA = bar[0][opts.pxSplit];		// bar size may change during dock
+                bar.css(opts.origin, newPos).css(opts.fixed, splitter._DF);
+                A.css(opts.origin, 0).css(opts.split, newPos).css(opts.fixed, splitter._DF);
+                B.css(opts.origin, newPos + bar._DA)
+                    .css(opts.split, splitter._DA - bar._DA - newPos).css(opts.fixed, splitter._DF);
+                // IE fires resize for us; all others pay cash
+                if (!$.browser.msie)
+                    panes.trigger("resize");
+            }
+
+            function dimSum(jq, dims) {
+                // Opera returns -1 for missing min/max width, turn into 0
+                var sum = 0;
+                for (var i = 1; i < arguments.length; i++)
+                    sum += Math.max(parseInt(jq.css(arguments[i])) || 0, 0);
+                return sum;
+            }
+
+            // Determine settings based on incoming opts, element classes, and defaults
+            var vh = (args.splitHorizontal ? 'h' : args.splitVertical ? 'v' : args.type) || 'v';
+            var opts = $.extend({
+                activeClass: 'active',	// class name for active splitter
+                pxPerKey: 8,			// splitter px moved per keypress
+                tabIndex: 0,			// tab order indicator
+                accessKey: ''			// accessKey for splitbar
+            }, {
+                v: {					// Vertical splitters:
+                    keyLeft: 39, keyRight: 37, cursor: "e-resize",
+                    splitbarClass: "vsplitbar", outlineClass: "voutline",
+                    type: 'v', eventPos: "pageX", origin: "left",
+                    split: "width", pxSplit: "offsetWidth", side1: "Left", side2: "Right",
+                    fixed: "height", pxFixed: "offsetHeight", side3: "Top", side4: "Bottom"
+                },
+                h: {					// Horizontal splitters:
+                    keyTop: 40, keyBottom: 38, cursor: "n-resize",
+                    splitbarClass: "hsplitbar", outlineClass: "houtline",
+                    type: 'h', eventPos: "pageY", origin: "top",
+                    split: "height", pxSplit: "offsetHeight", side1: "Top", side2: "Bottom",
+                    fixed: "width", pxFixed: "offsetWidth", side3: "Left", side4: "Right"
+                }
+            }[vh], args);
+
+            // Create jQuery object closures for splitter and both panes
+            var splitter = $(this).css({position: "relative"});
+            var panes = $(">*", splitter[0]).css({
+                position: "absolute", 			// positioned inside splitter container
+                "z-index": "1",					// splitbar is positioned above
+                "-moz-outline-style": "none"	// don't show dotted outline
+            });
+            var A = $(panes[0]);		// left  or top
+            var B = $(panes[1]);		// right or bottom
+
+            // Focuser element, provides keyboard support; title is shown by Opera accessKeys
+            var focuser = $('<a href="javascript:void(0)"></a>')
+                .attr({accessKey: opts.accessKey, tabIndex: opts.tabIndex, title: opts.splitbarClass})
+                .bind($.browser.opera ? "click" : "focus", function () {
+                    this.focus();
+                    bar.addClass(opts.activeClass)
+                })
+                .bind("keydown", function (e) {
+                    var key = e.which || e.keyCode;
+                    var dir = key == opts["key" + opts.side1] ? 1 : key == opts["key" + opts.side2] ? -1 : 0;
+                    if (dir)
+                        resplit(A[0][opts.pxSplit] + dir * opts.pxPerKey, false);
+                })
+                .bind("blur", function () {
+                    bar.removeClass(opts.activeClass)
+                });
+
+            // Splitbar element, can be already in the doc or we create one
+            var bar = $(panes[2] || '<div></div>')
+                .insertAfter(A).css("z-index", "100").append(focuser)
+                .attr({"class": opts.splitbarClass, unselectable: "on"})
+                .css({position: "absolute", "user-select": "none", "-webkit-user-select": "none",
+                    "-khtml-user-select": "none", "-moz-user-select": "none"})
+                .bind("mousedown", startSplitMouse);
+            // Use our cursor unless the style specifies a non-default cursor
+            if (/^(auto|default|)$/.test(bar.css("cursor")))
+                bar.css("cursor", opts.cursor);
+
+            // Cache several dimensions for speed, rather than re-querying constantly
+            bar._DA = bar[0][opts.pxSplit];
+            splitter._PBF = $.boxModel ? dimSum(splitter, "border" + opts.side3 + "Width", "border" + opts.side4 + "Width") : 0;
+            splitter._PBA = $.boxModel ? dimSum(splitter, "border" + opts.side1 + "Width", "border" + opts.side2 + "Width") : 0;
+            A._pane = opts.side1;
+            B._pane = opts.side2;
+            $.each([A, B], function () {
+                this._min = opts["min" + this._pane] || dimSum(this, "min-" + opts.split);
+                this._max = opts["max" + this._pane] || dimSum(this, "max-" + opts.split) || 9999;
+                this._init = opts["size" + this._pane] === true ?
+                    parseInt($.curCSS(this[0], opts.split)) : opts["size" + this._pane];
+            });
+
+            // Determine initial position, get from cookie if specified
+            var initPos = A._init;
+            if (!isNaN(B._init))	// recalc initial B size as an offset from the top or left side
+                initPos = splitter[0][opts.pxSplit] - splitter._PBA - B._init - bar._DA;
+            if (opts.cookie) {
+                if (!$.cookie)
+                    alert('jQuery.splitter(): jQuery cookie plugin required');
+                var ckpos = parseInt($.cookie(opts.cookie));
+                if (!isNaN(ckpos))
+                    initPos = ckpos;
+                $(window).bind("unload", function () {
+                    var state = String(bar.css(opts.origin));	// current location of splitbar
+                    $.cookie(opts.cookie, state, {expires: opts.cookieExpires || 365,
+                        path: opts.cookiePath || document.location.pathname});
+                });
+            }
+            if (isNaN(initPos))	// King Solomon's algorithm
+                initPos = Math.round((splitter[0][opts.pxSplit] - splitter._PBA - bar._DA) / 2);
+
+            var resizeHandler = function () {
+                var top = splitter.offset().top;
+                var wh = $(window).height();
+                splitter.css("height", Math.max(wh - top - splitter._hadjust, splitter._hmin) + "px");
+                if (!$.browser.msie) splitter.trigger("resize");
+            };
+
+            // Resize event propagation and splitter sizing
+            if (opts.anchorToWindow) {
+                // Account for margin or border on the splitter container and enforce min height
+                splitter._hadjust = dimSum(splitter, "borderTopWidth", "borderBottomWidth", "marginBottom");
+                splitter._hmin = Math.max(dimSum(splitter, "minHeight"), 20);
+                $(window).bind("resize", resizeHandler);
+                resizeHandler();
+            }
+            else if (opts.resizeToWidth && !$.browser.msie)
+                $(window).bind("resize", function () {
+                    splitter.trigger("resize");
+                });
+
+            // Resize event handler; triggered immediately to set initial position
+            splitter.bind("resize",function (e, size) {
+                // Determine new width/height of splitter container
+                splitter._DF = splitter[0][opts.pxFixed] - splitter._PBF;
+                splitter._DA = splitter[0][opts.pxSplit] - splitter._PBA;
+                // Bail if splitter isn't visible or content isn't there yet
+                if (splitter._DF <= 0 || splitter._DA <= 0) return;
+                // Re-divvy the adjustable dimension; maintain size of the preferred pane
+                resplit(!isNaN(size) ? size : (!(opts.sizeRight || opts.sizeBottom) ? A[0][opts.pxSplit] :
+                    splitter._DA - B[0][opts.pxSplit] - bar._DA));
+                e.stopPropagation();
+            }).trigger("resize", [initPos]);
+        });
+    };
 
 })(jQuery);
diff --git a/media/js/lib/ui.multiselect.js b/media/js/lib/ui.multiselect.js
index f61435d..f567294 100644
--- a/media/js/lib/ui.multiselect.js
+++ b/media/js/lib/ui.multiselect.js
@@ -25,290 +25,302 @@
  */
 
 
-(function($) {
-
-$.widget("ui.multiselect", {
-	_init: function() {
-		this.element.hide();
-		this.id = this.element.attr("id");
-		this.container = $('<div class="ui-multiselect ui-helper-clearfix ui-widget"></div>').insertAfter(this.element);
-		this.count = 0; // number of currently selected options
-		this.selectedContainer = $('<div class="selected"></div>').appendTo(this.container);
-		this.availableContainer = $('<div class="available"></div>').appendTo(this.container);
-		this.selectedActions = $('<div class="actions ui-widget-header ui-helper-clearfix"><span class="count">0 '+$.ui.multiselect.locale.itemsCount+'</span><a href="#" class="remove-all">'+$.ui.multiselect.locale.removeAll+'</a></div>').appendTo(this.selectedContainer);
-		this.availableActions = $('<div class="actions ui-widget-header ui-helper-clearfix"><input type="text" class="search empty ui-widget-content ui-corner-all"/><a href="#" class="add-all">'+$.ui.multiselect.locale.addAll+'</a></div>').appendTo(this.availableContainer);
-		this.selectedList = $('<ul class="selected connected-list"><li class="ui-helper-hidden-accessible"></li></ul>').bind('selectstart', function(){return false;}).appendTo(this.selectedContainer);
-		this.availableList = $('<ul class="available connected-list"><li class="ui-helper-hidden-accessible"></li></ul>').bind('selectstart', function(){return false;}).appendTo(this.availableContainer);
-		
-		var that = this;
-
-		// set dimensions
-		this.container.width(this.element.width()+1);
-		this.selectedContainer.width(Math.floor(this.element.width()*this.options.dividerLocation));
-		this.availableContainer.width(Math.floor(this.element.width()*(1-this.options.dividerLocation)));
-
-		// fix list height to match <option> depending on their individual header's heights
-		this.selectedList.height(Math.max(this.element.height()-this.selectedActions.height(),1));
-		this.availableList.height(Math.max(this.element.height()-this.availableActions.height(),1));
-		
-		if ( !this.options.animated ) {
-			this.options.show = 'show';
-			this.options.hide = 'hide';
-		}
-		
-		// init lists
-		this._populateLists(this.element.find('option'));
-		
-		// make selection sortable
-		if (this.options.sortable) {
-			$("ul.selected").sortable({
-				placeholder: 'ui-state-highlight',
-				axis: 'y',
-				update: function(event, ui) {
-					// apply the new sort order to the original selectbox
-					that.selectedList.find('li').each(function() {
-						if ($(this).data('optionLink'))
-							$(this).data('optionLink').remove().appendTo(that.element);
-					});
-				},
-				receive: function(event, ui) {
-					ui.item.data('optionLink').attr('selected', true);
-					// increment count
-					that.count += 1;
-					that._updateCount();
-					// workaround, because there's no way to reference 
-					// the new element, see http://dev.jqueryui.com/ticket/4303
-					that.selectedList.children('.ui-draggable').each(function() {
-						$(this).removeClass('ui-draggable');
-						$(this).data('optionLink', ui.item.data('optionLink'));
-						$(this).data('idx', ui.item.data('idx'));
-						that._applyItemState($(this), true);
-					});
-			
-					// workaround according to http://dev.jqueryui.com/ticket/4088
-					setTimeout(function() { ui.item.remove(); }, 1);
-				}
-			});
-		}
-		
-		// set up livesearch
-		if (this.options.searchable) {
-			this._registerSearchEvents(this.availableContainer.find('input.search'));
-		} else {
-			$('.search').hide();
-		}
-		
-		// batch actions
-		$(".remove-all").click(function() {
-			that._populateLists(that.element.find('option').removeAttr('selected'));
-			return false;
-		});
-		$(".add-all").click(function() {
-			that._populateLists(that.element.find('option').attr('selected', 'selected'));
-			return false;
-		});
-	},
-	destroy: function() {
-		this.element.show();
-		this.container.remove();
-
-		$.widget.prototype.destroy.apply(this, arguments);
-	},
-	_populateLists: function(options) {
-		this.selectedList.children('.ui-element').remove();
-		this.availableList.children('.ui-element').remove();
-		this.count = 0;
-
-		var that = this;
-		var items = $(options.map(function(i) {
-	      var item = that._getOptionNode(this).appendTo(this.selected ? that.selectedList : that.availableList).show();
-
-			if (this.selected) that.count += 1;
-			that._applyItemState(item, this.selected);
-			item.data('idx', i);
-			return item[0];
-    }));
-		
-		// update count
-		this._updateCount();
-  },
-	_updateCount: function() {
-		this.selectedContainer.find('span.count').text(this.count+" "+$.ui.multiselect.locale.itemsCount);
-	},
-	_getOptionNode: function(option) {
-		option = $(option);
-		var node = $('<li class="ui-state-default ui-element" title="'+option.text()+'"><span class="ui-icon"/>'+option.text()+'<a href="#" class="action"><span class="ui-corner-all ui-icon"/></a></li>').hide();
-		node.data('optionLink', option);
-		return node;
-	},
-	// clones an item with associated data
-	// didn't find a smarter away around this
-	_cloneWithData: function(clonee) {
-		var clone = clonee.clone();
-		clone.data('optionLink', clonee.data('optionLink'));
-		clone.data('idx', clonee.data('idx'));
-		return clone;
-	},
-	_setSelected: function(item, selected) {
-		item.data('optionLink').attr('selected', selected);
-
-		if (selected) {
-			var selectedItem = this._cloneWithData(item);
-			item[this.options.hide](this.options.animated, function() { $(this).remove(); });
-			selectedItem.appendTo(this.selectedList).hide()[this.options.show](this.options.animated);
-			
-			this._applyItemState(selectedItem, true);
-			return selectedItem;
-		} else {
-			
-			// look for successor based on initial option index
-			var items = this.availableList.find('li'), comparator = this.options.nodeComparator;
-			var succ = null, i = item.data('idx'), direction = comparator(item, $(items[i]));
-
-			// TODO: test needed for dynamic list populating
-			if ( direction ) {
-				while (i>=0 && i<items.length) {
-					direction > 0 ? i++ : i--;
-					if ( direction != comparator(item, $(items[i])) ) {
-						// going up, go back one item down, otherwise leave as is
-						succ = items[direction > 0 ? i : i+1];
-						break;
-					}
-				}
-			} else {
-				succ = items[i];
-			}
-			
-			var availableItem = this._cloneWithData(item);
-			succ ? availableItem.insertBefore($(succ)) : availableItem.appendTo(this.availableList);
-			item[this.options.hide](this.options.animated, function() { $(this).remove(); });
-			availableItem.hide()[this.options.show](this.options.animated);
-			
-			this._applyItemState(availableItem, false);
-			return availableItem;
-		}
-	},
-	_applyItemState: function(item, selected) {
-		if (selected) {
-			if (this.options.sortable)
-				item.children('span').addClass('ui-icon-arrowthick-2-n-s').removeClass('ui-helper-hidden').addClass('ui-icon');
-			else
-				item.children('span').removeClass('ui-icon-arrowthick-2-n-s').addClass('ui-helper-hidden').removeClass('ui-icon');
-			item.find('a.action span').addClass('ui-icon-minus').removeClass('ui-icon-plus');
-			this._registerRemoveEvents(item.find('a.action'));
-			
-		} else {
-			item.children('span').removeClass('ui-icon-arrowthick-2-n-s').addClass('ui-helper-hidden').removeClass('ui-icon');
-			item.find('a.action span').addClass('ui-icon-plus').removeClass('ui-icon-minus');
-			this._registerAddEvents(item.find('a.action'));
-		}
-		
-		this._registerHoverEvents(item);
-	},
-	// taken from John Resig's liveUpdate script
-	_filter: function(list) {
-		var input = $(this);
-		var rows = list.children('li'),
-			cache = rows.map(function(){
-				
-				return $(this).text().toLowerCase();
-			});
-		
-		var term = $.trim(input.val().toLowerCase()), scores = [];
-		
-		if (!term) {
-			rows.show();
-		} else {
-			rows.hide();
-
-			cache.each(function(i) {
-				if (this.indexOf(term)>-1) { scores.push(i); }
-			});
-
-			$.each(scores, function() {
-				$(rows[this]).show();
-			});
-		}
-	},
-	_registerHoverEvents: function(elements) {
-		elements.removeClass('ui-state-hover');
-		elements.mouseover(function() {
-			$(this).addClass('ui-state-hover');
-		});
-		elements.mouseout(function() {
-			$(this).removeClass('ui-state-hover');
-		});
-	},
-	_registerAddEvents: function(elements) {
-		var that = this;
-		elements.click(function() {
-			var item = that._setSelected($(this).parent(), true);
-			that.count += 1;
-			that._updateCount();
-			return false;
-		})
-		// make draggable
-		.each(function() {
-			$(this).parent().draggable({
-	      connectToSortable: 'ul.selected',
-				helper: function() {
-					var selectedItem = that._cloneWithData($(this)).width($(this).width() - 50);
-					selectedItem.width($(this).width());
-					return selectedItem;
-				},
-				appendTo: '.ui-multiselect',
-				containment: '.ui-multiselect',
-				revert: 'invalid'
-	    });
-		});
-	},
-	_registerRemoveEvents: function(elements) {
-		var that = this;
-		elements.click(function() {
-			that._setSelected($(this).parent(), false);
-			that.count -= 1;
-			that._updateCount();
-			return false;
-		});
- 	},
-	_registerSearchEvents: function(input) {
-		var that = this;
-
-		input.focus(function() {
-			$(this).addClass('ui-state-active');
-		})
-		.blur(function() {
-			$(this).removeClass('ui-state-active');
-		})
-		.keypress(function(e) {
-			if (e.keyCode == 13)
-				return false;
-		})
-		.keyup(function() {
-			that._filter.apply(this, [that.availableList]);
-		});
-	}
-});
-		
-$.extend($.ui.multiselect, {
-	defaults: {
-		sortable: true,
-		searchable: true,
-		animated: 'fast',
-		show: 'slideDown',
-		hide: 'slideUp',
-		dividerLocation: 0.6,
-		nodeComparator: function(node1,node2) {
-			var text1 = node1.text(),
-			    text2 = node2.text();
-			return text1 == text2 ? 0 : (text1 < text2 ? -1 : 1);
-		}
-	},
-	locale: {
-		addAll:'Add all',
-		removeAll:'Remove all',
-		itemsCount:'items selected'
-	}
-});
+(function ($) {
+
+    $.widget("ui.multiselect", {
+        _init: function () {
+            this.element.hide();
+            this.id = this.element.attr("id");
+            this.container = $('<div class="ui-multiselect ui-helper-clearfix ui-widget"></div>').insertAfter(this.element);
+            this.count = 0; // number of currently selected options
+            this.selectedContainer = $('<div class="selected"></div>').appendTo(this.container);
+            this.availableContainer = $('<div class="available"></div>').appendTo(this.container);
+            this.selectedActions = $('<div class="actions ui-widget-header ui-helper-clearfix"><span class="count">0 ' + $.ui.multiselect.locale.itemsCount + '</span><a href="#" class="remove-all">' + $.ui.multiselect.locale.removeAll + '</a></div>').appendTo(this.selectedContainer);
+            this.availableActions = $('<div class="actions ui-widget-header ui-helper-clearfix"><input type="text" class="search empty ui-widget-content ui-corner-all"/><a href="#" class="add-all">' + $.ui.multiselect.locale.addAll + '</a></div>').appendTo(this.availableContainer);
+            this.selectedList = $('<ul class="selected connected-list"><li class="ui-helper-hidden-accessible"></li></ul>').bind('selectstart',function () {
+                return false;
+            }).appendTo(this.selectedContainer);
+            this.availableList = $('<ul class="available connected-list"><li class="ui-helper-hidden-accessible"></li></ul>').bind('selectstart',function () {
+                return false;
+            }).appendTo(this.availableContainer);
+
+            var that = this;
+
+            // set dimensions
+            this.container.width(this.element.width() + 1);
+            this.selectedContainer.width(Math.floor(this.element.width() * this.options.dividerLocation));
+            this.availableContainer.width(Math.floor(this.element.width() * (1 - this.options.dividerLocation)));
+
+            // fix list height to match <option> depending on their individual header's heights
+            this.selectedList.height(Math.max(this.element.height() - this.selectedActions.height(), 1));
+            this.availableList.height(Math.max(this.element.height() - this.availableActions.height(), 1));
+
+            if (!this.options.animated) {
+                this.options.show = 'show';
+                this.options.hide = 'hide';
+            }
+
+            // init lists
+            this._populateLists(this.element.find('option'));
+
+            // make selection sortable
+            if (this.options.sortable) {
+                $("ul.selected").sortable({
+                    placeholder: 'ui-state-highlight',
+                    axis: 'y',
+                    update: function (event, ui) {
+                        // apply the new sort order to the original selectbox
+                        that.selectedList.find('li').each(function () {
+                            if ($(this).data('optionLink'))
+                                $(this).data('optionLink').remove().appendTo(that.element);
+                        });
+                    },
+                    receive: function (event, ui) {
+                        ui.item.data('optionLink').attr('selected', true);
+                        // increment count
+                        that.count += 1;
+                        that._updateCount();
+                        // workaround, because there's no way to reference
+                        // the new element, see http://dev.jqueryui.com/ticket/4303
+                        that.selectedList.children('.ui-draggable').each(function () {
+                            $(this).removeClass('ui-draggable');
+                            $(this).data('optionLink', ui.item.data('optionLink'));
+                            $(this).data('idx', ui.item.data('idx'));
+                            that._applyItemState($(this), true);
+                        });
+
+                        // workaround according to http://dev.jqueryui.com/ticket/4088
+                        setTimeout(function () {
+                            ui.item.remove();
+                        }, 1);
+                    }
+                });
+            }
+
+            // set up livesearch
+            if (this.options.searchable) {
+                this._registerSearchEvents(this.availableContainer.find('input.search'));
+            } else {
+                $('.search').hide();
+            }
+
+            // batch actions
+            $(".remove-all").click(function () {
+                that._populateLists(that.element.find('option').removeAttr('selected'));
+                return false;
+            });
+            $(".add-all").click(function () {
+                that._populateLists(that.element.find('option').attr('selected', 'selected'));
+                return false;
+            });
+        },
+        destroy: function () {
+            this.element.show();
+            this.container.remove();
+
+            $.widget.prototype.destroy.apply(this, arguments);
+        },
+        _populateLists: function (options) {
+            this.selectedList.children('.ui-element').remove();
+            this.availableList.children('.ui-element').remove();
+            this.count = 0;
+
+            var that = this;
+            var items = $(options.map(function (i) {
+                var item = that._getOptionNode(this).appendTo(this.selected ? that.selectedList : that.availableList).show();
+
+                if (this.selected) that.count += 1;
+                that._applyItemState(item, this.selected);
+                item.data('idx', i);
+                return item[0];
+            }));
+
+            // update count
+            this._updateCount();
+        },
+        _updateCount: function () {
+            this.selectedContainer.find('span.count').text(this.count + " " + $.ui.multiselect.locale.itemsCount);
+        },
+        _getOptionNode: function (option) {
+            option = $(option);
+            var node = $('<li class="ui-state-default ui-element" title="' + option.text() + '"><span class="ui-icon"/>' + option.text() + '<a href="#" class="action"><span class="ui-corner-all ui-icon"/></a></li>').hide();
+            node.data('optionLink', option);
+            return node;
+        },
+        // clones an item with associated data
+        // didn't find a smarter away around this
+        _cloneWithData: function (clonee) {
+            var clone = clonee.clone();
+            clone.data('optionLink', clonee.data('optionLink'));
+            clone.data('idx', clonee.data('idx'));
+            return clone;
+        },
+        _setSelected: function (item, selected) {
+            item.data('optionLink').attr('selected', selected);
+
+            if (selected) {
+                var selectedItem = this._cloneWithData(item);
+                item[this.options.hide](this.options.animated, function () {
+                    $(this).remove();
+                });
+                selectedItem.appendTo(this.selectedList).hide()[this.options.show](this.options.animated);
+
+                this._applyItemState(selectedItem, true);
+                return selectedItem;
+            } else {
+
+                // look for successor based on initial option index
+                var items = this.availableList.find('li'), comparator = this.options.nodeComparator;
+                var succ = null, i = item.data('idx'), direction = comparator(item, $(items[i]));
+
+                // TODO: test needed for dynamic list populating
+                if (direction) {
+                    while (i >= 0 && i < items.length) {
+                        direction > 0 ? i++ : i--;
+                        if (direction != comparator(item, $(items[i]))) {
+                            // going up, go back one item down, otherwise leave as is
+                            succ = items[direction > 0 ? i : i + 1];
+                            break;
+                        }
+                    }
+                } else {
+                    succ = items[i];
+                }
+
+                var availableItem = this._cloneWithData(item);
+                succ ? availableItem.insertBefore($(succ)) : availableItem.appendTo(this.availableList);
+                item[this.options.hide](this.options.animated, function () {
+                    $(this).remove();
+                });
+                availableItem.hide()[this.options.show](this.options.animated);
+
+                this._applyItemState(availableItem, false);
+                return availableItem;
+            }
+        },
+        _applyItemState: function (item, selected) {
+            if (selected) {
+                if (this.options.sortable)
+                    item.children('span').addClass('ui-icon-arrowthick-2-n-s').removeClass('ui-helper-hidden').addClass('ui-icon');
+                else
+                    item.children('span').removeClass('ui-icon-arrowthick-2-n-s').addClass('ui-helper-hidden').removeClass('ui-icon');
+                item.find('a.action span').addClass('ui-icon-minus').removeClass('ui-icon-plus');
+                this._registerRemoveEvents(item.find('a.action'));
+
+            } else {
+                item.children('span').removeClass('ui-icon-arrowthick-2-n-s').addClass('ui-helper-hidden').removeClass('ui-icon');
+                item.find('a.action span').addClass('ui-icon-plus').removeClass('ui-icon-minus');
+                this._registerAddEvents(item.find('a.action'));
+            }
+
+            this._registerHoverEvents(item);
+        },
+        // taken from John Resig's liveUpdate script
+        _filter: function (list) {
+            var input = $(this);
+            var rows = list.children('li'),
+                cache = rows.map(function () {
+
+                    return $(this).text().toLowerCase();
+                });
+
+            var term = $.trim(input.val().toLowerCase()), scores = [];
+
+            if (!term) {
+                rows.show();
+            } else {
+                rows.hide();
+
+                cache.each(function (i) {
+                    if (this.indexOf(term) > -1) {
+                        scores.push(i);
+                    }
+                });
+
+                $.each(scores, function () {
+                    $(rows[this]).show();
+                });
+            }
+        },
+        _registerHoverEvents: function (elements) {
+            elements.removeClass('ui-state-hover');
+            elements.mouseover(function () {
+                $(this).addClass('ui-state-hover');
+            });
+            elements.mouseout(function () {
+                $(this).removeClass('ui-state-hover');
+            });
+        },
+        _registerAddEvents: function (elements) {
+            var that = this;
+            elements.click(function () {
+                var item = that._setSelected($(this).parent(), true);
+                that.count += 1;
+                that._updateCount();
+                return false;
+            })
+                // make draggable
+                .each(function () {
+                    $(this).parent().draggable({
+                        connectToSortable: 'ul.selected',
+                        helper: function () {
+                            var selectedItem = that._cloneWithData($(this)).width($(this).width() - 50);
+                            selectedItem.width($(this).width());
+                            return selectedItem;
+                        },
+                        appendTo: '.ui-multiselect',
+                        containment: '.ui-multiselect',
+                        revert: 'invalid'
+                    });
+                });
+        },
+        _registerRemoveEvents: function (elements) {
+            var that = this;
+            elements.click(function () {
+                that._setSelected($(this).parent(), false);
+                that.count -= 1;
+                that._updateCount();
+                return false;
+            });
+        },
+        _registerSearchEvents: function (input) {
+            var that = this;
+
+            input.focus(function () {
+                $(this).addClass('ui-state-active');
+            })
+                .blur(function () {
+                    $(this).removeClass('ui-state-active');
+                })
+                .keypress(function (e) {
+                    if (e.keyCode == 13)
+                        return false;
+                })
+                .keyup(function () {
+                    that._filter.apply(this, [that.availableList]);
+                });
+        }
+    });
+
+    $.extend($.ui.multiselect, {
+        defaults: {
+            sortable: true,
+            searchable: true,
+            animated: 'fast',
+            show: 'slideDown',
+            hide: 'slideUp',
+            dividerLocation: 0.6,
+            nodeComparator: function (node1, node2) {
+                var text1 = node1.text(),
+                    text2 = node2.text();
+                return text1 == text2 ? 0 : (text1 < text2 ? -1 : 1);
+            }
+        },
+        locale: {
+            addAll: 'Add all',
+            removeAll: 'Remove all',
+            itemsCount: 'items selected'
+        }
+    });
 
 })(jQuery);
diff --git a/media/js/manage-classifications.js b/media/js/manage-classifications.js
index 27c8c2e..d333614 100644
--- a/media/js/manage-classifications.js
+++ b/media/js/manage-classifications.js
@@ -1,6 +1,6 @@
-$(function() {
-  "use strict";
-  $('.value-name').click(function() {
-    $(this).next().toggle();
-  });
+$(function () {
+    "use strict";
+    $('.value-name').click(function () {
+        $(this).next().toggle();
+    });
 });
diff --git a/media/js/manage-groups.js b/media/js/manage-groups.js
index 502aaa0..2d589bb 100644
--- a/media/js/manage-groups.js
+++ b/media/js/manage-groups.js
@@ -1,17 +1,17 @@
-$(function() {
-  "use strict";
-  $('#user-groups').find('input[type=checkbox]').change(function() {
-    var $t = $(this),
-      user = this.id.split('-')[2],
-      group = this.id.split('-')[1];
-    $.ajaxJSON({
-      method: 'post',
-      url: $dj.ajax_set_group,
-      data: {
-        user_id: user,
-        group_id: group,
-        set: $t.is(':checked')
-      }
+$(function () {
+    "use strict";
+    $('#user-groups').find('input[type=checkbox]').change(function () {
+        var $t = $(this),
+            user = this.id.split('-')[2],
+            group = this.id.split('-')[1];
+        $.ajaxJSON({
+            method: 'post',
+            url: $dj.ajax_set_group,
+            data: {
+                user_id: user,
+                group_id: group,
+                set: $t.is(':checked')
+            }
+        });
     });
-  });
 });
diff --git a/media/js/manage-qualifiers.js b/media/js/manage-qualifiers.js
index f53a7a4..cc86043 100644
--- a/media/js/manage-qualifiers.js
+++ b/media/js/manage-qualifiers.js
@@ -1,8 +1,8 @@
-$(function() {
-  "use strict";
-  $('.qualifier-label').click(function() {
-    $(this).next().toggle();
-  });
-  $('#vocab-accordion').accordion(
-    {autoHeight: false, collapsible: true, active: false});
+$(function () {
+    "use strict";
+    $('.qualifier-label').click(function () {
+        $(this).next().toggle();
+    });
+    $('#vocab-accordion').accordion(
+        {autoHeight: false, collapsible: true, active: false});
 });
diff --git a/media/js/manager-view.js b/media/js/manager-view.js
index 745e0c4..0eef59e 100644
--- a/media/js/manager-view.js
+++ b/media/js/manager-view.js
@@ -1,43 +1,42 @@
-$(function() {
-  "use strict";
-  $('#add-vocabulary').click(function() {
-    var new_vocab = $('#new-vocabulary');
-    var name = new_vocab.value();
-    new_vocab.val('');
-    $.ajaxJSON({
-      method: 'post',
-      url: $dj.ajax_add_vocabulary,
-      data: {name: name},
-      callback: function() {
-        location.reload(); // porządniejszy by był zwykły formularz...
-      }
+$(function () {
+    "use strict";
+    $('#add-vocabulary').click(function () {
+        var new_vocab = $('#new-vocabulary');
+        var name = new_vocab.value();
+        new_vocab.val('');
+        $.ajaxJSON({
+            method: 'post',
+            url: $dj.ajax_add_vocabulary,
+            data: {name: name},
+            callback: function () {
+                location.reload(); // porządniejszy by był zwykły formularz...
+            }
+        });
     });
-  });
-  $('.user-privileges').find('input[type=checkbox]').change(function() {
-    var $t = $(this),
-      id = this.id.split('-')[1],
-      type = this.id.split('-')[0],
-      table_id = $t.closest('table')[0].id,
-      vocab_name = table_id.substr(table_id.indexOf('_') + 1);
-    $.ajaxJSON({
-      method: 'post',
-      url: $dj.ajax_set_permission,
-      data: {
-        name: vocab_name,
-        vocab_id: id,
-        perm: type,
-        on: $t.is(':checked')
-      }
+    $('.user-privileges').find('input[type=checkbox]').change(function () {
+        var $t = $(this),
+            id = this.id.split('-')[1],
+            type = this.id.split('-')[0],
+            table_id = $t.closest('table')[0].id,
+            vocab_name = table_id.substr(table_id.indexOf('_') + 1);
+        $.ajaxJSON({
+            method: 'post',
+            url: $dj.ajax_set_permission,
+            data: {
+                name: vocab_name,
+                vocab_id: id,
+                perm: type,
+                on: $t.is(':checked')
+            }
+        });
+        var view_checkbox = $('#view-' + id), change_checkbox = $('#change-' + id);
+        if (type === 'change' && $t.is(':checked') && !view_checkbox.is(':checked')) {
+            view_checkbox.prop('checked', true).change();
+        }
+        if (type === 'view' && !$t.is(':checked') && change_checkbox.is(':checked')) {
+            change_checkbox.prop('checked', false).change();
+        }
     });
-    var view_checkbox = $('#view-'+id), change_checkbox = $('#change-'+id);
-    if (type === 'change' && $t.is(':checked') &&
-        !view_checkbox.is(':checked')) {
-      view_checkbox.prop('checked', true).change();
-    }
-    if (type === 'view' && ! $t.is(':checked') && change_checkbox.is(':checked')) {
-      change_checkbox.prop('checked', false).change();
-    }
-  });
-  $('#vocab-accordion').togglepanels();
+    $('#vocab-accordion').togglepanels();
     //{autoHeight: false, collapsible: true, active: false});
 });
diff --git a/media/js/paginer.js b/media/js/paginer.js
index a1d6f7e..94d873c 100644
--- a/media/js/paginer.js
+++ b/media/js/paginer.js
@@ -8,222 +8,222 @@ var page_numbers = {};
 paginer.page_numbers = page_numbers;
 
 function get_page_number(id) {
-  "use strict";
-  if (!page_numbers[id])
-    return 1;
-  return page_numbers[id];
+    "use strict";
+    if (!page_numbers[id])
+        return 1;
+    return page_numbers[id];
 }
 paginer.get_page_number = get_page_number;
 
 function get_list_id(elem) {
-  "use strict";
-  return elem.id.split('-')[0];
+    "use strict";
+    return elem.id.split('-')[0];
 }
 
-var paginer_link_click = function() {
-  "use strict";
-  change_page($(this).parents('div.paginer')[0].id,
-              $('span.page_nr', this).text());
+var paginer_link_click = function () {
+    "use strict";
+    change_page($(this).parents('div.paginer')[0].id,
+        $('span.page_nr', this).text());
 };
 
-var perform_group_action = function() {
-  "use strict";
-  var container, id, action, ajax_url, row_ids;
-  container = $(this).parents('div.paginer')[0];
-  id = container.id;
-  action = this.id.replace(id + '-', '');
-  ajax_url = window['ajax_' + action];
-  row_ids = $('.checkrow:checked', container).map(function() {
-    return this.id.replace(id + '-', '');
-  }).get();
-  if (row_ids.length === 0)
-      common.error_alert("Niczego nie zaznaczono");
-  $.each(row_ids, function(i, row_id) {
-    $.ajaxJSON({
-      method: 'post',
-      url: ajax_url,
-      data: {row_id: row_id}
+var perform_group_action = function () {
+    "use strict";
+    var container, id, action, ajax_url, row_ids;
+    container = $(this).parents('div.paginer')[0];
+    id = container.id;
+    action = this.id.replace(id + '-', '');
+    ajax_url = window['ajax_' + action];
+    row_ids = $('.checkrow:checked', container).map(function () {
+        return this.id.replace(id + '-', '');
+    }).get();
+    if (row_ids.length === 0)
+        common.error_alert("Niczego nie zaznaczono");
+    $.each(row_ids, function (i, row_id) {
+        $.ajaxJSON({
+            method: 'post',
+            url: ajax_url,
+            data: {row_id: row_id}
+        });
     });
-  });
-  update_list(id);
+    update_list(id);
 };
 
-var update_filters = function() {
-  "use strict";
-  var list_id = get_list_id(this);
-  var params = $dj.paginer[list_id][1];
-  params.filters = $.extend([], $dj.original_paginer[list_id][1].filters);
-  $('#' + list_id + '-filter_panel').find('li').each(function() {
-    var field_name = $(this).find('.field-choice').val();
-    var lookup = $(this).find('.lookup-choice').val();
-    var value = $(this).find('.value').value();
-    params.filters.push([field_name, lookup, value]);
-  });
-  change_page(list_id, 1);
+var update_filters = function () {
+    "use strict";
+    var list_id = get_list_id(this);
+    var params = $dj.paginer[list_id][1];
+    params.filters = $.extend([], $dj.original_paginer[list_id][1].filters);
+    $('#' + list_id + '-filter_panel').find('li').each(function () {
+        var field_name = $(this).find('.field-choice').val();
+        var lookup = $(this).find('.lookup-choice').val();
+        var value = $(this).find('.value').value();
+        params.filters.push([field_name, lookup, value]);
+    });
+    change_page(list_id, 1);
 };
 
-var update_order = function() {
-  "use strict";
-  var sort_choices = this.parentNode;
-  var list_id = get_list_id(this);
-  var sign = $('.sort-direction', this).text() > 0? '' : '-';
-  var field_name = $('.sort-field-name', this).text();
-  $dj.paginer[list_id][1].order_by = sign + field_name;
-  change_page(list_id, 1);
-  $('.sort-direction', this).text(-(sign + '1'));
-  show_order(list_id);
+var update_order = function () {
+    "use strict";
+    var sort_choices = this.parentNode;
+    var list_id = get_list_id(this);
+    var sign = $('.sort-direction', this).text() > 0 ? '' : '-';
+    var field_name = $('.sort-field-name', this).text();
+    $dj.paginer[list_id][1].order_by = sign + field_name;
+    change_page(list_id, 1);
+    $('.sort-direction', this).text(-(sign + '1'));
+    show_order(list_id);
 };
 
 function show_order(list_id) {
-  "use strict";
-  var sort_choices = $('#' + list_id + '-sort_choices');
-  var current_choice, icon;
-  var order_field = $dj.paginer[list_id][1].order_by;
-  var icon_classes = ['ui-icon-arrow-1-s', 'ui-icon-arrow-1-n'];
-  var sign = order_field[0] === '-';
-  if (sign)
-    order_field = order_field.substr(1);
-  current_choice = $('#' + list_id + '-' + order_field + '-sort_choice');
-  $('.current', sort_choices).removeClass('current');
-  current_choice.addClass('current');
-  if (sign)
-    icon_classes.reverse();
-  icon = $('.sort-icon', current_choice);
-  icon.removeClass(icon_classes[0]).addClass(icon_classes[1]);
+    "use strict";
+    var sort_choices = $('#' + list_id + '-sort_choices');
+    var current_choice, icon;
+    var order_field = $dj.paginer[list_id][1].order_by;
+    var icon_classes = ['ui-icon-arrow-1-s', 'ui-icon-arrow-1-n'];
+    var sign = order_field[0] === '-';
+    if (sign)
+        order_field = order_field.substr(1);
+    current_choice = $('#' + list_id + '-' + order_field + '-sort_choice');
+    $('.current', sort_choices).removeClass('current');
+    current_choice.addClass('current');
+    if (sign)
+        icon_classes.reverse();
+    icon = $('.sort-icon', current_choice);
+    icon.removeClass(icon_classes[0]).addClass(icon_classes[1]);
 }
 paginer.show_order = show_order;
 
 function reload_panel(list_id) {
-  "use strict";
-  var panel = $('#' + list_id + '-filter_panel');
-  var filters =  $dj.paginer[list_id][1].filters;
-  if (panel.length === 0)
-    return;
-  $.each(filters, function(i, filter) {
-    if (i >= $dj.original_paginer[list_id][1].filters.length) {
-      var field_name = filter[0], lookup = filter[1], value = filter[2];
-      new_filter_row(list_id);
-      var row = panel.find('li').last();
-      row.find('.field-choice').val(field_name).change();
-      row.find('.lookup-choice').val(lookup);
-      var value_field = row.find('.value');
-      if (value_field.is(':checkbox')) {
-        if (value)
-          this.checked = 'checked';
-        else
-          this.checked = '';
-      } else {
-        value_field.val(value);
-      }
-    }
-  });
+    "use strict";
+    var panel = $('#' + list_id + '-filter_panel');
+    var filters = $dj.paginer[list_id][1].filters;
+    if (panel.length === 0)
+        return;
+    $.each(filters, function (i, filter) {
+        if (i >= $dj.original_paginer[list_id][1].filters.length) {
+            var field_name = filter[0], lookup = filter[1], value = filter[2];
+            new_filter_row(list_id);
+            var row = panel.find('li').last();
+            row.find('.field-choice').val(field_name).change();
+            row.find('.lookup-choice').val(lookup);
+            var value_field = row.find('.value');
+            if (value_field.is(':checkbox')) {
+                if (value)
+                    this.checked = 'checked';
+                else
+                    this.checked = '';
+            } else {
+                value_field.val(value);
+            }
+        }
+    });
 }
 paginer.reload_panel = reload_panel;
 
 function paginer_bind_events(id) {
-  "use strict";
-  $('div#' + id + ' a.link').click(paginer_link_click);
-  $('div#' + id + ' .group-action').click(perform_group_action);
+    "use strict";
+    $('div#' + id + ' a.link').click(paginer_link_click);
+    $('div#' + id + ' .group-action').click(perform_group_action);
 }
 
 paginer.bind_events = {};
 function paginer_ajax_callback(data, id) {
-  "use strict";
-  paginer_bind_events(id);
-  var list_callback = paginer.bind_events[$dj.paginer[id][0]];
-  if ($.isFunction(list_callback))
-    list_callback(id);
+    "use strict";
+    paginer_bind_events(id);
+    var list_callback = paginer.bind_events[$dj.paginer[id][0]];
+    if ($.isFunction(list_callback))
+        list_callback(id);
 }
 
 function change_page(id, nr, protect_hash) {
-  "use strict";
-  var param = {
-    paginer_id: id,
-    paginer_type: $dj.paginer[id][0],
-    params: $dj.paginer[id][1],
-    page_nr: nr,
-    action: $dj.paginer[id][2],
-    group_actions: $dj.paginer[id][3]
-  };
-  $.ajaxJSON({
-    method: 'post',
-    url: $dj.ajax_paginer,
-    data: param,
-    description: "Pobranie strony",
-    dest: $('#'+id+'.paginer'),
-    callback: paginer_ajax_callback,
-    callback_args: [id]
-  });
-  page_numbers[id] = nr;
-  if (!protect_hash)
-    common.update_hash();
+    "use strict";
+    var param = {
+        paginer_id: id,
+        paginer_type: $dj.paginer[id][0],
+        params: $dj.paginer[id][1],
+        page_nr: nr,
+        action: $dj.paginer[id][2],
+        group_actions: $dj.paginer[id][3]
+    };
+    $.ajaxJSON({
+        method: 'post',
+        url: $dj.ajax_paginer,
+        data: param,
+        description: "Pobranie strony",
+        dest: $('#' + id + '.paginer'),
+        callback: paginer_ajax_callback,
+        callback_args: [id]
+    });
+    page_numbers[id] = nr;
+    if (!protect_hash)
+        common.update_hash();
 }
 
 function update_list(id, protect_hash) {
-  "use strict";
-  change_page(id, get_page_number(id), protect_hash);
+    "use strict";
+    change_page(id, get_page_number(id), protect_hash);
 }
 paginer.update_list = update_list;
 
 var filter_row_counter = 1; // dla niepowtarzalności idów
 function new_filter_row_html(list_id) {
-  "use strict";
-  var new_row_html = $.ajax({
-    type: 'get',
-    url: $dj.ajax_new_filter_row,
-    data: {list_type: $dj.paginer[list_id][0]},
-    async: false
-  }).responseText.replace(/NUM/g, filter_row_counter);
-  filter_row_counter++;
-  return new_row_html;
+    "use strict";
+    var new_row_html = $.ajax({
+        type: 'get',
+        url: $dj.ajax_new_filter_row,
+        data: {list_type: $dj.paginer[list_id][0]},
+        async: false
+    }).responseText.replace(/NUM/g, filter_row_counter);
+    filter_row_counter++;
+    return new_row_html;
 }
 
 paginer.init_widget = {};
-var update_filter_row = function() {
-  "use strict";
-  var num = this.id.split('-')[0].split('_')[2];
-  var row = $(this).closest('li');
-  var list_id = get_list_id($(this).closest('.filter-panel')[0]);
-  var list_type = $dj.paginer[list_id][0];
-  var field_name = $(this).val();
-  row.find('.dynamic-field').remove();
-  var dynamic_field_html = $.ajax({
-    type: 'get',
-    url: $dj.ajax_dynamic_field,
-    data: {list_type: list_type, field_name: field_name},
-    async: false
-  }).responseText.replace(/NUM/g, num);
-  $(dynamic_field_html).insertAfter(this);
-  var init_widget = paginer.init_widget[list_type][field_name];
-  if ($.isFunction(init_widget)) {
-    init_widget(row);
-  }
+var update_filter_row = function () {
+    "use strict";
+    var num = this.id.split('-')[0].split('_')[2];
+    var row = $(this).closest('li');
+    var list_id = get_list_id($(this).closest('.filter-panel')[0]);
+    var list_type = $dj.paginer[list_id][0];
+    var field_name = $(this).val();
+    row.find('.dynamic-field').remove();
+    var dynamic_field_html = $.ajax({
+        type: 'get',
+        url: $dj.ajax_dynamic_field,
+        data: {list_type: list_type, field_name: field_name},
+        async: false
+    }).responseText.replace(/NUM/g, num);
+    $(dynamic_field_html).insertAfter(this);
+    var init_widget = paginer.init_widget[list_type][field_name];
+    if ($.isFunction(init_widget)) {
+        init_widget(row);
+    }
 };
 
 function new_filter_row(list_id) {
-  "use strict";
-  var row_html = new_filter_row_html(list_id);
-  var filter_li = $('<li/>');
-  filter_li.append($(row_html));
-  $('#' + list_id + '-filter_panel').append(filter_li);
-  filter_li.find('.field-choice').change();
+    "use strict";
+    var row_html = new_filter_row_html(list_id);
+    var filter_li = $('<li/>');
+    filter_li.append($(row_html));
+    $('#' + list_id + '-filter_panel').append(filter_li);
+    filter_li.find('.field-choice').change();
 }
 
-var new_filter_click = function() {
-  "use strict";
-  new_filter_row(get_list_id(this));
+var new_filter_click = function () {
+    "use strict";
+    new_filter_row(get_list_id(this));
 };
 
-$(function() {
-  "use strict";
-  $('div.paginer a.link').click(paginer_link_click);
-  $('.group-action').click(perform_group_action);
-  $('.filter-button').click(update_filters);
-  $('.sort-choices .sort-choice').click(update_order);
-  $('.add-filter-row').click(new_filter_click);
-  $(document).on('change', '.field-choice', update_filter_row);
-  $(document).on('click', '.delete-filter', function() {
-    $(this).closest('li').remove();
-  });
-  $(window).trigger('hashchange');
+$(function () {
+    "use strict";
+    $('div.paginer a.link').click(paginer_link_click);
+    $('.group-action').click(perform_group_action);
+    $('.filter-button').click(update_filters);
+    $('.sort-choices .sort-choice').click(update_order);
+    $('.add-filter-row').click(new_filter_click);
+    $(document).on('change', '.field-choice', update_filter_row);
+    $(document).on('click', '.delete-filter', function () {
+        $(this).closest('li').remove();
+    });
+    $(window).trigger('hashchange');
 });
\ No newline at end of file
diff --git a/media/js/pattern-view.js b/media/js/pattern-view.js
index 9250ae3..1f01659 100644
--- a/media/js/pattern-view.js
+++ b/media/js/pattern-view.js
@@ -1,182 +1,189 @@
 var main_field = 'name';
 var qualifier_options = { // copypasta z leksemów...
-  noneSelectedText: 'Wybierz kwalifikatory',
+    noneSelectedText: 'Wybierz kwalifikatory',
     selectedText: '# kwalifikatorów',
     selectedList: 4,
     header: false,
-    create: function() {
-    "use strict";
-    var select = $(this);
-    var selected = select.val();
-    if (selected) {
-      $.each(selected, function(i, value) {
-        toggle_excluded(select, value, false);
-      });
+    create: function () {
+        "use strict";
+        var select = $(this);
+        var selected = select.val();
+        if (selected) {
+            $.each(selected, function (i, value) {
+                toggle_excluded(select, value, false);
+            });
+        }
+    },
+    click: function (event, ui) {
+        "use strict";
+        toggle_excluded(this, ui.value, !ui.checked);
     }
-  },
-  click: function(event, ui) {
-    "use strict";
-    toggle_excluded(this, ui.value, !ui.checked);
-  }
 };
 $.extend(jqgrid, {
-  main_field: main_field,
-  initialColModel: [
-    {name:'name', index:'name', width:150},
-    {name:'type', index:'type', width:70},
-    {name:'part_of_speech', index:'part_of_speech', width:200}
-  ],
-  initialColNames: ['Id', 'Typ', 'Cz. mowy'],
-  initial_sort_rules: [{field: main_field, order: 'asc'}],
-  grid_caption: "Wzory",
-  edit_form_id: 'pattern-edit-form',
-  edit_form_cancel_id: 'pattern-edit-cancel',
-  edit_form_submit_id: 'pattern-edit-submit'
+    main_field: main_field,
+    initialColModel: [
+        {name: 'name', index: 'name', width: 150},
+        {name: 'type', index: 'type', width: 70},
+        {name: 'part_of_speech', index: 'part_of_speech', width: 200}
+    ],
+    initialColNames: ['Id', 'Typ', 'Cz. mowy'],
+    initial_sort_rules: [
+        {field: main_field, order: 'asc'}
+    ],
+    grid_caption: "Wzory",
+    edit_form_id: 'pattern-edit-form',
+    edit_form_cancel_id: 'pattern-edit-cancel',
+    edit_form_submit_id: 'pattern-edit-submit'
 });
 var deleted;
 $dj.reverse_exclusion_classes = {};
 
+function get_id() {
+    "use strict";
+    return parseInt($('#' + jqgrid.edit_form_id).find('[name="id"]').val(), 10);
+}
 
-$.each($dj.exclusion_classes, function(ec, qualifiers) {
-  "use strict";
-  $.each(qualifiers, function(i, q_id) {
-    $dj.reverse_exclusion_classes[q_id] = ec;
-  });
+$.each($dj.exclusion_classes, function (ec, qualifiers) {
+    "use strict";
+    $.each(qualifiers, function (i, q_id) {
+        $dj.reverse_exclusion_classes[q_id] = ec;
+    });
 });
 
 // duuuużo copypasty :(
 function toggle_excluded(select, value, enable) {
-  "use strict";
-  var ec = $dj.reverse_exclusion_classes[Number(value)],
-      values = $dj.exclusion_classes[ec];
-  if (values)
-    $.each(values, function(i, v) {
-      if (v !== Number(value))
-        common.multiselect_toggle(select, v, enable);
-    });
+    "use strict";
+    var ec = $dj.reverse_exclusion_classes[Number(value)],
+        values = $dj.exclusion_classes[ec];
+    if (values)
+        $.each(values, function (i, v) {
+            if (v !== Number(value))
+                common.multiselect_toggle(select, v, enable);
+        });
 }
 
 function init_form_widgets() {
-  "use strict";
-  $(document).on('click', 'span.remove', function() {
-    var li = $(this).closest('li');
-    var name = li.find('input')[0].id;
-    if (name.split('-')[1] !== 'add')
-      deleted.push(name.split('-')[1]);
-    li.remove();
-    jqgrid.show_changed();
-  });
-  $(document).on('click', '.add-ending', function() {
-    var id = $('input[name=id]', $(this).closest('form')).value();
-    var new_row = $(get_new_row_html());
-    $(this).closest('tr').find('.ending-group').append(new_row);
-    $('#ending-list').find('.qualifiers').last().multiselect2(qualifier_options);
-    jqgrid.show_changed();
-  });
+    "use strict";
+    $(document).on('click', 'span.remove', function () {
+        var li = $(this).closest('li');
+        var name = li.find('input')[0].id;
+        if (name.split('-')[1] !== 'add')
+            deleted.push(name.split('-')[1]);
+        li.remove();
+        jqgrid.show_changed();
+    });
+    $(document).on('click', '.add-ending', function () {
+        var id = $('input[name=id]', $(this).closest('form')).value();
+        var new_row = $(get_new_row_html());
+        var this_group = $(this).closest('tr').find('.ending-group');
+        this_group.append(new_row);
+        this_group.find('.qualifiers').last().multiselect2(qualifier_options);
+        jqgrid.show_changed();
+    });
 }
 jqgrid.init_form_widgets = init_form_widgets;
 
 function load_content(id) {
-  "use strict";
-  $.ajaxJSON({
-    method: 'get',
-    url: $dj.ajax_edit_form,
-    dest: $('#edit'),
-    data: {id: id},
-    callback: function() {
-      edit_form_init();
-      //created = Boolean(is_created);
-    }
-  });
-  jqgrid.grid.jqGrid('setGridParam', {'lastSelectedId' : id});
+    "use strict";
+    $.ajaxJSON({
+        method: 'get',
+        url: $dj.ajax_edit_form,
+        dest: $('#edit'),
+        data: {id: id},
+        callback: function () {
+            edit_form_init();
+            //created = Boolean(is_created);
+        }
+    });
+    jqgrid.grid.jqGrid('setGridParam', {'lastSelectedId': id});
 }
 jqgrid.load_content = load_content;
 
 function edit_form_init() {
-  "use strict";
-  $('button', '#edit').button();
-  $('#ending-list.editable').find('.ending-group').sortable().sortable({
-    change: function() {
-      jqgrid.show_changed();
-    }
-  });
-  //$('#ending-list').disableSelection();
-  $('#ending-list').find('.qualifiers').multiselect2(qualifier_options);
-  deleted = [];
-  jqgrid.hide_changed();
-  if (jqgrid.ctrl)
-    jqgrid.ctrl.remove();
+    "use strict";
+    $('button', '#edit').button();
+    $('#ending-list.editable').find('.ending-group').sortable().sortable({
+        change: function () {
+            jqgrid.show_changed();
+        }
+    });
+    //$('#ending-list').disableSelection();
+    $('#ending-list').find('.qualifiers').multiselect2(qualifier_options);
+    deleted = [];
+    jqgrid.hide_changed();
+    if (jqgrid.ctrl)
+        jqgrid.ctrl.remove();
 }
 jqgrid.edit_form_init = edit_form_init;
 
-jqgrid.edit_form_submit = function() {
-  "use strict";
-  var this_form = $(this);
-  var form_data = this_form.serializeArray();
-  form_data.push({name: 'deleted', value: deleted});
-  deleted = [];
-  var ending_list = [];
-  var rows = $('#ending-list').find('tr');
-  $.each(rows, function(i, row){
-    var label = $(row).find('td:eq(0) strong').html();
-    var endings = [];
-    $(row).find('td:eq(1) input').map(function(i, input) {
-      var id = $(input).attr('id').split('-')[1], q_id;
-      if (id === 'add')
-        q_id = '#id_add-' + $(input).attr('id').split('-')[2] + '-qualifiers';
-      else
-        q_id = '#id_end' + id + '-qualifiers';
-      endings.push({
-        id: id,
-        string: $(input).val(),
-        qualifiers: $(q_id).val() || []
-      });
+jqgrid.edit_form_submit = function () {
+    "use strict";
+    var this_form = $(this);
+    var form_data = this_form.serializeArray();
+    form_data.push({name: 'deleted', value: deleted});
+    deleted = [];
+    var ending_list = [];
+    var rows = $('#ending-list').find('tr');
+    $.each(rows, function (i, row) {
+        var label = $(row).find('td:eq(0) strong').html();
+        var endings = [];
+        $(row).find('td:eq(1) input').map(function (i, input) {
+            var id = $(input).attr('id').split('-')[1], q_id;
+            if (id === 'add')
+                q_id = '#id_add-' + $(input).attr('id').split('-')[2] + '-qualifiers';
+            else
+                q_id = '#id_end' + id + '-qualifiers';
+            endings.push({
+                id: id,
+                string: $(input).val(),
+                qualifiers: $(q_id).val() || []
+            });
+        });
+        ending_list.push({base_form_label: label, endings: endings});
     });
-    ending_list.push({base_form_label: label, endings: endings});
-  });
-  form_data.push({name: 'ending_list', value: ending_list});
-  jqgrid.ctrl = getBusyOverlay(
-    'viewport',
-    {color: 'black', opacity: 0.5},
-    {size: 100});
-  $.ajaxJSON({
-    method: 'post',
-    url: $dj.ajax_update_pattern,
-    data: {
-      form_data: form_data
-    },
-    description: "Zapisanie zmian",
-    callback: function() {
-      jqgrid.hide_changed();
-      jqgrid.grid.jqGrid('setGridParam', {'setOnComplete' : true});
-      jqgrid.grid.trigger("reloadGrid");
-    },
-    error_callback: function(xhr, status, error) {
-      common.error_alert(status + ': ' + error);
-      if (jqgrid.ctrl)
-        jqgrid.ctrl.remove();
-    },
-    bad_data_callback: function() {
-      if (jqgrid.ctrl)
-        jqgrid.ctrl.remove();
-      return true;
-    }
-  });
-  return false;
+    form_data.push({name: 'ending_list', value: ending_list});
+    jqgrid.ctrl = getBusyOverlay(
+        'viewport',
+        {color: 'black', opacity: 0.5},
+        {size: 100});
+    $.ajaxJSON({
+        method: 'post',
+        url: $dj.ajax_update_pattern,
+        data: {
+            form_data: form_data
+        },
+        description: "Zapisanie zmian",
+        callback: function () {
+            jqgrid.hide_changed();
+            jqgrid.grid.jqGrid('setGridParam', {'setOnComplete': true});
+            jqgrid.grid.trigger("reloadGrid");
+        },
+        error_callback: function (xhr, status, error) {
+            common.error_alert(status + ': ' + error);
+            if (jqgrid.ctrl)
+                jqgrid.ctrl.remove();
+        },
+        bad_data_callback: function () {
+            if (jqgrid.ctrl)
+                jqgrid.ctrl.remove();
+            return true;
+        }
+    });
+    return false;
 };
 
 var new_row_counter = 1; // potrzebne tylko dla niepowtarzalności idów
 function get_new_row_html() {
-  "use strict";
-  var new_row_html = $.ajax({
-    type: 'get',
-    url: $dj.ajax_new_ending_row,
-    data: {},
-    async: false // w zasadzie się tak nie powinno robić
-  }).responseText;
-  var row_html = new_row_html.replace(/NUM/g, new_row_counter);
-  new_row_counter++;
-  return row_html;
+    "use strict";
+    var new_row_html = $.ajax({
+        type: 'get',
+        url: $dj.ajax_new_ending_row,
+        data: {pattern_id: get_id()},
+        async: false // w zasadzie się tak nie powinno robić
+    }).responseText;
+    var row_html = new_row_html.replace(/NUM/g, new_row_counter);
+    new_row_counter++;
+    return row_html;
 }
 
 jqgrid.add_buttons = function() {};
diff --git a/media/js/sort-dialog.js b/media/js/sort-dialog.js
deleted file mode 100644
index e69de29..0000000
--- a/media/js/sort-dialog.js
+++ /dev/null
diff --git a/paginer/__init__.py b/paginer/__init__.py
index 1926fc1..c4b8404 100644
--- a/paginer/__init__.py
+++ b/paginer/__init__.py
@@ -3,27 +3,30 @@
 from django.conf import settings
 from django.utils.importlib import import_module
 
+
 class PaginerObject(object):
-  def __init__(self, func, template, perm=None, group_action_names=None,
-               filters=None, field_form_class=None):
-    self.queryset = func
-    self.template = template
-    self.perm = perm
-    self.group_action_names = group_action_names
-    self.filters = filters
-    self.filter_field_form = field_form_class
+    def __init__(self, func, template, perm=None, group_action_names=None,
+                 filters=None, field_form_class=None):
+        self.queryset = func
+        self.template = template
+        self.perm = perm
+        self.group_action_names = group_action_names
+        self.filters = filters
+        self.filter_field_form = field_form_class
+
 
 class PaginationTypes(object):
-  def __init__(self):
-    self.dict = {}
+    def __init__(self):
+        self.dict = {}
 
-  def __getitem__(self, name):
-    return self.dict[name]
+    def __getitem__(self, name):
+        return self.dict[name]
+
+    def add(self, name, func, template, perm=None, group_action_names=None,
+            filters=None, field_form_class=None):
+        self.dict[name] = PaginerObject(
+            func, template, perm, group_action_names, filters, field_form_class)
 
-  def add(self, name, func, template, perm=None, group_action_names=None,
-          filters=None, field_form_class=None):
-    self.dict[name] = PaginerObject(
-      func, template, perm, group_action_names, filters, field_form_class)
 
 types = PaginationTypes()
 
@@ -31,25 +34,26 @@ for a in settings.INSTALLED_APPS:
     try:
         mod = import_module('.pagination_types', a)
         for (name, t) in mod.types.iteritems():
-          types.add(name, *t)
+            types.add(name, *t)
     except ImportError:
         pass
 
+
 class PaginationList(object):
-  def __init__(self):
-    self.dict = {}
-
-  def __getitem__(self, id):
-    return self.dict[id]
-
-  def add(self, id, list_type, params, action=None, group_actions=None):
-    self.dict[id] = {
-      'id': id,
-      'type': list_type,
-      'params': params,
-      'template': types[list_type].template,
-      'group_action_names': types[list_type].group_action_names,
-      'action': action,
-      'group_actions': group_actions,
-      'filters': types[list_type].filters,
-    }
\ No newline at end of file
+    def __init__(self):
+        self.dict = {}
+
+    def __getitem__(self, id):
+        return self.dict[id]
+
+    def add(self, id, list_type, params, action=None, group_actions=None):
+        self.dict[id] = {
+            'id': id,
+            'type': list_type,
+            'params': params,
+            'template': types[list_type].template,
+            'group_action_names': types[list_type].group_action_names,
+            'action': action,
+            'group_actions': group_actions,
+            'filters': types[list_type].filters,
+        }
\ No newline at end of file
diff --git a/paginer/ajax.py b/paginer/ajax.py
index 6ad427e..f2f431c 100644
--- a/paginer/ajax.py
+++ b/paginer/ajax.py
@@ -3,31 +3,34 @@
 from common.decorators import ajax, render, render_template
 from paginer import types, PaginationList
 
+
 @render_template('ajax_paginer.html')
 @ajax(method='post', template='ajax_paginer.html')
 def get_page_content(request, paginer_id, paginer_type, params, action, page_nr,
                      group_actions=None):
-  paginer = PaginationList()
-  paginer.add(
-    paginer_id, paginer_type, params, action=action,
-    group_actions=group_actions)
-  return {
-    'paginer': paginer,
-    'id': paginer_id,
-    'page_nr': page_nr,
-  }
+    paginer = PaginationList()
+    paginer.add(
+        paginer_id, paginer_type, params, action=action,
+        group_actions=group_actions)
+    return {
+        'paginer': paginer,
+        'id': paginer_id,
+        'page_nr': page_nr,
+    }
+
 
 @render()
 @ajax(method='get', encode_result=False)
 def new_filter_row(request, list_type):
-  filter_field_form_class = types[list_type].filter_field_form
-  form = filter_field_form_class(prefix='field_NUM')
-  return {'form': form}
+    filter_field_form_class = types[list_type].filter_field_form
+    form = filter_field_form_class(prefix='field_NUM')
+    return {'form': form}
+
 
 @render()
 @ajax(method='get', encode_result=False)
 def field_form(request, list_type, field_name):
-  filter_data = types[list_type].filters[field_name]
-  lookup_choices = filter_data[1]
-  form = filter_data[2](prefix='value_NUM')
-  return {'lookup_choices': lookup_choices, 'form': form}
\ No newline at end of file
+    filter_data = types[list_type].filters[field_name]
+    lookup_choices = filter_data[1]
+    form = filter_data[2](prefix='value_NUM')
+    return {'lookup_choices': lookup_choices, 'form': form}
\ No newline at end of file
diff --git a/paginer/decorators.py b/paginer/decorators.py
index d8c99fd..f50574c 100644
--- a/paginer/decorators.py
+++ b/paginer/decorators.py
@@ -3,22 +3,25 @@
 from functools import wraps
 from django.core.urlresolvers import reverse
 
+
 def paginated(func):
-  """Decorator to be used on view functions that use pagination"""
-  @wraps(func)
-  def new_func(request, *args, **kwargs):
-    output = func(request, *args, **kwargs)
-    if not isinstance(output, dict):
-      return output
-    paginer = output['paginer']
-    js_vars = output.get('js_vars', {})
-    js_vars['paginer'] = dict((id, (d['type'], d['params'], d['action'],
-                                    d['group_actions']))
-      for (id, d) in paginer.dict.iteritems())
-    js_vars['original_paginer'] = js_vars['paginer']
-    js_vars['ajax_paginer'] = reverse('get_page_content')
-    js_vars['ajax_new_filter_row'] = reverse('new_filter_row')
-    js_vars['ajax_dynamic_field'] = reverse('field_form')
-    output['js_vars'] = js_vars
-    return output
-  return new_func
+    """Decorator to be used on view functions that use pagination"""
+
+    @wraps(func)
+    def new_func(request, *args, **kwargs):
+        output = func(request, *args, **kwargs)
+        if not isinstance(output, dict):
+            return output
+        paginer = output['paginer']
+        js_vars = output.get('js_vars', {})
+        js_vars['paginer'] = dict((id, (d['type'], d['params'], d['action'],
+                                        d['group_actions']))
+                                  for (id, d) in paginer.dict.iteritems())
+        js_vars['original_paginer'] = js_vars['paginer']
+        js_vars['ajax_paginer'] = reverse('get_page_content')
+        js_vars['ajax_new_filter_row'] = reverse('new_filter_row')
+        js_vars['ajax_dynamic_field'] = reverse('field_form')
+        output['js_vars'] = js_vars
+        return output
+
+    return new_func
diff --git a/paginer/templates/field_form.html b/paginer/templates/field_form.html
index a502d34..4ca0614 100644
--- a/paginer/templates/field_form.html
+++ b/paginer/templates/field_form.html
@@ -1,8 +1,8 @@
 <span class="dynamic-field">
   <select name="lookup" class="lookup-choice">
-    {% for value, label in lookup_choices %}
-      <option value="{{ value }}">{{ label }}</option>
-    {% endfor %}
+      {% for value, label in lookup_choices %}
+          <option value="{{ value }}">{{ label }}</option>
+      {% endfor %}
   </select>
   {{ form.as_table }}
 </span>
\ No newline at end of file
diff --git a/paginer/templates/filter_panel.html b/paginer/templates/filter_panel.html
index 72c5b7f..f9dd2da 100644
--- a/paginer/templates/filter_panel.html
+++ b/paginer/templates/filter_panel.html
@@ -1,8 +1,8 @@
 {% load i18n %}
 
 <form action="" class="{{ list_id }}_filter_list">
-  <ul>
-    {{ form.as_ul }}
-    <input type="submit" value="{% trans "Pokaż" %}"/>
-  </ul>
+    <ul>
+        {{ form.as_ul }}
+        <input type="submit" value="{% trans "Pokaż" %}"/>
+    </ul>
 </form>
\ No newline at end of file
diff --git a/paginer/templates/new_filter_row.html b/paginer/templates/new_filter_row.html
index 952ef5d..2af135e 100644
--- a/paginer/templates/new_filter_row.html
+++ b/paginer/templates/new_filter_row.html
@@ -1,4 +1,4 @@
 {{ form.field.as_widget }}
 <button type="button" class="delete-filter">
-  <span class="ui-icon ui-icon-closethick"></span>
+    <span class="ui-icon ui-icon-closethick"></span>
 </button>
\ No newline at end of file
diff --git a/paginer/templates/paginated_list.html b/paginer/templates/paginated_list.html
index fd27e2e..53149bc 100644
--- a/paginer/templates/paginated_list.html
+++ b/paginer/templates/paginated_list.html
@@ -1,7 +1,7 @@
 {% load i18n get %}
 
 {% with paginer|get:id as paginer_obj %}
-  <div id="{{ id }}" class="paginer paginer-{{ paginer_obj.type }}">
-    {% include "paginated_list_rows.html" %}
-  </div>
+    <div id="{{ id }}" class="paginer paginer-{{ paginer_obj.type }}">
+        {% include "paginated_list_rows.html" %}
+    </div>
 {% endwith %}
diff --git a/paginer/templates/paginated_list_panel.html b/paginer/templates/paginated_list_panel.html
index 20ef4be..017a72d 100644
--- a/paginer/templates/paginated_list_panel.html
+++ b/paginer/templates/paginated_list_panel.html
@@ -1,30 +1,33 @@
 {% load i18n get %}
 
 {% with paginer|get:id as paginer_obj %}
-  {% if paginer_obj.params.sort_fields %}
-    <ul id={{ id }}-sort_choices class="sort-choices">
-      {% for field in paginer_obj.params.sort_fields %}
-        <li id="{{ id }}-{{ field }}-sort_choice" class="sort-choice">
-          <span class="sort-icon ui-icon"></span>
-          <a>
-            <div class="sort-direction">1</div>
-            <div class="sort-field-name">{{ field }}</div>{% trans field %}</a>
-        {# TODO nazwa pola... #}
-        </li>
-      {% endfor %}
-    </ul>
-    <div class="clearer"></div>
-  {% endif %}
-  {% if paginer_obj.params.filter_fields %}
-    <ul id="{{ id }}-filter_panel" class="filter-panel">
-    </ul>
-    <p>
-      <button type="button" id="{{ id }}-add_filter_row" class="add-filter-row">
-        {% trans "Dodaj filtr" %}
-      </button>
-      <button type="button" id="{{ id }}-filter_button" class="filter-button">
-        {% trans "Filtruj" %}
-      </button>
-    </p>
-  {% endif %}
+    {% if paginer_obj.params.sort_fields %}
+        <ul id={{ id }}-sort_choices class="sort-choices">
+            {% for field in paginer_obj.params.sort_fields %}
+                <li id="{{ id }}-{{ field }}-sort_choice" class="sort-choice">
+                    <span class="sort-icon ui-icon"></span>
+                    <a>
+                        <div class="sort-direction">1</div>
+                        <div class="sort-field-name">{{ field }}</div>
+                        {% trans field %}</a>
+                    {# TODO nazwa pola... #}
+                </li>
+            {% endfor %}
+        </ul>
+        <div class="clearer"></div>
+    {% endif %}
+    {% if paginer_obj.params.filter_fields %}
+        <ul id="{{ id }}-filter_panel" class="filter-panel">
+        </ul>
+        <p>
+            <button type="button" id="{{ id }}-add_filter_row"
+                    class="add-filter-row">
+                {% trans "Dodaj filtr" %}
+            </button>
+            <button type="button" id="{{ id }}-filter_button"
+                    class="filter-button">
+                {% trans "Filtruj" %}
+            </button>
+        </p>
+    {% endif %}
 {% endwith %}
diff --git a/paginer/templates/paginated_list_rows.html b/paginer/templates/paginated_list_rows.html
index 4f53c92..66934e8 100644
--- a/paginer/templates/paginated_list_rows.html
+++ b/paginer/templates/paginated_list_rows.html
@@ -1,24 +1,25 @@
 {% load i18n pagination_tags get %}
 
 {% if page_nr %}
-  {% autopaginate id page_nr ajax %}
+    {% autopaginate id page_nr ajax %}
 {% else %}
-  {% autopaginate id %}
+    {% autopaginate id %}
 {% endif %}
 
 {% with paginer|get:id as paginer_obj %}
-  {% paginate id %}
-  {% for row in paginer_obj.list %}
-    {% include paginer_obj.template %}
-  {% endfor %}
-  {% if not paginer_obj.list %}
-    {% trans "Brak pozycji do wyświetlenia" %}
-  {% else %}
-    {% for action in paginer_obj.group_actions %}
-      <button id="{{ id }}-{{ action }}" class="group-action {{ action }}">
-        {{ paginer_obj.group_action_names|get:action }}
-      </button>
+    {% paginate id %}
+    {% for row in paginer_obj.list %}
+        {% include paginer_obj.template %}
     {% endfor %}
-  {% endif %}
-  {% paginate id %}
+    {% if not paginer_obj.list %}
+        {% trans "Brak pozycji do wyświetlenia" %}
+    {% else %}
+        {% for action in paginer_obj.group_actions %}
+            <button id="{{ id }}-{{ action }}"
+                    class="group-action {{ action }}">
+                {{ paginer_obj.group_action_names|get:action }}
+            </button>
+        {% endfor %}
+    {% endif %}
+    {% paginate id %}
 {% endwith %}
diff --git a/paginer/templates/pagination.html b/paginer/templates/pagination.html
index 6838bd7..bf035a2 100644
--- a/paginer/templates/pagination.html
+++ b/paginer/templates/pagination.html
@@ -1,33 +1,34 @@
 {% load i18n %}
 
 {% if is_paginated %}
-  <div class="paginer-links">
-    {% if page_obj.has_previous %}
-      <a class="link prev">
-        <span class="page_nr">{{ page_obj.previous_page_number }}</span>
-        &lsaquo;&lsaquo; {% trans "previous" %}
-      </a>
-    {% else %}
-      <span class="disabled prev">&lsaquo;&lsaquo; {% trans "previous" %}</span>
-    {% endif %}
-    {% for page in pages %}
-      {% if page %}
-        {% ifequal page page_obj.number %}
-          <span class="current page">{{ page }}</span>
+    <div class="paginer-links">
+        {% if page_obj.has_previous %}
+            <a class="link prev">
+                <span class="page_nr">{{ page_obj.previous_page_number }}</span>
+                &lsaquo;&lsaquo; {% trans "previous" %}
+            </a>
         {% else %}
-          <a class="link page"><span class="page_nr">{{ page }}</span>{{ page }}</a>
-        {% endifequal %}
-      {% else %}
-        ...
-      {% endif %}
-    {% endfor %}
-    {% if page_obj.has_next %}
-      <a class="link next">
-        <span class="page_nr">{{ page_obj.next_page_number }}</span>
-        {% trans "next" %} &rsaquo;&rsaquo;
-      </a>
-    {% else %}
-      <span class="disabled next">{% trans "next" %} &rsaquo;&rsaquo;</span>
-    {% endif %}
-  </div>
+            <span class="disabled prev">&lsaquo;&lsaquo; {% trans "previous" %}</span>
+        {% endif %}
+        {% for page in pages %}
+            {% if page %}
+                {% ifequal page page_obj.number %}
+                    <span class="current page">{{ page }}</span>
+                {% else %}
+                    <a class="link page"><span
+                            class="page_nr">{{ page }}</span>{{ page }}</a>
+                {% endifequal %}
+            {% else %}
+                ...
+            {% endif %}
+        {% endfor %}
+        {% if page_obj.has_next %}
+            <a class="link next">
+                <span class="page_nr">{{ page_obj.next_page_number }}</span>
+                {% trans "next" %} &rsaquo;&rsaquo;
+            </a>
+        {% else %}
+            <span class="disabled next">{% trans "next" %} &rsaquo;&rsaquo;</span>
+        {% endif %}
+    </div>
 {% endif %}
diff --git a/paginer/templatetags/pagination_tags.py b/paginer/templatetags/pagination_tags.py
index ba8210b..76c88e6 100644
--- a/paginer/templatetags/pagination_tags.py
+++ b/paginer/templatetags/pagination_tags.py
@@ -12,158 +12,163 @@ DEFAULT_PAGINATION = getattr(settings, 'PAGINER_DEFAULT_PAGINATION', 10)
 DEFAULT_WINDOW = getattr(settings, 'PAGINER_DEFAULT_WINDOW', 4)
 DEFAULT_ORPHANS = getattr(settings, 'PAGINER_DEFAULT_ORPHANS', 0)
 
+
 @register.simple_tag(takes_context=True)
 def autopaginate(context, id, page=1, ajax=False,
                  paginate_by=DEFAULT_PAGINATION, orphans=DEFAULT_ORPHANS):
-  list_type = context['paginer'][id]['type']
-  params = context['paginer'][id]['params']
-  queryset = types[list_type].queryset(params, context['user'])
-  paginator = Paginator(queryset, paginate_by, orphans)
-  try:
-    page_obj = paginator.page(page)
-  except InvalidPage:
-    context['invalid_page'] = True
-    return u''
-  if ajax and types[list_type].perm:
-    for object in page_obj.object_list:
-      if not types[list_type].perm(context['user'], object, 'view'):
-        context['invalid_permissions'] = True
+    list_type = context['paginer'][id]['type']
+    params = context['paginer'][id]['params']
+    queryset = types[list_type].queryset(params, context['user'])
+    paginator = Paginator(queryset, paginate_by, orphans)
+    try:
+        page_obj = paginator.page(page)
+    except InvalidPage:
+        context['invalid_page'] = True
         return u''
-  context['paginer'][id]['list'] = page_obj.object_list
-  if 'paginator' not in context:
-    context['paginator'] = {}
-  if 'page_obj' not in context:
-    context['page_obj'] = {}
-  context['paginator'][id] = paginator
-  context['page_obj'][id] = page_obj
-  return u''
+    if ajax and types[list_type].perm:
+        for object in page_obj.object_list:
+            if not types[list_type].perm(context['user'], object, 'view'):
+                context['invalid_permissions'] = True
+                return u''
+    context['paginer'][id]['list'] = page_obj.object_list
+    if 'paginator' not in context:
+        context['paginator'] = {}
+    if 'page_obj' not in context:
+        context['page_obj'] = {}
+    context['paginator'][id] = paginator
+    context['page_obj'][id] = page_obj
+    return u''
+
 
 @register.inclusion_tag('pagination.html', takes_context=True)
 def paginate(context, id, window=DEFAULT_WINDOW):
-  try:
-    paginator = context['paginator'][id]
-    page_obj = context['page_obj'][id]
-    page_range = paginator.page_range
-    # First and last are simply the first *n* pages and the last *n* pages,
-    # where *n* is the current window size.
-    first = set(page_range[:window])
-    last = set(page_range[-window:])
-    # Now we look around our current page, making sure that we don't wrap
-    # around.
-    current_start = page_obj.number-1-window
-    if current_start < 0:
-      current_start = 0
-    current_end = page_obj.number-1+window
-    if current_end < 0:
-      current_end = 0
-    current = set(page_range[current_start:current_end])
-    pages = []
-    # If there's no overlap between the first set of pages and the current
-    # set of pages, then there's a possible need for elusion.
-    if len(first.intersection(current)) == 0:
-      first_list = list(first)
-      first_list.sort()
-      second_list = list(current)
-      second_list.sort()
-      pages.extend(first_list)
-      diff = second_list[0] - first_list[-1]
-      # If there is a gap of two, between the last page of the first
-      # set and the first page of the current set, then we're missing a
-      # page.
-      if diff == 2:
-        pages.append(second_list[0] - 1)
-      # If the difference is just one, then there's nothing to be done,
-      # as the pages need no elusion and are correct.
-      elif diff == 1:
-        pass
-      # Otherwise, there's a bigger gap which needs to be signaled for
-      # elusion, by pushing a None value to the page list.
-      else:
-        pages.append(None)
-      pages.extend(second_list)
-    else:
-      unioned = list(first.union(current))
-      unioned.sort()
-      pages.extend(unioned)
-    # If there's no overlap between the current set of pages and the last
-    # set of pages, then there's a possible need for elusion.
-    if len(current.intersection(last)) == 0:
-      second_list = list(last)
-      second_list.sort()
-      diff = second_list[0] - pages[-1]
-      # If there is a gap of two, between the last page of the current
-      # set and the first page of the last set, then we're missing a
-      # page.
-      if diff == 2:
-        pages.append(second_list[0] - 1)
-      # If the difference is just one, then there's nothing to be done,
-      # as the pages need no elusion and are correct.
-      elif diff == 1:
-        pass
-      # Otherwise, there's a bigger gap which needs to be signaled for
-      # elusion, by pushing a None value to the page list.
-      else:
-        pages.append(None)
-      pages.extend(second_list)
-    else:
-      differenced = list(last.difference(current))
-      differenced.sort()
-      pages.extend(differenced)
-    to_return = {
-      'id': id, # chyba niepotrzebne
-      'pages': pages,
-      'page_obj': page_obj,
-      'paginator': paginator,
-      'is_paginated': paginator.count > paginator.per_page,
-    }
-    return to_return
-  except KeyError:
-    return {}
-  except AttributeError:
-    return {}
+    try:
+        paginator = context['paginator'][id]
+        page_obj = context['page_obj'][id]
+        page_range = paginator.page_range
+        # First and last are simply the first *n* pages and the last *n* pages,
+        # where *n* is the current window size.
+        first = set(page_range[:window])
+        last = set(page_range[-window:])
+        # Now we look around our current page, making sure that we don't wrap
+        # around.
+        current_start = page_obj.number - 1 - window
+        if current_start < 0:
+            current_start = 0
+        current_end = page_obj.number - 1 + window
+        if current_end < 0:
+            current_end = 0
+        current = set(page_range[current_start:current_end])
+        pages = []
+        # If there's no overlap between the first set of pages and the current
+        # set of pages, then there's a possible need for elusion.
+        if len(first.intersection(current)) == 0:
+            first_list = list(first)
+            first_list.sort()
+            second_list = list(current)
+            second_list.sort()
+            pages.extend(first_list)
+            diff = second_list[0] - first_list[-1]
+            # If there is a gap of two, between the last page of the first
+            # set and the first page of the current set, then we're missing a
+            # page.
+            if diff == 2:
+                pages.append(second_list[0] - 1)
+            # If the difference is just one, then there's nothing to be done,
+            # as the pages need no elusion and are correct.
+            elif diff == 1:
+                pass
+            # Otherwise, there's a bigger gap which needs to be signaled for
+            # elusion, by pushing a None value to the page list.
+            else:
+                pages.append(None)
+            pages.extend(second_list)
+        else:
+            unioned = list(first.union(current))
+            unioned.sort()
+            pages.extend(unioned)
+            # If there's no overlap between the current set of pages and the last
+        # set of pages, then there's a possible need for elusion.
+        if len(current.intersection(last)) == 0:
+            second_list = list(last)
+            second_list.sort()
+            diff = second_list[0] - pages[-1]
+            # If there is a gap of two, between the last page of the current
+            # set and the first page of the last set, then we're missing a
+            # page.
+            if diff == 2:
+                pages.append(second_list[0] - 1)
+            # If the difference is just one, then there's nothing to be done,
+            # as the pages need no elusion and are correct.
+            elif diff == 1:
+                pass
+            # Otherwise, there's a bigger gap which needs to be signaled for
+            # elusion, by pushing a None value to the page list.
+            else:
+                pages.append(None)
+            pages.extend(second_list)
+        else:
+            differenced = list(last.difference(current))
+            differenced.sort()
+            pages.extend(differenced)
+        to_return = {
+            'id': id, # chyba niepotrzebne
+            'pages': pages,
+            'page_obj': page_obj,
+            'paginator': paginator,
+            'is_paginated': paginator.count > paginator.per_page,
+        }
+        return to_return
+    except KeyError:
+        return {}
+    except AttributeError:
+        return {}
 
 # kolejne dwa tagi wyglądają jak jakieś syfne haki...
 
 @register.inclusion_tag('paginated_list.html', takes_context=True)
 def paginated_list(context, id, page_nr=1, extra=None): # extra=HACK
-  if not extra:
-    extra = {}
-  to_return = dict(extra)
-  to_return.update({
-    'id': id,
-    'page_nr' : page_nr,
-    'paginer': context['paginer'],
-    'ajax': False,
-    'user': context['user'],
-  })
-  return to_return
+    if not extra:
+        extra = {}
+    to_return = dict(extra)
+    to_return.update({
+        'id': id,
+        'page_nr': page_nr,
+        'paginer': context['paginer'],
+        'ajax': False,
+        'user': context['user'],
+    })
+    return to_return
+
 
 @register.inclusion_tag('paginated_list_rows.html', takes_context=True)
 def paginated_list_ajax(context, id, page_nr=1, extra=None): # extra=HACK
-  if not extra:
-    extra = {}
-  to_return = dict(extra)
-  to_return.update({
-    'id': id,
-    'page_nr' : page_nr,
-    'paginer': context['paginer'],
-    'ajax': True,
-    'user': context['user'],
-  })
-  return to_return
+    if not extra:
+        extra = {}
+    to_return = dict(extra)
+    to_return.update({
+        'id': id,
+        'page_nr': page_nr,
+        'paginer': context['paginer'],
+        'ajax': True,
+        'user': context['user'],
+    })
+    return to_return
+
 
 @register.inclusion_tag('paginated_list_panel.html', takes_context=True)
 def paginated_list_panel(context, id, extra=None): # extra=HACK
-  if not extra:
-    extra = {}
-  to_return = dict(extra)
-  to_return.update({
-    'id': id,
-    'paginer': context['paginer'],
-    'user': context['user'],
-  })
-  return to_return
+    if not extra:
+        extra = {}
+    to_return = dict(extra)
+    to_return.update({
+        'id': id,
+        'paginer': context['paginer'],
+        'user': context['user'],
+    })
+    return to_return
+
 
 @register.inclusion_tag('filter_panel.html')
 def filter_panel(list_id, form):
-  return {'list_id': list_id, 'form': form}
+    return {'list_id': list_id, 'form': form}
diff --git a/settings.py b/settings.py
index 4aa5cdf..f2b3173 100644
--- a/settings.py
+++ b/settings.py
@@ -3,7 +3,6 @@
 
 import os.path
 import database_data
-from django.core.urlresolvers import reverse
 
 PROJECT_PATH = os.path.dirname(__file__)
 
@@ -16,7 +15,7 @@ SQL_STACKTRACE = False
 INTERNAL_IPS = ('127.0.0.1',)
 
 ADMINS = (
-    # ('Your Name', 'your_email@domain.com'),
+# ('Your Name', 'your_email@domain.com'),
 )
 
 MANAGERS = ADMINS
@@ -76,7 +75,7 @@ SECRET_KEY = 'odly=^#uh*w!-7@da1vm!(#s%$l2nlxrkw4^5f1x50(d=31gr0'
 TEMPLATE_LOADERS = (
     'django.template.loaders.filesystem.Loader',
     'django.template.loaders.app_directories.Loader',
-#     'django.template.loaders.eggs.Loader',
+    #     'django.template.loaders.eggs.Loader',
 )
 
 MIDDLEWARE_CLASSES = (
@@ -93,7 +92,7 @@ MIDDLEWARE_CLASSES = (
 ROOT_URLCONF = 'lexeme_forge.urls_main'
 
 TEMPLATE_DIRS = (
-    os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
+    os.path.join(os.path.dirname(__file__), 'templates').replace('\\', '/'),
 )
 
 INSTALLED_APPS = (
diff --git a/skrypty/adjadv.py b/skrypty/adjadv.py
index 678a71e..1031aa2 100644
--- a/skrypty/adjadv.py
+++ b/skrypty/adjadv.py
@@ -3,29 +3,32 @@
 
 import sys
 
+
 def get_lines():
-  first = True
-  search = False
-  lines = []
-  for line in sys.stdin:
-    if first:
-      if '\tadj:' in line:
-        search = True
-        adj = line.split()[0]
-        nie_prefix = ''
-        while adj.startswith(nie_prefix):
-          nie_prefix += 'nie'
-      first = False
-    if search and '\tadv:pos' in line:
-      if not line.startswith(nie_prefix):
-        lines.append('%s %s\n' % (line.split()[0], adj))#, line.split()[2]))
-      else:
-        print>>sys.stderr, line.split()[0], adj
-    if line == '\n':
-      first = True
-      search = False
-  return lines
+    first = True
+    search = False
+    lines = []
+    for line in sys.stdin:
+        if first:
+            if '\tadj:' in line:
+                search = True
+                adj = line.split()[0]
+                nie_prefix = ''
+                while adj.startswith(nie_prefix):
+                    nie_prefix += 'nie'
+            first = False
+        if search and '\tadv:pos' in line:
+            if not line.startswith(nie_prefix):
+                lines.append(
+                    '%s %s\n' % (line.split()[0], adj))#, line.split()[2]))
+            else:
+                print>> sys.stderr, line.split()[0], adj
+        if line == '\n':
+            first = True
+            search = False
+    return lines
+
 
 if __name__ == '__main__':
-  lines = get_lines()
-  sys.stdout.write(''.join(lines))
+    lines = get_lines()
+    sys.stdout.write(''.join(lines))
diff --git a/skrypty/base_forms.py b/skrypty/base_forms.py
index 219f4be..0967267 100644
--- a/skrypty/base_forms.py
+++ b/skrypty/base_forms.py
@@ -3,17 +3,19 @@
 
 import sys
 
+
 def get_lines():
-  first = True
-  lines = []
-  for line in sys.stdin:
-    if first:
-      lines.append(line)
-      first = False
-    if line == '\n':
-      first = True
-  return lines
+    first = True
+    lines = []
+    for line in sys.stdin:
+        if first:
+            lines.append(line)
+            first = False
+        if line == '\n':
+            first = True
+    return lines
+
 
 if __name__ == '__main__':
-  lines = get_lines()
-  sys.stdout.write(''.join(lines))
+    lines = get_lines()
+    sys.stdout.write(''.join(lines))
diff --git a/skrypty/filter_forms.py b/skrypty/filter_forms.py
index 016c547..d023db3 100755
--- a/skrypty/filter_forms.py
+++ b/skrypty/filter_forms.py
@@ -2,65 +2,73 @@
 #-*- coding:utf-8 -*-
 
 def test_subst(tag):
-  return tag.startswith('subst') and not tag.startswith('subst:ger')
+    return tag.startswith('subst') and not tag.startswith('subst:ger')
+
 
 def test_v(tag):
-  prefixes = ('verb', 'subst:ger', 'pact', 'ppas', 'pant', 'pcon')
-  for prefix in prefixes:
-    if tag.startswith(prefix):
-      return True
-  return False
+    prefixes = ('verb', 'subst:ger', 'pact', 'ppas', 'pant', 'pcon')
+    for prefix in prefixes:
+        if tag.startswith(prefix):
+            return True
+    return False
+
 
 def test_ndm(tag):
-  prefixes = ('adv', 'conj', 'interj', 'prep', 'qub', 'xxx')
-  for prefix in prefixes:
-    if tag.startswith(prefix):
-      return prefix != 'adv' or not tag.endswith(':sup')
-  return False
+    prefixes = ('adv', 'conj', 'interj', 'prep', 'qub', 'xxx')
+    for prefix in prefixes:
+        if tag.startswith(prefix):
+            return prefix != 'adv' or not tag.endswith(':sup')
+    return False
+
 
 def test_adj(tag):
-  return tag.startswith('adj') and not tag.endswith(':sup')
+    return tag.startswith('adj') and not tag.endswith(':sup')
+
 
 def test_other(tag):
-  return not (test_subst(tag) or test_v(tag) or test_ndm(tag) or test_adj(tag))
+    return not (
+    test_subst(tag) or test_v(tag) or test_ndm(tag) or test_adj(tag))
+
 
 def test(lc, tag):
-  if lc == 'subst':
-    return test_subst(tag)
-  elif lc == 'v':
-    return test_v(tag)
-  elif lc == 'ndm':
-    return test_ndm(tag)
-  elif lc == 'adj':
-    return test_adj(tag)
-  elif lc == 'other':
-    return test_other(tag)
-  else:
-    return tag.startswith(lc)
+    if lc == 'subst':
+        return test_subst(tag)
+    elif lc == 'v':
+        return test_v(tag)
+    elif lc == 'ndm':
+        return test_ndm(tag)
+    elif lc == 'adj':
+        return test_adj(tag)
+    elif lc == 'other':
+        return test_other(tag)
+    else:
+        return tag.startswith(lc)
+
 
 if __name__ == '__main__':
-  import sys
-  lc = sys.argv[1]
-  with open(sys.argv[2]) as file:
-    state = 'query'
-    negated = []
-    for line in file:
-      line = line.rstrip('\n')
-      if line == '':
-        if state == 'print':
-          print
-          if negated:
-            for line in negated:
-              print line
-            print
-            negated = []
+    import sys
+
+    lc = sys.argv[1]
+    with open(sys.argv[2]) as file:
         state = 'query'
-      elif state == 'query':
-        tag = line.split('\t')[1]
-        if test(lc, tag):
-          print line
-          state = 'print'
-        else:
-          state = 'wait'
-      elif state == 'print':
-        print line
+        negated = []
+        for line in file:
+            line = line.rstrip('\n')
+            if line == '':
+                if state == 'print':
+                    print
+                    if negated:
+                        for line in negated:
+                            print line
+                        print
+                        negated = []
+                state = 'query'
+            elif state == 'query':
+                tag = line.split('\t')[1]
+                if test(lc, tag):
+                    print line
+                    state = 'print'
+                else:
+                    state = 'wait'
+            elif state == 'print':
+                print line
diff --git a/skrypty/wytnij.py b/skrypty/wytnij.py
index 4a5fb78..2f5bb45 100755
--- a/skrypty/wytnij.py
+++ b/skrypty/wytnij.py
@@ -3,26 +3,28 @@
 
 import sys
 
+
 def get_lines(word):
-  first = True
-  cut = False
-  maybe_next = False
-  lines = []
-  for line in sys.stdin:
-    if first:
-      if line.startswith(word + '\t'):
-        cut = True
-      elif maybe_next:
-        break # już nie ma więcej homonimów
-      first = False
-    if cut:
-      lines.append(line)
-    if line == '\n':
-      if cut:
-        maybe_next = True
-      first = True
-  return lines
+    first = True
+    cut = False
+    maybe_next = False
+    lines = []
+    for line in sys.stdin:
+        if first:
+            if line.startswith(word + '\t'):
+                cut = True
+            elif maybe_next:
+                break # już nie ma więcej homonimów
+            first = False
+        if cut:
+            lines.append(line)
+        if line == '\n':
+            if cut:
+                maybe_next = True
+            first = True
+    return lines
+
 
 if __name__ == '__main__':
-  lines = get_lines(sys.argv[1])
-  sys.stdout.write(''.join(lines))
+    lines = get_lines(sys.argv[1])
+    sys.stdout.write(''.join(lines))
diff --git a/skrypty/wytnij_wiele.py b/skrypty/wytnij_wiele.py
index 483aa41..329876b 100755
--- a/skrypty/wytnij_wiele.py
+++ b/skrypty/wytnij_wiele.py
@@ -3,24 +3,26 @@
 
 import sys
 
+
 def get_lines(words, reverse):
-  first = True
-  cut = False
-  lines = []
-  for line in sys.stdin:
-    if first:
-      word = line.split('\t')[0].decode('utf-8')
-      cut = (word in words) != reverse
-      first = False
-    if cut:
-      lines.append(line)
-    if line == '\n':
-      first = True
-  return lines
+    first = True
+    cut = False
+    lines = []
+    for line in sys.stdin:
+        if first:
+            word = line.split('\t')[0].decode('utf-8')
+            cut = (word in words) != reverse
+            first = False
+        if cut:
+            lines.append(line)
+        if line == '\n':
+            first = True
+    return lines
+
 
 if __name__ == '__main__':
-  reverse = len(sys.argv) > 2 and sys.argv[2] == '-r'
-  with open(sys.argv[1]) as words_file:
-    words = [line.strip().decode('utf-8') for line in words_file]
-  lines = get_lines(words, reverse)
-  sys.stdout.write(''.join(lines))
+    reverse = len(sys.argv) > 2 and sys.argv[2] == '-r'
+    with open(sys.argv[1]) as words_file:
+        words = [line.strip().decode('utf-8') for line in words_file]
+    lines = get_lines(words, reverse)
+    sys.stdout.write(''.join(lines))
diff --git a/sql/add_unique.sql b/sql/add_unique.sql
index a8393cb..1013f75 100644
--- a/sql/add_unique.sql
+++ b/sql/add_unique.sql
@@ -1,2 +1,2 @@
-alter table odmieniasie add unique (l_id, oind) deferrable initially deferred;
-alter table zakonczenia add unique (w_id, efobaz, zind) deferrable initially deferred;
+ALTER TABLE odmieniasie ADD UNIQUE (l_id, oind) DEFERRABLE INITIALLY DEFERRED;
+ALTER TABLE zakonczenia ADD UNIQUE (w_id, efobaz, zind) DEFERRABLE INITIALLY DEFERRED;
diff --git a/sql/delete_adj.sql b/sql/delete_adj.sql
index 844bac2..491abc0 100644
--- a/sql/delete_adj.sql
+++ b/sql/delete_adj.sql
@@ -1,8 +1,40 @@
-SELECT set_config('var.user_id', '0', false);
-delete FROM odsylacze WHERE l_id_do in (select id from leksemy where ("leksemy"."slownik" = 'Morfologik' and pos in ('adj', 'adjcom')));
-delete FROM odsylacze WHERE l_id_od in (select id from leksemy where ("leksemy"."slownik" = 'Morfologik' and leksemy.pos in ('adj', 'adjcom')));
-delete FROM odmieniasie WHERE l_id in (select id from leksemy where ("leksemy"."slownik" = 'Morfologik' and leksemy.pos in ('adj', 'adjcom')));
-delete FROM leksemy_w_slownikach WHERE l_id in (select id from leksemy where leksemy.pos in ('adj', 'adjcom') and slownik = 'Morfologik');
-delete FROM leksemy_w_slownikach WHERE l_id in (select id from leksemy where leksemy.pos in ('adj', 'adjcom')) and slownik = 'Morfologik';
-delete FROM kwalifikatory_leksemow WHERE lexeme_id in (select id from leksemy where leksemy.pos in ('adj', 'adjcom') and slownik = 'Morfologik');
-delete FROM "leksemy" WHERE ("leksemy"."slownik" = 'Morfologik' and leksemy.pos in ('adj', 'adjcom'));
+SELECT
+    set_config('var.user_id', '0', FALSE);
+DELETE FROM odsylacze
+WHERE l_id_do IN (SELECT
+                      id
+                  FROM leksemy
+                  WHERE ("leksemy"."slownik" = 'Morfologik' AND
+                         pos IN ('adj', 'adjcom')));
+DELETE FROM odsylacze
+WHERE l_id_od IN (SELECT
+                      id
+                  FROM leksemy
+                  WHERE ("leksemy"."slownik" = 'Morfologik' AND
+                         leksemy.pos IN ('adj', 'adjcom')));
+DELETE FROM odmieniasie
+WHERE l_id IN (SELECT
+                   id
+               FROM leksemy
+               WHERE ("leksemy"."slownik" = 'Morfologik' AND
+                      leksemy.pos IN ('adj', 'adjcom')));
+DELETE FROM leksemy_w_slownikach
+WHERE l_id IN (SELECT
+                   id
+               FROM leksemy
+               WHERE leksemy.pos IN ('adj', 'adjcom') AND
+                     slownik = 'Morfologik');
+DELETE FROM leksemy_w_slownikach
+WHERE l_id IN (SELECT
+                   id
+               FROM leksemy
+               WHERE leksemy.pos IN ('adj', 'adjcom')) AND
+      slownik = 'Morfologik';
+DELETE FROM kwalifikatory_leksemow
+WHERE lexeme_id IN (SELECT
+                        id
+                    FROM leksemy
+                    WHERE leksemy.pos IN ('adj', 'adjcom') AND
+                          slownik = 'Morfologik');
+DELETE FROM "leksemy"
+WHERE ("leksemy"."slownik" = 'Morfologik' AND leksemy.pos IN ('adj', 'adjcom'));
diff --git a/sql/delete_data.sql b/sql/delete_data.sql
index 7ddd244..379b5fb 100644
--- a/sql/delete_data.sql
+++ b/sql/delete_data.sql
@@ -1,39 +1,40 @@
-SELECT set_config('var.user_id', '0', false);
-delete from dictionary_inputform;
-delete from dictionary_inputlexeme;
-delete from history;
-delete from dictionary_savedexportdata;
-delete from dictionary_savedfilter;
-delete from dictionary_lexemeform;
-delete from paradygmatywsjp;
-delete from naglowki_tabel;
-delete from komorki_tabel;
-delete from klatki;
-delete from szablony_tabel;
-delete from warianty;
-delete from odsylacze;
-delete from typyodsylaczy;
-delete from leksemy_w_slownikach;
-delete from kwalifikatory_odmieniasiow;
-delete from odmieniasie;
-delete from dictionary_lexemecv;
-delete from kwalifikatory_leksemow;
-delete from dictionary_lexemeav;
-delete from dictionary_lexemeattributevalue;
-delete from dictionary_lexemeattribute_inflection_characteristics;
-delete from dictionary_lexemeattribute_parts_of_speech;
-delete from dictionary_lexemeattribute;
-delete from leksemy;
-delete from kwalifikatory_zakonczen;
-delete from zakonczenia;
-delete from wzory;
-delete from typywzorow;
-delete from charfle;
-delete from efobazy;
-delete from klasygramatyczne;
-delete from czescimowy;
-delete from kwalifikatory;
-delete from klasy_wykluczania;
+SELECT
+    set_config('var.user_id', '0', FALSE);
+DELETE FROM dictionary_inputform;
+DELETE FROM dictionary_inputlexeme;
+DELETE FROM history;
+DELETE FROM dictionary_savedexportdata;
+DELETE FROM dictionary_savedfilter;
+DELETE FROM dictionary_lexemeform;
+DELETE FROM paradygmatywsjp;
+DELETE FROM naglowki_tabel;
+DELETE FROM komorki_tabel;
+DELETE FROM klatki;
+DELETE FROM szablony_tabel;
+DELETE FROM warianty;
+DELETE FROM odsylacze;
+DELETE FROM typyodsylaczy;
+DELETE FROM leksemy_w_slownikach;
+DELETE FROM kwalifikatory_odmieniasiow;
+DELETE FROM odmieniasie;
+DELETE FROM dictionary_lexemecv;
+DELETE FROM kwalifikatory_leksemow;
+DELETE FROM dictionary_lexemeav;
+DELETE FROM dictionary_lexemeattributevalue;
+DELETE FROM dictionary_lexemeattribute_inflection_characteristics;
+DELETE FROM dictionary_lexemeattribute_parts_of_speech;
+DELETE FROM dictionary_lexemeattribute;
+DELETE FROM leksemy;
+DELETE FROM kwalifikatory_zakonczen;
+DELETE FROM zakonczenia;
+DELETE FROM wzory;
+DELETE FROM typywzorow;
+DELETE FROM charfle;
+DELETE FROM efobazy;
+DELETE FROM klasygramatyczne;
+DELETE FROM czescimowy;
+DELETE FROM kwalifikatory;
+DELETE FROM klasy_wykluczania;
 
 --delete from wartosci_klasyfikacji;
 --delete from klasyfikacje;
diff --git a/sql/delete_ndm.sql b/sql/delete_ndm.sql
index 9f0148a..3fdc633 100644
--- a/sql/delete_ndm.sql
+++ b/sql/delete_ndm.sql
@@ -1,8 +1,44 @@
-SELECT set_config('var.user_id', '0', false);
-delete FROM odsylacze WHERE l_id_od in (select id from leksemy where ("leksemy"."slownik" = 'Morfologik' and pos in ('adv', 'advcom', 'conj', 'burk', 'interj', 'prep', 'qub', 'comp', 'advndm')));
-delete FROM odsylacze WHERE l_id_do in (select id from leksemy where ("leksemy"."slownik" = 'Morfologik' and pos in ('adv', 'advcom', 'conj', 'burk', 'interj', 'prep', 'qub', 'comp', 'advndm')));
-delete FROM odmieniasie WHERE l_id in (select id from leksemy where ("leksemy"."slownik" = 'Morfologik' and leksemy.pos in ('adv', 'advcom', 'conj', 'burk', 'interj', 'prep', 'qub', 'comp', 'advndm')));
-delete FROM leksemy_w_slownikach WHERE l_id in (select id from leksemy where leksemy.pos in ('adv', 'advcom', 'conj', 'burk', 'interj', 'prep', 'qub', 'comp', 'advndm') and slownik = 'Morfologik');
-delete FROM leksemy_w_slownikach WHERE l_id in (select id from leksemy where leksemy.pos in ('adv', 'advcom', 'conj', 'burk', 'interj', 'prep', 'qub', 'comp', 'advndm')) and slownik = 'Morfologik';
-delete FROM kwalifikatory_leksemow WHERE lexeme_id in (select id from leksemy where leksemy.pos in ('adv', 'advcom', 'conj', 'burk', 'interj', 'prep', 'qub', 'comp', 'advndm') and slownik = 'Morfologik');
-delete FROM "leksemy" WHERE ("leksemy"."slownik" = 'Morfologik' and leksemy.pos in ('adv', 'advcom', 'conj', 'burk', 'interj', 'prep', 'qub', 'comp', 'advndm'));
+SELECT
+    set_config('var.user_id', '0', FALSE);
+DELETE FROM odsylacze
+WHERE l_id_od IN (SELECT
+                      id
+                  FROM leksemy
+                  WHERE ("leksemy"."slownik" = 'Morfologik' AND pos IN
+                                                                ('adv', 'advcom', 'conj', 'burk', 'interj', 'prep', 'qub', 'comp', 'advndm')));
+DELETE FROM odsylacze
+WHERE l_id_do IN (SELECT
+                      id
+                  FROM leksemy
+                  WHERE ("leksemy"."slownik" = 'Morfologik' AND pos IN
+                                                                ('adv', 'advcom', 'conj', 'burk', 'interj', 'prep', 'qub', 'comp', 'advndm')));
+DELETE FROM odmieniasie
+WHERE l_id IN (SELECT
+                   id
+               FROM leksemy
+               WHERE ("leksemy"."slownik" = 'Morfologik' AND leksemy.pos IN
+                                                             ('adv', 'advcom', 'conj', 'burk', 'interj', 'prep', 'qub', 'comp', 'advndm')));
+DELETE FROM leksemy_w_slownikach
+WHERE l_id IN (SELECT
+                   id
+               FROM leksemy
+               WHERE leksemy.pos IN
+                     ('adv', 'advcom', 'conj', 'burk', 'interj', 'prep', 'qub', 'comp', 'advndm')
+                     AND slownik = 'Morfologik');
+DELETE FROM leksemy_w_slownikach
+WHERE l_id IN (SELECT
+                   id
+               FROM leksemy
+               WHERE leksemy.pos IN
+                     ('adv', 'advcom', 'conj', 'burk', 'interj', 'prep', 'qub', 'comp', 'advndm'))
+      AND slownik = 'Morfologik';
+DELETE FROM kwalifikatory_leksemow
+WHERE lexeme_id IN (SELECT
+                        id
+                    FROM leksemy
+                    WHERE leksemy.pos IN
+                          ('adv', 'advcom', 'conj', 'burk', 'interj', 'prep', 'qub', 'comp', 'advndm')
+                          AND slownik = 'Morfologik');
+DELETE FROM "leksemy"
+WHERE ("leksemy"."slownik" = 'Morfologik' AND leksemy.pos IN
+                                              ('adv', 'advcom', 'conj', 'burk', 'interj', 'prep', 'qub', 'comp', 'advndm'));
diff --git a/sql/delete_subst.sql b/sql/delete_subst.sql
index c6078e9..d441322 100644
--- a/sql/delete_subst.sql
+++ b/sql/delete_subst.sql
@@ -1,8 +1,41 @@
-SELECT set_config('var.user_id', '0', false);
-delete FROM odsylacze WHERE l_id_do in (select id from leksemy where ("leksemy"."slownik" = 'Morfologik' and pos in ('subst', 'osc', 'skrs')));
-delete FROM odsylacze WHERE l_id_od in (select id from leksemy where ("leksemy"."slownik" = 'Morfologik' and leksemy.pos in ('subst', 'osc', 'skrs')));
-delete FROM odmieniasie WHERE l_id in (select id from leksemy where ("leksemy"."slownik" = 'Morfologik' and leksemy.pos in ('subst', 'osc', 'skrs')));
-delete FROM leksemy_w_slownikach WHERE l_id in (select id from leksemy where leksemy.pos in ('subst', 'osc', 'skrs') and slownik = 'Morfologik');
-delete FROM leksemy_w_slownikach WHERE l_id in (select id from leksemy where leksemy.pos in ('subst', 'osc', 'skrs')) and slownik = 'Morfologik';
-delete FROM kwalifikatory_leksemow WHERE lexeme_id in (select id from leksemy where leksemy.pos in ('subst', 'osc', 'skrs') and slownik = 'Morfologik');
-delete FROM "leksemy" WHERE ("leksemy"."slownik" = 'Morfologik' and leksemy.pos in ('subst', 'osc', 'skrs'));
+SELECT
+    set_config('var.user_id', '0', FALSE);
+DELETE FROM odsylacze
+WHERE l_id_do IN (SELECT
+                      id
+                  FROM leksemy
+                  WHERE ("leksemy"."slownik" = 'Morfologik' AND
+                         pos IN ('subst', 'osc', 'skrs')));
+DELETE FROM odsylacze
+WHERE l_id_od IN (SELECT
+                      id
+                  FROM leksemy
+                  WHERE ("leksemy"."slownik" = 'Morfologik' AND
+                         leksemy.pos IN ('subst', 'osc', 'skrs')));
+DELETE FROM odmieniasie
+WHERE l_id IN (SELECT
+                   id
+               FROM leksemy
+               WHERE ("leksemy"."slownik" = 'Morfologik' AND
+                      leksemy.pos IN ('subst', 'osc', 'skrs')));
+DELETE FROM leksemy_w_slownikach
+WHERE l_id IN (SELECT
+                   id
+               FROM leksemy
+               WHERE leksemy.pos IN ('subst', 'osc', 'skrs') AND
+                     slownik = 'Morfologik');
+DELETE FROM leksemy_w_slownikach
+WHERE l_id IN (SELECT
+                   id
+               FROM leksemy
+               WHERE leksemy.pos IN ('subst', 'osc', 'skrs')) AND
+      slownik = 'Morfologik';
+DELETE FROM kwalifikatory_leksemow
+WHERE lexeme_id IN (SELECT
+                        id
+                    FROM leksemy
+                    WHERE leksemy.pos IN ('subst', 'osc', 'skrs') AND
+                          slownik = 'Morfologik');
+DELETE FROM "leksemy"
+WHERE ("leksemy"."slownik" = 'Morfologik' AND
+       leksemy.pos IN ('subst', 'osc', 'skrs'));
diff --git a/sql/delete_unique.sql b/sql/delete_unique.sql
index 9e72f1b..476cf0c 100644
--- a/sql/delete_unique.sql
+++ b/sql/delete_unique.sql
@@ -1,5 +1,8 @@
 \t
 
-select 'alter table zakonczenia drop constraint '|| constraint_name || ';' from information_schema.table_constraints where constraint_type = 'UNIQUE' and table_name = 'zakonczenia';
+SELECT 'alter table zakonczenia drop constraint '|| constraint_name || ';' FROM information_schema.table_constraints WHERE constraint_type = 'UNIQUE' AND table_name = 'zakonczenia';
 
-select 'alter table odmieniasie drop constraint '|| constraint_name || ';' from information_schema.table_constraints where constraint_type = 'UNIQUE' and table_name = 'odmieniasie';
+SELECT
+    'alter table odmieniasie drop constraint ' || constraint_name || ';'
+FROM information_schema.table_constraints
+WHERE constraint_type = 'UNIQUE' AND table_name = 'odmieniasie';
diff --git a/sql/delete_v.sql b/sql/delete_v.sql
index dc99888..9b5d61a 100644
--- a/sql/delete_v.sql
+++ b/sql/delete_v.sql
@@ -1,8 +1,41 @@
-SELECT set_config('var.user_id', '0', false);
-delete FROM odsylacze WHERE l_id_do in (select id from leksemy where ("leksemy"."slownik" = 'Morfologik' and pos in ('v', 'ger', 'pact', 'ppas', 'appas')));
-delete FROM odsylacze WHERE l_id_od in (select id from leksemy where ("leksemy"."slownik" = 'Morfologik' and pos in ('v', 'ger', 'pact', 'ppas', 'appas')));
-delete FROM odmieniasie WHERE l_id in (select id from leksemy where ("leksemy"."slownik" = 'Morfologik' and leksemy.pos in ('v', 'ger', 'pact', 'ppas', 'appas')));
-delete FROM leksemy_w_slownikach WHERE l_id in (select id from leksemy where leksemy.pos in ('v', 'ger', 'pact', 'ppas', 'appas') and slownik = 'Morfologik');
-delete FROM leksemy_w_slownikach WHERE l_id in (select id from leksemy where leksemy.pos in ('v', 'ger', 'pact', 'ppas', 'appas')) and slownik = 'Morfologik';
-delete FROM kwalifikatory_leksemow WHERE lexeme_id in (select id from leksemy where leksemy.pos in ('v', 'ger', 'pact', 'ppas', 'appas') and slownik = 'Morfologik');
-delete FROM "leksemy" WHERE ("leksemy"."slownik" = 'Morfologik' and leksemy.pos in ('v', 'ger', 'pact', 'ppas', 'appas'));
+SELECT
+    set_config('var.user_id', '0', FALSE);
+DELETE FROM odsylacze
+WHERE l_id_do IN (SELECT
+                      id
+                  FROM leksemy
+                  WHERE ("leksemy"."slownik" = 'Morfologik' AND
+                         pos IN ('v', 'ger', 'pact', 'ppas', 'appas')));
+DELETE FROM odsylacze
+WHERE l_id_od IN (SELECT
+                      id
+                  FROM leksemy
+                  WHERE ("leksemy"."slownik" = 'Morfologik' AND
+                         pos IN ('v', 'ger', 'pact', 'ppas', 'appas')));
+DELETE FROM odmieniasie
+WHERE l_id IN (SELECT
+                   id
+               FROM leksemy
+               WHERE ("leksemy"."slownik" = 'Morfologik' AND
+                      leksemy.pos IN ('v', 'ger', 'pact', 'ppas', 'appas')));
+DELETE FROM leksemy_w_slownikach
+WHERE l_id IN (SELECT
+                   id
+               FROM leksemy
+               WHERE leksemy.pos IN ('v', 'ger', 'pact', 'ppas', 'appas') AND
+                     slownik = 'Morfologik');
+DELETE FROM leksemy_w_slownikach
+WHERE l_id IN (SELECT
+                   id
+               FROM leksemy
+               WHERE leksemy.pos IN ('v', 'ger', 'pact', 'ppas', 'appas')) AND
+      slownik = 'Morfologik';
+DELETE FROM kwalifikatory_leksemow
+WHERE lexeme_id IN (SELECT
+                        id
+                    FROM leksemy
+                    WHERE leksemy.pos IN ('v', 'ger', 'pact', 'ppas', 'appas')
+                          AND slownik = 'Morfologik');
+DELETE FROM "leksemy"
+WHERE ("leksemy"."slownik" = 'Morfologik' AND
+       leksemy.pos IN ('v', 'ger', 'pact', 'ppas', 'appas'));
diff --git a/sql/drop.sql b/sql/drop.sql
index 4015061..8d194c4 100644
--- a/sql/drop.sql
+++ b/sql/drop.sql
@@ -1,48 +1,48 @@
 -- bardzo nieaktualne!
- drop table "auth_group_permissions" cascade;
- drop table "auth_group" cascade;
- drop table "auth_user_user_permissions" cascade;
- drop table "auth_user_groups" cascade;
- drop table "auth_message" cascade;
- drop table "auth_permission" cascade;
- drop table "django_session" cascade;
- drop table "registration_registrationprofile" cascade;
- drop table "wartosci_klasyfikacji" cascade;
- drop table "czescimowy" cascade;
- drop table "klasygramatyczne" cascade;
- drop table "kwalifikatory_leksemow" cascade;
- drop table "kwalifikatory_odmieniasiow" cascade;
- drop table "dictionary_lexemecv" cascade;
- drop table "odmieniasie" cascade;
- drop table "zakonczenia" cascade;
- drop table "kwalifikatory_zakonczen" cascade;
- drop table "klasyfikacje" cascade;
- drop table "kwalifikatory" cascade;
- drop table "leksemy_w_slownikach" cascade;
- drop table "klasy_wykluczania" cascade;
- drop table "slowniki_managers" cascade;
- drop table "slowniki_editors" cascade;
- drop table "slowniki_classifications" cascade;
- drop table "slowniki_viewers" cascade;
- drop table "slowniki" cascade;
- drop table "odsylacze" cascade;
- drop table "typywzorow" cascade;
- drop table "charfle" cascade;
- drop table "efobazy" cascade;
- drop table "klatki" cascade;
- drop table "komorki_tabel" cascade;
- drop table "szablony_tabel" cascade;
- drop table "naglowki_tabel" cascade;
- drop table "dictionary_lexemeform" cascade;
- drop table "accounts_usersettings" cascade;
- drop table "dictionary_savedfilter" cascade;
- drop table "wzory" cascade;
- drop table "leksemy" cascade;
- drop table "auth_user" cascade;
- drop table "django_content_type" cascade;
- drop table "django_admin_log" cascade;
- drop table "history" cascade;
- drop table "warianty" cascade;
- drop table "dictionary_inputlexeme" cascade;
- drop table "dictionary_inputform" cascade;
- drop table "typyodsylaczy" cascade;
+DROP TABLE "auth_group_permissions" CASCADE;
+DROP TABLE "auth_group" CASCADE;
+DROP TABLE "auth_user_user_permissions" CASCADE;
+DROP TABLE "auth_user_groups" CASCADE;
+DROP TABLE "auth_message" CASCADE;
+DROP TABLE "auth_permission" CASCADE;
+DROP TABLE "django_session" CASCADE;
+DROP TABLE "registration_registrationprofile" CASCADE;
+DROP TABLE "wartosci_klasyfikacji" CASCADE;
+DROP TABLE "czescimowy" CASCADE;
+DROP TABLE "klasygramatyczne" CASCADE;
+DROP TABLE "kwalifikatory_leksemow" CASCADE;
+DROP TABLE "kwalifikatory_odmieniasiow" CASCADE;
+DROP TABLE "dictionary_lexemecv" CASCADE;
+DROP TABLE "odmieniasie" CASCADE;
+DROP TABLE "zakonczenia" CASCADE;
+DROP TABLE "kwalifikatory_zakonczen" CASCADE;
+DROP TABLE "klasyfikacje" CASCADE;
+DROP TABLE "kwalifikatory" CASCADE;
+DROP TABLE "leksemy_w_slownikach" CASCADE;
+DROP TABLE "klasy_wykluczania" CASCADE;
+DROP TABLE "slowniki_managers" CASCADE;
+DROP TABLE "slowniki_editors" CASCADE;
+DROP TABLE "slowniki_classifications" CASCADE;
+DROP TABLE "slowniki_viewers" CASCADE;
+DROP TABLE "slowniki" CASCADE;
+DROP TABLE "odsylacze" CASCADE;
+DROP TABLE "typywzorow" CASCADE;
+DROP TABLE "charfle" CASCADE;
+DROP TABLE "efobazy" CASCADE;
+DROP TABLE "klatki" CASCADE;
+DROP TABLE "komorki_tabel" CASCADE;
+DROP TABLE "szablony_tabel" CASCADE;
+DROP TABLE "naglowki_tabel" CASCADE;
+DROP TABLE "dictionary_lexemeform" CASCADE;
+DROP TABLE "accounts_usersettings" CASCADE;
+DROP TABLE "dictionary_savedfilter" CASCADE;
+DROP TABLE "wzory" CASCADE;
+DROP TABLE "leksemy" CASCADE;
+DROP TABLE "auth_user" CASCADE;
+DROP TABLE "django_content_type" CASCADE;
+DROP TABLE "django_admin_log" CASCADE;
+DROP TABLE "history" CASCADE;
+DROP TABLE "warianty" CASCADE;
+DROP TABLE "dictionary_inputlexeme" CASCADE;
+DROP TABLE "dictionary_inputform" CASCADE;
+DROP TABLE "typyodsylaczy" CASCADE;
diff --git a/sql/history.sql b/sql/history.sql
index 9095124..5a41432 100644
--- a/sql/history.sql
+++ b/sql/history.sql
@@ -1,95 +1,132 @@
 -- DEFAULTS
 
 ALTER TABLE history
-  ALTER user_id_ SET DEFAULT current_setting('var.user_id'::text)::integer,
-  ALTER transaction_began_ SET DEFAULT transaction_timestamp(),
-  ALTER timestamp_ SET DEFAULT clock_timestamp();
+ALTER user_id_ SET DEFAULT current_setting('var.user_id' :: TEXT) :: INTEGER,
+ALTER transaction_began_ SET DEFAULT transaction_timestamp(),
+ALTER timestamp_ SET DEFAULT clock_timestamp();
 
 
 -- make_history_
 
 CREATE OR REPLACE FUNCTION make_history_()
-RETURNS TRIGGER
+    RETURNS TRIGGER
 LANGUAGE plpgsql
 AS
-$BODY$
-
-DECLARE
-    ri RECORD;
-    oldValue TEXT;
-    newValue TEXT;
-    isColumnSignificant BOOLEAN;
-    isValueModified BOOLEAN;
-    lexemeId INTEGER;
-    patternId INTEGER;
-    temp RECORD;
-    userId TEXT;
-BEGIN
-    IF (TG_OP = 'DELETE') THEN
-        temp := OLD;
-    ELSE
-        temp := NEW;
-    END IF;
-
-    SELECT current_setting('var.user_id') INTO userId;
-    IF (userId = '0') THEN
-        RETURN temp;
-    END IF;
-
-    IF (TG_TABLE_NAME = 'leksemy') THEN
-        lexemeId := temp.id;
-    ELSIF (TG_TABLE_NAME IN ('odmieniasie', 'leksemy_w_slownikach')) THEN
-        lexemeId := temp.l_id;
-    ELSIF (TG_TABLE_NAME IN ('kwalifikatory_leksemow', 'dictionary_lexemeav', 'dictionary_lexemecv')) THEN
-        lexemeId := temp.lexeme_id;
-    ELSIF (TG_TABLE_NAME = 'odsylacze') THEN
-        lexemeId := temp.l_id_od;
-    ELSIF (TG_TABLE_NAME = 'kwalifikatory_odmieniasiow') THEN
-        SELECT l_id INTO lexemeId FROM odmieniasie WHERE id = temp.lexemeinflectionpattern_id;
-    END IF;
-    IF (TG_TABLE_NAME = 'wzory') THEN
-        patternId := temp.id;
-    ELSIF (TG_TABLE_NAME = 'zakonczenia') THEN
-        patternId := temp.w_id;
-    ELSIF (TG_TABLE_NAME = 'kwalifikatory_zakonczen') THEN
-        SELECT w_id INTO patternId FROM zakonczenia WHERE id = temp.ending_id;
-    END IF;
-
-    FOR ri IN
-        SELECT ordinal_position, column_name, data_type
+    $BODY$
+
+    DECLARE
+        ri                  RECORD;
+        oldValue            TEXT;
+        newValue            TEXT;
+        isColumnSignificant BOOLEAN;
+        isValueModified     BOOLEAN;
+        lexemeId            INTEGER;
+        patternId           INTEGER;
+        temp                RECORD;
+        userId              TEXT;
+    BEGIN
+        IF (TG_OP = 'DELETE')
+        THEN
+            temp := OLD;
+        ELSE
+            temp := NEW;
+        END IF;
+
+        SELECT
+            current_setting('var.user_id')
+        INTO userId;
+        IF (userId = '0')
+        THEN
+            RETURN temp;
+        END IF;
+
+        IF (TG_TABLE_NAME = 'leksemy')
+        THEN
+            lexemeId := temp.id;
+        ELSIF (TG_TABLE_NAME IN ('odmieniasie', 'leksemy_w_slownikach'))
+            THEN
+                lexemeId := temp.l_id;
+        ELSIF (TG_TABLE_NAME IN
+               ('kwalifikatory_leksemow', 'dictionary_lexemeav', 'dictionary_lexemecv'))
+            THEN
+                lexemeId := temp.lexeme_id;
+        ELSIF (TG_TABLE_NAME = 'odsylacze')
+            THEN
+                lexemeId := temp.l_id_od;
+        ELSIF (TG_TABLE_NAME = 'kwalifikatory_odmieniasiow')
+            THEN
+                SELECT
+                    l_id
+                INTO lexemeId
+                FROM odmieniasie
+                WHERE id = temp.lexemeinflectionpattern_id;
+        END IF;
+        IF (TG_TABLE_NAME = 'wzory')
+        THEN
+            patternId := temp.id;
+        ELSIF (TG_TABLE_NAME = 'zakonczenia')
+            THEN
+                patternId := temp.w_id;
+        ELSIF (TG_TABLE_NAME = 'kwalifikatory_zakonczen')
+            THEN
+                SELECT
+                    w_id
+                INTO patternId
+                FROM zakonczenia
+                WHERE id = temp.ending_id;
+        END IF;
+
+        FOR ri IN
+        SELECT
+            ordinal_position,
+            column_name,
+            data_type
         FROM information_schema.columns
         WHERE
             table_schema = quote_ident(TG_TABLE_SCHEMA)
-        AND table_name = quote_ident(TG_TABLE_NAME)
+            AND table_name = quote_ident(TG_TABLE_NAME)
         ORDER BY ordinal_position
-    LOOP
-        -- NEW value
-        IF (TG_OP = 'DELETE') THEN
-            newValue := ''::varchar;
+        LOOP
+-- NEW value
+        IF (TG_OP = 'DELETE')
+        THEN
+            newValue := '' :: VARCHAR;
         ELSE
-            EXECUTE 'SELECT ($1).' || ri.column_name || '::text' INTO newValue USING NEW;
+            EXECUTE 'SELECT ($1).' || ri.column_name || '::text'
+            INTO newValue
+            USING NEW;
         END IF;
-        -- OLD value
-        IF (TG_OP = 'INSERT') THEN
-            oldValue := ''::varchar;
+-- OLD value
+        IF (TG_OP = 'INSERT')
+        THEN
+            oldValue := '' :: VARCHAR;
         ELSE
-            EXECUTE 'SELECT ($1).' || ri.column_name || '::text' INTO oldValue USING OLD;
+            EXECUTE 'SELECT ($1).' || ri.column_name || '::text'
+            INTO oldValue
+            USING OLD;
         END IF;
 
-        isColumnSignificant := (position( '_x_' in ri.column_name ) < 1) AND (ri.column_name NOT IN ('id', 'l_id', 'lexeme_id', 'l_id_od', 'data_modyfikacji'));
-        IF isColumnSignificant THEN
+            isColumnSignificant := (position('_x_' IN ri.column_name) < 1) AND
+                                   (ri.column_name NOT IN
+                                    ('id', 'l_id', 'lexeme_id', 'l_id_od', 'data_modyfikacji'));
+        IF isColumnSignificant
+        THEN
             isValueModified := oldValue <> newValue;
-            IF isValueModified THEN
+            IF isValueModified
+            THEN
                 INSERT INTO history (operation_, table_oid_, table_name_, id_, column_name_, ordinal_position_of_column_, old_value_, new_value_, lexeme_id_, pattern_id_)
-                VALUES (TG_OP, TG_RELID, TG_TABLE_NAME, temp.id, ri.column_name::VARCHAR, ri.ordinal_position, oldValue::text, newValue::text, lexemeId, patternId);
+                    VALUES (TG_OP, TG_RELID, TG_TABLE_NAME, temp.id,
+                            ri.column_name :: VARCHAR, ri.ordinal_position,
+                            oldValue :: TEXT, newValue ::
+                                              TEXT, lexemeId, patternId);
             END IF;
         END IF;
-    END LOOP;
+        END LOOP;
 
-    RETURN temp;
-END;
+        RETURN temp;
+    END;
 
-$BODY$;
+    $BODY$;
 
 
 -- TRIGGERS
diff --git a/sql/obliczanki.sql b/sql/obliczanki.sql
index c9bc6f3..ac1580a 100644
--- a/sql/obliczanki.sql
+++ b/sql/obliczanki.sql
@@ -1,44 +1,74 @@
 -- nieadj to 20, 21, 22, 23
 
 -- SGJP
-select pos,
-      case when l_id_od is null then 'aff' else 'neg' end as nie,
-      count(*)
-from leksemy l left outer join odsylacze o on (l.id=o.l_id_od and typods_id in (20, 21, 22, 23))
-where slownik='SGJP'
-group by pos, nie;
+SELECT
+    pos,
+    CASE WHEN l_id_od IS null THEN 'aff'
+    ELSE 'neg' END AS nie,
+    count(*)
+FROM leksemy l LEFT OUTER JOIN odsylacze o
+        ON (l.id = o.l_id_od AND typods_id IN (20, 21, 22, 23))
+WHERE slownik = 'SGJP'
+GROUP BY pos, nie;
 
 -- wspólne (złe! leksem się liczy tyle razy, ile razy jest w słowniku)
-select pos,
-      case when l_id_od is null then 'aff' else 'neg' end as nie,
-      count(*)
-from leksemy l join leksemy_w_slownikach s1 on (l.id=s1.l_id) join leksemy_w_slownikach s2 on (l.id=s2.l_id) left outer join odsylacze o on (l.id=o.l_id_od and typods_id in (20, 21, 22, 23))
-where s1.slownik='SGJP' and s2.slownik='Morfologik'
-group by pos, nie;
+SELECT
+    pos,
+    CASE WHEN l_id_od IS null THEN 'aff'
+    ELSE 'neg' END AS nie,
+    count(*)
+FROM leksemy l JOIN leksemy_w_slownikach s1
+        ON (l.id = s1.l_id)
+    JOIN leksemy_w_slownikach s2
+        ON (l.id = s2.l_id)
+    LEFT OUTER JOIN odsylacze o
+        ON (l.id = o.l_id_od AND typods_id IN (20, 21, 22, 23))
+WHERE s1.slownik = 'SGJP' AND s2.slownik = 'Morfologik'
+GROUP BY pos, nie;
 
 -- razem
-select pos,
-      case when l_id_od is null then 'aff' else 'neg' end as nie,
-      count(*)
-from leksemy l left outer join odsylacze o on (l.id=o.l_id_od and typods_id in (20, 21, 22, 23))
-where slownik in ('SGJP','Morfologik')
-group by pos, nie;
+SELECT
+    pos,
+    CASE WHEN l_id_od IS null THEN 'aff'
+    ELSE 'neg' END AS nie,
+    count(*)
+FROM leksemy l LEFT OUTER JOIN odsylacze o
+        ON (l.id = o.l_id_od AND typods_id IN (20, 21, 22, 23))
+WHERE slownik IN ('SGJP', 'Morfologik')
+GROUP BY pos, nie;
 
 -- tylko Morfologik
-select pos,
-      case when l_id_od is null then 'aff' else 'neg' end as nie,
-      count(*)
-from leksemy l left outer join odsylacze o on (l.id=o.l_id_od and typods_id in (20, 21, 22, 23))
-where slownik = 'Morfologik'
-group by pos, nie;
+SELECT
+    pos,
+    CASE WHEN l_id_od IS null THEN 'aff'
+    ELSE 'neg' END AS nie,
+    count(*)
+FROM leksemy l LEFT OUTER JOIN odsylacze o
+        ON (l.id = o.l_id_od AND typods_id IN (20, 21, 22, 23))
+WHERE slownik = 'Morfologik'
+GROUP BY pos, nie;
 
 -- tylko SGJP (wspólne bez not)
-select pos,
-      case when l_id_od is null then 'aff' else 'neg' end as nie,
-      count(*)
-from leksemy l left outer join odsylacze o on (l.id=o.l_id_od and typods_id in (20, 21, 22, 23))
-where slownik='SGJP' and not exists (select id from leksemy_w_slownikach where l_id=l.id and slownik='Morfologik')
-group by pos, nie;
+SELECT
+    pos,
+    CASE WHEN l_id_od IS null THEN 'aff'
+    ELSE 'neg' END AS nie,
+    count(*)
+FROM leksemy l LEFT OUTER JOIN odsylacze o
+        ON (l.id = o.l_id_od AND typods_id IN (20, 21, 22, 23))
+WHERE slownik = 'SGJP' AND NOT exists(SELECT
+                                          id
+                                      FROM leksemy_w_slownikach
+                                      WHERE l_id = l.id AND
+                                            slownik = 'Morfologik')
+GROUP BY pos, nie;
 
 -- Morfologik wg statusów
-select pos, status, count(*) from leksemy l where slownik='Morfologik' group by pos, status order by pos, status;
+SELECT
+    pos,
+    status,
+    count(*)
+FROM leksemy l
+WHERE slownik = 'Morfologik'
+GROUP BY pos, status
+ORDER BY pos, status;
diff --git a/sqlstacktrace/__init__.py b/sqlstacktrace/__init__.py
index b160326..8fd7cf3 100644
--- a/sqlstacktrace/__init__.py
+++ b/sqlstacktrace/__init__.py
@@ -4,7 +4,8 @@ from django.conf import settings
 from .replacer import replace_call
 
 
-SQL_STACKTRACE = settings.SQL_STACKTRACE if hasattr(settings, 'SQL_STACKTRACE') else False
+SQL_STACKTRACE = settings.SQL_STACKTRACE if hasattr(settings,
+                                                    'SQL_STACKTRACE') else False
 if SQL_STACKTRACE:
     from django.db.backends import BaseDatabaseWrapper
     from .stacktracecursor import StacktraceCursorWrapper
diff --git a/sqlstacktrace/replacer.py b/sqlstacktrace/replacer.py
index d7d0aa7..74bb3b6 100644
--- a/sqlstacktrace/replacer.py
+++ b/sqlstacktrace/replacer.py
@@ -27,10 +27,12 @@ def replace_call(func):
     def inner(callback):
         def wrapped(*args, **kwargs):
             return callback(func, *args, **kwargs)
+
         actual = getattr(func, '__wrapped__', func)
         wrapped.__wrapped__ = actual
         wrapped.__doc__ = getattr(actual, '__doc__', None)
         wrapped.__name__ = actual.__name__
         _replace_function(func, wrapped)
         return wrapped
+
     return inner
diff --git a/sqlstacktrace/stacktrace.py b/sqlstacktrace/stacktrace.py
index eb42725..076aaf7 100644
--- a/sqlstacktrace/stacktrace.py
+++ b/sqlstacktrace/stacktrace.py
@@ -3,17 +3,19 @@
 Code is from debug_toolbar.
 """
 
-
 import sys
 import os.path
 import inspect
-import django
 import SocketServer
 
+import django
+
+
 # Figure out some paths
 django_path = os.path.realpath(os.path.dirname(django.__file__))
 socketserver_path = os.path.realpath(os.path.dirname(SocketServer.__file__))
 
+
 def getframeinfo(frame, context=1):
     """
     Get information about a frame or traceback object.
@@ -50,7 +52,8 @@ def getframeinfo(frame, context=1):
     else:
         lines = index = None
 
-    return inspect.Traceback(filename, lineno, frame.f_code.co_name, lines, index)
+    return inspect.Traceback(filename, lineno, frame.f_code.co_name, lines,
+                             index)
 
 
 def get_stack(context=1):
diff --git a/sqlstacktrace/stacktracecursor.py b/sqlstacktrace/stacktracecursor.py
index 7dc2970..e86e468 100644
--- a/sqlstacktrace/stacktracecursor.py
+++ b/sqlstacktrace/stacktracecursor.py
@@ -11,6 +11,7 @@ class StacktraceCursorWrapper(CursorWrapper):
     """Wrapper for substitution the CursorWrapper.
     Added to SQl-query a comment with python stack trace.
     """
+
     def execute(self, sql, params=()):
         try:
             stacks = get_stacktrace()
@@ -18,10 +19,12 @@ class StacktraceCursorWrapper(CursorWrapper):
             for stack in stacks:
                 stacktrace.append(
                     u"""File "{0}", line {1}, in {2}\n\t{3}""".format(
-                        *[smart_unicode(stack_data) for stack_data in stack]).replace("%", "%%"))
+                        *[smart_unicode(stack_data) for stack_data in
+                          stack]).replace("%", "%%"))
             stacktrace = "\n".join(stacktrace)
             stacktrace = stacktrace.replace('/*', '\/\*').replace('*/', '\*\/')
         except:
             stacktrace = u"WITHOUT STACKTRACE"
-        sql = u"{sql} \n/* {stacktrace} \n*/".format(stacktrace=stacktrace, sql=smart_unicode(sql))
+        sql = u"{sql} \n/* {stacktrace} \n*/".format(stacktrace=stacktrace,
+                                                     sql=smart_unicode(sql))
         return self.cursor.execute(sql, params)
diff --git a/templates/base.html b/templates/base.html
index 0d2d6b0..7f1c0e4 100644
--- a/templates/base.html
+++ b/templates/base.html
@@ -1,29 +1,42 @@
-{% load url from future %}<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+{% load url from future %}<!DOCTYPE html PUBLIC
+        "-//W3C//DTD XHTML 1.0 Strict//EN"
+        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3c.org/1999/xhtml" xml:lang="pl" lang="pl">
 <head>
-<title>{% block title %}{% endblock %}</title>
-<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
-<link rel="shortcut icon" href="{{ MEDIA_URL }}forge.ico" type="image/x-icon"/>
-<script type="text/javascript" src="{{ MEDIA_URL }}js/lib/jquery-1.7.1.js"></script>
-<script type="text/javascript" src="{{ MEDIA_URL }}js/lib/jquery.json-2.2.min.js"></script>
-<script type="text/javascript" src="{{ MEDIA_URL }}js/lib/jquery-ui-1.8.21.custom.min.js"></script>
-<script type="text/javascript" src="{{ MEDIA_URL }}js/lib/jquery.ui.datepicker-pl.js"></script>
-<script type="text/javascript" src="{{ MEDIA_URL }}js/base-layout.js"></script>
-<script type="text/javascript" src="{{ MEDIA_URL }}js/common.js"></script>
-{% if paginer %}
-  <script type="text/javascript" src="{{ MEDIA_URL }}js/paginer.js"></script>
-{% endif %}
-{% load script jsonify %}
-{% script %}
-  var $dj = {};
-  {% for name,var in js_vars.iteritems %}
-    $dj.{{ name }} = {{ var|jsonify }};
-  {% endfor %}
-{% endscript %}
-<link rel="stylesheet" href="{{ MEDIA_URL }}css/lib/smoothness/jquery-ui-1.8.21.custom.css" type="text/css" media="screen" charset="utf-8" />
-<link rel="stylesheet" href="{{ MEDIA_URL }}css/general.css" type="text/css" media="screen" charset="utf-8" />
-<link rel="stylesheet" href="{{ MEDIA_URL }}css/inflection_table.css" type="text/css" media="screen" charset="utf-8" />
-{% block extrahead %}{% endblock %}
+    <title>{% block title %}{% endblock %}</title>
+    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
+    <link rel="shortcut icon" href="{{ MEDIA_URL }}forge.ico"
+          type="image/x-icon"/>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/jquery-1.7.1.js"></script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/jquery.json-2.2.min.js"></script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/jquery-ui-1.8.21.custom.min.js"></script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/lib/jquery.ui.datepicker-pl.js"></script>
+    <script type="text/javascript"
+            src="{{ MEDIA_URL }}js/base-layout.js"></script>
+    <script type="text/javascript" src="{{ MEDIA_URL }}js/common.js"></script>
+    {% if paginer %}
+        <script type="text/javascript"
+                src="{{ MEDIA_URL }}js/paginer.js"></script>
+    {% endif %}
+    {% load script jsonify %}
+    {% script %}
+        var $dj = {};
+        {% for name,var in js_vars.iteritems %}
+            $dj.{{ name }} = {{ var|jsonify }};
+        {% endfor %}
+    {% endscript %}
+    <link rel="stylesheet"
+          href="{{ MEDIA_URL }}css/lib/smoothness/jquery-ui-1.8.21.custom.css"
+          type="text/css" media="screen" charset="utf-8"/>
+    <link rel="stylesheet" href="{{ MEDIA_URL }}css/general.css" type="text/css"
+          media="screen" charset="utf-8"/>
+    <link rel="stylesheet" href="{{ MEDIA_URL }}css/inflection_table.css"
+          type="text/css" media="screen" charset="utf-8"/>
+    {% block extrahead %}{% endblock %}
 </head>
 {% load i18n %}
 
@@ -32,53 +45,57 @@
 <!-- Container -->
 <!--div id="container"-->
 
-    <!-- Header -->
-    <div id="header">
-        <div id="branding">
+<!-- Header -->
+<div id="header">
+    <div id="branding">
         {% block branding %}{% endblock %}
-        </div>
-        {% if user.is_active %}
+    </div>
+    {% if user.is_active %}
         <div id="user-tools">
             {# if debug #}
-              <span id="show-debug">debug</span>
+            <span id="show-debug">debug</span>
             {# endif #}
-            <strong>{% filter force_escape %}{{ user.username }}{% endfilter %}</strong>
+            <strong>{% filter force_escape %}
+                {{ user.username }}{% endfilter %}</strong>
             {% block userlinks %}
                 <a href="{% url 'settings' %}">
-                Ustawienia</a> /
+                    Ustawienia</a> /
                 <a href="{% url 'auth_logout' %}">
-                {% trans 'Log out' %}</a>
+                    {% trans 'Log out' %}</a>
             {% endblock %}
         </div>
-        {% endif %}
-        {% include 'main_menu.html' %}
-        {% block nav-global %}{% endblock %}
+    {% endif %}
+    {% include 'main_menu.html' %}
+    {% block nav-global %}{% endblock %}
 
-        {% if messages %}
+    {% if messages %}
         <ul class="messagelist">{% for message in messages %}
-          <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
+            <li{% if message.tags %}
+                class="{{ message.tags }}"{% endif %}>{{ message }}</li>
         {% endfor %}</ul>
-        {% endif %}
-    </div>
-    <!-- END Header -->
-    <!-- Content -->
-    <div id="content">
-        {% block pretitle %}{% endblock %}
-        {% block content_title %}{% if title %}<h1>{{ title }}</h1>{% endif %}{% endblock %}
-        {% block content %}
+    {% endif %}
+</div>
+<!-- END Header -->
+<!-- Content -->
+<div id="content">
+    {% block pretitle %}{% endblock %}
+    {% block content_title %}{% if title %}<h1>{{ title }}</h1>
+    {% endif %}{% endblock %}
+    {% block content %}
         {% block object-tools %}{% endblock %}
         {{ content }}
-        {% endblock %}
-        {% block sidebar %}{% endblock %}
-    </div>
-    <!-- END Content -->
+    {% endblock %}
+    {% block sidebar %}{% endblock %}
+</div>
+<!-- END Content -->
 
-    {% block footer %}<div id="footer"></div>{% endblock %}
-    {% block modal_elements %}{% endblock %}
-    {# if debug #}
-      <iframe id="debug">
-      </iframe>
-    {# endif #}
+{% block footer %}
+    <div id="footer"></div>{% endblock %}
+{% block modal_elements %}{% endblock %}
+{# if debug #}
+<iframe id="debug">
+</iframe>
+{# endif #}
 <!--/div-->
 <!-- END Container -->
 
diff --git a/templates/main_menu.html b/templates/main_menu.html
index be58070..d7bb448 100644
--- a/templates/main_menu.html
+++ b/templates/main_menu.html
@@ -1,18 +1,18 @@
 {% load url from future %}
 <ul id="main_menu">
-  {% if perms.dictionary.view_lexeme %}
-    <li><a href="{% url 'lexeme_view' %}">Leksemy</a></li>
-  {% endif %}
-  {% if perms.dictionary.view_pattern %}
-    <li><a href="{% url 'pattern_view' %}">Wzory</a></li>
-  {% endif %}
-  <li><a href="{% url 'tasks' %}">Zadania</a></li>
-  <li><a href="{% url 'reports' %}">Raporty</a></li>
-  <li><a href="{% url 'history_view' %}">Historia</a></li>
-  {% if perms.dictionary.export_lexemes %}
-    <li><a href="{% url 'export' %}">Eksport</a></li>
-  {% endif %}
-  {% if perms.dictionary.manage_vocabulary or perms.auth.add_user %}
-    <li><a href="{% url 'management_menu' %}">Administracja</a></li>
-  {% endif %}
+    {% if perms.dictionary.view_lexeme %}
+        <li><a href="{% url 'lexeme_view' %}">Leksemy</a></li>
+    {% endif %}
+    {% if perms.dictionary.view_pattern %}
+        <li><a href="{% url 'pattern_view' %}">Wzory</a></li>
+    {% endif %}
+    <li><a href="{% url 'tasks' %}">Zadania</a></li>
+    <li><a href="{% url 'reports' %}">Raporty</a></li>
+    <li><a href="{% url 'history_view' %}">Historia</a></li>
+    {% if perms.dictionary.export_lexemes %}
+        <li><a href="{% url 'export' %}">Eksport</a></li>
+    {% endif %}
+    {% if perms.dictionary.manage_vocabulary or perms.auth.add_user %}
+        <li><a href="{% url 'management_menu' %}">Administracja</a></li>
+    {% endif %}
 </ul>
diff --git a/urls.py b/urls.py
index d6b5ded..75e4abc 100644
--- a/urls.py
+++ b/urls.py
@@ -9,101 +9,116 @@ from common.util import url
 #admin.autodiscover()
 
 urlpatterns = patterns('',
-  # Example:
-  # (r'^lexeme_forge/', include('lexeme_forge.foo.urls')),
-  url(r'^accounts/register/$', 'accounts.views.register'),
-  url(r'^accounts/settings/$', 'accounts.views.settings'),
-  url(r'^accounts/manage-groups/$', 'accounts.views.manage_groups'),
-  (r'^accounts/', include('registration.backends.default.urls')),
+                       # Example:
+                       # (r'^lexeme_forge/', include('lexeme_forge.foo.urls')),
+                       url(r'^accounts/register/$', 'accounts.views.register'),
+                       url(r'^accounts/settings/$', 'accounts.views.settings'),
+                       url(r'^accounts/manage-groups/$',
+                           'accounts.views.manage_groups'),
+                       (r'^accounts/',
+                        include('registration.backends.default.urls')),
 
-  url(r'^ajax/history-table/$', 'dictionary.ajax_history.history_table'),
-  url(r'^ajax/prompter-list/$', 'dictionary.ajax_prompter.prompter_list'),
+                       url(r'^ajax/history-table/$',
+                           'dictionary.ajax_history.history_table'),
+                       url(r'^ajax/prompter-list/$',
+                           'dictionary.ajax_prompter.prompter_list'),
 
-  url(r'^%s(?P<path>.*)$' % settings.MEDIA_URL.lstrip('/'),
-      'django.views.static.serve',
-      kwargs={'document_root': settings.MEDIA_ROOT}),
+                       url(r'^%s(?P<path>.*)$' % settings.MEDIA_URL.lstrip('/'),
+                           'django.views.static.serve',
+                           kwargs={'document_root': settings.MEDIA_ROOT}),
 )
 
 urlpatterns += patterns('dictionary.ajax_lexeme_view',
-  url(r'^ajax/inflection_tables/$', 'get_inflection_tables'),
-  url(r'^ajax/odm-forms/$', 'odm_forms'),
-  url(r'^ajax/lexeme_edit_form/$', 'lexeme_edit_form'),
-  url(r'^ajax/update_lexeme/$', 'update_lexeme'),
-  url(r'^ajax/table_preview/$', 'table_preview'),
-  url(r'^ajax/new_lip_row/$', 'new_lip_edit_row'),
-  url(r'^ajax/save_columns/$', 'save_columns'),
-  url(r'^ajax/add_vocabulary/$', 'add_vocabulary'),
-  url(r'^ajax/get_privileges/$', 'vocabulary_permissions'),
-  url(r'^ajax/set_privilege$', 'set_vocabulary_permission'),
-  url(r'^ajax/new_cr_row/$', 'new_cross_reference_row'),
-  url(r'^ajax/delete_lexeme/$', 'delete_lexeme'),
-  url(r'^ajax/check-pos/$', 'check_pos'),
-  url(r'^ajax/check-pattern/$', 'check_pattern'),
-  url(r'^ajax/check-classifications/$', 'check_classifications'),
-  url(r'^ajax/get-ics/$', 'get_ics'),
-  url(r'^ajax/create-lexeme/$', 'create_lexeme'),
-  url(r'^ajax/classification-forms/$', 'classification_forms'),
-  url(r'^ajax/extra-attributes/$', 'extra_attributes'),
-  url(r'^ajax/check-attributes/$', 'check_attributes'),
-  url(r'^ajax/homonym-count/$', 'homonym_count'),
-  url(r'^ajax/cr-homonyms/$', 'cr_homonyms'),
-  url(r'^ajax/new-action-row/$', 'new_action_row'),
-  url(r'^ajax/dynamic-fields/$', 'dynamic_action_fields'),
-  url(r'^ajax/execute-actions$', 'execute_group_actions'),
+                        url(r'^ajax/inflection_tables/$',
+                            'get_inflection_tables'),
+                        url(r'^ajax/odm-forms/$', 'odm_forms'),
+                        url(r'^ajax/lexeme_edit_form/$', 'lexeme_edit_form'),
+                        url(r'^ajax/update_lexeme/$', 'update_lexeme'),
+                        url(r'^ajax/table_preview/$', 'table_preview'),
+                        url(r'^ajax/new_lip_row/$', 'new_lip_edit_row'),
+                        url(r'^ajax/save_columns/$', 'save_columns'),
+                        url(r'^ajax/add_vocabulary/$', 'add_vocabulary'),
+                        url(r'^ajax/get_privileges/$',
+                            'vocabulary_permissions'),
+                        url(r'^ajax/set_privilege$',
+                            'set_vocabulary_permission'),
+                        url(r'^ajax/new_cr_row/$', 'new_cross_reference_row'),
+                        url(r'^ajax/delete_lexeme/$', 'delete_lexeme'),
+                        url(r'^ajax/check-pos/$', 'check_pos'),
+                        url(r'^ajax/check-pattern/$', 'check_pattern'),
+                        url(r'^ajax/check-classifications/$',
+                            'check_classifications'),
+                        url(r'^ajax/get-ics/$', 'get_ics'),
+                        url(r'^ajax/create-lexeme/$', 'create_lexeme'),
+                        url(r'^ajax/classification-forms/$',
+                            'classification_forms'),
+                        url(r'^ajax/extra-attributes/$', 'extra_attributes'),
+                        url(r'^ajax/check-attributes/$', 'check_attributes'),
+                        url(r'^ajax/homonym-count/$', 'homonym_count'),
+                        url(r'^ajax/cr-homonyms/$', 'cr_homonyms'),
+                        url(r'^ajax/new-action-row/$', 'new_action_row'),
+                        url(r'^ajax/dynamic-fields/$', 'dynamic_action_fields'),
+                        url(r'^ajax/execute-actions$', 'execute_group_actions'),
 )
 
 urlpatterns += patterns('dictionary.ajax_lexeme_jqgrid',
-  url(r'^ajax/lexemes/$', 'get_lexemes'),
-  url(r'^ajax/location/$', 'get_location'),
-  url(r'^ajax/find_id/$', 'find_id'),
+                        url(r'^ajax/lexemes/$', 'get_lexemes'),
+                        url(r'^ajax/location/$', 'get_location'),
+                        url(r'^ajax/find_id/$', 'find_id'),
 )
 
 urlpatterns += patterns('dictionary.ajax_filters',
-  url(r'^ajax/save_filter/$', 'save_filter'),
-  url(r'^ajax/get_filters/$', 'get_filters'),
-  url(r'^ajax/delete_filter/$', 'delete_filter'),
+                        url(r'^ajax/save_filter/$', 'save_filter'),
+                        url(r'^ajax/get_filters/$', 'get_filters'),
+                        url(r'^ajax/delete_filter/$', 'delete_filter'),
 )
 
 urlpatterns += patterns('dictionary.ajax_pattern_view',
-  url(r'^ajax/patterns/objects/$', 'get_patterns'),
-  url(r'^ajax/patterns/find_id/$', 'find_id', name='patterns_find_id'),
-  url(r'^ajax/patterns/location/$', 'get_location',
-      name='patterns_get_location'),
-  url(r'^ajax/patterns/save_columns/$', 'save_columns',
-      name='patterns_save_columns'),
-  url(r'^ajax/patterns/pattern_edit_form/$', 'pattern_edit_form'),
-  url(r'^ajax/patterns/new_ending_row/$', 'new_ending_row'),
-  url(r'^ajax/update_pattern/$', 'update_pattern'),
+                        url(r'^ajax/patterns/objects/$', 'get_patterns'),
+                        url(r'^ajax/patterns/find_id/$', 'find_id',
+                            name='patterns_find_id'),
+                        url(r'^ajax/patterns/location/$', 'get_location',
+                            name='patterns_get_location'),
+                        url(r'^ajax/patterns/save_columns/$', 'save_columns',
+                            name='patterns_save_columns'),
+                        url(r'^ajax/patterns/pattern_edit_form/$',
+                            'pattern_edit_form'),
+                        url(r'^ajax/patterns/new_ending_row/$',
+                            'new_ending_row'),
+                        url(r'^ajax/update_pattern/$', 'update_pattern'),
 )
 
 urlpatterns += patterns('dictionary.ajax_export',
-  url(r'^ajax/new_qualifier_row/$', 'magic_qualifier_row'),
-  url(r'^ajax/save_export_data/$', 'save_export_data'),
-  url(r'^ajax/get_export_data/$', 'get_export_data'),
-  url(r'^ajax/delete_export_data/$', 'delete_export_data'),
+                        url(r'^ajax/new_qualifier_row/$',
+                            'magic_qualifier_row'),
+                        url(r'^ajax/save_export_data/$', 'save_export_data'),
+                        url(r'^ajax/get_export_data/$', 'get_export_data'),
+                        url(r'^ajax/delete_export_data/$',
+                            'delete_export_data'),
 )
 
 urlpatterns += patterns('accounts.ajax',
-  url(r'^ajax/set_group/$', 'set_group'),
-  url(r'^ajax/save-default-owner/$', 'save_default_owner'),
+                        url(r'^ajax/set_group/$', 'set_group'),
+                        url(r'^ajax/save-default-owner/$',
+                            'save_default_owner'),
 )
 
 urlpatterns += patterns('dictionary.views',
-  url(r'^$', 'lexeme_view'),
-  url(r'^wzory/$', 'pattern_view'),
-  url(r'^zadania/$', 'tasks'),
-  url(r'^raporty/$', 'reports'),
-  url(r'^widok-wydawcy/$', 'manager_view'),
-  url(r'^klasyfikacje/$', 'manage_classifications'),
-  url(r'^kwalifikatory/$', 'manage_qualifiers'),
-  url(r'^historia/$', 'history_view'),
-  url(r'^eksport/$', 'export'),
-  url(r'^administracja/$', 'management_menu'),
-  url(r'^WSJP/(.+)/$', 'wsjp_table'),
+                        url(r'^$', 'lexeme_view'),
+                        url(r'^wzory/$', 'pattern_view'),
+                        url(r'^zadania/$', 'tasks'),
+                        url(r'^raporty/$', 'reports'),
+                        url(r'^widok-wydawcy/$', 'manager_view'),
+                        url(r'^klasyfikacje/$', 'manage_classifications'),
+                        url(r'^kwalifikatory/$', 'manage_qualifiers'),
+                        url(r'^historia/$', 'history_view'),
+                        url(r'^eksport/$', 'export'),
+                        url(r'^administracja/$', 'management_menu'),
+                        url(r'^WSJP/(.+)/$', 'wsjp_table'),
 )
 
 urlpatterns += patterns('paginer.ajax',
-  url(r'^ajax/get-page/$', 'get_page_content'),
-  url(r'^ajax/new-filter-row/$', 'new_filter_row'),
-  url(r'^ajax/dynamic-field/$', 'field_form'),
+                        url(r'^ajax/get-page/$', 'get_page_content'),
+                        url(r'^ajax/new-filter-row/$', 'new_filter_row'),
+                        url(r'^ajax/dynamic-field/$', 'field_form'),
 )
\ No newline at end of file
diff --git a/urls_main.py b/urls_main.py
index 2af7940..b40b616 100644
--- a/urls_main.py
+++ b/urls_main.py
@@ -3,10 +3,10 @@ from django.conf.urls import *
 from django.conf import settings
 
 if settings.SITE_PREFIX:
-  prefix = r'^%s/' % settings.SITE_PREFIX.lstrip('/')
+    prefix = r'^%s/' % settings.SITE_PREFIX.lstrip('/')
 else:
-  prefix = r'^'
+    prefix = r'^'
 
 urlpatterns = patterns('',
-  (prefix, include('urls')),
+                       (prefix, include('urls')),
 )