// --------------------------------------------------------------
// EquineAffairs.js
//
// Standard Javascript functions for EquineAffairs website (it assumes
// that the XbGetElementById.js is installed).
//
// --------------------------------------------------------------


// --------------------------------------------------------------
// Name: jsUpdateMemberDisciplines
//
// Description: This method supports the update of the member 
//              disciplines when the Membership type is updated.
//
// --------------------------------------------------------------
function jsUpdateMemberDisciplines(objId)
{
	// Mark the object as set
	var obj = xbGetElementById(objId);
	if (obj)
		obj.value='1';	
}

// --------------------------------------------------------------
// Name: jsShow
//
// Description: This method either hides / shows the details required
//              when claiming a voucher.
//
// --------------------------------------------------------------

function jsShow()
{
	var DiscountObj = xbGetElementById("Discounts");
	var v1 = xbGetElementById("trVoucher1");
	var v2 = xbGetElementById("trVoucher2");
	var v3 = xbGetElementById("trVoucher3");
	
	if (DiscountObj[DiscountObj.selectedIndex].text == "")
	{
	    v1.style.visibility = 'hidden';
	    v2.style.visibility = 'hidden';
	    v3.style.visibility = 'hidden';
	}
	else
	{
	    v1.style.visibility = 'visible';
	    v2.style.visibility = 'visible';
	    v3.style.visibility = 'visible';	
	}
}

// --------------------------------------------------------------
// Name: jsCalculateTotal
//
// Description: This method calculates the total cost of the membership
//              and details what the costs involve.
//
// --------------------------------------------------------------
function jsCalculateTotal()
{
	var costObj = xbGetElementById("Amount");
	var typeObj = xbGetElementById("MembershipTypeDescription");
	var divObj = xbGetElementById("dvTotalCost");
	var DiscountObj = xbGetElementById("Discounts");
	var AssociationObj = xbGetElementById("Associations");
	var MemberPackObj = xbGetElementById("cp_hard_copy_membership_pack");
	var mcost = 0;
	var discount = 0;
	var disp_discount = 0;
	var voucher = 0;
	var discountMsg = "";
	var regmembers = "";
	var pandp = 0;
	var pandptext = "";
	var totalcost = 0;
	var i;
	var j;
	var a;
	var jj;
	var freeVoucher = false;
	var tMsg = "";
	
	// Defaults
	mcost = costObj.value;
	
	// Go through the list of registered associations
	jj = 0;
	for (j = 0; j < AssociationObj.options.length; j++)
	{
	    if (AssociationObj.options[j].selected == true)
	    {
	        for (i = 0; i < jsAssociate.Count(); i++)
	        {
		    a = jsAssociate.Next(i);
		    if (a.AssociateID == AssociationObj.options[j].value)
		    {
		        if (a.AssociateDiscount > discount)
		        {
		            discount = a.AssociateDiscount;
		        }
		        discountMsg+= a.AssociateName + ", ";
		        jj++;
		        if (jj == 3)
		        {
			    discountMsg+= "<br>";
			    jj = 0;
			}
		    }
	        }
	    }
	}

	// Check if they have a voucher
	if (DiscountObj[DiscountObj.selectedIndex].value >= 0)
	{
	    // Has a voucher
	    if (DiscountObj[DiscountObj.selectedIndex].value == 0)
	    {
			freeVoucher = true;
			discount = 0;
			disp_discount = mcost;
			discountMsg = "Free Membership using your FREE membership voucher";
	    }
	    else
	    {
			disp_discount+= Number(DiscountObj[DiscountObj.selectedIndex].value);
			discountMsg+= DiscountObj[DiscountObj.selectedIndex].text;
	    }
	}
	
	xbGetElementById("_membershipPandPRequired").value = 0;
	if (MemberPackObj.checked) xbGetElementById("_membershipPandPRequired").value = 1;
	
	// Check Post and Packing
	if (MemberPackObj.checked && !freeVoucher)
	{
	    pandp = 1.50;
	    var f1 = new ToFmt(pandp);
	    pandp=f1.fmtF(13,2);
	    pandptext = "Postage &amp; Packing for delivery of your Membership Pack";
	}

	// Cost
	if (discount > 0)
	{
	    // If the discount exists then calculate it as a percentage.
	    // Then check the value against the selected voucher if any, and the highest is used
	    discount = mcost * discount / 100;
	    disp_discount = ((discount > disp_discount) ? discount : disp_discount);
	}
	
	disp_discount = -1 * disp_discount;
	var f2 = new ToFmt(disp_discount);
	disp_discount=f2.fmtF(13,2)
	
	var f3 = new ToFmt(mcost);
	mcost=f3.fmtF(13,2)
	
	totalcost = Number(mcost) + Number(disp_discount) + Number(pandp);
	var f4 = new ToFmt(totalcost);
	totalcost=f4.fmtF(13,2)
    	
    	// Display Totals
    	xbGetElementById("dvShowMCost").innerHTML = mcost;
    	xbGetElementById("dvShowMCostText").innerHTML = typeObj.value;
    	xbGetElementById("dvShowDiscount").innerHTML = disp_discount;
    	xbGetElementById("dvShowDiscountText").innerHTML = discountMsg;
    	xbGetElementById("dvShowPandP").innerHTML = pandp;
	xbGetElementById("dvShowTotalCost").innerHTML = totalcost;
	xbGetElementById("dvShowPandPtxt").innerHTML = pandptext;

	// Build userId
	if (xbGetElementById("cp_first_name") && xbGetElementById("cp_last_name"))
	{
	    xbGetElementById("_membershipid").value = xbGetElementById("cp_first_name").value.substring(0,1) + xbGetElementById("cp_last_name").value;
	}
	
	// Update hidden objects as well
	xbGetElementById("_membershipCost").value = mcost;
	xbGetElementById("_membershipDiscount").value = discount;
	xbGetElementById("_membershipDiscountText").value = discountMsg;
	xbGetElementById("_membershipPandP").value = pandp;
	xbGetElementById("_membershipTotal").value = totalcost;
}

// --------------------------------------------------------------
// Name: horseDetails
//
// Description: Provide the capability to maintain horse details
// at runtime and populat the horse details when posting results
//
// --------------------------------------------------------------
function horseDetails()
{
    var divId = xbGetElementById("dvShowHorses"); 
    if (divId)
    {
	var iStyle = "STYLE='position:absolute;top:700px;left:100px;width:700px;height:500px;'";
	var iPage = "<IFRAME NAME='frmHorses' ID='frmHorses' " + iStyle + " SRC='MaintainHorseDetails.asp?init=true'></IFRAME>";
    
	divId.innerHTML = iPage;
	divId.style.visibility = 'visible';
	//hideShowCovered(divId);
    }
}

// --------------------------------------------------------------
// Name: cancelHorses
//
// Description: Hide the Horse Details Page
//
// --------------------------------------------------------------

function cancelHorses()
{
    var divId = xbGetElementById("dvShowHorses");

    hideShowCovered(divId);
    divId.innerHTML = "";
    divId.style.visibility = 'hidden';
}

// --------------------------------------------------------------
// Name: ShowSecretaryDetails
//
// Description: Show Secretary Details
//
// --------------------------------------------------------------  
function ShowSecretaryDetails(divText, Address, fullName, Telephone, Mobile, Fax, Email, Website, Notes)
{
	var divId = xbGetElementById(divText);
	var iHTML = "";
	var iText = "";
	
	if (divId.style.display == "block")
	{
		// Hide it
		divId.style.visibility = 'hidden';
		divId.style.display = 'none';	
	}
	else
	{
		// Show It
		
		iText = fullName + ", " + Address
		if (Telephone != "") iText += "<br/>Tel: " + Telephone;
		if (Fax != "") iText += ", Fax: " + Fax;
		if (Mobile != "") iText += ", Mobile: " + Mobile;
		if (Email != "") iText += ", Email: <a href='mailto:" + Email + "'>" + Email + "</a>";
		if (Website != "") iText += ", WebSite: <a href='http://" + Website + "' target='_blank'>" + Website + "</a>";
		if (Notes != "") iText += "<br/>Notes: " + Notes;


		iHTML += "<tr><td>&nbsp;</td><td class='datag' wrap>" + iText + "</td></tr>"

		divId.innerHTML = iHTML;
		divId.style.display = 'block';
		divId.style.visibility = 'visible';
    }
}
	
// --------------------------------------------------------------
// Name: ShowLocationDetails
//
// Description: Show Location Details
//
// --------------------------------------------------------------  
function ShowLocationDetails(divText, locationName, Address, Map, Contact, Telephone, Mobile, Fax, Email, Website, Directions)
{
	var divId = xbGetElementById(divText);
	var iHTML = "";
	var iText = "";
	
	if (divId.style.display == "block")
	{
		// Hide it
		divId.style.visibility = 'hidden';
		divId.style.display = 'none';	
	}
	else
	{
		// Show It
		iText = locationName + ", " + Address
		if (Map != "") iText += "<br/><b>Map Link:</b> <a target='_blank' href='http://uk.multimap.com/p/browse.cgi?pc=" + Map + "'>" + Map + "</a>";
		if (Contact != "") iText += "<br/><b>Contact:</b> " + Contact;
		if (Telephone != "") iText += ", <b>Tel:</b> " + Telephone;
		if (Fax != "") iText += ", <b>Fax:</b> " + Fax;
		if (Mobile != "") iText += ", <b>Mobile:</b> " + Mobile;
		if (Email != "") iText += ", <b>Email:</b> <a href='mailto:" + Email + "'>" + Email + "</a>";
		if (Website != "") iText += ", <b>WebSite:</b> <a target='_blank' href='http://" + Website + "'>" + Website + "</a>";
		if (Directions != "") iText += "<br/><b>Directions:</b> " + Directions;


		iHTML += "<tr><td>&nbsp;</td><td wrap>" + iText + "</td></tr>"

		divId.innerHTML = iHTML;
		divId.style.display = 'block';
		divId.style.visibility = 'visible';
    }
}
 
// --------------------------------------------------------------
// Name: jsAssociate
//
// Description: Associate Object.
//
// --------------------------------------------------------------
jsAssociate = function()
{
	this.AssociateID = null;
	this.AssociateCode = null;
	this.AssociateName = null;
	this.AssociateDiscount = null;
	this.selected = false;
  
    // one-time initialisations
	if (typeof jsAssociate._list == "undefined") {
		jsAssociate._list = new Array();
	}
};

jsAssociate.Add = function(AssociateID, AssociateCode, AssociateName, AssociateDiscount)
{
    var p = new Object();
    
    p.AssociateID = AssociateID;
    p.AssociateCode = AssociateCode;
    p.AssociateName = AssociateName;
    p.AssociateDiscount = AssociateDiscount;
    p.selected = false;
   
    this._list[this._list.length] = p;
};

jsAssociate.Select = function(AssociateID)
{
    for (pId = 0; pId < this._list.length; pId++)
    {
        if (AssociateID == this._list[pId].AssociateID)
        {
		this._list[pId].selected = (this._list[pId].selected == false ? true : false);
		break;
	}
    }    
};

jsAssociate.Get = function(id)
{
	for (pId = 0; pId < this._list.length; pId++)
	{
		if (id == this._list[pId].AssociateID)
		{
			return (this._list[pId]);
		}
	}
};

jsAssociate.Next = function(pId)
{
    return this._list[pId];
};

jsAssociate.Count = function()
{
    return this._list.length;
};



// ----------------------------------------------------------------
// Regions()
//
// Constructor for building Regions
// ----------------------------------------------------------------
Regions = function()
{
	this.RegionId = null;
	this.Name = null;
  
    // one-time initialisations
	if (typeof Regions._list == "undefined") {
		Regions._list = new Array();
	}

    // one-time initialisations
	if (typeof Regions._counties == "undefined") {
		Regions._counties = new Array();
	}
		
};

// ----------------------------------------------------------------
// Add()
//
// Add a new region to the Regions Object 
// ----------------------------------------------------------------
Regions.Add = function(RegionId, Name)
{
    var p = new Object();
    
    p.RegionId = RegionId;
    p.Name = Name;

    this._list[this._list.length] = p;
};

// ----------------------------------------------------------------
// AddCounty()
//
// Add a new region to the Regions Object 
// ----------------------------------------------------------------
Regions.AddCounty = function(RegionId, County) {
    for (pId = 0; pId < this._list.length; pId++)
    {
        if (RegionId == this._list[pId].RegionId)
        { 
        	p = this._list[pId];
			if (typeof p._counties == "undefined")
			{
			    alert('init');
				p._counties = new Array();
			}
			
    		p._counties[p._counties] = County;
    		alert(p._counties[0].Name);
    	}
    }
};

// ----------------------------------------------------------------
// Get()
//
// Retrieve an existing counties for a given region 
// Returning an array of Counties 
// ----------------------------------------------------------------
Regions.Get = function(id)
{
    for (pId = 0; pId < this._list.length; pId++)
    {
        if (id == this._list[pId].RegionId)
        {       
        	return (this._list[pId]);
		}
    }
    return (a);
};

// ----------------------------------------------------------------
// Next()
//
// Get Next Property
// ----------------------------------------------------------------
Regions.Next = function(pId)
{
    return this._list[pId];
};

// ----------------------------------------------------------------
// Count()
//
// Return the number of Regions stored
// ----------------------------------------------------------------
Regions.Count = function()
{
    return this._list.length;
};

// ----------------------------------------------------------------
// Counties()
//
// Constructor for building Counties
// ----------------------------------------------------------------
Counties = function()
{
	this.CountyId = null;
	this.Name = null;
	this.RegionId = null;
  
    // one-time initialisations
	if (typeof Counties._list == "undefined") {
		Counties._list = new Array();
	}
	
};

// ----------------------------------------------------------------
// Add()
//
// Add a new region to the Counties Object 
// ----------------------------------------------------------------
Counties.Add = function(CountyId, Name, RegionId) {
    var p = new Object();
    
    p.CountyId = CountyId;
    p.Name = Name;
	p.RegionId = RegionId;
	
    this._list[this._list.length] = p;
    
    Regions.AddCounty(RegionId, p);
    
};

// ----------------------------------------------------------------
// Get()
//
// Retrieve an existing counties for a given region 
// Returning an array of Counties 
// ----------------------------------------------------------------
Counties.Get = function(id)
{
    for (pId = 0; pId < this._list.length; pId++)
    {
        if (id == this._list[pId].RegionId)
        {       
        	return (this._list[pId]);
		}
    }
    return (a);
};

// ----------------------------------------------------------------
// Next()
//
// Get Next Property
// ----------------------------------------------------------------
Counties.Next = function(pId)
{
    return this._list[pId];
};

// ----------------------------------------------------------------
// Count()
//
// Return the number of Counties stored
// ----------------------------------------------------------------
Counties.Count = function()
{
    return this._list.length;
};

// Supporting Methods
function setRegion(RegionId)
{
	var region = Regions.Get(RegionId);
	if (region && region.RegionId == RegionId)
	{
	   alert(region.Name);
	   alert(region._counties[0].Name);
    }
}

// --------------------------------------------------------------
// Name: jsHorses
//
// Description: Horses Object.
//
// --------------------------------------------------------------
jsHorses = function()
{
	this.MemberHorseID = null;
	this.HorseName = null;
	this.HorseHeight = null;
	this.Breed = null;
	this.Address_1 = null;
	this.Address_2 = null;
	this.Address_3 = null;
	this.Address_4 = null;
	this.County_ID = null;
	this.PostCode = null;
	this.valid = true;
  
	// one-time initialisations
	if (typeof jsHorses._list == "undefined") {
		jsHorses._list = new Array();
	}
};

jsHorses.Add = function(MemberHorseID, HorseName, HorseHeight, Breed, Address_1, Address_2, Address_3, Address_4, County_ID, PostCode)
{
    var p = new Object();
    
    p.MemberHorseID = MemberHorseID;
    p.HorseName = HorseName;
    p.HorseHeight = HorseHeight;
    p.Breed = Breed;
    p.Address_1 = Address_1;
    p.Address_2 = Address_2;
    p.Address_3 = Address_3;
    p.Address_4 = Address_4;
    p.County_ID = County_ID;
    p.PostCode = PostCode;
    p.valid = true;
   
    this._list[this._list.length] = p;
};

jsHorses.Delete = function(id)
{
	for (pId = 0; pId < this._list.length; pId++)
	{
		if (id == this._list[pId].MemberHorseID)
		{
			this._list[pId].valid = false;
		}
	}
};

jsHorses.Next = function(pId)
{
    return this._list[pId];
};

jsHorses.Count = function()
{
    return this._list.length;
};


// ----------------------------------------------------------------
// Initialisers
// ----------------------------------------------------------------
var iRegions = new Regions();
var iCounties = new Counties();
var iAssociate = new jsAssociate();
var iHorses = new jsHorses();

// Number Formatter
function ToFmt(x){
 this.x=x;
 this.fmt00 = fmt00;
 this.fmtF=fmtF;
 this.spacer=" ";
 this.setSpacer=setSpacer;
}

function fmt00(){
 // fmt00: Tags leading zero onto numbers 0 - 9.
 // Particularly useful for displaying results from Date methods.
 //
 if (parseInt(this.x) < 0) var neg = true;
 if (Math.abs(parseInt(this.x)) < 10){
  this.x = "0"+ Math.abs(this.x);
 }
 if (neg) this.x = "-"+this.x;
 return this.x;
}
function filljunk(lenf){
 // Fills field of length lenf with asterisks
 var str="";
 for (var i=0; i < lenf; i++){
  str +="*";
 }
 return str;
}

function setSpacer(spc){
 var spc;
 this.spacer=spc;
 return this.spacer;
}

function fmtF(w,d){

 // fmtF: formats in a style similar to Fortran's Fw.d, where w is the
 // width of the field and d is the number of figures after the decimal
 // point. 
 // The result is aligned to the right of the field.  The default
 // padding character is a space " ". This can be modified using the 
 // setSpacer(string) method of ToFmt. 
 // If the result will not fit in the field , the field will be returned
 // containing w asterisks.
 var width=w;
 var dpls=d;
 var lt1=false;
 var len=this.x.toString().length;
 var junk;
 var res="";
// First check for valid format request
 if ( width < (dpls+2)){
  window.alert("Illegal format specified : w = " + d +
               " w = " + d +
                "\nUsage: [ToFmt].fmtF(w,d)" +
                "\nWidth (w) of field must be greater or equal to the number " +
                "\nof digits to the right of the decimal point (d) + 2");
  junk = filljunk(width);
  return junk;
 }
// Work with absolute value
 var absx=Math.abs(this.x);
// Nasty fix to deal with numbers < 1 and problems with leading zeros!
 if ((absx < 1) && (absx > 0)){
  lt1 = true;
  absx+=10;
 }
// Get postion of decimal point
 var pt_pos = absx.toString().indexOf(".");
 if ( pt_pos == -1){
  res+= absx;
  res+= ".";
  for (var i = 0; i < dpls; i++){
   res += 0;
  }  
 }
 else{
  res = Math.round(absx * Math.pow(10,dpls));
  res=res.toString();
  if (res.length == 
      Math.round(Math.floor(absx * Math.pow(10,dpls))).toString().length){ 
   res = res.substring(0,pt_pos) + "." + 
         res.substring(pt_pos,res.length);
  }
  else{
   pt_pos++;
   res = res.substring(0,pt_pos) + "." + 
          res.substring(pt_pos,res.length);
  } 
// Remove leading 1 from  numbers < 1 (Nasty fix!)
  if (lt1) {
   res=res.substring(1,res.length);
  }
 }
 // Final formatting statements
 // Reinsert - sign for negative numbers
 if (this.x < 0)res = "-"+res;
 // Check whether the result fits in the width of the field specified
 if (res.length > width){
  res=filljunk(width);
 }
 // If necessary, pad from the left with the spacer string
 else if (res.length < width){
  var res_bl="";
  for (var i = 0; i < (width - res.length); i++){
   res_bl += this.spacer ;
  } 
  res = res_bl + res;
 }
 return res;
}

// ----------------------------------------------------------------
// hideShowCovered()
//
// The Property window may appear overlapping certain types of tags
// which need to be marked hidden when the property window is shown
// and marked visible when the property window is removed.
// ----------------------------------------------------------------
function hideShowCovered(el) {
		
	function getVisib(obj){
		return obj.style.visibility;
	};

	var tags = new Array("applet", "iframe", "select");

	var p = getAbsolutePos(el);
	var EX1 = p.x;
	var EX2 = el.offsetWidth + EX1;
	var EY1 = p.y;
	var EY2 = el.offsetHeight + EY1;

	for (var k = tags.length; k > 0; ) {
		var ar = document.getElementsByTagName(tags[--k]);
		var cc = null;

		for (var i = ar.length; i > 0;) {
			cc = ar[--i];

			p = getAbsolutePos(cc);
			var CX1 = p.x;
			var CX2 = cc.offsetWidth + CX1;
			var CY1 = p.y;
			var CY2 = cc.offsetHeight + CY1;

			if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
				cc.style.visibility = "visible";
			} else {
				cc.style.visibility = (cc.style.visibility == "hidden" ? "visible" : "hidden");
			}
		}
	}
};

// ----------------------------------------------------------------
// getAbsolutePos()
//
// Get the absolute position of an element
// ----------------------------------------------------------------
function getAbsolutePos(el) {
	var SL = 0, ST = 0;
	var is_div = /^div$/i.test(el.tagName);
	if (is_div && el.scrollLeft)
		SL = el.scrollLeft;
	if (is_div && el.scrollTop)
		ST = el.scrollTop;
	var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
	if (el.offsetParent) {
		var tmp = getAbsolutePos(el.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
};

var ie5 = document.getElementById != null;

function doOver() {
	var el = window.event.srcElement;
	bgc = el.style.backgroundColor;

	if (bgc != "") {
		el.style.borderTopColor = "white";
		el.style.borderLeftColor = "white";
		el.style.borderRightColor = "black";
		el.style.borderBottomColor = "black";
	
		colorBox.style.backgroundColor = bgc;
		colorName.innerHTML = bgc;
	}
}
function doClick() {
	bgc = window.event.srcElement.style.backgroundColor;
	window.event.srcElement.style.borderColor = bgc;
	if (bgc != "") {
		window.external.raiseEvent("colorchange", bgc);
	}
}
function doOut() {
	var el = window.event.fromElement;
	bgc = el.style.backgroundColor;

	if (bgc != "") {
		el.style.borderColor = bgc;
	}
}

var colors = new Array("aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black",
"blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral",
"cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen",
"darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen",
"darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray",
"dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod",
"gray","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender",
"lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow",
"lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray",
"lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine",
"mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen",
"mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy",
"oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise",
"palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","red","rosybrown",
"royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue",
"slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise",
"violet","wheat","white","whitesmoke","yellow","yellowgreen");

var sysColors = new Array("activeborder","activecaption","appworkspace","background","buttonface",
"buttonhighlight","buttonshadow","buttontext","captiontext","graytext","highlight","highlighttext",
"inactiveborder","inactivecaption","inactivecaptiontext","infobackground","infotext","menu","menutext",
"scrollbar","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","window",
"windowframe","windowtext");

function writeRow(ar) {
	var cells = 15;
	var str = "";
	
	for (var i=0; i<ar.length; ) {
		str += "<tr>"
		for (var j=0; j<=cells && i<ar.length; j++) {
			str += "<td style='background-color: " + ar[i] + "; border: 1px outset " + ar[i] + ";'>";
			str += "&nbsp;</td>\n";
			i++;
		}
		str += "</tr>\n";
	}
	return str;
}
	
// ----------------------------------------------------------------
// County()
//
// Constructor for building County
// ----------------------------------------------------------------
County = function()
{
	this.RegionID = null;
	this.CountyID = null;
	this.County = null;
  	
    // one-time initialisations
	if (typeof County._list == "undefined") {
		County._list = new Array();
	}
};

// ----------------------------------------------------------------
// Add()
//
// Add a new property to the County Object
// ----------------------------------------------------------------
County.Add = function(RegionId, CountyId, County)
{
    var p = new Object();
    
    p.RegionID = RegionId;
    p.CountyID = CountyId;
    p.County = County;
   
    this._list[this._list.length] = p;
};


// ----------------------------------------------------------------
// Get()
//
// Retrieve an existing county by using the Region Identifier
// Returning an array of counties
// ----------------------------------------------------------------
County.Get = function(id)
{
	var a = new Array();
	var pId;
	
    for (pId = 0; pId < this._list.length; pId++)
    {
        if (id == this._list[pId].RegionID)
        {
			a[a.length] = this._list[pId];
		}
    }
    return (a);
};

// ----------------------------------------------------------------
// Next()
//
// Get Next County
// ----------------------------------------------------------------
County.Next = function(pId)
{
    return this._list[pId];
};

// ----------------------------------------------------------------
// Convert()
//
// Convert the counties to a select list based on the region Identifier
// ----------------------------------------------------------------
County.Convert = function(id)
{
	var iId;
    var select = "<select id='CountyId' name='CountyId' SIZE=6 Multiple>";
    for (iId = 0; iId < this._list.length; iId++)
    {
        if (id == this._list[iId].RegionID)
        {
			r = this._list[iId];
			select += "<option value=" + r.CountyID + ">" + r.County + "</option>";
		}
    }
    select += "</select>";
    return (select);
};

// ----------------------------------------------------------------
// Count()
//
// Return the number of counties stored
// ----------------------------------------------------------------
County.Count = function()
{
    return this._list.length;
};

// ----------------------------------------------------------------
// Initialisers
// ----------------------------------------------------------------
var oCounty = new County();

// ----------------------------------------------------------------
// ChangeRegion()
//
// Sets the list of counties based on the selected region
// ----------------------------------------------------------------
function ChangeRegion()
{
	var region = xbGetElementById("RegionId");
	if (region != null && 
		region.options[region.selectedIndex].value > 0)
	{
		var id = region.options[region.selectedIndex].value;
		SetRegion(id);
	}
}	

// ----------------------------------------------------------------
// SetRegion()
//
// Retrieves the list of counties for the selected region into
// a multiselect list allow the guest to select one or more counties
// ----------------------------------------------------------------
function SetRegion(id)
{
	if (id != null)
	{
		// Change Region Dropdown List
		var region = xbGetElementById("RegionId");
		if (region != null)
		{
			for (i = 0; i < region.options.length; i++)
			{
				if (region.options[i].value == id)
				{
					// Mark the region as selected
					region.options[i].selected = true;
					region.options[i].selectedIndex = i;
					i = region.options.length;
				}
			}
		}
	
		/*
		// Change County Options available
		var obj = xbGetElementById("CountiesPlaceholder");
		if (obj != null)
		{
			obj.innerHTML = County.Convert(id);
		}
		*/
	}
}

// ----------------------------------------------------------------
// UpdateDate()
//
// Update the from date to reduce it by 4 months.
// ----------------------------------------------------------------
function UpdateDate(fromDate, amount)
{
	var newMonth = fromDate.getMonth() - amount;
	var years = 0;
	if (newMonth <= 0) {
		while (newMonth <= 0)
		{
			newMonth += 12;
			years -= 1;
		}
	} else if (newMonth > 11) {
		while (newMonth > 11)
		{
			newMonth -= 12;
			years += 1;
		}
	}

	fromDate.setMonth(newMonth);
	fromDate.setFullYear(fromDate.getFullYear() + years);
	return fromDate;
}

function GetMonth(fromDate)
{
	return (fromDate.getMonth() == 0 ? 1 : fromDate.getMonth());
	
}

// ----------------------------------------------------------------
// ProcessGuestOptions()
//
// Process the options and call the required url with the options 
// selected.
// ----------------------------------------------------------------
function ProcessGuestOptions()
{
	var countyList = "";
	//var counties = xbGetElementById("CountyId");
	var region = xbGetElementById("RegionId");
	var viewType = xbGetElementById("viewType", "form1");
	var NumCounties = 0;
	var isValid = false;
	var showEvents = false;
	var url = "";
	var toDate=new Date();
	var fromDate=new Date();
	var fdate = "";
	var tdate = "";
	var months = new Array('1','2','3','4','5','6','7','8','9','10','11','12');
	
	// Process Dates
	fromDate = UpdateDate(fromDate, 4);
	toDate =UpdateDate(toDate,1)
	fdate = fromDate.getDate() + "/" + GetMonth(fromDate) + "/" + fromDate.getFullYear();
	tdate = toDate.getDate() + "/" + months[toDate.getMonth()] + "/" + toDate.getFullYear();
	showEvents = (viewType[0].checked ? true : false);
	
	if (showEvents)
	{
		// View Events for the past four months
		url = "search_event_list.asp?guest=true&from=rl&ToDate=" + tdate + "&FromDate=" + fdate + "&ddlb_region=" + region.options[region.selectedIndex].value;
	}
	else
	{
		// View Training Clinics for the past four months
		url = "search_training_clinic_list.asp?guest=true&from=rl&ToDate=" + tdate + "&FromDate=" + fdate + "&ddlb_region=" + region.options[region.selectedIndex].value;
	}
	
	// Jump to URL
	top.location = url;

	/*	
	if (counties != null)
	{
		for (i = 0; i < counties.options.length; i++)
		{
			if (counties.options[i].selected)
			{
				countyList+= "," + counties.options[i].value;
				NumCounties++;
			}
		}

		countyList = countyList.substring(1);
		if (NumCounties > 0)
			isValid = true;
		else
		{
			if (NumCounties == 0)
				alert("Please select atleast one county from the list provided; if there are no counties displayed please select the region you wish to view.");
		}
		
		// If form valid then call search page
		if (isValid)
		{
			
			if (showEvents)
			{
				// View Events for the past four months
				url = "search_event_list.asp?guest=true&from=rl&ToDate=" + tdate + "&FromDate=" + fdate + "&ddlb_county=" + countyList + "&ddlb_region=" + region.options[region.selectedIndex].value;
			}
			else
			{
				// View Training Clinics for the past four months
				url = "search_training_clinic_list.asp?guest=true&from=rl&ToDate=" + tdate + "&FromDate=" + fdate + "&ddlb_county=" + countyList + "&ddlb_region=" + region.options[region.selectedIndex].value;
			}
			
			// Jump to URL
			top.location = url;
		}
	}
	*/
}

// Extended Tooltip Javascript
// copyright 9th August 2002, 3rd July 2005
// by Stephen Chapman, Felgall Pty Ltd

// permission is granted to use this javascript provided that the below code is not altered
var DH = 0;var an = 0;var al = 0;var ai = 0;if (document.getElementById) {ai = 1; DH = 1;}else {if (document.all) {al = 1; DH = 1;} else { browserVersion = parseInt(navigator.appVersion); if ((navigator.appName.indexOf('Netscape') != -1) && (browserVersion == 4)) {an = 1; DH = 1;}}} function fd(oi, wS) {if (ai) return wS ? document.getElementById(oi).style:document.getElementById(oi); if (al) return wS ? document.all[oi].style: document.all[oi]; if (an) return document.layers[oi];}
function pw() {return window.innerWidth != null? window.innerWidth: document.body.clientWidth != null? document.body.clientWidth:null;}
function mouseX(evt) {if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); else return null;}
function mouseY(evt) {if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return null;}
function popUp(evt,oi) 
	{
		return;
		if (DH) 
		{
			var wp = pw(); 
			ds = fd(oi,1); 
			dm = fd(oi,0); 
			st = ds.visibility; 
			if (dm.offsetWidth) 
				ew = dm.offsetWidth; 
			else if (dm.clip.width) 
				ew = dm.clip.width; 
			
				hideShowCovered(oi);			
			if (st == "visible" || st == "show") 
			{ 
				ds.visibility = "hidden"; 
			} 
			else 
			{
				tv = mouseY(evt) + 20; 
				lv = mouseX(evt) - (ew/4); 
				if (lv < 2) 
					lv = 2; 
				else if (lv + ew > wp) 
					lv -= ew/2; 
				
				if (!an) 
				{
					lv += 'px';
					tv += 'px';
				} 
				ds.left = lv; 
				ds.top = tv; 
				ds.visibility = "visible";
			}
		}
	}
                  