/*
 * SABEngine.js - Select a Benefit Quoting Engine
 * Written by AMaitland
 * Version 1.1
 */

function Window_Resize()
{
	var clientWidth = document.body.clientWidth;
	if (clientWidth != _clientWidth)
	{
		_clientWidth = clientWidth < 1280 ? clientWidth : 1280;
		_clientWidth = clientWidth < 1024 ? 1024 : clientWidth;
		$('bodyContainer').setStyle({ width: _clientWidth + 'px' });
		$('headerTable').setStyle({ width: (clientWidth < 1280 ? clientWidth : 1280) + 'px' });
	}
}

function Init_SAB()
{
	_optionsService.Submit(_initQuote.Adults, _initQuote.Dependants, _initQuote.Destination, _initQuote.StartDate, _initQuote.EndDate);
}

function updateStartDate(e)
{
	var startDate = $('tempStartDate').value;
	var currentDate = _quoteControl.StartDate.GetSimpleDate().ToString();
	
	if (startDate != currentDate)
	{
		_quoteControl.StartDate.updateDate(startDate);
		_optionsService.Submit(_initQuote.Adults, _initQuote.Dependants, _initQuote.Destination, _initQuote.StartDate, _initQuote.EndDate);
	}
}

function updateEndDate(e)
{
	var endDate = $('tempEndDate').value;
	var currentDate = _quoteControl.EndDate.GetSimpleDate().ToString();
	
	if (endDate != currentDate)
	{
		_quoteControl.EndDate.updateDate(endDate);
		_optionsService.Submit(_initQuote.Adults, _initQuote.Dependants, _initQuote.Destination, _initQuote.StartDate, _initQuote.EndDate);
	}
}

function loadSavedState(control, id, stateHash)
{
	if (stateHash != null)
	{
		control.restoreSliderState(stateHash.get(id));
	}
}

function Page_Unload()
{
	if (_quoteControl != null)
	{
		try
		{
			var quote = _quoteControl.getQuote();

			var quoteCookie = new Mondial.QuoteCookie();

			quoteCookie.Update(quote);
			quoteCookie.Mode = Mondial.QUOTE_MODE_SAB;
			quoteCookie.SliderState = _sliderStateArray;
			new Mondial.CookieHandler().save(quoteCookie);
		}
		catch (err)
		{
			//Ignore
		}
	}
}
 
function cbQuoteChange(o)
{
  var isBasicValid = _basicValidator.Validate();
  if(isBasicValid)
  {
    var validator = new Mondial.QuoteValidator(_quoteControl.StartDate, _quoteControl.EndDate, new Mondial.SimpleDate().ParseString(_today), new Mondial.SimpleDate().ParseString(_todayPlusOneYear), new Mondial.SimpleDate().ParseString(_todayPlusTwoYear), "1", "year");
    var isValid = validator.Validate();
    if(isValid)
    {
      reqPremium(_controlArray, _quoteControl, _quoteService, 'status', _sliderStateArray);
    }
    else
    {
      _errorDisplayControl.AppendAndDisplay(validator.ValidateMessage);
    }
  }
  else
  {
    _errorDisplayControl.AppendAndDisplay(_basicValidator.ValidateMessage);
  }
}

function cbDestinationChange(o)
{
  var quote = _quoteControl.getQuote();
	
  _optionsService.Submit(quote.Adults, quote.Dependants, quote.Destination, quote.StartDate, quote.EndDate);
}

function onChange_EndMonthYear(evt)
{
  var endDate = Event.element(evt).value;
  _quoteControl.EndDate.updateDays(endDate);
  evt.stop();
}

function onChange_StartMonthYear(evt)
{
  var startDate = Event.element(evt).value;
  _quoteControl.StartDate.updateDays(startDate);
  _quoteControl.EndDate.resetEndDates(_arrEndDates);
  evt.stop();
}

function IsDomestic(destination)
{
  if(destination.toUpperCase() == 'AUSTRALIA')
  {
    return true;
  }
  return false;
}

// call back for SAB premium returned by AJAX
function ajax_cb_sab_premium(o)
{
	var x = o.responseXML.documentElement;
	
	var success = (x.attributes[0].nodeValue == "True");
	
	if(success)
	{
		var premium = x.getElementsByTagName("PREMIUM");
		$('divPremium').innerHTML = premium[0].childNodes[0].nodeValue;
		$('divPremium1').innerHTML = premium[0].childNodes[0].nodeValue;

		var items = x.getElementsByTagName("BENEFIT");
		var len = items.length;
		for(var i=0;i < len; i++)
		{
			var item = items[i];
			if(item.nodeName == "BENEFIT")
			{
				var attr = item.attributes;
				var prodid = attr[0].nodeValue;
				var value = attr[1].nodeValue;
				$('calcval' + prodid).update("$" + value);
			}
		}

		items = x.getElementsByTagName("EXCESS");
		len = items.length;
		for(var i = 0; i < len; i++)
		{
			var item = items[i];
			if(item.nodeName == "EXCESS")
			{
				var attr = item.attributes;
				var value = attr[1].nodeValue;
				var amountDiv = $('calcval0');
				if(amountDiv != null)
				{
					amountDiv.update("$" + value);
				}
			}
		}
		$('buyButtonTable').show();
		$('buyButtonTable1').show();
	}
	else
	{
		var message = x.attributes[1].nodeValue;
		_errorDisplayControl.AppendAndDisplay(message);
		$('buyButtonTable').hide();
		$('buyButtonTable1').hide();
	}

	$('sabQuoteProcessing').hide();
};

function ajaxOptionsLoaded(response)
{
	_options = response.responseText.evalJSON(true);
	
	if(_options.IsValid)
	{
		//Remove any sliders
		$('sabContainerDiv').childElements().each(function(e)
		{
		  e.remove();
		});

		
		//Load the select a benefit options
		Load_SAB();
		
		//Use Quote change method so validation is fired.
		if(_hasError)
		{
			_hasError = false;
			_errorDisplayControl.AppendAndDisplay(_errorMessage);
		}
		else
		{
			cbQuoteChange(null);
		}
	}
	else
	{
		_errorDisplayControl.AppendAndDisplay(_options.Message);
	}
};

function sabTimeout(response)
{
	_errorDisplayControl.AppendAndDisplay('Your quote request timed out, please try again.');
	$('sabQuoteProcessing').hide();
	$('buyButtonTable').show();
}

// AJAX code to get premium calculation
// Build list of selection;
function reqPremium(controlArray, quoteControl, quoteService, status, stateHash)
{
	_errorDisplayControl.Hide();
	$('buyButtonTable').hide();
	$('sabQuoteProcessing').show();
	
	var selections = "";
	
	controlArray.each(function(ctl)
	{
		if(ctl.IsEnabled)
		{
			selections += ctl.BenefitSelection.value + ";"
		}
	});

	var quote = quoteControl.getQuote();
	quote.Selection = selections;
	
	//Save the state of current sliders
	saveSliderState(controlArray, stateHash);
	
	quoteService.Submit(quote.Adults, quote.Dependants, quote.Destination, selections, 0, quote.StartDate, quote.EndDate, false);
}

function escapeHTML(str)
{
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
}; 

function saveSliderState(controls, stateHash)
{
	controls.each(function(control)
	{
		var state = control.getSliderState();
		if(state != null)
		{
			stateHash.set(state.Id, state);
		}
	});
}

function getCookieDate(firstDate, secondDate, today)
{
	var dteStart = new Mondial.SimpleDate().ParseString(secondDate);
	
	if(!dteStart.IsGreater(new Mondial.SimpleDate().ParseString(today).ToString()))
	{
		return firstDate;
	}
	
	return secondDate;
}

/*
 * SABLib.js - Select a Benefit Quoting Engine
 * Written by AMaitland
 * Version 1.1
 */
 
var Mondial =
{
	//Standard Mode (Multi Quote)
	QUOTE_MODE_STANDARD : 0,
	//Select a Benefit Mode
	QUOTE_MODE_SAB : 1,
	SAB_COOKIE_NAME : "worldcareSABCookie",
	IEBrowserVersion : parseFloat(navigator.appVersion.split('MSIE')[1]),
	//TODO: tidy up some of this
	Browser:
	{
		IEBrowserVersion : parseInt(navigator.appVersion.split('MSIE')[1], 10),
		IE6 : parseInt(navigator.appVersion.split('MSIE')[1], 10) == 6
	},
	ApplyPNGFix : ((this.IEBrowserVersion >= 5.5) && (this.IEBrowserVersion < 7) && (document.body.filters)),
	//Create Mondial.Ajax namespace
	Ajax : {},
	MapTimeUnit : function(unit)
	{
	  var unitInt = parseInt(unit, 10);
	  if(unitInt == 0)
	  {
	    return "Day";
	  }
	  if(unitInt == 1)
	  {
	    return "Month";
	  }
	  //Default Return of "Year"
	  return "Year";
	}
};

Mondial.Options = Class.create(
{
  ///<summary>
  /// setOptions - Extends object's *options* property with the given object
  ///</summary>
  setOptions: function(options)
  {
    var prototype = this.constructor.prototype;

    // if it's an instance and options are still default ones
    if (this !== prototype && this.options === prototype.options)
      this.options = this.allOptions();

    this.options = Object.extend(this.options, options || {});
  },
  allOptions: function()
  {
    var superclass = this.constructor.superclass, ancestor = superclass && superclass.prototype;
    return (ancestor && ancestor.allOptions) ? Object.extend(ancestor.allOptions(), this.options) : Object.clone(this.options);
  }
});

Mondial.BasicValidator = Class.create(
{
	ValidateMessage : "OK",
	StartDate : null,
	EndDate : null,
	Today : null,
	PurchaseCutOff : null,
	TodayPlusTwoYears : null,
	
	initialize : function(dmyStartDate, dmyEndDate, sdToday, sdPurchaseCutOff, todayPlusTwoYears)
	{
		this.StartDate = dmyStartDate;
		this.EndDate = dmyEndDate;
		this.Today = sdToday;
		this.PurchaseCutOff = sdPurchaseCutOff;
		this.TodayPlusTwoYears = todayPlusTwoYears;
	},
	IsStartDateValid : function ()
	{
		//Validate start date
		var dteStart = this.StartDate.GetSimpleDate();
		var dteEnd = this.EndDate.GetSimpleDate();
		dteStart.MinRange = this.Today.ToString();
		dteStart.MaxRange = this.PurchaseCutOff.ToString();
		
		if(!dteStart.IsGreater(this.Today.ToString()))
		{
			this.ValidateMessage = "Start date is invalid. Earliest possible start date is " + this.Today.ToString();
			return false;
		}
		if(!dteStart.IsInRange())
		{
			this.ValidateMessage = "Start date is invalid. Policy start dates must be between " + this.Today.ToString() + " and " + dteStart.MaxRange;
			return false;
		}
		
		return true;
	},
	IsEndDateValid : function ()
	{
		//Validate end date
		var dteStart = this.StartDate.GetSimpleDate();
		var dteEnd = this.EndDate.GetSimpleDate();
		dteEnd.MinRange = this.Today.ToString();
		dteEnd.MaxRange = this.TodayPlusTwoYears.ToString();
		
		if(!dteEnd.IsInRange())
		{
			this.ValidateMessage = "Policy End Date must be between " + this.Today.ToString() + " and " + dteEnd.MaxRange;
			return false;
		}
		if(!dteEnd.IsGreater(dteStart.ToString()))
		{
			this.ValidateMessage = "End Date must come after Start Date";
			return false;
		}
		
		return true;	
	},
	Validate : function ()
	{
		this.ValidateMessage = "OK";
		
		return this.IsStartDateValid() && this.IsEndDateValid();
	}
});

Mondial.QuoteValidator = Class.create(
{
	StartDate : null,
	EndDate : null,
	ValidateMessage : "OK",
	Today : null,
	PurchaseCutOff : null,
	MaxLength : null,
	MaxLengthUnit : null,
	TodayPlusTwoYears : null,
	
	initialize : function(dmyStartDate, dmyEndDate, sdToday, sdPurchaseCutOff, todayPlusTwoYears, intMaxLength, strMaxLengthUnit)
	{
		this.StartDate = dmyStartDate;
		this.EndDate = dmyEndDate;
		this.Today = sdToday;
		this.PurchaseCutOff = sdPurchaseCutOff;
		this.MaxLength = parseInt(intMaxLength, 10);
		this.MaxLengthUnit = strMaxLengthUnit;
		this.TodayPlusTwoYears = todayPlusTwoYears;
	},
	IsStartDateValid : function ()
	{
		//Validate start date
		var dteStart = this.StartDate.GetSimpleDate();
		var dteEnd = this.EndDate.GetSimpleDate();
		dteStart.MinRange = this.Today.ToString();
		dteStart.MaxRange = this.PurchaseCutOff.ToString();
		
		if(!dteStart.IsGreater(this.Today.ToString()))
		{
			this.ValidateMessage = "Start date is invalid. Earliest possible start date is " + this.Today.ToString();
			return false;
		}
		if(!dteStart.IsInRange())
		{
			this.ValidateMessage = "Start date is invalid. Policy start dates must be between " + this.Today.ToString() + " and " + dteStart.MaxRange;
			return false;
		}
		
		return true;
	},
	IsEndDateValid : function ()
	{
		//Validate end date
		var dteStart = this.StartDate.GetSimpleDate();
		var dteEnd = this.EndDate.GetSimpleDate();
		dteEnd.MinRange = this.Today.ToString();
		dteEnd.MaxRange = this.TodayPlusTwoYears.ToString();
		
		if(!dteEnd.IsInRange())
		{
			this.ValidateMessage = "Policy End Date must be between " + this.Today.ToString() + " and " + dteEnd.MaxRange;
			return false;
		}
		if(!dteEnd.IsGreater(dteStart.ToString()))
		{
			this.ValidateMessage = "End Date must come after Start Date";
			return false;
		}
		
		if(!this.ValidateMaxLength(this.MaxLength, this.MaxLengthUnit))
		{
		  this.ValidateMessage = "Policy Length cannot exceed " + this.MaxLength + " " + this.MaxLengthUnit + (this.MaxLengthUnit.toLowerCase() == "year" ? "" : "(s)");
			return false;
		}
		
		return true;	
	},
	ValidateMaxLength : function ()
	{
		var dteStartDate = this.StartDate.GetSimpleDate().GetDate();
		var dteEndDate = this.EndDate.GetSimpleDate().GetDate();
		
		var syear = 0;
		var unit = this.MaxLengthUnit.toLowerCase();
		
		if(/year/.test(unit))
		{
			// add number of years and then turn into a date
			syear = parseInt(dteStartDate.getFullYear(), 10) + parseInt(this.MaxLength, 10);
			dteStartDate.setYear(syear);
		}
		else if(/month/.test(unit))
		{
			smonth = parseInt(dteStartDate.Month, 10) + parseInt(this.MaxLength, 10);
			if(smonth > 12)
			{
				smonth = parseInt(smonth, 10) - 12;
				syear = parseInt(syear, 10) + 1;
			}
			
			dteStartDate.setMonth(smonth - 1);
		}
		else if(/day/.test(unit))
		{
			var length = parseInt(this.MaxLength, 10) - 1;
			dteStartDate.setDate(dteStartDate.getDate() + length);
		}

		if(dteEndDate.getTime() >= dteStartDate.getTime())
		{
			return false;
		}
		else
		{
			return true;
		}
	},
	Validate : function ()
	{
		this.ValidateMessage = "OK";
		
		return this.IsStartDateValid() && this.IsEndDateValid();
	}
});

Mondial.DMYControl = Class.create(
{
	/// <summary>
	/// DMYControl - Represents a Two Part Date Control (Day and Month+Year)
	/// Both the Day control and Month+Year controls MUST be dropdown's
	/// </summary>
	/// <param name="ddDay">The day drop down list</param>
	/// <param name="ddMonthYear">The Month+Year drop down list</param>
	/// <param name="strInitialDate">The initial date in string format (dd/MM/yyyy)</param>
	initialize: function(ddDay, ddMonthYear, strInitialDate)
	{
		this.DDDay = $(ddDay);
		this.DDMonthYear = $(ddMonthYear);
		this.InitialDate = strInitialDate;
		var dte = new Mondial.SimpleDate().ParseString(strInitialDate);
		this.updateMonthOnLoad(dte.ToMonthYearStr(), dte.Day);
	},
	GetSimpleDate: function()
	{
		return new Mondial.SimpleDate().ParseTwoPartDate(this.DDDay.value, this.DDMonthYear.value);
	},
	updateDate: function(strDate)
	{
		var dte = new Mondial.SimpleDate().ParseString(strDate);
		var strMonthYear = dte.ToMonthYearStr();

		var len = this.DDDay.options.length;
		for (var i = 0; i < len; i++)
		{
			if (parseInt(this.DDDay.options[i].value, 10) == dte.Day)
			{
				this.DDDay.options[i].selected = true;
			}
		}

		len = this.DDMonthYear.options.length;
		for (var i = 0; i < len; i++)
		{
			if (this.DDMonthYear.options[i].value == strMonthYear)
			{
				this.DDMonthYear.options[i].selected = true;
			}
		}
	},
	updateMonthOnLoad: function(strMonthYear, strDay)
	{
		var dte = new Mondial.SimpleDate().ParseString("01/" + strMonthYear);

		var intDaysInMonth;

		try
		{
			intDaysInMonth = dte.DaysInMonth();
		}
		catch (err)
		{
			//Ignore this error
		}

		//Check to see if days in month is ok.
		if (intDaysInMonth >= 28)
		{
			var dteCurrent = new Mondial.SimpleDate().Now();
			var dte = dteCurrent.ToMonthYearStr();
			var avaliableDays = intDaysInMonth - dteCurrent.Day;

			//If the month is the current, the remove all past dates and adjust
			// number of days in month
			if (strMonthYear == dte)
			{
				if (intDaysInMonth < this.DDMonthYear.options.length)
				{
					while (this.DDMonthYear.options.length > intDaysInMonth)
					{
						this.removeSelectElement(ddControl, ddControl.length - 1);
					}
				}
			}
		}

		this.updateDate(this.InitialDate);
	},
	//Wrapper function around the remove, incase we need to implement some backwards compatable functions
	removeSelectElement: function(dd, intIndex)
	{
		dd.removeChild(dd.options[intIndex]);
	},
	updateDays: function(strMonthYear)
	{
		var ddControl = $(this.DDDay);
		var dte = new Mondial.SimpleDate().ParseString("01/" + strMonthYear);

		var intDaysInMonth;

		try
		{
			intDaysInMonth = dte.DaysInMonth();
		}
		catch (err)
		{
			//Ignore this error
		}

		//Check to see if days in month is ok.
		if (intDaysInMonth >= 28)
		{
			var dteCurrent = new Mondial.SimpleDate().Now();
			var avaliableDays = intDaysInMonth - dteCurrent.Day + 1;

			//If the month is the current, the remove all past dates and adjust
			// number of days in month
			if (strMonthYear == dteCurrent.ToMonthYearStr())
			{
				if (ddControl.length < intDaysInMonth)
				{
					while (parseInt((ddControl.options[ddControl.length - 1].value), 10) != intDaysInMonth)
					{
						var intVal = parseInt((ddControl.options[ddControl.length - 1].value), 10) + 1;
						this.createAppendOption(ddControl, intVal);
					}
				}

				if (intDaysInMonth < ddControl.length)
				{
					while (ddControl.length > intDaysInMonth)
					{
						this.removeSelectElement(ddControl, ddControl.length - 1);
					}
				}

				if (ddControl.length > avaliableDays)
				{
					while (ddControl.length > avaliableDays)
					{
						this.removeSelectElement(ddControl, 0);
					}
				}
			}
			else
			{
				while (parseInt((ddControl.options[0].value), 10) != 1)
				{
					var op = document.createElement("option");
					var intVal = parseInt((ddControl.options[0].value), 10) - 1;
					op.innerHTML = intVal;
					op.value = intVal;
					ddControl.insertBefore(op, ddControl.options[0]);
				}

				if (intDaysInMonth < ddControl.length)
				{
					while (ddControl.length > intDaysInMonth)
					{
						this.removeSelectElement(ddControl, ddControl.length - 1);
					}
				}
				else
				{
					while (ddControl.length < intDaysInMonth)
					{
						var intVal = parseInt((ddControl.options[ddControl.length - 1].value), 10) + 1;
						this.createAppendOption(ddControl, intVal);
					}
				}
			}
		}
	},
	createAppendOption: function(ddParent, val)
	{
		var op = document.createElement("option");
		op.innerHTML = val;
		op.value = val;
		ddParent.appendChild(op);
	},
	updateEndDates: function(arrDates, intIndex)
	{
		this.resetEndDates(arrDates);

		for (var i = 0; i < intIndex; i++)
		{
			this.DDMonthYear.removeChild(this.DDMonthYear.options[0]);
		}

		var intTotal = 13;
		if (this.DDMonthYear.options.length == 12)
		{
			intTotal = 12;
		}

		while (this.DDMonthYear.options.length > intTotal)
		{
			this.DDMonthYear.removeChild(this.DDMonthYear.options[this.DDMonthYear.options.length - 1]);
		}
	},
	resetEndDates: function(arrDates)
	{
		if (this.DDMonthYear.options.length < arrDates.length)
		{
			var matchFound = false;

			var len = arrDates.length;
			for (var i = 0; i < len; i++)
			{
				if (arrDates[i] != this.DDMonthYear.options[0] && !matchFound)
				{
					this.DDMonthYear.insertBefore(arrDates[i], this.DDMonthYear.options[i]);
				}
				else if (arrDates[i] != this.DDMonthYear.options[0])
				{
					this.DDMonthYear.appendChild(arrDates[i]);
				}
			}

			var intCount = arrDates.length - this.DDMonthYear.options.length;
			for (var i = intCount; i >= 0; i--)
			{
				this.DDMonthYear.insertBefore(arrDates[i], this.DDMonthYear.options[0]);
			}
		}
	}
});

Mondial.SimpleDate = Class.create(
{
	MaxRange : 0,
	MinRange : 0,
	initialize : function(intDay, intMonth, intYear)
	{
		this.Day = intDay;
		this.Month = intMonth;
		this.Year = intYear;
	},
	Now : function ()
	{
		var dteCurrent = new Date();
		dteCurrent.setDate(dteCurrent.getDate());
		
		return this.ParseDate(dteCurrent);
	},
	ToMonthYearStr : function()
	{
		return this.padDate(this.Month) + "/" + this.Year;
	},
	GetDate : function()
	{
		//JS Month starts from 0-11
		return new Date(this.Year, parseInt(this.Month - 1, 10), this.Day);
	},
	padDate : function (intInput)
	{
		if(intInput < 10)
		{
			intInput = "0" + intInput;
		}
		return intInput;
	},	
	ParseTwoPartDate : function(strDay, strMonthYear)
	{
		var intIndex = strMonthYear.indexOf("/");
		this.Day = parseInt(strDay, 10);
		this.Month = parseInt(strMonthYear.substring(0, intIndex), 10);
		this.Year = parseInt(strMonthYear.substring(intIndex + 1), 10);
		
		return this;
	},
	ParseMonthYear : function(strMonthYear)
	{
		var intIndex = strMonthYear.indexOf("/");
		this.Day = 1;
		this.Month = parseInt(strMonthYear.substring(0, intIndex), 10);
		this.Year = parseInt(strMonthYear.substring(intIndex + 1), 10);		
	},
	ParseString : function(strDayMonthYear)
	{
		var dtCh = "/";
		var pos1 = strDayMonthYear.indexOf(dtCh);
		var pos2 = strDayMonthYear.indexOf(dtCh, pos1+1);
		this.Day = parseInt(strDayMonthYear.substring(0, pos1), 10);
		this.Month = parseInt(strDayMonthYear.substring(pos1+1, pos2), 10);
		this.Year = parseInt(strDayMonthYear.substring(pos2+1), 10);
		
		return this;
	},
	ParseDate : function(jsdate)
	{
		this.Day  = jsdate.getDate();
		this.Month = jsdate.getMonth() + 1;
		this.Year  = parseInt(jsdate.getFullYear(), 10);
		
		return this;
	},
	DaysInMonth : function()
	{
		var dd = new Date(this.Year, this.Month, 0);
		return dd.getDate();
	},
	//Is the current date between MinRange and MaxRange
	IsInRange : function()
	{
		if(this.MinRange == null && this.MaxRange == null)
		{
			return true;
		}
		else
		{
			if (this.MinRange == null || this.MinRange == "")
			{
				this.MinRange = 0;
			}
			
			if (this.MaxRange == null || this.MaxRange == "")
			{
				this.MaxRange = 0;
			}

			var intVal = this.convertToInt(this);
	    var intMinOp = this.MinRange == 0 ? 0 : this.convertToInt(new Mondial.SimpleDate().ParseString(this.MinRange));
	    var intMaxOp = this.MaxRange == 0 ? 0 : this.convertToInt(new Mondial.SimpleDate().ParseString(this.MaxRange));
			
			return (intVal >= intMinOp) && (intVal <= intMaxOp);
		}
	},
	//Is given date greater than current SimpleDate
	IsGreater : function (strDate2)
	{
		var intDate1 = this.convertToInt(this);
		var intDate2 = this.convertToInt(new Mondial.SimpleDate().ParseString(strDate2));

		return (intDate1 >= intDate2);
	},
	GetFullYear : function(year, century, cutoffyear)
	{
		return (year + parseInt(century)) - ((year < cutoffyear) ? 0 : 100);
	},
	convertToInt : function (simpleDate)
	{
		return simpleDate.GetDate().valueOf();
	},
	//Outputs the simple date in the format dd/MM/yyyy
	ToString : function()
	{
		return this.padDate(this.Day) + "/" + this.padDate(this.Month) + "/" + this.Year;
	}
});

Mondial.Quote = Class.create(
{
	Adults : 1,
	Dependants : 0,
	Destination : "WORLDWIDE",
	StartDate : "",
	EndDate : "",
	Selection : "",
	
	///Prototype Init Function - Called when object created
	initialize : function()
	{

	}
});

Mondial.QuoteCookie = Class.create(Mondial.Quote,
{
	Mode : Mondial.QUOTE_MODE_SAB,
	SliderState : null,
	initialize: function($super, quote)
	{
    $super();
    if(quote != null)
    {
			this.Update(quote);	
		}
  },
  Update : function (quote)
  {
		this.Adults = quote.Adults;
		this.Dependants = quote.Dependants;
		this.Destination = quote.Destination;
		this.StartDate = quote.StartDate;
		this.EndDate = quote.EndDate;
		if(quote.Selection != null && quote.Selection != "")
		{
			this.Selection = quote.Selection;
		}
		if(quote.Mode != null)
		{
			this.Mode = quote.Mode;
		}
		if(quote.SliderState != null)
		{
			this.SliderState = quote.SliderState;
		}
  }  
});

Mondial.QuoteControl = Class.create(
{
	//Reference to event handler functions
	OnDestinationChange: null,
	OnAdultsChange: null,
	OnChildrenChange: null,
	OnStartDateChange: null,
	OnEndDateChange: null,

	///Prototype Init Function - Called when object created
	initialize: function(destination, adults, children, startDay, startMonthYear, endDay, endMonthYear, startDate, endDate, initQuote)
	{
		//Controls
		this.Destination = $(destination);
		this.Adults = $(adults);
		this.Children = $(children);
		this.StartDay = $(startDay);
		this.StartMonthYear = $(startMonthYear);
		this.EndDay = $(endDay);
		this.EndMonthYear = $(endMonthYear);
		this.StartDate = new Mondial.DMYControl(startDay, startMonthYear, initQuote != null ? initQuote.StartDate : startDate);
		this.EndDate = new Mondial.DMYControl(endDay, endMonthYear, initQuote != null ? initQuote.EndDate : endDate);
		this.InitialQuote = initQuote;
	},
	getQuote: function()
	{
		var quote = new Mondial.Quote();

		quote.Destination = this.Destination.options[this.Destination.selectedIndex == -1 ? 0 : this.Destination.selectedIndex].value;
		quote.Adults = this.Adults.options[this.Adults.selectedIndex == -1 ? 0 : this.Adults.selectedIndex].value;
		quote.Dependants = this.Children.options[this.Children.selectedIndex == -1 ? 0 : this.Children.selectedIndex].value;
		quote.StartDate = this.StartDay.value + '/' + this.StartMonthYear.value;
		quote.EndDate = this.EndDay.value + '/' + this.EndMonthYear.value;

		return quote;
	},
	loadStandard: function(masterPlans)
	{
		var dest = null;
		var adult = null;
		var child = null;
		if (this.Destination.options.length > 0)
		{
			dest = this.Destination.options[this.Destination.selectedIndex == -1 ? 0 : this.Destination.selectedIndex].value;
		}
		else
		{
			dest = this.InitialQuote.Destination;
		}
		if (this.Adults.options.length > 0)
		{
			adult = this.Adults.options[this.Adults.selectedIndex == -1 ? 0 : this.Adults.selectedIndex].value;
		}
		else
		{
			adult = this.InitialQuote.Adults;
		}
		if (this.Children.options.length > 0)
		{
			child = this.Children.options[this.Children.selectedIndex == -1 ? 0 : this.Children.selectedIndex].value;
		}
		else
		{
			child = this.InitialQuote.Dependants;
		}

		var maxAdults = masterPlans[0].MaxAdults;
		var maxDependants = masterPlans[0].MaxDependants;

		this.Adults.options.length = 0;
		this.Children.options.length = 0;

		for (var i = 0; i < maxAdults; i++)
		{
			this.Adults.options[i] = new Option(i + 1, i + 1);
		}
		for (var i = 0; i <= maxDependants; i++)
		{
			this.Children.options[i] = new Option(i, i);
		}
		this.Destination.options.length = 0; // clear list box
		var regions = masterPlans[0].AvaliableDestinations;
		var len = regions.length;
		for (i = 0; i < len; i++)
		{
			this.Destination.options[i] = new Option(regions[i].Description, regions[i].Value);
		}

		if (dest != null)
		{
			this.setDestination(dest);
		}

		if (adult != null)
		{
			this.setAdult(adult);
		}

		if (child != null)
		{
			this.setChild(child);
		}
	},
	clearEvents: function()
	{
		if (this.OnDestinationChange != null) Event.stopObserving(this.Destination, "change", this.OnDestinationChange);
		if (this.OnAdultsChange != null) Event.stopObserving(this.Adults, "change", this.OnAdultsChange);
		if (this.OnChildrenChange != null) Event.stopObserving(this.Children, "change", this.OnChildrenChange);
		if (this.OnStartDateChange != null) Event.stopObserving(this.StartDay, "change", this.OnStartDateChange);
		if (this.OnStartDateChange != null) Event.stopObserving(this.StartMonthYear, "change", this.OnStartDateChange);
		if (this.OnEndDateChange != null) Event.stopObserving(this.EndDay, "change", this.OnEndDateChange);
		if (this.OnEndDateChange != null) Event.stopObserving(this.EndMonthYear, "change", this.OnEndDateChange);

	},
	//Clears controls (does not clear start and end date)
	clearControls: function()
	{
		this.Destination.options.length = 0;
		this.Adults.options.length = 0;
		this.Children.options.length = 0;
	},
	setOnDestinationChange: function(handler)
	{
		if (this.OnDestinationChange != null)
		{
			Event.stopObserving(this.Destination, "change", this.OnDestinationChange);
		}
		this.OnDestinationChange = handler;
		this.Destination.observe("change", handler);
	},
	setOnAdultsChange: function(handler)
	{
		if (this.OnAdultsChange != null)
		{
			Event.stopObserving(this.Adults, "change", this.OnAdultsChange);
		}
		this.OnAdultsChange = handler;
		this.Adults.observe("change", handler);
	},
	setOnChildrenChange: function(handler)
	{
		if (this.OnChildrenChange != null)
		{
			Event.stopObserving(this.Children, "change", this.OnChildrenChange);
		}
		this.OnChildrenChange = handler;
		this.Children.observe("change", handler);
	},
	setOnStartDateChange: function(handler)
	{
		if (this.OnStartDateChange != null)
		{
			Event.stopObserving(this.StartDay, "change", this.OnStartDateChange);
			Event.stopObserving(this.StartMonthYear, "change", this.OnStartDateChange);
		}
		this.OnStartDateChange = handler;
		this.StartDay.observe("change", handler);
		this.StartMonthYear.observe("change", handler);
	},
	setOnEndDateChange: function(handler)
	{
		if (this.OnEndDateChange != null)
		{
			Event.stopObserving(this.EndDay, "change", this.OnEndDateChange);
			Event.stopObserving(this.EndMonthYear, "change", this.OnEndDateChange);
		}
		this.OnEndDateChange = handler;
		this.EndDay.observe("change", handler);
		this.EndMonthYear.observe("change", handler);
	},
	setAdult: function(selected)
	{
		var len = this.Adults.options.length;
		for (var i = 0; i < len; i++)
		{
			var option = this.Adults.options[i];
			if (option.value == selected)
			{
				option.selected = true;
			}
		}
	},
	setChild: function(selected)
	{
		var len = this.Children.options.length;
		for (var i = 0; i < len; i++)
		{
			var option = this.Children.options[i];
			if (option.value == selected)
			{
				option.selected = true;
			}
		}
	},
	setDestination: function(selected)
	{
		var len = this.Destination.options.length;
		for (var i = 0; i < len; i++)
		{
			var option = this.Destination.options[i];
			if (option.value.toUpperCase() == selected.toUpperCase())
			{
				option.selected = true;
			}
		}
	},
	setStartDate: function(startDate)
	{
		this.StartDate.updateDate(startDate);
	},
	setEndDate: function(endDate)
	{
		this.EndDate.updateDate(endDate);
	},
	getDestination: function()
	{
		return this.Destination.options[this.Destination.selectedIndex == -1 ? 0 : this.Destination.selectedIndex].value;
	}
});

Mondial.SABQuoteControl = Class.create(
{
	//Reference to event handler functions
	OnDestinationChange: null,
	OnAdultsChange: null,
	OnChildrenChange: null,
	OnStartDateChange: null,
	OnEndDateChange: null,

	///Prototype Init Function - Called when object created
	initialize: function(destination, adults, children, startDay, startMonthYear, endDay, endMonthYear, startDate, endDate, initQuote)
	{
		//Controls
		this.Destination = $(destination);
		this.Adults = $(adults);
		this.Children = $(children);
		this.StartDay = $(startDay);
		this.StartMonthYear = $(startMonthYear);
		this.EndDay = $(endDay);
		this.EndMonthYear = $(endMonthYear);
		this.StartDate = new Mondial.DMYControl(startDay, startMonthYear, initQuote != null ? initQuote.StartDate : startDate);
		this.EndDate = new Mondial.DMYControl(endDay, endMonthYear, initQuote != null ? initQuote.EndDate : endDate);
		this.InitialQuote = initQuote;
	},
	getQuote: function()
	{
		var quote = new Mondial.Quote();

		quote.Destination = this.Destination.options[this.Destination.selectedIndex == -1 ? 0 : this.Destination.selectedIndex].value;
		quote.Adults = this.Adults.options[this.Adults.selectedIndex == -1 ? 0 : this.Adults.selectedIndex].value;
		quote.Dependants = this.Children.options[this.Children.selectedIndex == -1 ? 0 : this.Children.selectedIndex].value;
		quote.StartDate = this.StartDay.value + '/' + this.StartMonthYear.value;
		quote.EndDate = this.EndDay.value + '/' + this.EndMonthYear.value;

		return quote;
	},
	Load: function(options)
	{
		var dest = this.Destination.options.length > 0 ? (this.getDestination()) : this.InitialQuote.Destination;
		var adult = this.Adults.options.length > 0 ? (this.Adults.options[this.Adults.selectedIndex == -1 ? 0 : this.Adults.selectedIndex].value) : this.InitialQuote.Adults;
		var child = this.Children.options.length > 0 ? (this.Children.options[this.Children.selectedIndex == -1 ? 0 : this.Children.selectedIndex].value) : this.InitialQuote.Dependants;

		this.Adults.options.length = 0;
		this.Children.options.length = 0;

		var len = options.MaxAdults;
		for (var i = 0; i < len; i++)
		{
			this.Adults.options[i] = new Option(i + 1, i + 1);
		}
		len = options.MaxDependants;
		for (var i = 0; i <= len; i++)
		{
			this.Children.options[i] = new Option(i, i);
		}
		this.Destination.options.length = 0; // clear list box
		len = options.Regions.length;
		for (i = 0; i < len; i++)
		{
			var val = options.Regions[i];
			this.Destination.options[i] = new Option(val, val);
		}
		if (dest != null) { this.setDestination(dest); }
		if (adult != null) { this.setAdult(adult); }
		if (child != null) { this.setChild(child); }
	},
	clearEvents: function()
	{
		if (this.OnDestinationChange != null) Event.stopObserving(this.Destination, "change", this.OnDestinationChange);
		if (this.OnAdultsChange != null) Event.stopObserving(this.Adults, "change", this.OnAdultsChange);
		if (this.OnChildrenChange != null) Event.stopObserving(this.Children, "change", this.OnChildrenChange);
		if (this.OnStartDateChange != null) Event.stopObserving(this.StartDay, "change", this.OnStartDateChange);
		if (this.OnStartDateChange != null) Event.stopObserving(this.StartMonthYear, "change", this.OnStartDateChange);
		if (this.OnEndDateChange != null) Event.stopObserving(this.EndDay, "change", this.OnEndDateChange);
		if (this.OnEndDateChange != null) Event.stopObserving(this.EndMonthYear, "change", this.OnEndDateChange);

	},
	//Clears controls (does not clear start and end date)
	clearControls: function()
	{
		this.Destination.options.length = 0;
		this.Adults.options.length = 0;
		this.Children.options.length = 0;
	},
	setOnDestinationChange: function(handler)
	{
		if (this.OnDestinationChange != null)
		{
			Event.stopObserving(this.Destination, "change", this.OnDestinationChange);
		}
		this.OnDestinationChange = handler;
		this.Destination.observe("change", handler);
	},
	setOnAdultsChange: function(handler)
	{
		if (this.OnAdultsChange != null)
		{
			Event.stopObserving(this.Adults, "change", this.OnAdultsChange);
		}
		this.OnAdultsChange = handler;
		this.Adults.observe("change", handler);
	},
	setOnChildrenChange: function(handler)
	{
		if (this.OnChildrenChange != null)
		{
			Event.stopObserving(this.Children, "change", this.OnChildrenChange);
		}
		this.OnChildrenChange = handler;
		this.Children.observe("change", handler);
	},
	setOnStartDateChange: function(handler)
	{
		if (this.OnStartDateChange != null)
		{
			Event.stopObserving(this.StartDay, "change", this.OnStartDateChange);
			Event.stopObserving(this.StartMonthYear, "change", this.OnStartDateChange);
		}
		this.OnStartDateChange = handler;
		this.StartDay.observe("change", handler);
		this.StartMonthYear.observe("change", handler);
	},
	setOnEndDateChange: function(handler)
	{
		if (this.OnEndDateChange != null)
		{
			Event.stopObserving(this.EndDay, "change", this.OnEndDateChange);
			Event.stopObserving(this.EndMonthYear, "change", this.OnEndDateChange);
		}
		this.OnEndDateChange = handler;
		this.EndDay.observe("change", handler);
		this.EndMonthYear.observe("change", handler);
	},
	setAdult: function(selected)
	{
		var len = this.Adults.options.length;
		for (var i = 0; i < len; i++)
		{
			var option = this.Adults.options[i];
			if (option.value == selected)
			{
				option.selected = true;
			}
		}
	},
	setChild: function(selected)
	{
		var len = this.Children.options.length;
		for (var i = 0; i < len; i++)
		{
			var option = this.Children.options[i];
			if (option.value == selected)
			{
				option.selected = true;
			}
		}
	},
	setDestination: function(selected)
	{
		var len = this.Destination.options.length;
		for (var i = 0; i < len; i++)
		{
			var option = this.Destination.options[i];
			if (option.value.toUpperCase() == selected.toUpperCase())
			{
				option.selected = true;
			}
		}
	},
	setStartDate: function(startDate)
	{
		this.StartDate.updateDate(startDate);
	},
	setEndDate: function(endDate)
	{
		this.EndDate.updateDate(endDate);
	},
	getDestination: function()
	{
		return this.Destination.options[this.Destination.selectedIndex == -1 ? 0 : this.Destination.selectedIndex].value;
	}
});

Mondial.ErrorItem = Class.create(
{
	Id : 0,
	Message : "",
	Status : 0,
	
	///Prototype Init Function - Called when object created
	initialize : function(id, message, status)
	{
		this.Id = id;
		this.Message = message;
		this.Status = status;
	}
});

Mondial.ErrorDisplayControl = Class.create(
{
	Container: null,
	Title: "Error",
	Items: {},
	Height: 31,

	///Prototype Init Function - Called when object created
	initialize: function(container, buyButtonTable, buyButtonTable1)
	{
		this.Container = $(container);
		this.BuyButtonTable = $(buyButtonTable);
		this.BuyButtonTable1 = $(buyButtonTable1);
	},
	AppendAndDisplay: function(message)
	{
		var errorTemplate = new Template('<ul><li>#{message}</li></ul>');
		this.Container.update(errorTemplate.evaluate({ message: message, title: this.Title }));
		Effect.Shake(this.Container.id);
		if (message.length > 60)
		{
			this.Container.setStyle({ height: this.Height + 10 });
		}
		else
		{
			this.Container.setStyle({ height: this.Height });
		}
		this.Display();
	},
	AppendAndDisplayWarning: function(message)
	{
		var errorTemplate = new Template('<strong>#{title}</strong><br/><ul><li>#{message}</li></ul>');
		this.Container.update(errorTemplate.evaluate({ message: message, title: "Please Note:" }));
		Effect.Shake(this.Container.id);
		if (message.length > 60)
		{
			this.Container.setStyle({ height: this.Height + 10 });
		}
		else
		{
			this.Container.setStyle({ height: this.Height });
		}
		this.Display();
	},
	Display: function()
	{
		this.Container.show();
		this.BuyButtonTable.hide();
		this.BuyButtonTable1.hide();
	},
	Hide: function()
	{
		this.Container.hide();
		this.BuyButtonTable.show();
		this.BuyButtonTable1.show();
	}
});

Mondial.Ajax.Request = Class.create(Ajax.Request,
{
	_request : null,
	_respondToReadyState : null,
	running : false,
	autoCancel : true,
	
	///Prototype Init Function - Called when object created
	initialize : function($super, options)
	{
		this._request = this.request;
		this._respondToReadyState = this.respondToReadyState;
		this.request = Prototype.emptyFunction;
		$super(options);
		
		this.respondToReadyState = (function(readyState)
		{
			this.running = false;
			this._respondToReadyState(readyState);
		});
	},
	send : function (url)
	{
		if(this.autoCancel) this.cancel();
		this.running = true;
		this._request(url);		
	},
	cancel: function()
	{
		if(this.running)
		{
			this.running = false;
			this.transport.onreadystatechange = Prototype.emptyFunction;
			this.transport.abort();
		}
	}
});

Mondial.BaseService = Class.create(
{
	Request : null,
	RequestTimeout : 20, //Timeout in seconds
	aborted : false,
	Url : "",
	requestTimer : null,
	running : false,
	onComplete : null,
	onError : null,
	onStart : null,
	onNotFound : null,
	onTimeout : null,
	
	///Prototype Init Function - Called when object created
	initialize : function(url, onComplete, onError, onNotFound, onStart, onTimeout)
	{
		this.URL = url;
		this.onComplete = onComplete;
		this.onError = onError;
		this.onStart = onStart;
		this.onNotFound = onNotFound;
		this.onTimeout = onTimeout;
	},
	internalSubmit : function(url, method)
	{
		//If we have an existing request, abort it
		this.abortRequest();
		
		this.aborted = false;
		
		this.clearTimeout();
		
		//Make a call to the start function
		if(this.onStart) this.onStart();
		
		var modTime = "&MT=" + Math.random();
		
		this.setAbortRequestTimeout();
									
		this.Request = new Ajax.Request(url + modTime,
		{
			method      : method,
			onSuccess   : this.onSuccess.bind(this),
			on404       : this.onNotFound.bind(this),
			onFailure   : this.onError.bind(this)
		});
	},
	onException : function(e)
	{
		
	},
	abortRequest : function()
	{
		if(this.Request != null && this.Request.getStatus() != 200)
		{
		  this.aborted = true;
		  this.Request.transport.onreadystatechange = Prototype.emptyFunction;
			this.Request.transport.abort();
		}
	},
	clearTimeout : function()
	{
		if(this.requestTimer)
		{
			window.clearTimeout(this.requestTimer);
		}
	},
	onSuccess : function(response)
	{
		this.clearTimeout();
		if(this.aborted)
		{
			this.onTimeout(response).bind(this);
		}
		else if(this.Request.success())
		{
			this.onComplete(response).bind(this);
		}
	},
	setAbortRequestTimeout : function()
	{
		this.requestTimer = window.setTimeout((function() {this.abortRequest()}).bind(this), this.RequestTimeout * 1000);
	}
});

Mondial.StandardQuoteService = Class.create(Mondial.BaseService,
{
	///Prototype Init Function - Called when object created
	initialize: function($super, url, onComplete, onError, onNotFound, onStart, onTimeout)
	{
		$super(url, onComplete, onError, onNotFound, onStart, onTimeout);
	},
	Submit: function(intAdults, intDependants, strDestination, strStartDate, strEndDate, masterPlans)
	{
		var planIDs = "";

		var len = masterPlans.length;
		for (var i = 0; i < len; i++)
		{
			planIDs = planIDs + masterPlans[i].Id + ";";
		}

		var urlParams = "&A=" + intAdults + "&C=" + intDependants + "&R=" + strDestination + "&SD=" + strStartDate + "&ED=" + strEndDate + "&P=" + planIDs;

		this.internalSubmit(this.URL + "?op=QUOTE" + urlParams, 'GET');
	}
});

Mondial.SABQuoteService = Class.create(Mondial.BaseService,
{
	///Prototype Init Function - Called when object created
	initialize: function($super, url, onComplete, onError, onNotFound, onStart, onTimeout)
	{
    $super(url, onComplete, onError, onNotFound, onStart, onTimeout);
	},
	Submit : function(intAdults, intDependants, strDestination, strSelection, strDOB, strStartDate, strEndDate, strPESelected)
	{
		var urlParams = "&A="+intAdults+"&C="+intDependants+"&R="+strDestination+"&S="+strSelection+"&SD="+strStartDate+"&ED="+strEndDate + "&DOB=" + strDOB + "&PE=" + strPESelected;
		this.internalSubmit(this.URL + "?op=CALC" + urlParams, 'GET');
	}
});

Mondial.SABOptionsService = Class.create(Mondial.BaseService,
{
	///Prototype Init Function - Called when object created
	initialize: function($super, url, onComplete, onError, onNotFound, onStart, onTimeout)
	{
    $super(url, onComplete, onError, onNotFound, onStart, onTimeout);
	},
	Submit : function(intAdults, intDependants, strDestination, strStartDate, strEndDate)
	{
		var urlParams = "&A=" + intAdults + "&C=" + intDependants+ "&R=" + strDestination + "&SD=" + strStartDate + "&ED=" + strEndDate + "&DOB=0";
		
		this.internalSubmit(this.URL + "?op=OFETCH" + urlParams, 'GET');
	}
});

Mondial.SliderState = Class.create(
{
	Id : -1, 
	SelectedIndex : -1,
	SelectedValue : 0, 
	IsToggle : false,
	ToggleValue : false,
	
	///Prototype Init Function - Called when object created
	initialize : function(id, selectedIndex, selectedValue, isToggle, toggleValue)
	{
		this.Id = id;
		this.SelectedIndex = selectedIndex;
		this.SelectedValue = selectedValue;
		this.IsToggle = isToggle;
		this.ToggleValue = toggleValue;
	}
});

Mondial.SABControl = Class.create(Mondial.Options,
{
	Id: 0,
	Slider: null,
	IsEnabled: true,
	IsDomestic: false,
	Benefits: null,
	ToggleOnly: false,
	DefaultBenefit: null,
	IsExcessType: false,
	BenefitSelection: null,
	ToolTip: null,
	HiddenBenefitField: null,
	PremiumDiv: null,
	SliderContainer: null,
	BenefitLink: null,
	BenefitLinkHeading: null,
	WindowWidth: 0,
	BenefitSpacerSize: 0,
	DefaultBenefitIndex: -1,
	Container: null,
	options:
	{
		sliderSize: 396,
		sliderHandleImg: '',
		questionMark: '',
		sliderLeftHandle: '',
		sliderRightHandle: ''
	},
	///Prototype Init Function - Called when object created
	initialize: function(ctlId, enabled, container, benefits, toggleOnly, options)
	{
		this.Id = ctlId;
		this.Benefits = benefits;
		this.ToggleOnly = toggleOnly;
		this.Container = $(container);
		this.IsEnabled = enabled;

		this.setOptions(options);

		if (Prototype.Browser.IE)
		{
			this.WindowWidth = document.body.offsetWidth - 20;
		}

		if (this.IsEnabled)
		{
			this.LoadBenefits();
		}
	},
	LoadBenefits: function()
	{
		var defaultBenefit = null;
		var defaultBenefitIndex = -1;
		var benefitIds = [];
		var intValue = 0;
		var sliderVals = [];

		if (this.Benefits.length > 1)
		{
			// distance between tick marks
			this.BenefitSpacerSize = this.options.sliderSize / (this.Benefits.length - 1);
		}
		else
		{
			this.BenefitSpacerSize = this.options.sliderSize;
		}

		var spacerSize = parseInt(this.BenefitSpacerSize, 10);

		this.Benefits.each(function(b, i)
		{
			if (b.IsDefault)
			{
				defaultBenefit = b;
				defaultBenefitIndex = i;
			}
			benefitIds.push(b.Id);
			sliderVals.push(intValue);
			intValue = parseInt(intValue, 10) + spacerSize;
		});

		sliderVals[sliderVals.length - 1] = this.options.sliderSize;

		this.CurrentSliderIndex = defaultBenefitIndex;
		this.DefaultBenefit = defaultBenefit;
		this.DefaultBenefitIndex = defaultBenefitIndex;
		this.DefaultSliderValue = this.DefaultBenefitIndex * this.BenefitSpacerSize;
		this.SliderValues = sliderVals;
		this.DefaultSliderValue = parseInt(this.DefaultSliderValue, 10);
	},
	BuildSlider: function()
	{
		//Use slider size so slider goes all the way to the end incase increments are not even
		this.Slider = new Control.Slider('slider-handle' + this.Id, 'slider' + this.Id, { onChange: this.onBenefitChange.bind(this), range: $R(0, this.options.sliderSize), startSpan: "slider_span" + this.Id, values: this.SliderValues, sliderValue: this.DefaultSliderValue });
		//Change this so control has reference to these controls
		if (this.IsExcessType)
		{
			this.BenefitSelection.value = "EXCESS|" + this.DefaultBenefit.Id + "|F|" + this.DefaultBenefit.Amount;
		}
		else
		{
			this.BenefitSelection.value = "BENEFIT|" + this.Id + "|" + (this.DefaultBenefit.ToggleValue ? "T" : "F") + "|" + this.DefaultBenefit.Amount;
		}
		this.ToolTip.title = "Benefit value = " + (this.DefaultBenefit.IsUnlimited ? "Unlimited" : this.DefaultBenefit.Amount);
		this.PremiumDiv.update("$" + this.DefaultBenefit.Premium);
		$("sliderPlus" + this.Id).observe('click', this.Slider.moveForward.bind(this.Slider));
		$("sliderMinus" + this.Id).observe('click', this.Slider.moveBack.bind(this.Slider));
	},
	NilExcess: function()
	{
		var hiddenBenefitField = Builder.node("input", { type: 'hidden', id: 'amt' + this.Id });

		DomUtils.appendChildren(this.Container, new Array(hiddenBenefitField), 'innerSliderContainer');

		this.BenefitSelection = $('amt' + this.Id);
		this.HiddenBenefitField = $('amt' + this.Id);
		this.PremiumDiv = null;
		this.SliderContainer = null;
		this.BenefitLink = null;
		this.BenefitLinkHeading = null;
		this.BenefitSelection.value = "EXCESS|" + this.DefaultBenefit.Id + "|F|" + this.DefaultBenefit.Amount;
	},
	Disable: function()
	{
		this.Slider.setDisabled();
	},
	Enable: function()
	{
		this.Slider.setEnabled();
	},
	Remove: function()
	{
		$("sliderControl" + this.Id).remove();
		if (this.HiddenBenefitField != null)
		{
			this.HiddenBenefitField.remove();
		}
	},
	onBenefitChange: function(v, s)
	{
		this.CurrentSliderIndex = s.getSelectedIndex();
		var benefit = this.getSelectedBenefit();

		if (this.ToggleOnly)
		{
			if (this.CurrentSliderIndex > 1)
			{
				this.CurrentSliderIndex = 1;
			}
		}

		this.ToolTip.title = "Benefit value = " + benefit.Amount;

		if (this.IsExcessType)
		{
			var excess_val = benefit.Id;
			this.BenefitSelection.value = "EXCESS|" + excess_val + "|F|" + benefit.Amount;
		}
		else
		{
			var bTFlag = "F";

			if (this.ToggleOnly)
			{
				bTFlag = (this.CurrentSliderIndex == 0) ? "F" : "T";
			}
			this.BenefitSelection.value = "BENEFIT|" + this.Id + "|" + bTFlag + "|" + benefit.Amount;
		}

		this.onCalculate();
	},
	getSelectedAmount: function()
	{
		return this.Benefits[this.CurrentSliderIndex].Amount;
	},
	getSelectedBenefit: function()
	{
		return this.Benefits[this.CurrentSliderIndex];
	},
	getSliderState: function()
	{
		//When there is no excess, then null returned - so state for this is not saved
		if (this.IsExcessType && this.Benefits.length == 1)
		{
			return null;
		}
		else if (this.IsEnabled)
		{
			var benefit = this.getSelectedBenefit();

			var toggleValue = false;
			if (this.ToggleOnly)
			{
				toggleValue = (this.CurrentSliderIndex == 0) ? false : true;
			}

			return new Mondial.SliderState(this.Id, this.CurrentSliderIndex, benefit.Amount, this.ToggleOnly, toggleValue);
		}
		return new Mondial.SliderState(this.Id, -1, 0, false, false);
	},
	setSelectedBenefit: function(val, triggerOnChange)
	{
		var index = 0;
		this.Benefits.each(function(b, i)
		{
			if (this.Benefts[i].value == val)
			{
				index = i;
			}
		});

		//Remove 
		this.Slider.setSelectedIndex(index, triggerOnChange);
	},
	restoreSliderState: function(state)
	{
		if (state != null)
		{
			this.onCalculate = Prototype.emptyFunction;
			try
			{
				if (this.Slider.getSelectedIndex() != state.SelectedIndex)
				{
					this.Slider.setSelectedIndex(state.SelectedIndex, true);
				}
			}
			catch (e)
			{
				alert(e);
			}
		}
	},
	//Values are only for a 396px slider - Return Different values for IE6
	getPadding: function(noOfBenefits)
	{
		if (noOfBenefits == 7)
		{
			return Mondial.Browser.IE6 ? [-9, 52, 111, 171, 234, 294, 355] : [-9, 52, 111, 171, 234, 294, 355];
		}
		else if (noOfBenefits == 6)
		{
			return Mondial.Browser.IE6 ? [-9, 64, 136, 208, 280, 355] : [-9, 64, 136, 208, 280, 355];
		}
		else if (noOfBenefits == 5)
		{
			return Mondial.Browser.IE6 ? [-9, 81, 173, 263, 355] : [-9, 81, 173, 263, 355];
		}
		else if (noOfBenefits == 4)
		{
			return Mondial.Browser.IE6 ? [-9, 100, 200, 365] : [-9, 100, 200, 365];
		}
		else if (noOfBenefits == 3)
		{
			return Mondial.Browser.IE6 ? [-9, 173, 355] : [-9, 173, 355];
		}
		else
		{
			return [-9, 355];
		}
	},
	onCalculate: function()
	{
		alert("TODO: wire up this function(event) when used.");
	},
	BuildSliderDiv: function(name)
	{
		if (this.IsEnabled)
		{
			this.BuildEnabledSliderDiv(name);
		}
	},
	BuildEnabledSliderDiv: function(strName)
	{
		var hiddenBenefitField = Builder.node("input", { type: 'hidden', id: 'amt' + this.Id });
		var arrNodes = [];
		var sliderSize = this.BenefitSpacerSize;
		var padding = this.getPadding(this.Benefits.length);

		if (this.ToggleOnly)
		{
			arrNodes.push(Builder.node('div', { className: 'sliderBenefitValue', style: 'left:' + padding[0] + 'px;' }, "No"));
			arrNodes.push(Builder.node('div', { className: 'sliderBenefitValue', style: 'left:' + padding[1] + 'px;' }, "Yes"));
		}
		else
		{
			// Build the values under the slider
			this.Benefits.each(function(b, i)
			{
				var amt = b.Amount;
				if (b.IsUnlimited)
				{
					amt = "Unlimited";
				}

				if (b.Amount == 0)
				{
					amt = "0";
				}

				var node = (b.IsDefault ? Builder.node("strong", [amt]) : amt);

				arrNodes.push(Builder.node('div', { className: 'sliderBenefitValue', style: 'left:' + padding[i] + 'px;' }, node));
			});
		}

		var container = Builder.node('table', { id: "sliderControl" + this.Id, border: 0, className: 'sliderControl', cellSpacing: 0, cellPadding: 0 },
		[
			Builder.node('tr', {},
			[
				Builder.node('td', { height: '20', width: '437', colspan: 2 },
				[
					Builder.node('a', { id: "benefitsLink" + this.Id, className: 'standardLink sabToolTip', href: '', style: 'float:left;padding-left:4px;margin-right:3px;' },
					[
					  Builder.node('img', { id: "benefitsLinkImg" + this.Id, src: this.options.questionMark, border: 0, style: "float:left;" })
					]),
					Builder.node('a', { id: "benefitsLinkHeading" + this.Id, href: '', className: 'sliderTitle', style: 'float:left' }, [strName])
				])
			]),
			Builder.node('tr', {},
			[
				Builder.node('td', {},
				[
				  Builder.node('table', { border: 0, style: 'width:445px;height:30px;', cellPadding: 0, cellSpacing: 0 },
					[
						Builder.node('tr', {},
						[
							Builder.node('td', { height: '100%', width: '23' },
							[
							  Builder.node('img', { id: "sliderMinus" + this.Id, src: this.options.sliderLeftHandle, border: 0, style: 'position:relative;top:-2px;left:1px;cursor:pointer;' })
							]),
							Builder.node('td', { height: '100%', width: '381' },
							[
							  Builder.node('div', { id: "contbox" + this.Id, className: 'sliderInternalDiv' },
					      [
						      Builder.node('div', { id: "slider" + this.Id + "-tooltip", style: "left:0px;", title: "Slider" + this.Id, tabIndex: -1 }),
						      Builder.node('div', { id: "slider_wrap" + this.Id, style: 'width: ' + this.options.sliderSize + 'px;', className: 'sliderWrap' },
						      [
							      Builder.node('span', { id: "slider_span" + this.Id, className: 'sliderShader' }),
							      Builder.node('div', { id: "slider_right" + this.Id, style: 'position: absolute; text-align: right; width: ' + this.options.sliderSize + 'px;' }, ['']),
							      Builder.node('div', { id: "slider_left" + this.Id, style: 'position: absolute; width: ' + this.options.sliderSize + 'px;' }, ['']),
							      Builder.node('div', { id: "slider" + this.Id, className: 'sliderBody', style: 'width: ' + this.options.sliderSize + 'px; height: 10px; position: absolute;' },
							      [
								      Builder.node('div', { id: "slider-handle" + this.Id, style: "width: 33px; height: 15px; cursor: col-resize;" },
								      [
									      Builder.node('img', { src: this.options.sliderHandleImg, style: "float:left;" })
								      ])
							      ])
						      ])
					      ]),
					      Builder.node('div', { id: "sliderBenefidContainer" + this.Id, className: 'sliderBenefitContainer' }, [arrNodes])
							]),
							Builder.node('td', { height: '100%', width: '23' },
							[
							  Builder.node('img', { id: "sliderPlus" + this.Id, src: this.options.sliderRightHandle, border: 0, style: 'position:relative;top:-2px;right:3px;cursor:pointer;' })
							])
						])
					])
				]),
				Builder.node('td', {},
				[
					Builder.node('div', { id: "calcval" + this.Id, className: 'sliderPremium' }, ["$0.00"])
				])
			]),
			Builder.node('tr', {},
			[
				Builder.node('td', { colspan: 2 },
				[
					Builder.node('div', { id: "sliderSummary" + this.Id, className: 'sliderSummaryDiv' })
				])
			]),
		]);

		DomUtils.appendChildren(this.Container, new Array(container, hiddenBenefitField), 'innerSliderContainer');

		if (Prototype.Browser.IE)
		{
			//Correct slider offset as IE calculates this differently to other browsers
			$("slider" + this.Id).style.left = $("slider" + this.Id).offsetLeft;
		}

		this.ToolTip = $("slider" + this.Id + "-tooltip");
		this.BenefitSelection = $('amt' + this.Id);
		this.HiddenBenefitField = $('amt' + this.Id);
		this.PremiumDiv = $("calcval" + this.Id);
		this.SliderContainer = $("sliderBenefidContainer" + this.Id);
		this.BenefitLink = $("benefitsLink" + this.Id);
		this.BenefitLinkHeading = $("benefitsLinkHeading" + this.Id);
		if (this.IsExcessType)
		{
			$("sliderSummary" + this.Id).update(this.IsDomestic ? $("benefitSummaryExcessDomestic").innerHTML : $("benefitSummaryExcess").innerHTML);
		}
		else
		{
			$("sliderSummary" + this.Id).update(this.IsDomestic ? $("benefitSummaryDomestic" + this.Id).innerHTML : $("benefitSummary" + this.Id).innerHTML);
		}
		
		var benefitClick = function(e)
		{
			e.stop();
			var summary = $("sliderSummary" + this.Id);
			summary.toggle();
			$("benefitsLinkImg" + this.Id).src = summary.visible() ? '/images/minus.gif' : '/images/plus.gif';
			var setHeight = $('sabContainerDiv').getHeight() - 350;
			$('footer').setStyle({ top: setHeight + 'px' });
		};

		this.BenefitLinkHeading.observe('click', benefitClick.bind(this));
		this.BenefitLink.observe('click', benefitClick.bind(this));
		
		$("sliderSummary" + this.Id).hide();
	}
});

var DomUtils =
{
	removeChildElements : function(c)
	{
		while (c.hasChildNodes())
		{
			c.removeChild(c.firstChild);
		}
	},
	appendChild : function (parent, elm, id)
	{
		if(Prototype.Browser.IE)
		{
			//Workaround bug in IE
			var y = document.createElement('div');
			y.id = id;
			y.innerHTML = elm.outerHTML;
			parent.appendChild(y);
		}
		else
		{
			parent.appendChild(elm);
		}
	},
	appendChildren : function (parent, elements, id)
	{
		if(Prototype.Browser.IE)
		{
			//Workaround bug in IE
			var y = document.createElement('div');
			y.id = id;
			elements.each(function(elm)
			{
				y.innerHTML = y.innerHTML + elm.outerHTML;
			});
			parent.appendChild(y);
		}
		else
		{
			elements.each(function(elm)
			{
				parent.appendChild(elm);
			});
		}
	},
	createPNGFixedStyle : function(imgURL, style)
	{
		return Mondial.ApplyPNGFix ? style + "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgURL + "', sizingMethod='scale');background-image:none;" : style;
	}
};

var CookieUtil =
{
	//Functions from http://www.quirksmode.org/js/cookies.html
	createCookie: function(name, value, days)
	{
		if (days)
		{
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			var expires = "; expires=" + date.toGMTString();
		}
		else var expires = "";

		document.cookie = name + "=" + value + expires + "; path=/";
	},
	readCookie: function(name)
	{
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		var len = ca.length;
		for (var i = 0; i < len; i++)
		{
			var c = ca[i];
			while (c.charAt(0) == ' ') c = c.substring(1, c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
		}
		return null;
	},
	eraseCookie: function(name)
	{
		this.createCookie(name, "", -1);
	}
};

Mondial.CookieHandler = Class.create(
{
	initialize : function()
	{
		
	},
	load : function()
	{
		var content = CookieUtil.readCookie(Mondial.SAB_COOKIE_NAME);
		if(content != null)
		{
			var quoteCookie = new Mondial.QuoteCookie();
			var obj = unescape(content).evalJSON(true);
			quoteCookie.Update(obj);
			return quoteCookie;
		}
		return null;
	},
	save : function(quoteCookie)
	{
		var jsonQuote = escape(Object.toJSON(quoteCookie));
		CookieUtil.createCookie(Mondial.SAB_COOKIE_NAME, jsonQuote);
	}
});