/**
 * This javascript is currently coded to work properly with the Mozilla (Gecko) engine
 * 
 * It has been tested in FireFox and K-Meleon at this time
 * 
 * It is only partially coded to address IE idiosyncracies, and is known not to work properly in IE
 */

///////////////////////////////////////////////////
//   Menu Events Script
///////////////////////////////////////////////////

function menuClicked( path )
{
  //window.location.href = path;
  document.HiddenVars.action = path;
  document.HiddenVars.submit();
}

///////////////////////////////////////////////////
//   Content Editing Script
///////////////////////////////////////////////////

var editIsInProgress = false;
var contentHasChanged = null;

function onPageUnload()
{
  /*
   This function is not yet working properly
   Seems there is no way to stop the page from unloading and losing the changes...
   Only able to detect that the page is unloading and return the user to the same page, though edits have been lost...???
   */
  if ( editIsInProgress )
  {
    var textEditor = document.Editor.TextEditor;
    if ( textEditor.defaultValue != textEditor.value )
    {
      var result = confirm( "You are in the process of editing content, are you sure you want to exit?" );
      if ( ! result )
      {
        alert( textEditor.value );
        var headerEditor = document.Editor.HeaderEditor;
        var changedText = textEditor.value;
        var changedHeader = headerEditor.value;
        window.location.reload();
        textEditor = document.Editor.TextEditor;
        headerEditor = document.Editor.HeaderEditor;
        textEditor.value = changedText;
        headerEditor.value = changedHeader;
        alert( 'after reload' );
        showForm();
      } // ! result
    } // if textEditor has changed
  }
}

function onPageLoad() // profiler
{
  // load the editor javascript
  /*
  var editorJavascript = document.createElement('script');
  editorJavascript.setAttribute( "type", "text/javascript;e4x=1" );
  editorJavascript.setAttribute( "src", "/_/scripts/EditorWindow.js" );
  document.getElementsByTagName("head")[0].appendChild( editorJavascript );
  //*/

  /*
  var topMenuLogin = document.getElementById( 'TopMenuLogin' );
  if ( topMenuLogin )
  {
    if ( topMenuLogin.innerHTML == "Logout" )
    {
      // hook the editor aware events
      //hookEditorEvents( 'Content' );
    }
  }
  //*/
}

// text editor special effects (visual clues)

function hasTextChanged()
{
 return null;
}

function showBorder( entity )
{
  var topMenuLogin = document.getElementById( 'TopMenuLogin' );
  if ( topMenuLogin.innerHTML == "Logout" )
    //if ( entity.syle ) // attempt to prevent IE errors
      //entity.style.border='1px dashed #00f';
    entity.style.outline='1px dashed #00f';
}

function hideBorder( entity )
{
  //if ( entity.syle ) // attempt to prevent IE errors
    //entity.style.border='0px none #000';
  entity.style.outline='0px none #000';
}

// adding new content

function addNewContent( contentType )
{
  var submission = { "ContentType": contentType };
  var newContentId = postContent( '/_/webapi/Content.php', {'Method':'AddNewContent','Submission':Object.toJSON(submission)} );
  if ( newContentId != "" )
  {
    location.href = '/?Id=' + newContentId;
  }
}

// managing the text editor window

function showEditor() // profiler
{
  if ( ! document.EditorForm )
  {
    loadEditorForm();
  }
  editIsInProgress = true;
  editorWindow = document.getElementById('EditorWindow');
  if(editorWindow)
  {
    editorWindow.style.display='block';
  }
  // hook the CKEditor
  // note that by hooking it here, we're limiting ourselves to one fixed textarea...  Need to address this...
  // See if we can read the editor's XML descriptor (maybe JSON by the time it reaches here)
  // If we can, then we can use a property such as WYSIWYG=1 to hook specific fields for editing
  try
  {
    CKEDITOR.replace('Contents');
    //var contents = document.getElementById('Contents');
    var editor = CKEDITOR.instances['Contents'];
    //editor.attach(contents);
//*
    CKEDITOR.event.implementOn( editor );
    editor.on('blur', 
//*
    function() 
      {
        CKEDITOR.instances['Contents'].updateElement();
        //var contents = document.getElementById('Contents');
        //editor.updateElement();
      }
    );
//*/
  }
  catch (e)
  {
  }
}

function hideEditor() // profiler
{
  editorWindow = document.getElementById('EditorWindow');
  if(editorWindow)
  {
    editorWindow.style.display='none';
  }
  editIsInProgress = false;
}

function loadEditorForm() // profiler
{
  //document.getElementById('EditorWindow').innerHTML = getContent( '/EditorWindow.html.inc' );
  //document.getElementById('EditorWindow').innerHTML = postContent( '/_/webapi/Content.php', 'Method=GetEditor&Id='+document.HiddenVars.PageId.value );
  new Ajax.Request('/_/webapi/Content.php', { parameters: {'Method':'GetEditor','Id':document.HiddenVars.PageId.value},
    onSuccess: function(transport) {document.getElementById('EditorWindow').innerHTML = transport.responseText;},
    asynchronous: false } );
}

///////////////////////////////////////////////////
//   Login Script
///////////////////////////////////////////////////

function login() // profiler
{
  var topMenuLogin = document.getElementById( 'TopMenuLogin' );
  if ( topMenuLogin.innerHTML == "Logout" )
  {
    logout();
    return;
  }

  showLogin();

  var loginForm = document.LoginForm;

  loginForm.Username.value = "";
  loginForm.Password.value = "";
  loginForm.Username.focus();
}

function validateCredentials() // profiler
{
  var username = myBase64Encode( document.LoginForm.Username.value );
  var password = myBase64Encode( document.LoginForm.Password.value );

  var authentication = postContent( '/_/webapi/User.php', {'Method':'Login','Username':username, 'Password':password} );

  hideLogin();

  // if the login was successful (test the returned authentication)
  if ( authentication != '' )
  {
    location.reload();
  }
  else
  {
    alert( "Login failed" );
  }
}

function logout() // profiler
{
  var authentication = document.HiddenVars.Authentication.value;
  postContent( '/_/webapi/User.php', { 'Method':'Logout' } );

  location.reload();
}

/// form management

function showLogin() // profiler
{
  if ( ! document.LoginForm )
  {
    loadLoginForm();
  }
  editIsInProgress = true;
  oDiv = document.getElementById('LoginWindow');
  oDiv.style.display='block';
}

function hideLogin() // profiler
{
  oDiv = document.getElementById('LoginWindow');
  oDiv.style.display='none';
  editIsInProgress = false;

  document.LoginForm.Username.value = "";
  document.LoginForm.Password.value = "";
}

function loadLoginForm() // profiler
{
  document.getElementById('LoginWindow').innerHTML = getContent( '/LoginWindow.html.inc' );
}

//... this will be superceded by Prototype.js
//... probably modify these calls to use the prototype syntax

///////////////////////////////////////////////////
//   AJAX Script
///////////////////////////////////////////////////

/** 
 * 
 * 
 * @param url
 * @param params (object with properties to be used as parameters)
 */
function postContent( url, params ) // ???
{
  if(!params)
  {
    var params = {};
  }
  params.evalScripts = true;
  /////////////
  var result = '';
  new Ajax.Request(url, { parameters: params,
                          onSuccess: function(transport){result = transport.responseText},
                          asynchronous: false } 
                   );
  return result;
  //////////////
}

function getContent( url ) // profiler
{ 
  var params = {};
  params.evalScripts = true;
  /////////////
  var result = '';
  new Ajax.Request(url, { parameters: params,
                          onSuccess: function(transport){result = transport.responseText},
                          asynchronous: false } 
                   );
  return result;
}

/*
function getXML( url ) 
{ 
  xmlHttp=GetXmlHttpObject();
  if (xmlHttp==null)
  {
    alert ("Your browser does not support dynamic content\r\nThe editing features of this site will not work");
    return;
  } 
  xmlHttp.open("GET", url, false);
  xmlHttp.send(null);
  if (xmlHttp.status==200)
  {
    return xmlHttp.responseXML;
    //xmlContent = xmlContent.trim();
    //return xmlContent;
  }
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}
*/

///////////////////////////////////////////////////
//   Utility Scripts
///////////////////////////////////////////////////

// enhance the String object with trim capability
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}


//hook and unhook object events to function calls
//...  http://www.floresense.com/resc_center/?art=81
function hookEvent(obj,evtName,fnCall)
{
  evtName=evtName.toLowerCase();
  doCapture=false;
  if (obj.addEventListener){
      obj.addEventListener(evtName.replace('on',''),
    function(){eval(fnCall);},false);
  }
  else if(obj.attachEvent){
   obj.attachEvent(evtName,function(){eval(fnCall);});
   //also do detachEvent later
  }
  else{
     eval(obj+"."+evtName +"="+ fnCall);
  }
}

function unhookEvent(obj,evtName,fnCall)
{
  evtName=evtName.toLowerCase();
  doCapture=false;
  if (obj.addEventListener){
      obj.removeEventListener(evtName.replace('on',''),
    function(){eval(fnCall);},doCapture);
  }
  else if(obj.attachEvent){
   obj.detachEvent(evtName,function(){eval(fnCall);});
  }
  else{
     eval(obj+"."+evtName +"='';");
  }
}

