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();

env = window.location.href.match("/backend(_dev|_prod)?.php");
if (env) {
  env = env[0];
}
else {
  env = '/backend.php';
}

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 (what.hasClassName('group-closed')) {
    what.removeClassName('group-closed');
    what.addClassName('group-open');
    $(element).style.display = 'block';
  }
  else {
    what.removeClassName('group-open');
    what.addClassName('group-closed');
    $(element).style.display = 'none';
  }
}

function toggleListGroup(what, element)
{
  if (what.hasClassName('group-closed-list')) {
    what.removeClassName('group-closed-list');
    what.addClassName('group-open-list');
    $(element).style.display = 'block';
  }
  else {
    what.removeClassName('group-open-list');
    what.addClassName('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 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 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 restoreDeleted(url) {
  //gets all the selected items
  var ids = [];
  $('admin-list-99').select('input:checked').each(function(item) {
    ids.push(Math.round(item.id.replace('restore-id-','')));
  });

  if (ids.length == 0) {
    alert("Nothing to be restored!");
    return false;
  }

  if ( confirm("Weet je zeker dat je de geselecteerde items wilt herstellen?")) {
    new Ajax.Request(url, {
      parameters: {
        ids : ids.join(','),
        what: 'deleted'
      },
      onSuccess: function(t) {
         popup.Close();
         window.location.reload();
      }
    });
  }
}

/*
function restoreVersion(url) {
  //gets all the selected items
  var ids = [];
  $('admin-list-99').select('input:checked').each(function(item) {
    ids.push(Math.round(item.id.replace('restore-id-','')));
  });

  if (ids.length == 0) {
    alert("Nothing to be restored!");
    return false;
  }

  if ( confirm("Weet je zeker dat je de geselecteerde items wilt herstellen?")) {
    new Ajax.Request(url, {
      parameters: { ids: ids.join(',') },
      onSuccess: function(t) {
         popup.Close();
         window.location.reload();
      }
    });
  }
}
*/

function executeRestoreDraft() {
  var form = new msFormActions();
  form.doDraftSPSubmit()
}

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, maxwidth)
{
  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;
  }

  try {
    $$('#'+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';
    });

  }
  catch(e) {}

  // determine max width of list
  if (!maxwidth) {
    maxwidth = xWidth(list_id);
  }

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

  // determine width of properties block
  propertieswidth = xWidth($$('#'+list_id+' > ul li .admin-list-properties').first());
  o = $$('#'+list_id+' > ul li .admin-list-properties').first();
  if (o) {
    propertieswidth = o.style.width.substr(0, o.style.width.length - 2);
  }
  else {
    propertieswidth = 0;
  }

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

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

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

function showVersion(versie)
{

  new Ajax.Request(version_url_show+versie,
  {
    onSuccess: function(t) {
	    var response = t.responseText.evalJSON();

	    alert(t.responseText);

	    popup.Title.update(response.title);
	    popup.ClonedNode.update(response.content);


      //popup.Set(t.responseText);
    }
  });
};

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';
    alt = translate('Waarde expliciet ingeschakeld');
  }
  else if (v == 'on') {
    v = '';
    i = 'optional';
    alt = translate('Haal waarde uit onderliggende opties (overerving)');
  }
  else if (v == '') {
    v = 'off';
    i = 'close';
    alt = translate('Waarde expliciet uitgeschakeld');
  }

  element.src = '/shared/img/checkbox/checkbox-'+i+'.gif';
  element.alt = alt;
  element.title = alt;
  $(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";
}

function updateImagePreview(what, multiple) {
  multiple = (typeof(multiple) == 'undefined') ? 'false' : 'true';

  if (multiple == 'true') {
    new Ajax.Request(window.location.href + '?reloadImage=' + what + '&multiple=' + multiple, {
      onSuccess: function(e) {
        Element.insert(what + '-container', e.responseText);
      },
      evalScripts: true
      
    });
  }
  else {
    new Ajax.Updater(what + '-container', window.location.href + '?reloadImage=' + what + '&multiple=' + multiple);
  }
}

Event.observe(window, 'load', function()
{
	document_loaded = true;
}
);

var env = window.location.href.match("/(?:backend|frontend)?(_dev|_prod)?.php");
env = env!=null && (typeof env=='object') && env.length ? env[0] : '';

if (!window.location.href.match("login")) {
  // keep alive to stay logged in
  // should not be loaded on login screen, because this will give an OK message
  new PeriodicalExecuter(function() { new Ajax.Request( env + '/login/keepalive', { method: 'get' }); }, 300);
}


if(typeof console != 'object') {
	// we miss the console object
	// probably IE
	console = Class.create();
	console.prototype =
	{
	  initialize: function ()
	  {

	  },

	  log: function(what)
	  {
	  }
	}
}

document.observe("msRibbon:loaded", function(event) {
  if( $('tinymce-container') ) {
    // We have a tinyMCE container
    // try to move TinyMCE into that container

    myTinyMCE.moveToRibbon();
  }
});