// var NEW_DEAL_DESIGN = NEW_DEAL_DESIGN || false;
var fk_alerts = false,
    fk_currentTab = 0,
    fk_currentSubTab = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    fk_pageTitleBase = '',
    fk_loadedTab = [],
    fk_savedForm = [],
    fk_loadingContentElement = fk_loadingContentElement || new Element('div', {'class': 'loading'}).update('Loading content. Please wait...'), // initial loading element
    fk_loadingContent = fk_loadingContentElement.clone(1),
    fk_loadingEventElement = null, // holds event clicked on
    fk_results = 'show',
    fk_withForm = 0,
    fk_withRating = 'talent',
    fk_withSkills = 'current',
    fk_withMfSkills = 0,
    fk_ntPlayersShow = '',
    fk_specialString = null;

(function () {
  if (!window.console) {
    window.console = (function () {
      return {};
    }(window));
  }
  
  if (!window.console.log) { window.console.log =  function () {}; }
  if (!window.console.time) { window.console.time =  function () {}; }
  if (!window.console.timeEnd) { window.console.timeEnd =  function () {}; }
}());

function fk_newPage(tab, pageTitle, loadTabs) {
  fk_currentTab = tab;
  fk_pageTitleBase = pageTitle;
  if (loadTabs) {
    // $('main-content').update(fk_loadingContent);
    fk_updateData(loadTabs + '&tab=' + fk_currentTab + '&ajax=2', null);
  }
}

function fk_loadContent(pars, tab, reload) {
  if (typeof fk_liveViewer != 'undefined' && fk_liveViewer.get('running')) {
    clearTimeout(liveTimer);
    // fk_liveViewer.get('running') = false;
    fk_liveViewer.set('running', false);
  }
  var loaded = 0, mainContent = mainContent || $('main-content'), mainLoading = mainLoading || $('main-loading');
  fk_loadedTab[fk_currentTab] = mainContent.innerHTML + ' ';
  fk_saveForms(fk_currentTab);

  if (fk_loadedTab[tab] && !reload) {
    loaded = 1;

    mainContent.hide();
    mainLoading.show();
    mainContent.update(fk_loadedTab[tab]);
    fk_onComplete();
    mainContent.show();
    mainLoading.hide();
  } else {
    if (reload && reload !== 1) {
      pars += (pars.length > 0 ? '&' : '') + $(reload).serialize();
    }
    pars = pars.replace('?', '');

    var myAjax = new Ajax.Updater('main-content', '?', {
      evalScripts: true,
      parameters: pars,
      onCreate: function () {
        // hide main-content and show main-loading
        mainContent.hide();
        mainLoading.show();

        // add progress mouse
        // fk_loadingEventElement = window.event && Event.findElement(window.event);
        // [document.body, fk_loadingEventElement].invoke('addClassName', 'progress');

        (document.body || $$('body')[0]).addClassName('progress');
      },
      onComplete: function () { 
        fk_onComplete();

        // show main-content and hide main-loading again
        mainContent.show();// 21ms
        mainLoading.hide();


        // remove progress mouse
        // [document.body, fk_loadingEventElement].invoke('removeClassName', 'progress');

        document.body.removeClassName('progress');
      },
      onSuccess: function (transport, json) {
        if (fk_alerts) {
          // Used to be able to see the error output for this type of server request.
          alert('fk_loadContent() response: ' + transport.responseText); 
        }

        var str, head = head || document.head || $$('head')[0];

        if (json.js) {
          var js = $('js') || head;
          json.js.each(function (file) {
            if (!js.select('script[type=text/javascript][src]').invoke('readAttribute', 'src').include(file)) {
              js.insert({'bottom': new Element('script', {'type': 'text/javascript', 'src': file})});
            }
          });
        }

        if (json.css) {
          json.css.each(function(file){
            if (!head.select('script[type=text/javascript][href]').invoke('readAttribute', 'href').include(file)) {
              head.insert({'bottom': new Element('link', {'type': 'text/css', 'rel': 'stylesheet', 'href': file, 'media': 'screen'})});
            }
          });
        }


        if (json.check_tables) {
          check_tables(json.check_tables);
        }
        if (json.checkConsistency) {
          fk_checkConsistency(json.checkConsistency);
        }
        if (json.convertmr) {//Anders matchrapportskonvertering från zold
          convertmr(json.convertmr);
        }
        if (json.upload_mr) {
          fk_upload_mr(json.upload_mr.step);
        }
        if (json.fixname) {
          //console.log('rad 71 table = ' + json.fixname.table + ' firstlast = ' + json.fixname.firstlast + ' step =' + json.fixname.step + ' name = ' + json.fixname.name + ' ids =' + json.fixname.ids);
          fk_fixname(json.fixname.table, json.fixname.firstlast, json.fixname.step, json.fixname.name, json.fixname.ids, json.fixname.i, json.fixname.j, json.fixname.k);
         //   fk_fixname(json.fixname.step);

        }

        
        if (json.money) {
          $('club-money').update(json.money.amount);
        }
        if (json.content) {
          $(json.content.id).update(json.content.html);
          if (json.content.reference && json.content.container) {
            $(json.content.container).style.height = $(json.content.reference).offsetHeight + 'px';
          }
        }
        if (json.redirect) {
          $('main-loading').show();
          $('main-content').hide();
          str = '?loc=' + json.redirect.loc;
          if (json.redirect.error) {
            str += '&error=' + json.redirect.error;
          }
          if (fk_alerts) {
            alert(str); 
          }
          window.location = str;
        }
        if (json.initiateLoadTabs) {
          str = json.initiateLoadTabs.loadTabs + '&tab=' + fk_currentTab + '&subtab=' + fk_currentSubTab[fk_currentTab] + '&ajax=2';
          if (fk_alerts) {
            alert('fk_loadContent initiateLoadTabs');
            alert(str);
          }
          fk_updateData(str, null);
        }
        if (json.loadTab) {
          str = 'loc=' + json.loadTab.loc + '&ajax=1';
          if (fk_alerts) {
            alert('fk_loadContent loadTab');
            alert(str);
          }
          // mainContent.update(fk_loadingContent);
          fk_loadContent(str, fk_currentTab, 1);
        }
        if (json.unloadTabs) {
          if (fk_alerts) {
            alert('fk_loadContent unloadTabs');
          }
          var tabs = json.unloadTabs.tabs,
              length = tabs.length,
              i;
          for (i = 0; i < length; i++) {
            fk_loadedTab[tabs[i]] = null;
            fk_savedForm[tabs[i]] = null;
          }
        }
        if (json.switchTab) {
          str = '?loc=' + json.switchTab.loc + '&ajax=1';
          if (fk_alerts) {
            alert(str);
          }
          fk_loadContent(str, json.switchTab.tab, 1);
          fk_loadedTab[json.switchTab.unload] = null;
          fk_savedForm[json.switchTab.unload] = null;
        }
        if (json.updateTabs) {
          if (fk_alerts) {
            alert('fk_loadContent updateTabs');
          }
          var length = json.updateTabs.tab.length,
              tab,
              link,
              i;
          for (i = 0; i < length; i++) {
            tab = json.updateTabs.tab[i];
            link = $(tab.id);
            link.href = tab.url;
            // link.onclick = new Function(tab.action);  // The Function constructor is eval.
            link.onclick = function () {
              tab.action
            };
          }
          length = fk_loadedTab.length;
          for (i = 0; i < length; i++) {
            fk_loadedTab[i] = null;
          }
          length = fk_savedForm.length;
          for (i = 0; i < length; i++) {
            fk_savedForm[i] = null;
          }
        }
        if (json.specialString) {
          fk_specialString = json.specialString.str;
        }
      }
    });
  }

  if (tab >= 0) {
    var tabActive = $$('.tab-active')[0];

    if (tabActive.id != ('main-tabs_' + tab)) {
      tabActive.removeClassName('tab-active');
    }

    $('main-tabs_' + tab).addClassName('tab-active').removeClassName('hidden');

    fk_currentTab = tab;
    if (loaded) {
      fk_updateForms(tab);
    }

    document.title = fk_pageTitleBase + $('main-tabs_' + tab + '_name').innerHTML;
    ($('nav-bar') || $('blue-nav')).update(document.title.replace(/ - /g, " &raquo; "));
    if (fk_ntPlayersShow != '') {
      fk_changeNtPlayersTab(false);
    }
    if (typeof fk_liveViewer != 'undefined' && fk_liveViewer.get('tab') == fk_currentTab && !fk_liveViewer.get('running')) {
      fk_liveViewer.set('running', true);
      divScroll.activeScroll(true);
      liveTimer = setTimeout("fk_livePlay()", liveTimeout * liveTimeoutSpeed);
    }
  }
}

function fk_updateData(pars, form) {
  if (form && form !== 1) {
    pars += (pars.length > 0 ? '&' : '') + $(form).serialize();
  }
  pars = pars.replace('?', '');

  var myAjax = new Ajax.Request('?', { 
    parameters: pars,
    onCreate: function () {
      // add progress mouse

      // fk_loadingEventElement = window.event && Event.findElement(window.event);
      // [document.body, fk_loadingEventElement].invoke('addClassName', 'progress');

      document.body.addClassName('progress');
    },
    onComplete: function (transport) { 
      fk_onComplete();
      
      // remove progress mouse
      // [document.body, fk_loadingEventElement].invoke('removeClassName', 'progress');

      document.body.removeClassName('progress');
    },
    onSuccess: function (transport, json) {
      if (json.alert){
        alert(json.alert);
      }
      if (json.log) {
        json.log.each(function (e) {
          console.log(e);
        });
      }

      if (fk_alerts) {
        alert('fk_updateData() response: ' + transport.responseText); // Used to be able to see the error output for this type of server request.
      }
      var str, head = $$('head')[0];
      
      if (json.js) {
        json.js.each(function (file) {
          if (!($('js')||head).select('script[type=text/javascript][src]').invoke('readAttribute', 'src').include(file)) {
            ($('js') || head).insert({'bottom': new Element('script', { type: 'text/javascript', src: file }) });
          }
        });
      }
      if (json.css) {
        json.css.each(function (file) {
          if (!head.select('script[type=text/javascript][href]').invoke('readAttribute', 'href').include(file)) {
            head.insert({'bottom': new Element('link', { 'type': 'text/css', 'rel': 'stylesheet', 'href': file, 'media': 'screen' }) });
          }
        });
      }
      if (json.check_tables) {
        if (json.check_tables.status && check_tables.table[(check_tables.counter-1)]) {
          var status = json.check_tables.status;
          $('results').update('Database: <b>' + (check_tables.zold ? 'zold' : 'freekick') + ' (' + check_tables.counter + ' / ' + check_tables.total + ')</b><br /><br />' + 'running: <b>' + (check_tables.table[check_tables.counter] ? (status.fail ? 'failed' : check_tables.table[check_tables.counter]) : 'ALL DONE! (' + check_tables.counter + ')') + '</b>' + '<br /><br />' + 'Table: <b>' + status.table + '</b>' + (status.fail ? '(failed)' : '') + '<br />' + 'Op: <b>' + status.op + '</b><br />' + 'Type: <b>' + status.type + '</b><br />' + 'Text: <b>' + status.text + '</b><br />');
          if (!status.fail) {
            check_tables();
          }
        }
      }
      if (json.checkConsistency) {
        fk_checkConsistency(json.checkConsistency);
      }
      if (json.convertmr) {//Anders matchrapportskonvertering från zold
        convertmr(json.convertmr);
      }
      if (json.upload_mr) {
        var tmp;
        if (json.upload_mr.step == '') {
          $('running').remove();
        }
        $('results').innerHTML += '<br />Running database: <b>' + json.upload_mr.table + '</b> (step) ' + json.upload_mr.step;
        if (json.upload_mr.step) {
          fk_upload_mr(json.upload_mr.step, json.upload_mr.zold_tables);
        }
      }
      if (json.fixname) {
        //console.log('rad 240 table = ' + json.fixname.table + ' firstlast = ' + json.fixname.firstlast + ' step =' + json.fixname.step + ' name = ' + json.fixname.name + ' ids =' + json.fixname.ids);
        $('results').innerHTML += '<br />' + json.fixname.table;
        if (json.fixname.step) {
          fk_fixname(json.fixname.table, json.fixname.firstlast, json.fixname.step, json.fixname.name, json.fixname.ids, json.fixname.i, json.fixname.j, json.fixname.k);
        }
      }

      if (json.deleteRow) {
        //$(json.removeBookmark.table).deleteRow($(json.removeBookmark.id).rowIndex);  
        var row = $(json.deleteRow), table = row.up('table');
        table.deleteRow(row.rowIndex);

        alternateRows.init(table);
      }
      
      
      /* remove this av use json.confirm instead? */
      if (json.bidConfirm) {
        if (json.bidConfirm.type == 'alert') {
          alert(json.bidConfirm.alert);
        } else {
          if (confirm(json.bidConfirm.confirm)) {
            str = '?loc=' + json.bidConfirm.loc + '&bidvalue=' + json.bidConfirm.bidValue + '&agent_avg=' + json.bidConfirm.agentAvg + '&agent_max=' + json.bidConfirm.agentMax + '&control_id=' + json.bidConfirm.controlId + '&ajax=1';
            if (fk_alerts) {
              alert(str); 
            }
            fk_loadContent(str, json.bidConfirm.tab, 1);
          }
        }
      }
      
      if (json.registerCheck) {
        console.log(json.registerCheck);
        var fieldObjId = json.registerCheck.fieldObjId;
        var fieldLoadingObjId = fieldObjId + '_status_loading';
        fk_hideGroupOfElements(fieldObjId + '_status');

        $(fieldLoadingObjId).addClassName('hidden').update(fk_loadingContent).removeClassName('hidden');

        fk_setRegFieldStatus(fieldObjId, json.registerCheck.status, json.registerCheck.statusTextId);
      }
      
      if (json.confirm) {
        if (json.confirm.alert) {
          alert(json.confirm.alert);
        } else {
          if (confirm(json.confirm.confirm)) {
            str = '?loc=' + json.confirm.loc;
            
            if (json.confirm.disableButton) {
              var disableButton = $(json.confirm.disableButton);
              if (disableButton) {
                disableButton.disable();
              }
            }
            
            if (json.confirm.params) {
              $H(json.confirm.params).keys().each(function(key){
                str += '&' + key + '=' + json.confirm.params[key];
              });
            }
            
            if (json.confirm.ajax) {
              str += '&ajax=' + json.confirm.ajax;
            }
            
              
            if (fk_alerts) {
              alert('confirm:\n\n' + str); 
            }
            
            
            switch (json.confirm.ajax) {
              case 1:
                fk_loadContent(str, (json.confirm.tab||fk_currentTab), (json.confirm.form || 1));
                break;
              case 2:
                fk_updateData(str, (json.confirm.form || 1));
                break;
              default:
                $('main-content').hide();
                $('main-loading').show();
                window.location = str;
                break;
            }
          } else {
            if (json.confirm.deny) {
              str = '?loc=' + json.confirm.deny.loc;
                  
              if (json.confirm.deny.params) {
                $H(json.confirm.deny.params).keys().each(function (key) {
                  str += '&' + key + '=' + json.confirm.deny.params[key];
                });
              }
              
              if (json.confirm.deny.ajax) {
                str += '&ajax=' + json.confirm.deny.ajax;
              }
              
              if (fk_alerts) {
                alert('confirm (deny):\n\n' + str); 
              }
              
              switch (json.confirm.deny.ajax) {
                case 1:
                  fk_loadContent(str, json.confirm.deny.tab, (json.confirm.form ? json.confirm.form : 1));
                  break;
                case 2:
                  /* naz: test adding form */
                  fk_updateData(str, (json.confirm.form ? json.confirm.form : 1));
                  break;
                default:
                  $('main-content').hide();
                  $('main-loading').show();
                  window.location = str;
                  break;
              }
            }
          }
        }
      }
      if (json.money) {
        $('club-money').update(json.money.amount);
      }
      if (json.content) {
        $(json.content.id).update(json.content.html);

        if (json.content.reference && json.content.container) {
          $(json.content.container).style.height = $(json.content.reference).offsetHeight + 'px';
        }
      }
      if (json.contentContent) {

        var el = $(json.contentContent.id);
        el.update(transport.responseText);

        if (json.contentContent.reference && json.contentContent.container) {
          $(json.contentContent.container).style.height = $(json.contentContent.reference).offsetHeight + 'px';
        }
      }
      if (json.playerStatisticsLoaded) {
        $(json.playerStatisticsLoaded.id).removeClassName('loading');
        fk_playersStatisticsLoaded = 1;
      }
      if (json.killLink) {
        var obj = $(json.killLink.id);
        obj.addClassName('dead-link');
        obj.onclick = function(){return false;};
        //obj.href = '#';
      }

      if (json.messages) {
        fk_msgAction(json.messages);
      }
      if (json.redirect) {
        // $('main-content').update(fk_loadingContent);
        $('main-content').hide();
        $('main-loading').show();

        str = '?loc=' + json.redirect.loc;
        if (json.redirect.error) {
          str += '&error=' + json.redirect.error;
        }
        if (fk_alerts) {
          alert(str); 

        }
        window.location = str;
      }
      if (json.initiateLoadTabs) {
        str = json.initiateLoadTabs.loadTabs + '&tab=' + fk_currentTab + '&subtab=' + fk_currentSubTab[fk_currentTab] + '&ajax=2';
        if (fk_alerts) {
          alert('fk_updateData initiateLoadTabs');
          alert(str);
        }
        // $('main-content').update(fk_loadingContent);
        fk_updateData(str, null);
      }
      if (json.loadTabs != null) {
        if (fk_alerts) {
          alert('fk_updateData loadTabs');
        }
        var part = transport.responseText.split('{{{[[[loadTabs]]]}}}'),
            length = part.length,
            content = true,
            number;
        if (fk_alerts) {
          alert(part[0]); // Used to be able to see the error output for this type of server request.
        }
        for (i = 0; i < length; i++) {
          content = !content;
          if (content) {
            if (number == json.loadTabs) {
              $('main-content').update(part[i]);
              part[i].evalScripts();
            } else {
              fk_loadedTab[number] = part[i];
            }  
          } else {
            number = Number(part[i]);
          }
        }
      }
      if (json.unloadTabs) {
        if (fk_alerts) {
          alert('fk_updateData unloadTabs');
        }
        var tabs = json.unloadTabs.tabs,
            length = tabs.length,
            i;
        for (i = 0; i < length; i++) {
          fk_loadedTab[tabs[i]] = null;
          fk_savedForm[tabs[i]] = null;
        }
      }
      if (json.loadTab) {
        str = 'loc=' + json.loadTab.loc + '&ajax=1';
        if (fk_alerts) {
          alert('fk_updateData loadTab');
          alert(str);
        }
        // $('main-content').update(fk_loadingContent);
        fk_loadContent(str, fk_currentTab, 1);
      }
      if (json.collapseExpand) {
        if (fk_alerts) {
          alert('fk_updateData collapseExpand');
        }

        json.collapseExpand.list.each(function(l){
           fk_collapse(l, json.collapseExpand.action);
        });
        /*
        for (var i = 0, length = json.collapseExpand.list.length; i < length; i++) {
          fk_collapse(json.collapseExpand.list[i], json.collapseExpand.action);
        }
        */
      }
      if (json.updateResultsToggle) {
        fk_results = json.updateResultsToggle.status;
        var button = $('results_toggle');
        button.update(json.updateResultsToggle.text);
        button.blur();
      }
      if (json.updateFormToggle) {
        fk_withForm = Number(json.updateFormToggle.status);
        var button = $('form_toggle');
        if (fk_withForm) {
          button.removeClassName('off');
          button.addClassName('on');
          button.update(json.updateFormToggle.text);
        } else {
          button.removeClassName('on');
          button.addClassName('off');
          button.update(json.updateFormToggle.text);
        }
        button.blur();
      }
      if (json.updateRatingToggle) {
        fk_withRating = json.updateRatingToggle.status;
        var button = $('rating_toggle');
        button.update(json.updateRatingToggle.text);
        button.blur();
      }
      if (json.updateSkillsToggle) {
        fk_withSkills = json.updateSkillsToggle.status;
        var button = $('skills_toggle');
        button.update(json.updateSkillsToggle.text);
        button.blur();
      }
      if (json.updateMfSkillsToggle) {
        fk_withMfSkills = Number(json.updateMfSkillsToggle.status);
        var button = $('mf_skills_toggle');
        if (fk_withMfSkills) {
          button.removeClassName('off');
          button.addClassName('on');
          button.update(json.updateMfSkillsToggle.text);
        } else {
          button.removeClassName('on');
          button.addClassName('off');
          button.update(json.updateMfSkillsToggle.text);
        }
        button.blur();
      }
      if (json.siteHelp) {
        Tip(json.siteHelp.content, TITLE, json.siteHelp.title + ($('nav-bar') || $('blue-nav')).innerHTML, DELAY, 0, STICKY, true, CLOSEBTN, true, WIDTH, 350, FOLLOWSCROLL, true, FIX, [10, 10]);
      }
      if (json.disableSubmit) {
        fk_disableSubmit();
      }
      if (json.removePlayerFromLineup) {
        fk_removePlayerFromLineup(json.removePlayerFromLineup.player, json.removePlayerFromLineup.row, json.removePlayerFromLineup.activeChoiceClass);
        if (json.removePlayerFromLineup.status) {
          fk_updateLineupStatus(json.removePlayerFromLineup.status);
        }
      }
      if (json.addPlayerInLineup) {
        if (json.addPlayerInLineup.failed) {
          $('add_player').disable();
          alert(json.addPlayerInLineup.failed);
        } else {
          fk_addPlayerInLineup(json.addPlayerInLineup.player);
          if (json.addPlayerInLineup.status) {
            fk_updateLineupStatus(json.addPlayerInLineup.status);
          }
        }
      }
      if (json.editPlayerInLineup) {
        if (json.editPlayerInLineup.failed) {
          $('edit_player').disabled = false;
          $('cancel_edit').disabled = false;
          alert(json.editPlayerInLineup.failed);
        } else {
          fk_editPlayerInLineup(json.editPlayerInLineup.player, json.editPlayerInLineup.gkTab);
          if (json.editPlayerInLineup.status) {
            fk_updateLineupStatus(json.editPlayerInLineup.status);
          }
        }
      }
      if (json.changeSearchLeagues) {
        $('search-division').update(json.changeSearchLeagues.division);
        $('search-series').update(json.changeSearchLeagues.series);
        $('num-series').update(json.changeSearchLeagues.numSeries);
      }
      if (json.forumlogin) {
        $('username').value = json.forumlogin.username;
        $('password').value = json.forumlogin.password;
        $('forum-form').submit();
      }
      if (json.forumopen) {
        $('forum-form').submit();
      }
      if (json.phpbb3login) {
        $('username').value = json.phpbb3login.username;
        $('password').value = json.phpbb3login.password;
        $('forum-form').submit();
      }
      if (json.dutyInfo) {
        $('dutyInfo').update(json.dutyInfo.content);
      }
      if (json.reSearch) {
        if (fk_loadedTab[json.reSearch.search]) {
          $('main-content').update(fk_loadedTab[json.reSearch.search]);
          var tabs = $$('.tab-active'),
              length = tabs.length,
              e, i;
          for (i = 0; i < length; i++) {
            e = tabs[i];
            if (e.id != ('main-tabs_' + json.reSearch.search) && e.id != ('footer-tabs_' + json.reSearch.search)) {
              e.addClassName('tab-hidden').removeClassName('tab-active');
            }
          }
          $('main-tabs_' + json.reSearch.search).addClassName('tab-active').removeClassName('tab-hidden');

          fk_currentTab = json.reSearch.search;
          fk_updateForms(json.reSearch.search);
          fk_loadContent('loc=transfers.results&ajax=1', json.reSearch.results, json.reSearch.form);
        }
      }
      if (json.moveListItem) {
        var element = $(json.moveListItem.id), sibling, list, imgs;
        switch (json.moveListItem.dir) {
          case -1:
            sibling = element.previous();
            sibling.insert({before: element});
            break;
          case 1:
            sibling = element.next();
            sibling.insert({after: element});
            break;
        }
        
        list = element.up('ul').select('li[id]');
        [element, sibling].each(function(el){
            imgs = (el.down('.move-arrows')||el.down('.move-arrow')).descendants();
            imgs.each(function(img){
              if (el === list.first()) {
                if (img.hasClassName('move-arrow-up')) {
                  img.removeClassName('move-arrow-up').addClassName('move-arrow-up-disabled');
                }
              } else {
                if (img.hasClassName('move-arrow-up-disabled')) {
                  img.removeClassName('move-arrow-up-disabled').addClassName('move-arrow-up');
                }
              }
              
              if (el === list.last()) {
                if (img.hasClassName('move-arrow-down')) {
                  img.removeClassName('move-arrow-down').addClassName('move-arrow-down-disabled');
                }
              } else {
                if (img.hasClassName('move-arrow-down-disabled')) {
                  img.removeClassName('move-arrow-down-disabled').addClassName('move-arrow-down');
                }
              }
            });
        });
      }
      if (json.set_pieces) {
        $('side').enable().removeClassName('invisible').setValue(json.set_pieces.side);
        fk_addInstruction.init($('side'));
        
        $('options').enable().removeClassName('invisible').setValue(json.set_pieces.option);
        fk_addInstruction.init($('options'));
        
        if (json.set_pieces.modification) {
          $('modification').enable().removeClassName('invisible').setValue(json.set_pieces.modification);
        } else {
          $('modification').disable().addClassName('invisible');
        }

        $('number').setValue(json.set_pieces.edit);
        
        $('add-instruction').disable().hide();
        $('edit-instruction').enable().show();
      }
      if (json.toto) {
        // autofíll (random, lastweek)
        if (json.toto.autofill) {
          $H(json.toto.autofill).keys().each(function(key){
            $('toto-row-'+key).select('input[type=radio][name^=match]')[json.toto.autofill[key]].checked = true;
          });
        } 
        
        // error
        if (json.toto.error) {
          $H(json.toto.error).keys().each(function(row){
            $('toto-row-'+row).down('.error-icon').removeClassName('hidden').writeAttribute('title', json.toto.error[row]);
          });
        }
      }
      if (json.tour) {
        $('tour-image').update(json.tour.image).setStyle({
          'background-color': json.tour.image
        });
        $('tour-info').update(json.tour.info);
      }
      if (json.specialString) {
        fk_specialString = json.specialString.str;
      }
    }
  });
}

document.on("dom:loaded",function(){
  if (!document.head) {
    document.head = $$('head')[0];

  }

  if (!document.body) {
    document.body = $$('body')[0];
  }

  document.on('click', '.highlightable', fk_highlightable);

  /* Placeholder */
  $$('input[placeholder]', 'textarea[placeholder]').each(function(element) {
    $(element).addPlaceholder();
  });

  fk_onComplete();
});
Ajax.Responders.register({
  onFailure: function (json) {
    if (json.redirect) {
      $('main-content').hide();
      $('main-loading').show();
      str = '?loc=' + json.redirect.loc + '&error=' + json.redirect.error;
      if (fk_alerts) {
        alert(str); 
      }
      window.location = str;
    }
    // [document.body, fk_loadingEventElement].invoke('removeClassName', 'progress');
    document.body.removeClassName('progress');
  }
});





var fk_onComplete = function(scope){
  // check for native autofocus support
  var _nativeAutofocus = (function () {
    var i = document.createElement('input');
    return 'autofocus' in i;
  }());
  
  if (!_nativeAutofocus) {
    (function () {
      var element = $$('[autofocus]');

      if (element && element[0]) {
        element[0].focus();
      }
    }());
  }
  
  /* Placeholder */
  $$('input[placeholder]', 'textarea[placeholder]').each(function (element) {
    $(element).addPlaceholder();
  });

  scope = scope || $('main-content');

  // alternate row coloring
  scope.select('.alternate').each(function(e){
    alternateRows.init(e);
  });

  // simple table row coloring
  scope.select('.st-body').each(function(e){
    e.select('tr:nth-child(even)').invoke('addClassName', 'even');
    e.select('tr:nth-child(odd)').invoke('addClassName', 'odd');
  });

};

var alternateRows = new (Class.create({
  initialize: function () {
    Object.extend(this, {
      alternateClass: ['alternateEven', 'alternateOdd'],
      headerRowClass: 'alternateRowHeader',
      rowClass: 'alternateRow',
      
      ignore: (function () {
        var classNames = $w((document.body || $$('body')[0] || '').className);
        if (!classNames) { return; }
        return (classNames.indexOf('ff3') !== -1);
      }())
    });
    return this;
  },
  init: function (element) {
    "use strict";
    // console.time('alternate::init()');
    
    element = $(element);
    if (!element) { throw 'Element: ' + element; }
    if (!element.hasClassName('alternate')) {  element = element.up('.alternate'); }
    
    var rows = [], i = 1, className = '', classNames = [], marked = 0;
    
    if ('table' === element.nodeName.toLowerCase()) {
      rows = element.select('tr:not(.no-alternate,.hidden)');
      //if (rows && ('th' === rows[0].firstDescendant().nodeName.toLowerCase())) {
      if (rows[0] && rows[0].match(':has(th)')) {
        rows[0].addClassName(this.rowClass + ' ' + this.headerRowClass);
        rows.shift();
      }
    } else {
      rows = Selector.matchElements(element.childElements(), ':not(.no-alternate,.hidden,' + this.headerRowClass + ')');
    }

    // console.log(this.ignore + ' ' + rows.length);

    if (!rows) { return; }
    
    // console.log((this.ignore ? 'true' : 'false') + ' & ' + rows.length);
    if (this.ignore && rows.length > 200) { return; }
    
    // console.time(' alternate each rows');
    
    rows.each(function (row) {
      // create an array with all the rows classes
      classNames = $w(row.className);
      
      // skip if row have class no-alternate
      if (-1 !== classNames.indexOf('no-alternate')) { return; }
      
      // look for table header
      if (('tr' === row.nodeName.toLowerCase()) && ('th' === row.firstDescendant().nodeName.toLowerCase())) {
        // console.log(row);
        i = 0;
        className = ' ' + this.headerRowClass;
      } else if (-1 === classNames.indexOf('sortfixed')) {
        // if not sortfix
        className = '';
        
        // only add this.rowClass once
        if (-1 !== classNames.indexOf(this.rowClass)) {
          className = this.rowClass;
        }
        
        className += ' ' + this.alternateClass[i % 2];
        
        // check for existing even/odd classes
        if (-1 !== classNames.indexOf(this.alternateClass[0])) {
          classNames = classNames.without(this.alternateClass[0]);
        } else if (-1 !== classNames.indexOf(this.alternateClass[1])) {
          classNames = classNames.without(this.alternateClass[1]);
        }
        
        // check for existing marked even/odd
        marked = 0;
        if (-1 !== classNames.indexOf(this.alternateClass[0] + 'Marked')) {
          classNames = classNames.without(this.alternateClass[0] + 'Marked');
          marked = 1;
        } else if (-1 !== classNames.indexOf(this.alternateClass[1] + 'Marked')) {
          classNames = classNames.without(this.alternateClass[1] + 'Marked');
          marked = 1;
        }
        if (marked) {
          className += ' ' + className + 'Marked';
        }
      }
      // add the classnames to the row
      classNames.push(this.rowClass, className);
      row.className = classNames.join(' ');
      i = i + 1;
      return;
    }.bind(this));
    // console.timeEnd(' alternate each rows');
    // console.timeEnd('alternate::init()');
    // console.log('----------');
    return element;
  }
}))();


var fk_alternate = function(root) {
  var rows,isEven = 1, altClass;
  if (!root.hasClassName('alternate')) {
    root=root.up('.alternate');
  }
  
  if (!root) { return; }
  
  if ('table' === root.nodeName.toLowerCase()) {
    rows = root.select('tr:not(.no-alternate):not(.hidden)');
  } else {
    rows = root.childElements();
  }
  
  if (!rows) { return; }

  rows.each(function (r) {
    r.addClassName('alternateRow');
    
    if ('tr' === r.nodeName.toLowerCase()) {
      if (('th' === r.firstDescendant().nodeName.toLowerCase())) {
        isEven = 1;
        r.addClassName('alternateRowHeader');
      }
    }

    if (r.hasClassName('alternateRowHeader')) { return; }
    if (r.hasClassName('sortfixed')) { return; }

    isEven = !isEven;
    r.removeClassName('none');

    r.removeClassName('alternateEven').removeClassName('alternateOdd');
    altClass = (isEven ? 'Even' : 'Odd');

    r.addClassName('alternate' + altClass);
    if (r.hasClassName('alternateEvenMarked') || r.hasClassName('alternateOddMarked')) {
      r.removeClassName('alternateEvenMarked').removeClassName('alternateOddMarked').addClassName('alternate' + altClass + 'Marked');
    }
  });
}
if (!fk_alternate) {
  var fk_alternate = function(e) {
    return alternateRows.init(e);
  };
}

var fk_highlightable = function(ev, root){
  var el = ev.findElement(),row;

  if (el.hasClassName('no-highlight') || el.up('.no-highlight')) {
    return; 
  }
  
  switch (root.nodeName.toLowerCase()) {
  case 'table':
    row = ('tr' === el.nodeName.toLowerCase()) ? el : el.up('tr');
    if (row && !row.down('td')) { return; }
    break;
  case 'ul':
  case 'ol':
    row = ('li' === el.nodeName.toLowerCase()) ? el : el.up('li');
    break;
  default:
    row = (el.hasClassName('alternateRow') || el.up('.alternateRow'));
  }
  
  if (!row) {
    return;
  }
  
  if (row.hasClassName('alternateOdd')) {
    row.toggleClassName('alternateOddMarked');
  } else if (row.hasClassName('alternateEven')) {
    row.toggleClassName('alternateEvenMarked');
  } else {
    row.toggleClassName('alternateMarked');
  }

  if (typeof row._marked == undefined) {
    row._marked = 0;
  }
  row._marked = !row._marked;
};






function fk_inputType(el) {
  var type = 0, 
      tag = el.tagName.toLowerCase(), 
      att;
  if ('textarea' === tag) {
    type = 5;
  } else if ('select' === tag) {
    type = 6;
  } else if ('input' === tag) {
    att = el.readAttribute('type').toLowerCase();

    switch (att) {
    case 'hidden':
      type = 4;
      break;
    case 'radio':
      type = 3;
      break;
    case 'checkbox':
      type = 2;
      break;
    case 'text':
      type = 1;
      break;
    default:
      type = 0;
    }
  }
  return type;
}

function fk_saveForms(tab) {
  if (Prototype.Browser.IE) {
    return;
  }

  var arrForm = $('main-content').getElementsByTagName('form'),
      formLength = arrForm.length,
      arrElement,
      elementLength,
      forms = [],
      inputs,
      i, j, k;
  

  for (i = 0; i < formLength; i++) {
    inputs = [];
    arrElement = $(arrForm[i].id).getElements();
    elementLength = arrElement.length;
    for (j = 0; j < elementLength; j++) {
      switch (fk_inputType(arrElement[j])) {
      case 1:
        // text
      case 4:
        // hidden
      case 5:
        // textarea
        inputs[j] = $F(arrElement[j]);
        break;
      case 2:
        // checkbox
      case 3:
        // radio
        if ($F(arrElement[j]) == null) {
          inputs[j] = 0;
        } else {
          inputs[j] = 1;
        }
        break;
      case 6:
        // select
        if (arrElement[j].multiple) {
          inputs[j] = [];
          for (k = 0; k < arrElement[j].options.length; k++) {
            if (arrElement[j].options[k].selected) {
              inputs[j][k] = 1;
            } else  {
              inputs[j][k] = 0;
            }
          }
        } else{
          inputs[j] = arrElement[j].selectedIndex;
        }
        break;
      }
    }
    forms[i] = inputs;
  }
  fk_savedForm[tab] = forms;

}

function fk_updateForms(tab) {
  if (Prototype.Browser.IE) {
    return;
  }
  
  if (fk_savedForm[tab]) {
    var arrForm = $('main-content').getElementsByTagName('form'),
        formLength = arrForm.length,
        arrElement,
        elementLength,
        i, j, k;
    for (i = 0; i < formLength; i++) {
      arrElement = $(arrForm[i].id).getElements();
      elementLength = arrElement.length;
      for (j = 0; j < elementLength; j++) {
        switch (fk_inputType(arrElement[j])) {
        case 1:
          // text
        case 4:
          // hidden
        case 5:
          // textarea
          arrElement[j].value = fk_savedForm[tab][i][j];
          break;
        case 2:
          // checkbox
        case 3:
          // radio
          if (fk_savedForm[tab][i][j]) {
            arrElement[j].checked = true;
          } else {
            arrElement[j].checked = false;
          }
          break;
        case 6:
          // select
          if (arrElement[j].multiple) {
            for (k = 0; k < arrElement[j].options.length; k++) {
              if (fk_savedForm[tab][i][j][k]) {
                arrElement[j].options[k].selected = true;
              } else {
                arrElement[j].options[k].selected = false;
              }
            }
          } else{
            arrElement[j].selectedIndex = fk_savedForm[tab][i][j];
          }
          break;
        }
      }
    }
  }
}

function fk_siteHelp(loc) {
  var str = 'loc=' + loc + '&site_help=' + fk_currentTab + '&ajax=2';
  if (fk_alerts) {
    alert(str); 
  }
  fk_updateData(str, null);
  return false;
}

function fk_toggleSetting(type, loc) {
  var str;
  switch (type) {
  case 'results':
    if (fk_specialString) {
      loc = fk_specialString;
    }
    str = 'loc=' + loc + '&toggle_results=' + (fk_results == 'hide' ? 'show' : 'hide') + '&tab=' + fk_currentTab + '&subtab=' + fk_currentSubTab[fk_currentTab] + '&ajax=2';
    break;
  case 'form':
    str = 'loc=' + loc + '&toggle_form=' + (fk_withForm == 0 ? 1 : 0) + '&tab=' + fk_currentTab + '&subtab=' + fk_currentSubTab[fk_currentTab] + '&ajax=2';
    break;
  case 'rating':
    str = 'loc=' + loc + '&toggle_rating=' + (fk_withRating == 'talent' ? 'current' : 'talent') + '&tab=' + fk_currentTab + '&subtab=' + fk_currentSubTab[fk_currentTab] + '&ajax=2';
    break;
  case 'skills':
    str = 'loc=' + loc + '&toggle_skills=' + (fk_withSkills == 'potential' ? 'current' : 'potential') + '&tab=' + fk_currentTab + '&subtab=' + fk_currentSubTab[fk_currentTab] + '&ajax=2';
    break;
  case 'mf_skills':
    str = 'loc=' + loc + '&toggle_mf_skills=' + (fk_withMfSkills == 0 ? 1 : 0) + '&tab=' + fk_currentTab + '&subtab=' + fk_currentSubTab[fk_currentTab] + '&ajax=2';
    break;
  }
  if (fk_alerts) {
    alert(str); 
  }
  fk_updateData(str, null);
  return false;
}

function fk_cleanNumber(elem) {
  var num = Math.abs(parseInt(elem.value, 10));
  if (isNaN(num)) {
    elem.clear();
  } else {
    elem.value = num;
  }
}


(function () {
  // FORM ELEMENT
  
  Element.addMethods(['INPUT', 'TEXTAREA'],{
    empty: function (element) {
      return ($F(element).empty() || element.hasClassName('placeholder'));
    }
  });

  
  // check for native placeholder support
  (function () {
    // PLACEHOLDER (singleton)
    var placeholderControl = new (Class.create({
      // only runs once
      initialize: function () {
        Object.extend(this, {
          // check for native support
          _nativePlaceholder: (function() {
            var i = document.createElement('input');
            return 'placeholder' in i;
          }()),
          // onfocus event
          onfocus: function (event, element) {
            element = element || event.findElement();

            if (element.readAttribute('placeholder') === $F(element)) {
              element.removeClassName('placeholder').clear();
            }
          },
  
          // onblur event
          onblur: function (event) {
            var element = event.findElement();
            
            if (element.empty()) {
              element.addClassName('placeholder').setValue(element.readAttribute('placeholder'));
            }
          },
          ignore: (function () {
            return (Prototype.Browser.MobileSafari && /iPhone OS 3/.test(navigator.userAgent));
          }())
        });
        
        // return the class
        return this;
      },
      
      // init() is called on each elements
      init: function (element) {
        if (this.ignore || this._nativePlaceholder) { return element; }
        // read the placeholder attribute
        var value = element.readAttribute('placeholder');
        
        // turn off autocomplete
        if (element.id !== 'username') {
          element.writeAttribute('autocomplete', 'off');
        }        
        
        // add title if needed
        if (!element.title) { element.writeAttribute('title', value); }
        
        // if empty add placeholder class and value
        if (element.empty() && !element.hasAttribute('autofocus')) {
          element.addClassName('placeholder').setValue(value);
        }
        
        // add the event listeners
        element.observe('focus', this.onfocus.bind(this)).observe('blur', this.onblur.bind(this));
               
        // returns the element
        return element;
      }    
    }))();
    
    
    // add as a Method for the elements
    Element.addMethods(['INPUT', 'TEXTAREA'], {
      addPlaceholder: function (element) {
        return placeholderControl.init($(element));
      }
    });
  }());

  // singleton version of textarea autogrow functionality
  var autogrowControl = new (Class.create({
    // main initialize, only runs once
    initialize: function () {
      // add default properties
      Object.extend(this, {
        autogrow: null,
        shadow: null
      });
      return this;
    },
    
    // runs on each new element
    init: function (element) {
      // only run if element exists in the DOM 
      if (!(element = $(element))) { return null; }
      
      // check if the element already is initialized
      if (this.autogrow !== element) {
        // set the elements minimum height avalue
        if (!element.minHeight) {
          element.minHeight = element.measure('height');
        }
        
        // save the element in the autogrow namespace
        this.autogrow = element;
        
        // handler shortcut
        var handler = this.update.bind(this);
        // add events 
        this.autogrow.observe('focus', handler)
                     .observe('keyup', handler)
                     .observe('update', handler)
                     .observe('paste', handler); 
      }
      // set the shadow
      this.shadow = this.getShadow();
      this.update(element);

      return element;
    },
    
    // the handler
    update: function (event) {
      // which element triggered?
      // check if the event is a element
      var element = (Object.isElement(event) ? event : event.findElement());
      
      // extent element and check if it's the current element
      if ((element = $(element)) && (this.autogrow !== element)) {
        // set as current element
        this.autogrow = element;
      }
      
      if (this.autogrow) {
        // get the shadow
        this.shadow = this.getShadow();
        
        // quit if no shadow
        if (!this.shadow) return;
        
        // get the textarea content and replace new line with <br />
        var str = $F(this.autogrow).gsub(/\n/, '<br />');
        
        // update shadow with textarea content if different
        if (this.shadow.innerHTML != str) {
          // do shadow content update
          this.shadow.update(str);
        }

        // get layouts
        this.autogrow.layout = this.autogrow.getLayout();
        this.shadow.layout = this.shadow.getLayout();
        
        // set width
        if (!this.shadow.style.width) {
          this.shadow.setStyle({ 
            'width': Math.max(this.autogrow.layout.get('border-box-width'), 0) + 'px' 
          });
        }
        
        // compare textarea vs shadow height
        if (this.autogrow.layout.get('border-box-height') !== this.shadow.layout.get('border-box-height')) {
          // set the new height
          this.autogrow.setStyle({ 
            'height': (Math.max(this.shadow.layout.get('border-box-height'), this.autogrow.minHeight))+'px' 
          });
        }
      } else if (this.shadow) {
        // if !autogrow and shadow, remove shadow
        this.shadow.remove();
        this.shadow = null;
      }
    },
    getShadow: function () {
      // if no shadow
      if (!this.shadow) {
        // create shadow
        // and add styles
        this.shadow = new Element('div', {
          'class': 'autogrow-shadow'
        });
        document.body.insert({ bottom: this.shadow });
      }
      // return the shadow
      return this.shadow;
    }
  }))();
  
  // add as a Method for the element
  Element.addMethods('TEXTAREA', {
    autogrow: function (element) {
      element = $(element);
      autogrowControl.init(element);
      return element;
    }
  });
  
}());

var fk_addAutogrow = function (element) {
  return element.autogrow();
};

var Toggler = new (Class.create({
  initialize: function(){
    Object.extend(this, {
      active:  null
    });

    document.on('click', function(event) {
      if (this.getActive() && !event.findElement().descendantOf(this.getActive())) {
        this.hide();
      }
    }.bind(this));

    return this;
  },

  getActive: function() {
    return this.active;
  },

  root: function(element) {
    return element.up('.toggler-holder');
  },

  show: function(element) {
    if (element !== this.active) {
      if (this.active) {
        this.hide();
      }
      this.active = this.root(element);
      this.active.addClassName('toggler');
      
    }
  },
  hide: function(element) {
    if (this.active && (!element || element === this.active)) {
      this.active.removeClassName('toggler');
      this.active = null;
    }
  },

  toggle: function (element) {
    if (this.active === this.root(element)) {
      this.hide();
    } else {
      this.show(element);
    }
  }
}));

function fk_toggleActiveListItem(el) {
  el=$(el);
  if (el.nodeName.toLowerCase() != 'li') {
    el=el.up('li');
  }
  el.addClassName('active').siblings().invoke('removeClassName', 'active');
}
function fk_toggleListItems(el) {
  el=$(el);
  var p=el.up();
  el.toggleClassName('list-icon-expanded').toggleClassName('list-icon-collapsed');
  el.next().toggleClassName('hidden');
  
  if (!el.next().hasClassName('hidden')) {
    p.siblings().each(function(e){
      e.down('a').removeClassName('list-icon-expanded').addClassName('list-icon-collapsed')
       .next('ul').addClassName('hidden')
       .down('li').removeClassName('hidden');
      
    });
  }
}

// new clock function
var fk_clock = (function(){
  var timer = null, diff = null, clock = null;
  function start(y, m, d, h, min, sec){
    if (timer) {
      stop();
    }
//  diff = client - server
    diff = (+new Date()) - (+new Date(y, m, d, h, min, sec));

    timer = setInterval(update, 1000);
  }
  function stop() {
    clearInterval(timer);
    timer = null;
  }
  function update(){
    var now = new Date(), h, m, s;

    // now.setTime(now.getTime() - diff);
    now.setTime((+now) - diff);

    h = now.getHours();
    m = now.getMinutes();
    s = now.getSeconds();
    
    if (h < 10) { h = '0' + h; }
    if (m < 10) { m = '0' + m; }
    if (s < 10) { s = '0' + s; }
    
    clock = clock || $('fk-clock');
    if (clock) {
      clock.value = '' + h + ':' + m + ':' + s;
    }
  }
  return {
    start: start,
    stop: stop
  };
}());
var fk_startclock = fk_startclock || fk_clock.start;

var fk_fetchContent = function(loc, el, forceReload) {
  if (!(el = $(el))) { new Error('Error: ' + loc + ' could now be found'); }
  if (!Object.isString(loc)) { new Error('Type Error: loc is not a string\n' + loc); }
  
  if (!!forceReload || !el.hasClassName('loaded')) {
    el.update(fk_loadingContent).addClassName('loaded').removeClassName('hidden');
    fk_updateData('loc=' + loc + '&ajax=2', 1);
  } else {
    el.toggleClassName('hidden');
  }
};

var fk_notification = (function(){
  var _registered = [], _started = false;

  var _handler = new Ajax.PeriodicalUpdater('APU', '/', {
    parameters: { 
      notification: [_registered],
      ajax: 3
    },
    method: 'get',
    frequency: 30, 
    decay: 1,

    onSuccess: function(transport, json) {
      if (json.notification) {
        var el;
        $H(json.notification).each(function(n){
          _update($('new_' + n.key), n.value);
        });
      }
    }
  });

  _handler.stop();

  var _update = function(el, value){
    if (!el || !value) {
      return;
    }

    var elCount = el.down('.new-count');

    if ('-' === value) {
      value = parseInt(elCount.innerHTML, 10) - 1;
    }

    if ('+' === value) {
      value = parseInt(elCount.innerHTML, 10) + 1;
    }

    if ('++' === value || value > 0) {
      el.addClassName('new');
    } else {
      value = 0;
      el.removeClassName('new');
    }
    elCount.update(value);
  };

  // _started = true;
  
  var _start = function() {
    if (!_started) {
      _started = true;
      _handler.start();
    }
  };

  var _stop = function() {
    if (!_started) {
      _started = false;
      _handler.stop();
    }
  };

  return {
    register: function(h){
      _registered.push(h);
      return this;
    },
    unregister: function(h) {
      _registered = _registered.without(h);
      return this;
    },

    start: _start,
    stop: _stop,

    // registered: _registered,

    update: _update
  };
}());


// idle timeout
var fk_idle = (function(){
  var events = $w('mousemove keydown DOMMouseScroll mousewheel mousedown');
  var defaultTimeout = (1000 * 60 * 10);
  var lastActive = (+new Date());
  var timeout = null;

  document.on('idle:return', function(ev) {
    lastActive = (+new Date);

    // clear old timeout
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
    // set new timeout
    timeout = setTimeout(function(){
      document.fire('idle:timeout');
    }, defaultTimeout - (+new Date) + lastActive);
  });
  // document.on('idle:timeout', function(ev) { });

  events.each(function(ev){
    document.on(ev, function(){
      document.fire('idle:return');
    });
  });

  document.fire('idle:return');       
        
  return {
    // can set and display the timeout
    timeout: function(timeout) {
      if (timeout) {
        defaultTimeout = timeout;
      } 
      return defaultTimeout;
    },
    // displays the current idletime
    idletime: function() {
      return (+new Date) - lastActive;
    }
  };
}());


