// These are also defined in rte.js, but the two files shouldn't normally be
// used together.
var hr = '<hr size="1"  style="height:1px;border-width:0;color:gray;background-color:gray" />';

function createXmlHttpRequest()
{
  var xmlHttp = null;
  // Create the HttpRequest - abort if not possible
  try {
    xmlHttp = new XMLHttpRequest();  // Firefox, Opera 8.0+, Safari, IE7
  }
  catch(e) {
    try {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); // Old IE
    }
    catch(e) {
      alert ("Your browser is not suitable for webpage editing using mysitenow.co.uk. We recommend that you use an up-to-date version of Firefox, downloadable from www.mozilla.com/firefox/");
      return null;
    }
  }
  return xmlHttp;
}

var alertDlg = null;

function ieWarn() {
  showAlert('Warning', '<p>In order to log in to this site you must use <a href="http://www.mozilla.com/firefox/">Firefox</a></p><p>You cannot log in to this this site using Internet Explorer, Safari, Google Chrome, Opera etc. as these browsers do not provide the necessary editing features in the required form.</p>' + hr);
}

// opWarn is the Opera version of ieWarn, needed because Opera doesn't support
// MooTools.
function opWarn() {
  alert("In order to log in to this website you must use the Firefox browser, available from www.mozilla.com/firefox/.\n\nYou cannot log in to this this site using Internet Explorer, Safari, Google Chrome, Opera etc. as these browsers do not provide the necessary editing features in the required form.");
}

function showAlert(caption, msg) {
  // Remove existing dialog if any
  if (alertDlg) {
    alertDlg.destroy();
  }
  // Creat new one
  alertDlg = new StickyWinFx( {
    fadeDuration: 0, // No fade
    draggable: false,
    content: StickyWin.ui(caption, msg,
    {
      fadeDuration: 1000, // (fade in and out)
      cornerHandle: false,
      draggable: false,
      width: '400px',
      buttons: [
        {
          text: 'OK'
        }
      ]
    } )
  } );
}

// -----

// Add a 'trim' method to JS strings
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }

var logonDlg = null;
var okDlg = null;
var newPwdDlg = null;

function logon_x(userName, pwd) {
  var xmlHttp = createXmlHttpRequest();
  xmlHttp.open("POST", 'logon_v2.php', true);
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status == 200) {
        var resultText = xmlHttp.responseText;
        if (resultText.substr(0, 2) == 'OK') {
          var userName = resultText.substr(5);
          if (okDlg != null) {
            okDlg.destroy();
          }
          var msg = (resultText.substr(2, 1) == '*'
            ? 'Your annual subscription is now payable - please check your MySiteNow account (accessed from your Site Management page) for more information.'
            : 'You have no new messages.'
            );
          okDlg = new StickyWinFx({
            fadeDuration: 1000, // (fade in and out)
            draggable: false,
            content: StickyWin.ui('Logged in',
              '<form action="index.php?0" name="okForm" method="POST" target="_top"><p><strong>Welcome back, ' + userName + '</strong></p><p>' + msg + '</p><p>&nbsp;</p><p><input type="submit" name="okButton" value="Continue"></p></form>',
            {
              width: '400px',
              cornerHandle: false
            } )
          } );
        } else if (resultText.substr(0, 3) == 'ALT') {
          // Logged on using temporary password
          var userName = resultText.substr(6);
          if (newPwdDlg != null) {
            newPwdDlg.destroy();
          }
          newPwdDlg = new StickyWinFx({
            fadeDuration: 1000, // (fade in and out)
            draggable: false,
            content: StickyWin.ui('Logged in with temporary password',
              '<form action="index.php?0" name="newPwdForm" method="POST" target="_top"><p><strong>Welcome back, ' + userName + '</strong></p><p>You have just logged in using a temporary password. As you will not be able to use this again, please enter the password you wish to use in future.</p><p><input type="text" style="width:343px;" maxlength="20" name="new_pwd"></p><p>&nbsp;</p><p><input type="submit" name="btn_new_pwd" value="Continue"></p></form>',
            {
              width: '400px',
              cornerHandle: false
            } )
          } )
        } else {
          okDlg = new StickyWinFx({
            fadeDuration: 1000, // (fade in and out)
            draggable: false,
            content: StickyWin.ui('Warning!',
              '<p><br><strong>You were unable to log in...</strong></p><p>' +  resultText + '</p><p>&nbsp;</p>' + hr,
            {
              width: '400px',
              cornerHandle: false,
              buttons: [
                {
                  text: 'OK'
                }
              ]
            } )
          } )
          //showAlert('Error', 'Sorry - you entered an incorrect user name or password.');
        }
      }
    }
  }
  args = 'username=' + userName + '&pwd=' + pwd;
  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlHttp.send(encodeURI(args));
}

function logon_help_x(emailAddr)
{
  var xmlHttp = createXmlHttpRequest();
  xmlHttp.open("POST", 'lost_logon.php', true);
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status == 200) {
        var resultText = xmlHttp.responseText;
        if (resultText.substr(0, 2) == 'OK') {
          showAlert('Information', '<p><strong>New login details have been sent to your email address. Please check your emails and log on using the new password.</strong></p>' + hr);
        } else {
          showAlert('Error', '<p>We could not send your new login details. Please check your email address and try again</p>' + hr);
        }
      }
    }
  }
  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlHttp.send('email_address=' + emailAddr);
}

var logonhelpDlg = null;
function logon_help() {
  if (logonhelpDlg != null) {
    logonhelpDlg.destroy();
  }
  logonhelpDlg = new StickyWinFx({
    fadeDuration: 1000, // (fade in and out)
    draggable: false,
    content: StickyWin.ui('Help',
      '<form name="logonhelpForm" method="POST" action="" enctype="multipart/form-data"><p><strong>Forgotten your username or password?</strong></p><p>Just enter your email address below (the one that you used when setting up your website) and click \'OK\'. After checking the email address we will send you an email containing your user name and a new password.</p><p><strong>Email address:</strong></p><p><input type="text" name="email_address" maxlength="255" style="width:343px;"></p></form>' + hr,
      {
      width: '400px',
      cornerHandle: false,
      buttons: [
        {
          text: 'OK',
          onClick: function(){ var emailAddr = document.forms.logonhelpForm.email_address.value; logon_help_x(emailAddr); }
        },
        {
          text: 'Cancel'
        }
      ]
      }
    )
  });
}

function logon() {
  if (logonDlg == null) {
    logonDlg = new StickyWinFx({
      fadeDuration: 1000, // (fade in and out)
      draggable: false,
      content: StickyWin.ui('Logging in',
        '<form name="logonForm" method="POST" enctype="multipart/form-data"><table border="0" cellpadding="4" cellspacing="0"><tr><td width="50%"><strong>User name</strong></td><td><input type="text" name="username" class="dlg" maxlength="100" style="font-size: 11px; font-family: Verdana" /></td></tr><tr><td width="50%"><strong>Password</strong></td><td><input type="password" name="pwd" class="dlg" maxlength="20" style="font-size: 11px; font-family: Verdana" /></td></tr><tr><td colspan="2"><br><span class="red">Forgotten your email address or password? Click \'Help!\'</span></td></tr></table></form>' + hr,
        {
        width: '400px',
        cornerHandle: false,
        buttons: [
          { // We still need to add the wrapping attributes to the table
            text: 'Log in',
            onClick: function(){ var userName = document.logonForm.username.value; var pwd = document.logonForm.pwd.value; res = logon_x(userName, pwd); }
          },
          {
            text: 'Cancel'
          },
          {
            text: 'Help!',
            onClick: function(){ logon_help(); }
          }
        ]
        }
      )
    });
  }
  logonDlg.show();
}

function adjustComponentFrameHeight(component_id, extra) {
  //alert('adjustComponentFrameHeight');
  // FF and W3C compliant browsers only - revisit for IE
  if (document.getElementById(component_id).contentDocument) {
    var h = document.getElementById(component_id).contentDocument.body.scrollHeight;
    if (extra != undefined) {
      h = h + parseInt(extra);
    }
    //alert('scrollheight = ' + h);
    document.getElementById(component_id).style.height = h + 15 + 'px';
  }
}

function setComponentFrameHeight(component_id, height) {
  // FF and W3C compliant browsers only - revisit for IE
  if (document.getElementById(component_id).contentDocument) {
    document.getElementById(component_id).style.height = height + 'px';
  }
}

// This function is to be called on MouseUp events and checks that the selected
// HTML is editable.
function checkEditable(e)
{
  //alert('Checking editable');
  //return true;

  var userSelection;
  var container = document.getElementById('container');
  if (container) {
    var iframeWin = document.getElementById('container').contentWindow;
    userSelection = iframeWin.getSelection();
  } else {
    userSelection = window.getSelection();
  }

  //var iframeWin = document.getElementById('container').contentWindow;
  //var userSelection = iframeWin.getSelection();
  //var userSelection = window.getSelection();

  if (userSelection.isCollapsed) {
    //alert('Selection is collapsed');
  } else {
    // Check that start and end nodes are the same
    if (userSelection.anchorNode != userSelection.focusNode) {
      //showAlert('Error', 'This selection cannot be used as it would affect the page layout.');
      userSelection.collapseToStart();
    }
  }
  // Check that selection is replaceable
  var node = userSelection.anchorNode;
  var replaceable = false;
  var level = 0;
  if (node == null) {
    return;
  }
  while (node.nodeName != 'BODY' && level < 20) {
    if (node.nodeName == 'DIV' && node.className == 'replaceable_text') {
      //alert('Selection is replaceable');
      replaceable = true;
      break;
    } else {
      node = node.parentNode;
      level = parseInt(level) + 1;
      //alert('Level = ' + level);
    }
  }
  if (!replaceable) {
    alert('Selection is not replaceable');
    return;
  }
}

function getColumnType(selection)
{
  alert('Getting column type');

  if (selection == null) {
    alert('Selection is empty');
    return false;
  }

  // Climb up tree to containing column DIV
  var node = selection.anchorNode;
  if (node == null) {
    alert('Node is null');
    return false;
  }
  var level = 0;
  while (node.nodeName != 'BODY' && level < 20) {
    if (node.nodeName == 'DIV' && (node.className == 'left_2column' || node.className == 'right_column')) {
      return node.className;
    } else {
      node = node.parentNode;
      level = parseInt(level) + 1;
    }
  }
  return false; // not in editable column - shouldn't happen if selected
}

var replaceimageDlg = null;

function replaceImage(id, columnType)
{
  // alert('replaceImage(id = ' + id + ', columnType = ' + columnType);

  if (replaceimageDlg != null) {
    replaceimageDlg.destroy();
  }

  // If selection is in left-hand column we allow more width options. Early
  // versions didn't check column type, so in those cases we don't allow
  // width to be matched to column width.
  var ws = '';
  ws += '<input type="radio" name="selWidth" value="current" checked> &nbsp; Match width of existing image<br>';
  if (columnType == 'left_2column') {
    ws += '<input type="radio" name="selWidth" value="615"> &nbsp; Display over full width of column<br>';
    ws += '<input type="radio" name="selWidth" value="307"> &nbsp; Display over half width of column<br>';
    ws += '<input type="radio" name="selWidth" value="205"> &nbsp; Display over one third width of column<br>';
  } else if (columnType == 'right_column') {
    ws += '<input type="radio" name="selWidth" value="220"> &nbsp; Display over full width of column<br>';
    ws += '<input type="radio" name="selWidth" value="110"> &nbsp; Display over half width of column<br>';
  }
  ws += '<input type="radio" name="selWidth" value="asis"> &nbsp; Display at actual size<br>';

  // Before displaying the upload dialog, check that the user is authorised
  var xmlHttp = createXmlHttpRequest();
  xmlHttp.open("POST", 'is_webmaster.php', true);
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status == 200) {
        var resultText = xmlHttp.responseText;
        if (resultText == 'OK') {
          // Display a dialog containing the file upload form
          replaceimageDlg = new StickyWinFx( {
            fadeDuration: 1000, // (fade in and out)
            draggable: false,
            content: StickyWin.ui('Upload Image File', '<form name="uploadimageForm" action="" method="POST" enctype="multipart/form-data" target="_self"><p><strong>Choose an image to upload:</strong></p><input name="userfile" type="FILE" size="50" style="font-size: 11px; font-family: Verdana" maxlength="255" /><br>Maximum file size: 200K<input type="hidden" name="MAX_FILE_SIZE" value="1048576" /><br><br><strong>Display options:</strong></p><br>&nbsp;<br>' + ws + '<br>&nbsp;<br><input type="checkbox" name="cbx_add_frame"> &nbsp; Add a frame around the image<input type="hidden" name="imageId" value="' + id + '" /><input type="hidden" name="btn_upload_image" value="replace"><br><br></form>' + hr,
            {
              fadeDuration: 1000, // (fade in and out)
              cornerHandle: false,
              draggable: false,
              width: '400px',
              buttons: [
                {
                  text: 'Upload',
                  onClick: function() { document.forms.uploadimageForm.submit(); }
                },
                {
                  text: 'Cancel'
                }
              ]
            } )
          } );
        }
      }
    }
  }
  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlHttp.send(null);
}

Dlg = null;

function replaceMasthead()
{
  if (replaceimageDlg != null) {
    replaceimageDlg.destroy();
  }
  // Before displaying the upload dialog, check that the user is authorised
  var xmlHttp = createXmlHttpRequest();
  xmlHttp.open("POST", 'is_webmaster.php', true);
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status == 200) {
        var resultText = xmlHttp.responseText;
        if (resultText == 'OK') {
          // Display a dialog containing the file upload form
          replaceimageDlg = new StickyWinFx( {
            fadeDuration: 1000, // (fade in and out)
            draggable: false,
            content: StickyWin.ui('Upload Image File', '<form name="uploadmastheadForm" action="" method="POST" enctype="multipart/form-data" target="_self"><p><strong>Choose a masthead image to upload:</strong></p><input name="userfile" type="FILE" size="50" style="font-size: 11px; font-family: Verdana" maxlength="255" /><br>Maximum file size: 200K<input type="hidden" name="MAX_FILE_SIZE" value="102400" /><input type="hidden" name="btn_upload_image" value="replace"><input type="hidden" name="imageId" value="masthead" /><br><br></form><p>The masthead image should be 900 x 180 pixels and should be in JPEG format.</p>' + hr,
            {
              fadeDuration: 1000, // (fade in and out)
              cornerHandle: false,
              draggable: false,
              width: '400px',
              buttons: [
                {
                  text: 'Upload',
                  onClick: function() { document.forms.uploadmastheadForm.submit(); }
                },
                {
                  text: 'Cancel'
                }
              ]
            } )
          } );
        }
      }
    }
  }
  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlHttp.send(null);
}

function sendMlistRequest(adminEmail, firstName, lastName, emailAddress)
{
  var xmlHttp = createXmlHttpRequest();
  xmlHttp.open("POST", 'send_mlist_request.php', true);
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status == 200) {
        var resultText = xmlHttp.responseText;
        if (resultText == 'OK') {
          showAlert('Information', 'Thanks for requesting to join our mailing list. Please look out for our confirmation email at ' + emailAddress)
        } else {
          showAlert('Error', 'Your request to join our mailing list could not be processed because ' + resultText + '. Please try again.')
        }
      }
    }
  }
  args = 'admin_email=' + adminEmail + '&first_name=' + firstName + '&last_name=' + lastName + '&email_address=' + emailAddress;
  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlHttp.send(encodeURI(args));
}

var mlistRequestDlg = null;
function showMlistRequestDlg(adminEmail) {
  if (mlistRequestDlg) {
    mlistRequestDlg.destroy();
  }
  mlistRequestDlg = new StickyWinFx({
    fadeDuration: 1000,
    draggable: true,
    content: StickyWin.ui('Mailing List Request',
      '<form name="mlist_request_form" method="POST" enctype="multipart/form-data"><p>Please enter your name and email address below and click the Join button. We will confirm your request as soon as possible.</p><table border="0" cellspacing="0" cellpadding="0" style="width:100%"><tr><td style="width:25%">First name:</td><td style="width:70%"><input name="first_name" id="first_name" maxlength="20" style="width:200px;"></td></tr><tr><td style="width:25%">Last name:</td><td style="width:70%"><input name="last_name" id="last_name" maxlength="20" style="width:200px;"></td></tr><tr><td style="width:25%">Email address:</td><td style="width:70%"><input name="email_address" id="email_address" maxlength="255" style="width:200px;"></td></tr><tr><td colspan="2">&nbsp;</td></tr></table></form>' + hr,
      {
      width: '400px',
      buttons: [
        {
          text: 'Join',
          //onClick: function(){ document.forms.mlist_request_form.submit(); }
          onClick: function(){ var firstName = document.mlist_request_form.first_name.value; var lastName = document.mlist_request_form.last_name.value; var emailAddress = document.mlist_request_form.email_address.value; sendMlistRequest(adminEmail, firstName, lastName, emailAddress); }
        },
        {
          text: 'Cancel'
        }
      ]
      }
    )
  });
  return false;
}

//window.addEvent('domready', function() {
//});

sfHover = function() {
  var sfEls = document.getElementById("nav").getElementsByTagName("LI");
  for (var i = 0; i < sfEls.length; i++) {
    sfEls[i].onmouseover = function() {
      this.className += " sfhover";
    }
    sfEls[i].onmouseout = function() {
      this.className = this.className.replace(new RegExp(" sfhover\\b"), "");
    }
  }
}

function obfusc(ins) {
  var len = ins.length;
  var outs = '';
  for (i = 0; i < len; i++) {
    outs = outs + '&#' + ins.charCodeAt(i) + ';';
  }
  return outs;
}

