// javascript for the site


//constants
var sAJAXAutoSuggestURL = 'ajax.php?ajaxaction=searchsuggestwiki&search=';
var sAJAXrootURL        = 'ajax.php';


//globals
var iCommentsAssetType = "";
var iCommentsAssetID   = ""


//add trim to the String prototype;
String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g, '');
}




//sniff browser http://www.aspandjavascript.co.uk/javascript/javascript_api/browser_sniffer.asp

	var ns4 = document.layers;
	var op5 = (navigator.userAgent.indexOf("Opera 5")!=-1) 
		||(navigator.userAgent.indexOf("Opera/5")!=-1);
	var op6 = (navigator.userAgent.indexOf("Opera 6")!=-1) 
		||(navigator.userAgent.indexOf("Opera/6")!=-1);
	var agt=navigator.userAgent.toLowerCase();
	var mac = (agt.indexOf("mac")!=-1);
	var ie = (agt.indexOf("msie") != -1); 
	var mac_ie = mac && ie;



//media wiki startu stuff
// MediaWiki JavaScript support functions

var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var is_gecko = /gecko/.test( clientPC ) &&
	!/khtml|spoofer|netscape\/7\.0/.test(clientPC);
var webkit_match = clientPC.match(/applewebkit\/(\d+)/);
if (webkit_match) {
	var is_safari = clientPC.indexOf('applewebkit') != -1 &&
		clientPC.indexOf('spoofer') == -1;
	var is_safari_win = is_safari && clientPC.indexOf('windows') != -1;
	var webkit_version = parseInt(webkit_match[1]);
}
var is_khtml = navigator.vendor == 'KDE' ||
	( document.childNodes && !document.all && !navigator.taintEnabled );
// For accesskeys; note that FF3+ is included here!
var is_ff2 = /firefox\/[2-9]|minefield\/3/.test( clientPC );
// These aren't used here, but some custom scripts rely on them
var is_ff2_win = is_ff2 && clientPC.indexOf('windows') != -1;
var is_ff2_x11 = is_ff2 && clientPC.indexOf('x11') != -1;
if (clientPC.indexOf('opera') != -1) {
	var is_opera = true;
	var is_opera_preseven = window.opera && !document.childNodes;
	var is_opera_seven = window.opera && document.childNodes;
	var is_opera_95 = /opera\/(9.[5-9]|[1-9][0-9])/.test( clientPC );
}




// Global external objects used by this script.
/*extern ta, stylepath, skin */

// add any onload functions in this hook (please don't hard-code any events in the xhtml source)
var doneOnloadHook;

if (!window.onloadFuncts) {
	var onloadFuncts = [];
}

function addOnloadHook(hookFunct) {
	// Allows add-on scripts to add onload functions
	if(!doneOnloadHook) {
		onloadFuncts[onloadFuncts.length] = hookFunct;
	} else {
		hookFunct();  // bug in MSIE script loading
	}
}

function hookEvent(hookName, hookFunct) {
	addHandler(window, hookName, hookFunct);
}

/**
 * Add an event handler to an element
 *
 * @param Element element Element to add handler to
 * @param String attach Event to attach to
 * @param callable handler Event handler callback
 */
function addHandler( element, attach, handler ) {
	if( window.addEventListener ) {
		element.addEventListener( attach, handler, false );
	} else if( window.attachEvent ) {
		element.attachEvent( 'on' + attach, handler );
	}
}


function isValidEmail(str) {
   return (str.indexOf(".") >= 1) && (str.indexOf("@") > 0);
}

function GetValueSafe(xx) {
  try
  {
    return(xx[0].firstChild.nodeValue);
  }
  catch (er)
  {
    return(" ");
  }
}

function FloorToZero(iVal){

  if (iVal < 0){
    return 0;
  }else{
    return iVal;
  }
}


function writeTip(sTemp){
  if (sTemp == ''){
    //clear
    return nd();
  }else{
    //set tool tip
    return overlib(sTemp,  BGCOLOR, '#0099cc', FGCOLOR, '#eceff6', TEXTFONT, 'tahoma,verdana,arial,sans-serif');
  }
}



function DrawCircle(sCoords){
  //580,275,33 -> database
  var x, y, width, height = 0;
  var arrCoords = sCoords.split(",");
  
  document.getElementById("debug").innerHTML = arrCoords.length;
  
  if (arrCoords.length != 3){
    return false;
  }
  //drawEllipse(X, Y, width, height); -> where xy = top right corner (not centre)
  //width & height = (arrCoords[2] * 2)
  //x = arrCoords[0] - arrCoords[2]
  //y = arrCoords[1] - arrCoords[2]
  
  x = arrCoords[0] - arrCoords[2];
  y = arrCoords[1] - arrCoords[2];
  width = arrCoords[2] * 2;
  height = width;
  
    document.getElementById("debug").innerHTML = arrCoords.length;
  //
  jg.clear();
  jg.setStroke(5);
  jg.setColor("#0099cc");
  jg.drawEllipse(x, y, width, height);
  jg.paint();
  
  
  document.getElementById("debug").innerHTML = "sCoords=" + sCoords + "<br />x=" + x + ", y=" + y + ", width=" + width + ", height=" + height;
  document.getElementById("debug").innerHTML = "";
}

function DrawRect(sCoords){
  var x, y, width, height = 0;
  //jg.drawRect(X, Y, width, height);
  // database supplies: 545,52,647,212 (xyzx)
  //first off parse the co-ords...
  var arrCoords = sCoords.split(",");
  if (arrCoords.length != 4){
    return false;
  }

  //ok now have an array
  //we have pairs [0] -> [2] and [1] -> [3] but is possible the order is wrong!

  //deal with the X coords
  if (arrCoords[0] > arrCoords[2]){
    x = arrCoords[2];
    width = arrCoords[0] - arrCoords[2];
  }else{
    x = arrCoords[0];
    width = arrCoords[2] - arrCoords[0];
  }


  //deal with the Y coords
  if (arrCoords[1] > arrCoords[3]){
    y = arrCoords[3];
    height = arrCoords[3] - arrCoords[1];
  }else{
    y = arrCoords[0];
    height = arrCoords[1] - arrCoords[3];
  }


  //sanity check then display


  //
  jg.clear();
  jg.setStroke(5);

  //
  jg.setColor("#0099cc");
  
  // a   b
  // c   d
  
  // a = [0,1]
  // b = [2,1]
  // c = [0,3]
  // d = [2,3]
  
  
  document.getElementById("debug").innerHTML = "sCoords=" + sCoords + "<br />x=" + x + ", y=" + y + ", width=" + width + ", height=" + height;
  
  //a - > b
  jg.drawLine(arrCoords[0], arrCoords[1], arrCoords[2], arrCoords[1]);
  document.getElementById("debug").innerHTML = document.getElementById("debug").innerHTML + "<br />top: " + arrCoords[0] + " " + arrCoords[1] + " " + arrCoords[2] + " " + arrCoords[1];
  
  //a -> c
//  jg.drawLine(arrCoords[0], arrCoords[1], arrCoords[0], arrCoords[3]);
//  document.getElementById("debug").innerHTML = document.getElementById("debug").innerHTML + "<br />left: " + arrCoords[0] + " " + arrCoords[1] + " " + arrCoords[0] + " " + arrCoords[3];
  
  //c -> d
  jg.drawLine(arrCoords[0], arrCoords[3], arrCoords[2], arrCoords[3]);
  document.getElementById("debug").innerHTML = document.getElementById("debug").innerHTML + "<br />bottom: " + arrCoords[0] + " " + arrCoords[3] + " " + arrCoords[2] + " " + arrCoords[3];

  
  //d -> b
  jg.drawLine(arrCoords[2], arrCoords[1], arrCoords[2], arrCoords[3]);
  document.getElementById("debug").innerHTML = document.getElementById("debug").innerHTML + "<br />right: " + arrCoords[2] + " " + arrCoords[1] + " " + arrCoords[2] + " " + arrCoords[3];

  //a -> d
//  jg.drawLine(arrCoords[0], arrCoords[1], arrCoords[2], arrCoords[3]);

//  jg.drawRect(x, y, width, height);


  //why aren't the left and right hand side ones working in IE7 and the drawrect is really buggered :-(

  //jg.drawLine(arrCoords[0], arrCoords[1], arrCoords[2], arrCoords[3]);
  jg.paint();

  document.getElementById("debug").innerHTML = "";
}



function HoopThem(sShape, sCoords){

  try
  {

    if (sShape == ''){
      jg.clear();
    }


    if (sShape == 'rect'){
      //draw a rect
      DrawRect(sCoords);
      //jg.drawRect(X, Y, width, height);
      // database supplies: 545,52,647,212 (xyzx)
    }

    if (sShape == 'circle'){
      DrawCircle(sCoords);
      //  document.getElementById('content').innerHTML = sShape + ' - ' + sCoords;
      //jg.setColor("#ff0000"); // red
      //jg.drawLine(10, 113, 220, 55); // co-ordinates related to "myCanvas"
      //jg.setColor("#0000ff"); // blue
      //jg.fillRect(110, 120, 30, 60);
      //jg.paint();

      //jg.clear();
    }

  }catch(err){


  }
}



/* AJAX functions */

//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
  if (window.XMLHttpRequest) {
    return new XMLHttpRequest();
  } else if(window.ActiveXObject) {
  	return new ActiveXObject("Microsoft.XMLHTTP");	
  } else {
    alert("ERROR: Your Browser does not support AJAX requests.");
  }
}



/////// MEDIA WIKI AUTOSUGGEST ////////








function getElementWidth(Elem) {
	if (ns4) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.width;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (op5) {
			xPos = elem.style.pixelWidth;
		} else {
			xPos = elem.offsetWidth;
		}
		return xPos;
	}
}






/* picture align centre? */
function doCentrePicture(){

  //firefox workaround
  //get width of picture
  var iWidth = getElementWidth("imgGroupPic"); // document.getElementById("photoID").offsetWidth;
  iWidth = iWidth / 2;

  document.getElementById("photoID").style.left = -iWidth + "px";
}



function Plural(iVal){
  if (iVal == 1) {
    return '';
  }else{
    return 's';
  }
}

function make2digits(iVal) {
  if (iVal > 9) {
    return(iVal);
  }else{
    return("0" + iVal);  
  }
}



//// matt AJAX stuff ////
//use globals 
/*
          var bAuthenticated   = true;   //allow flagging
          var bAdmin           = false;  //allow deletion
          var cnstShowcomments = true;   //allow!
*/

/*
  <commentID>46</commentID> 
  <authenticatorIcon>./pictures/siteimages/oldsms.gif</authenticatorIcon> 
  <AuthenticatorName>Old Site</AuthenticatorName> 
  <ProfileLink /> 
  <CreatorName></CreatorName> 
  <when>at 15:24 on 08 September 2001</when> 
  <comment></comment> 
*/

function displayComments(x){
  document.getElementById('divComments').innerHTML = "comments";

  var bComments = false;
  var out = "";
  var sNoCommentsYet = "<img src=\"pictures/siteimages/comments.gif\" alt=\"Comments\" title=\"Comments\" />&nbsp;&nbsp; no comments yet!<br /><br />";
  
  if (x.length < 1) {
//    out = "<div class=\"clsCommentsTitle\"><img src=\"pictures/siteimages/comments.gif\" alt=\"Comments\" title=\"Comments\" />&nbsp;&nbsp; [no comments yet]</div>\n";
  } else {
    out = "<div class=\"clsCommentsTitle\"><img src=\"pictures/siteimages/comments.gif\" alt=\"Comments\" title=\"Comments\" />&nbsp;&nbsp;<small>" + x.length + " Comment" + Plural(x.length) + ":</small></div>\n";

    for (i=0; i< x.length; i++)
    {
      bComments = true;
      //write out the comments...
      //get variables!
      xx=x[i].getElementsByTagName("commentID");
      iCommentID = GetValueSafe(xx);
      
      xx=x[i].getElementsByTagName("authenticatorIcon");
      sAuthenticatorIcon = GetValueSafe(xx);
      xx=x[i].getElementsByTagName("AuthenticatorName");
      sAuthenticatorName = GetValueSafe(xx);
      xx=x[i].getElementsByTagName("ProfileLink");
      sProfileLink = GetValueSafe(xx);   
      
      xx=x[i].getElementsByTagName("CreatorName");
      sCreatorUserName = GetValueSafe(xx);
      xx=x[i].getElementsByTagName("when");
      sWhen = GetValueSafe(xx);
      
      
      xx=x[i].getElementsByTagName("commentText");
      sComment = GetValueSafe(xx);
      sComment = sComment.replace(/\n/gi, "\n<br />")
    
      //xx[0].firstChild.nodeValue

      out += "<div class=\"clsCommentHeader\">\n";
      out += "<table class=\"clsCommentHeaderTable\"><tr><td>\n";
      out += "<img name=\"grouppic\" id=\"grouppic\" src=\"" + sAuthenticatorIcon + "\" border=0 alt=\"" + sAuthenticatorName + "\" />&nbsp;&nbsp;\n";
//      alert(">" + sProfileLink + "<");
      if (sProfileLink.trim() != "") {out += "<a href=\"" + sProfileLink +  "\"  target=\"_blank\">\n";}
      out += sCreatorUserName;
      if (sProfileLink != "") {out += "</a>";}
      out += " wrote " + sWhen + ":\n";
      out += "</td>\n<td class=\"clsCommentHeaderTableActionCell\">";


      out += "<!-- authenticated --><a href=\"#\" onClick=\"return(doFlagComment(" + iCommentID + "))\"><img src=\"./pictures/siteimages/flag.gif\" title=\"Click here to flag this comment as unsuitable\" alt=\"Click here to flag this comment as unsuitable\" border=\"0\"/></a>";

      if (bAuthenticated){

        if (bAdmin){
          out += "<!-- admin --><a href=\"#\" onClick=\"return(doKillComment(" + iCommentID + "))\"><img src=\"./pictures/siteimages/kill.gif\" title=\"Click here to kill this comment\" alt=\"Click here to kill this comment\" border=\"0\"/></a>";
        }else{
          out += "<!-- not admin -->";
        }
      }else{
        out += "<!-- not authenticated -->&nbsp;";
      }
   
      out += "</td></tr></table>\n";
      out += "</div>\n";
      out += "<div class=\"clsCommentText\">\n";
      out += "<img src=\"./pictures/siteimages/start_quote_rb.gif\" width=\"24\" height=\"13\" alt=\"\" border=\"0\" />\n";
      out += sComment + "\n";
      out += "<img src=\"./pictures/siteimages/end_quote_rb.gif\" align=\"right\" width=\"23\" height=\"13\" alt=\"\" border=\"0\" vspace=\"0\"><br clear=\"all\"/>\n";
      out += "</div>\n";
    }
  }

  //draw the submit comment box?
  if (bAuthenticated){
      out += "<!-- submit comment form -->\n";
      out += "<div class=\"clsCommentHeader\">\n";
      if (!bComments){ out += sNoCommentsYet; }
      out += "Add your own comment: (Please be warned that leaving personal contact information in the message is probably a bad idea).\n";
      out += "</div>\n";
      out += "<div class=\"clsCommentText\">\n";    
      out += "<form id=\"frmAddComment\">";
      out += "<textarea class=\"clsTextBoxExpand\" name=\"txtAddComment\" id=\"txtAddComment\"></textarea>\n";
      out += "<br /><button onClick=\"return(SubmitComment())\">Submit Comment</button>\n";
      out += "\n";
      out += "\n";
      out += "\n";
      out += "</form>\n";
      out += "</div>\n";
  }else{
      out += "<!-- submit comment form but not logged in! -->\n";
      out += "<div class=\"clsCommentNeedToLogin\">\n";
      if (!bComments){ out += sNoCommentsYet; }
      out += "Login to the site to add your own comments!<br /><a href=\"?action=staticpage&amp;subaction=show&amp;pageid=1\">Click here for more information</a>\n";
      out += "</div>\n";

  }
  
  document.getElementById('divComments').innerHTML = out;
}


function WriteComments(sAssetID, iAssetType){
  var xmlhttp=false; //Clear our fetching variable
  var divToUse = document.getElementById("divComments");

  if (!(cnstShowcomments)){
    divToUse.innerHTML = "[To see comments, you must login first...]";
    return;
  }
  
  iCommentsAssetType = iAssetType;
  iCommentsAssetID   = sAssetID;

  divToUse.innerHTML = "&nbsp;<img src=\"./pictures/siteimages/hourglass.gif\" title=\"image: loading icon\" />&nbsp;Loading comments...&nbsp;"; //perhaps show a loading thingy?

  xmlhttp = getXmlHttpRequestObject();

  //query the AJAX interface for comments
  var sAjaxPath = sAJAXrootURL + '?ajaxaction=getCommentsForObject&assetid=' + sAssetID + '&assettype=' + iAssetType;
  xmlhttp.open('GET', sAjaxPath, true); //Open the file through GET, and add the id we want to retrieve as a GET variable
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4) { //Check if it is ready to recieve data
      if (xmlhttp.status == 200) {
        x = xmlhttp.responseXML.documentElement.getElementsByTagName("comment");
        //populate the DIV
        //populate the results
        displayComments(x);

      } else {
        divToUse.innerHTML = '';
      }
    }
  }
  xmlhttp.send(null) //Nullify the XMLHttpRequest
  return false;
}


function doFlagComment(iCommentID){

  //reset the form for niceness
  document.getElementById("txtAlerter").value     = ""; //actually should be the authenticated user's name
  document.getElementById("txtAlerterMail").value = ""; //actually should be the authenticated user's mail address
  document.getElementById("cmboRemoveNow").checked  = false;
  document.getElementById("cmboReason").value     = "";
  document.getElementById("txtMessage").value     = "";
  
  //display dialog to submit 
  document.getElementById("commentID").value = iCommentID;
  
  doShowHideFlagComment(true);

  return false;
}


function ShowHidePhotoIfThere(bShow){
// photoID
 
   var divToUsePhoto = document.getElementById("photoID");
   var divToUseNames = document.getElementById("divPhotoNames");
   
   if ((divToUsePhoto == null) || (divToUseNames == null)) {
     return;
   }
   
  if (bShow){
    divToUsePhoto.style.visibility = "visible";
    divToUsePhoto.style.display    = "block";
    divToUseNames.style.visibility = "visible";
    divToUseNames.style.display    = "block";
  }else{
    divToUsePhoto.style.visibility = "hidden";
    divToUsePhoto.style.display    = "none";
    divToUseNames.style.visibility = "hidden";
    divToUseNames.style.display    = "none";
  }
  

}

function doShowHideFlagComment(bShow){
  var divToUse = document.getElementById("divFlagMessageToAdminForm");
  
  if (bShow){
    divToUse.style.visibility = "visible";
    divToUse.style.display    = "block";
    ShowHidePhotoIfThere(false);
  }else{
    divToUse.style.visibility = "hidden";
    divToUse.style.display    = "none";
    ShowHidePhotoIfThere(true);
  }
  
  return false;
}

function doSubmitFlagComment(){

  //get values:
var txtAlerter      = document.getElementById("txtAlerter").value;
var txtAlerterMail  = document.getElementById("txtAlerterMail").value;
var cmboRemoveNow   = document.getElementById("cmboRemoveNow").checked;
var cmboReason      = document.getElementById("cmboReason").value;
var txtMessage      = document.getElementById("txtMessage").value;
var commentID       = document.getElementById("commentID").value;

//alert('cmboRemoveNow=' + cmboRemoveNow);

  //use these globals
  //iCommentsAssetType
  //iCommentsAssetID

  //validate form...
  if (txtAlerter.trim() == ""){
    alert('You must provide your name!');
    document.getElementById("txtAlerter").focus();
    return false;
  }
  
  //should check valid email address?
  if (txtAlerterMail.trim() == ""){
    alert('You must provide your email address so that we may confirm details with you!');
    document.getElementById("txtAlerterMail").focus();
    return false;
  }
  
  if (!(isValidEmail(txtAlerterMail))){
    alert('You must provide a valid email address so that we may confirm details with you!');
    document.getElementById("txtAlerterMail").focus();
    return false;
  }
  
  if (cmboReason.trim() == ""){
    alert('Please choose the most suitable reason for flagging this comment from the drop down list.');
    document.getElementById("cmboReason").focus();
    return false;
  }
  
  if (txtMessage.trim() == ""){
    alert('Please give your reasons for wishing to flag this message to the administrators - and what you would like them to do.');
    document.getElementById("txtMessage").focus();
    return false;
  }

  //submit the comments
  //prob should show working in some way?
  var postparams = "txtAlerter=" + encodeURI( txtAlerter ) +
                   "&txtAlerterMail=" + encodeURI( txtAlerterMail ) +
                   "&cmboRemoveNow=" + encodeURI( cmboRemoveNow ) +
                   "&cmboReason=" + encodeURI( cmboReason ) +
                   "&txtMessage=" + encodeURI( txtMessage ) +
                   "&iCommentsAssetType=" + encodeURI( iCommentsAssetType ) +
                   "&iCommentsAssetID=" + encodeURI( iCommentsAssetID ) +
                   "&commentID=" + encodeURI( commentID );

  var divToUse = document.getElementById("divComments");
  divToUse.innerHTML = "&nbsp;<img src=\"./pictures/siteimages/hourglass.gif\" title=\"image: loading icon\" />&nbsp;Please wait whilst your message is sent...&nbsp;"; //perhaps show a loading thingy?
  
  //AJAX url
  var sAjaxPath = sAJAXrootURL + '?ajaxaction=FlagCommentToAdmins';
  
  http_request = getXmlHttpRequestObject();
      
  http_request.onreadystatechange = function(){
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert( http_request.responseText );
            var sResult = http_request.responseXML.documentElement.getElementsByTagName("result")[0].firstChild.nodeValue;
            
            if (sResult == 'ok'){
              divToUse.innerHTML = "";
              alert('You message has been sent to the administrators');
              //refresh comments
              DoComments(); //remember this function "knows" the parameters for the comments
            }else{
              alert('ERROR: Unable to flag this comment to the administrators, please try again later.');
              
              var sErrorMsg = http_request.responseXML.documentElement.getElementsByTagName("error_message")[0].firstChild.nodeValue;

              divToUse.innerHTML = "ERROR message : " + sErrorMsg;
//              //refresh comments//
//              DoComments(); //remember this function "knows" the parameters for the comments
            }
         } else {
            alert('There was a problem with the request.');
         }
         //refresh comments
         DoComments(); //remember this function "knows" the parameters for the comments         
      }

  };
  http_request.open('POST', sAjaxPath, true);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", postparams.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(postparams);

  doShowHideFlagComment(false);
  
  return false;  
}


function doKillComment(iCommentID){
var xmlhttp=false; //Clear our fetching variable

  //confirm
  var r=confirm("Are you really sure that you wish to kill this comment? It will be lost forever!!!!");
  
  if (r!=true) {return;}
  
  var divToUse = document.getElementById("divComments");
  divToUse.innerHTML = "&nbsp;<img src=\"./pictures/siteimages/hourglass.gif\" title=\"image: loading icon\" />&nbsp;Please wait whilst the kill is actioned...&nbsp;"; //perhaps show a loading thingy?

  xmlhttp = getXmlHttpRequestObject();       
  var sAjaxPath = sAJAXrootURL + '?ajaxaction=KillComment&commentID=' + iCommentID.toString();

  xmlhttp.open('GET', sAjaxPath, true); //Open the file through GET, and add the id we want to retrieve as a GET variable
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4) { //Check if it is ready to recieve data
      if (xmlhttp.status == 200) {
        var sResult = xmlhttp.responseXML.documentElement.getElementsByTagName("result")[0].firstChild.nodeValue;

        if (sResult == 'ok'){
          divToUse.innerHTML = "";
          alert('Comment killed');
          //refresh comments
          DoComments(); //remember this function "knows" the parameters for the comments         
        }else{
          alert('ERROR: Unable to kill comment, please try again later.');
        }
      }
    }
  }
  xmlhttp.send(null) //Nullify the XMLHttpRequest
  return false;
}


function SubmitComment(){


  //use these globals
  //iCommentsAssetType
  //iCommentsAssetID
  
  var txtAddComment      = document.getElementById("txtAddComment").value;
  
  if (txtAddComment.trim() == ""){
    alert('You don\'t seem to have added a message!');
    document.getElementById("txtAddComment").focus();
    return false;
  }
  
  var postparams = "iCommentsAssetType=" + encodeURI( iCommentsAssetType ) +
                   "&iCommentsAssetID=" + encodeURI( iCommentsAssetID ) +
                   "&commentText=" + encodeURI( txtAddComment );

  var divToUse = document.getElementById("divComments");
  divToUse.innerHTML = "&nbsp;<img src=\"./pictures/siteimages/hourglass.gif\" title=\"image: loading icon\" />&nbsp;Please wait whilst your comment is added...&nbsp;"; //perhaps show a loading thingy?
  
  //AJAX url
  var sAjaxPath = sAJAXrootURL + '?ajaxaction=SubmitComment';
  
  http_request = getXmlHttpRequestObject();
      
  http_request.onreadystatechange = function(){
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            var sResult = http_request.responseXML.documentElement.getElementsByTagName("result")[0].firstChild.nodeValue;
            
//  document.getElementById("debug").innerHTML = http_request.responseText;
            
            if (sResult == 'ok'){
              //refresh comments
              DoComments(); //remember this function "knows" the parameters for the comments         
            }else{
              var sLocalErr = "";
              try
              {
                sLocalErr = " [ " + http_request.responseXML.documentElement.getElementsByTagName("result")[0].firstChild.nodeValue + "]";
              } catch(err){
                //
              }
              alert('ERROR: Unable to post your comment at this time, please try again later. ' + sLocalErr);
            }
         } else {
            alert('There was a problem with the request.');
         }
         //refresh comments
         DoComments(); //remember this function "knows" the parameters for the comments
      }

  };
  http_request.open('POST', sAjaxPath, true);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", postparams.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(postparams);

//  doShowHideFlagComment(false);
  
  return false;  
  

}


function doHideFlagCorrection(bShow){
  var divToUse = document.getElementById("divCorrections");
  
  if (bShow){
    divToUse.style.visibility = "visible";
    divToUse.style.display    = "block";
    ShowHidePhotoIfThere(false);
  }else{
    divToUse.style.visibility = "hidden";
    divToUse.style.display    = "none";
    ShowHidePhotoIfThere(true);
  }
  
  return false;
}


function ShowCorrectAssetForm(iAssetType, iAssetID){

  //populate form
  document.getElementById("CorrectAssetType").value = iAssetType;
  document.getElementById("CorrectAssetID").value   = iAssetID;
  
  // show form
  doHideFlagCorrection(true);
  
  return false;
}



function doSubmitFlagCorrection(){


  //get values:
var txtAlerter      = document.getElementById("CorrecttxtAlerter").value;
var txtAlerterMail  = document.getElementById("CorrecttxtAlerterMail").value;
var txtMessage      = document.getElementById("CorrecttxtMessage").value;

  //get these from the form - hate globals!!!
var iCommentsAssetType = document.getElementById("CorrectAssetType").value;
var iCommentsAssetID   = document.getElementById("CorrectAssetID").value;

  //validate form...
  if (txtAlerter.trim() == ""){
    alert('You must provide your name!');
    document.getElementById("CorrecttxtAlerter").focus();
    return false;
  }
  
  //should check valid email address?
  if (txtAlerterMail.trim() == ""){
    alert('You must provide your email address so that we may confirm details with you, if necessary!');
    document.getElementById("CorrecttxtAlerterMail").focus();
    return false;
  }
  
  if (!(isValidEmail(txtAlerterMail))){
    alert('You must provide a valid email address so that we may confirm details with you, if necessary!');
    document.getElementById("CorrecttxtAlerterMail").focus();
    return false;
  }
  
  if (txtMessage.trim() == ""){
    alert('Please give as much information as possible.');
    document.getElementById("CorrecttxtMessage").focus();
    return false;
  }

  //submit the comments
  //prob should show working in some way?
  var postparams = "txtAlerter=" + encodeURI( txtAlerter ) +
                   "&txtAlerterMail=" + encodeURI( txtAlerterMail ) +
                   "&txtMessage=" + encodeURI( txtMessage ) +
                   "&iCommentsAssetType=" + encodeURI( iCommentsAssetType ) +
                   "&iCommentsAssetID=" + encodeURI( iCommentsAssetID );

  var divToUse = document.getElementById("divComments");
  divToUse.innerHTML = "&nbsp;<img src=\"./pictures/siteimages/hourglass.gif\" title=\"image: loading icon\" />&nbsp;Please wait whilst your message is sent...&nbsp;"; //perhaps show a loading thingy?
  
  //AJAX url
  var sAjaxPath = sAJAXrootURL + '?ajaxaction=SubmitCorrection';
  
  http_request = getXmlHttpRequestObject();
      
  http_request.onreadystatechange = function(){
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
//            alert( http_request.responseText );
            var sResult = http_request.responseXML.documentElement.getElementsByTagName("result")[0].firstChild.nodeValue;
            
            if (sResult == 'ok'){
              divToUse.innerHTML = "";
              alert('You message has been sent to the administrators, many thanks for your corrections.');
              //refresh comments
              DoComments(); //remember this function "knows" the parameters for the comments
            }else{
              alert('ERROR: Sorry, it was not possible to send the corrections to the administrators at the moment, please try again later or contact us via our Contact page.');
              
              var sErrorMsg = http_request.responseXML.documentElement.getElementsByTagName("error_message")[0].firstChild.nodeValue;

              divToUse.innerHTML = "ERROR message : " + sErrorMsg;
//              //refresh comments//
//              DoComments(); //remember this function "knows" the parameters for the comments
            }
         } else {
            alert('There was a problem with the request.');
         }
         //refresh comments
         DoComments(); //remember this function "knows" the parameters for the comments         
      }

  };
  http_request.open('POST', sAjaxPath, true);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", postparams.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(postparams);

  doHideFlagCorrection(false);
  
  return false;  


}


function isNumeric(sText){
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
   
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
}


function ValidateDateString(sDate){

  if (sDate.length != 10){
    return false;
  }
  
  // 12/01/2009
  // dd/mm/yyyy
  // 0123456789
 
  var sDay   = sDate.substr(0, 2);
  var sMonth = sDate.substr(3, 2);
  var sYear  = sDate.substr(6, 4);
  
//  alert("isNumeric(sDay)=" + isNumeric(sDay));
//  alert("isNumeric(sMonth)=" + isNumeric(sMonth));
//  alert("isNumeric(sYear)=" + isNumeric(sYear));

  //numbers?
  if ((!isNumeric(sDay)) || (!isNumeric(sMonth)) || (!isNumeric(sYear))){
    return false;
  }

  //ok now check the values:
  var iDay   = parseInt(sDay, 10);
  var iMonth = parseInt(sMonth, 10);
  var iYear  = parseInt(sYear, 10);

  if ((iDay < 1) || (iDay > 31)){
    return false;
  }

  if ((iMonth < 1) || (iMonth > 12)){
    return false;
  }

  var d = new Date(); 
  if ((iYear < 1920) || (iYear > d.getFullYear())){
    return false;
  }

  return true;
}

function checkGroupUploadForm1(){


  var sNewCourseName      = document.getElementById("txtNewCourseName").value;
  var sNewCourseDate      = document.getElementById("txtNewCourseDate").value;

//alert(sNewCourseDate);

  if (sNewCourseName.trim() == ""){
    alert('You must supply a course name!');
    document.getElementById("txtNewCourseName").focus();
    return false;
  }

  if (!ValidateDateString(sNewCourseDate)){
    alert('You must supply a date in the form dd/mm/yyyy!');
    document.getElementById("txtNewCourseDate").focus();
    return false;
  }

  return true;
}