  var sLastDialogID =null;

  function PleaseWait() {
    $.blockUI({message: $('#pleaseWaitMessage').html(), css: {width: '220px', height: '30px', border: '0px'}});
  }

  function PostAjaxForm(formid, functionName) {
    PleaseWait();
    PostAjaxFormTransparent(formid, functionName);
  }

  function PostAjaxFormTransparent(formid, callbackFunction) {
    var options = {
        success: callbackFunction,
        error: AjaxError,
        url: '/cms.php',
        dataType:  "json",
        type: 'POST'
    };

    $("#" + formid).ajaxSubmit(options);
    return false;
  }

  function GetAjaxCall(url, functionName) {
    PleaseWait();
    GetAjaxCallTransparent(url, functionName);
  }

  function CMSAddGlobalParametersToURL(sURL) {
    // do not add token, if token exists
    if (sURL.indexOf(_cmsauthenticitytoken_parameter) < 0) {
      var sSep = '?';
      if (sURL.indexOf(sSep) > -1) sSep = '&';
      sURL = sURL + sSep +_cmsauthenticitytoken_parameter;
    }
    return sURL;
  }

  function GetAjaxCallTransparent(url, functionName) {
    url = CMSAddGlobalParametersToURL(url);

    $.ajax({
       url: url,
       processData: false,
       dataType:  'json',
       success: functionName,
       error: AjaxError,
       type: 'GET'
     });
  }

  function AjaxError(XMLHttpRequest, textStatus, errorThrown) {
    if(textStatus == 'parsererror') {
      jQuery.unblockUI();
      toasterMessage('Error! Wasn`t able to parse ajax response.','ERROR');
      if(XMLHttpRequest.responseText != '') {
        var sError = XMLHttpRequest.responseText;

        if(sError.length > 1024) {
          sError = sError.substr(0,1024);
        }

        if(sError.indexOf('<title>') !== -1) sError = '';

        var sMessage = CHAMELEON.CORE.i18n.Translate('Fehler! Ajax Antwort:\n\n%s1',sError);

        // check if response is the login page, so we need to redirect the user
        if(XMLHttpRequest.responseText.indexOf('<input type="hidden" name="pagedef" value="login" />') !== -1) {
          var sLogoutMessage = CHAMELEON.CORE.i18n.Translate('Es ist ein Rechte-Problem aufgetreten und Sie wurden abgemeldet.\nMöchten Sie zur Login Seite weitergeleitet werden?');
          if(confirm(sLogoutMessage)) {
            top.document.location.href='/cms.php';
          }
        } else {
          alert(sMessage);
        }
      }
      console.log("%s: %o", 'error', XMLHttpRequest);
    }
  }

	/*
	* we provide a nice Message Box instead of bothering operating system window
	* allowed style types: MESSAGE (default), WARNING, ERROR, FATAL
	*/
	function toasterMessage(message,type) {
	  if(type == 'ERROR' || type == 'FATAL') {
	    $("#toaster").removeClass('notice');
	    $("#toaster").removeClass('success');
	    $("#toaster").addClass('error');
	  } else if(type == 'WARNING') {
	    $("#toaster").removeClass('error');
	    $("#toaster").removeClass('success');
	    $("#toaster").addClass('notice');
    } else if(type == 'MESSAGE') {
	    $("#toaster").removeClass('notice');
	    $("#toaster").removeClass('error');
	    $("#toaster").addClass('success');
	  }
	  $("#toaster").html(message);
	  $("#toaster").show();

		// animate message
		var st = $(document).scrollTop();
		var documentHalfWidth = Math.round($(document).width()/2);
		var toasterHalfWidth = Math.round($('#toaster').width()/2);
		var taosterCenterPos = documentHalfWidth - toasterHalfWidth;

		$('#toaster').attr("style","left: "+taosterCenterPos+"px");
		$('#toaster').animate({top:st-6});

		window.setTimeout(function() {
  	  $('#toaster').animate({top:-100});
	  }, 8000);
	}

  function CmsAjaxCallback_OpenLink(sResponse, statusText) {
    CloseModalIFrameDialog();
    window.open(sResponse);
  }
  function DisplayAjaxMessage(data,statusText) {
    CloseModalIFrameDialog();
    toasterMessage(data,'MESSAGE');
  }

  function DisplayAjaxTextarea(data,statusText) {
    CloseModalIFrameDialog();
    var content = "<form accept-charset=\"UTF-8\"><textarea wrap=\"off\" style=\"width:100%;height:550px;\">"+data+"</textarea></form>";
    CreateModalIFrameDialogFromContent(content,750,650);
  }

  function CMSAddDivToBody(id, divcontent) {
    var newdiv = document.createElement('div');
    newdiv.setAttribute('id',id);
    newdiv.innerHTML = divcontent;
    var attmp = document.getElementById('__idbecauseppldonotknowhowtousejs');
    document.body.insertBefore(newdiv,attmp);
  }

  /*
  * save variable in CMS registry
  */
  function saveCMSRegistryEntry(id,value) {
    registryID = '_CMSRegistry_' + id;
    if(document.getElementById(registryID)) {
      document.getElementById(registryID).innerHTML = value;
    } else {
      var newdiv = document.createElement('div');

      newdiv.setAttribute('id',registryID);
      newdiv.style.display = 'none';
      newdiv.innerHTML = value;

      document.body.appendChild(newdiv);
    }
  }

  /*
  * get variable from CMS registry
  */
  function getCMSRegistryEntry(id) {
    registryID = '_CMSRegistry_' + id;
    if(document.getElementById(registryID)) {
      return document.getElementById(registryID).innerHTML;
    } else {
      return false; // alert('CMS registry error! Object ID: ' + registryID + ' is missing.');
    }
  }

  /*
  * delete variable from CMS registry
  */
  function deleteCMSRegistryEntry(id) {
    registryID = '_CMSRegistry_' + id;
    if(document.getElementById(registryID)) {
      document.body.removeChild(registryID);
    }
  }

  /*
  * create dialog
  */
	function LoadJQMDialog(width,height,dialogContent,hasCloseButton,title,isDraggable,isResizable,isModal) {
	  if(typeof(isModal) == "undefined"){
	    if(hasCloseButton){
	     isModal = true;
	    } else {
	      isModal = false;
	    }
	  }
    if(!title) title = 'Chameleon CMS';
    if(typeof(isDraggable)=='undefined') isDraggable = true;
    if(typeof(isResizable)=='undefined') isResizable = true;

    if($('#modal_dialog').length == 0){
      $('body').append('<div id="modal_dialog" style="display: none;"></div>');
    }

    $('#modal_dialog').dialog({
      width: parseInt(width) + 15,
      height: parseInt(height),
      title: title,
      modal: isModal,
      position: "center",
      resizable: isResizable,
      draggable: isDraggable,
      close: function(event, ui) {CloseModalIFrameDialog();},
      open: function(event, ui) {
        if(!hasCloseButton) {
          $(event.currentTarget).find('.ui-dialog-titlebar-close').css('display','none');
        }
      }
    }).html(dialogContent);

    if(!hasCloseButton) {
      $('#cmscontainer').click(function() {
        $("#modal_dialog").dialog("close");
      });
    }

    return true;
	}

 	/*
	* creates a ModalDialog without close button from iFrame
	*/
  function CreateModalIFrameDialog(url,width,height,title,isDraggable,isResizable) {
    url = CMSAddGlobalParametersToURL(url);
    var dialogContent = '<iframe id="dialog_list_iframe" src="'+url+'" width="100%" height="100%" border="0" frameborder="0"></iframe>';
    LoadJQMDialog(width,height,dialogContent,false,title,isDraggable,isResizable);
  }

 	/*
	* creates a ModalDialog with close button from iFrame
	*/
  function CreateModalIFrameDialogCloseButton(url,width,height,title,isDraggable,isResizable) {
    url = CMSAddGlobalParametersToURL(url);
    var dialogContent = '<iframe id="dialog_list_iframe" src="'+url+'" width="100%" height="100%" border="0" frameborder="0"></iframe>';
    LoadJQMDialog(width,height,dialogContent,true,title,isDraggable,isResizable);
  }

 	/*
	* creates a ModalDialog with close button from contentstring
	*/
  function CreateModalIFrameDialogFromContent(content,width,height,title,isDraggable,isResizable) {
    LoadJQMDialog(width,height,content,true,title,isDraggable,isResizable);
  }

 	/*
	* creates a ModalDialog with close button from DIV-Container (ID)
	*/
  function CreateModalDialogFromContainer(contentID,width,height,title,isDraggable,isResizable) {
    var content = $('#'+contentID).html();
    $('#'+contentID).html('');
    top.sLastDialogID = contentID;
    var dialogContent = '<div style="width:100%;height:100%;" id="modal_dialog_content">'+content+'</div>';
    LoadJQMDialog(width,height,dialogContent,true,title,isDraggable,isResizable);
  }

 	/*
	* creates a ModalDialog to show a full image from Image-URL
	*/
  function CreateMediaZoomDialogFromImageURL(imageURL,width,height) {
    dialogContent = '<a href="#" onclick="CloseModalIFrameDialog();"><img src="'+imageURL+'" width="'+width+'" height="'+height+'" border="0" style="cursor:hand;cursor:pointer;" /></a>';
	width = (parseInt(width)+30);
	height = (parseInt(height)+30);
    LoadJQMDialog(width,height,dialogContent,true);
  }

 	/*
	* creates a ModalDialog without close button from contentstring
	*/
  function CreateModalIFrameDialogFromContentWithoutClose(content,width,height,title,isDraggable,isResizable) {
    LoadJQMDialog(width,height,content,false,title,isDraggable,isResizable);
  }

  /*
  * closes Modal Dialog
  */
  function CloseModalIFrameDialog() {
    $('#modal_dialog').html('&nbsp;');
    if($('#modal_dialog').dialog('isOpen')) {
      $('#modal_dialog').dialog('destroy');
    }
    jQuery.unblockUI();
  }

  function getRadioValue(rObj) {
    var returnVal = false;
    for (var i=0; i<rObj.length; i++) {
      if (rObj[i].checked) returnVal = rObj[i].value;
    }
    return returnVal;
  }

  function InitVideoPlayer(playerID,FLVPlayerURL,maxThumbWidth,playerHeight) {
    $('#flashContainer' + playerID).flash(
        { src: FLVPlayerURL,
          id: playerID,
          name: playerID,
          align: 'middle',
          wmode: 'window',
          quality: 'high',
          allowScriptAccess: 'always',
          allowfullscreen: 'true',
          width: maxThumbWidth,
          height: playerHeight },
        { version: 9 }
    );
  }

  function UpdateHeaderTransactionNameNew() {
    var HeaderWorkflowTitle = top.document.getElementById("HeaderWorkflowTitle");
    $('#dialog_list_iframe').load(function(){
      var modalframe = $("#dialog_list_iframe").contents();
      var name = $(modalframe).find('#name').val();
      var id = $(modalframe).find('input[name=id]').val();
      var tableid = $(modalframe).find('input[name=tableid]').val();
      sHeaderWorkflowTitleHTML = '<a href="#" id="HeaderWorkflowTitle" class="linkTransactionCurrent" onclick="CreateModalIFrameDialogCloseButton(\'/cms.php?pagedef=tableeditorPopup&amp;tableid='+tableid+'&amp;id='+id+'\',1000,750,\''+name+'\');">'+name+'</a>';
      $(HeaderWorkflowTitle).replaceWith(sHeaderWorkflowTitleHTML);
    });
  }

  function addslashes(str) {
    // Escapes single quote, double quotes and backslash characters in a string with backslashes
    //
    // version: 1004.1212
    // discuss at: http://phpjs.org/functions/addslashes    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // +   improved by: Nate
    // +   improved by: Onno Marsman    // +   input by: Denny Wardhana
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Oskar Larsson Högfeldt (http://oskar-lh.name/)
    // *     example 1: addslashes("kevin's birthday");
    // *     returns 1: 'kevin\'s birthday'
    return (str+'').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
  }

  function UpdateHeaderTransactionsCallback(data, e) {
    if(typeof(data.bHasActive)=='undefined') { } else {
      var HeaderWorkflowTitle = top.document.getElementById("HeaderWorkflowTitle");
      if(data.bHasActive) {
        var sNameWithSlashes = addslashes(data.sName);
        sHeaderWorkflowTitleHTML = '<a href="#" id="HeaderWorkflowTitle" class="linkTransactionCurrent" onclick="CreateModalIFrameDialogCloseButton(\'/cms.php?pagedef=tableeditorPopup&amp;tableid='+data.sTableId+'&amp;id='+data.sTransactionId+'\',1000,750,\''+sNameWithSlashes+'\');">'+data.sName+'</a>';
      } else {
        sHeaderWorkflowTitleHTML = '<div id="HeaderWorkflowTitle">'+data.sName+'</div>';
      }
      $(HeaderWorkflowTitle).replaceWith(sHeaderWorkflowTitleHTML);
    }
  }

  /**
   * switches the edit portal which will used as default portal while editing
   */
  function SwitchEditPortal() {
    PostAjaxFormTransparent('portalChooserForm',SwitchEditPortalCallback);
  }

  function SwitchEditPortalCallback() {
    $('#portalChooser').slideToggle('fast');
    $('#portalContentBoxNameSpan').html(document.getElementById('activePortalID').options[document.getElementById('activePortalID').options.selectedIndex].text);
  }
