var gHandsetCost = new Array();
var gAverageCost = new Array();
var gMinutes = new Array();
var gMonthlyCost = new Array();
var gContractLength = new Array();
var gTexts = new Array();
var gInternet = new Array();

var gMode = '';
var gProductID = '';
var gProductClassID = '';

var gContractLengthSelection = 0;
var gHandsetCostSelection = 0;
var gAverageCostSelection = 0;
var gInternetSelection = 0;

var gDealsCache = [];
var gHandsetsCache = [];

var gInitSliders = false;
var gInitAdvancedSliders = false;
var gDisableDealFetch = false;
var gControlsDisabled = false;

var gDealsLoadedFn;

var gChooseHandsetOpen = false;
var gChooseHandsetLinkText;
var gDealSummaryId = 0;

var gTmrWaitShow = 100; /* 500; */
var gTmrWaitHide = 250;	/* 750; */

function dealFinderInitialiseOnLoad(mode, productID, productClassID, dealsLoaded) {

	if (typeof(mode) != 'undefined' )
		gMode = mode;

	if ( typeof(productID) != 'undefined' )
		gProductID = productID;
	
	if ( typeof(productClassID) != 'undefined' )
		gProductClassID = productClassID;
		
	if ( typeof(dealsLoaded) == 'function' )
		gDealsLoadedFn = dealsLoaded;
	
	$('#deal_finder_choose_handset .deal_handset_dialog_close').click(function() {
		$('#deal_finder_choose_handset').dialog('close');
	});
	$('#deal_finder_choose_handset')
		.find('.deal_handset_dialog_close')
			.hover(function() {
					$(this).attr('class','deal_handset_dialog_close_hover');
				}, function () {
					$(this).attr('class','deal_handset_dialog_close');
				})
			.end()
		.dialog({autoOpen:false,
  			resizable:false,
  			modal:true,
  			draggable:false,
  			width:'765px',
  			height: 'auto',
  			title: 'Select Handset For Deal',
  			overlay: {"background-color": "white",
  				opacity: 0.6},
  			dialogClass: 'deal_handset_dialog'
  		}).removeClass('deal_handset_dialog_items_hide')
  		.addClass('deal_handset_dialog_items');

	gContractLength.push({text: 'Don\'t Mind', search: ''});
	gContractLength.push({text: '6 months', search: '6'});
	gContractLength.push({text: '12 months', search: '12'});
	gContractLength.push({text: '18 months', search: '18'});
	gContractLength.push({text: '24 months', search: '24'});
	$('#contract_length_output').html(gContractLength[0].text);
	$('#contract_length_max').html(gContractLength[0].text);
	$('#contract_length_min').html(gContractLength[gContractLength.length-1].text);
	gContractLengthSelection=0;

	gHandsetCost.push({text: 'Don\'t Mind', search: ''});
	gHandsetCost.push({text: 'Free', search: '0'});
	gHandsetCost.push({text: '&#163;10', search: '10'});
	gHandsetCost.push({text: '&#163;20', search: '20'});
	gHandsetCost.push({text: '&#163;30', search: '30'});
	gHandsetCost.push({text: '&#163;40', search: '40'});
	gHandsetCost.push({text: '&#163;50', search: '50'});
	gHandsetCost.push({text: '&#163;75', search: '75'});
	gHandsetCost.push({text: '&#163;100', search: '100'});
	gHandsetCost.push({text: '&#163;150', search: '150'});
	gHandsetCost.push({text: '&#163;200', search: '200'});
	gHandsetCost.push({text: '&#163;250', search: '250'});
	gHandsetCost.push({text: '&#163;400', search: '400'});
	$('#phone_cost_output').html(gHandsetCost[0].text);
	$('#phone_cost_max').html(gHandsetCost[0].text);
	$('#phone_cost_min').html(gHandsetCost[gHandsetCost.length-1].text);
	gHandsetCostSelection=0;

	gMinutes.push({text: 'Don\'t Mind', search: ''});
	gMinutes.push({text: '50', search: '50'});
	gMinutes.push({text: '100', search: '100'});
	gMinutes.push({text: '150', search: '150'});
	gMinutes.push({text: '200', search: '200'});
	gMinutes.push({text: '250', search: '250'});
	gMinutes.push({text: '300', search: '300'});
	gMinutes.push({text: '400', search: '400'});
	gMinutes.push({text: '500', search: '500'});
	gMinutes.push({text: '600', search: '600'});
	gMinutes.push({text: '700', search: '700'});
	gMinutes.push({text: '800', search: '800'});
	gMinutes.push({text: '1000', search: '1000'});
	gMinutes.push({text: '1500', search: '1500'});
	gMinutes.push({text: 'Unlimited', search: '9999'});
	$('#minutes_output').html(gMinutes[0].text);
	$('#minutes_max').html(gMinutes[0].text);
	$('#minutes_min').html(gMinutes[gMinutes.length-1].text);

	gMonthlyCost.push({text: 'Don\'t Mind', search: ''});
	gMonthlyCost.push({text: 'FREE', search: '0'});
	gMonthlyCost.push({text: '&#163;10', search: '10'});
	gMonthlyCost.push({text: '&#163;15', search: '15'});
	gMonthlyCost.push({text: '&#163;20', search: '20'});
	gMonthlyCost.push({text: '&#163;25', search: '25'});
	gMonthlyCost.push({text: '&#163;30', search: '30'});
	gMonthlyCost.push({text: '&#163;35', search: '35'});
	gMonthlyCost.push({text: '&#163;40', search: '40'});
	gMonthlyCost.push({text: '&#163;45', search: '45'});
	gMonthlyCost.push({text: '&#163;50', search: '50'});
	gMonthlyCost.push({text: '&#163;60', search: '60'});
	gMonthlyCost.push({text: '&#163;75', search: '75'});
	$('#monthly_cost_output').html(gMonthlyCost[0].text);
	$('#monthly_cost_max').html(gMonthlyCost[0].text);
	$('#monthly_cost_min').html(gMonthlyCost[gMonthlyCost.length-1].text);

	gTexts.push({text: 'Don\'t Mind', search: ''});
	gTexts.push({text: '100', search: '100'});
	gTexts.push({text: '200', search: '200'});
	gTexts.push({text: '300', search: '300'});
	gTexts.push({text: '400', search: '400'});
	gTexts.push({text: '500', search: '500'});
	gTexts.push({text: '600', search: '600'});
	gTexts.push({text: '700', search: '700'});
	gTexts.push({text: '800', search: '800'});
	gTexts.push({text: '900', search: '900'});
	gTexts.push({text: '1000', search: '1000'});
	gTexts.push({text: '1200', search: '1200'});
	gTexts.push({text: '1500', search: '1500'});
	gTexts.push({text: '2000', search: '2000'});
	gTexts.push({text: 'Unlimited', search: '9999'});
	$('#texts_output').html(gTexts[0].text);
	$('#texts_max').html(gTexts[0].text);
	$('#texts_min').html(gTexts[gTexts.length-1].text);

	gAverageCost.push({text: 'Don\'t Mind', search: ''});
	gAverageCost.push({text: '&#163;10', search: '10'});
	gAverageCost.push({text: '&#163;20', search: '20'});
	gAverageCost.push({text: '&#163;30', search: '30'});
	gAverageCost.push({text: '&#163;40', search: '40'});
	gAverageCost.push({text: '&#163;50', search: '50'});
	gAverageCost.push({text: '&#163;75', search: '75'});
	gAverageCost.push({text: '&#163;100', search: '100'});
	gAverageCost.push({text: '&#163;150', search: '150'});
	gAverageCost.push({text: '&#163;200', search: '200'});
	gAverageCost.push({text: '&#163;250', search: '250'});
	gAverageCost.push({text: '&#163;400', search: '400'});
	$('#average_cost_output').html(gAverageCost[0].text);
	$('#average_cost_max').html(gAverageCost[0].text);
	$('#average_cost_min').html(gAverageCost[gAverageCost.length-1].text);
	gAverageCostSelection=0
	
	gInternet.push({text: 'Don\'t Mind', search: ''});
	gInternet.push({text: '500 MB', search: '0.5'});
	gInternet.push({text: '1 GB', search: '1'});
	gInternet.push({text: '5 GB', search: '5'});
	gInternet.push({text: '10 GB', search: '10'});
	gInternet.push({text: 'Unlimited', search: '9999'});
	$('#internet_output').html(gInternet[0].text);
	$('#internet_max').html(gInternet[0].text);
	$('#internet_min').html(gInternet[gInternet.length-1].text);
	gInternetSelection=0;
	
	$('#deal_finder_show_advanced_a').click(function(event) {
			event.preventDefault();
			if ( !gControlsDisabled ) {
				$('#deal_finder_show_advanced')
					.removeClass('deal_finder_advanced_label')
					.addClass('deal_finder_advanced_label_hide');
				$('#deal_finder_hide_advanced')
					.removeClass('deal_finder_advanced_label_hide')
					.addClass('deal_finder_advanced_label');
				$("#deal_finder_advanced")
					.show();
				initAdvancedSliders();
			}
		});
	$('#deal_finder_hide_advanced_a').click(function(event) {
			event.preventDefault();
			if ( !gControlsDisabled ) {	
				$('#deal_finder_hide_advanced')
					.removeClass('deal_finder_advanced_label')
					.addClass('deal_finder_advanced_label_hide');
				$('#deal_finder_show_advanced')
					.removeClass('deal_finder_advanced_label_hide')
					.addClass('deal_finder_advanced_label');
				$("#deal_finder_advanced")
					.hide();
			}
		});
	$('#deal_finder_advanced').hide();
	
	$('#deal_finder_networks a').click(function(event) {
			event.preventDefault();
			if ( !gControlsDisabled ) {	
				var checkbox = $(this).parent();
				var doFindDeals = false;
				if ( checkbox.hasClass('checked') ) {
					checkbox
						.removeClass('checked')
						.addClass('unchecked');
					doFindDeals = true;
				} else if ( checkbox.hasClass('unchecked') ) {
					checkbox
						.removeClass('unchecked')
						.addClass('checked');
					doFindDeals = true;
				}
				if ( doFindDeals )
					findDeals();
			}
		});
		
	$('#free_phones a').click(function(event) {
			event.preventDefault();
			if ( !gControlsDisabled ) {	
				var checkbox = $(this).parent();
				var doFindDeals = false;
				if ( checkbox.hasClass('checked') ) {
					checkbox
						.removeClass('checked')
						.addClass('unchecked');
					$(this).html('Click to only show FREE phones');
					doFindDeals = true;
				} else if ( checkbox.hasClass('unchecked') ) {
					checkbox
						.removeClass('unchecked')
						.addClass('checked');
					$(this).html('Click to show all deals');
					doFindDeals = true;
				}
				if ( doFindDeals )
					findDeals();
			}
		});
}

function dealFinderInitialiseHandsets() {
	createDropDown('select_handset_type','hform_',
			'deal_finder_default_handset_help_A',
			'deal_finder_handset_help_A',
			'deal_finder_handset_panel_A1',
			findHandsets);

	createDropDown('select_handset_camera','hcamera_',
			'deal_finder_default_handset_help_A',
			'deal_finder_handset_help_A',
			'deal_finder_handset_panel_A1',
			findHandsets);

	createDropDown('select_handset_function','hmain_',
			'deal_finder_default_handset_help_A',
			'deal_finder_handset_help_A',
			'deal_finder_handset_panel_A2',
			findHandsets);

	createDropDown('select_handset_manufacturer','hmfr_',
			'deal_finder_default_handset_help_A',
			'deal_finder_handset_help_A',
			'deal_finder_handset_panel_A2',
			findHandsets);


	createCheckbox('select_handset_best_seller', false,
			'deal_finder_default_handset_help_A',
			'deal_finder_handset_help_A',
			findHandsets);
	
	createCheckbox('select_handset_latest', false,
			'deal_finder_default_handset_help_A',
			'deal_finder_handset_help_A',
			findHandsets);

	
	createMultiChoice('select_handset_features',
			'deal_finder_default_handset_help_A',
			'deal_finder_handset_help_A',
			findHandsets);

}

function resetHandsetFinder() {
	selectDropDown('select_handset_type','hform_0');
	selectDropDown('select_handset_camera','hcamera_0');
	selectDropDown('select_handset_function','hmain_0');
	selectDropDown('select_handset_manufacturer','hmfr_0');
	selectDropDown('select_handset_rating','hrating_0');
	
	setCheckboxChecked('select_handset_best_seller',false);
	setCheckboxChecked('select_handset_latest',false);

	resetMultiChoiceSelected('select_handset_features');
}

function createDropDown(id,selected,defaultHelpId,helpPanelId, containingDivId, callback) {
	var tmrHideId = newId('timer');
	var tmrShowId = newId('timer');
	var jChoices = $('#' + id + '_choices_inner');
	var fnHideTimer = function() {
			jChoices.hide();
			$('#'+containingDivId).css('overflow','hidden');
		};
	var fnShowTimer = function() {
			if ( !jChoices.is(':visible') ) {
/*
				var jValue = $('#' + id + '_value');
				var winH = $(window).height();
				var winST = $(window).scrollTop();
				var valOfs = jValue.offset();
				var valH = jValue.outerHeight();
				var dropH = jChoices.outerHeight();
				
				var spcHa = valOfs.top-winST;
				var spcHb = winH-(valOfs.top+valH)+winST;
				
				if ( spcHb < dropH && spcHa > spcHb) {
					jChoices.css('top',0-dropH-valH + 'px');
				} else {
					jChoices.css('top','0px');
				}
				$('#'+containingDivId).css('overflow','visible');
*/
				jChoices.show();
			}
		};
	
	jChoices
		.hover(function() {
				$('#' + helpPanelId).html($('#' + id + '_help').html());
				jChoices.stopTime(tmrHideId);
			},function() {
				$('#' + helpPanelId).html($('#' + defaultHelpId).html());
				jChoices.oneTime(gTmrWaitHide,tmrHideId,fnHideTimer);
			});
	$('#' + id + '_choices_close')
		.click(function() {
				fnHideTimer();
			})
		.hover(function() {
				$(this).addClass('handset_dropdown_choices_close_hover');
			},function() {
				$(this).removeClass('handset_dropdown_choices_close_hover');
			});
	$('#' + id + '_choices_inner li.handset_dropdown_choice')
		.hover(function() {
				var jItemHelp = $('#' + this.id + '_help');
				$(this).addClass('handset_dropdown_choice_hover');
				if ( jItemHelp.length > 0 )
					$('#' + helpPanelId).html(jItemHelp.html());
			}, function() {
				$(this).removeClass('handset_dropdown_choice_hover');
				$('#' + helpPanelId).html($('#' + id + '_help').html());
			})
		.click(function() {
				jChoices.hide();
				selectDropDown(id,this.id,callback);
				return false;
			});
	$('#' + id + '_value')
		.html($('#' + selected).html())
		.click(function() {
				if ( !jChoices.is(':visible') )
					jChoices.show();
			})
		.hover(function() {
				$('#' + helpPanelId).html($('#' + id + '_help').html());
				jChoices.oneTime(gTmrWaitShow,tmrShowId,fnShowTimer);
				jChoices.stopTime(tmrHideId);
			},function() {
				$('#' + helpPanelId).html($('#' + defaultHelpId).html());
				jChoices.stopTime(tmrShowId);
				if ( jChoices.is(':visible') )
					jChoices.oneTime(gTmrWaitHide,tmrHideId,fnHideTimer);
			});
	$('#' + selected)
		.removeClass('handset_dropdown_choice')
		.addClass('handset_dropdown_choice_selected')
	
	var jId = $('#' + id);
	if ( jId.length > 0 )
		jId.get(0).dropDownId = selected;
}

function selectDropDown(id, selectedId, callback) {
	var item;
	var jItem = $('#' + id); 
	var jSelected = $('#' + selectedId)
	
	if ( jItem.length > 0 ) {
		 item = jItem.get(0);
		$('#' + id + '_value')
			.html(jSelected.html());
		if ( item.dropDownId != selectedId ) {
			item.dropDownId = selectedId;
			$('#' + id + '_choices_inner li.handset_dropdown_choice_selected')
				.removeClass('handset_dropdown_choice_selected')
				.addClass('handset_dropdown_choice')					
			jSelected
				.removeClass('handset_dropdown_choice')
				.addClass('handset_dropdown_choice_selected')
			if ( typeof(callback) == 'function' )
				callback();
		}
	}
}

function getDropDownSelectedId(id) {
	var selectedId = '';
	var jId = $('#' + id);
	
	if ( jId.length > 0 ) {
		if ( typeof(jId.get(0).dropDownId) != 'undefined' )
			selectedId = jId.get(0).dropDownId;
	}
	return selectedId;
}

function getIdValue(id) {
	var value = '';
	if ( id.length > 0 ) {
		var separator = id.indexOf('_');
		
		if ( separator >= 0 ) {
			value = id.substring(separator+1,id.length);
		}
	}
	return value;
}

function getDropDownSelectedIdValue(id) {
	return getIdValue(getDropDownSelectedId(id));
	
}

function createMultiChoice(id,defaultHelpId,helpPanelId, callback) {
	var tmrHideId = newId('timer');
	var tmrShowId = newId('timer');
	var jChoices = $('#' + id + '_choices_inner');
	var fnHideTimer = function() {
			if ( jChoices.is(':visible') ) {
				var selection;
				jChoices.hide();
				selection = getMultiChoiceSelectedIds(id);
				if ( selection != jChoices.get(0).selection ) {
					jChoices.get(0).selection = selection;
					if ( typeof(callback) == 'function' )
						callback();
				}
			}
		};
	var fnShowTimer = function() {
			if ( !jChoices.is(':visible') ) {
				jChoices.show();
			}				
		};

	jChoices
		.hover(function() {
				$('#' + helpPanelId).html($('#' + id + '_help').html());
				jChoices.stopTime(tmrHideId);
			},function() {
				$('#' + helpPanelId).html($('#' + defaultHelpId).html());
				jChoices.oneTime(gTmrWaitHide,tmrHideId,fnHideTimer);
			});
	$('#' + id + '_choices_inner')
		.hover(function() {
				jChoices.stopTime(tmrHideId);
			}, function() {
				jChoices.oneTime(100,tmrHideId,fnHideTimer);
			});
	$('#' + id + '_choices_inner li')
		.hover(function() {
				var jItemHelp = $('#' + this.id + '_help');
				$(this).addClass('handset_multichoice_choice_hover');
				if ( jItemHelp.length > 0 )
					$('#' + helpPanelId).html(jItemHelp.html());
			}, function() {
				$(this).removeClass('handset_multichoice_choice_hover');
				$('#' + helpPanelId).html($('#' + id + '_help').html());
			})
		.click(function() {
				jThis = $(this);
				
				if ( jThis.hasClass('handset_multichoice_choice_selected') ) {
					jThis.removeClass('handset_multichoice_choice_selected');
				} else {
					jThis.addClass('handset_multichoice_choice_selected');
				}
				showMultiChoiceSelection(id);
				return false;
			});
	$('#' + id + '_choices_close')
		.click(function() {
				fnHideTimer();
			})
		.hover(function() {
				$(this).addClass('handset_multichoice_choices_close_hover');
			},function() {
				$(this).removeClass('handset_multichoice_choices_close_hover');
			});
	$('#' + id + '_value')
		.click(function() {				
				fnShowTimer();
			})
		.hover(function() {
				$('#' + helpPanelId).html($('#' + id + '_help').html());
				jChoices.oneTime(gTmrWaitShow,tmrShowId,fnShowTimer);
				jChoices.stopTime(tmrHideId);
			},function() {
				$('#' + helpPanelId).html($('#' + defaultHelpId).html());
				jChoices.stopTime(tmrShowId);
				if ( jChoices.is(':visible') )
					jChoices.oneTime(gTmrWaitHide,tmrHideId,fnHideTimer);
			});
	showMultiChoiceSelection(id);
	jChoices.get(0).selection = getMultiChoiceSelectedIds(id);
}

function showMultiChoiceSelection(id) {
	var html = '';
	$('#' + id + '_choices_inner li.handset_multichoice_choice_selected')
		.each(function() {
				html += '<div class="' + id + '_choice_value">' + $(this).html() + '</div>';
			});
	if ( html.length == 0 )
		html = "Select features...";
	$('#' + id + '_value').html(html);
}

function getMultiChoiceSelectedIds(id) {
	var selectedId = '';
	
	$('#' + id + '_choices_inner li.handset_multichoice_choice_selected')
		.each(function() {
				if ( this.id.length > 0 ) {
					if ( selectedId.length != 0 )
						selectedId += ',';
					selectedId += this.id;
				}
			});
	return selectedId;
}

function resetMultiChoiceSelected(id) {

	$('#' + id + '_choices_inner li.handset_multichoice_choice_selected')
		.removeClass('handset_multichoice_choice_selected');
	showMultiChoiceSelection(id);
	jChoices.get(0).selection = getMultiChoiceSelectedIds(id);
}

function getMultiChoiceSelectedIdValues(id) {
	var selectedId = '';
	
	$('#' + id + '_choices_inner li.handset_multichoice_choice_selected')
		.each(function() {
				if ( this.id.length > 0 ) {
					var value = getIdValue(this.id);

					if ( value.length > 0 ) {
						if ( selectedId.length != 0 )
							selectedId += ',';
						selectedId += value;
					}
				}
			});
	return selectedId;
}

function createCheckbox(id,checked,defaultHelpId,helpPanelId, callback) {
	var jId = $('#' + id);
	
	if ( jId.length > 0 ) {
		jId
			.hover(function() {
					$('#' + helpPanelId).html($('#' + id + '_help').html());
				},function() {
					$('#' + helpPanelId).html($('#' + defaultHelpId).html());
				})
			.click(function() {
					setCheckboxChecked(id,!this.checked);
					if ( typeof(callback) == 'function' )
						callback();
					return false;
				});
		setCheckboxChecked(id,checked);
	}
}

function setCheckboxChecked(id,checked) {
	var jCheckbox = $('#' + id);
	
	if ( jCheckbox.length > 0 ) {
		jCheckbox 
			.get(0).checked = checked;
		if ( checked ) {
			jCheckbox.addClass('handset_checkbox_checked');
		} else {
			jCheckbox.removeClass('handset_checkbox_checked');
		}
	}
}

function getCheckboxChecked(id) {
	var checked = false;
	var jId = $('#' + id);
	
	if ( jId.length > 0 )
		checked = jId.get(0).checked;

	return checked;
}

function getCheckboxCheckedSql(id) {
	if ( getCheckboxChecked(id) ) {
		return '1';
	} else {
		return '';
	}
}


function findSliderIndex(items,search) {
	var found = 0;

	for (i = 0 ; i < items.length ; i++) {
		if ( items[i].search == search ) {
			found = i ;
			break;
		}
	}
	return found;
}

function disableControls() {
	gControlsDisabled = true;
	$('#contract_length').slider("disable");
	$('#average_cost').slider("disable");
	$('#minutes').slider("disable");
	$('#monthly_cost').slider("disable");
	$('#phone_cost').slider("disable");
	$('#texts').slider("disable");
	$('#internet').slider("disable");
}	

function enableControls() {
	gControlsDisabled = false;
	$('#contract_length').slider("enable");
	$('#average_cost').slider("enable");
	$('#minutes').slider("enable");
	$('#monthly_cost').slider("enable");
	$('#phone_cost').slider("enable");
	$('#texts').slider("enable");
	$('#internet').slider("enable");
}

function initialiseSliders() {
	if ( !gInitSliders ) {
		$('#free_phones')
			.hover(function() {
				$('#deal_finder_help_A').html($('#free_phones_help').html());
			}, function() {
				$('#deal_finder_help_A').html($('#deal_finder_default_help_A').html());
			});
		$('#monthly_cost')
			.slider({min:0,
				max: gMonthlyCost.length-1,
				stepping:1,
				orientation: 'vertical',
				value: 0,
				slide: function(e,ui) {
					$('#monthly_cost_output').html(gMonthlyCost[ui.value].text);
				},
				change:function(e,ui) {
					findDeals();
				}
			});
		$('#monthly_cost_wrapper')
			.hover(function() {
				$('#deal_finder_help_A').html($('#monthly_cost_help').html());
			}, function() {
				$('#deal_finder_help_A').html($('#deal_finder_default_help_A').html());
			});

		$('#minutes').slider({min:0,
				max:gMinutes.length-1,
				stepping:1,
				orientation: 'vertical',
				value: 0,
				slide:function(e,ui) {
					$('#minutes_output').html(gMinutes[ui.value].text);
				},
				change:function(e,ui) {
					findDeals();
				}
			});
		$('#minutes_wrapper')
			.hover(function() {
				$('#deal_finder_help_A').html($('#minutes_help').html());
			}, function() {
				$('#deal_finder_help_A').html($('#deal_finder_default_help_A').html());
			});

		$('#texts').slider({min:0,
				max:gTexts.length-1,
				stepping:1,
				orientation: 'vertical',
				value: 0,
				slide:function(e,ui) {
					$('#texts_output').html(gTexts[ui.value].text);
				},
				change:function(e,ui) {
					findDeals();
				}
			});
		$('#texts_wrapper')
			.hover(function() {
				$('#deal_finder_help_A').html($('#texts_help').html());
			}, function() {
				$('#deal_finder_help_A').html($('#deal_finder_default_help_A').html());
			});

		if ( !gInitSliders ) {
			gDisableDealFetch = true;

			$('#monthly_cost').slider("moveTo",findSliderIndex(gMonthlyCost,''));
			$('#minutes').slider("moveTo",findSliderIndex(gMinutes,''));
			$('#texts').slider("moveTo",findSliderIndex(gTexts,''));

			gDisableDealFetch = false;
			gInitSliders = true;

			findDeals();
		}
	}
}

function initAdvancedSliders() {
	$('#contract_length').slider({min:0,
			max:gContractLength.length-1,
			stepping:1,
			orientation: 'vertical',
			value: 0,
			slide:function(e,ui) {
				$('#contract_length_output').html(gContractLength[ui.value].text);
			},
			change:function(e,ui) {
				gContractLengthSelection = ui.value;
				findDeals();
			}
		});
	$('#contract_length_wrapper')
		.hover(function() {
			$('#deal_finder_help_B').html($('#contract_length_help').html());
		}, function() {
			$('#deal_finder_help_B').html($('#deal_finder_default_help_B').html());
		});

	$('#average_cost').slider({min:0,
			max:gAverageCost.length-1,
			stepping:1,
			orientation: 'vertical',
			value: 0,
			slide:function(e,ui) {
				$('#average_cost_output').html(gAverageCost[ui.value].text);
			},
			change:function(e,ui) {
				gAverageCostSelection = ui.value;
				findDeals();
			}
		});
	$('#average_cost_wrapper')
		.hover(function() {
			$('#deal_finder_help_B').html($('#average_cost_help').html());
		}, function() {
			$('#deal_finder_help_B').html($('#deal_finder_default_help_B').html());
		});


	$('#phone_cost').slider({min:0,
			max:gHandsetCost.length-1,
			stepping:1,
			orientation: 'vertical',
			value: 0,
			slide:function(e,ui) {
				$('#phone_cost_output').html(gHandsetCost[ui.value].text);
			},
			change:function(e,ui) {
				gHandsetCostSelection = ui.value;
				findDeals();
			}
		});
	$('#phone_cost_wrapper')
		.hover(function() {
			$('#deal_finder_help_B').html($('#phone_cost_help').html());
		}, function() {
			$('#deal_finder_help_B').html($('#deal_finder_default_help_B').html());
		});

	$('#internet').slider({min:0,
			max:gInternet.length-1,
			stepping:1,
			orientation: 'vertical',
			value: 0,
			slide:function(e,ui) {
				$('#internet_output').html(gInternet[ui.value].text);
			},
			change:function(e,ui) {
				gInternetSelection = ui.value;
				findDeals();
			}
		});
	$('#internet_wrapper')
		.hover(function() {
			$('#deal_finder_help_B').html($('#internet_help').html());
		}, function() {
			$('#deal_finder_help_B').html($('#deal_finder_default_help_B').html());
		});

	$('#deal_finder_networks')
		.hover(function() {
			$('#deal_finder_help_B').html($('#networks_help').html());
		}, function() {
			$('#deal_finder_help_B').html($('#deal_finder_default_help_B').html());
		});


	if ( !gInitAdvancedSliders ) {
		gDisableDealFetch = true;

		$('#contract_length').slider("moveTo",findSliderIndex(gContractLength,''));
		$('#average_cost').slider("moveTo",findSliderIndex(gAverageCost,''));
		$('#phone_cost').slider("moveTo",findSliderIndex(gHandsetCost,''));
		$('#internet').slider("moveTo",findSliderIndex(gInternet,''));

		gDisableDealFetch = false;
		gInitAdvancedSliders = true;
	}
}

function findDeals(rowStart, rowCount) {
	if (rowStart == undefined)
		rowStart = 1;
	if (rowCount == undefined)
		rowCount = 10;
	if ( !gDisableDealFetch ) {
		var networks = '';
		var sdata = 'mode=' + gMode + '&pid=' + gProductID + '&pcid=' + gProductClassID;

		disableControls();
		gChooseHandsetOpen = false;
		$('#deal_finder_handset_chooser')
			.fadeOut('fast');
		$('#found_handsets').fadeOut('fast');
		$('#deal_finder_info')
			.html('<div class="deal_finder_waiting_info"></div><div class="deal_finder_overlay"></div>');
		$('#found_deals')
			.append('<div class="deal_finder_waiting">Locating deals...</div>');
		sdata = sdata + '&mc='+gMonthlyCost[$("#monthly_cost").slider("value")].search ;
		sdata = sdata + '&mi='+gMinutes[$("#minutes").slider("value")].search ;
		sdata = sdata + '&te='+gTexts[$("#texts").slider("value")].search ;
		sdata = sdata + '&hc='+gHandsetCost[gHandsetCostSelection].search;
		sdata = sdata + '&ma='+gAverageCost[gAverageCostSelection].search;
		sdata = sdata + '&cl='+gContractLength[gContractLengthSelection].search;
		sdata = sdata + '&in='+gInternet[gInternetSelection].search;
		sdata = sdata + '&rs='+rowStart;
		sdata = sdata + '&rc='+rowCount;
		$('li.single_network')
			.each(function() {
					if ( $(this).hasClass('checked') ) {
						if ( 0 != networks.length )
							networks = networks + ',';
						networks = networks + this.id.substring(20);
					}
				});
		sdata = sdata + '&ne=' + networks;
		sdata += '&of=';
		if ( $('#free_phones').hasClass('checked') )
			sdata += '1';
		if ( typeof(gDealsCache[sdata]) != 'undefined' ) {
			 setTimeout(function() {
				foundDeals(gDealsCache[sdata]);
			},500);
		} else {
			$.ajax({url: gWebRoot + '/deals.ajax',
				type:'GET',
				cache: false,
				data: sdata,
				success: function(html) {
					foundDeals(html, sdata);
				},
				error: function() {
					$("#found_deals").html('<div class="deal_finder_error">An error occured locating deals</div>');
					enableControls();
				}
			});
		}
	}
}

function foundDeals(html,cache) {
	var data = $(html);

	gHandsetsCache = [];
	$('#found_deals')
		.html(data.find('#deal_list').html());
	$('#deal_finder_info')
		.html(data.find('#deal_finder_info').html());

	if ( typeof(cache) != 'undefined' ) {
		if ( typeof(gDealsLoadedFn) == 'function' )
			gDealsLoadedFn(html);
		gDealsCache[cache] = html;
	}

	enableControls();
}

function chooseDealHandset(link, summaryID) {
	if ( !gChooseHandsetOpen ) {
		gSummaryDealId = summaryID;
		gChooseHandsetOpen = true;
		
		$('#deal_finder_handsets_info')
			.html($('#DS'+summaryID+' td.deal_table_info').html())
		$('#found_deals_info')
			.show();
		$('#found_deals')
			.fadeOut('fast', function() {
					$('#deal_finder_main')
						.hide();
					$('#deal_finder_handset_chooser')
						.show();
					$('#deal_finder_handsets')
						.fadeIn('fast');
					$('#deal_finder_handsets_none')
						.hide();
					$('#handset_finder_step_2')
						.show();
					getHandsetFinder();
				});
	} else {
		var jFadeOut;
		var fnFadeOut = function() {
				$('#found_deals_info')
					.hide();
				$('#found_handsets')
					.html('');
				$('#deal_finder_main')
					.show();
				$('#handset_finder_step_2')
					.hide();
				$('#deal_finder_handsets_none')
					.show();
				$('#found_deals')
					.fadeIn('fast');
			};
		if ( link )
			$(link).html(gChooseHandsetLinkText);
		gChooseHandsetOpen = false;

		$('#deal_finder_main')
			.show();
		jFadeOut = $('#found_handsets')
			.add('#deal_finder_handset_chooser');
		if ( jFadeOut.length == 0 ) {
			fnFadeOut();
		} else {
			jFadeOut.fadeOut('fast',fnFadeOut);
		}			
	}

	return false;
}

function getHandsetFinder() {
	var sdata = 'mode=hf&dsid=' + gSummaryDealId;

	$('#deal_finder_handsets')
		.html('<div style="width:745px;height:150px;" class="image_viewer_loading"><div class="deal_finder_handsets_loading">Locating phones</div></div>')
		.show();
	if ( typeof(gHandsetsCache[sdata]) != 'undefined' ) {
		 setTimeout(function() {
			gotHandsetFinder(gHandsetsCache[sdata]);
		},500);
	} else {
		$.ajax({url: gWebRoot + '/deals.ajax',
			type:'GET',
			cache: false,
			data: sdata,
			success: function(html) {
				gotHandsetFinder(html, sdata);
			},
			error: function() {
				$('#deal_finder_handsets').html('<div class="deal_finder_error">An error occured locating phones</div>');
			}
		});
	}
}

function gotHandsetFinder(html,cache) {
	var jData = $(html);

	if ( typeof(cache) != 'undefined' )
		gHandsetsCache[cache] = html;
	$('#deal_finder_handsets')
		.html(jData.find('#finder_handsets').html())
	dealFinderInitialiseHandsets();
	$('#deal_finder_handsets')
		.fadeIn('fast',function() {
				findHandsets();
			});
}

function findHandsets() {
	$('#found_handsets')
		.html('<div style="width:745px;height:150px;" class="image_viewer_loading"><div class="deal_finder_handsets_loading">Locating phones</div></div>')
		.show();
	$('#deal_finder_handset_info')
		.html('<div class="deal_finder_waiting_info"></div>');

	var sdataN = 'mode=hn&dsid=' + gSummaryDealId;
	sdataN += "&chfo=" + getDropDownSelectedIdValue('select_handset_type');
	sdataN += "&chca=" + getDropDownSelectedIdValue('select_handset_camera');
	sdataN += "&chmf=" + getDropDownSelectedIdValue('select_handset_function');
	sdataN += "&chma=" + getDropDownSelectedIdValue('select_handset_manufacturer');
	sdataN += "&chbs=" + getCheckboxCheckedSql('select_handset_best_seller');
	sdataN += "&chla=" + getCheckboxCheckedSql('select_handset_latest');
	sdataN += "&chfe=" + getMultiChoiceSelectedIdValues('select_handset_features');

	if ( typeof(gHandsetsCache[sdataN]) != 'undefined' ) {
		 setTimeout(function() {
			foundHandsetNarrative(gHandsetsCache[sdataN]);
		},500);
	} else {
		$.ajax({url: gWebRoot + '/deals.ajax',
			type:'GET',
			cache: false,
			data: sdataN,
			success: function(html) {
				foundHandsetNarrative(html, sdataN);
			},
			error: function() {
				$('#deal_finder_handset_info')
					.html('<div class="deal_finder_error">An error occured locating phones</div>');
			}
		});
	}

	var sdataH = 'mode=h&dsid=' + gSummaryDealId;
	sdataH += "&chfo=" + getDropDownSelectedIdValue('select_handset_type');
	sdataH += "&chca=" + getDropDownSelectedIdValue('select_handset_camera');
	sdataH += "&chmf=" + getDropDownSelectedIdValue('select_handset_function');
	sdataH += "&chma=" + getDropDownSelectedIdValue('select_handset_manufacturer');
	sdataH += "&chbs=" + getCheckboxCheckedSql('select_handset_best_seller');
	sdataH += "&chla=" + getCheckboxCheckedSql('select_handset_latest');
	sdataH += "&chfe=" + getMultiChoiceSelectedIdValues('select_handset_features');
	if ( typeof(gHandsetsCache[sdataH]) != 'undefined' ) {
		 setTimeout(function() {
			foundHandsets(gHandsetsCache[sdataH]);
		},500);
	} else {
		$.ajax({url: gWebRoot + '/deals.ajax',
			type:'GET',
			cache: false,
			data: sdataH,
			success: function(html) {
				foundHandsets(html, sdataH);
			},
			error: function() {
				$('#deal_finder_choose_handset_content').html('<div class="deal_finder_error">An error occured locating phones</div>');
			}
		});
	}
	
}

function foundHandsets(html,cache) {

	if ( typeof(cache) != 'undefined' )
		gHandsetsCache[cache] = html;
	$('#found_handsets')
		.html(html);
}


function foundHandsetNarrative(html, cache) {
	if ( typeof(cache) != 'undefined' )
		gHandsetsCache[cache] = html;
	$('#deal_finder_handset_info')
		.html(html);
}


function highlightDeal(deal) {
	var sdata = 'mode=d&did=' + deal;

	$('#callout_deals')
		.html('<div class="deal_finder_deal_waiting">Locating Deal...</div>');
	$.ajax({url: gWebRoot + '/deals.ajax',
			type:'GET',
			cache: false,
			data: sdata,
			success: function(html) {
					$('#callout_deals')
						.html(html);
				},
			error: function() {
				$('#callout_deals')
					.html('<div class="deal_finder_error">An error occured locating the deal</div>');
			}
		});
}

