/*!
 * Quicksearch JS V1.3
 * http://www.mobileshop.com
 *
 * Copyright (c) 2009 http://www.mobileshop.com
 *
 * Author Dan Whitfield
 *
 * Date: 26-05-2009 (Tues, 26 May 2009)
 */
 
// This is the PHP page that handles all the AJAX requests.
var ajaxHandler = "/quick_search.php";
 
// This array holds all the paramiter names for all the different form actions.
var urlParams = new Array();

// Add in the different params possible for PAYM.
urlParams["paym"] = new Array();

// Sitefind params.
urlParams["paym"][0] 		   = new Array();
urlParams["paym"][0]["manu"]  = 'manu';
urlParams["paym"][0]["model"] = 'idhandset';
urlParams["paym"][0]["net"]   = 'net';
urlParams["paym"][0]["mins"]  = 'mins';
urlParams["paym"][0]["texts"] = 'text';

// PAYM handset page params.
urlParams["paym"][1] 		   = new Array();
urlParams["paym"][1]["manu"]  = 'manu';
urlParams["paym"][1]["model"] = 'model';
urlParams["paym"][1]["net"]   = 'net[]';
urlParams["paym"][1]["mins"]  = 'min';
urlParams["paym"][1]["texts"] = 'txt';

// Add in the different params possible for PAYG.
urlParams["payg"] = new Array();

// PAYG page params.
urlParams["payg"][0] 		   = new Array();
urlParams["payg"][0]["manu"]  = 'manu';
urlParams["payg"][0]["model"] = 'model';
urlParams["payg"][0]["net"]   = 'net';

// PAYG handset page params.
urlParams["payg"][1] 		   = new Array();
urlParams["payg"][1]["manu"]  = 'manu';
urlParams["payg"][1]["model"] = 'model';
urlParams["payg"][1]["net"]   = 'net[]';
urlParams["payg"][1]["price"] = 'hp';

// So that we can drop users down to the deals tables for the different pages, the default is for the sitefind.
var anchorLink = '#list';

// Keep a track of which state the quicksearch is currently in, default is set to paym.
var formState = 'paym';

// Function to make sure that we don't display any networks that would result in no results for selected manufacturers or handsets.
function updateNetworkOptions()
{
	// Get the selected manufacturer.
	var chosenManu = $("#manuSelect").attr("value");
	
	// Get the selected model if any.
	var chosenModel = $("#modelSelect").attr("value");
	
	$.get(ajaxHandler + "?updatenetworks=true&cma=" + chosenManu + "&cmo=" + chosenModel, function(data)
	{
		// Update networkSelect with the new list of networks that are specific to the current selections.
		$("#networkSelect").html(data);
	});
}

// Function to make sure that the form sends the user to the most relevant place depending on their selections.
function updateFormAction(formState, model)
{
	// Get the selected handset's name in text for the action URL.
	var manuSelect = document.getElementById("manuSelect");
	var chosenManu = manuSelect.options[manuSelect.selectedIndex].text.replace(/ /g, "-");

	var modelSelect = document.getElementById("modelSelect");
	var chosenModel = modelSelect.options[modelSelect.selectedIndex].text.replace(/ /g, "-");

	if(formState == 'payg')
	{
		if(model == '')
		{
			$("#qsearch").attr("action", "/mobile-phones/pay-as-you-go/");
			anchorLink = '#features-jump';
		}
		else
		{
			$("#qsearch").attr("action", "/mobile-phones/" + chosenManu.toLowerCase() + "-" + chosenModel.toLowerCase() + "/pay-as-you-go.html");
		}
	}
	else if(formState == 'paym')
	{
		if(model == '')
		{
			$("#qsearch").attr("action", "/mobile-phones/site-find.php");
			anchorLink = '#list';
		}
		else
		{
			$("#qsearch").attr("action", "/mobile-phones/" + chosenManu.toLowerCase() + "-" + chosenModel.toLowerCase() + "/pay-monthly.html");
		}
	}
}

// Function to re-set event listeners because of dynamic content.
function setListeners()
{
	// Listener on manufacturer select box to update model options.
	$("#manuSelect").change(function()
	{
		var chosenManu = $("#manuSelect").attr("value");
		
		// All is the value in the PAYM any options whereas PAYG uses nothing.
		if(chosenManu == 'all' || chosenManu == '')
		{
			// Disable the select box if Any is selected.
			$("#modelSelect").html("<option value=\"\">Model:</option>");
			$("#modelSelect").attr("disabled", "disabled");
			updateNetworkOptions();
		}
		else
		{
			$.get(ajaxHandler + "?fs=" + formState + "&manu=" + chosenManu, function(data)
			{
				// Update modelSelect with the new list of models, enable modelSelect and update the networks.
				$("#modelSelect").html(data);
				$("#modelSelect").removeAttr("disabled");
				updateNetworkOptions();
			});
		}
	});
	
	// Update the netowrks available for the chosen handset.
	$("#modelSelect").change(function()
	{
		updateNetworkOptions();
		
		var chosenModel = $("#modelSelect").attr("value");
		
		// If a specific model has been chosen then change the action accordingly.
		updateFormAction(formState, chosenModel);
	});
	
	$("#submit_btn").click(function()
	{
		// Initialise all the param variables.
		var selManu  = '';
		var selModel = '';
		var selNet   = '';
		var selMins  = '';
		var selText  = '';
		var selPrice = '';
		
		// Get any selected model.
		var chosenModel = $("#modelSelect").attr("value");
		
		// Default the inner params type to 0.
		var paramType = 0;
		
		// If a model is chosen then use inner type 1 (handset pages).
		if(chosenModel != '')
		{
			paramType = 1;
		}
		
		// Assign the correct params profile to a variable for easy use.
		var params = urlParams[formState][paramType];
		
		// Get the correct action for the selection.
		var formAction = $("#qsearch").attr("action");
		
		if($("#manuSelect").attr("value") && chosenModel == '')
		{
			selManu = params["manu"] + "=" + $("#manuSelect").attr("value").toLowerCase();
		}
		
		if($("#modelSelect").attr("value") && chosenModel != '')
		{
			selModel = params["model"] + "=" + $("#modelSelect").attr("value").toLowerCase();
		}
		
		if($("#networkSelect").attr("value"))
		{
			var netSelect = $("#networkSelect").attr("value").toLowerCase();
		
			// This is because the paym finders use all instead of everything.
			if(formState == 'paym' && netSelect == 'everything')
			{
				netSelect = '';
			}
			
			if(chosenModel != '' && formState == 'payg' && netSelect == 'everything')
			{
				netSelect = '';
			}
			
			selNet = params["net"] + "=" + netSelect;
		}
		
		if($("#handsetPrice").attr("value"))
		{
			selPrice = params["price"] + "=" + $("#handsetPrice").attr("value").toLowerCase();
		}
		
		// Amended URL that doesn't include the mins or the texts.
		selManuArea = '';
		
		if(selManu != '')
		{
			selManuArea = selManu + '&';
		}
		
		selModelArea = '';
		
		if(selModel != '')
		{
			selModelArea = selModel + '&';
		}
		
		selNetArea = '';
		
		if(selNet != '')
		{
			selNetArea = selNet + '&';
		}
		
		selPriceArea = '';
		
		if(selPrice != '')
		{
			selPriceArea = selPrice + '&';
		}
		
		if(formState == 'paym' && selManu == 'manu=all' && selModel == '' && selNet == '')
		{
			window.location = "/mobile-phones/site-find.php";
			return false;
		}
		
		if(formState == 'paym' && selManuArea)
		{
			if(selManuArea == "manu=all&")
			{
				selManuArea = "";
			}
		}
		
		window.location = formAction + "?" + selManuArea + selModelArea + selNetArea.replace("everything", "") + selPriceArea;
		return false;
	});
}
 
// Has the quicksearch loaded?
if($("#quicksearch"))
{	
	// Disable the model select box as there are no options initially.
	$("#modelSelect").attr("disabled", "disabled");
	
	// Save the default forms for quick response, PAYM form in generated HTML.
	var paymForm  = $("#dynamicFormArea").html();
	var paygForm;
	
	// Get PAYG form from AJAX request that calls file_get_contents on /includes/templates/default/quick_search/payg_form.html.
	$.get(ajaxHandler + "?check=payg", function(data)
	{
  		paygForm = data;
	});
	
	// Set up a listener for PAYM/PAYG form swap select box.
	$("#contractType").change(function()
	{
		// Get the requested form type, this will be either paym or payg.
		formState = $("#contractType").attr("value");
		
		// Set the HTML of the dynamicFormArea element depending on the form type requested, re-set the modelselect to disabled and re-set all listeners for the form.
		if(formState == 'payg')
		{
			$("#dynamicFormArea").html(paygForm);
			$("#modelSelect").attr("disabled", "disabled");
			updateFormAction(formState, '');
			setListeners();
		}
		else
		{
			$("#dynamicFormArea").html(paymForm);
			$("#modelSelect").attr("disabled", "disabled");
			updateFormAction(formState, '');
			setListeners();
		}
	});
	
	setListeners();
}