/*
 * QuoteEngine.js - Travel Insurance Quote Engine
 * Written by AMaitland
 * Copyright © 2011 Allianz Global Assistance Australia
 * Version 1.2
 */
 
Mondial =
{
	IEBrowserVersion : parseFloat(navigator.appVersion.split('MSIE')[1]),
	Browser:
	{
		IEBrowserVersion : parseFloat(navigator.appVersion.split('MSIE')[1]),
		IE6 : (this.IEBrowserVersion >= 5.5) && (this.IEBrowserVersion < 7)
	},
	AnalyticsTrackEvent : function (tracker, category, action, optional_label, optional_value)
	{
		if (_gaq != null)
		{
			_gaq.push(['_trackEvent', category, action, optional_label, optional_value]);
		}
	},
	PNGFix : function (className)
	{
	  try
	  {
	    if(Mondial.Browser.IE6)
      {
        $$(className).each(function(elm)
        {
          var img = elm.descendants()[0];
          
          img.setStyle({filter : 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)'});

          elm.setStyle({filter : "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + img.src + "')", display : 'inline-block' });
        });
      }
    }
    catch(e)
    {
    }
	},	
	ApplyPNGFix : ((this.IEBrowserVersion >= 5.5) && (this.IEBrowserVersion < 7) && (document.body.filters)),
	//Create Mondial.Ajax namespace
	Ajax : {}
};

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. Policys 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 = "End date is invalid. Policys end dates must be between " + this.Today.ToString() + " and " + dteEnd.MaxRange;
			return false;
		}
		if(!dteEnd.IsGreater(dteStart.ToString()))
		{
			this.ValidateMessage = "End date is invalid. End date must come after the 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 = intMaxLength;
		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. Policys 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 = "End date is invalid. Policys end dates must be between " + this.Today.ToString() + " and " + dteEnd.MaxRange;
			return false;
		}
		if (!dteEnd.IsGreater(dteStart.ToString()))
		{
			this.ValidateMessage = "End date is invalid. End date must come after the start date.";
			return false;
		}

		if (!this.ValidateMaxLength(this.MaxLength, this.MaxLengthUnit))
		{
			this.ValidateMessage = "Policy Length cannot exceed " + this.MaxLength + " " + this.MaxLengthUnit + "(s)";
			return false;
		}

		return true;
	},
	ValidateMaxLength: function()
	{
		var dteStartDate = this.StartDate.GetSimpleDate().GetDate();
		var dteEndDate = this.EndDate.GetSimpleDate().GetDate();

		var syear = 0;

		if (/year/.test(this.MaxLengthUnit))
		{
			// 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(this.MaxLengthUnit))
		{
			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(this.MaxLengthUnit))
		{
			var length = parseInt(this.MaxLength, 10);
			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 (yyyy-MM-dd)</param>
  initialize : function(ddDay, ddMonthYear, strInitialDate)
	{
		this.DDDay = $(ddDay);
		this.DDMonthYear = $(ddMonthYear);
		this.InitialDate = new Mondial.SimpleDate().ParseJSONString(strInitialDate);
		this.updateMonthOnLoad(this.InitialDate.ToMonthYearStr(), this.InitialDate.Day);
	},
	GetSimpleDate : function ()
	{
		return new Mondial.SimpleDate().ParseTwoPartDate(this.DDDay.value, this.DDMonthYear.value);
	},
	updateDate : function (strDate)
	{
	  this._updateDate(new Mondial.SimpleDate().ParseString(strDate));
	},
	_updateDate : function (dte)
	{
		var strMonthYear = dte.ToMonthYearStr();
		
		for(var i = 0; i < this.DDDay.options.length; i++)
		{
			if(parseInt(this.DDDay.options[i].value, 10) == dte.Day)
			{
				this.DDDay.options[i].selected = true;
			}
		}
		
		for(var i = 0; i < this.DDMonthYear.options.length; 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;
		
			for(var i = 0; i < arrDates.length; 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)
	{
		this.ParseTwoPartDate(1, strMonthYear);
		
		return this;
	},
	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;
	},
	//Parse the date string that is returned when an object in JSON serialized from .Net
	ParseJSONString : function(strDayMonthYear)
	{
		var dtCh = "-";
		var pos1 = strDayMonthYear.indexOf(dtCh);
		var pos2 = strDayMonthYear.indexOf(dtCh, pos1+1);
		this.Day = parseInt(strDayMonthYear.substring(pos2+1), 10);
		this.Month = parseInt(strDayMonthYear.substring(pos1+1, pos2), 10);
		this.Year = parseInt(strDayMonthYear.substring(0, pos1), 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.ToString());
			var intMinOp = this.convertToInt(this.MinRange);
			var intMaxOp = this.convertToInt(this.MaxRange);
			
			return (intVal >= intMinOp) && (intVal <= intMaxOp);
		}
	},
	//Is given date greater than current SimpleDate
	IsGreater : function (strDate2)
	{
		var intDate1 = this.convertToInt(this.ToString());
		var intDate2 = this.convertToInt(strDate2);
		return (intDate1 >= intDate2);
	},
	GetFullYear : function(year, century, cutoffyear)
	{
		return (year + parseInt(century)) - ((year < cutoffyear) ? 0 : 100);
	},
	convertToInt : function (strDate)
	{
		var date = new Date();
		var dateorder = "dmy";
		var century = "2000";
		var cutoffyear = (date.getFullYear() + 10).toString();
		var num, cleanInput, m, exp;
		
		var yearFirstExp = new RegExp("^\\s*((\\d{4})|(\\d{2}))([-./])(\\d{1,2})\\4(\\d{1,2})\\s*$");
		m = strDate.match(yearFirstExp);
		var day, month, year;
		if (m != null && (m[2].length == 4 || dateorder == "ymd"))
		{
			day = m[6];
			month = m[5];
			year = (m[2].length == 4) ? m[2] : this.GetFullYear(parseInt(m[3], 10), century, cutoffyear)
		}
		else
		{
			if(dateorder == "ymd")
			{
				return null;
			}						
			var yearLastExp = new RegExp("^\\s*(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))\\s*$");
			m = strDate.match(yearLastExp);
			if (m == null)
			{
				return null;
			}
			if (dateorder == "mdy")
			{
				day = m[3];
				month = m[1];
			}
			else
			{
				day = m[1];
				month = m[3];
			}
			year = (m[5].length == 4) ? m[5] : this.GetFullYear(parseInt(m[6], 10), century, cutoffyear)
		}
		month -= 1;
		var date = new Date(year, month, day);
		return (typeof(date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null;
	},
	//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 : "",
	Age : 0,
	Excess : 3000,
	
	///Prototype Init Function - Called when object created
	initialize : function()
	{

	}
});

Mondial.QuoteControl = Class.create(
{
	//Reference to event handler functions
	OnDestinationChange : null,
	
	///Prototype Init Function - Called when object created
	initialize : function(startDay, startMonthYear, endDay, endMonthYear, destination, adults, dependants, initialStartDate, initialEndDate)
	{
		//Controls
		this.StartDay = $(startDay);
		this.StartMonthYear = $(startMonthYear);
		this.EndDay = $(endDay);
		this.EndMonthYear = $(endMonthYear);
		this.StartDate = new Mondial.DMYControl(startDay, startMonthYear, initialStartDate);
		this.EndDate = new Mondial.DMYControl(endDay, endMonthYear, initialEndDate);
		this.Destination = $(destination);
		this.Adults = $(adults);
		this.Children = $(dependants);
	},
	getQuote : function()
	{
		var quote = new Mondial.Quote();
	
		quote.Destination = this.getDDValue(this.Destination);
		quote.Adults = this.getDDValue(this.Adults);
		quote.Dependants = this.getDDValue(this.Children);
		quote.StartDate = this.StartDay.value + '/' + this.StartMonthYear.value;
		quote.EndDate = this.EndDay.value + '/' +  this.EndMonthYear.value;

		return quote;
	},
	clearEvents : function()
	{
		if(this.OnDestinationChange != null) Event.stopObserving(this.Destination, "change", this.OnDestinationChange);
	},
	setOnDestinationChange : function(handler)
	{
		if(this.OnDestinationChange != null)
		{
			Event.stopObserving(this.Destination, "change", this.OnDestinationChange);
		}
		this.OnDestinationChange = handler;		
		this.Destination.observe("change", handler);
	},
	getDestination : function()
	{
		return this.getDDValue(this.Destination);
	},
	getDDValue : function (control)
	{
		return control.options[control.selectedIndex == -1 ? 0 : control.selectedIndex].value;
	}
});

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)
		});
	},
	abortRequest : function()
	{
		if(this.Request != null && !this.Request.success())
		{
			this.aborted = true;
			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, planIDs)
	{
		var urlParams = "&A=" + intAdults + "&C=" + intDependants+ "&R=" + strDestination + "&SD=" + strStartDate + "&ED=" + strEndDate + "&P=" + planIDs;
		
		this.internalSubmit(this.URL + "?op=COMPCANCELQUOTE" + urlParams, 'GET');
	}
});

Mondial.PlanControl = Class.create(
{
	SelectedPlan : null,
	Premium : 0.00,
	Destination : "WORLDWIDE",
	OnBuyClick : null,
	BuyNowImage : '',
	MasterPlan : null,
	Enabled : true,
	
	///Prototype Init Function - Called when object created
	initialize : function(masterPlan, container, imagesDir, destination)
	{
		this.Id = "planControl" + masterPlan.Id;
		this.MasterPlan = masterPlan;
		
		//International
		this.PremiumDiv = $(this.Id + "_premium");
		//Domestic
		this.PremiumDivDom = $(this.Id + "_premium_dom");
		this.BuyLink = $(this.Id + "_buyLink");
		this.BuyLinkDom = $(this.Id + "_buyLink_dom");
		this.BuyLink.observe("click", this.buy_click.bind(this));
		if(this.BuyLinkDom) this.BuyLinkDom.observe("click", this.buy_click.bind(this));
	},
	setPremium : function(premium)
	{
		var div = this._isDomestic(this.Destination) ? this.PremiumDivDom : this.PremiumDiv;
		
		if(premium == "0.00")
		{
			div.update("N/A");
			this.BuyLink.hide();
		}
		else
		{
			div.update("$" + premium);
			this.BuyLink.show();
		}
	},
	_isDomestic : function (destination)
	{
		return destination.toUpperCase() == "NEW ZEALAND";
	},
	setDestination : function(destination)
	{
		this.Destination = destination;
		var masterPlan = this.MasterPlan;
		this.SelectedPlan = null;
	
		if(masterPlan.HasMultipleRegions)
		{
			this.SelectedPlan = this._findPlan(masterPlan, destination);
		}
		else
		{
			this.SelectedPlan = masterPlan.AvaliablePlans[0];
		}
		
		this.Enabled = this.SelectedPlan.Enabled;
	},
	_findPlan : function(masterPlan, destination)
	{
		for(var i = 0; i < masterPlan.AvaliablePlans.length; i++)
		{
			var childPlan = masterPlan.AvaliablePlans[i];
			for(var j = 0; j < childPlan.Destinations.length; j++)
			{
				if(childPlan.Destinations[j].Value.toUpperCase() == destination.toUpperCase())
				{
					return childPlan;
				}
			}
		}
		
		return null;
	},
	getValidator : function(quoteControl, today, todayPlusOneYear, todayPlusTwoYears)
	{
		return new Mondial.QuoteValidator(quoteControl.StartDate, quoteControl.EndDate, new Mondial.SimpleDate().ParseString(today), new Mondial.SimpleDate().ParseString(todayPlusOneYear), new Mondial.SimpleDate().ParseString(todayPlusTwoYears), this.SelectedPlan.MaxLength, this.SelectedPlan.MaxLenghtUnit);
	},
	setOnBuyClick : function(handler)
	{
		this.OnBuyClick = handler;
	},
	buy_click : function(e)
	{
		e.stop();
		if(this.OnBuyClick != null)
		{
			this.OnBuyClick(this.MasterPlan);
		}
	}
});
