// JavaScript Document

var bo_ns_id = 0;
var flashvars = {};
var params = {};
var attributes = {};
var dmWorkPath = "/scripts/";

params.allowscriptaccess = "sameDomain"; 

var sOpn = String.fromCharCode(60);
var sCls = String.fromCharCode(62);


function reloadCa() {
	document.getElementById('caimg').src='/includes/caimage.asp?' + Date();
}

function submitFeedback() {
	document.getElementById('feedbackCode').hide(); 
	var frm = document.getElementById("hguy8i0b")
	if (frm) {
		frm.action = "/ni09sw87h.asp";
		frm.submit();
	}
}

function findAdId() {
	if (document.getElementById("searchbyid").style.display=="block")
		document.getElementById("searchbyid").style.display="none";
	else
		document.getElementById("searchbyid").style.display="block";
}

function checkOptions(oObj) {
	var name, boxes, i;
	if (oObj.checked) {
		any = document.getElementById(oObj.name);
		if (any) any.checked = false;
	}
}

function checkAnyOptions(id, qty) {
	var fld, opt, checked = true, i;
	fld = document.getElementById(id);
	if (fld) {
		for (i=1;i<=qty;i++) {
			opt = document.getElementById(id + String(i));
			if (opt) {
				if (opt.type=="checkbox") {
					if (fld.checked) opt.checked = false;
				}
				else {
					if (fld.checked) opt.disabled = true; else opt.disabled = false;
				}
			}
		}
	}
}


function toggleChampSearch() {
	var div = document.getElementById("selectordiv");
	if (div) {
		if (div.style.display=="") {
			div.style.display="none"; }
		else {
			div.style.display=""; }
	}
}

function startIeFix(){
  if(isIE()){
    document.write('<div id="bo_ns_id_' + bo_ns_id + '"><!-- ');
  }
}

function endIeFix(){
  if(isIE()){
    document.write('</div>');
    var theObject = document.getElementById("bo_ns_id_" + bo_ns_id++);
    var theCode = theObject.innerHTML;
    theCode = theCode.substring(4 ,9+theCode.indexOf("</object>"))
    document.write(theCode);
  }
}

function isIE(){
  // only for Win IE 6+
  // But not in Windows 98, Me, NT 4.0, 2000
  var strBrwsr= navigator.userAgent.toLowerCase();
  if(strBrwsr.indexOf("msie") > -1 && strBrwsr.indexOf("mac") < 0){
    if(parseInt(strBrwsr.charAt(strBrwsr.indexOf("msie")+5)) < 6){
      return false;
    }
    if(strBrwsr.indexOf("win98") > -1 ||
       strBrwsr.indexOf("win 9x 4.90") > -1 ||
       strBrwsr.indexOf("winnt4.0") > -1 ||
       strBrwsr.indexOf("windows nt 5.0") > -1)
    {
      return false;
    }
    return true;
  }else{
    return false;
  }
}

function callBack(valid) {
	var tbl = document.getElementById("callbacktable");
	var spn = document.getElementById("callbackmessage");
	if (valid) {
		if (tbl && spn) {
			tbl.style.display="none";
			spn.innerHTML = "<p style='color:maroon;text-align:right;'>Thank you for your interest, we will contact you very soon</p>"
		}
	}
	else {
		if (tbl && spn) {
			tbl.style.display="";
			spn.innerHTML = "<p style='color:red;text-align:right;'>Please complete all fields marked with a red asterix <sup>*</sup></p>"
		}
	}	
}

function addMultiDate(obj1, obj2, obj3) {
	var x = document.getElementsByName(obj1);
	var sel = document.getElementById(obj2);
	var fld = document.getElementById(obj3);
	var dat = x[0];
	if (sel && dat) {
		var oOpt = document.createElement('option');
		oOpt.text = dat.value;
		oOpt.value = dat.value;
		try {
			sel.add(oOpt, null); // standards compliant; doesn't work in IE
		}
		catch(ex) {
			sel.add(oOpt); // IE only
		}
	
		setDateValue(sel,fld);
	}
}

function removeOptionSelected(obj1, obj2)
{
  var elSel = document.getElementById(obj1);
  var fld = document.getElementById(obj2);
  var i;
  for (i = elSel.length - 1; i>=0; i--) {
    if (elSel.options[i].selected) {
      elSel.remove(i);
    }
  }

  setDateValue(elSel,fld);
}

function setDateValue(obj1, obj2) {
	var stext = "";
	for (i=0;i<obj1.length;i++) {
		stext += obj1.options[i].value + "|";
	}
	obj2.value = stext;
}

function setButton() {
	if (addedId!="") {
		swapImg(addedId, '', '/images/inbasket.gif');
	}
}

function thanks() {
	document.getElementById("systhanks").innerHTML = "<b>Thank you for your feedback.</b>";
	document.getElementById("systheform").style.display="none";
	document.getElementById("feedbackerr").style.display="none";
}

function invalid() {
	document.getElementById("systhanks").innerHTML = "";
	document.getElementById("feedbackerr").style.display = "";
	document.getElementById("systheform").style.display = "";
	sysReloadCa();
}

function sysReloadCa() {
	document.getElementById('syscaimg').src='/includes/caimage.asp?' + Date();
}

function isEmail(emailStr) {
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
		alert("Please check your email address (" + emailStr + ") in particular the @'s and .'s");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
		alert("Please check your email address, the name before the '@' contains some invalid characters.");
		return false;
	   }
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
		alert("Please check your email address, the domain name contains some invalid characters.");
		return false;
	   }
	}
	
	if (user.match(userPat)==null) {
		alert("Please check your email address, the name before the '@' appears to be invalid.");
		return false;
	}
	
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
		if (IPArray[i]>255) {
		alert("Please check your email address, the destination IP address is invalid.");
		return false;
	   }
	}
	return true;
	}
	
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
	if (domArr[i].search(atomPat)==-1) {
		alert("Please check your email address, the domain name does not appear to be valid.");
		return false;
	   }
	}
	
	if (checkTLD && domArr[domArr.length-1].length!=2 && 
		domArr[domArr.length-1].search(knownDomsPat)==-1) {
		alert("Please check your email address, it should end in a well-known domain or two letter country.");
		return false;
	}
	
	if (len<2) {
		alert("Please check your email address, it is missing a hostname.");
		return false;
	}
	
	return true;
}

function emailOrWebCheck(str) {
	
	var emailPat=/\b[A-Z0-9._%-]+(.+)@(.+)[A-Z0-9.-]+(.+)\.[A-Z]{2,4}\b/i;
	var webPat=/\bwww(\W*)\.(\W*)[A-Z0-9.-]+(\W?)\.(\W?)[A-Z]{2,4}\b/i;
	var httpPat=/\bhttp(.*)(\W*)\:(\W*)\b/;
	
	var matchArray=str.match(emailPat);
	if (matchArray!=null) {
		alert("Please do not include email addresses in your advert.");
		return false;
	}

	matchArray=str.match(webPat);
	if (matchArray!=null) {
		alert("Please do not include website addresses in your advert.");
		return false;
	}

	matchArray=str.match(httpPat);
	if (matchArray!=null) {
		alert("Please do not include website addresses in your advert.");
		return false;
	}
	
	return true;
}

function checkSelected(iMax) {
	var selected = false;
	var selcount = 0;
	var inpfields = document.getElementsByTagName("input");
	for (var n=0;n<inpfields.length;n++) {
		if (inpfields[n].type=="checkbox") {
			if (inpfields[n].checked) {
				selected = true;
				selcount++;
			}
		}
	}
	if (selcount > iMax)
		document.getElementById("chargeapply").style.display="";
	else
		document.getElementById("chargeapply").style.display="none";
		
	document.getElementById("btnNext").disabled = !selected;
}

function addImg() {
	modalDialogShow("uploadimg.asp",500,380);
}


function confirmLogout() {
	if (confirm("Are you sure you want to log out?")) document.getElementById("frmlogout").submit();
}

function logout() {
	document.getElementById("frmlogout").submit();
}

function updateBasket(iQty) {
		var bskt = document.getElementById("basketatag");
		basketitems = iQty;
		bskt.innerHTML = "(" + basketitems + ")";
}

function popup(img) {
	result = window.open("/viewimage.asp?img=" + img, "prodimg", "height=350,width=350,scrollbars,resizable");
	var cr = String.fromCharCode(13);
	if (result == null) alert("You browser is currently blocking Popups." + cr + cr + "Please change your settings to allow popups on this site." + cr + "Alternatively just click on 'more details' to view the images.");
}

function sImgR() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function loadImg() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=loadImg.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function swapImg() { //v3.0
  var i,j=0,x,a=swapImg.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function writeIn(pre, dom1, ext) {
	var lt = String.fromCharCode(60);
	var gt = String.fromCharCode(62);
	var at = String.fromCharCode(64);
	var qt = String.fromCharCode(34);
	var eq = String.fromCharCode(61);
	
	var act1 = String.fromCharCode(109) + "a";
	var act2 = "i" + String.fromCharCode(108);
	var act3 = "to";
	var act4 = String.fromCharCode(58);
	
	var lnk1 = lt + String.fromCharCode(97) + " " + String.fromCharCode(104) + String.fromCharCode(114) + String.fromCharCode(101) + String.fromCharCode(102) + eq + qt + act1 + act2 + act3 + act4;
	var lnk2 = lt + String.fromCharCode(47) + String.fromCharCode(97) + gt;
	
	var ad = lnk1 + pre + at + dom1 + ext + qt + gt + pre + at + dom1 + ext + lnk2;
	var ol = document.getElementById("kont");
	ol.innerHTML = ad;
}

/*==============================================================================

    Routines written by John Gardner - 2003 - 2005

    See www.braemoor.co.uk/software for information about more freeware
    available.

/*==============================================================================

Routine to write a session cookie

    Parameters:
        cookieName        Cookie name
        cookieValue       Cookie Value
    
    Return value:
        true              Session cookie written successfullly
        false             Failed - persistent cookies are not enabled

   e.g. if (writeSessionCookie("pans","drizzle") then
           alert ("Session cookie written");
        else
           alert ("Sorry - Session cookies not enabled");
*/

function writeSessionCookie (cookieName, cookieValue) {
  if (testSessionCookie()) {
    document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
    return true;
  }
  else return false;
}

/*==============================================================================

Routine to get the current value of a cookie

    Parameters:
        cookieName        Cookie name
    
    Return value:
        false             Failed - no such cookie
        value             Value of the retrieved cookie

   e.g. if (!getCookieValue("pans") then  {
           cookieValue = getCoookieValue ("pans2);
        }
*/

function getCookieValue (cookieName) {
  var exp = new RegExp (escape(cookieName) + "=([^;]+)");
  if (exp.test (document.cookie + ";")) {
    exp.exec (document.cookie + ";");
    return unescape(RegExp.$1);
  }
  else return false;
}

/*==============================================================================

Routine to see if session cookies are enabled

    Parameters:
        None
    
    Return value:
        true              Session cookies are enabled
        false             Session cookies are not enabled

   e.g. if (testSessionCookie())
           alert ("Session coookies are enabled");
        else
           alert ("Session coookies are not enabled");
*/

function testSessionCookie () {
  document.cookie ="testSessionCookie=Enabled";
  if (getCookieValue ("testSessionCookie")=="Enabled")
    return true 
  else
    return false;
}

/*==============================================================================

Routine to see of persistent cookies are allowed:

    Parameters:
        None
    
    Return value:
        true              Session cookies are enabled
        false             Session cookies are not enabled

   e.g. if (testPersistentCookie()) then
           alert ("Persistent coookies are enabled");
        else
           alert ("Persistent coookies are not enabled");
*/

function testPersistentCookie () {
  writePersistentCookie ("testPersistentCookie", "Enabled", "minutes", 1);
  if (getCookieValue ("testPersistentCookie")=="Enabled")
    return true  
  else 
    return false;
}

/*==============================================================================

Routine to write a persistent cookie

    Parameters:
        CookieName        Cookie name
        CookieValue       Cookie Value
        periodType        "years","months","days","hours", "minutes"
        offset            Number of units specified in periodType
    
    Return value:
        true              Persistent cookie written successfullly
        false             Failed - persistent cookies are not enabled
    
    e.g. writePersistentCookie ("Session", id, "years", 1);
*/       

function writePersistentCookie (CookieName, CookieValue, periodType, offset) {

  var expireDate = new Date ();
  offset = offset / 1;
  
  var myPeriodType = periodType;
  switch (myPeriodType.toLowerCase()) {
    case "years":
      expireDate.setYear(expireDate.getFullYear()+offset);
      break;
    case "months":
      expireDate.setMonth(expireDate.getMonth()+offset);
      break;
    case "days":
      expireDate.setDate(expireDate.getDate()+offset);
      break;
    case "hours":
      expireDate.setHours(expireDate.getHours()+offset);
      break;
    case "minutes":
      expireDate.setMinutes(expireDate.getMinutes()+offset);
      break;
    default:
      alert ("Invalid periodType parameter for writePersistentCookie()");
      break;
  } 
  
  document.cookie = escape(CookieName ) + "=" + escape(CookieValue) + "; expires=" + expireDate.toGMTString() + "; path=/";
}  

/*==============================================================================

Routine to delete a persistent cookie

    Parameters:
        CookieName        Cookie name
    
    Return value:
        true              Persistent cookie marked for deletion
    
    e.g. deleteCookie ("Session");
*/    

function deleteCookie (cookieName) {

  if (getCookieValue (cookieName)) writePersistentCookie (cookieName,"Pending delete","years", -1);  
  return true;     
}

function IsNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }

function toggleAdvSearch() {
	var btn = document.getElementById("advsearchbtn");
	if (document.getElementById("advsearch").style.display=="") {
		document.getElementById("advsearch").style.display="none";
		btn.value="Search within THIS Category";
	}
	else {
		document.getElementById("advsearch").style.display="";
		btn.value="Hide Search Options";
	}
}

function validateAdvert() {
	var msg = document.getElementById("addesc");
	var title = document.getElementById("adtitle");
	var upload = document.getElementById("uploading");
	
	if (title.value=="") {
		if (upload) upload.style.display="none";
		alert("Please enter an advert title");
		msg.focus();
		return false;
	}
	
	if (msg.value=="") {
		if (upload) upload.style.display="none";
		alert("Please enter some advert details");
		msg.focus();
		return false;
	}
	else {
		var desc = new String(msg.value);
		var newdesc = "";
		for (i=0;i<desc.length;i++) {
			iChar = desc.charCodeAt(i);
			sChar = desc.charAt(i);
			if ((iChar<32 || (iChar>125 && iChar < 128) || iChar > 254) && iChar!=10 && iChar!=13) {
				newdesc += "";
			}
			else {
				newdesc += sChar;
			}
		}
		msg.value=newdesc;
	}
	
	if (!checkCaps(msg)) {
		if (upload) upload.style.display="none";
		msg.focus();
		return false;
	}
	
	if (!emailOrWebCheck(title.value)) {
		if (upload) upload.style.display="none";
		return false;
	}
	if (!emailOrWebCheck(msg.value)) {
		if (upload) upload.style.display="none";
		return false;
	}
	
	i=1;
	var img, lUpload = false;
	while (true) {
		img = document.getElementById("image" + String(i++));
		if (!img) break;
		if (img.value!="") lUpload = true;
	}
	if (lUpload) document.getElementById("uploading").style.display="";

	return true;
}

function checkCaps(oObj) {
	var val = new String(oObj.value), sChar, iasc;
	var sentence = new String(""), upperNext = true;
	var i, count=0, len=val.length, perc=0.5;
	
	for (i=0;i<len;i++) {
		sChar = val.charAt(i);
		iasc = val.charCodeAt(i);
		if (sChar==sChar.toUpperCase() && !(iasc >= 48 && iasc <= 57)) count++;
		if (sChar=="!" || sChar=="?" || sChar=="." || iasc==10 || iasc==13) upperNext=true;
		if ((iasc >= 65 && iasc <= 90) || (iasc >= 97 && iasc <= 122) || (iasc >= 48 && iasc <= 57)) {
			if (upperNext) {
				sChar= sChar.toUpperCase();
				upperNext = false;
			}
			else {
				sChar = sChar.toLowerCase();
			}
		}
		sentence = sentence + sChar;
	}
	
	if ((count/len) > perc) {
		// number of caps exceeds limit
		oObj.value = sentence;
		alert("Unfortunately you can't use excessive CAPITAL LETTERS in your advert" + String.fromCharCode(10) + "We have converted this for you so please check this before proceeding.");
		oObj.focus();
		return false;
	}
	else {
		return true;
	}
}

function loadDateRange(oMth, oYrs) {
	var newEle, dDate = new Date();
	var iYear = dDate.getFullYear();
	var contactform = document.getElementById("contactform");

	for (i=0;i<12;i++) {
		newEle = document.createElement("OPTION"); newEle.text = aMonths[i]; newEle.value = i+1;
		oMth.options.add(newEle);
	}
	for (i=iYear;i<=iYear+1;i++) {
		newEle = document.createElement("OPTION"); newEle.text = i; newEle.value = i;
		oYrs.options.add(newEle);
	 }
}

function setDays(oMth, oDys, oYrs) {
	var iDays = aDays[oMth.value-1], newEle, iVal = 0;
	if (oMth.value == 2) {
		var iDiv = oYrs.value / 4; 
		if ((iDiv - Math.floor(iDiv)) == 0) iDays = 29;
	}
	if (oDys.length == 0) {
			for (i=0;i<iDays;i++) {
				newEle = document.createElement("OPTION"); newEle.text = i+1; newEle.value = i+1;
				oDys.options.add(newEle);
			}
		}
	else {
		iVal = oDys.value;
		if (oDys.options.length+1 > iDays) {
			for (i=oDys.options.length;i>=iDays;i--) oDys.options.remove(i);}
		else {
			if (oDys.options.length+1 <= iDays) {
				for (i=oDys.options.length;i<iDays;i++) {
					newEle = document.createElement("OPTION"); newEle.text = i+1; newEle.value = i+1;
					oDys.options.add(newEle);
				}
			}
			if (iVal > 0) {
				oDys.selectedIndex = (iVal>iDays)?iDays-1:iVal-1;
			}
		}
	}
}

function addToSelectList(sFrom, sTo, sField, sList) {
	var newval, fldval, comma, i, exists, newtxt, iFromIndex;
	exists = false;
	
	var oFrom, oTo, oField;
	
	oFrom  = document.getElementById(sFrom);
	oTo    = document.getElementById(sTo);
	oField = document.getElementById(sField);
	oList  =  document.getElementById(sList);
	
	if (oFrom && oTo && oFrom.selectedIndex >= 0) {
		newtxt = oFrom.options[oFrom.selectedIndex].text;
		newval = oFrom.options[oFrom.selectedIndex].value;
		
		if (newval != "") {
			var oOpt = document.createElement('option');
			oOpt.text = newtxt;
			oOpt.value = newval;
			
			var sel = null;
			for (i=0;i<oTo.length;i++) {
				if (oTo.options[i].text > newtxt) {
					sel=oTo.options[i];
					break;
				}
			}
			
			try {
				oTo.add(oOpt, sel); // standards compliant; doesn't work in IE
			}
			catch(ex) {
				// IE only
				if (sel==null) 
					oTo.add(oOpt);
				else
					oTo.add(oOpt, i);
			}
			
			iFromIndex = oFrom.selectedIndex;
			oFrom.remove(iFromIndex);
			if (iFromIndex < oFrom.length)
				oFrom.selectedIndex = iFromIndex;
			else
				oFrom.selectedIndex = 0;
				
			if (oList.length < 5)
				oList.size = (oList.length<2) ? 2 : oList.length;
			else
				oList.size = 5;
			
		}
		
		if (oField && oList) {
			comma = "", fldval = "";
			for (i=0;i<oList.length;i++) {
				fldval += (comma + oList.options[i].value);
				comma = ",";
			}
			oField.value = fldval;
		}
	}
}


// Custom Functions 

function showDiv(sDiv) {

	var div = document.getElementById(sDiv);
	var downarrow = document.getElementById("downarrow_" + sDiv);
	var uparrow = document.getElementById("uparrow_" + sDiv);
	
	if(div) {
		if(div.style.display == "none") {
			div.style.display = "block";
			if(downarrow && uparrow) {
				downarrow.style.display = "none";
				uparrow.style.display = "block";
			}
		}
		else {
			div.style.display = "none";	
			if(downarrow && uparrow) {
				downarrow.style.display = "block";
				uparrow.style.display = "none";
			}
		}
	}
	
}

function hideDiv(sDiv) {
	var div = document.getElementById(sDiv);
	var downarrow = document.getElementById("downarrow_" + sDiv);
	var uparrow = document.getElementById("uparrow_" + sDiv);
	
	if(downarrow && uparrow) {
		downarrow.style.display = "block";
		uparrow.style.display = "none";
	}
	if(div) {
		div.style.display = "none";	 
		
	}
	
}

function Right(str, n)
        /***
                IN: str - the string we are RIGHTing
                    n - the number of characters we want to return

                RETVAL: n characters from the right side of the string
        ***/
        {
                if (n <= 0)     // Invalid bound, return blank string
                   return "";
                else if (n > String(str).length)   // Invalid bound, return
                   return str;                     // entire string
                else { // Valid bound, return appropriate substring
                   var iLen = String(str).length;
                   return String(str).substring(iLen, iLen - n);
                }
        }
