//this file now includes some additonal functions not just validation
var awCMUsePanelMenu;
function awCMOnLoad() {
    if (awCMUsePanelMenu) {
        awCMPanelOnLoad();
    }
}

// global function to deal with document.all
if(document.all && !document.getElementById) {
    document.getElementById = function(id) {
         return document.all[id];
    }
}

var csvalcustom=false;
var csyear; var csmonth;
var sFilmstripImage = "";

function awCMcstest(){
	// use to test the web sever is serving this file
	alert("Successful call to cdgval.js");
	}
	
function cstrim(s){
	// equivalent to vb trim
	var whitespace = " \t\n\r";
	if ((s == null) || (s.length == 0)){return "";}
	while (s.length>0){
		var c = s.charAt(0);
		if (whitespace.indexOf(c) == -1){break;}
		else {s = s.substring(1)}	
	}
	while (s.length>0){
		var c = s.charAt(s.length-1);
		if (whitespace.indexOf(c) == -1){break;}
		else {s = s.substring(0, s.length-1)}
	}
return s;
}

function awCMcsval(form){
	// iterates through the form elements checking for v_fields,
	// looking up their matching fields and calling csfield for each one
	var s=""; var fname; var valtype; var ss
	var sline = "__________________________________________\n\n"
	var x = form.length;
	var foundfield = false;
	x = x -1
	for (var i = 0; i <= x; i++) {
	    if (form.elements != null) {
	        fname = form.elements[i].name
	        if (fname.substring(0, 2) == "v_") {
	            valtype = form.elements[i].value
	            valtype = valtype.toUpperCase()
	            fname = fname.substring(2)
	            for (var j = 0; j <= x; j++) {
	                if (form.elements[j].name == fname) {
	                    // do something different for a check box
	                    if (form.elements[j].type == "checkbox") {
	                        s = s + csfield(form.elements[j].checked, valtype, fname);
	                    }
	                    else {
	                        s = s + csfield(form.elements[j].value, valtype, fname);
	                    }
	                }
	            }
	        }
	    }
	}
	if (s!="") {
		ss = sline + "This form has error(s) and cannot be submitted.\n"
		ss = ss + "Please correct the following error(s) and re-submit:\n"
		s = ss + sline + s
		alert(s);
		return false;}
	else {
	return true;}
}

function csfield(v, valtype, fname){
	// validation of a single field, against a validation string
	// which can have multiple elements eg "MONEYPOSITIVE"
	var s=""; var isminus; var cursign = "£$p"; var digits= ".01234567890"
	v = cstrim(v);
	
	if (v == "")
	{
		if ((valtype.search("REQUIRED")!=-1) && (v == ""))
		{
			s = s + fname + " may not be left blank\n"
		}
					
		if ((valtype.search("TERMS")!=-1)) // && ( v == "" ))
		{
			s = s + "we are unable to proceed unless you accept our terms and conditions.\nPlease read our terms and check the " + fname + " box\n"; 
		}
	
	}
	else
	{
		if ((valtype.search("NUMBER")!=-1)||(valtype.search("MONEY")!=-1))
		{
			if (v.charAt(0)=="+")
			{
				v = v.substring(1);
			}
			if (valtype.search("MONEY")!=-1)
			{
				if (v.charAt(0)=="-")
				{
					isminus=true;
					v=v.substring(1);
				}
				if (cursign.indexOf(v.charAt(0))!=-1)
				{
					v = v.substring(1);
				}	
				if (v.charAt(0)=="+")
				{
					v = v.substring(1);
				}
				if (cursign.indexOf(v.charAt(v.length -1))!=-1)
				{
					v = v.substring(0, v.length-1);
				}
			}
			if (v=="")
			{
				v = 0;
			}
			if (v.charAt(0)=="-")
			{
				isminus=true;
				v=v.substring(1);
			}
			for (var i=0;i<v.length;i++)
			{
				if (digits.indexOf(v.charAt(i)) == -1)
				{
					s= s + fname + " may only contain digits (" + v.charAt(i) + " is not)\n";
					break;
				}
			}
			if (v.indexOf(".", Math.max(0, v.indexOf(".")+1))!=-1)
			{
				s =s + fname + " may only have one decimal place (" + v + " does not)\n";
			}	
			if ((isminus==true) && (v!=0))
			{
				v = "-" + v;
			}
			if (s == "")
			{
				if ((valtype.search("INTEGER")!=-1) && (Math.round(v)!= v))
				{
					s= s + fname + " must be a whole number (" + v + " is not)\n";
				}
				if ((valtype.search("NONZERO")!=-1) && (v == 0))
				{
					s= s + fname + " cannot be zero\n";
				}
				if ((valtype.search("POSITIVE")!=-1) && (v < 0))
				{
					s= s + fname + " must be positive (" + v + " is not)\n";
				}
				if ((valtype.search("NEGATIVE")!=-1) && (v > 0))
				{
					s = s + fname + " must be negative (" + v + " is not)\n";
				}
				if ((valtype.search("YYYY"))!=-1)
				{
					csyear=v;
				}
				if ((valtype.search("MOY"))!=-1)
				{
					csmonth=v;
				}
				if (((valtype.search("DOM"))!=-1) && (csmonth!=""))
				{
					switch(csmonth)
					{
						case "04":
						case "06":
						case "09":
						case "11":
							if (v=="31")
							{
								s= s + fname + " - no 31st day of month " + csmonth + "\n";
							}
							break;
						case "02":
							if (v=="31")
							{
								s= s + fname + " - no 31st day of February\n";
							}
							if (v=="30")
							{
								s= s + fname + " - no 30th day of February\n";
							}
							if ((v=="29") && (csyear!=""))
							{
								if (csyear%4!=0)
								{
									s= s + fname + " - no 29th day of February in " + csyear +"\n";
								}
							}
							break;
					} // switch (csmonth)
				} //DOM 
			}// (s == "")
		}//NUMBER or MONEY		
		else
		{
			if (valtype.search("EMAIL")!=-1)
			{
				//var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
				//var regex = new RegExp(emailReg);
				//if (regex.test(v)==false){
				 var addressPattern =  /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
				if (addressPattern.test(v)==false)
				{
					s = s + fname + " must be a valid e-mail address (" + v + " is not)\n";
				}
			}	
		}
		//DATE ?use a drop down box?
		//URL
		//POSTCODE
		//ZIP
		//IMAGE - check file extensions
		if (csvalcustom)
		{
			s = s + awCMcscustom(v, valtype, fname);
		}			
	} // end of else of (v == "")
	
return s;
}

/* IMAGE handling routines for GALLERY, FILMSTRIP, SLIDESHOW, THUMBNAILS*/

// swap gallery images:
function awSwapImageAndCaption( sImage, sCaption)
{
	document.getElementById('awGalleryMain').src = sImage
	document.getElementById('awGalleryCaption').innerText = sCaption
}

// filmstrip functions
function awRollFilmstrip( sDirection, sTableName )
{
	//find start of roll
	var myTDs = document.getElementById('awFilmstripTable1').rows[0].getElementsByTagName("td");

	//we have one td for a button at each end
	var nCurrentLeft = -1;
	var nCurrentRight = -1;
	var nNoOfImages = 0;
	for (i=2;i<(myTDs.length - 1);i++)
	{
		if (myTDs.item(i).style.display == "")
		{
			if (nCurrentLeft == -1) nCurrentLeft = i;
		
			nNoOfImages++;
		}
		else
		{
			if ( (nCurrentRight == -1 ) && (nCurrentLeft != -1) ) nCurrentRight = i;
		}
	}

    if ((sDirection == "left") && (myTDs.item(myTDs.length - 1).firstChild.disabled == false)) {

        myTDs.item(nCurrentLeft).style.display = "none";
        myTDs.item(nCurrentRight).style.display = "";
        if (nCurrentRight == myTDs.length - 2) myTDs.item(myTDs.length - 1).firstChild.disabled = true;
        myTDs.item(1).firstChild.disabled = false;
    }

    if ((sDirection == "right") && (myTDs.item(1).firstChild.disabled == false)) {
        myTDs.item(nCurrentLeft - 1).style.display = "";
        if (nCurrentRight == -1) nCurrentRight = myTDs.length - 1;
        myTDs.item(nCurrentRight - 1).style.display = "none";
        if (nCurrentLeft == 3) myTDs.item(1).firstChild.disabled = true;
        myTDs.item(myTDs.length - 1).firstChild.disabled = false;
    }
} 

// used to open image uploader
function showCrossModal( vsDestination, vsName, vnWidth, vnHeight ) 
{
	vsName = vsName.replace(' ','');
	window.open( vsDestination, vsName,'width=' + vnWidth + ',height=' + vnHeight + ',scrollbars=no,menubar=no,resizable=yes,toolbar=no,location=no,status=yes');
} 

// standard preload function
function awPreLoadImages() 
{ 
  var oDoc=document; 
  if(oDoc.images)
  { 
  	if(!oDoc.preloadList) oDoc.preloadList=new Array();
    var nCounter;
	var nLength=oDoc.preloadList.length, sArgs=awPreLoadImages.arguments;
	for(nCounter=0; nCounter<sArgs.length; nCounter++)
    if (sArgs[nCounter].indexOf("#")!=0)
	{
		oDoc.preloadList[nLength]=new Image;
		oDoc.preloadList[nLength++].src=sArgs[nCounter];
	}
  }
}

// thmbnail and blowup functions
function awThumbImage ( image, caption, index )
{
	this.image = image;
	this.caption = caption;
	this.index = index;
}

function awShowThumbs()
{	
	document.getElementById("awThumbs").style.display = "";
	document.getElementById("awBlowUp").style.display = "none";
}

function awShowBlowUp( nThumb )
{
	m_nBlowUpNumber = nThumb;
	document.getElementById("awBlowUpThumb").src = m_oThumbs[nThumb].image;
	
	// set the path for further zooming
	sFilmstripImage = m_oThumbs[nThumb].image.substring(m_oThumbs[nThumb].image.lastIndexOf('/') + 1);
	
	document.getElementById("awBlowUpCaption").innerText = m_oThumbs[nThumb].caption;
	if ( m_nBlowUpNumber > m_oThumbs.length -2 )
	{
		document.getElementById("awNextBlowUp").disabled = true;		
	}
	else
	{
		document.getElementById("awNextBlowUp").disabled = false;		
	}
	if (m_nBlowUpNumber < 1 )
	{
		document.getElementById("awPreviousBlowUp").disabled = true;		
	}
	else
	{
		document.getElementById("awPreviousBlowUp").disabled = false;
	}
	
	document.getElementById("awThumbs").style.display = "none";
	document.getElementById("awBlowUp").style.display = "";
	// preload images
	for (var nCounter = 0; nCounter < m_oThumbs.length; nCounter++ )
	{
		// do not preload the one we are displaying
		if ( nCounter != m_nBlowUpNumber )
		{
				awPreLoadImages ( m_oThumbs[nCounter].image );
		}
	}
}

function awShowNewBlowUp( vbForwards )
{
	// handle whether we are going backwards or forwards
	var nIncrement = 1;
	if (!vbForwards) nIncrement = -1;
	m_nBlowUpNumber = m_nBlowUpNumber + nIncrement;
	
	// set the image src
	document.getElementById("awBlowUpThumb").src = m_oThumbs[m_nBlowUpNumber].image;
	
	// set the path for further zooming
	sFilmstripImage = m_oThumbs[m_nBlowUpNumber].image.substring(m_oThumbs[m_nBlowUpNumber].image.lastIndexOf('/') + 1);
	
	// set the caption
	document.getElementById("awBlowUpCaption").innerText = m_oThumbs[m_nBlowUpNumber].caption;
	
	//hide the forward button if we have reached the end
	if (m_nBlowUpNumber == m_oThumbs.length - 1)
	{
			document.getElementById("awNextBlowUp").disabled = true;
	}
	else
	{
			document.getElementById("awNextBlowUp").disabled = false;
	}
	
	// hide the backwards button if we are at the start
	if ( m_nBlowUpNumber == 0 )
	{
			document.getElementById("awPreviousBlowUp").disabled = true;
	}
	else
	{
			document.getElementById("awPreviousBlowUp").disabled = false;
	}
}

function awToggleVisibility( elementName )
{
	if 	( document.getElementById( elementName ).style.display == "none" )
	{
		document.getElementById( elementName ).style.display = "";
	}
	else
	{
		document.getElementById( elementName ).style.display = "none";
	}
}

function awTogglePlusMinus( elementName )
{
	if 	( document.getElementById( elementName ).value == "+" )
	{
		document.getElementById( elementName ).value = "-";
	}
	else
	{
		document.getElementById( elementName ).value = "+";
	}
}

// function to instantiate an XMLHttpRequest object
function createXMLHttpRequest() 
{
	try 
	{ 
		return new XMLHttpRequest(); 
	} 
	catch(tryMicrosoft) 
	{
		try 
		{ 
			return new ActiveXObject("Msxml2.XMLHTTP"); 
		} 
		catch (tryOtherMicrosoft) 
		{
			try 
			{ 
				return new ActiveXObject("Microsoft.XMLHTTP"); 
			} 
			catch (failed) 
			{
				alert("XMLHttpRequest not supported");
				return null;	
			}
		}	
	}
 }
 
 function testAjaxPost()
 {
	var oRequest = createXMLHttpRequest();
	oRequest.open("POST", "ajaxResponse.aspx", false);
    oRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	//oRequest.send("id=1&user="+txtUser.value+"&password="+txtPassword.value);
	oRequest.send("id=1");
	var oResponse = oRequest.responseText;
	alert(oResponse); 
	document.getElementById('ajaxOutput1').innerHTML = oResponse;
 }
 
 function testAjax()
 {
	var oRequest = createXMLHttpRequest();
	oRequest.open("GET", "hello.txt", false);
	oRequest.send(null);
	
	var oResponse = oRequest.responseText;
	alert(oResponse);
}

// Asirra CAPTCHA code
var passThroughFormSubmit = false;
function SubmitAsirraForm() {
    if (passThroughFormSubmit) {
        return true;
    }

    // check we have a valid email address
    var validUserEmail = csfield(document.getElementById('Username').value, 'EMAILREQUIRED', 'Email');
    if (validUserEmail != '') {
        
        // need to leave a message somewhere to say email address invalid
        alert(validUserEmail);
        return false;
    }
    
    //then...
    Asirra_CheckIfHuman(HumanCheckComplete);
    return false;
}

function HumanCheckComplete(isHuman) {
    var isRegistering = true;
    document.getElementById('areRegistering').value = 'yes';
    if (document.getElementById('@btn_loginU').value != 'Register me') {
        isRegistering = false;
    }
    if ((isRegistering) && (!isHuman)) {
        alert("Please correctly identify the cats.");
    }
    else {
        if (!isRegistering) {
            document.getElementById('areRegistering').value = 'yno';
        }
        passThroughFormSubmit = true;
        formElt = document.getElementById("frmMemberLogin");
        formElt.submit();
    }
}

function showAsirra() {

    document.getElementById('asirraDiv').style.display = '';
    document.getElementById('loginDiv').style.display = 'none';
    document.getElementById('@btn_loginU').value = 'Register me';
    document.getElementById('@btn_register').style.display = 'none';
}
