/*
 * Copyright(c) 2008, www.softidiom.com.
 */

//load ext overrides - patches to 2.1
document.write('<script type="text/javascript" src="/site/js/ext_overrides.js"><\/script>');
Ext.Ajax.timeout = 180000;   //set default timeout to 3 minutes
var renderedPackages = false;
var packages = [];
var selectedPackage, oldPackage, nextStep, tabs, quotedWin, ecodedPassword, active_email, active_password, soc, event_code_info, socDiv;
var steps = ['Quick Quote','Your Details','Regulation','About the Event','Declaration'];
var step = 'Quick Quote';
var stepIndex = 0;
var loggedIn = false;
var currencySymbol = '£';
var validEventCode = '';
var new_email_valid = false;
var new_email_value = "";
var new_customer = true;
var dates_invalid = true;
var ignoreDateValidEvents = false;
var currency_ds, form;
var affiliateCookieName = "_ea_affiliate";
var affiliateCode = "";
var affiliateCodeReq = "";
affiliateCodeReq = (Request.QueryString("affiliate")).toString();
if (affiliateCodeReq !== null) {
	Delete_Cookie( affiliateCookieName, '/', null );
	Set_Cookie( affiliateCookieName, affiliateCodeReq, null, '/', null, null );
}
if (Get_Cookie(affiliateCookieName)) {
	affiliateCode = Get_Cookie(affiliateCookieName);
}

Ext.BLANK_IMAGE_URL = '/shared/ext/2.0/resources/images/default/s.gif';
Ext.QuickTips.init(); 
//Ext.form.Field.prototype.msgTarget = 'side'; 

Ext.onReady(function(){
	//data stores
	postalCountry_ds = new Ext.data.JsonStore({
  	  url: '/site/phpeventassured/getcountrylist.php',
  	  root: 'list',
  	  baseParams:{type: 'postal'},
  	  fields: [{name:'country', type: 'string'} ]
	});
	postalCountry_ds.load(); 
	venueCountry_ds = new Ext.data.JsonStore({
  	  url: '/site/phpeventassured/getcountrylist.php',
  	  root: 'list',
  	  baseParams:{type: 'venue'},
  	  fields: [{name:'country', type: 'string'} ]
	});
	venueCountry_ds.load(); 
	jurisdictionCountry_ds = new Ext.data.JsonStore({
  	  url: '/site/phpeventassured/getcountrylist.php',
  	  root: 'list',
  	  baseParams:{type: 'jurisdiction'},
  	  fields: [{name:'country', type: 'string'} ]
	});
	jurisdictionCountry_ds.load(); 
	
	currency_ds = new Ext.data.SimpleStore ({
		fields: [ "name","description" ],
		data: [['Currency Pound Sterling','GBP - Pounds Sterling (£)'],['Currency Euros','EURO - Euros (€)'],['Currency American Dollars','USD - US Dollars ($)']]
	});
	
    form = new Ext.FormPanel( 
		{
		xtype:"form",
		labelWidth: 300,
		width: 800,
		buttons: [{
	        text: 'Previous Step',
	        id: 'previousButton',
	        disabled: true,
	        handler: previousStep
	    },{
	        text: 'Next Step',
	        id: 'nextButton',
	        handler: nextStep
	    }],
		items:[{
		    xtype:"tabpanel",
		    id: 'tabs',
		    deferredRender: false,
		    activeTab:0,
		    //defaults:{hideMode:'visibility'},
			items:[{
			    xtype:"panel",
			    title:"Quick Quote",
			    id: 'Quick Quote',
			    //autoScroll:true,
			    bodyStyle: 'padding: 8px;background:#EBF3FC',
			    height: 630,
			    items:[{
			        xtype:"fieldset",
			        title:"Choose your currency",
			        autoHeight:true,
			        items:[{
			            xtype:"combo",
			            fieldLabel:"What currency would you like the insurance in?",
			            name: 'currency',
			            id: 'currency',
			            value: 'Currency Pound Sterling',
			            editable: false,
						triggerAction: 'all',
			            mode: 'local',
						listClass: 'x-combo-list-small',
						width: 170,
						valueField: 'name',
						displayField: 'description',
						store: currency_ds
			          }]
			      },{
			        xtype:"fieldset",
			        title:"Event Code",
			        autoHeight:true,
			        items:[{
			            xtype:"textfield",
			            fieldLabel:"Event code (if you have one) <img id='eventCode_help' class='fieldHelp' src='/shared/images/icons/help.gif'/>",
			            name:"eventCode",
			            id: 'eventCode',
						width: 170,
						maxLengthText: 10,
						value: (Request.QueryString("event")).toString(),
						//allowBlank: true,
						validator: function(value) {
							return eventCodeValidator(value);
							/*Ext.Ajax.request({
							   url: '/php/getEventCodeInfoAndPackages.php',
							   params: 'eventCode='+value,
							   success: function(response, opts) {
									event_code_info = Ext.util.JSON.decode(response.responseText);
									packages = event_code_info.packages;
									if (renderedPackages == true) {
										refreshPackages();
									}else{
										renderedPackages = true;
										packagesLoaded();
									}
									if(event_code_info.Error) {
										Ext.getCmp('eventCode').markInvalid('This event code is not valid. Enter a new code or clear this field.');
										Ext.getCmp('venueCountry').enable();
										Ext.getCmp('event_name').enable();
										Ext.getCmp('opening_date').enable();
										Ext.getCmp('closing_date').enable();
										Ext.getCmp('venue').enable();
										Ext.getCmp('venue_county').enable();
										Ext.getCmp('venue_town').enable();
										Ext.getCmp('organiser').enable();
										event_code_info = null;
										validEventCode = '';
										refreshQuote();
									} else {
										//update fields based on the event code
										Ext.getCmp('venueCountry').setValue(event_code_info.Country);
										Ext.getCmp('venueCountry').disable();
										Ext.getCmp('event_name').setValue(event_code_info.EventName);
										Ext.getCmp('event_name').disable();
										Ext.getCmp('opening_date').setValue(Date.parseDate(event_code_info.OpeningDate,'j/n/Y'));
										Ext.getCmp('opening_date').disable();
										Ext.getCmp('closing_date').setValue(Date.parseDate(event_code_info.ClosingDate,'j/n/Y'));
										Ext.getCmp('closing_date').disable();
										Ext.getCmp('venue').setValue(event_code_info.MainVenue);
										Ext.getCmp('venue').disable();
										Ext.getCmp('venue_town').setValue(event_code_info.City);
										Ext.getCmp('venue_town').disable();
										Ext.getCmp('venue_county').setValue(event_code_info.County);
										Ext.getCmp('venue_county').disable();
										Ext.getCmp('organiser').setValue(event_code_info.EventOrganiserName);
										Ext.getCmp('organiser').disable();
										validEventCode = value;
										refreshQuote();
									}
							   },
							   failure: function(response, opts) {
							   	   alert('There has been a problem connecting to the server. This may be due to a problem with your Internet connection, or we could be performing maintenance on the server. Please try again. If you continue to experience problems, contact us for further assistance.');
							   }
							});
							return true; */
						}
			          }]
			      },{
			        xtype:"fieldset",
			        title:"Location",
			        autoHeight:true,
			        items:[{
			            xtype:"combo",
			            fieldLabel:"Where are you based? <img id='based_help' class='fieldHelp' src='/shared/images/icons/help.gif'/>",
			            name:"ContAdd7",
			            id: 'country',
						triggerAction: 'all',
						selectOnFocus:true,
						forceSelection: true,
			            allowBlank: false,
			            mode: 'local',
						listClass: 'x-combo-list-small',
						width: 170,
						valueField: 'country',
						displayField: 'country',
						store: postalCountry_ds
			          },{
			            xtype:"combo",
			            fieldLabel:"Where is the event being held? <img id='held_help' class='fieldHelp' src='/shared/images/icons/help.gif'/>",
			            name:"VenCountry",
			            id:'venueCountry',
						triggerAction: 'all',
						selectOnFocus:true,
						forceSelection: true,
			            allowBlank: false,
			            mode: 'local',
						listClass: 'x-combo-list-small',
						width: 170,
						valueField: 'country',
						displayField: 'country',
						store: venueCountry_ds
			          }]
			      },{
			        xtype:"fieldset",
			        title:"Choose your Package  <img id='package_help' class='fieldHelp' src='/shared/images/icons/help.gif'/>",
			        id: 'package',
			        labelWidth: 300,
			        items:[{
			            xtype:"checkbox",
			            fieldLabel:"Check here if Employers' Liability insurance is required",
			            name:"EALiabilityEL",
			            id: 'liability'
			          }
			        ]
			      },{
			        xtype:"fieldset",
			        title:"Your Premium",
			        id: 'quotation',
			        labelWidth: 75,
			        autoHeight:true,
			        items:[
						{
		                    xtype:'textfield',
		                    fieldLabel: 'Premium',
		                    name: 'premium',
				            id: 'premium',
		                    readOnly: true,
		                    width: 80
		                },
						{
		                    xtype:'textfield',
		                    fieldLabel: 'TAX',
		                    name: 'tax',
		                    id: 'tax',
		                    readOnly: true,
		                    width: 80
		                },
						{
		                    xtype:'textfield',
		                    fieldLabel: 'Total',
		                    name: 'total',
		                    id: 'total',
		                    readOnly: true,
		                    width: 80,
		                    style: 'font-weight: bold; color:#15428B; background: #CEDFF5 url(/shared/ext/2.0/resources/images/default/tabs/tab-strip-bg.gif) repeat-x scroll center bottom;'
		                },
						{
				            xtype:"textfield",
				            fieldLabel:"Description",
				            name:"description",
				            id: 'description',
				            value: 'Complete the fields above then select a package for an instant quotation',
				            readOnly: true,
							width: 660
						}
					]
			      }]
			  },{
			    xtype:"panel",
			    title:"Your Details",
			    id: 'Your Details',
				autoScroll: true,
			    bodyStyle: 'padding: 8px;background:#EBF3FC',
			    height: 630,
			    items:[{
			        xtype:"fieldset",
			        title:"Returning customer?",
			        id:'returningCustomer',
			        checkboxToggle: true,
			        collapsed: true,
			        labelWidth: 150,
			        autoHeight:true,
			        items:[{
			            xtype:"textfield",
			            fieldLabel:"Email Address",
			            name:"email",
			            id: 'email',
						width: 300
					},{
			            xtype:"textfield",
			            fieldLabel:"Password",
			            name:"password",
			            id: 'password',
			            inputType: 'password',
						width: 200
					},{
			            xtype:"button",
			            text: 'Login',
			            name:"Login",
			            id: 'login',
			            style: 'margin-left:155px'
					}
					]
		        },{
			        xtype:"fieldset",
			        title:"New Customer?&nbsp;&nbsp;&nbsp;Please enter your email and choose a password",
			        checkboxToggle: true,
			        id:'newCustomer',
			        labelWidth: 150,
			        autoHeight:true,
			        items:[{
			            xtype:"textfield",
			            fieldLabel:"Email Address",
			            name:"new_email",
			            id: 'new_email',
			            vtype: 'email',
						width: 300,
						validator: function(value) {
							new_email_value = value;
							new_email_valid = false;
							Ext.Ajax.request({
							   url: '/site/phpeventassured/check_email.php',
							   params: {email: value},
							   success: function(response, opts) {
									result = Ext.util.JSON.decode(response.responseText);
									if (new_email_value == opts.params.email) { //ignore old responses for other email addresses
										new_email_valid = result.success;
										if(!new_email_valid) {
											Ext.getCmp('new_email').markInvalid('This email is already registered. To login, click "Returning Customer" above.');
											Ext.getCmp('email').setValue(value);
										}
									}
							   },
							   failure: function(response, opts) {
							   	   alert('There has been a problem connecting to the server. This may be due to a problem with your Internet connection, or we could be performing maintenance on the server. Please try again. If you continue to experience problems, contact us for further assistance.');
							   }
							});
							return true;
						}
					},{
			            xtype:"textfield",
			            fieldLabel:"Confirm Email Address",
			            name:"confirm_new_email",
			            id: 'confirm_new_email',
			            vtype: 'email',
						width: 300,
						validator: function(value) {
							if(Ext.getCmp('new_email').getValue() == value) {
								return true;
							} else {
								return 'Emails do not match';
							}
						}
					},{
			            xtype:"textfield",
			            fieldLabel:"Password",
			            name:"new_password",
			            id: 'new_password',
			            inputType: 'password',
						width: 200
					},{
			            xtype:"textfield",
			            fieldLabel:"Confirm Password",
			            name:"confirm_new_password",
			            id: 'confirm_new_password',
			            inputType: 'password',
						width: 200,
						validator: function(value) {
							if(Ext.getCmp('new_password').getValue() == value) {
								return true;
							} else {
								return 'Passwords do not match';
							}
						}
					},{
			            xtype:"textfield",
			            fieldLabel:"Password Hint",
			            name:"password_hint",
			            id: 'password_hint',
						width: 300
					}
					]
		        },{
			        xtype:"fieldset",
			        title:"Your details",
			        labelWidth: 150,
			        autoHeight:true,
			        items:[{
			            xtype:"textfield",
			            fieldLabel:"Title",
			            name:"title",
			            id: 'personTitle',
			            allowBlank: false,
						width: 100
					},{
			            xtype:"textfield",
			            fieldLabel:"First name",
			            name:"first_name",
			            id: 'first_name',
						allowBlank: false,
						width: 300
					},{
			            xtype:"textfield",
			            fieldLabel:"Surname",
			            name:"surname",
			            id: 'surname',
						allowBlank: false,
						width: 300
					},{
			            xtype:"textfield",
			            fieldLabel:"Company/Organisation <img id='company_help' class='fieldHelp' src='/shared/images/icons/help.gif'/>",
			            name:"company",
			            id: 'company',
						allowBlank: false,
						width: 300,
						validator: function(value) {
							var v = value.toLowerCase();
							if(v.length < 2 | v == '-' | v == '--' | v == '.' | v == '..' | v == 'na' | v == 'n/a' | v == 'not application' | v == 'none') {
								return 'Enter the name of your company or organisation. If you are a sole trader, please enter your full name. (Please note that we only provide insurance to individuals if this is in the course of a business activity). This name will appear on your insurance documents and has legal standing in relation to your insurance.';
							}
							return true;
						}
					},{
			            xtype:"textfield",
			            fieldLabel:"Building",
			            name:"building",
			            id: 'building',
						width: 300
					},{
			            xtype:"textfield",
			            fieldLabel:"Number and Road",
			            name:"numberAndRoad",
			            id: 'numberAndRoad',
						allowBlank: false,
						width: 300
					},{
			            xtype:"textfield",
			            fieldLabel:"District",
			            name:"district",
			            id: 'district',
						width: 300
					},{
			            xtype:"textfield",
			            fieldLabel:"Postal Town",
			            name:"town",
			            id: 'town',
						allowBlank: false,
						width: 300
					},{
			            xtype:"textfield",
			            fieldLabel:"County/State",
			            name:"county",
			            id: 'county',
						width: 300
					},{
			            xtype:"textfield",
			            fieldLabel:"Postcode",
			            name:"postcode",
			            id: 'postcode',
						allowBlank: false,
						width: 100
					},{
			            xtype:"textfield",
			            fieldLabel:"Telephone",
			            name:"telephone",
			            id: 'telephone',
						allowBlank: false,
						width: 200
					},{
			            xtype:"textfield",
			            fieldLabel:"FAX",
			            name:"fax",
			            id: 'fax',
						width: 200
					}
					]
		        }]
			  },{
			    xtype:"panel",
			    title:"Regulation",
			    id: 'Regulation',
			    bodyStyle: 'padding: 8px;background:#EBF3FC',
			    height: 630,
			    items:[{
			        xtype:"fieldset",
			        title:"For regulatory purposes, please check the boxes below to confirm...",
			        labelWidth: 350,
			        autoHeight:true,
			        items:[{
			            xtype:"checkbox",
			            fieldLabel:"You are NOT a 'Consumer' customer <img id='notConsumer_help' class='fieldHelp' src='/shared/images/icons/help.gif'/>",
			            name:"notConsumer",
			            id: 'notConsumer'
					},{
			            xtype:"checkbox",
			            fieldLabel:"You agree to accept documentation in the English language",
			            name:"englishLanguage",
			            id: 'englishLanguage'
					},{
			            xtype:"checkbox",
			            fieldLabel:"You do NOT have any assets in the USA or Canada",
			            name:"noUSAorCanada",
			            id: 'noUSAorCanada'
					}
					]
		        },{
			        xtype:"fieldset",
			        title:"Please also tell us...",
			        labelWidth: 350,
			        items:[{
			            xtype:"checkbox",
			            fieldLabel:"If you are a business with an annual turnover below £1 Million",
			            name:"turnover",
			            id: 'turnover'
					},{
			            xtype:"combo",
			            fieldLabel:"Law applicable to the insurance contract <img id='jurisdiction_help' class='fieldHelp' src='/shared/images/icons/help.gif'/>",
			            name:"jurisdiction",
			            id: 'jurisdiction',
						triggerAction: 'all',
						selectOnFocus:true,
						forceSelection: true,
			            allowBlank: false,
			            mode: 'local',
			            value: 'England',
						listClass: 'x-combo-list-small',
						width: 170,
						listWidth: 187,
						valueField: 'country',
						displayField: 'country',
						store: jurisdictionCountry_ds
					}
					]
		        }]
			  },{
			    xtype:"panel",
			    title:"About the Event",
			    id: 'About the Event',
			    height: 630,
			    bodyStyle: 'padding: 8px;background:#EBF3FC',
			    items:[{
			        xtype:"fieldset",
			        title:"About the event",
			        labelWidth: 200,
			        autoHeight:true,
			        items:[{
			            xtype:"textfield",
			            fieldLabel:"Event name",
			            name:"event_name",
			            id: 'event_name',
						allowBlank: false,
			            width: 300
					},{
			            xtype:"textfield",
			            fieldLabel:"Event Organiser (if known)",
			            name:"organiser",
			            id: 'organiser',
			            width: 300
					}
					]
		        },{
			        xtype:"fieldset",
			        title:"When is the event being held?",
			        labelWidth: 200,
			        autoHeight:true,
			        items:[{
			            xtype:"datefield",
			            fieldLabel:"First Departure Date <img id='departure_date_help' class='fieldHelp' src='/shared/images/icons/help.gif'/>",
			            name:"departure_date",
			            id: 'departure_date',
			            format: 'D, jS M, Y',
						allowBlank: false,
			            readOnly: true,
			            width: 140
					},{
			            xtype:"datefield",
			            fieldLabel:"Last return date <img id='return_date_help' class='fieldHelp' src='/shared/images/icons/help.gif'/>",
			            name:"return_date",
			            id: 'return_date',
			            format: 'D, jS M, Y',
						allowBlank: false,
			            readOnly: true,
			            width: 140
					},{
			            xtype:"datefield",
			            fieldLabel:"Show opening date",
			            name:"opening_date",
			            id: 'opening_date',
			            format: 'D, jS M, Y',
						allowBlank: false,
			            readOnly: true,
			            width: 140
					},{
			            xtype:"datefield",
			            fieldLabel:"Show closing date",
			            name:"closing_date",
			            id: 'closing_date',
			            format: 'D, jS M, Y',
						allowBlank: false,
			            readOnly: true,
			            width: 140
					}
					]
		        },{
			        xtype:"fieldset",
			        title:"Where is the event being held?",
			        labelWidth: 200,
			        autoHeight:true,
			        items:[{
			            xtype:"textfield",
			            fieldLabel:"Main venue",
			            name:"venue",
			            id: 'venue',
						allowBlank: false,
			            width: 300
					},{
			            xtype:"textfield",
			            fieldLabel:"Town/City",
			            name:"venue_town",
			            id: 'venue_town',
						allowBlank: false,
			            width: 300
					},{
			            xtype:"textfield",
			            fieldLabel:"County/State",
			            name:"venue_county",
			            id: 'venue_county',
			            width: 300
					}
					]
		        }]
			  },{
			    xtype:"panel",
			    title:"Declaration",
			    id: 'Declaration',
			    bodyStyle: 'padding: 8px;background:#EBF3FC',
			    height: 630,
				items:[{
			        xtype:"fieldset",
			        title:"Acceptance of Quotation and Declaration",
			        id: 'declarationFieldSet',
			        autoHeight:true
				},{
			        xtype:"fieldset",
			        title:"Confirm Declaration",
			        labelWidth: 350,
			        autoHeight:true,
			        items:[{
			            xtype:"checkbox",
			            fieldLabel:"Are you able to confirm every part of the declaration above? ",
			            name:"agree",
			            id: 'agree'
			        },{
			            xtype:"textarea",
			            fieldLabel:"If not, please provide reason/information",
			            name:"reason",
			            id: 'reason',
			            maxLength: 200,
			            width: 400,
			            height: 38
			        }]
				},{
			        xtype:"fieldset",
			        title:"Important Notice",
			        id:"importantNotice",
			        labelWidth: 350,
			        autoHeight:true
				}]
			  }]

			}]
			}
	);

	//Form Field Events
	Ext.getCmp('eventCode').on('valid',function(fld){
		if(fld.getValue() == "") {
			event_code_info = null;
			Ext.getCmp('venueCountry').enable();
			Ext.getCmp('event_name').enable();
			Ext.getCmp('opening_date').enable();
			Ext.getCmp('closing_date').enable();
			Ext.getCmp('venue').enable();
			Ext.getCmp('venue_county').enable();
			Ext.getCmp('venue_town').enable();
			Ext.getCmp('organiser').enable();
			validEventCode = '';
			eventCodeValidator("");
			refreshQuote();
		}
	});
	Ext.getCmp('currency').on('select',function(){
		refreshPackages();
		refreshQuote();
		refreshClaimLimit();
	});
	Ext.getCmp('venueCountry').on('select',function(){
		refreshQuote();
	});
	Ext.getCmp('country').on('select',function(){
		refreshQuote();
	});
	Ext.getCmp('liability').on('check',function(checkbox,value){
		showLiabilityPackageOption(value);
		refreshQuote();
	});
	Ext.getCmp('returningCustomer').on('expand',function(panel){
		new_customer = false;
		panel.setTitle('Returning Customer?&nbsp;&nbsp;&nbsp;Please login below');
		Ext.getCmp('newCustomer').collapse();
		Ext.getCmp('newCustomer').setTitle('New Customer?');
	});
	Ext.getCmp('newCustomer').on('expand',function(panel){
		new_customer = true;
		panel.setTitle('New Customer?&nbsp;&nbsp;&nbsp;Please enter your email and choose a password');
		Ext.getCmp('returningCustomer').collapse();
		Ext.getCmp('returningCustomer').setTitle('Returning Customer?');
	});
	Ext.getCmp('newCustomer').on('collapse',function(panel){
		Ext.getCmp('returningCustomer').expand();
	});
	Ext.getCmp('returningCustomer').on('collapse',function(panel){
		Ext.getCmp('newCustomer').expand();
	});
	Ext.getCmp('password').on('specialkey',function(field, e){
		if(e.getKey() == e.RETURN) {
			loginOut();
		}
		
	});
	Ext.getCmp('departure_date').on('valid',function(field){
		if (!ignoreDateValidEvents){
			refreshEventDates();
		}
	});
	Ext.getCmp('return_date').on('valid',function(field){
		if (!ignoreDateValidEvents){
			refreshEventDates();
		}
	});
	Ext.getCmp('opening_date').on('valid',function(field){
		if (!ignoreDateValidEvents){
			refreshEventDates();
		}
	});
	Ext.getCmp('closing_date').on('valid',function(field){
		if (!ignoreDateValidEvents){
			refreshEventDates();
		}
	});
	Ext.getCmp('login').on('click',function(){
		loginOut();
	});

	function loginOut() {
		if(loggedIn) {
			logout();
		} else {
			login();
		}
	}

	function login() {
		Ext.getCmp('login').disable();
		Ext.Ajax.request({
		   //url: '/cgi-bin/ee/SISite/runpage.html?runpageuri=/cgi-bin/ee/login.html?email='+Ext.getCmp('email').getValue()+'&password='+Ext.getCmp('password').getValue()+'&runpagestart=JSON_START&runpageend=JSON_END&runpagemime=text',
		   url: '/site/phpeventassured/login.php?email='+Ext.getCmp('email').getValue()+'&password='+Ext.getCmp('password').getValue(),
			success: function(response, opts) {
				Ext.getCmp('login').enable();
				result = Ext.util.JSON.decode(response.responseText);
				if(!result.loggedIn) {
					if(result.message == 'Login failed: user not registered') {
						Ext.Msg.alert('Email Address Not Registered','This email address has not been registered on this website. Either re-type the email address, or click <b>New Customer</b> to register as a new customer.');
						return;
					}
					Ext.Msg.show({
						title: 'Login Failed',
						msg: 'The login details are incorrect. If you have forgotten your password, ensure your email address is entered correctly then click the Hint button below to receive your password hint via email.',
						animEl: 'login',
						closable: false,
						buttons: {ok: 'Try again', cancel: 'Email me my Password Hint'},
						fn: function(btn) {
							if(btn == 'cancel') {
								Ext.Ajax.request({
									url: '/site/phpeventassured/email_hint.php',
									params: {
										email: Ext.getCmp('email').getValue()
									},
									success: function(response, opts) {
										result = Ext.util.JSON.decode(response.responseText);
									},
									failure: function(response, opts) {
								   	   alert('There has been a problem connecting to the server. This may be due to a problem with your Internet connection, or we could be performing maintenance on the server. Please try again. If you continue to experience problems, contact us for further assistance.');
									}
								});
								
							}
						}
					});
					return;
				}
				user_id = result.userID;
				initLogin();
		   },
		   failure: function(response, opts) {
		   	    Ext.getCmp('login').setText('Login');
				Ext.getCmp('login').enable();
		   	   alert('There has been a problem connecting to the server. This may be due to a problem with your Internet connection, or we could be performing maintenance on the server. Please try again. If you continue to experience problems, contact us for further assistance.');
		   }
		});
	}	

	function logout() {
		Ext.getCmp('login').disable();
		Ext.Ajax.request({
		   //url: '/cgi-bin/ee/SISite/runpage.html?runpageuri=/cgi-bin/ee/login.html&runpagestart=JSON_START&runpageend=JSON_END&runpagemime=text&email=INVALIDEMAIL&password=INVALIDPASSWORD',
			url: '/site/phpeventassured/logout.php',
		   success: function(response, opts) {
				loggedIn = false;
				refreshLogin();
		   },
		   failure: function(response, opts) {
		   	    Ext.getCmp('login').setText('Log out');
				Ext.getCmp('login').enable();
		   	   alert('There has been a problem connecting to the server. This may be due to a problem with your Internet connection, or we could be performing maintenance on the server. Please try again. If you continue to experience problems, contact us for further assistance.');
		   }
		});
	}
	
	//tab events
	tabs = Ext.getCmp('tabs');
	tabs.on('tabchange',function(tabPanel,tab){
		step = tab.title;
		nextStep = step;
		refreshNavigationButtons();

		if (Ext.isSafari){
			//safari incorrectly places the trigger button on the left when the date field is created hidden (e.g. on a tab)
			//manually shift the buttons into the correct position each time a new tab is selected
			if (Ext.getDom('departure_date')){
				Ext.getDom('departure_date').nextSibling.style.left=Ext.getDom('departure_date').style.width;
			}
			if (Ext.getDom('return_date')){
				Ext.getDom('return_date').nextSibling.style.left=Ext.getDom('return_date').style.width;
			}
			if (Ext.getDom('opening_date')){
				Ext.getDom('opening_date').nextSibling.style.left=Ext.getDom('opening_date').style.width;
			}
			if (Ext.getDom('closing_date')){
				Ext.getDom('closing_date').nextSibling.style.left=Ext.getDom('closing_date').style.width;
			}
			if (Ext.getDom('jurisdiction')){
				Ext.getDom('jurisdiction').nextSibling.style.left=Ext.getDom('jurisdiction').style.width;
			}
		}		

	});
	
	
	//get the packages if no event code has been passed in, otherwise the validator will get them when checking eventCode
	if (!((Request.QueryString("event")).toString() )){
		Ext.Ajax.request({
		  // url: '/php/get_packages.php',
		  url: '/site/phpeventassured/getEventCodeInfoAndPackages.php',
		  params: {eventCode: "" },
		   success: function(response, opts) {
				packages = Ext.util.JSON.decode(response.responseText).packages;
				if (renderedPackages == true) {
					refreshPackages();
				}else{
					renderedPackages = true;
					packagesLoaded();
				}
		   },
		   failure: function(response, opts) {
		   	   alert('There has been a problem connecting to the server. This may be due to a problem with your Internet connection, or we could be performing maintenance on the server. Please try again. If you continue to experience problems, contact us for further assistance.');
		   }
		});
	}
	form.render('quote');
	initLogin();
	
	//Post render
	declarationTemplate = new Ext.Template(
	'	<p class="form_paragraph">It is agreed that this proposal and information supplied with it by you or on your behalf shall form the basis of the contract and shall form part of the contract of insurance in respect of the event shown</p>'+
	'	<p class="form_paragraph"><b>I/WE DECLARE: Unless amended or stated below by Us/Me, I/We confirm</b></p>'+
	'	<ol class="form_numberedList">'+
	'	  <li>that the cover detailed above is in accordance with my/our requirements and that this form is a statement of My/Our demands and needs in relation to the insurance of our exhibit.</li>'+
	'	  <li>There are <b>no known</b> existing circumstances at the time of arranging this insurance which might develop and give rise to a claim under any part of this insurance.</li>'+
	'	  <li>I/We have contracted to take exhibition space at the Event all preliminary arrangements to ensure satisfactory exhibit have been made </li>'+
	'	  <li>I/We have not suffered any loss or circumstances which might have given rise to a claim under this type of insurance in the last 5 years where the sum claimed exceeded <span id="claimLimit">£500</span></li>'+
	'	  <li><b>I/We have not been convicted of any criminal offence</b> (other than minor driving offences not resulting in disqualification) in the last 5 years</li>'+
	'	  <li><b>I/We have not been declared bankrupt</b> nor been involved in any company or business which has gone into liquidation, receivership or come to an arrangement with creditors in the last 5 years</li>'+
	'	  <li><b>No insurer has declined</b> nor imposed any special terms on any exhibitor type insurance </li>'+
	'	  <li>The Property to be insured under this insurance is My/Our Property or for which I/we are legally liable and it is all in <b>a good state of repair and condition and the Values stated represent the full replacement cost of property being taken to the Event</b></li>'+
	'	  <li>All the information contained in this Proposal or in documents supplied in support of the Proposal by Me/Us or on my/Our behalf is to the best of my/our knowledge after enquiry true and complete and I/We have disclosed all material facts. A material fact is information which might affect the underwriters’ decision whether or not accept a risk and at what terms.</li>'+
	'	  <li>I/We have read the Summary of Cover provided</li>'+
	'	  <li>I/We have read the Initial Disclosure and Terms of Business Document for this insurance</li>'+
	'	</ol>'
	);
	var target = Ext.getDom('declarationFieldSet').childNodes[1];
	declarationTemplate.append(target, {});

	importantTemplate = new Ext.Template(
		'<p class="form_paragraph"><b>If you are in any doubt about what constitutes a material fact you should ask us. Please note that any misleading statement or non disclosure of material information may invalidate the insurance. If you have any doubts about how to answer a question, please ask us. If you are not sure if information is material, then you should disclose it. No cover is in place until confirmed by Us in writing.</b></p><p class="form_paragraph" style="color:#15428B;font-weight:bold">When you are completely happy with the information you have provided, click Finish below to receive a formal quotation by email.</p>'
	);
	var target = Ext.getDom('importantNotice').childNodes[1];
	importantTemplate.append(target, {});
		

	//tool tips
    new Ext.ToolTip({
    	target: 'eventCode_help',
        title: 'Event Code',
        html: 'If you have been given an event code, enter it here and parts of this form will be completed for you.',
        dismissDelay: 0,
        showDelay: 0,
        hideDelay: 0,
        trackMouse: true
    });
    new Ext.ToolTip({
    	target: 'based_help',
        title: 'Where are you based?',
        html: 'Insurance is only available from this web site in countries which are on this drop-down list.<br /><br />Please note that England, Scotland, Wales and Northern Ireland are separately listed.',
        dismissDelay: 0,
        showDelay: 0,
        hideDelay: 0,
        trackMouse: true
    });
    new Ext.ToolTip({
    	target: 'held_help',
        title: 'Where is the event being held?',
        html: 'This website will give quotations for events being held in the countries in this drop-down list.<br /><br />For other countries, please call +44(0)1376 330624',
        dismissDelay: 0,
        showDelay: 0,
        hideDelay: 0,
        trackMouse: true
    });
    new Ext.ToolTip({
    	target: 'package_help',
        title: 'Choose your Package',
        html: 'Select one package from the four provided. If you need higher cover than is provided by any of these packages, please call us on 44 (0)1376 330624 for a tailored quotation.',
        dismissDelay: 0,
        showDelay: 0,
        hideDelay: 0,
        trackMouse: true
    });
    new Ext.ToolTip({
    	target: 'company_help',
        title: 'Company/Organisation',
        html: 'Enter the name of your company or organisation. If you are a sole trader, please enter your full name. (Please note that we only provide insurance to individuals if this is in the course of a business activity). This name will appear on your insurance documents and has legal standing in relation to your insurance.',
        dismissDelay: 0,
        showDelay: 0,
        hideDelay: 0,
        trackMouse: true
    });
    new Ext.ToolTip({
    	target: 'notConsumer_help',
        title: 'Not a Consumer',
        html: 'A Consumer as defined by the UK Financial Services Authority is a person acting outside a business, trade or profession – in essence a private individual acting in a private capacity. We regret that at the moment we do not offer Consumer insurances.',
        dismissDelay: 0,
        showDelay: 0,
        hideDelay: 0,
        trackMouse: true
    });
    new Ext.ToolTip({
    	target: 'jurisdiction_help',
        title: 'Law applicable to the insurance contract',
        html: 'The contract of insurance is subject to (and defaults to) English law unless both parties agree otherwise. Please note this is the law of contract for the purpose any (unlikely) dispute under the insurance. It is not the geographical limit of cover (which is detailed in the insurance policy.)',
        dismissDelay: 0,
        showDelay: 0,
        hideDelay: 0,
        trackMouse: true
    });
    new Ext.ToolTip({
    	target: 'departure_date_help',
        title: 'First Departure Date',
        html: 'The date the first person leaves to go to the event',
        dismissDelay: 0,
        showDelay: 0,
        hideDelay: 0,
        trackMouse: true
    });
    new Ext.ToolTip({
    	target: 'return_date_help',
        title: 'Last Return Date',
        html: 'The day the last person returns home after the event',
        dismissDelay: 0,
        showDelay: 0,
        hideDelay: 0,
        trackMouse: true
    });
	
});

	function refreshClaimLimit() {
		var claimLimit = '£500';
		switch(Ext.getCmp('currency').getValue()) {
			case 'Currency Pound Sterling':
				var claimLimit = '£500';
				break;
			case 'Currency Euros':
				var claimLimit = '€750';
				break;
			case 'Currency American Dollars':
				var claimLimit = '$1000';
				break;
		} 
		Ext.getDom('claimLimit').innerHTML = claimLimit;
	}
	
	function refreshQuote() {
		var country = Ext.getCmp('country').getRawValue();
		var venueCountry = Ext.getCmp('venueCountry').getRawValue();
		var liability = Ext.getCmp('liability').getValue();
		var currency = Ext.getCmp('currency').getValue();
		if(country == "" || venueCountry =="" || !selectedPackage) {
				Ext.getCmp('premium').setValue('');
				Ext.getCmp('tax').setValue('');
				Ext.getCmp('total').setValue('');
				Ext.getCmp('description').setValue('Complete the fields above then select a package for an instant quotation');
		} else {
			Ext.Ajax.request({
			   url: '/site/phpeventassured/get_ee_quick_quote.php',
			   params: {
			   	ContAdd7: country,
				VenCountry: venueCountry,
				EAEE_Package: selectedPackage,
				EALiabilityEL: liability,
				currency: currency,
				eventCode: validEventCode},
				success: function(response, opts) {
					result = Ext.util.JSON.decode(response.responseText);
					if(result.status) {
						Ext.getCmp('premium').setValue('');
						Ext.getCmp('tax').setValue('');
						Ext.getCmp('total').setValue('');
						Ext.getCmp('description').setValue('Quick quote unavailable. Please call +44 (0)1376 330624 to arrange your cover or email info@event-assured.com');
						Ext.get('description').setStyle('background','#FFCCCC !important');
					} else {
						Ext.get('description').setStyle('background','#FFFFFF url(../images/default/form/text-bg.gif) repeat-x scroll 0pt');
						Ext.getCmp('premium').setValue(formatCurrency(result.premium));
						Ext.getCmp('tax').setValue(formatCurrency(result.tax));
						Ext.getCmp('total').setValue(formatCurrency(result.total));
						Ext.getCmp('description').setValue(result.taxdescription+'. Happy with this quote? Click Next to continue.');
					}
					refreshSummaryOfCover();
			   },
			   failure: function(response, opts) {
			   	   alert('There has been a problem connecting to the server. This may be due to a problem with your Internet connection, or we could be performing maintenance on the server. Please try again. If you continue to experience problems, contact us for further assistance.');
			   }
			});
		}
	}
	
	function refreshEventDates() {
		//if there is a departure date and no other dates, default other dates to the departure date
		dates_invalid = false;
		if(Ext.getCmp('departure_date').getValue() != "") {
			if(Ext.getCmp('departure_date').getValue().getTime() < new Date().getTime()) {
				Ext.getCmp('departure_date').markInvalid('The First departure date cannot be in the past');
				dates_invalid = true;
			}
			if(Ext.getCmp('return_date').getValue() == "") {
				Ext.getCmp('return_date').setValue(Ext.getCmp('departure_date').getValue())
			} else {
				if(Ext.getCmp('return_date').getValue().getTime() < Ext.getCmp('departure_date').getValue().getTime()) {
					Ext.getCmp('return_date').markInvalid('The Last return date must be on or after the First departure date');
					dates_invalid = true;
				}
			}
			if(Ext.getCmp('opening_date').getValue() == "") {
				Ext.getCmp('opening_date').setValue(Ext.getCmp('departure_date').getValue())
			} else {
				if(Ext.getCmp('opening_date').getValue().getTime() < Ext.getCmp('departure_date').getValue().getTime()) {
					Ext.getCmp('departure_date').markInvalid('The First departure date must be on or before the Show opening date');
					dates_invalid = true;
				}	
			}
			if(Ext.getCmp('closing_date').getValue() == "") {
				Ext.getCmp('closing_date').setValue(Ext.getCmp('departure_date').getValue())
			} else {
				if(Ext.getCmp('closing_date').getValue().getTime() > Ext.getCmp('return_date').getValue().getTime()) {
					Ext.getCmp('return_date').markInvalid('The Last return date must be on or after the Show closing date');
					dates_invalid = true;
				}
			}
			if(Ext.getCmp('closing_date').getValue().getTime() < Ext.getCmp('opening_date').getValue().getTime()) {
				Ext.getCmp('closing_date').markInvalid('The Closing date must be on or after the Show opening date');
				dates_invalid = true;
			}
			if (!dates_invalid){
				ignoreDateValidEvents = true;
				Ext.getCmp('departure_date').clearInvalid();
				Ext.getCmp('return_date').clearInvalid();
				Ext.getCmp('opening_date').clearInvalid();
				Ext.getCmp('closing_date').clearInvalid();
				ignoreDateValidEvents = false;
			}
		}


	}
	
	
	function formatCurrency(amount) {
		var i = parseFloat(amount);
		if(isNaN(i)) { i = 0.00; }
		var minus = '';
		if(i < 0) { minus = '-'; }
		i = Math.abs(i);
		i = parseInt((i + .005) * 100);
		i = i / 100;
		s = new String(i);
		if(s.indexOf('.') < 0) { s += '.00'; }
		if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
		s = minus + s;
		return currencySymbol+s;
	}

	function refreshSummaryOfCover() {
		if(!Ext.get('total')) {
			return;
		}
		var code = validEventCode;
		var suffix = '';
		if(event_code_info && !event_code_info.Error) {
			suffix = code.charAt(code.length-1);
		}
		var socDocGBP = 'EXHIBITOR EXPRESS SUMMARY OF COVER GBP.pdf';
		var socDocUSD = 'EXHIBITOR EXPRESS SUMMARY OF COVER USD.pdf';
		var socDocEUR = 'EXHIBITOR EXPRESS SUMMARY OF COVER EURO.pdf';
		if(event_code_info && !event_code_info.Error) {
			if(event_code_info.SOC_GBP) { socDocGBP = event_code_info.SOC_GBP }
			if(event_code_info.SOC_USD) { socDocUSD = event_code_info.SOC_USD }
			if(event_code_info.SOC_EUR) { socDocEUR = event_code_info.SOC_EUR }
		}
		var socDoc;
		switch(currencySymbol) {
			case '£':
				socDoc = '/documents/'+socDocGBP;
				break;
			case '$':
				socDoc = '/documents/'+socDocUSD;
				break;
			case '€':
				socDoc = '/documents/'+socDocEUR;
				break;
		}
		var info = '';
		var tipLink = '';
		if(event_code_info && !event_code_info.Error && event_code_info.SOCBalloon) {
			tipLink = ' <img id="soc_help" class="fieldHelp" src="/shared/images/icons/help.gif"/>';
		} 
		if(socDoc) {
			info = '<a href="'+socDoc+'" style="font-size:11px" target="_blank"><img src="/shared/images/icons/page_white_acrobat.png" width=16 height=16 style="virtical-align:text-top;margin-top:6px" />&nbsp;Click here to read the Summary of Cover ('+currencySymbol+') for this event</a>'+tipLink;
		}
		if(suffix == 'w' || suffix == 'W') {
			info = 'This premium is calculated based on our <b>enhanced cover'+tipLink+'</b> designed specifically for this event. <a href="'+socDoc+'" style="font-size:11px" target="_blank"><br /><img src="/shared/images/icons/page_white_acrobat.png" width=16 height=16 style="virtical-align:text-top;margin-top:6px" />&nbsp;Click here to view the Special Summary of Cover for this event ('+currencySymbol+')</a>.<br /><br />Our standard cover is available at lower cost – <a href="javascript:setStandardEventCodeSuffix()" style="font-size:11px">click here for standard cover</a>.';
		}
		if(suffix == 's' || suffix == 'S') {
			info = 'This premium is calculated based on our <b>standard cover'+tipLink+'</b>. <a href="'+socDoc+'" style="font-size:11px" target="_blank"><br /><img src="/shared/images/icons/page_white_acrobat.png" width=16 height=16 style="virtical-align:text-top;margin-top:6px" />&nbsp;Click here to view our Standard Summary of Cover ('+currencySymbol+')</a>.<br /><br />Our enhanced cover is also available  –  <a href="javascript:setSpecialEventCodeSuffix()" style="font-size:11px">click here for enhanced cover</a>.';
		}
		if(!soc) {
			soc = '<div id="socDiv" style="font-size:11px;margin: -70px 0px 0px 90px; width:563px; z-index"></div>'
			Ext.DomHelper.insertAfter(Ext.get('total'),soc,true);
			socDiv = Ext.get('socDiv');
		}
		socDiv.dom.innerHTML = info;
		if(event_code_info && event_code_info.SOCBalloon) {
		    new Ext.ToolTip({
		    	target: 'soc_help',
		        html: event_code_info.SOCBalloon,
		        width: 200,
		        dismissDelay: 0,
		        showDelay: 0,
		        hideDelay: 0,
		        trackMouse: true
		    });
		}
		socDiv.show();
	}
	

	function nextStep() {
		step = tabs.getActiveTab().title;
		stepIndex = steps.indexOf(step);
		if(stepIndex == steps.length-1) {
			//process finish
			var pack = 0;
			if(Ext.getDom('package_option1').checked) {pack=1}
			if(Ext.getDom('package_option2').checked) {pack=2}
			if(Ext.getDom('package_option3').checked) {pack=3}
			if(Ext.getDom('package_option4').checked) {pack=4}
			if(Ext.getCmp('returningCustomer').collapsed) {
				active_email = Ext.getCmp('new_email').getValue();
			} else {
				active_email = Ext.getCmp('email').getValue()
			}

			if(pack == 0) {
				Ext.Msg.alert('Pick a Package','Please select the package you would like');
				tabs.activate(0);
				return;
			}
			if(new_customer) {
				if(!new_email_valid) {
					Ext.getCmp('new_email').markInvalid('This email is already registered. To login, click "Returning Customer?" above.');
					Ext.Msg.alert('Form incomplete','The email address you are trying to register with is already in use. To login, click "Returning Customer?"');
					tabs.activate(1);
					return;
				}
				if(Ext.getCmp('new_email').getValue() == '' || Ext.getCmp('confirm_new_email').getValue() == '' || Ext.getCmp('new_password').getValue() == '' || Ext.getCmp('confirm_new_password').getValue() == '' || Ext.getCmp('password_hint').getValue() == '') {
					Ext.getCmp('new_email').markInvalid('This field is required if you are not logged in as an Existing Customer');
					Ext.getCmp('confirm_new_email').markInvalid('This field is required if you are not logged in as an Existing Customer');
					Ext.getCmp('new_password').markInvalid('This field is required if you are not logged in as an Existing Customer');
					Ext.getCmp('confirm_new_password').markInvalid('This field is required if you are not logged in as an Existing Customer');
					Ext.getCmp('password_hint').markInvalid('This field is required if you are not logged in as an Existing Customer');
					tabs.activate(1);
					Ext.Msg.alert('Form incomplete','Please either login if you are a returning customer, or if you are a new customer enter and confirm your email address and the password you would like to use to access this website.');
					return;
				}
			} else {
				//if(Ext.getCmp('email').getValue() == '' || Ext.getCmp('password').getValue() == '') {
				if(Ext.getCmp('email').getValue() == '' ) {
					Ext.getCmp('email').markInvalid('This field is required if wish to login as an Existing Customer');
					//Ext.getCmp('password').markInvalid('This field is required if wish to login as an Existing Customer');
					tabs.activate(1);
					Ext.Msg.alert('Form incomplete','Please either login if you are a returning customer, or if you are a new customer enter and confirm your email address and the password you would like to use to access this website.');
					return;
				}
			}
			if(dates_invalid) {
				Ext.Msg.alert('Form incomplete','The dates you have entered are incorrect or illogical. Please check the dates.');
				tabs.activate(3);
				return;
			}
			var regMessage = '';
			if(!Ext.getCmp('notConsumer').getValue()) {
				regMessage += '<b>You are NOT a Consumer customer - unchecked</b><br />We regret at this time we do not offer Consumer Insurance. If you are acting for a business, trade or profession, please confirm this by checking the box.';
			}
			if(!Ext.getCmp('englishLanguage').getValue()) {
				if(regMessage != '') {regMessage += '<br /><br />'}
				regMessage += '<b>You agree to accept documentation in the English language - unchecked</b><br />We regret at this time we only offer documentation written in the English language. If you are happy to receive documentation written in the English language, please confirm this by checking the box.';
			}
			if(regMessage != '') {
				Ext.Msg.alert('Regulation Incomplete',regMessage);
				tabs.activate(2);
				return;	
			}
			if(!form.form.isValid()) {
				tabs.activate(0);
				Ext.Msg.alert('Form incomplete','Please check each step and complete or correct all fields marked with red underlines. For assistance, hover your mouse on any incorrect fields for an explanation of the problem.');
				return;
			}
			if(!Ext.getCmp('agree').getValue() && !Ext.getCmp('reason').getValue()) {
				tabs.activate(4);
				Ext.Msg.alert('Confirm Declaration Required','Please either check the Confirm Declaration box or provide a suitable reason');
				return;
			}
			
			Ext.Msg.wait('Thank you for completing the questions. Your quotation is being prepared','Please wait');
			//commit
			Ext.Ajax.request({
			   url: '/site/phpeventassured/ee_commit.php',
			   params: {
					username: active_email,
					ContTitle: Ext.getCmp('personTitle').getValue(),
					ContForename: Ext.getCmp('first_name').getValue(),
					ContSurname: Ext.getCmp('surname').getValue(),
					CustName: Ext.getCmp('company').getValue(),
					ContAdd1: Ext.getCmp('building').getValue(),
					ContAdd2: Ext.getCmp('numberAndRoad').getValue(),
					ContAdd3: Ext.getCmp('district').getValue(),
					ContAdd4: Ext.getCmp('town').getValue(),
					ContAdd5: Ext.getCmp('county').getValue(),
					ContAdd6: Ext.getCmp('postcode').getValue(),
					ContAdd7: Ext.getCmp('country').getValue(),
					ContTelephone: Ext.getCmp('telephone').getValue(),
					ContFax: Ext.getCmp('fax').getValue(),
					ContEmail: active_email,
					CustFSCS: Ext.getCmp('turnover').getValue(),
					CustTypeRetail: Ext.getCmp('notConsumer').getValue(),
					EAJurisdiction: Ext.getCmp('jurisdiction').getValue(),
					CustEnglishDocumentation: Ext.getCmp('englishLanguage').getValue(),
					EALiabilityAssUSACanada: Ext.getCmp('noUSAorCanada').getValue(),
					OrganiserName: Ext.getCmp('organiser').getValue(),
					SchedEventTitle: Ext.getCmp('event_name').getValue(),
					SchedFirstDep: Ext.getCmp('departure_date').getValue().format('d/m/Y'),
					SchedLastRet: Ext.getCmp('return_date').getValue().format('d/m/Y'),
					SchedOpeningDate: Ext.getCmp('opening_date').getValue().format('d/m/Y'),
					SchedClosingDate: Ext.getCmp('closing_date').getValue().format('d/m/Y'),
					VenVenue: Ext.getCmp('venue').getValue(),
					VenCity: Ext.getCmp('venue_town').getValue(),
					VenState: Ext.getCmp('venue_county').getValue(),
					VenCountry: Ext.getCmp('venueCountry').getValue(),
					EAEE_Package: selectedPackage,
					EALiabilityEL: Ext.getCmp('liability').getValue(),
					EADecln1: Ext.getCmp('agree').getValue(),
					EADeclnNoComply: Ext.getCmp('reason').getValue(),
					currency: Ext.getCmp('currency').getValue(),
					eventCode: validEventCode,
					AffiliateCode: affiliateCode
			   },
			   success: function(response, opts) {
			   	    Ext.Msg.hide();
					result = Ext.util.JSON.decode(response.responseText);
					Ext.getCmp('nextButton').enable();
					//if(result.referReason != "") {
				   	  // Ext.Msg.alert('Automatic Quotation Unavailable','Your application needs input from one of our underwriting team, who will be in contact', function(){
					   	   //top.location = '/index.html';
					   	//   return;
				   	  // });
					//} else {
						quoteSubmitted(active_email,result.quoteId, result.referReason);
					//}
			   },
			   failure: function(response, opts) {
			   	   Ext.Msg.hide();
			   	   alert('There has been a problem connecting to the server. This may be due to a problem with your Internet connection, or we could be performing maintenance on the server. Please try again. If you continue to experience problems, contact us for further assistance.');
			   }
			});

			
			return;
		}
		nextStep = steps[stepIndex+1];
		tabs.activate(Ext.getCmp(nextStep));
		refreshNavigationButtons();
	}
	
	function previousStep() {
		step = tabs.getActiveTab().title;
		stepIndex = steps.indexOf(step);
		nextStep = steps[stepIndex-1];
		tabs.activate(Ext.getCmp(nextStep));
		refreshNavigationButtons();
	}
	function refreshNavigationButtons() {
		if(nextStep == steps[0]) {
			Ext.getCmp('previousButton').disable();
		} else {
			Ext.getCmp('previousButton').enable();
		}
		if(nextStep == steps[steps.length-1]) {
			Ext.getCmp('nextButton').setText('Finish');
		} else {
			Ext.getCmp('nextButton').setText('Next Step');
		}
	}
	
	function packagesLoaded() {
		packageTemplate = new Ext.Template(
		'		<table id="packageTable" cellSpacing="0" cellPadding="2" width="760" border="0">'+
		'		  <tr align="middle">'+
		'		    <td style="BORDER-TOP: 0px; BORDER-LEFT: 0px" width="50%">&nbsp;</td>'+
		'		    <th id="packageHeading" colSpan="4">PACKAGE</th>'+
		'		  </tr>'+
		'		  <tr align="middle">'+
		'		    <th id="sumHeading" width="50%">Sum Insured/Limit</th>'+
		'		    <td align="right"><strong>1</strong></td>'+
		'		    <td align="right"><strong>2</strong></td>'+
		'		    <td align="right"><strong>3</strong></td>'+
		'		    <td align="right"><strong>4</strong></td>'+
		'		  </tr>'+
		'		  <tr align="right">'+
		'		    <td class="prompt" align="left">Cancellation &amp; Disruption</td>'+
		'		    <td id="P1_cancellation">&nbsp;</td>'+
		'		    <td id="P2_cancellation">&nbsp;</td>'+
		'		    <td id="P3_cancellation">&nbsp;</td>'+
		'		    <td id="P4_cancellation">&nbsp;</td>'+
		'		  </tr>'+
		'		  <tr align="right">'+
		'		    <td class="prompt" align="left">Loss or Damage to Property</td>'+
		'		    <td id="P1_propertyDamage">&nbsp;</td>'+
		'		    <td id="P2_propertyDamage">&nbsp;</td>'+
		'		    <td id="P3_propertyDamage">&nbsp;</td>'+
		'		    <td id="P4_propertyDamage">&nbsp;</td>'+
		'		  </tr>'+
		'		  <tr align="right">'+
		'		    <td class="prompt" align="left">Damage to property of the Venue lent or hired to you '+
		'		    including shell scheme</td>'+
		'		    <td id="P1_venueDamage">&nbsp;</td>'+
		'		    <td id="P2_venueDamage">&nbsp;</td>'+
		'		    <td id="P3_venueDamage">&nbsp;</td>'+
		'		    <td id="P4_venueDamage">&nbsp;</td>'+
		'		  </tr>'+
		'		  <tr align="right">'+
		'		    <td class="prompt" align="left">Public Liability</td>'+
		'		    <td id="P1_publicLiability">&nbsp;</td>'+
		'		    <td id="P2_publicLiability">&nbsp;</td>'+
		'		    <td id="P3_publicLiability">&nbsp;</td>'+
		'		    <td id="P4_publicLiability">&nbsp;</td>'+
		'		  </tr>'+
		'		  <tr align="right">'+
		'		    <td class="prompt" align="left">Optional '+"Employers'"+' Liability</td>'+
		'		    <td id="P1_employersLiability">&nbsp;</td>'+
		'		    <td id="P2_employersLiability">&nbsp;</td>'+
		'		    <td id="P3_employersLiability">&nbsp;</td>'+
		'		    <td id="P4_employersLiability">&nbsp;</td>'+
		'		  </tr>'+
		'		  <tr align="right">'+
		'		    <td class="prompt" align="right"><b><span style="color:#15428B">Please select one package &gt;&gt;&gt;</span></b></td>'+
		'		    <td><label for="package_option1"><b>Package 1&nbsp;</b></label><input id="package_option1" type="radio" value="1" name="package_option"></td>'+
		'		    <td><label for="package_option2"><b>Package 2&nbsp;</b></label><input id="package_option2" type="radio" value="2" name="package_option"></td>'+
		'		    <td><label for="package_option3"><b>Package 3&nbsp;</b></label><input id="package_option3" type="radio" value="3" name="package_option"></td>'+
		'		    <td><label for="package_option4"><b>Package 4&nbsp;</b></label><input id="package_option4" type="radio" value="4" name="package_option"></td>'+
		'		  </tr>'+
		'		</table>'+
		'		<p id="currencyMessage"></p>'

		);
		var target = Ext.getDom('package').childNodes[1];
		packageTemplate.append(target, {});
		showLiabilityPackageOption(false);
		refreshPackages();
		Ext.get('package_option1').on('click',function(){
			selectPackage(1);
		});
		Ext.get('package_option2').on('click',function(){
			selectPackage(2);
		});
		Ext.get('package_option3').on('click',function(){
			selectPackage(3);
		});
		Ext.get('package_option4').on('click',function(){
			selectPackage(4);
		});
	}
	
	function selectPackage(packNo) {
		if(oldPackage) {
			stylePackage(oldPackage, 'background', '#EBF3FC');
		}
		selectedPackage = packNo;
		stylePackage(selectedPackage, 'background', '#fff');
		oldPackage = selectedPackage;
		refreshQuote();
	}
	
	function stylePackage(packNo, styleElement, styleValue) {
		Ext.get('P'+packNo+'_cancellation').setStyle(styleElement, styleValue);
		Ext.get('P'+packNo+'_propertyDamage').setStyle(styleElement, styleValue);
		Ext.get('P'+packNo+'_venueDamage').setStyle(styleElement, styleValue);
		Ext.get('P'+packNo+'_publicLiability').setStyle(styleElement, styleValue);
		Ext.get('P'+packNo+'_employersLiability').setStyle(styleElement, styleValue);
	}
	function eventCodeValidator(value) {
		Ext.Ajax.request({
		   url: '/site/phpeventassured/getEventCodeInfoAndPackages.php',
		   params: 'eventCode='+value,
		   success: function(response, opts) {
				event_code_info = Ext.util.JSON.decode(response.responseText);
				packages = event_code_info.packages;
				if (renderedPackages == true) {
					refreshPackages();
				}else{
					renderedPackages = true;
					packagesLoaded();
				}
				if(event_code_info.Error) {
					if (value != "") {
						Ext.getCmp('eventCode').markInvalid('This event code is not valid. Enter a new code or clear this field.');
					}
					Ext.getCmp('venueCountry').enable();
					Ext.getCmp('event_name').enable();
					Ext.getCmp('opening_date').enable();
					Ext.getCmp('closing_date').enable();
					Ext.getCmp('venue').enable();
					Ext.getCmp('venue_county').enable();
					Ext.getCmp('venue_town').enable();
					Ext.getCmp('organiser').enable();
					event_code_info = null;
					validEventCode = '';
					refreshQuote();
				} else {
					//update fields based on the event code
					Ext.getCmp('venueCountry').setValue(event_code_info.Country);
					Ext.getCmp('venueCountry').disable();
					Ext.getCmp('event_name').setValue(event_code_info.EventName);
					Ext.getCmp('event_name').disable();
					Ext.getCmp('opening_date').setValue(Date.parseDate(event_code_info.OpeningDate,'j/n/Y'));
					Ext.getCmp('opening_date').disable();
					if (Ext.isIE){
						if(Ext.getCmp('opening_date').wrap){
							//the wrap element width is 0px . It's alpha filter doesn't display bigger than that and so the disabled input is invisible. Remove the width from the style so the input displays. Other browsers use opacity and work ok
							Ext.getCmp('opening_date').wrap.dom.style.width = '';
						}
					}
					Ext.getCmp('closing_date').setValue(Date.parseDate(event_code_info.ClosingDate,'j/n/Y'));
					Ext.getCmp('closing_date').disable();
					if (Ext.isIE){
						if(Ext.getCmp('closing_date').wrap){
							//the wrap element width is 0px . It's alpha filter doesn't display bigger than that and so the disabled input is invisible. Remove the width from the style so the input displays. Other browsers use opacity and work ok
							Ext.getCmp('closing_date').wrap.dom.style.width = '';
						}
					}
					Ext.getCmp('venue').setValue(event_code_info.MainVenue);
					Ext.getCmp('venue').disable();
					Ext.getCmp('venue_town').setValue(event_code_info.City);
					Ext.getCmp('venue_town').disable();
					Ext.getCmp('venue_county').setValue(event_code_info.County);
					Ext.getCmp('venue_county').disable();
					Ext.getCmp('organiser').setValue(event_code_info.EventOrganiserName);
					Ext.getCmp('organiser').disable();
					validEventCode = value;
					refreshQuote();
				}
		   },
		   failure: function(response, opts) {
		   	   alert('There has been a problem connecting to the server. This may be due to a problem with your Internet connection, or we could be performing maintenance on the server. Please try again. If you continue to experience problems, contact us for further assistance.');
		   }
		});
		return true;
	}

	function refreshPackages() {
		switch(Ext.getCmp('currency').getValue()) {
			case 'Currency Pound Sterling':
				currencySymbol = '£';
				//package 1
				Ext.getDom('P1_cancellation').innerHTML = packages[0].GBP.cancellation;
				Ext.getDom('P1_propertyDamage').innerHTML = packages[0].GBP.propertyDamage;
				Ext.getDom('P1_venueDamage').innerHTML = packages[0].GBP.venueDamage;
				Ext.getDom('P1_publicLiability').innerHTML = packages[0].GBP.publicLiability;
				Ext.getDom('P1_employersLiability').innerHTML = packages[0].GBP.employersLiability;
				//package 2
				Ext.getDom('P2_cancellation').innerHTML = packages[1].GBP.cancellation;
				Ext.getDom('P2_propertyDamage').innerHTML = packages[1].GBP.propertyDamage;
				Ext.getDom('P2_venueDamage').innerHTML = packages[1].GBP.venueDamage;
				Ext.getDom('P2_publicLiability').innerHTML = packages[1].GBP.publicLiability;
				Ext.getDom('P2_employersLiability').innerHTML = packages[1].GBP.employersLiability;
				//package 3
				Ext.getDom('P3_cancellation').innerHTML = packages[2].GBP.cancellation;
				Ext.getDom('P3_propertyDamage').innerHTML = packages[2].GBP.propertyDamage;
				Ext.getDom('P3_venueDamage').innerHTML = packages[2].GBP.venueDamage;
				Ext.getDom('P3_publicLiability').innerHTML = packages[2].GBP.publicLiability;
				Ext.getDom('P3_employersLiability').innerHTML = packages[2].GBP.employersLiability;
				//package 4
				Ext.getDom('P4_cancellation').innerHTML = packages[3].GBP.cancellation;
				Ext.getDom('P4_propertyDamage').innerHTML = packages[3].GBP.propertyDamage;
				Ext.getDom('P4_venueDamage').innerHTML = packages[3].GBP.venueDamage;
				Ext.getDom('P4_publicLiability').innerHTML = packages[3].GBP.publicLiability;
				Ext.getDom('P4_employersLiability').innerHTML = packages[3].GBP.employersLiability;
				break;
			case 'Currency Euros':
				currencySymbol = '€';
				//package 1
				Ext.getDom('P1_cancellation').innerHTML = packages[0].EURO.cancellation;
				Ext.getDom('P1_propertyDamage').innerHTML = packages[0].EURO.propertyDamage;
				Ext.getDom('P1_venueDamage').innerHTML = packages[0].EURO.venueDamage;
				Ext.getDom('P1_publicLiability').innerHTML = packages[0].EURO.publicLiability;
				Ext.getDom('P1_employersLiability').innerHTML = packages[0].EURO.employersLiability;
				//package 2
				Ext.getDom('P2_cancellation').innerHTML = packages[1].EURO.cancellation;
				Ext.getDom('P2_propertyDamage').innerHTML = packages[1].EURO.propertyDamage;
				Ext.getDom('P2_venueDamage').innerHTML = packages[1].EURO.venueDamage;
				Ext.getDom('P2_publicLiability').innerHTML = packages[1].EURO.publicLiability;
				Ext.getDom('P2_employersLiability').innerHTML = packages[1].EURO.employersLiability;
				//package 3
				Ext.getDom('P3_cancellation').innerHTML = packages[2].EURO.cancellation;
				Ext.getDom('P3_propertyDamage').innerHTML = packages[2].EURO.propertyDamage;
				Ext.getDom('P3_venueDamage').innerHTML = packages[2].EURO.venueDamage;
				Ext.getDom('P3_publicLiability').innerHTML = packages[2].EURO.publicLiability;
				Ext.getDom('P3_employersLiability').innerHTML = packages[2].EURO.employersLiability;
				//package 4
				Ext.getDom('P4_cancellation').innerHTML = packages[3].EURO.cancellation;
				Ext.getDom('P4_propertyDamage').innerHTML = packages[3].EURO.propertyDamage;
				Ext.getDom('P4_venueDamage').innerHTML = packages[3].EURO.venueDamage;
				Ext.getDom('P4_publicLiability').innerHTML = packages[3].EURO.publicLiability;
				Ext.getDom('P4_employersLiability').innerHTML = packages[3].EURO.employersLiability;
				break;
			case 'Currency American Dollars':
				currencySymbol = '$';
				//package 1
				Ext.getDom('P1_cancellation').innerHTML = packages[0].USD.cancellation;
				Ext.getDom('P1_propertyDamage').innerHTML = packages[0].USD.propertyDamage;
				Ext.getDom('P1_venueDamage').innerHTML = packages[0].USD.venueDamage;
				Ext.getDom('P1_publicLiability').innerHTML = packages[0].USD.publicLiability;
				Ext.getDom('P1_employersLiability').innerHTML = packages[0].USD.employersLiability;
				//package 2
				Ext.getDom('P2_cancellation').innerHTML = packages[1].USD.cancellation;
				Ext.getDom('P2_propertyDamage').innerHTML = packages[1].USD.propertyDamage;
				Ext.getDom('P2_venueDamage').innerHTML = packages[1].USD.venueDamage;
				Ext.getDom('P2_publicLiability').innerHTML = packages[1].USD.publicLiability;
				Ext.getDom('P2_employersLiability').innerHTML = packages[1].USD.employersLiability;
				//package 3
				Ext.getDom('P3_cancellation').innerHTML = packages[2].USD.cancellation;
				Ext.getDom('P3_propertyDamage').innerHTML = packages[2].USD.propertyDamage;
				Ext.getDom('P3_venueDamage').innerHTML = packages[2].USD.venueDamage;
				Ext.getDom('P3_publicLiability').innerHTML = packages[2].USD.publicLiability;
				Ext.getDom('P3_employersLiability').innerHTML = packages[2].USD.employersLiability;
				//package 4
				Ext.getDom('P4_cancellation').innerHTML = packages[3].USD.cancellation;
				Ext.getDom('P4_propertyDamage').innerHTML = packages[3].USD.propertyDamage;
				Ext.getDom('P4_venueDamage').innerHTML = packages[3].USD.venueDamage;
				Ext.getDom('P4_publicLiability').innerHTML = packages[3].USD.publicLiability;
				Ext.getDom('P4_employersLiability').innerHTML = packages[3].USD.employersLiability;
				break;
		} 
	}

	function showLiabilityPackageOption(bool) {
		if(bool) {
			var clr = '#444444';
		} else {
			var clr = '#aaa';
		}
		Ext.get('P1_employersLiability').setStyle('color',clr);
		Ext.get('P2_employersLiability').setStyle('color',clr);
		Ext.get('P3_employersLiability').setStyle('color',clr);
		Ext.get('P4_employersLiability').setStyle('color',clr);
	}









function setStandardEventCodeSuffix() {
	var code = Ext.getCmp('eventCode').getValue();
	Ext.getCmp('eventCode').setValue(code.substr(0,code.length-1)+"S");
}
function setSpecialEventCodeSuffix() {
	var code = Ext.getCmp('eventCode').getValue();
	Ext.getCmp('eventCode').setValue(code.substr(0,code.length-1)+"W");
}


function quoteSubmitted(username,quote_id, referReason) {
	encodePassword(username,quote_id, referReason);
}

function encodePassword(username,quote_id, referReason) {
	if(Ext.getCmp('returningCustomer').collapsed) {
		active_password = Ext.getCmp('new_password').getValue();
	} else {
		active_password = Ext.getCmp('password').getValue();
	}
	/*if(active_password == '') {
		encodedPassword =  ''; //blank passwords are not updated in the database (see save_user.php). 
		return saveUser(username,quote_id, referReason);	//The password may be blank if the user was already logged in
	}*/
	encodedPassword = active_password;
	saveUser(username,quote_id, referReason);
	/*Ext.Ajax.request({
	   url: '/cgi-bin/encode.cgi',
	   params: {
	   	   data: active_password
	   },
	   success: function(response, opts) {
			result = Ext.util.JSON.decode(response.responseText);
			if(result.success) {
				encodedPassword = result.response;
				saveUser(username,quote_id, referReason);
			} else {
		   	   alert('There has been a problem connecting to the server. This may be due to a problem with your Internet connection, or we could be performing maintenance on the server. Please try again. If you continue to experience problems, contact us for further assistance.');
			}
	   },
	   failure: function(response, opts) {
	   	   alert('There has been a problem connecting to the server. This may be due to a problem with your Internet connection, or we could be performing maintenance on the server. Please try again. If you continue to experience problems, contact us for further assistance.');
	   }
	});*/
}

function refreshLogin() {
	if(loggedIn) {
		Ext.getCmp('returningCustomer').expand();
		Ext.getCmp('email').disable();
		Ext.getCmp('password').disable();
		Ext.getCmp('email').setValue(result.email);
		Ext.getCmp('personTitle').setValue(result.title);
		Ext.getCmp('first_name').setValue(result.first_name);
		Ext.getCmp('surname').setValue(result.last_name);
		Ext.getCmp('company').setValue(result.company);
		Ext.getCmp('building').setValue(result.building);
		Ext.getCmp('numberAndRoad').setValue(result.numberAndRoad);
		Ext.getCmp('district').setValue(result.district);
		Ext.getCmp('town').setValue(result.town);
		Ext.getCmp('county').setValue(result.county);
		if(Ext.getCmp('country').getValue() == '') {
			Ext.getCmp('country').setValue(result.country);
		}
		Ext.getCmp('postcode').setValue(result.postcode);
		Ext.getCmp('telephone').setValue(result.telephone);
		Ext.getCmp('fax').setValue(result.fax);
		Ext.getCmp('login').setText('Log out');
		Ext.getCmp('login').enable();
		Ext.getCmp('personTitle').focus(true);
	} else {
		Ext.getCmp('email').enable();
		Ext.getCmp('password').enable();
		Ext.getCmp('email').setValue('');
		Ext.getCmp('password').setValue('');
		Ext.getCmp('personTitle').setValue('');
		Ext.getCmp('first_name').setValue('');
		Ext.getCmp('surname').setValue('');
		Ext.getCmp('company').setValue('');
		Ext.getCmp('building').setValue('');
		Ext.getCmp('numberAndRoad').setValue('');
		Ext.getCmp('district').setValue('');
		Ext.getCmp('town').setValue('');
		Ext.getCmp('county').setValue('');
		//Ext.getCmp('country').setValue('');
		Ext.getCmp('postcode').setValue('');
		Ext.getCmp('telephone').setValue('');
		Ext.getCmp('fax').setValue('');
		Ext.getCmp('login').setText('Login');
		Ext.getCmp('login').enable();
		Ext.getCmp('email').focus(true);

	}
}


function initLogin() {
	if(user_id != 0) {
		Ext.Ajax.request({
		   url: '/site/phpeventassured/get_user.php',
		   params: {
				si_user_id: user_id
		   },
		   success: function(response, opts) {
				result = Ext.util.JSON.decode(response.responseText);
				loggedIn = result.success;
				if(result.success) {
					result = result.data;
					refreshLogin();
				} else {
			   	   alert('There has been a problem connecting to the server. This may be due to a problem with your Internet connection, or we could be performing maintenance on the server. Please try again. If you continue to experience problems, contact us for further assistance.');
				}
		   },
		   failure: function(response, opts) {
		   	   alert('There has been a problem connecting to the server. This may be due to a problem with your Internet connection, or we could be performing maintenance on the server. Please try again. If you continue to experience problems, contact us for further assistance.');
		   }
		});
	}
}

function silentLogin(username,password,quote_id, referReason) {
	//don't need to call login because save_user.php updates the session username and password
	nextStepWindow(username, quote_id, referReason);
	/*Ext.Ajax.request({
	   url: '/cgi-bin/ee/SISite/runpage.html?runpageuri=/cgi-bin/ee/login.html?email='+username+'&password='+password+'&runpagestart=JSON_START&runpageend=JSON_END&runpagemime=text',
	   success: function(response, opts) {
			nextStepWindow(username, quote_id, referReason);
	   },
	   failure: function(response, opts) {
			nextStepWindow(username, quote_id, referReason);
	   }
	});*/
}

function saveUser(username,quote_id, referReason) {
	Ext.Ajax.request({
	   url: '/site/phpeventassured/save_user.php',
	   params: {
			email: active_email,
			password: encodedPassword,
			hint: Ext.getCmp('password_hint').getValue(),
			title: Ext.getCmp('personTitle').getValue(),
			first_name: Ext.getCmp('first_name').getValue(),
			surname: Ext.getCmp('surname').getValue(),
			company: Ext.getCmp('company').getValue(),
			building: Ext.getCmp('building').getValue(),
			numberAndRoad: Ext.getCmp('numberAndRoad').getValue(),
			district: Ext.getCmp('district').getValue(),
			town: Ext.getCmp('town').getValue(),
			county: Ext.getCmp('county').getValue(),
			postcode: Ext.getCmp('postcode').getValue(),
			country: Ext.getCmp('country').getValue(),
			phone: Ext.getCmp('telephone').getValue(),
			fax: Ext.getCmp('fax').getValue()
	   },
	   success: function(response, opts) {
			result = Ext.util.JSON.decode(response.responseText);
			if(result.success) {
				silentLogin(username,active_password,quote_id, referReason);
			} else {
		   	   alert('There has been a problem connecting to the server. This may be due to a problem with your Internet connection, or we could be performing maintenance on the server. Please try again. If you continue to experience problems, contact us for further assistance.');
			}
	   },
	   failure: function(response, opts) {
	   	   alert('There has been a problem connecting to the server. This may be due to a problem with your Internet connection, or we could be performing maintenance on the server. Please try again. If you continue to experience problems, contact us for further assistance.');
	   }
	});
}

function nextStepWindow(username, quote_id, referReason) {
	Ext.Msg.hide();
	if (referReason === "") {
		if(!quotedWin){
			var htm = "";
			htm +='<h2>Your quotation is on its way to you</h2><p>An email has been sent to the email address you have provided ('+username+') containing a detailed quotation together with the completed Application Form/Statement of Facts and our Initial Disclosure and Terms of Business Document for Web Commercial Customers. Typically this will arrive in a few minutes. If it has not arrived after a few hours, please check your spam filter.<br /><br /></p><h2>Quotation Number</h2><p>Your reference number for this quotation is <b>'+quote_id+'</b>. Please make a note of this number.<br /><br /></p><h2>Review and purchase quotes</h2><p>You can review your quotes and decide to purchase at any time by visiting the My Quotes <a href="/myaccount?quote='+quote_id+'" target="_blank">My Quotes</a> section of this website.<br /><br /></p><h2>Buy Now for Instant Cover</h2><p>You can purchase your cover right now using secure Sage Pay payment by clicking the Buy button below.</p><div id="paymentform"></div>';
	        quotedWin = new Ext.Window({
	        	title: 'Quotation Confirmed',
	            layout:'fit',
	            width:550,
	            height:300,
	            resizable: false,
	            closeAction:'hide',
	            modal: true,
	            plain: true,
	            bodyStyle: 'padding: 20px',
	            html: htm,
				buttons: [{
			        text: 'Close',
			        id: 'closeButton',
			        handler: closeButtonClicked
			    },{
			        text: '<b>Buy Cover Now &gt;&gt;</b>',
			        id: 'buyButton',
			        handler: function() {buyButtonClicked(username, quote_id)}
			    }]
				});
			quotedWin.show();
		}
	} else {
		//there is a refer reason so display it, then navigate to index
		Ext.Msg.alert(
			'Automatic Quotation Unavailable','Your application needs input from one of our underwriting team, who will be in contact',
			function(){
				top.location = '/';
			});	
	}
}

function buyButtonClicked(username, quote_id) {
	var conn = new Ext.data.Connection();
	conn.on('requestcomplete', function(sender, param) {
		var response = Ext.util.JSON.decode(param.responseText);
		if (response.error == "") {
			var transaction_type = "PAYMENT"; //get from server ?
			//var live_purchaseURL="https://ukvps.protx.com/vspgateway/service/vspform-register.vsp"; 
			//var test_purchaseURL="https://ukvpstest.protx.com/vspgateway/service/vspform-register.vsp";
			//var simulator_purchaseURL="https://ukvpstest.protx.com/VSPSimulator/VSPFormGateway.asp";
			//var purchaseURL = live_purchaseURL;
			var purchaseURL = response.protx_server_url;
			var vendor = response.vendor;
			var crypt = response.crypt;
			htm = '<form action="'+purchaseURL+'" method="POST" id="VSPForm" name="VSPForm">';
			htm +='<input type="hidden" name="VPSProtocol" value="2.22">';
			htm +='<input type="hidden" name="TxType" value="'+transaction_type+'">';
			htm +='<input type="hidden" name="Vendor" value="'+vendor+'">';
			htm +='<input type="hidden" name="Crypt" value="'+crypt+'">';
			htm +='</form>';
			Ext.getDom('paymentform').innerHTML = htm;
			Ext.Msg.wait('Redirect you to the secure Sage Pay payment server','Payment');
			Ext.getDom('VSPForm').submit();

		} else {
			Ext.Msg.alert('Error',response.error);
		}
	}, { scope: this }); 
	conn.on('requestException', function(sender, param) {
		Ext.Msg.alert('Error','Unable to get order details - please try in a few seconds time');
	}, { scope: this });
	conn.request({
		url:'/site/phpeventassured/get_protx_form_data.php', 
		method: 'POST',
		params: {
			username: username,
			quote_id: quote_id
		}
	});
}

function closeButtonClicked() {
	Ext.Msg.alert('Thank you','Thank you for allowing us to quote for your event. We hope you find the email quotation we have sent you both competitive and comprehensive. To purchase cover later, simply log into this website using the email address and password you have provided.', function() {
		top.location = '/';
	});
}




/*
Script Name: Javascript Cookie Script
Author: Public Domain, with some modifications
Script Source URI: http://techpatterns.com/downloads/javascript_cookies.php
Version 1.1.1
Last Update: 4 October 2007

Changes:
1.1.1 fixes a problem with Get_Cookie that did not correctly handle case
where cookie is initialized but it has no "=" and thus no value, the 
Get_Cookie function generates a NULL exception. This was pointed out by olivier, thanks

1.1.0 fixes a problem with Get_Cookie that did not correctly handle
cases where multiple cookies might test as the same, like: site1, site

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
*/

// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );

// To use, simple do: Get_Cookie('cookie_name'); 
// replace cookie_name with the real cookie name, '' are required
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ) 
	{
		return null;
	}
}

/*
only the first 2 parameters are required, the cookie name, the cookie
value. Cookie time is in milliseconds, so the below expires will make the 
number you pass in the Set_Cookie function call the number of days the cookie
lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

Generally you don't need to worry about domain, path or secure for most applications
so unless you need that, leave those parameters blank in the function call.
*/
function Set_Cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	// if the expires variable is set, make the correct expires time, the
	// current script below will set it for x number of days, to make it
	// for hours, delete * 24, for minutes, delete * 60 * 24
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	//alert( 'today ' + today.toGMTString() );// this is for testing purpose only
	var expires_date = new Date( today.getTime() + (expires) );
	//alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}