document_loaded = false;

version_element = 'tabs-page-4';
version_url_show = '';
version_url_index = '';
version_url_restore = '';

has_load = false;
delay_count = 0;
menustatus = true;

multidelete = Array();
gcwidth = Array();
gowidth = Array();

cnt_customs = Array();
cnt_cultures = Array();
cnt_domains = Array();
has_delete = Array();

function setFocus(veld) 
{
  try {
    document.getElementById(veld).focus();
  } catch(e) {}
}

function showTime()
{
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    var timeValue = ((hours < 10) ? '0' : '') + hours;
    timeValue  += ((minutes < 10) ? ":0" : ":") + minutes;
    timeValue  += ((seconds < 10) ? ":0" : ":") + seconds;
    if (document.getElementById('clock')) {
      document.getElementById('clock').innerHTML = timeValue;
    }
    timerID = setTimeout("showTime()", 1000);
}

function toggleElements(elem1, elem2, state, type) 
{
  if (!state) {
    $(elem1).style.display = 'none';
    $(elem2).style.display = type;
  }
  else {
    $(elem2).style.display = 'none';
    $(elem1).style.display = type;
  }
}

function toggleGroup(what, element)
{
	if ($(element)) {
	  if (hasClass(what, 'group-closed')) {
	    removeClass(what, 'group-closed');
	    addClass(what, 'group-open');
	    $(element).style.display = 'block';
	  }
	  else {
	    removeClass(what, 'group-open');
	    addClass(what, 'group-closed');
	    $(element).style.display = 'none';
	  }
	}
}

function toggleListGroup(what, element)
{
	if ($(element)) {
	  if (hasClass(what, 'group-closed-list')) {
	    removeClass(what, 'group-closed-list');
	    addClass(what, 'group-open-list');
	    $(element).style.display = 'block';
	  }
	  else {
	    removeClass(what, 'group-open-list');
	    addClass(what, 'group-closed-list');
	   	$(element).style.display = 'none';
	  }
	}
}

function popup(url, width, height) 
{
  options = 'width='+width+',height='+height+',scrollbars=no,toolbar=no,location=no,resize=no';
  window.open(url, 'popup', options);
}

function delay_input(inputfield, what, url)
{
  delay_count++;
  setTimeout(function() {
    delay_count--;
    if (delay_count==0) {
      new Ajax.Updater(what, url, {
        parameters: {s:$(inputfield).value},
        onLoaded: function() { $('mloader').style.display = 'none' },
        onLoading: function() { $('mloader').style.display = 'block' },
        evalScripts: true

      });
    }
  }, 500);
}

function loaderUpdate(what, url)
{
  new Ajax.Updater(what, url, {
    onLoaded: function() { $('mloader').style.display = 'none' },
    onLoading: function() { $('mloader').style.display = 'block' },
    evalScripts: true

  });
}

function toggleSubmenu(id)
{
  //return true;

  if ($(id).style.display == 'none') {
    //$(id).style.display = 'block';
    new Effect.SlideDown(id, {
      duration: 0.3
    });
    $('toggle-'+id).src = '/backend/img/menu-toggle-unfold.gif';

    set_cookie('submenu-'+id, 'open', 31);
  }
  else {
    //$(id).style.display = 'none';
    new Effect.SlideUp(id, {
      duration: 0.3
    });
    $('toggle-'+id).src = '/backend/img/menu-toggle-fold.gif';

    set_cookie('submenu-'+id, 'close', 31);
  }
}

function toggleTopbar()
{
  if (!$('search-form')) {
    return false;
  }

  if (xHeight('search-form') > 0) {
    new Effect.SlideUp($('search-form'),
    {
      duration: 0.2,
      afterFinish: function() {
        $('toggle-top-menu').style.background = 'url(/backend/img/vertical-bar-open.gif) no-repeat center';
      }
    });

    set_cookie('search-bar', 'true', 31);

  }
  else {
    new Effect.SlideDown($('search-form'),
    { duration: 0.2,
      afterFinish: function() {
        $('toggle-top-menu').style.background = 'url(/backend/img/vertical-bar-close.gif) no-repeat center';
      }
    });

    set_cookie('search-bar', 'false', 31);
  }
}

function toggleMenu(init)
{    
  if (init == 'init') {
    
    if ($('menu')) {
      try {
        $('inner-container').style.position = 'absolute';
        $('inner-container').style.top = '30px';
        $('inner-container').style.width = '99%';
        $('inner-container').style.marginLeft = '0px';
      }
      catch(e) {}

      if (get_cookie('search-bar') == 'true') {
        toggleTopbar();
      }

      menustatus = get_cookie('menustatus');
      if (menustatus == 'false') {
        menustatus = false;
        $('menu-small').style.display = 'block';
        $('menu').style.display = 'none';
        $('menu-container').style.left = '-163px';
        $('inner-container').style.left = '42px';

        $('menu-toggle-img').src = '/backend/img/bar-open.gif';
      }
      else {
        menustatus = true;

        try {
          $('menu-small').style.display = 'none';
          $('menu').style.display = 'block';
          $('menu-container').style.left = '0';
          $('inner-container').style.left = '207px';

          $('menu-toggle-img').src = '/backend/img/bar-close.gif';
        }
        catch(e) {}
      }
      
      try {
        $('inner-container').style.width = (xClientWidth() - xLeft('inner-container')) + 'px';
        $('menu-container').style.display = 'block';
        w = $('menu-container').style.height.substr(0, $('menu-container').style.height.length - 2);
        
        $('menu-container').style.height = (parseInt(w) - 30)+'px';

      }     
      catch(e) {}     
      
      return true;
    }
    else {
      // er is geen menu,bijv bij inloggen
      if ($('inner-container')) {
        $('inner-container').style.position = 'absolute';
        $('inner-container').style.marginLeft = '0px';
        $('inner-container').style.width = (xClientWidth() - xLeft('inner-container')) + 'px';

        $('menu-container').style.display = 'none';
      }
      return true;
    }
  }
  else {
    menustatus = !menustatus;
    set_cookie('menustatus', menustatus, 30);
  }

  if (menustatus) {
    new Effect.Move ($('menu-container'),{
      x: -52,
      y: 0,
      duration: 0.2,
      afterUpdate: function () {
        $('inner-container').style.left = (220 + xLeft($('menu-container')) - 14) + 'px';
      },
      afterFinish: function () {
        $('menu-small').style.display = 'none';
        $('menu').style.display = 'block';


        $('menu-toggle-img').src = '/backend/img/bar-close.gif';

        $('inner-container').style.left = (220 + xLeft($('menu-container')) - 14) + 'px';
        $('inner-container').style.width = (xClientWidth() - xLeft('inner-container')) + 'px';

        new Effect.Move ($('menu-container'),{
          x: 214,
          y: 0,
          duration: 0.3,
          afterUpdate: function () {
            $('inner-container').style.left = (220 + xLeft($('menu-container')) - 14) + 'px';
            $('inner-container').style.width = (xClientWidth() - xLeft('inner-container')) + 'px';
          },
          afterFinish: function () {
            $('inner-container').style.left = (220 + xLeft($('menu-container')) - 14) + 'px';
            $('inner-container').style.width = (xClientWidth() - xLeft('inner-container')) + 'px';
          }
        });
      }
    });

  }
  else {
    new Effect.Move ($('menu-container'),{
      x: -214,
      y: 0,
      duration: 0.3,
      afterUpdate: function () {
        $('inner-container').style.left = (220 + xLeft($('menu-container')) - 14) + 'px';
      },
      afterFinish: function () {
        $('menu-small').style.display = 'block';
        $('menu').style.display = 'none';

        $('menu-toggle-img').src = '/backend/img/bar-open.gif';

        $('inner-container').style.left = (220 + xLeft($('menu-container')) - 14) + 'px';
        $('inner-container').style.width = (xClientWidth() - xLeft('inner-container')) + 'px';

        new Effect.Move ($('menu-container'),{
          x: 52,
          y: 0,
          duration: 0.2,
          afterUpdate: function () {
            $('inner-container').style.left = (220 + xLeft($('menu-container')) - 14) + 'px';
            $('inner-container').style.width = (xClientWidth() - xLeft('inner-container')) + 'px';
          },
          afterFinish: function () {
            $('inner-container').style.left = (220 + xLeft($('menu-container')) - 14) + 'px';
            $('inner-container').style.width = (xClientWidth() - xLeft('inner-container')) + 'px';
          }
         });
      }
    });
  }
}

function set_cookie( name, value, expires, path, domain, secure )
{
  // set time, it's in milliseconds
  var today = new Date();
  today.setTime( today.getTime() );

  /*
  if the expires variable is set, make the correct
  expires time, the current script below will set
  it for x number of days, to make it for hours,
  delete * 24, for minutes, delete * 60 * 24
  */
  if ( expires )
  {
    expires = expires * 1000 * 60 * 60 * 24;
  }

  var expires_date = new Date( today.getTime() + (expires) );

  document.cookie = name + "=" +escape( value ) +
  ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
  ( ( path ) ? ";path=" + path : "" ) +
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ( ( secure ) ? ";secure" : "" );
}

function get_cookie( check_name ) 
{
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function insertAtCursor(myField, myValue) {
  //IE support
  if (document.selection) {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
  }
  //MOZILLA/NETSCAPE support
  else if (myField.selectionStart || myField.selectionStart == '0') {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos)
    + myValue
    + myField.value.substring(endPos, myField.value.length);
  } else {
    myField.value += myValue;
  }
}

function updateAlternations(elements, class1, class2)
{
  var onoff = true;
  $$(elements).each(function(s,i){
    if (s.id) {
      onoff = !onoff;

      s.addClassName(onoff ? class1 : class2);
      s.removeClassName(onoff ? class2 : class1);

      $$('#'+s.id+' td').each(function(s2,i2) {
        s2.addClassName(onoff ? class1 : class2);
        s2.removeClassName(onoff ? class2 : class1);
      });
    }

  });
}

function showHelp(module, action, field)
{
  var env = window.location.href.match("/backend(_dev|_prod)?.php")[0];
  Modalbox.show( env + '/mbhelptextbackend/helpindex/help_module/'+module+'/help_action/'+action+'/help_field/'+field, {
      title: 'Help',
      width: 750,
      inactiveFade: false

  });
}

function toggleDeletes(what, container)
{
  $$('#'+container+' input').each(function(s,i) {
    if (s.getAttribute('type') == 'checkbox' && s.id.substr(0,7) == 'delete_') {
      s.value = what.value;
      s.checked = what.checked;

      multidelete[s.id.substr(7,10)] = what.checked;
    }
  });
}

function multiDelete(what, checked) 
{
  $('delete-all-list-body-'+$('delete_'+what).up('.admin-list-container').id.substr(11)).checked = false;

  multidelete[what] = !checked;
}

// shouldn't we just always include php.js?
function isset() 
{
  var a=arguments; var l=a.length; var i=0;
    
  if (l==0) { 
    throw new Error('Empty isset'); 
  }
    
  while (i!=l) {
    if (typeof(a[i])=='undefined' || a[i]===null) { 
      return false; 
    } else { 
      i++; 
    }
  }
  return true;
}

function doDelete(what, bodyid) 
{
  var delstr = [];

  if (bodyid != 'undefined') {
    sbodyid = bodyid;
  }

  for (elem in multidelete) {
    if (!isNaN(elem)) {
      if (multidelete[elem] == true) {
        delstr.push(elem);
      }
    }
  }
  delstr = delstr.join('_');

 
  if (confirm('Weet u zeker dat u deze items wilt verwijderen?')) {
  	// we need to try this because delete_url != 'undefined' fails because... delete_url is undefined :s
  	try {
  	 	if (isset($(bodyid).delete_url)) {
  		   // if a delete url is set we're deleting from a "normal" list view 
  		   window.location.href= $(bodyid).delete_url + delstr;
  	   }
  	 } catch (e) {}
  	 
  	 try {
  	   if (isset(ajax_delete_url)) {
  		   // if an ajax delete url is set we're deleting from a panel list view
  		   new Ajax.Updater(ajax_list_container, ajax_delete_url+delstr, { evalScripts: true} );
  	   }
  	 } catch(e) {}
  }

  // temporary disabled modalbox because of jq/pt conflicts
  //if (what == true) {
    //window.location.href= delete_url + delstr;
    //return false;
  //}

  //Modalbox.show('<div id=\'confirmation-box\'><p>Weet u zeker dat u deze items wilt verwijderen?<\/p><button type=\'button\' onclick=\'doDelete(true)\'>Ja<\/button> <button type=\'button\' onclick=\'Modalbox.hide()\'>Nee<\/button><\/div>',{title: 'Bevestigen', width: 280});
}

function doAjaxDelete(url, what) 
{
  var delstr = '';

  for (elem in multidelete) {
    if (!isNaN(elem)) {
      if (multidelete[elem] == true) {
        delstr = delstr + '_' + elem;
      }
    }
  }
  delstr = delstr.substr(1, delstr.length -1);

  if (what == true) {

    new Ajax.Updater('loader-container-alternates', url, {
      parameters: { del: delstr },
      onSuccess: function(t) {
        Modalbox.hide();
      }
    });

    return false;
  }

  Modalbox.show('<div id=\'confirmation-box\'><p>Weet u zeker dat u deze items wilt verwijderen?<\/p><button type=\'button\' onclick=\"doAjaxDelete(\''+url+'\', true)\">Ja<\/button> <button type=\'button\' onclick=\'Modalbox.hide()\'>Nee<\/button><\/div>',{title: 'Bevestigen', width: 280});
}

function rescaleLists(list_id)
{
  awidth = (cnt_customs[list_id] * 20);
  cwidth = (cnt_cultures[list_id] * 20);
  dwidth = (cnt_domains[list_id] * 20);
  pwidth = awidth + cwidth + dwidth;

  if (cnt_customs[list_id] > 0) {
    pwidth++;
  }
  if (cnt_cultures[list_id] > 0) {
    pwidth++;
  }
  if (cnt_domains[list_id] > 0) {
    pwidth++;
  }
  if (has_delete[list_id] > 0) {
    pwidth += 32;
  }

  $$('#'+list_id+' .admin-list-properties').each(function(s) {
    s.style.width = pwidth + 'px';
  });

  $$('#'+list_id+' .admin-list-domains').each(function(s) {
    s.style.width = dwidth+'px';
  });

  $$('#'+list_id+' .admin-list-cultures').each(function(s) {
    s.style.width = cwidth+'px';
  });

  // determine max width of list
  maxwidth = xWidth(list_id);

  // determine width of properties block
  propertieswidth = xWidth($$('#'+list_id+' .admin-list-properties').first());

  // determine max content width
  contentwidth = maxwidth - propertieswidth;

  gcwidth[list_id] = contentwidth;
  gowidth[list_id] = propertieswidth;

  // resize the list
  $$('#'+list_id+' > ul').each(function(s) {
    s.style.width = maxwidth+'px';
  });

  // resize the content block
  $$('#'+list_id+' .admin-list-content').each(function(s) {
    s.style.width = contentwidth+'px';
  });
}

function showVersion(versie) 
{
  new Ajax.Updater(version_element, version_url_show+versie);
};

function showVersions()
{
  new Ajax.Updater(version_element, version_url_index);
}

function restoreVersion(versie)
{
  if (confirm('Weet je zeker dat je deze versie wilt terugzetten?')) {
    new Ajax.Request(version_url_restore, {
      parameters: { version: versie },
      onSuccess: function(t) {

        var a = window.location.hash;

        var href = window.location.href;

        if (a.length > 0) {
          href = window.location.href.substr(0, window.location.href.length - a.length);
        }

        window.location.href = href;
      }
    }
    );
  }
}

function tabSelector(what)
{
  $$('.tab-history').each(function(s,i) {
    if (s.id != what) {
      var flag = s.id.substr(s.id.length-5, 5);
      s.style.display = 'none';
      $('history-switch-'+flag+'-tab').removeClassName('active');
    }
  });

  var flag = what.substr(what.length-5, 5);
  $(what).style.display = 'block';
  $('history-switch-'+flag+'-tab').addClassName('active');
}

function optionalCheckbox(name, element)
{
  v = $(name).value;

  if (v == 'off') {
    v = 'on';
    i = 'on';
  }
  else if (v == 'on') {
    v = '';
    i = 'optional';
  }
  else if (v == '') {
    v = 'off';
    i = 'off';
  }

  element.src = '/backend/img/checkbox/checkbox-'+i+'.gif';

  $(name).value = v;
}

function convertWord(type, content) {
  switch (type) {
    // Gets executed before the built in logic performes it's cleanups
    case "before":
      //content = content.toLowerCase(); // Some dummy logic
      alert('you suck');
      break;

    // Gets executed after the built in logic performes it's cleanups
    case "after":
      //content = content.toLowerCase(); // Some dummy logic
      alert('you suck again');
      break;
  }

  return content;
}

function ShowHelpSymbol() {
   $('inner-container').className = "cursor";
}

Event.observe(window, 'load', function() 
  {
  	document_loaded = true;
  	
    if (!has_load) {
      showTime();
      overlibHelptekst();
      if ($('inner-container')) {
        var str = $('inner-container').getStyle('height');
        var inner_h = parseInt(str.substr(0, str.length - 2));
            str = $('menu-container').getStyle('height');
        var menu_h = parseInt(str.substr(0, str.length - 2));
  
        max_h = inner_h > menu_h ? inner_h : menu_h;
        
        if (max_h < xClientHeight()) {
          max_h = xClientHeight() - xHeight('header');
        }
        
        //alert(max_h + 30);
        
        xHeight('menu-container', (max_h + 30));
      
        toggleMenu('init');
  
        xTop('inner-container', 70);
      }

      has_load = true;
    }
  }
);

function checkCultureBeforeSubmit(what)
{
  if (typeof(currentculture) != 'undefined' && currentculture != defaultlang) {
    languageSelector(defaultlang);
    setTimeout(function() { 
      checkCultureBeforeSubmit(what)
    }, 50);
  }
  else {
    setTimeout(function() { 
      what.submit();
    }, 300);
    return true;
  }
  
  return false;
}

var env = window.location.href.match(/(\/[a-z_]+\.php)/);
env = env!=null && (typeof env=='object') && env.length ? env[0] : '';

new PeriodicalExecuter(function() { new Ajax.Request( env + '/security/keepalive', { method: 'get' }); }, 300);

