var minutes = [100,300,500,900,"<br/>2000"];
var minutesInt = [100,300,500,900,2000];
var minPrice = 15;
var visiblePhones = [];
var availablePlans = [];
var scrollIndex = 0;
var scrollEndPos = -15;
var scrollStartPos = 30;
var stopScrolling = true;
var intervalControl = null;
var lastAction = "";
var lastActionValue = 0;
var lastFilterManufacturer = false;
var lastFilterChecked = false;
var dragging = false;
var position = 0;
var defaultPageHeight = 0;
var planType;

var threePAYM = {
	visiblePhones: new Array(),
	availablePlans: new Array(),
	precedence: 'usage'
};


(function($) {
	var cache = [];
	// Arguments are image paths relative to the current page.
	$.preLoadImages = function() {
		if(arguments.length>0){
			var urlList = arguments[0];
			for (var i in urlList) {
				var cacheImage = document.createElement('img');
				cacheImage.src = urlList[i];
				cache.push(cacheImage);
			}
		}
	}
})(jQuery)

$(document).ready(function(){
	populateBestOffers();
    //Setting all phones to visible on load
	
	$("#flexibleInfo").hide();
	if(defaultPlanType == 'InternetTalker'){
		changeToTalker();
	}else{
		changeToTexter();
	}
	
	var imgUrlList = new Array();
	for(var urlIdx in devices){
		var phone = devices[urlIdx];
		imgUrlList.push(phone.smallImageUrl);
		imgUrlList.push(phone.largeImageUrl);
	}
	jQuery.preLoadImages(imgUrlList);
	devices = reorderArray(devices);
	for(var idx in devices){
		devices[idx].visibleIndex = idx;
		devices[idx].deviceIndex = idx;
	}
	visiblePhones = devices;
	updateFilters(visiblePhones);
	
	/*#######################################################
					Slider Initialisation
	########################################################*/
	
	//Set price slider and set the value of the price plan
	var options = {	
		value: 30, 
		min:10,	
		max:40, 
		range: 'min', 
		keypressSlideEnabled: false,
		moveOnMouseDown: false,
		stop: priceSliderChanged
	};
	createLabelledSlider("#priceSlider", options, 70, ['\u00A310','\u00A320', '\u00A330','\u00A340+'])
	$("#selectedPrice").html($("#priceSlider").slider("value"));
 
	//create minute slider and set the value fo the default minutes selected
    options = { 
    	value: 2, 
    	min:0,
    	max:4, 
    	range: 'min', 
    	keypressSlideEnabled: false,
    	moveOnMouseDown: false,
    	stop: minuteSliderChanged
    };
    createLabelledSlider("#minutesSlider", options, 50, (minutes));
	$("#selectedMinutes").html(minutes[$("#minutesSlider").slider("option", "value")-1]);
	
	var phoneSliderHelper = $("#phoneSlider").slider({
		min:0, 
		max:visiblePhones.length-1,
		slide: phoneSliderDrag,
		keypressSlideEnabled: false,
		moveOnMouseDown: false,
		change: phoneSliderChanged,
		stop: phoneSliderChanged
	});
	// Populate carousel with phone data and initialise the slider position to the middle phone. 
	populatePhoneSlots("#phoneCarousel", devices);
	var startSliderPosition = findCentrePhone(visiblePhones);
	setCentrePhoneAtVisibleIndex(startSliderPosition);
	$("#mobilesFound").html(visiblePhones.length);

	
	var setWidth = 360;
	var handleHelper = phoneSliderHelper.find('.ui-slider-handle')
	.mousedown(function(){
		phoneSliderHelper.width( 420 );
	})
	.mouseup(function(){
		phoneSliderHelper.width(420);
	});
	
	var handleSize = 60;
	phoneSliderHelper.find('.ui-slider-handle').css({
		width: handleSize,
		'margin-left': -handleSize/2
	});
	//handleHelper.width('').width(phoneSliderHelper.width() -  handleSize);
	
	//Show defult plan on load, which is 300 minutes for currently loaded phone
	var phone = visiblePhones[startSliderPosition];
	if(initialUsage){
		findNearestPlanByMinutes(phone, initialUsage);
	} else{
		//default to using 300 minutes as the load when no initialisation parameters set
		findNearestPlanByMinutes(phone, 300);
	}
	/*#######################################################
					Filters Event Handling
	########################################################*/
	
	$("#filterSmartphone :checkbox").bind('click', function(){lastFilterManufacturer = false; lastFilterChecked = $(this).attr('checked'); reapplyLastSliderAction();});
	$("#filterCamera :checkbox").bind('click', function(){lastFilterManufacturer = false; lastFilterChecked = $(this).attr('checked'); reapplyLastSliderAction();});
	$("#filterEmail :checkbox").bind('click', function(){lastFilterManufacturer = false; lastFilterChecked = $(this).attr('checked'); reapplyLastSliderAction();});
	$("#filterGPS :checkbox").bind('click', function(){lastFilterManufacturer = false; lastFilterChecked = $(this).attr('checked'); reapplyLastSliderAction();});
	$("#filterNokia").bind('click', function(){lastFilterManufacturer = true; lastFilterChecked = $(this).attr('checked');reapplyLastSliderAction();});
	$("#filterIPhone4").bind('click', function(){lastFilterManufacturer = true; lastFilterChecked = $(this).attr('checked');reapplyLastSliderAction();});
	$("#filterSamsung").bind('click', function(){lastFilterManufacturer = true; lastFilterChecked = $(this).attr('checked'); reapplyLastSliderAction();});
	$("#filterSony").bind('click', function(){lastFilterManufacturer = true; lastFilterChecked = $(this).attr('checked'); reapplyLastSliderAction();});
	$("#filterINQ").bind('click', function(){lastFilterManufacturer = true; lastFilterChecked = $(this).attr('checked'); reapplyLastSliderAction();});
	$("#filterBlackberry").bind('click', function(){lastFilterManufacturer = true; lastFilterChecked = $(this).attr('checked'); reapplyLastSliderAction();});
	$("#filterHTC").bind('click', function(){lastFilterManufacturer = true; lastFilterChecked = $(this).attr('checked'); reapplyLastSliderAction();});
	$("#filterThree").bind('click', function(){lastFilterManufacturer = true; lastFilterChecked = $(this).attr('checked'); reapplyLastSliderAction();});
	$("#filterLG").bind('click', function(){lastFilterManufacturer = true; lastFilterChecked = $(this).attr('checked'); reapplyLastSliderAction();});
	$("#filterSIM").bind('click', function(){lastFilterManufacturer = false; lastFilterChecked = $(this).attr('checked'); reapplyLastSliderAction();});
	$("#filterShowAll").bind('click', function(){unfilterAllPhones();});

	$("#flexibleTextLink").bind('click', function(){
		changeToTalker();
	});
	
	function changeToTalker(){
		$("#unlimitedInfo").hide();
		$("#flexibleInfo").show();
		$("#minutesTooltip").show();
		$("#minutesSliderText").html("How many minutes and/or texts do you want?");
		planType = 'talker';
		reapplyLastSliderAction();
	}
	
	$("#unlimitedTextLink").bind('click', function(){
		changeToTexter();
	});
	
	function changeToTexter(){
		$("#flexibleInfo").hide();
		$("#unlimitedInfo").show();
		$("#minutesTooltip").hide();
		$("#minutesSliderText").html("How many minutes a month do you want?");
		planType = 'texter';
		reapplyLastSliderAction();
	}
	
	$("#minutesTooltip").hide();
	
	$(".helpIcon").tooltip({effect: 'fade', predelay: 200,  position: "top right",  offset: [0, 0]  });

	$(".phoneSlot .phoneImage").bind('click', function(){
		setMinutes(initialUsage);
		var phoneIndex = parseInt($(this).siblings('.phoneIndex').html());
		setCentrePhoneAtVisibleIndex(devices[phoneIndex].visibleIndex);
		findNearestPlanByMinutes(devices[phoneIndex], getMinutes());
	});
	
	//Action triggered when clicking on a buy this plan button
	
	$("#moreDealsLink").bind('click', function(){
		if($("#moreDealsLink").html()=="&gt; More"){
			$("#moreDealsLink").html("&gt; Hide");
			$('#moreDealsContainer').slideDown('slow', function(){
				checkFloatingPanelPosition();
			});
		} else {
			$("#moreDealsLink").html("&gt; More");
			$('#moreDealsContainer').slideUp('slow', function(){
			});
		}
	});
	
	
	//Initialise the expand button to be a '+' on load, action when clicking the '+' expand button for cross sell items
	$("#crossSellPanel .expansionPane").hide();
	$("#crossSellPanel #nearestPlans .expandButton").bind('click', function(){
		//alert("expand cross sell");
		var me = this;
		shrinkAll(me);
	});
	
	$("#crossSellPanel #nearestPlans .shrinkButton").bind('click', function(){
		var me = this;
		$(me).parents(".expansionPane").slideUp('slow', function(){
			$(me).parents(".summarySlot").find(".expandButton").fadeIn('fast');
		});
	});
	
	$("#leftArrow").bind('click', function(){
		 moveCarouselLeftOne()
	});
	
	$("#rightArrow").bind('click', function(){
		 moveCarouselRightOne();
	});
	
	$("#phoneCarousel").draggable({
		start: function(event, ui){
			position = event.pageX;
		},
		drag: function(event, ui){
			var currentPosition = event.pageX;
			var difference = position - currentPosition;
			if(Math.abs(difference) >=50){
				position = currentPosition;
				if(difference > 0){
					 moveCarouselLeftOne();
				} else{
					 moveCarouselRightOne();
				}
			}
		},
		revert: true,
		opacity: 0, 
		helper: function(){
			return $("<div class='boldText smallText'>&nbsp;</div>");
		},
		containment: '#CSElement-PayMonthlyCarousel_New_v2'
		
	});
	
	$(window).bind('scroll', function(){
		if ($.browser.msie && jQuery.browser.version.substr(0,3)=="6.0") {
			//ie 6
			positionFloatPanelOnScrollIE6();
		} else{
			positionFloatPanelOnScroll();
		}
	});

});

function positionFloatPanelOnScrollIE6(){
	var rhs = $("#rightColumn").offset().top;
	var phones = $("#phoneCarousel").offset().top;
	var bodyScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
	bodyScrollTop += 50;
	var floatPanelHeight =  $("#floatingPanel").height();
	var floatPanelBottom = bodyScrollTop + floatPanelHeight;
	var pageBottom = $(".page").offset().top + $(".page").height();
	if(floatPanelBottom >= pageBottom){
		
		var absolutePosition = pageBottom - floatPanelHeight;
		if(absolutePosition> phones){
			absolutePosition = phones;
		}
		$("#floatingPanel").css('position', 'absolute');
		$("#floatingPanel").css('top', absolutePosition +"px");
	}
	else if(bodyScrollTop >rhs && bodyScrollTop<phones){
		$("#floatingPanel").css('position', 'absolute');
		$("#floatingPanel").css('top', bodyScrollTop+'px');
	} else if(bodyScrollTop >=phones){
		$("#floatingPanel").css('position', 'absolute');
		$("#floatingPanel").css('top', phones +"px");
	} else{
		$("#floatingPanel").css('position', 'static');
		$("#floatingPanel").css('top', '0px');
	}
}

function positionFloatPanelOnScroll(){
	var rhs = $("#rightColumn").offset().top;
	var floatPanel = $("#floatingPanel").offset().top;
	var floatMarker = $("#floatingMarker").offset().top;
	var phones = $("#phoneCarousel").offset().top;
	var floatPanelHeight =  $("#floatingPanel").height();
	var floatPanelBottom = floatMarker + floatPanelHeight;
	var pageBottom = $(".page").offset().top + $(".page").height();
	if(floatPanelBottom >= pageBottom){
		
		var absolutePosition = pageBottom - floatPanelHeight;
		if(absolutePosition> phones){
			absolutePosition = phones;
		}
		$("#floatingPanel").css('position', 'absolute');
		$("#floatingPanel").css('top', absolutePosition +"px");
	}
	else if(floatMarker >rhs && floatMarker<phones){
		$("#floatingPanel").css('position', 'fixed');
		$("#floatingPanel").css('top', '50px');
		
	} else if(floatMarker >=phones){
		$("#floatingPanel").css('position', 'absolute');
		$("#floatingPanel").css('top', phones +"px");
	} else{
		$("#floatingPanel").css('position', 'static');
		$("#floatingPanel").css('top', '0px');
	}
}

function checkFloatingPanelPosition(){
	var phones = $("#phoneCarousel").offset().top;
	var floatMarker =  document.documentElement.scrollTop || document.body.scrollTop;//$("#floatingMarker").offset().top;
	var floatPanelHeight =  $("#floatingPanel").height();
	var floatPanelBottom = floatMarker + floatPanelHeight;
	var pageBottom = $(".page").offset().top + $(".page").height();
	
	if(floatPanelBottom >= pageBottom){
		var absolutePosition = pageBottom - floatPanelHeight;
		if(absolutePosition> phones){
			absolutePosition = phones;
		}
		$("#floatingPanel").css('position', 'absolute');
		$("#floatingPanel").css('top', absolutePosition +"px");
	}
}

function shrinkAll(elementToOpen){
	if($(".openCrossSell").length>0 ){
		$(".openCrossSell .expansionPane").slideUp('slow', function(){
			$(".openCrossSell").removeClass('openCrossSell');
			$(this).parents(".summarySlot").find(".expandButton").fadeIn('fast', function(){
				$(elementToOpen).fadeOut('fast').parents(".summarySlot").find(".expansionPane").slideDown('slow', function(){
					checkFloatingPanelPosition();
					$(elementToOpen).parents('.summarySlot').addClass('openCrossSell');
				});
			});
		});
	} else{
		$(elementToOpen).fadeOut('fast').parents(".summarySlot").find(".expansionPane").slideDown('slow', function(){
			checkFloatingPanelPosition();
			$(elementToOpen).parents('.summarySlot').addClass('openCrossSell');
		});
	}
		
		
}

function populatePhoneSlots(selectorToPopulate, devicesToAdd){
	for(var i in devicesToAdd){
		var device = devicesToAdd[i];
		var smartphoneFilter = "";
		var gpsFilter = "";
		var emailFilter = "";
		var cameraFilter = "";
		if(!device.smartphone){	smartphoneFilter = "notFeature"; }
		if(!device.email){ emailFilter = "notFeature"; }
		if(!device.gps){ gpsFilter = "notFeature"; }
		if(!device.camera){ cameraFilter = "notFeature"; }
		var phoneSlot = "<div id='phoneSlot_"+ i +"' class='floatLeft phoneSlot'>"+
			"<div class='phoneIndex displayNone'>"+i+"</div>" +
			"<div class='phoneImage smallImage' style='background-image: url(" +device.smallImageUrl+ ");'/>" +
			"<div class='phoneImage largeImage' style='background-image: url(" +device.largeImageUrl+ ");'/>" +
			"<div class='phoneDetailsBox'>" +
				"<div class='phoneName smallTitle'>"+ device.displayName +"</div>" +
				"<div class='icons'>" +
					"<div class='floatLeft phoneIcon smartphoneIcon "+ smartphoneFilter +"'></div>" +
					"<div class='floatLeft phoneIcon cameraIcon "+ cameraFilter +"'></div>" +
					"<div class='floatLeft phoneIcon emailIcon "+ emailFilter +"'></div>" +
					"<div class='floatLeft phoneIcon gpsIcon "+ gpsFilter +"'></div>" +
					"<div class='clear'></div>" +
				"</div>" +
				"<a href='/_standalone/Device_Detail?content_aid=" + device.fatwireId+ "&iframe=true' rel='prettyPhoto' class='greyText smallText moreDetailsLink' onclick=\"window.open(this.href,'name','height=468,width=730'); return false;\">&gt;More details</a>" +
			"</div>" +
		"</div>";
		$(selectorToPopulate).append(phoneSlot);
	}
	/*$("a[rel^='prettyPhoto']").prettyPhoto({
		showTitle: false,allowresize: false,default_width: 700,default_height: 500,theme: 'light_square',
		iframe_markup: '<iframe src ="{path}" width="{width}" height="{height}" frameborder="no"></iframe>'
	});*/
	$(selectorToPopulate).append('<div class="clear"></div>');
	var width = (((devicesToAdd.length-1) * 80) + 160)*2;
	$(selectorToPopulate).css('width', width);
}

function moveCarouselLeftOne(){
	var currentPosition = getSliderValueBySelector("#phoneSlider");
	if(currentPosition > 0){
		
		setMinutes(initialUsage);
		setCentrePhoneAtVisibleIndex(currentPosition - 1);
		findNearestPlanByMinutes(visiblePhones[currentPosition -1], getMinutes());
	}
}
function moveCarouselRightOne(){
	var currentPosition = getSliderValueBySelector("#phoneSlider");
	if(currentPosition < (visiblePhones.length -1)){
		
		setMinutes(initialUsage);
		setCentrePhoneAtVisibleIndex(currentPosition + 1);
		findNearestPlanByMinutes(visiblePhones[currentPosition +1], getMinutes());
		
	}
}
function setCentrePhoneAtVisibleIndex(visiblePhoneIndex){
	if(visiblePhones[visiblePhoneIndex] && visiblePhones[visiblePhoneIndex].deviceIndex >= 0){
		var phoneIndex = visiblePhones[visiblePhoneIndex].deviceIndex;
		$('.centrePhone').removeClass('centrePhone');
		$('#phoneSlot_'+phoneIndex).addClass('centrePhone');
		var position = visiblePhoneIndex * -80;
		$('#phoneCarousel').css('left', position + 'px');
		$("#phoneSlider").slider('option', 'value', visiblePhoneIndex);	
	}
}
function populateBestOffers(){
	var numberOnMainBar = 3;
	
	if(bestOffers){
		configureScroll();
		//$("#scrollBlock").hide();
		if(bestOffers.length<3){
			numberOnMainBar = bestOffers.length;
		}
		
		//populateMainBar
		for(var i = 0; i<numberOnMainBar; i++){
			var offerToAdd = createBestOffer(bestOffers[i]);
			$("#bestOffersMain").append(offerToAdd);
		}
		$("#bestOffersMain").append("<div class='clear'></div>");
		
		//populate remaining bar
		for(var j = numberOnMainBar; j<bestOffers.length; j++){
			var offerToAdd = createBestOffer(bestOffers[j]);
			$("#bestOffersRemainder").append(offerToAdd);
		}
		
		$("#bestOffersItems .planPurchase").bind('click', function(){
			return linkToDeal($(this).find(".purchaseId").html(), $(this).find(".planType").html());
		});
		
		$("#bestOffersRemainder").append("<div class='clear'></div>");
		$("#bestOffersRemainder").hide();
		$("#bestOffersMoreExpand").bind('click', function(){
			$(this).addClass('hide');
			$("#bestOffersRemainder").slideDown();
			
		});
		$("#bestOffersExpansion, #findOutMoreText").bind('click', function(){
			if($("#bestOffersExpansion").html()=="+"){
				$("#bestOffersExpansion").html("-");
				resetScroller();
				stopTimer();
				$("#scrollBlock").hide();
				$("#bestOffersItems").slideDown();
			} else if($("#bestOffersExpansion").html()=="-"){
				$("#bestOffersExpansion").html("+");
				$("#bestOffersItems").slideUp();
				$("#scrollBlock").show();
				resetScroller();
				startTimer();
				
			}
			
		});
		
		if(!displayBestOffers){
			//$("#bestOffersExpansion").trigger('click');
			$("#scrollBlock").show();
			startTimer();
			$("#bestOffersExpansion").html('+');
			$("#bestOffersItems").hide();
		}
	}		
}
/*function debug(msg){
	$("#debugPanel").prepend("<div>" + msg + "</div>");
}*/
function getScrollDuration(){
	var currentPosition = $('#scrollBlock').css('padding-top').replace("px", "");
	var curPos = new Number(currentPosition);
	var distanceToBottom = new Number(80) - new Number(currentPosition);
	var remainingDistance = 80;
	var duration = 5000 * (remainingDistance/distanceToBottom);
	return new Number(duration).toFixed(0) + "";
}

function startTimer(){
	if(intervalControl!=null){
		stopTimer();
	} else{
		startScroller();
		intervalControl = setInterval(startScroller, 6000);
	}
}

function stopTimer(){
	stopScroller();
	clearInterval(intervalControl);
	intervalControl = null;
}

function startScroller(){
	if($("#bestOffersExpansion").html()!="+"){
		stopTimer();
	} else{
		resetScroller();
		
		var index = getScrollIndex();
		incrementScrollIndex();
		var scrollText = getScrollText(index);
		$("#scrollText").html(scrollText);
		
		
		runScroller();
	}
}
function stopScroller(){
	$('#scrollBlock').stop(false, false);
}
function runScroller(){
	var duration = getScrollDuration()*1;
	if(duration < 0){
		duration = 3000;
	}
	$('#scrollBlock').animate({paddingTop: '80px'}, duration, 'linear');
}
function resetScroller(){
	$("#scrollBlock").css('padding-top', '0px');
}

function getScrollText(index){
	var bestOffer = bestOffers[index];
	var scrollText = bestOffer.phoneManufacturer + " " + bestOffer.phoneModel + ". " + bestOffer.planUsage + " " + bestOffer.includedInPlan + " \u00A3" + bestOffer.planCost +" a month.";
	return scrollText;
}

function getScrollIndex(){
	return scrollIndex;
}

function incrementScrollIndex(){
	var currentIndex = scrollIndex + 1;
	scrollIndex = currentIndex%bestOffers.length;
}

function configureScroll(){
	$('#scrollBlock').mouseover(function(){
		stopTimer();
	});
	
	$('#scrollBlock').mouseleave(function(){
		var duration = getScrollDuration()*1;
		if(duration < 0){
			duration = 3000;
		}
		$('#scrollBlock').animate({paddingTop: '80px'}, duration, 'linear', function(){
			resetScroller();
			startTimer();
		});
	});

}

function createBestOffer(bestOffer){
	
	var bestOfferElement = 
		"<div class='bestOffer floatLeft'>" +
			"<div class='floatLeft bestOfferImage'><a href='/_standalone/Device_Detail?content_aid="+bestOffer.phoneId+"&iframe=true' onclick=\"window.open(this.href,'name','height=468,width=730'); return false;\"><img src='"+bestOffer.image+"'/></a></div>" +
			"<div class='bestOfferDetails floatLeft'>" +
				"<div class='bestOfferPhone smallText boldText'>" + bestOffer.phoneManufacturer + " "+  bestOffer.phoneModel + "</div>" +
				"<div class='bestOfferUsage smallText boldText'>"+ bestOffer.planUsage + " " + bestOffer.includedInPlan +"</div>" +
				"<div class='bestOfferContract greyText smallText boldText'>"+ bestOffer.contractPeriod +" months</div>" +
				"<div class='bestOfferPrice smallTitle boldText'>\u00A3"+ bestOffer.planCost +"</div>" +
				"<div class='planPurchase'>" +
					"<div class='purchaseId displayNone'>" + bestOffer.offerCode +"</div>" +
					"<div class='planType displayNone'>bestOffer</div>" + 
					"<div class='Content_C-Full_Button'>" +
						"<div class='normal'>" +     
						"<a title='Best offer "+ bestOffer.phoneManufacturer + " "+  bestOffer.phoneModel +"' href='http://threestore.three.co.uk/dealsummary.aspx?intid=dealbuilder&offercode="+ bestOffer.offerCode +"'>" +   
								"<span class='buttonText'>Buy now</span>" +
								"<span class='icon Purchase'></span>" +  
							"</a>" + 
						"</div>" +
					"</div>" +
				"</div>" +
			"</div>" +
		"</div>";
	return bestOfferElement;
	
}




function linkToDeal(dealId, dealType){
	var trackString= "clicks/Content_C/CustomElement/"+dealType+"/FindOutMore/"+dealId;
	var trackString2 = '/outgoing/CustomElement/'+dealType+'/3Store/'+dealId;
	pageTracker._trackPageview(trackString);
	pageTracker._trackPageview(trackString2);
	s.events = "event6";
	s.t();
	return true;
}

function calculateCost(phone, plan){
	var planDetails = getPlanDetailsById(phone.planData, plan.id);
	var cost = planDetails.handsetCost;
	if(planDetails.discountedPricePlan){
		cost = planDetails.discountedPricePlan + planDetails.handsetCost;
	}
	return new Number(cost).toFixed(2);
}

function calculateOriginalCost(phone, plan){
	var planDetails = getPlanDetailsById(phone.planData, plan.id);
	return (new Number(planDetails.handsetCost) + new Number(plan.cost));
}

function calculateRetailCost(handsetCost, retailCost){
	var cost = (new Number(handsetCost) + new Number(retailCost));
	if(isDecimal(cost)){
		cost = cost.toFixed(2);
	} else{
		cost.toFixed(0);
	}
	
	return cost;
}

function getPlanDetailsById(planList, id){
	var plan = null;
	for(var i in planList){
		if(planList[i].id == id){
			plan = planList[i];
		}
	}
	return plan;
}



/*###########################################################################################################
 * 									Plan Business Logic Functions
 ###########################################################################################################*/

function hideCarouselLoad(){
	$("#loadingIconCarousel").hide();
	$('#phonesContainer').removeClass('halfOpacity');
}

function hideDealsLoad(){
	$("#loadingIconDeals").hide();
	$('#dealsPanel').removeClass('halfOpacity');
}

function displayDeals(phone, bestPlan){
	setMinutes(bestPlan.planUsage);
	setPlanDeals(phone, bestPlan, "summary");
	$("#summaryPhone").html(phone.displayName);
	$("#summaryPhone").append('<span id="summaryContractPeriod" class="tinyTitle greyText">&nbsp;'+plans[bestPlan.planPosition].contract + '&nbsp;months</span>');
	$("#summaryPlanDeal #noPlanMessage").hide();
	$("#summaryPlanDeal #summaryPlanContainer").show();
	setCrossSell(phone, bestPlan);
}

/*
 * Find the nearest plan using minutes as precedence for a given phone
 */
function findNearestPlanByMinutes(phone, minutesChosen){
	
	if(phone){
		$('#dealsPanel').addClass('halfOpacity');
		$("#loadingIconDeals").show('fast', function(){
			availablePlans = plans;
			var bestPlanLocation = null;
			var bestMinutes = 0;
			for(var i in phone.planData){
				
				var plan = phone.planData[i];
				if(plan && plan.planUsage<=minutesChosen && plan.planUsage > bestMinutes && (plan.planType == planType || plan.planType == "oneplan" || plan.planType == "iPhonePlan")) {
					
					bestPlanLocation = i;
					bestMinutes = new Number(plan.planUsage);
				}
			}
			if(bestPlanLocation) {	
				var bestPlan = phone.planData[bestPlanLocation];
				var cost = bestPlan.planCost;
				var priceLimit = getSliderValueBySelector("#priceSlider");
				if(cost>priceLimit){
					setPrice(cost);
				}
				displayDeals(phone, bestPlan);
			} else{
				setMinutes(minutesChosen);
				if(isNaN(minutesChosen)){
					clearSummary('The ' + phone.displayName + ' isn\'t available on The One Plan. You can try adjusting the number of mins/texts, or choose a different phone.');
				}else{
					clearSummary('The ' + phone.displayName + ' isn\'t available with '+minutesChosen+' mins/texts. You can try adjusting the number of mins/texts, or choose a different phone.');
				}
			}
			lastAction = 'minuteFilter';
			lastActionValue = minutesChosen;
			setTimeout('hideDealsLoad()', 500);
		});
	} else {
		clearSummary("We can't find a deal that exactly matches your needs. But you can try adjusting the price, or choose a different phone.");
	}
}

function findNearestPlanBelowPriceLimit(phone, priceChosen){
	var bestPlan = null;
	if(phone){
		availablePlans = plans;
		var nearestPrice = 0;
		for(var i in phone.planData){
			var plan = phone.planData[i];
			var overallPlanPrice = plan.planCost;
			if(plan && overallPlanPrice<=priceChosen && overallPlanPrice > nearestPrice && (plan.planType == planType || plan.planType == "oneplan" || plan.planType == "iPhonePlan")) {
				bestPlan = plan;
				nearestPrice = overallPlanPrice;
			}
		}
	}
	return bestPlan;
}

function findLowestPricePlan(phone){
	var lowestPlan = null;
	var lowestCost = 9999999;
	for(var i in phone.planData){
		var plan = phone.planData[i];
		if( plan.planCost<lowestCost && (planType ==plan.planType || plan.planType == "oneplan" || plan.planType == "iPhonePlan")){
			lowestPlan = plan;
			lowestCost = plan.planCost;
		}
	}
	return lowestPlan;
}


function findPlansBelowPriceLimit(priceLimit){
	if(priceLimit){
		$('#phonesContainer').addClass('halfOpacity');
		$("#loadingIconCarousel").show('fast', function(){
		
			setPrice(priceLimit);
			var previousCentrePhone = getCurrentPhone();
			var nowVisible = new Array();
			var nearestPlans = new Array();
			var availableAfterFilter = filterPhones();
			var msg = "";
			var visibleIndex = 0;
			for(var i in devices){
				var phone = devices[i];
				var nearestPlan = findNearestPlanBelowPriceLimit(phone, priceLimit);
				if(nearestPlan && isInList(availableAfterFilter, phone)){
					phone.visibleIndex = visibleIndex;
					nowVisible.push(phone);
					nearestPlans.push(nearestPlan);
					visibleIndex++;
					$('#phoneSlot_'+phone.deviceIndex).removeClass('displayNone');
				} else {
					phone.visibleIndex = -1;
					$('#phoneSlot_'+phone.deviceIndex).addClass('displayNone');
				}
			}
			setVisiblePhones(nowVisible);
			updateFilters(visiblePhones);
			updateMobilesFound(visiblePhones.length);
			if(visiblePhones.length>0){
				var centrePosition = getVisiblePhoneLocation(visiblePhones, previousCentrePhone);
				if(!centrePosition){
					centrePosition = findCentrePhone(visiblePhones);
				}
				setCentrePhoneAtVisibleIndex(centrePosition);
				var centrePhone = visiblePhones[centrePosition];
				var planBelowLimit = nearestPlans[centrePosition];
				displayDeals(centrePhone, planBelowLimit);
			}else{
				clearSummary("We can't find a deal that exactly matches your needs. But you can try adjusting the price, or choose a different phone.");
			}
			lastAction = 'priceFilter';
			lastActionValue = priceLimit;
			setTimeout('hideCarouselLoad()', 500);
		});
	}
}

/*
 * Get a plan object from an array based on its id
 */
function getPlan(planList, id){
	for(var i in planList){
		var plan = planList[i];
		if(plan.id == id){
			return plan;
		}
	}
	return null;
}

/*
 * Find the position in the array of a plan id
 */
function getPlanPosition(planList, planId){
	for(var i in planList){
		var plan = planList[i];
		if(plan.id == planId){
			return new Number(i);
		}
	}
	return null;
}

/*
 * Get a plan object lower (if exists) than the current best plan
 */
function getLowerPlan(phone, planData, bestPlan, planType){
	var lowerPlan = null;
	if(planType == 'talker' && bestPlan.planType != 'oneplan' && bestPlan.planType != 'iPhonePlan'){
		var equivPlanId = plans[bestPlan.planPosition].equivId;
		lowerPlan = getPlan(planData, equivPlanId);
	} else{
		lowerPlan = lowerPlanFinder(phone, planData, bestPlan);
	}
	return lowerPlan;
		
}

function getPlansByType(planList, type){
	var newPlanList = new Array();
	for(var i in planList){
		var plan = planList[i];
		if(plan.planType == type){
			newPlanList.push(plan);
		}
	}
	return newPlanList;
}

//Returns FULL PLAN
function lowerPlanFinder(phone, planData, bestPlan){
	var lowerPlan = null;
	var bestPlanPosition = getPlanPosition(planData, bestPlan.id);
	if(bestPlanPosition){
		if(bestPlanPosition > 0){
			var newPlanPosition = bestPlanPosition -1;
			lowerPlan = planData[newPlanPosition];
		} else if((bestPlanPosition + 2)<planData.length -1){
			//Not actually a lower plan, it is the lowest plan above the higher plan
			lowerPlan = planData[bestPlanPosition+2];
		}
	}
	return lowerPlan
}

/*
 * Get a plan object higher (if exists) above the current best plan
 */ 
//Returns FULL PLAN
function getHigherPlan(phone, planData, bestPlan, planType){
	var higherPlan = null;
	if(planType=='talker' && bestPlan.planType != 'oneplan' && bestPlan.planType != 'iPhonePlan'){
		higherPlan = lowerPlanFinder(phone, planData, bestPlan);
	} else{
		var bestPlanPosition = getPlanPosition(planData, bestPlan.id);
		if(bestPlanPosition){
			if(bestPlanPosition <= planData.length-2){
				var newPlanPosition = bestPlanPosition + 1;
				higherPlan = planData[newPlanPosition];
			} else if((bestPlanPosition - 2)>0){
				//Not actually a higher plan, it is the highest plan below the lower plan
				higherPlan = planData[bestPlanPosition-2];
			}
		}
	}
	return higherPlan;
		
}


/*###########################################################################################################
 * 									Plan Summary Functions
 ###########################################################################################################*/
/*
 * helper method for setting the deal summary and the deal options for higher and lower value items.
 */
function setPlanDeals(phone, plan, planSelectorPrefix){
		var planPrefix = "#" + planSelectorPrefix + "PlanDeal #" + planSelectorPrefix;
		var fullPlanData = plans[plan.planPosition];
		$(planPrefix + "Plan").html(fullPlanData.lbl);
		$(planPrefix + "ContractPeriod").html(fullPlanData.contract + " months");
		$(planPrefix + "Cost").html("\u00A3" + getCostToDisplay(plan.planCost));
		$(planPrefix + "PlanBullets").html("<ul>" + fullPlanData.info +"</ul>");

		var upfrontCost = "";
		if(phone.displayName.indexOf("iPhone")!=-1){
			$(planPrefix + "Upfront").html("Plus \u00A3" + getCostToDisplay(plan.upfrontCost) + " upfront cost.");
			$(planPrefix + "Upfront").show();
		}else{
			$(planPrefix + "Upfront").hide();
		}
		if(plan.retailPricePlan){
			$(planPrefix + "Reductions .originalPrice").html(getCostToDisplay(plan.retailPricePlan));
			$(planPrefix + "Reductions").show();
		} else{
			$(planPrefix + "Reductions").hide();
		}
		
		$("#" + planSelectorPrefix + "PlanDeal .purchaseId").html(plan.storecode);
		$("#" + planSelectorPrefix + "PlanDeal .planType").html(plan.planType);
		$("#" + planSelectorPrefix + "PlanDeal .planPurchase a").attr("href", "http://threestore.three.co.uk/dealsummary.aspx?intid=dealbuilder&offercode=" + plan.storecode);
		$("#" + planSelectorPrefix + "PlanDeal .planPurchase a").attr("onClick", "return linkToDeal('"+plan.storecode+"', '"+plan.planType+"')")
		$("#" + planSelectorPrefix + "PlanDeal .planPurchase a").attr("title", phone.displayName + " - " +fullPlanData.lbl); 
}

/*
 * Clear the deal summry, higher and lower deals as well as the cross sell panels
 * There are no deals for this price/usage.
 */
function clearSummary(msg){
	$("#summaryPlanDeal #noPlanMessage").html(msg);
	$("#summaryPlanDeal #noPlanMessage").show();
	$("#summaryPlanDeal #summaryPlanContainer").hide();
	$("#crossSellPanel").hide();
}



function limitPhonePlansByType(phonePlanList, type){
	var newPhonePlanList = new Array();
	for(var i in phonePlanList){		
		if( phonePlanList[i].planType == type||phonePlanList[i].planType == "oneplan"||phonePlanList[i].planType == "iPhonePlan"){
			newPhonePlanList.push(phonePlanList[i]);
		}
	}
	return newPhonePlanList;
		
}

/*
 * Generate the cross sell panel content dynamically as well as the higher and lower deals
 */
function setCrossSell(phone, bestPlan){
	var currentType = planType;
	var planData = phone.planData;
	if(currentType == 'texter'){
		planData = limitPhonePlansByType(phone.planData, 'texter');
	}
	var lowerPlan = getLowerPlan(phone, planData, bestPlan, currentType);
	var higherPlan = getHigherPlan(phone, planData, bestPlan, currentType);
	
	
	$("#moreDealsPanel").hide();
	//if no additional plans hide the cross sell panel
	if(!lowerPlan && !higherPlan){
		$("#crossSellPanel").hide();
	} else{
		//if any deals exist shw the panel
		$("#crossSellPanel").show();
		$("#otherDeals").html("More " + phone.displayName + " packages...");
		//if the lower plan is empty but the higher not then swap 
		if(!lowerPlan && higherPlan){
			lowerPlan = higherPlan;
			higherPlan = null;
		}
		//if the lower plan is more expensive than the higher plan then swap  
		else if(lowerPlan && higherPlan && lowerPlan.planCost >= higherPlan.planCost){
			if(planType!='talker'){
				var tempPlan = lowerPlan;
				lowerPlan = higherPlan;
				higherPlan = tempPlan;
			}			
		}
		
		//if lower plan exists then show and populate plan deals
		if(lowerPlan){
			$("#lowerPlanDeal").show();
			setPlanDeals(phone, lowerPlan, "lower");
		} else {
			$("#lowerPlanDeal").hide();
		}
		
		//if higher plan exists then show and populate plan deals
		if(higherPlan){
			$("#higherPlanDeal").show();
			setPlanDeals(phone, higherPlan, "higher");
		} else {
			$("#higherPlanDeal").hide();
		}
		if(lowerPlan || higherPlan){
			//Populate the 'more deals' hidden menu with any remaining cross sell items
			if(!lowerPlan){
				lowerPlan=higherPlan;
			}else if(!higherPlan){
				higherPlan = lowerPlan;
			}
			populateMorePlans(phone, planData, bestPlan, lowerPlan, higherPlan, currentType);
		}	
	}
}

/*
 * Populate cross sell menu below 'more deals'
 */
function populateMorePlans(phone, validPlanData, mainPlan, lowerPlan, higherPlan, currentPlanType){
	var morePlans = getMorePlansData(validPlanData, mainPlan, lowerPlan, higherPlan);
	$('#moreDealsContainer').hide();
	$("#moreDealsLink").html("&gt; More");
	$('#moreDealsContainer').html(" ");
	if(morePlans.length<1){		
		$("#moreDealsPanel").hide();
	} else {
		$("#moreDealsPanel").show();
		for(var i=0; i<morePlans.length; i++){
			var plan = morePlans[i];
			var planDetails = plans[plan.planPosition];
			if(planDetails && (currentPlanType =='talker' || (currentPlanType=='texter' && plan.planType==currentPlanType) || (currentPlanType=='texter' && plan.planType=='iPhonePlan'))){
				createHiddenCrossSell(phone, plan, planDetails);
			}
		}
	}
	$("#moreDealsContainer .planPurchase").bind('click', function(){
		return linkToDeal($(this).find(".purchaseId").html(), $(this).find(".planType").html());
	});
	
	$("#moreDealsContainer .expandButton").unbind('click');
	$("#moreDealsContainer .expandButton").bind('click', function(){
		var me = this;
		shrinkAll(me);
		
	});
	
	$("#moreDealsContainer .shrinkButton").unbind('click');
	$("#moreDealsContainer .shrinkButton").bind('click', function(){
		var me = this;
		$(me).parents(".expansionPane").slideUp('slow', function(){
			$(me).parents(".summarySlot").find(".expandButton").fadeIn('fast');
		});
	});
}

/*
 * Create a cross sell item via Jquery and append to the more deals container ensure the expansion pane is hidden on start
 */
function createHiddenCrossSell(phone, plan, planDetails){
	var crossSellItem = $("<div class='hiddenCrossSell threeBorderBottom summarySlot'></div>");
	
	$(crossSellItem).append("<div class='hiddenPlan tinyTitle heightFix'>" + planDetails.lbl + "</div>");
	$(crossSellItem).append("<div class='hiddenContractPeriod tinyTitle greyText heightFix'>" + planDetails.contract + " months</div>");
	$(crossSellItem).append("<div><div class='hiddenCost largeTitle floatLeft clearLeft'>\u00A3" + getCostToDisplay(plan.planCost) + "</div><div class='expandButton mediumTitle floatRight'>>Tell me more</div><div class='clear'></div></div>");
	$(crossSellItem).append("<div class='clear'></div>");
	var discount = "";
	if(plan.retailPricePlan){
		discount = "<div id='hiddenReductions' class='reductions boldText'>" +
			"<div class='onlinePriceText'>Online only price.</div><div class='retailPriceText'>(Retail price \u00A3<span class='originalPrice'>"+getCostToDisplay(plan.retailPricePlan)+"</span>).</div>" +
		"</div>";
		
	}
	var upfrontCost = "";
	if(phone.displayName.indexOf("iPhone")!=-1){
		upfrontCost = "<div class='upfrontCost'>Plus \u00A3" + getCostToDisplay(plan.upfrontCost) + " upfront cost.</div>";
	}
	$(crossSellItem).append(
		"<div class='expansionPane floatLeft clearBoth'>" +
			upfrontCost +
			discount + 
			"<div class='smallText'>Includes:" +
				"<div class='hiddenPlanBullets dealPlanBullets'><ul>" + planDetails.info + "</ul></div>" +
			"</div>" +
			"<div class='planPurchase'>" +
				"<div class='purchaseId displayNone'>" + plan.storecode +"</div>" + 
				"<div class='planType displayNone'>" + plan.planType +"</div>" + 
				"<div class='Content_C-Full_Button'>" +
					"<div class='normal'>" +     
					"<a title='Best offer "+ phone.displayName +"' onClick='return linkToDeal(\""+plan.storecode+"\", \""+plan.planType+"\")' href='http://threestore.three.co.uk/dealsummary.aspx?intid=dealbuilder&offercode="+ plan.storecode +"'>" +   
							"<span class='buttonText'>Buy this deal</span>" +
							"<span class='icon Purchase'></span>" +  
						"</a>" + 
					"</div>" +
				"</div>" +
			"</div>" +
			"<div class='shrinkButton mediumTitle floatRight'>>Hide</div>" +
		"</div>" +
		"<div class='clear'></div>");	
	$("#moreDealsContainer").append(crossSellItem);
	$(".hiddenCrossSell .expansionPane").hide();
}

/*
 * Find exclusive list of plans not currently used as either summary (main) or higher or lower
 */
function getMorePlansData(validPlanData, mainPlan, lowerPlan, higherPlan){
	var morePlans = new Array();
	var count = 0;
	for(var i in validPlanData){
		var plan = validPlanData[i];
		if(plan.id != mainPlan.id && plan.id != lowerPlan.id && plan.id != higherPlan.id){
			morePlans.push(plan);
			count++;
		}
	}
	return morePlans;
}

/*###########################################################################################################
 * 									Filter Functions
 ###########################################################################################################*/
/*
 * Filter phones using eval to find the variable as the filter paramters as 
 * string passed as argument
 */
function filterPhone(phone, filters){
	var validFilter = true;
	if(filters.smartphone && !phone.smartphone) { validFilter = false; }
	if(filters.camera && !phone.camera) { validFilter = false; }
	if(filters.gps && !phone.gps) { validFilter = false; }
	if(filters.email && !phone.email) { validFilter = false; }
	//if(filters.sim && !phone.sim) { validFilter = false; }
	
	var validManufacturer = false;
	var hasManufacturerFilter = false;
	for(var i in filters.manufacturer){
		
		if(filters.manufacturer[i].filterOn){
			
			hasManufacturerFilter = true;
			validManufacturer = false;
			if(phone.model && filters.manufacturer[i].name.indexOf('iPhone 4')!=-1){
					if(phone.model.indexOf(filters.manufacturer[i].name)!=-1){
						validManufacturer = true;
					}
					}else{
						if(phone.manufacturer == filters.manufacturer[i].name){
							validManufacturer = true;
						}
					}
			break;
		}
	}
	if(hasManufacturerFilter && !validManufacturer){
		validFilter = false;
	}
	
	return !validFilter;
}

function filterPhoneOnAttributes(phone, filters){
	var validFilter = true;
	if(filters.smartphone && !phone.smartphone) { validFilter = false; }
	if(filters.camera && !phone.camera) { validFilter = false; }
	if(filters.gps && !phone.gps) { validFilter = false; }
	if(filters.email && !phone.email) { validFilter = false; }
	//if(filters.sim && !phone.sim) { validFilter = false; }
	
	return !validFilter;
}

function getSelectedFilters(){
	var filters = {
			smartphone: false,
			camera: false,
			gps: false,
			email: false,
			manufacturer: [
				{ name: 'Nokia', filterOn: false},
				{ name: 'iPhone 4', filterOn: false},
				{ name: 'Samsung', filterOn: false},
				{ name: 'Sony Ericsson', filterOn: false},
				{ name: 'INQ', filterOn: false},
				{ name: 'BlackBerry', filterOn: false},
				{ name: 'HTC', filterOn: false},
				//{ name: '3', filterOn: false},
				{ name: 'LG', filterOn: false}
			],
			sim: false
	};
	
	if($("#filterSmartphone :checkbox").attr('checked')){filters.smartphone = true; }
	if($("#filterEmail :checkbox").attr('checked')){filters.email = true; }
	if($("#filterCamera :checkbox").attr('checked')){filters.camera = true; }
	if($("#filterGPS :checkbox").attr('checked')){filters.gps = true; }
	if($("#filterNokia :checkbox").attr('checked')){filters.manufacturer[0].filterOn = true; }
	if($("#filterIPhone4 :checkbox").attr('checked')){filters.manufacturer[1].filterOn = true; }
	if($("#filterSamsung :checkbox").attr('checked')){filters.manufacturer[2].filterOn = true; }
	if($("#filterSony :checkbox").attr('checked')){filters.manufacturer[3].filterOn = true; }
	if($("#filterINQ :checkbox").attr('checked')){filters.manufacturer[4].filterOn = true; }
	if($("#filterBlackberry :checkbox").attr('checked')){filters.manufacturer[5].filterOn = true; }
	if($("#filterHTC :checkbox").attr('checked')){filters.manufacturer[6].filterOn = true; }
	//if($("#filterThree:checkbox").attr('checked')){filters.manufacturer[6].filterOn = true; }
	if($("#filterLG :checkbox").attr('checked')){filters.manufacturer[7].filterOn = true; }
	//if($("#filterSIM :checkbox").attr('checked')){filters.sim = true; }

	return filters;
}

function filterPhones(){
		var filteredList = [];
		var filters = getSelectedFilters();
		var msg = "";
		var currentPhone = devices[parseInt($('.centrePhone .phoneIndex').html())];
		var visibleIndex = 0;
		for(var i in devices){
			var phone = devices[i];
			if(!filterPhone(phone, filters)){
				msg += phone.displayName + "\n";
				phone.visibleIndex = visibleIndex;
				visibleIndex++;
				filteredList.push(phone);
				$('#phoneSlot_'+i).removeClass('displayNone');
			} else{
				phone.visibleIndex = -1;
				$('#phoneSlot_'+i).addClass('displayNone');
			}
		}
		
		updateFilters(filteredList);
		updateMobilesFound(filteredList.length);
		
		setVisiblePhones(filteredList);
		if(visiblePhones.length>0){
			var centreIndex = currentPhone.visibleIndex;
			if(!centreIndex || centreIndex < 0){
				centreIndex = visiblePhones[findCentrePhone(visiblePhones)].visibleIndex;
			}
			setCentrePhoneAtVisibleIndex(centreIndex);
		}
		return filteredList;	
}

function reapplyLastSliderAction(){
	
	var centrePhone = getCurrentPhone();
	if(lastAction!=null && lastActionValue !=null){
		
		$('#phonesContainer').addClass('halfOpacity');
		$("#loadingIconCarousel").show('fast', function(){
			if(lastAction == 'minuteFilter'){
				
				filterPhones();
				findNearestPlanByMinutes(getCurrentPhone(), lastActionValue);
				
			} else if(lastAction == 'priceFilter') {
				findPlansBelowPriceLimit(lastActionValue);
			}
			
			//Set new centre to the middle of the visible phones array 
			//unless the previously centre phone is still visible
			var centrePhonePosition = getVisiblePhoneLocation(visiblePhones, centrePhone);
			if(!centrePhonePosition){
				centrePhonePosition	= findCentrePhone(visiblePhones);	
			}
			
			setCentrePhoneAtVisibleIndex(centrePhonePosition);
			$("#mobilesFound").html(visiblePhones.length);
			setTimeout('hideCarouselLoad()', 500);
		});
		
	}
}

function updateMobilesFound(foundNumber){
	$("#mobilesFound").html(foundNumber + "&nbsp;");
}

function updateNoneManufacturerFilters(filteredList){
	var smartphoneCount = 0;
	var cameraCount = 0;
	var emailCount = 0;
	var gpsCount = 0;
	var nokiaCount = 0;
	var samsungCount = 0;
	var sonyCount = 0;
	var inqCount = 0;
	var blackberryCount = 0;
	var htcCount = 0;
	var threeCount = 0;
	var lgCount = 0;
	//var simCount = 0;
	

	for(var i=0; i<filteredList.length; i++){
		var phone = filteredList[i];
		if(phone.smartphone) { smartphoneCount++; }
		if(phone.email) { emailCount++; }
		if(phone.camera) { cameraCount++; }
		if(phone.gps) { gpsCount++; }
		//if(phone.sim) { simCount++; }
	}
	$('.filter.nonManufacturer').removeClass('noPhones');
	var checkedElements = $('.filter.nonManufacturer :checked');
	$('.filter.nonManufacturer :checked').removeAttr('checked');
	$(".filter.nonManufacturer :checkbox").removeAttr("disabled");
	$(checkedElements).attr('checked', 'checked');
	
	if(smartphoneCount<1){ $("#filterSmartphone").addClass('noPhones'); $("#filterSmartphone :checkbox").attr('disabled', 'disabled');}
	if(emailCount<1){$("#filterEmail").addClass('noPhones'); $("#filterEmail :checkbox").attr('disabled', 'disabled');}
	if(cameraCount<1){$("#filterCamera").addClass('noPhones'); $("#filterCamera :checkbox").attr('disabled', 'disabled');}
	if(gpsCount<1){$("#filterGPS").addClass('noPhones'); $("#filterGPS :checkbox").attr('disabled', 'disabled');}
	//if(simCount<1){$("#filterSIM").addClass('noPhones'); $("#filterSIM :checkbox").attr('disabled', 'disabled');}
}

function onlyRelaxManufacturerFilter(filteredList){
	var nokiaCount = 0;
	var iPhone4Count = 0;
	var samsungCount = 0;
	var sonyCount = 0;
	var inqCount = 0;
	var blackberryCount = 0;
	var htcCount = 0;
	//var threeCount = 0;
	var lgCount = 0;
	

	for(var i=0; i<filteredList.length; i++){
		var phone = filteredList[i];
		switch(phone.manufacturer){
			case 'Nokia':
				nokiaCount++;
				break;
			case 'Samsung':
				samsungCount++
				break;
			case 'Sony Ericsson':
				sonyCount++
				break;
			case 'INQ':
				inqCount++
				break;
			case 'Blackberry':
				blackberryCount++
				break;
			case 'HTC':
				htcCount++
				break;
			case 'LG':
				lgCount++
				break;
			default:
				break;
		}
		if(phone.model && phone.model.indexOf('iPhone 4')!=-1){
			iPhone4Count++
		}
	}
	var checkedElements = $('.filter :checked');
	
	if(nokiaCount>=1){$("#filterNokia").removeClass('noPhones'); $("#filterNokia :checkbox").removeAttr('checked'); $("#filterNokia :checkbox").removeAttr('disabled');}
	if(iPhone4Count>=1){$("#filterIPhone4").removeClass('noPhones'); $("#filterIPhone4 :checkbox").removeAttr('checked');$("#filterIPhone :checkbox").removeAttr('disabled');}
	if(samsungCount>=1){$("#filterSamsung").removeClass('noPhones'); $("#filterSamsung :checkbox").removeAttr('checked'); $("#filterSamsung :checkbox").removeAttr('disabled');}
	if(sonyCount>=1){$("#filterSony").removeClass('noPhones'); $("#filterSony :checkbox").removeAttr('checked'); $("#filterSony :checkbox").removeAttr('disabled');}
	if(inqCount>=1){$("#filterINQ").removeClass('noPhones'); $("#filterINQ :checkbox").removeAttr('checked'); $("#filterINQ :checkbox").removeAttr('disabled');}
	if(blackberryCount>=1){$("#filterBlackberry").removeClass('noPhones'); $("#filterBlackberry :checkbox").removeAttr('checked'); $("#filterBlackberry :checkbox").removeAttr('disabled');}
	if(htcCount>=1){$("#filterHTC").removeClass('noPhones'); $("#filterHTC :checkbox").removeAttr('checked'); $("#filterHTC :checkbox").removeAttr('disabled');}
	//if(threeCount>=1){$("#filterThree").removeClass('noPhones'); $("#filterThree :checkbox").removeAttr('checked'); $("#filterThree :checkbox").removeAttr('disabled');}
	if(lgCount>=1){$("#filterLG").removeClass('noPhones'); $("#filterLG :checkbox").removeAttr('checked'); $("#filterLG :checkbox").removeAttr('disabled');}
	$(checkedElements).attr('checked', 'checked');
}

function updateFilters(filteredList){
	var smartphoneCount = 0;
	var cameraCount = 0;
	var emailCount = 0;
	var gpsCount = 0;
	var nokiaCount = 0;
	var iPhone4Count = 0;
	var samsungCount = 0;
	var sonyCount = 0;
	var inqCount = 0;
	var blackberryCount = 0;
	var htcCount = 0;
	//var threeCount = 0;
	var lgCount = 0;
	//var simCount = 0;
	

	for(var i=0; i<filteredList.length; i++){
		var phone = filteredList[i];
		if(phone.smartphone) { smartphoneCount++; }
		if(phone.email) { emailCount++; }
		if(phone.camera) { cameraCount++; }
		if(phone.gps) { gpsCount++; }
		//if(phone.sim) { simCount++; }
		switch(phone.manufacturer){
			case 'Nokia':
				nokiaCount++;
				break;
			case 'Samsung':
				samsungCount++
				break;
			case 'Sony Ericsson':
				sonyCount++
				break;
			case 'INQ':
				inqCount++
				break;
			case 'BlackBerry':
				blackberryCount++
				break;
			case 'HTC':
				htcCount++
				break;
			case 'LG':
				lgCount++
				break;
			default:
				break;
		}
		if(phone.model && phone.model.indexOf('iPhone 4')!=-1){
			iPhone4Count++
		}
	}
	$('.filter').removeClass('noPhones');
	var checkedElements = $('.filter :checked');
	$('.filter :checked').removeAttr('checked');
	$('.filter :checkbox').removeAttr('disabled');
	$(checkedElements).attr('checked', 'checked');
	if(smartphoneCount<1){ $("#filterSmartphone").addClass('noPhones'); $("#filterSmartphone :checkbox").attr('disabled', 'disabled');}
	if(emailCount<1){$("#filterEmail").addClass('noPhones'); $("#filterEmail :checkbox").attr('disabled', 'disabled');}
	if(cameraCount<1){$("#filterCamera").addClass('noPhones'); $("#filterCamera :checkbox").attr('disabled', 'disabled');}
	if(gpsCount<1){$("#filterGPS").addClass('noPhones'); $("#filterGPS :checkbox").attr('disabled', 'disabled');}
	if(nokiaCount<1){$("#filterNokia").addClass('noPhones'); $("#filterNokia :checkbox").attr('disabled', 'disabled');}
	if(iPhone4Count<1){$("#filterIPhone4").addClass('noPhones'); $("#filterIPhone4 :checkbox").attr('disabled', 'disabled');}
	if(samsungCount<1){$("#filterSamsung").addClass('noPhones'); $("#filterSamsung :checkbox").attr('disabled', 'disabled');}
	if(sonyCount<1){$("#filterSony").addClass('noPhones'); $("#filterSony :checkbox").attr('disabled', 'disabled');}
	if(inqCount<1){$("#filterINQ").addClass('noPhones'); $("#filterINQ :checkbox").attr('disabled', 'disabled');}
	if(blackberryCount<1){$("#filterBlackberry").addClass('noPhones'); $("#filterBlackberry :checkbox").attr('disabled', 'disabled');}
	if(htcCount<1){$("#filterHTC").addClass('noPhones'); $("#filterHTC :checkbox").attr('disabled', 'disabled');}
	//if(threeCount<1){$("#filterThree").addClass('noPhones'); $("#filterThree :checkbox").attr('disabled', 'disabled');}
	if(lgCount<1){$("#filterLG").addClass('noPhones'); $("#filterLG :checkbox").attr('disabled', 'disabled');}
	//if(simCount<1){$("#filterSIM").addClass('noPhones'); $("#filterSIM :checkbox").attr('disabled', 'disabled');}
	
}

/*
 * unfilter phones by setting the active phones to all phones and 
 * removing noPhoens class from prevously empty filters
 */
function unfilterAllPhones(){
	$(".filter").removeClass('noPhones');
	$(".filter :checkbox").removeAttr("checked");
	$(".filter :checkbox").removeAttr("disabled");
	
	var centrePhone = getCurrentPhone();
 
	setVisiblePhones(devices);
	for(var idx in visiblePhones){
		visiblePhones[idx].visibleIndex = idx;
	}
	$("#mobilesFound").html(visiblePhones.length);
	
	$('.phoneSlot').removeClass('displayNone');
	updateFilters(visiblePhones);
	
	var centrePhonePosition = getVisiblePhoneLocation(visiblePhones, centrePhone);
	setCentrePhoneAtVisibleIndex(centrePhonePosition);
	findNearestPlanByMinutes(getCurrentPhone(), 300);
}

/*###########################################################################################################
 * 									Minutes/Price/Phone Access Functions
 ###########################################################################################################*/
function setMinutes(minsToSet){
	var mins = getPositionFromMinutesArray(minsToSet);
	setMinutesPosition(mins);
}

function getPositionFromMinutesArray(minsToGet){

	var bestMins = (minutesInt[minutesInt.length-1])+1;
	var bestMinsPos = new Number(0);
	if(isNaN(minsToGet))
	{
		minsToGet = 2000;
	}
	for(var i in minutesInt){
		var mins = minutesInt[i];
		if(mins>=minsToGet && mins<bestMins){
			bestMins = mins;
			bestMinsPos = new Number(i);
		}
	}
	return bestMinsPos;
}

function setMinutesPosition(position){
	var item = position;
	if(item < 0){
		item = 0;
	}
	$("#minutesSlider").slider("option", "value", position);
	if(planType == "talker"){
		$("#minutesSliderContainer .labelSmall").html("Mins/Texts");
	}else{
		$("#minutesSliderContainer .labelSmall").html("Mins");
	}
	
	if(isNaN(minutes[item])){
		$("#selectedMinutes").removeClass("onePlan");
		$("#selectedMinutes").html(minutesInt[item]);
		//$("#selectedMinutes").addClass("onePlan");
		$("#minutesSliderContainer .labelSmall").show();
	}else{
		$("#selectedMinutes").removeClass("onePlan");
		$("#selectedMinutes").html(minutes[item]);
		$("#minutesSliderContainer .labelSmall").show();
	}
	
}

function getMinutes(){
	var item = $("#minutesSlider").slider("option", "value");
	return minutesInt[item];
}

function setPrice(price){
	$("#priceSlider").slider('option', 'value', price);
	$("#selectedPrice").html(getCostToDisplay(price));
}

function getCurrentPhone(){
	return visiblePhones[$("#phoneSlider").slider('option', 'value')];
}

function getSliderPositionBySelector(selector){
	return $(selector).slider('option', 'value');
}
function setVisiblePhones(newVisiblePhones){
	visiblePhones = newVisiblePhones;
	$("#phoneSlider").slider('option', 'max', newVisiblePhones.length-1);
}
/*###########################################################################################################
 * 									Slider Functions
 ###########################################################################################################*/
/*
 * Create a labelled slider in the given CSS selector, with ethe provided options,
 * labels should appear with interval chosen and labels are provided as an array
 */
function createLabelledSlider(selector, options, interval, labels){
	var width = interval * (labels.length-1);
	createSliderLabels(selector, interval, labels);
	$(selector).slider(options);
	$(selector).css("width", width);
	$(selector).css("margin-left", interval*0.4);
}

/*
 * Create labels if there are are least two, they will be placed interval width
 * apart such that they overlap teh end of the slider by half an interval width
 */
function createSliderLabels(selector, interval, labels){
	if(labels.length > 2){
		var slideAxis = $('<div class="greyText slideAxis floatLeft"></div>');
		var axisLabels = $('<div></div>');
		for(var i=0; i<labels.length; i++){
			var div;
			if(i == (labels.length -1)){
				div = $('<div class="axisTag lastTag floatLeft">'+ labels[i] +'</div>');
			} else if(i>0){
				div = $('<div class="axisTag floatLeft">'+ labels[i] +'</div>').css('width', interval);
			} else {
				div = $('<div class="axisTag firstTag floatLeft">'+ labels[0] +'</div>').css('width', interval);
			}
			$(axisLabels).append(div);
		}
		
		//$(axisLabels).append("<div class='clear'></div>");
		$(slideAxis).html(axisLabels);
		//var axisMarkers = createAxisMarkers(interval, labels.length);
		
		$(selector).before(slideAxis);
		//$(selector).after(axisMarkers);
	}		
}

function createAxisMarkers(interval, numberOfMarkers){
	var axisMarkers = $("<div class='axisMarkers'></div>");
	for(var i=0; i<numberOfMarkers; i++){
		var div = $("<div class='floatLeft'></div>");//.css('width', interval);
		var inner = $("<div class='blackLine'>&nbsp;</div>").css('paddingLeft', (interval/2));
		$(div).html(inner);
		$(axisMarkers).append(div);
	}
	$(axisMarkers).append("<div class='clear'></div>");
	return axisMarkers;
	
}

function dropPhone(event, ui){
	var source = $(ui.draggable).parents(".phoneSlot").attr("id");
	var dest = $(this).attr("id");
	
}

/*
 * Method to trigger when the minutes slider is changed or has stopped being changed
 */
function minuteSliderChanged (event, ui){

		var item = ui.value;
		if(item < 0){
			item = 0;
		}
		
		var phone = getCurrentPhone();
		findNearestPlanByMinutes(phone, minutesInt[item]);

}

/*
 * Method to trigger when the price slider is changed or has stopped being changed
 */
function phoneSliderChanged(event, ui) {
	setCentrePhoneAtVisibleIndex(ui.value);
	//$("#minutesSlider").slider('value', 2);
	//Remove this to stop it from resetting to the default plan
	setMinutes(initialUsage);
	findNearestPlanByMinutes(visiblePhones[ui.value], getMinutes());
}

function phoneSliderDrag(event, ui) {
	//$("#minutesSlider").slider('value', 2);
	setCentrePhoneAtVisibleIndex(ui.value);
}

/*
 * Method to trigger when the price slider is changed or has stopped being changed
 */
function priceSliderChanged(event, ui) {
	if(event.which==1){
		findPlansBelowPriceLimit(ui.value);
	} 
}

function getSliderValueBySelector(selector){
	return $(selector).slider('option', 'value');
}

function setSliderValueBySelector(selector, value){
	var min = $(selector).slider('option', 'min');
	var max = $(selector).slider('option', 'max');
	var valueToSet = new Number(value);
	if(value < min){
		valueToSet = min;
	}
	if(value > max){
		valueToSet = max;
	}
	$(selector).slider('option', 'value', valueToSet);
	return valueToSet;
}

/*###########################################################################################################
 * 									Phone/Carousel Functions
 ###########################################################################################################*/

function loadPhone(selector, phone, isCentre){
	if(phone){
		$(selector).find(".phoneIcon").removeClass('notFeature');
		if(!phone.smartphone){
			$(selector).find(".smartphoneIcon").addClass('notFeature');
		}
		if(!phone.camera){
			$(selector).find(".cameraIcon").addClass('notFeature');
		}
		if(!phone.email){
			$(selector).find(".emailIcon").addClass('notFeature');
		}
		if(!phone.gps){
			$(selector).find(".gpsIcon").addClass('notFeature');
		}
		
		var phoneUrl = phone.smallImageUrl;
		if(isCentre){
			phoneUrl = phone.largeImageUrl;
		}
		$(selector).removeClass('hide');
		$(selector).find(".phoneImage").attr('src', phoneUrl);
		$(selector).find("#phoneName").html(phone.displayName);
		$(selector).find("#moreDetailsLink").attr('href', "/_standalone/Device_Detail?content_aid=" + phone.fatwireId);
		
		
	}else {
		$(selector).addClass('hide');
	}
}

/*function refreshCarousel(phonesList, centrePhonePosition){
	$("#phoneSlider").slider('option', 'max', phonesList.length-1);
	var validCentrePosition = setSliderValueBySelector("#phoneSlider", centrePhonePosition);
	loadPhone("#centrePhone", phonesList[validCentrePosition], true);
	loadPhone("#innerLeftPhone", phonesList[validCentrePosition-1], false);
	loadPhone("#innerRightPhone", phonesList[validCentrePosition+1], false);
	loadPhone("#outterLeftPhone", phonesList[validCentrePosition-2], false);
	loadPhone("#outterRightPhone", phonesList[validCentrePosition+2], false);
	findNearestPlanByMinutes(phonesList[validCentrePosition], getMinutes());
}*/



/*###########################################################################################################
 * 									Helper Functions
 ###########################################################################################################*/
function getCostToDisplay(cost){
	cost = new Number(cost);
	var displayCost = "" + Math.floor(cost);
	if(isDecimal(cost)){
		var decimal = ((cost*100)%100).toFixed(0);
		displayCost += "<span class='decimal mediumTitle'>."+decimal+"</span>";
	}
	return displayCost;
	
}

function isDecimal(number){
	var twoDecimal = number.toFixed(2);
	var decimal = ((twoDecimal * 100) % 100).toFixed(0);
	var isDecimal = false;
	if(decimal >0){
		isDecimal = true;
	}
	return isDecimal;
}

function isInList(phonesList, phone){
	var isVisible = false;
	for(var i in phonesList){
		var visiblePhone = phonesList[i];
		if(phone == visiblePhone){
			isVisible = true;
			break;
		}
	}
	return isVisible;
}

function getVisiblePhoneLocation(phonesList, phone){
	var visibleLocation = null;
	if(isInList(phonesList, phone)){
		for(var i in phonesList){
			var visiblePhone = phonesList[i];
			if(phone == visiblePhone){
				visibleLocation = i;
			}
		}
	}
	return visibleLocation;
}

function findCentrePhone(phonesList){
	var length = phonesList.length;
	var centre = (length-1)/2;
	if(length%2==0){
		centre = length/2;
	}
	return centre;
}

/*
 * Re-order the array to the format for ordering phones from a given hierarchy in the carousel
 */
function reorderArray(oldArray){
	var newArray = new Array();
	if(oldArray.length > 1){
		//Start at last element of the array if even number of elements
		var pos = oldArray.length-1;
		if(oldArray.length%2 != 0){
			//Start at second to last element of array if odd number of elements
			pos = oldArray.length-2;
		}
		
		
		//Add even elements to the new array
		while(pos>0){
			newArray.push(oldArray[pos]);
			pos = pos-2;
		}
		pos = 0;
		//Add odd elements to the new array
		while(pos<oldArray.length){
			newArray.push(oldArray[pos]);
			pos = pos + 2;
		}
	} else{
		newArray = oldArray;
	}
	return newArray;
}


/*###########################################################################################################
 * 									Print/Display Functions
 ###########################################################################################################*/
function printArrayId(array){
	var msg = "";
	for(var i in array){
		msg += array[i].id + "\n";
	}
	alert(msg);
}

function printPhoneList(phoneList){
	var msg = "";
	var i;
	for(i in phoneList){
		var phone = phoneList[i];
		msg += i + ": "+ phone.displayName + "\n";
	}
	alert(msg);
}

function printArray(array){
	var msg = "";
	var i;
	for(i in array){
		msg += array[i] + " ";
	}
	alert("length: " + i + "\n" + msg);
}
