//The insurance manager application wraps up our ajax request call to the insurance web service.
jQuery(function ($)
{
    var m_options = {};
    var m_vehicles = [];
    var m_REQUESTURL = "/Commerce/Insurance/REQUESTTYPECalculation.ashx";
    var m_Args =
	{
	    RESPONSETYPE: { name: "resp", value: null },
	    REQUESTTYPE: { name: "reqt", value: null },
	
	    GROUP_ID: { name: "groupId", value: null },
	    GROUP_TYPE_ID: { name: "groupTypeId", value: null },
	    
	    VEHICLES: { name: "vhls", value: null }
	};
	
	// create insurance manager jQuery plugin
    $.insuranceManager =
    {
        initialise: function (p_options)
        {
            $.extend(m_options, $.insuranceManager.defaults, p_options);
        },
        options: m_options,
        vehicles: m_vehicles,
        getData: function (p_dataType, p_requestType)
        {
            m_makeInsuranceRequest(p_dataType, p_requestType);
        },
        getCustomer: function (p_dataType, p_requestType)
        {
            m_makeInsuranceRequest(p_dataType); // use make ins request as customer details dosn't exsist m_makeCustomerRequest
        },
        onBeforeSend: on_BeforeSend,
        onSuccess: on_Success,
        onError: on_Error
    };

    $.insuranceManager.ZERO = 0;

    $.insuranceManager.responseTypes = {
        JSON: "Json",
        HTML: "Html"
    };

    $.insuranceManager.requestTypes = {
        NONE: "None",
        SINGLE: "Single",
        MULTIPLE: "List",
        CUSTOMER: "Customer"
    };

	// display states of an insurance list or single detail item, an insurance ui item will be of one of these
	// states and can be swithced from one state to another using switchUIInsuranceState
	$.insuranceManager.uiDisplayStates = {
        NONE: "None", // hide item
        LOADING: "Loading",
        CHECKING: "Checking",
        NOQUOTES: "NoQuotes",
        ERROR: "Error",
        CONTENT: "Content",
        NEW: "New", // form state
        EDIT: "Edit" // form state
    };

    $.insuranceManager.UI = {
        // main item
        INSURANCE_ITEM: ".pe-insurance-item",
        
        // single container
        INSURANCE_ITEM_FORM_CONTAINER: ".pe-insurance-form",
        INSURANCE_ITEM_SINGLE: ".pe-insurance-single",
        INSURANCE_ITEM_CHECKING_CONTAINER: ".pe-insurance-checking",
        INSURANCE_ITEM_LOADING_CONTAINER: ".pe-insurance-loading",
        INSURANCE_ITEM_RESULT_CONTAINER: ".pe-insurance-result",
        INSURANCE_ITEM_RESULT_CONTENT: ".pe-insurance-results-content",
        INSURANCE_ITEM_RESULTS_TEMPLATE: ".pe-insurance-result-template",
        INSURANCE_ITEM_RESULTS_NO_QUOTES: ".pe-insurance-noquotes",
        INSURANCE_ITEM_RESULTS_ERROR: ".pe-insurance-error",
        INSURANCE_ITEM_RESULTS_ITEM_QUOTE: ".pe-insurance-result-item-quote",
        
        // result list containters
        INSURANCE_ITEM_RESULTS_LIST: ".pe-insurance-list",
        INSURANCE_ITEM_RESULTS_LIST_ITEM: ".pe-insurance-result-list-item",
        INSURANCE_ITEM_RESULTS_LIST_ITEM_CHECKING: ".pe-insurance-result-list-checking",
        INSURANCE_ITEM_RESULTS_LIST_ITEM_LOADING: ".pe-insurance-result-list-loading",
        INSURANCE_ITEM_RESULTS_LIST_ITEM_NO_QUOTES: ".pe-insurance-result-list-noquotes",
        INSURANCE_ITEM_RESULTS_LIST_ITEM_ERROR: ".pe-insurance-result-list-error",
        INSURANCE_ITEM_RESULTS_LIST_ITEM_RESULTS: ".pe-insurance-result-list",
        INSURANCE_ITEM_RESULTS_LIST_ITEM_RESULTS_QUOTE: ".pe-insurance-result-list-quote",
        INSURANCE_ITEM_RESULTS_LIST_ITEM_TEMPLATE: ".pe-insurance-result-list-template",
        INSURANCE_ITEM_RESULTS_LIST_ITEM_RESULTS_CONTENT: ".pe-insurance-results-list-content",
        INSURANCE_ITEM_RESULTS_LIST_ITEM_ID: ".pe-insurance-result-list-item-id",
        // removed customer ui class names
        
        // vehicle input items        
        INSURANCE_ITEM_VEHICLE_CAPID: ".pe-insurance-vehicle-capid",
        INSURANCE_ITEM_VEHICLE_AGE: ".pe-insurance-vehicle-age",
        INSURANCE_ITEM_VEHICLE_YEAR: ".pe-insurance-vehicle-year",
        INSURANCE_ITEM_VEHICLE_VALUE: ".pe-insurance-vehicle-value",
        INSURANCE_ITEM_VEHICLE_ID: ".pe-insurance-vehicle-id",
        
        // customer form items
        INSURANCE_FORM_NEW: ".pe-insurance-form-new",
        INSURANCE_FORM_EDIT: ".pe-insurance-form-edit"
    };
    
    $.insuranceManager.defaults = {
        responseType: $.insuranceManager.responseTypes.JSON,
        requestType: $.insuranceManager.requestTypes.NONE,
        groupId: null,
        groupTypeId: null
    };
	
	// create the vehicle manager within the insurance manager
    $.insuranceManager.vehicle =
    {
        add: function (p_options)
        {
            var m_vehicle = $.extend({}, $.insuranceManager.vehicle.defaults, p_options);
            m_vehicles.push(m_vehicle);
        }
    };
	
	// works out from the current ui what request type we should be making.
	$.insuranceManager.getRequestType = function ()
	{
		var requestType;
		
		if ($($.insuranceManager.UI.INSURANCE_ITEM_RESULTS_LIST_ITEM).length > 0)
		{
			requestType = $.insuranceManager.requestTypes.MULTIPLE;
		}
		else if ($($.insuranceManager.UI.INSURANCE_ITEM_SINGLE).length > 0)
		{
			requestType = $.insuranceManager.requestTypes.SINGLE;
		}
		else
		{
			requestType = $.insuranceManager.requestTypes.NONE;
		}
		
		return requestType;
	};
	
	// get vehicle/s from ui to insurance manager instance
	$.insuranceManager.addVehicles = function ()
	{
		var requestType, vehicleListContainer;
		
		requestType = $.insuranceManager.getRequestType();
		vehicleListContainer = $($.insuranceManager.UI.INSURANCE_ITEM);
		
		vehicleListContainer.each(function ()
		{
			$.insuranceManager.addVehicle($(this)); // scope switched to each item
		});
	};
	
	// add a vehicle to the insurance manager instance scaping data from a ui element
	$.insuranceManager.addVehicle = function (jqVehicleInsuranceItem)
	{
		var vehicleCapId, vehicleValue, vehicleYear, vehicleId;
		
		if (jqVehicleInsuranceItem)
		{
			vehicleCapId = jqVehicleInsuranceItem.find("input.capId").val();
			vehicleValue = jqVehicleInsuranceItem.find("input.vehicleValue").val();
			vehicleYear = jqVehicleInsuranceItem.find("input.year").val();
			vehicleId = jqVehicleInsuranceItem.find("input.id").val();
		}
		else
		{
			vehicleCapId = $("input.capId").val();
			vehicleValue = $("input.vehicleValue").val();
			vehicleYear = $("input.year").val();
			vehicleId = $("input.id").val();
		}
		
		// only add vehicle with valid cap ids
		if (vehicleCapId && vehicleCapId !== 0)
		{
			$.insuranceManager.vehicle.add(
			{
				"VehicleCapId" : ((vehicleCapId) ? vehicleCapId : $.insuranceManager.ZERO),
				"VehicleValue" : ((vehicleValue) ? vehicleValue : $.insuranceManager.ZERO),
				"VehicleYear" : ((vehicleYear) ? vehicleYear :  $.insuranceManager.ZERO),
				"VehicleId"	: ((vehicleId) ? vehicleId :  $.insuranceManager.ZERO)
			});
		}
	};
	
	// returns a string of classes that can be used to target all the internal states of a insurance ui item.
	// this can be used to turn off all states in one go
	$.insuranceManager.getUIInternalStateClasses = function ()
	{
		var combindedStates, sep;
		sep = ", ";
		
		combindedStates = 
			$.insuranceManager.UI.INSURANCE_ITEM_FORM_CONTAINER + sep +
			$.insuranceManager.UI.INSURANCE_ITEM_CHECKING_CONTAINER + sep +
			$.insuranceManager.UI.INSURANCE_ITEM_LOADING_CONTAINER + sep +
			$.insuranceManager.UI.INSURANCE_ITEM_RESULT_CONTAINER + sep +
			$.insuranceManager.UI.INSURANCE_ITEM_RESULT_CONTENT + sep +
			$.insuranceManager.UI.INSURANCE_ITEM_RESULTS_NO_QUOTES + sep +
			$.insuranceManager.UI.INSURANCE_ITEM_RESULTS_ERROR + sep +
			$.insuranceManager.UI.INSURANCE_ITEM_RESULTS_LIST_ITEM_CHECKING + sep +
			$.insuranceManager.UI.INSURANCE_ITEM_RESULTS_LIST_ITEM_LOADING + sep +
			$.insuranceManager.UI.INSURANCE_ITEM_RESULTS_LIST_ITEM_NO_QUOTES + sep +
			$.insuranceManager.UI.INSURANCE_ITEM_RESULTS_LIST_ITEM_ERROR + sep +
			$.insuranceManager.UI.INSURANCE_ITEM_RESULTS_LIST_ITEM_RESULTS;
		
		return combindedStates;
	};
	
	// helper function to switch internal states of an insurance ui element
	// switches the active state and which mode the customers form should be in
	$.insuranceManager.switchUIInsuranceState = function(activeState, formState, jqUIItem)
	{
		var combindedItemStates, combindedFormStates, sep, activeStateClass, formStateClass;
		sep = ", ";
		
		// set all internal states to hidden
		combindedItemStates = $.insuranceManager.getUIInternalStateClasses();
		jqUIItem.find(combindedItemStates).hide();
		
		// set all form states to hidden
		combindedFormStates = $.insuranceManager.UI.INSURANCE_FORM_NEW + sep + $.insuranceManager.UI.INSURANCE_FORM_EDIT;
		jqUIItem.find(combindedFormStates).hide();
		
		// now work out the class of the active state to display
		switch (activeState)
		{
			case $.insuranceManager.uiDisplayStates.CHECKING:
				activeStateClass = $.insuranceManager.UI.INSURANCE_ITEM_CHECKING_CONTAINER + sep + $.insuranceManager.UI.INSURANCE_ITEM_RESULTS_LIST_ITEM_CHECKING;
				break;
			case $.insuranceManager.uiDisplayStates.NOQUOTES:
				activeStateClass = $.insuranceManager.UI.INSURANCE_ITEM_RESULTS_NO_QUOTES + sep + $.insuranceManager.UI.INSURANCE_ITEM_RESULTS_LIST_ITEM_NO_QUOTES;
				break;
			case $.insuranceManager.uiDisplayStates.ERROR:
				activeStateClass = $.insuranceManager.UI.INSURANCE_ITEM_RESULTS_ERROR + sep + $.insuranceManager.UI.INSURANCE_ITEM_RESULTS_LIST_ITEM_ERROR;
				break;
			case $.insuranceManager.uiDisplayStates.CONTENT:
				activeStateClass = $.insuranceManager.UI.INSURANCE_ITEM_RESULT_CONTAINER + sep + $.insuranceManager.UI.INSURANCE_ITEM_RESULTS_LIST_ITEM_RESULTS + sep + $.insuranceManager.UI.INSURANCE_ITEM_RESULT_CONTENT;
				break;
			case $.insuranceManager.uiDisplayStates.LOADING:
				activeStateClass = $.insuranceManager.UI.INSURANCE_ITEM_LOADING_CONTAINER + sep + $.insuranceManager.UI.INSURANCE_ITEM_RESULTS_LIST_ITEM_LOADING;
				break;
		}
		
		// if nessary show the active state
		if (activeStateClass)
		{
			jqUIItem.find(activeStateClass).show();
		}
		
		// now work out the class of the active form to display
		switch (formState)
		{
			case $.insuranceManager.uiDisplayStates.NEW:
				formStateClass = $.insuranceManager.UI.INSURANCE_FORM_NEW;
				break;
			case $.insuranceManager.uiDisplayStates.EDIT:
				formStateClass = $.insuranceManager.UI.INSURANCE_FORM_EDIT;
				break;
		}
		
		// if nessary show the active state
		if (formStateClass)
		{
			jqUIItem.find(formStateClass).show();
		}
		
		// show or hide main insurance container
		if (activeState === $.insuranceManager.uiDisplayStates.NONE && !formState)
		{
			jqUIItem.hide();
		}
		else
		{
			jqUIItem.show();
		}
	};
	
    $.insuranceManager.vehicle.defaults = {
        VehicleCapId: $.insuranceManager.ZERO,
        VehicleCapCode: $.insuranceManager.ZERO,
        VehicleYear: $.insuranceManager.ZERO,
        VehicleId: $.insuranceManager.ZERO,
        VehicleValue: $.insuranceManager.ZERO
    };

	/*
	=============================
	PRIVATE MEMBERS
	=============================
	*/
	
    // make the ajax request to the insurance proxy service.
    function m_makeInsuranceRequest(p_responseType, p_requestType)
    {
        //Sanity check our incoming request type.
        if (!p_responseType)
        {
			p_responseType = m_options.responseType;
		}
        if (!p_requestType)
        {
			p_requestType = m_options.requestType;
		}

        //Build our finance request arguments object. First set our common arguments.
        var requestArgs = $.extend({}, m_Args);
        requestArgs.RESPONSETYPE.value = p_responseType;
        requestArgs.REQUESTTYPE.value = p_requestType;
        
        requestArgs.VEHICLES.value = JSON.stringify(m_vehicles);
        
        requestArgs.GROUP_ID.value = m_options.groupId;
        requestArgs.GROUP_TYPE_ID.value = m_options.groupTypeId;

        $.ajax(
        {
            type: "POST",
            url: m_REQUESTURL.replace(/REQUESTTYPE/i, p_requestType),
            dataType: "json",
            data: toNameValueString(requestArgs),
            responseType: p_responseType,
            beforeSend: function (p_request)
            {
                $.insuranceManager.onBeforeSend(p_request, p_responseType, p_requestType);
            },
            success: function (p_response)
            {
                $.insuranceManager.onSuccess(p_response, p_responseType, p_requestType);
                /*
					SG: Logic added to remove site url, which is being appended in IE along with logo url.
					MSL: Needed for IE6 other wise https logos have the domain url prefixed to them.
                */
                if ($.browser.msie && $.browser.version <= 8)
                {
                    $("div.pe-insurance-results-list-content, div.insurance-row").each(
                        function (i)
                        {
                            // get all logo possible effected
                            var urlItems = $(this).find("a,img");
                            
                            // as we now could have multiple differing logos we need to treat each one by itself
                            urlItems.each(
								function()
								{
									var urlSource, urlDestination, urlItem, changeAttr, splitIndex;
									urlItem = $(this);
									
									if (this.src)
									{
										urlSource = urlItem.attr("src");
										changeAttr = "src";
									}
									else if(this.href)
									{
										urlSource = urlItem.attr("href");
										changeAttr = "href";
									}
									
									//alert("checking update on '" + urlSource + "' for type " + changeAttr + ".");
									
									// need to check for https and http due to customer info form, start from one in to ignore starting one
									if (urlSource && changeAttr && urlSource.indexOf("https", 1) > 0)
									{
										splitIndex = urlSource.indexOf("https", 1);
									}
									else if (urlSource && changeAttr && urlSource.indexOf("http", 1) > 0)
									{
										splitIndex = urlSource.indexOf("http", 1);
									}
									
									if (splitIndex && splitIndex > 0)
									{
										urlDestination = urlSource.substring(splitIndex, urlSource.length);
										if (urlDestination)
										{
											//alert("changing '" + urlSource + "'\n      to    \n'" + urlDestination + "'");
											urlItem.attr(changeAttr, urlDestination);
										}
									}
								}
                            );
                        }
                    );
                }
            },
            error: function ()
            {
                $.insuranceManager.onError(null, p_responseType, p_requestType);
            }
        });
    }

	/*
	=============================
	AJAX RESPONSE FUNCTIONS
	=============================
	*/

    //Default method called before the request is made.
    //In a standard incarnation this will dispay our FINANCE_ITEM matched DOM element(s).
    function on_BeforeSend(p_request, p_responseType, p_requestType)
    {
        var uiForm;
        var uiLoading;
        var uiResults;
		
		var uiInsuranceItem = (p_requestType === $.insuranceManager.requestTypes.MULTIPLE)? $($.insuranceManager.UI.INSURANCE_ITEM_RESULTS_LIST) : $("document");
		
		$.insuranceManager.switchUIInsuranceState($.insuranceManager.uiDisplayStates.LOADING, null, uiInsuranceItem);
    }

    //Default method called one the response has been recieved correctly.
    //This function can be overridden from the client application by setting the onSuccess function.
    function on_Success(p_response, p_responseType, p_requestType)
    {
        //First handle any returned server errors by switching to the error handler state.
        if (p_response.InsuranceCalculationResult.Exceptions)
        {
            on_Error(p_response, p_responseType, p_requestType);
            return;
        }
		
		// run main display state
		m_displayInsurance(p_requestType, p_response);
    }

    //Default method for handling errors should they occur.
    function on_Error(p_response, p_responseType, p_requestType)
	{
		var uiInsuranceItem;
		
		$($.insuranceManager.UI.INSURANCE_ITEM_RESULTS_ERROR + ', ' + $.insuranceManager.UI.INSURANCE_ITEM_RESULTS_LIST_ITEM_ERROR).each(
			function()
			{
				$(this).html(p_response.InsuranceCalculationResult.Exceptions[0].message["#cdata-section"]);
				//$(this).show();
			}
		);
        
        $.insuranceManager.switchUIInsuranceState($.insuranceManager.uiDisplayStates.ERROR, $.insuranceManager.uiDisplayStates.NEW, $($.insuranceManager.UI.INSURANCE_ITEM));
    }
	
	/*
	=============================
	UI STATE FUNCTIONS
	=============================
	*/
	
	// this function process the all successfull responses from code weavers and renders the correct state of the ui
	function m_displayInsurance(p_requestType, p_response)
	{
		var customerFormUrl, jqUIInsuranceItems;
		
		jqUIInsuranceItems = $($.insuranceManager.UI.INSURANCE_ITEM);
		customerFormUrl = getCustomerFormUrl(p_response);
		
		// we always want to set the form link so that a customer can add or edit their details
		if (customerFormUrl)
		{
			$($.insuranceManager.UI.INSURANCE_ITEM + " a.customer-form").attr("href",customerFormUrl);
		}
		
		// check response for customer state
		if (returnedQuotes(p_response))
		{
			// render the state of each item
			jqUIInsuranceItems.each(
				function()
				{
					m_displayInsuranceUIItem($(this), p_requestType, p_response);
				}
			);
			
			// state is switched within the m_displayInsuranceUIItem
		}
		// check if we have a customer form url
		else if (customerFormUrl)
		{
			// customer form state
			$.insuranceManager.switchUIInsuranceState($.insuranceManager.uiDisplayStates.NONE, $.insuranceManager.uiDisplayStates.NEW, jqUIInsuranceItems);
		}
		// other wise we do not have a valid response
		else
		{
			// error
			$.insuranceManager.switchUIInsuranceState($.insuranceManager.uiDisplayStates.NOQUOTES, null, jqUIInsuranceItems);
		}
	}
	
	// render the correct state of a single insurance item
	function m_displayInsuranceUIItem(jqUiItem, p_requestType, p_response)
	{
		var vehicleId, quoteItem, foundQuotes, quoteAppended;
		
		vehicleId = jqUiItem.find($.insuranceManager.UI.INSURANCE_ITEM_VEHICLE_ID).val();
		quoteItem = getDataItemFromList(p_response, vehicleId);
		foundQuotes = hasQuotes(quoteItem);
		
		if (foundQuotes)
		{
			for (var i = 0; i < quoteItem.Companies.Company.length; i = i + 1)
			{
				quoteAppended = appendCompanyQuote(jqUiItem, p_requestType, quoteItem.Companies.Company[i], quoteItem.Vehicle, i);
				
				if (p_requestType === $.insuranceManager.requestTypes.MULTIPLE && quoteAppended)
				{
					break; // we only need one quote on a list
				}
			}
			
			// show results content
			$.insuranceManager.switchUIInsuranceState($.insuranceManager.uiDisplayStates.CONTENT, $.insuranceManager.uiDisplayStates.EDIT, jqUiItem);
		}
		else
		{
			// show no quotes message
			$.insuranceManager.switchUIInsuranceState($.insuranceManager.uiDisplayStates.NOQUOTES, $.insuranceManager.uiDisplayStates.EDIT, jqUiItem);
		}
	}
	
	// a function that creates a quote template and appends it to the provided container
	function appendCompanyQuote(jqContainer, p_requestType, companyQuote, vehicleQuotedOn, quoteIndex)
	{
			var quoteAppended, templateClass, bestQuoteOnly, classIdPrefix, classResultContent, uiResultContent;
			
			quoteAppended = false;
			
			// set request dependant ui settings
			if (p_requestType === $.insuranceManager.requestTypes.MULTIPLE)
			{
				templateClass = $.insuranceManager.UI.INSURANCE_ITEM_RESULTS_LIST_ITEM_TEMPLATE;
				classIdPrefix = $.insuranceManager.UI.INSURANCE_ITEM_RESULTS_LIST_ITEM_RESULTS_QUOTE;
				classResultContent = $.insuranceManager.UI.INSURANCE_ITEM_RESULTS_LIST_ITEM_RESULTS_CONTENT;
				bestQuoteOnly = true;
			}
			else
			{
				templateClass = $.insuranceManager.UI.INSURANCE_ITEM_RESULTS_TEMPLATE;
				classIdPrefix = $.insuranceManager.UI.INSURANCE_ITEM_RESULTS_ITEM_QUOTE;
				classResultContent = $.insuranceManager.UI.INSURANCE_ITEM_RESULT_CONTENT;//pe-insurance-results-content
				bestQuoteOnly = false;
			}
			
			// get result content container
			uiResultContent = jqContainer.find(classResultContent);
			// reset result on first quote render
			if (quoteIndex === 0)
			{
				uiResultContent.html("");
				uiResultContent.show();
			}
			
			if (
					// check null reference
					(companyQuote) &&
					// best quote filter
					(
						// show all quotes if we don't need to filter
						!(bestQuoteOnly) ||
						// show only best quotes if nessary (list mode)
						(
							(bestQuoteOnly) &&
							(companyQuote._bestquote) &&
							(companyQuote._bestquote === "true")
						)
					) &&
					// premium unavailable filter
					(
						// show if attribute not returned
						!(companyQuote.PremiumUnavailable) ||
						// show if attribute not true
						(
							(companyQuote.PremiumUnavailable) &&
							(companyQuote.PremiumUnavailable !== "True")
						)
					)
				)
			{
				// tidy up the numbers
				companyQuote.MonthlyPremium = formatCurrency(companyQuote.MonthlyPremium);
				companyQuote.AnnualPremium = formatCurrency(companyQuote.AnnualPremium);
				
				var quoteTemplate, classId, uiResultContent;
				
				// create clone
				quoteTemplate = jqContainer.find(templateClass).clone();
				
				// replace placeholders
				replaceEncodedDataPlaceholders(companyQuote, quoteTemplate);
				
				// create identifying class
				classId = classIdPrefix + quoteIndex;
				
				// swap classes
				quoteTemplate.removeClass(templateClass.substring(1)).addClass(classId.substring(1));
				
				// populate the application form
				//populateApplicationForm(quoteTemplate, vehicleQuotedOn, companyQuote);
				
				// output and show template into result content
				uiResultContent.append(quoteTemplate);
				quoteTemplate.show();
				quoteAppended = true;
			}
			
			return quoteAppended;
	}
	
	/*
	=============================
	HEPLER FUNCTIONS
	=============================
	*/
	
	// helper function to check if a quote reponse item has quotes that we can use on the UI
	function hasQuotes(quotesItem)
	{
		var hasQuotes, refusalCount;
		
		hasQuotes = false;
		refusalCount = 0;
		
		if (quotesItem && quotesItem.Companies && quotesItem.Companies.Company)
		{
			for (var i = 0; i < quotesItem.Companies.Company.length; i = i + 1)
			{
				if (quotesItem.Companies.Company[i].PremiumUnavailable === 'True')
				{
					refusalCount = refusalCount + 1;
				}
			}
			
			hasQuotes = (quotesItem.Companies.Company.length > refusalCount);
		}
		
		return hasQuotes;
	}
	
	// helper function to check if the response contains any quote calculation
	function returnedQuotes (p_response)
	{
		return (
				(p_response) &&
				(p_response.InsuranceCalculationResult) &&
				(p_response.InsuranceCalculationResult.Calculations) &&
				(p_response.InsuranceCalculationResult.Calculations.Calculation) &&
				(
					// check for muliple quotes
					(
						(p_response.InsuranceCalculationResult.Calculations.Calculation.length) &&
						(p_response.InsuranceCalculationResult.Calculations.Calculation.length > 0)
					) ||
					// check for single quote
					(
						(p_response.InsuranceCalculationResult.Calculations.Calculation.Companies) &&
						(p_response.InsuranceCalculationResult.Calculations.Calculation.Vehicle)
					)
				)
			);
	}
	
	// helper function to get the url of the customer details form from the response
	function getCustomerFormUrl (p_response)
	{
		var url;
		
		if (
				(p_response) &&
				(p_response.InsuranceCalculationResult) &&
				(p_response.InsuranceCalculationResult.CustomerDetailsForm) &&
				(p_response.InsuranceCalculationResult.CustomerDetailsForm.Url)
			)
		{
			url = p_response.InsuranceCalculationResult.CustomerDetailsForm.Url;
		}
		
		return url;
	}
	
    //fucntion used to get a single insurance item from the full list returned, this is identified by the ID of the vehicle
    function getDataItemFromList (p_response, p_DataItemId)
    {
        var dataItem;
        
        // if response has calculation then get quote item
        if (returnedQuotes(p_response))
		{
			// if an id hasn't been provided or we only have one quote then get first quote
			if (!p_response.InsuranceCalculationResult.Calculations.Calculation.length)
			{
				dataItem = p_response.InsuranceCalculationResult.Calculations.Calculation;
				
				// ensure first quote matches incomming data id if we have an incomming data id
				if (
						(p_DataItemId) &&
						(p_DataItemId !== 0) &&
						(dataItem) &&
						(parseInt(dataItem.Vehicle.VehicleId) !== parseInt(p_DataItemId))
					)
				{
					dataItem = null; // as it does not match set to null
				}
			}
			else
			{
				// if a data id hasn't been provided then return first quote
				if (!p_DataItemId || p_DataItemId === 0)
				{
					dataItem = p_response.InsuranceCalculationResult.Calculations.Calculation[0];
				}
				else
				{
					// get matching quote item
					for (var i = 0; i < p_response.InsuranceCalculationResult.Calculations.Calculation.length; i = i + 1)
					{
						// get current company quote
						dataItem = p_response.InsuranceCalculationResult.Calculations.Calculation[i];
						
						// check if it matches
						if (parseInt(dataItem.Vehicle.VehicleId) == parseInt(p_DataItemId))
						{
							dataItem = p_response.InsuranceCalculationResult.Calculations.Calculation[i];
							break;
						}
						
						// reset company quote
						dataItem = null;
					}
				}
			}
		}
		
        return dataItem;
    }
});