
// For debugging
Debug = false;
function DebugThis(alertText){
	if(Debug){
		alert(alertText);
	}
}

// Holds filter state
var FilterObj = {
	"pName" : "",
	"pPrice": "",
	"pMinutes": "",
	"pTexts": "",
	"pTenure": "",
	"pHandsetPrice": "",
	"pBenefit": "",
	"pTopSeller": "",
	setPrice: function(value){		
		if(this.pPrice != value){
			this.pPrice = value;
		} else {
			this.pPrice = "";
		}
	},
	setMinutes: function(value){
		if(this.pMinutes != value){
			this.pMinutes = value;
		} else {
			this.pMinutes = "";
		}
	},
	setTexts: function(value){
		if(this.pTexts != value){
			this.pTexts = value;
		} else {
			this.pTexts = "";
		}		 
	},
	setBenefit: function(value){
		if(this.pBenefit != value){
			this.pBenefit = value;
		} else {
			this.pBenefit = "";
		}		 
	},
	setName: function(value){
		 this.pName = value;
	},	
	setTenure: function(value){
		 this.pTenure = value;
	},
	setHandsetPrice: function(value){
		 this.pHandsetPrice = value;
	},
	setTopSeller: function(value){
		 this.pTopSeller = value;
	}
}

function Trackit(svpPlanName){
      if(TrackingVariable == ""){
            dcsMultiTrack ('DCS.dcsuri','/shop/yourplan/paym/buy.link','WT.cg_n','Shop Plan PM New','WT.cg_s','Home','WT.cg_t','Buy','DCSext.plan_type',svpPlanName)            
      } else {
            dcsMultiTrack ('DCS.dcsuri','/shop/yourplan/paym/find_plan/buy.link','WT.cg_n','Shop Plan PM New','WT.cg_s','Find a plan','WT.cg_t','Filter - Buy','DCSext.plan_type',svpPlanName)           
      }
}

function scrollWindow(){
	for(var x = 0; x < 70; x++ ){
    	window.scrollBy(0,100); 
    }
}

/* Cookie Business ========================================================== */
function InitializeFilter(){	
	// Checking if from spotlight, looking for query string
	if($.jqURL.get('Filter')){		
		var FilterPreset = $.jqURL.get('Filter');
		// Displays plans according to query string, 
		// just 36 month plans for now, can be extended
		Filter18and24();
		scrollWindow();		// simple scroll to bottom of page
	} else {	
		// Checking if from Plans details page, looking for cookie
		var FilterSettings = ""; 
		if( $.cookie('paymCookie') != null ){
			FilterSettings = $.cookie('paymCookie'); 			// Read cookie
			$.cookie('paymCookie', null, { path:'/' });			// Delete cookie
		}
		if( FilterSettings != "" && FilterSettings != null){		
			// Displays plans according to cookie
			FilterPlans(FilterSettings);			
		} else {		
			// Displays Top Sellers
			TopSellers();			
		}	
	};
}

function FilterPlans(FilterSettings){	
	var FilterValues = FilterSettings.split("][");	
	// var cookieString = 'Tenure][Price][Minutes][Texts][Benefit';
	ResetTheFilter();	
	FilterObj.pTenure = FilterValues[0];
	FilterObj.pPrice = FilterValues[1];
	FilterObj.pMinutes = FilterValues[2];
	FilterObj.pTexts = FilterValues[3];
	FilterObj.pBenefit = FilterValues[4];
	
	FilterTheList(svpPlansALL);
	SetMenuDisplay(svpPlansFiltered);
	DisplayPlans(svpPlansFiltered);
			
	if( FilterValues[0] == "12-12" ){
		SetUp12onlyLayers();
	} else if ( FilterValues[0] == "36-36" ){
		SetUp36onlyLayers();
	} else {
		SetUp18and24Layers();
	}
}

function WriteCookie(){
	// Build the cookie string from the filter settings
	if( FilterObj.pTopSeller != "Yes" ){
		// var cookieString = 'Tenure][Price][Minutes][Texts][Benefit';
		// e.g. var cookieString = '18-24][""][""][""][""';
		var cookieString = FilterObj.pTenure + "][" + FilterObj.pPrice + "][" + FilterObj.pMinutes + "][" + FilterObj.pTexts + "][" + FilterObj.pBenefit;
		$.cookie('paymCookie', cookieString, { expires: 2, path:'/' });
	}
}

function FindOutMore(detailPageURL){
	WriteCookie();
	location.href = detailPageURL;
}
/* ========================================================================== */

function TextCorrection(InComingString){
	var HTMtoReturn = "";
	if(InComingString == "12-12"){
		HTMtoReturn = "12";
	} else {
		HTMtoReturn = InComingString.replace("-", " and ");
	}	
	return HTMtoReturn;
}

function GroupHTML(GroupCategory){
	var HTMLtoReturn = "";
	var SuffixToUse = "";
	SuffixToUse = FilterObj.pTenure;		
	if( SuffixToUse == "18-24-36" ){
		if( GroupCategory == "PayMonthly36" ){
			SuffixToUse = "36";
		} else {
			SuffixToUse = "18-24";
		}
	}		
	switch(GroupCategory){
		case "Dolphin":			
			HTMLtoReturn = '<div class="grouping Dolphin"><div class="groupDiv groupDolphin' + SuffixToUse + '" id="top_dolphin_plans" title="Dolphin ' + TextCorrection(SuffixToUse) + ' month plans"></div>';		
		break;
		case "Racoon":
			HTMLtoReturn = '<div class="grouping Racoon"><div class="groupDiv groupRacoon' + SuffixToUse+ '" id="top_racoon_plans" title="Racoon ' + TextCorrection(SuffixToUse) + ' month plans"></div>';			
		break;
		case "Panther":
			HTMLtoReturn = '<div class="grouping Panther"><div class="groupDiv groupPanther' + SuffixToUse + '" id="top_panther_plans" title="Panther ' + TextCorrection(SuffixToUse) + ' month plans"><p>Select a Panther plan to see our selection of email-capable phones (<a href="' + applicationPath + '/yourplan/push_email" class="overlay">what is push email?</a>)</p></div>';			
		break;
		case "PayMonthly36":
			HTMLtoReturn = '<a name="plans36"></a><div class="grouping Orange"><div class="groupDiv groupOrange' + SuffixToUse + '" id="top_orange_plans" title="Orange ' + TextCorrection(SuffixToUse) + ' month plans"></div>';	
		break;
		case "None":
			HTMLtoReturn = '<div class="grouping Email"><div class="groupDiv groupEmail' + SuffixToUse + '" id="top_email_plans" title="Email only ' + TextCorrection(SuffixToUse) + ' month plans"><p>Browse the internet and send and receive push email (<a href="' + applicationPath + '/yourplan/push_email" class="overlay">what is push email?</a>)</p></div>';							
		break;		
	}	
	return HTMLtoReturn;
}


function GroupHTML_btmBit(){
	var HTMtoReturn = "";
	HTMtoReturn = HTMtoReturn + '			</div>'	
	return HTMtoReturn;
}

var Categories = new Array("Dolphin", "Racoon", "Panther", "None", "PayMonthly36")
var Animals = new Array("dolphin", "racoon", "panther", "blackberry", "orange")
var PlanPrices = new Array("5","10","15","25","30","35","40","45","50","55","60","65","70","75","80","-");

// Functions 
function formatPrice(priceString, returnUnit){
	var returnValue = "";
	var priceArray = priceString.split(".");
	if( returnUnit == "pound" ){
		returnValue = priceArray[0]; 
	} else if ( returnUnit == "pence" ){
		returnValue = priceArray[1];
		if(returnValue.length == 1){
			returnValue = returnValue + '0'; 
		}		
	} else {
		returnValue = priceString;
	}
	return returnValue;
}

function removeSpaces(someString){
	var returnString = someString;
	while(returnString.indexOf(" ")!= -1){
		returnString = returnString.replace(" ","");
	}
	return returnString;
}

function IsFree(jsonPrice){
	var priceToReturn = jsonPrice;
	if(jsonPrice == "&pound;0.00"){
		priceToReturn = "<span class='orangeTxt'>FREE</span>";
	}
	return priceToReturn;
}

function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}

function HTML_topBit(svpHead, handSetPrice){
	var HTMtoReturn = "";
	HTMtoReturn = HTMtoReturn + '<div class="svp_group">';
	HTMtoReturn = HTMtoReturn + '	<div class="svp_group_top svp_' + svpHead.toLowerCase() + '" title="' + svpHead.toLowerCase() + '">';		
	HTMtoReturn = HTMtoReturn + '		<h5><span>' + svpHead.toLowerCase() + '</span></h5>';
	if(handSetPrice != null){
		HTMtoReturn = HTMtoReturn + '		<p>Your phone is <strong>' + IsFree(handSetPrice) + '</strong> with this plan</p>';
	}
	HTMtoReturn = HTMtoReturn + '		<hr>';
	HTMtoReturn = HTMtoReturn + '	</div>';
	HTMtoReturn = HTMtoReturn + '	<div class="svp_group_mid">';
	HTMtoReturn = HTMtoReturn + '		<div class="svp_group_mid_mid">';
	return HTMtoReturn;
}

function HTML_btmBit(){
	var HTMtoReturn = "";
	HTMtoReturn = HTMtoReturn + '			<hr>'		
	HTMtoReturn = HTMtoReturn + '			<div class="svp_group_btm"></div>'
	HTMtoReturn = HTMtoReturn + '		</div>'
	HTMtoReturn = HTMtoReturn + '	</div>'					
	HTMtoReturn = HTMtoReturn + '</div>'
	HTMtoReturn = HTMtoReturn + '<p class="backtoTop"><a href="#body-head">back to top</a></p>';
	return HTMtoReturn;
}

function correctTextValue(TextsValue){
	if(TextsValue == "-1"){
		return "unlimited";
	} else {
		return TextsValue;
	}
}

function correctBenefitValue(BenefitValue){
	if(BenefitValue == "-1"){
		return "&nbsp;";
	} else {
		return BenefitValue;
	}
}

function CalculateSavings(inStorePrice, onlinePrice, savePeriod){
	var Savings = (inStorePrice - onlinePrice) * savePeriod;
	Savings = Savings + "";
	return formatPrice(Savings, "pound");	
}

function planTemplate(svpPlanObj, Animal){		
	var HTMLtoReturn = "";
		
	HTMLtoReturn = HTMLtoReturn + '<div class="shadedBox_' + svpPlanObj.pTenure + '">'
	HTMLtoReturn = HTMLtoReturn + '		<div class="svp_item_rowfirst">'
	HTMLtoReturn = HTMLtoReturn + '			<ul class="svp_ftr_items">'
	HTMLtoReturn = HTMLtoReturn + '				<li class="tenure"><b>' + svpPlanObj.pTenure + '</b><br>months</li>'
	
	if(Animal == "blackberry" ){	
		HTMLtoReturn = HTMLtoReturn + '				<li class="eData"><b>' + correctTextValue(svpPlanObj.pData) + '</b><br>data</li>';	
	} else {	
		HTMLtoReturn = HTMLtoReturn + '				<li class="mins"><b>' + svpPlanObj.pMinutes + '</b><br>anytime minutes</li>'
		HTMLtoReturn = HTMLtoReturn + '				<li class="txt"><b>' + correctTextValue(svpPlanObj.pTexts) + '</b><br>texts</li>'
		HTMLtoReturn = HTMLtoReturn + '				<li class="unlimited">' + correctBenefitValue(svpPlanObj.pBenefit) + '</li>'	
	}
	
	HTMLtoReturn = HTMLtoReturn + '			</ul>'
	HTMLtoReturn = HTMLtoReturn + '			<div class="svp_item_rightcontent">'
	
	if( svpPlanObj.pInstorePrice == svpPlanObj.pPrice || svpPlanObj.pInstorePrice == "0.0" ){		
		HTMLtoReturn = HTMLtoReturn + '				<div class="svp_item_price_dolphin15">'
		HTMLtoReturn = HTMLtoReturn + '					<div class="svp_item_price_online"><h6>online</h6>&pound;' + formatPrice(svpPlanObj.pPrice, "pound") + '<sup>.' + formatPrice(svpPlanObj.pPrice, "pence") + '</sup></div>'
		HTMLtoReturn = HTMLtoReturn + '					<!-- <div class="clear"></div> -->'
		HTMLtoReturn = HTMLtoReturn + '				</div>'
		
		if( Animal == "orange" ){		
			HTMLtoReturn = HTMLtoReturn + '				<div class="svp_item_shout_web_only"><img src="/images/yourplan/paymonthly/roundel_includes_free_phone.png" alt="includes free phone" /></div>'
		} else {
			HTMLtoReturn = HTMLtoReturn + '				<div class="svp_item_shout_web_only">&nbsp;</div>'
		}
					
	} else {	
		HTMLtoReturn = HTMLtoReturn + '				<div class="svp_item_price">'
		HTMLtoReturn = HTMLtoReturn + '					<div class="svp_item_price_instore"><h6>instore</h6>&pound;' + formatPrice(svpPlanObj.pInstorePrice, "pound") + '<sup>.' + formatPrice(svpPlanObj.pInstorePrice, "pence") + '</sup></div>'
		HTMLtoReturn = HTMLtoReturn + '					<div class="svp_item_price_online"><h6>online</h6>&pound;' + formatPrice(svpPlanObj.pPrice, "pound") + '<sup>.' + formatPrice(svpPlanObj.pPrice, "pence") + '</sup></div>'
		HTMLtoReturn = HTMLtoReturn + '					<div style="clear: left;"></div>'
		HTMLtoReturn = HTMLtoReturn + '				</div>'
		HTMLtoReturn = HTMLtoReturn + '				<div class="svp_item_shout">'
		HTMLtoReturn = HTMLtoReturn + '					<span class="mid">Save</span><br />'
		HTMLtoReturn = HTMLtoReturn + '					<span class="lrg">&pound;' + CalculateSavings(svpPlanObj.pInstorePrice, svpPlanObj.pPrice, svpPlanObj.pTenure) + '</span>'
		HTMLtoReturn = HTMLtoReturn + '					<span class="sml">over&nbsp;' + svpPlanObj.pTenure + '</span><span class="sml2"><br>months</span>'						
		HTMLtoReturn = HTMLtoReturn + '				</div>'	
	}	
	
	HTMLtoReturn = HTMLtoReturn + '				<div class="svp_item_buy">'
    if( Animal == "blackberry" ){
        HTMLtoReturn = HTMLtoReturn + '					<form name="getPlan(' + svpPlanObj.pId + ')" method="post" action="' + applicationPath + '/yourplan/buynow">'        
    }else{
        HTMLtoReturn = HTMLtoReturn + '					<form name="getPlan(' + svpPlanObj.pId + ')" method="post" action="' + applicationPath + '/yourplan/selection">'
    }
	HTMLtoReturn = HTMLtoReturn + '					<input name="servicePlanTypeId(0)" value="' + svpPlanObj.pTypeId + '" type="hidden">';
	HTMLtoReturn = HTMLtoReturn + '					<input name="servicePlanGroupId(0)" value="' + svpPlanObj.pGroupId + '" type="hidden">';
	HTMLtoReturn = HTMLtoReturn + '					<input name="contractDurationId" value="' + svpPlanObj.pDurationId  + '" type="hidden">';
	HTMLtoReturn = HTMLtoReturn + '					<input name="handsetId" value="' + handsetId + '" type="hidden">';
    if( Animal == "blackberry" ){
        HTMLtoReturn = HTMLtoReturn + '					<input name="mapping" value="basket" type="hidden">';
    }else{
        HTMLtoReturn = HTMLtoReturn + '					<input name="mapping" value="additionalservices" type="hidden">';
    }

	HTMLtoReturn = HTMLtoReturn + '					<input name="servicePlanId" value="' + svpPlanObj.pId + '" type="hidden">';
	HTMLtoReturn = HTMLtoReturn + '					<input src="/images/yourplan/paymonthly/btn_buy.gif" id="buy' + svpPlanObj.pId + '" name="buy" alt="buy" title="buy" type="image" onclick="Trackit(\''+ svpPlanObj.pName +'\');" />'	
	HTMLtoReturn = HTMLtoReturn + 					'</form>'
	HTMLtoReturn = HTMLtoReturn + '				</div>'
	HTMLtoReturn = HTMLtoReturn + '				<div class="clear"></div>'						
	HTMLtoReturn = HTMLtoReturn + '			</div>'					
	HTMLtoReturn = HTMLtoReturn + '			<div class="clear"></div>';	

	if( svpPlanObj.pId == "11311" && handsetId == "0" ){
		HTMLtoReturn = HTMLtoReturn + '			<p class="specialPlan">Dolphin 15 plan is available on <strong>selected handsets</strong></p>'
	}	
						
	HTMLtoReturn = HTMLtoReturn + '			<div class="bottomSection">'						
	HTMLtoReturn = HTMLtoReturn + '				<div class="leftSection">'
	
	// Starts the container 
	if(( svpPlanObj.pMaps == "Yes" ) || ( svpPlanObj.pTryBundle != null && svpPlanObj.pTryBundle != "" ) || svpPlanObj.pData > 0 || svpPlanObj.pPremium == "Yes" ){	
		HTMLtoReturn = HTMLtoReturn + '					<div class="svpItemsListTop">'
		HTMLtoReturn = HTMLtoReturn + '						<div class="svpItemsListBottom">'	
	}
	
	// Starts the list
	if(( svpPlanObj.pMaps == "Yes" ) || ( svpPlanObj.pTryBundle != null && svpPlanObj.pTryBundle != "" ) || svpPlanObj.pData > 0 ){	
		HTMLtoReturn = HTMLtoReturn + '							<ul>'	
	}
	
	// Adds list item
	if( svpPlanObj.pMaps == "Yes" ){	
		HTMLtoReturn = HTMLtoReturn + '								<li><a href="' + applicationPath + '/yourplan/orange_maps" class="overlay" onclick="dcsMultiTrack (\'DCS.dcsuri\',\'/shop/yourplan/paym/orange_maps.link\',\'WT.cg_n\',\'Shop Plan PM New\',\'WT.cg_s\',\'Home\',\'WT.cg_t\',\'Orange Maps\',\'DCSext.plan_type\',\'' + svpPlanObj.pName + '\')">inclusive sat nav with Orange Maps</a></li>'		
	}
	
	// Adds list item
	if( svpPlanObj.pTryBundle != null && svpPlanObj.pTryBundle != "" ){	
		HTMLtoReturn = HTMLtoReturn + '								<li><a href="' + applicationPath + '/yourplan/unlimited_free_evening_and_weekend" class="overlay" onclick="dcsMultiTrack (\'DCS.dcsuri\',\'/shop/yourplan/paym/mobile_internet_trial.link\',\'WT.cg_n\',\'Shop Plan PM New\',\'WT.cg_s\',\'Home\',\'WT.cg_t\',\'Mobile internet trial\',\'DCSext.plan_type\',\'' + svpPlanObj.pName + '\')">' + svpPlanObj.pTryBundle + '</a></li>'	
	}
	
	// Adds list item
	if( svpPlanObj.pData > 0 ){	
		HTMLtoReturn = HTMLtoReturn + '								<li><a href="' + applicationPath + '/yourplan/internet_anytime_anywhere" class="overlay" onclick="dcsMultiTrack (\'DCS.dcsuri\',\'/shop/yourplan/paym/mobile_internet_500mb.link\',\'WT.cg_n\',\'Shop Plan PM New\',\'WT.cg_s\',\'Home\',\'WT.cg_t\',\'Mobile internet 500MB\',\'DCSext.plan_type\',\'' + svpPlanObj.pName + '\')">500MB anytime mobile internet browsing</a></li>'	
	}	
	
	// Ends the list
	if(( svpPlanObj.pMaps == "Yes" ) || ( svpPlanObj.pTryBundle != null && svpPlanObj.pTryBundle != "" ) || svpPlanObj.pData > 0 ){	
		HTMLtoReturn = HTMLtoReturn + '							</ul>'	
	}
	
	// Adds on the paragraph
	if(svpPlanObj.pPremium == "Yes" ){
		HTMLtoReturn = HTMLtoReturn + '							<p>and itemised billing, Answer Phone and dedicated Customer Service.</p>'
	}
	
	// Ends the container
	if(( svpPlanObj.pMaps == "Yes" ) || ( svpPlanObj.pTryBundle != null && svpPlanObj.pTryBundle != "" ) || svpPlanObj.pData > 0 || svpPlanObj.pPremium == "Yes" ){	
		HTMLtoReturn = HTMLtoReturn + '						</div>'	
		HTMLtoReturn = HTMLtoReturn + '					</div>'	
	}	
					
	HTMLtoReturn = HTMLtoReturn + '				</div>'						
	HTMLtoReturn = HTMLtoReturn + '				<div class="rightSection">';
	HTMLtoReturn = HTMLtoReturn + '					<p><a href=javascript:FindOutMore("' + applicationPath + '/show/plan/' + removeSpaces(svpPlanObj.pName).toLowerCase() + '/' + svpPlanObj.pTenure + '_months/' + svpPlanObj.pId + '/handset/' + handsetId + '")>find out more</a></p>';															
	HTMLtoReturn = HTMLtoReturn + '				</div>'						
	HTMLtoReturn = HTMLtoReturn + '				<div class="cboth"><!--  --></div>'
	HTMLtoReturn = HTMLtoReturn + '			</div>'
	HTMLtoReturn = HTMLtoReturn + '		</div>'			
	HTMLtoReturn = HTMLtoReturn + '</div>'	
	return HTMLtoReturn;
}

function ResetTheFilter(){
	FilterObj.setTenure(defaultSettings.pTenure)
	FilterObj.setPrice(defaultSettings.pPrice);
	FilterObj.setMinutes(defaultSettings.pMinutes);
	FilterObj.setTexts(defaultSettings.pTexts);
	FilterObj.setBenefit(defaultSettings.pBenefit);
	FilterObj.setName(defaultSettings.pName);
	FilterObj.setHandsetPrice(defaultSettings.pHandsetPrice);
	FilterObj.setTopSeller(defaultSettings.pTopSeller);
	FilterTheList(svpPlansALL)
}

function ChangeFilter(type, value){
	switch(type){
		case "Tenure":
			FilterObj.setTenure(value);			
		break;
		case "Price":			
			FilterObj.setPrice(value);			
		break;
		case "Minutes":
			FilterObj.setMinutes(value);		
		break;
		case "Texts":
			FilterObj.setTexts(value);							
		break;
		case "Benefit":
			FilterObj.setBenefit(value);			
		break;
		case "Name":
			FilterObj.setName(value);			
		break;
		case "HandsetPrice":
			FilterObj.setHandsetPrice(value);			
		break;
		case "TopSeller":
			FilterObj.setTopSeller(value);				
		break;
	}
}

function FilterOn(type, value){
	ChangeFilter(type, value)
	FilterTheList(svpPlansALL)	
	SetMenuDisplay(svpPlansFiltered)
	DisplayPlans(svpPlansFiltered)
}

function SetMenuDisplay(PlansList){
		
	var listedPrices = [];
	var listedMinutes = "+";
	var listedTexts = "+";
	var listedHandsetPrices = "+";
	var listedBenefits  = "+";
	var listedNames  = "+";	
	var listedTenure = "+";
	
	for(var x = 0; x < PlansList.length; x++){
		listedPrices[listedPrices.length] = PlansList[x].pPrice;
		listedMinutes = listedMinutes + PlansList[x].pMinutes + "+";
		listedTexts = listedTexts + PlansList[x].pTexts + "+";
		listedNames = listedNames + PlansList[x].pName + "+";
		listedBenefits = listedBenefits + PlansList[x].pCategory + "+";
		listedTenure = listedTenure + PlansList[x].pTenure + "+";
		if( handsetId != "" && handsetId != "0" ){	
			listedHandsetPrices = listedHandsetPrices + PlansList[x].pHandsetPrice + "+";							
		}	  
	}	
	
	// Resetting Price links
	var priceLinks = getElementsByClassName("priceFilter", "A", document.getElementById("PriceListUL"))
	var PriceDictionary = new Array("0-20","24-30","34-40","45-98");
	for(var x = 0; x < priceLinks.length; x++ ){
		priceLinks[x].href = 'javascript:FilterOn("Price", "'+ PriceDictionary[x] +'");';
		priceLinks[x].className = priceLinks[x].className.replace(" disabled","");
		priceLinks[x].className = priceLinks[x].className.replace(" active","");	
		priceLinks[x].blur();
	}
	for(var x = 0; x < priceLinks.length; x++ ){
		var SwitchIfOff = "YES";
		priceRange = PriceDictionary[x].split("-");			
		for(var j = 0; j < listedPrices.length; j++ ){ 
			if(listedPrices[j] > priceRange[0]-1 && listedPrices[j] < priceRange[1]+1 ){
				SwitchIfOff = "NO";
			}
		}
		if(SwitchIfOff == "YES"){
			priceLinks[x].href = "javascript:this.blur();";
			priceLinks[x].className = priceLinks[x].className + " disabled";
		}
	}
	if( FilterObj.pPrice != "" ){
		for(var x = 0; x < priceLinks.length; x++ ){
			if(PriceDictionary[x] == FilterObj.pPrice){
				priceLinks[x].className = priceLinks[x].className + " active";
			}
		}
	} 
	
	
	// Resetting Minute links
	var minLinks = getElementsByClassName("minuteFilter", "A", document.getElementById("MinutesListUL"))
	var minDictionary = new Array("100","200","400","600","900","1200","3000");
	for(var x = 0; x < minLinks .length; x++ ){
		minLinks[x].href = 'javascript:FilterOn("Minutes", "' + minDictionary[x]  + '");';
		minLinks[x].className = minLinks[x].className.replace(" disabled","");
		minLinks[x].className = minLinks[x].className.replace(" active","");
		minLinks[x].blur();
	}	
	for(var x = 0; x < minLinks.length; x++ ){
		var SwitchIfOff = "YES";
		var checkString = "+" + minDictionary[x] + "+";
		if(listedMinutes.indexOf(checkString) != -1 || listedMinutes == checkString){
			SwitchIfOff = "NO";	
		}			
		if(SwitchIfOff == "YES"){
			minLinks[x].href = "javascript:this.blur();";
			minLinks[x].className = minLinks[x].className + " disabled";
		}
	}
	if( FilterObj.pMinutes != "" ){
		for(var x = 0; x < minLinks.length; x++ ){
			if(minDictionary[x] == FilterObj.pMinutes){
				minLinks[x].className = minLinks[x].className + " active";
			}
		}
	}	
	
	
	// Resetting Text links
	var textLinks = getElementsByClassName("textFilter", "A", document.getElementById("TextsListUL"))
	var textDictionary = new Array("300","500","-1");
	for(var x = 0; x < textLinks .length; x++ ){
		textLinks[x].href = 'javascript:FilterOn("Texts", "' +  textDictionary[x]  + '");';
		textLinks[x].className =  textLinks[x].className.replace(" disabled","");
		textLinks[x].className =  textLinks[x].className.replace(" active","");
		textLinks[x].blur();
	}	
	for(var x = 0; x < textLinks.length; x++ ){
		var SwitchIfOff = "YES";
		var checkString = "+" + textDictionary[x] + "+";
		if(listedTexts.indexOf(checkString) != -1 || listedTexts == checkString){
			SwitchIfOff = "NO";	
		}			
		if(SwitchIfOff == "YES"){
			textLinks[x].href = "javascript:this.blur();";
			textLinks[x].className = textLinks[x].className + " disabled";
		}
	}
	if( FilterObj.pTexts != "" ){
		for(var x = 0; x < textLinks.length; x++ ){
			if(textDictionary[x] == FilterObj.pTexts){
				textLinks[x].className = textLinks[x].className + " active";
			}
		}
	}
	
	
	// Resetting Benefits links	
	var benefitsLinks = getElementsByClassName("benefitFilter", "A", document.getElementById("BenefitListUL"))	
	var benefitsDictionary = new Array("Dolphin","Racoon","Panther");
	for(var x = 0; x < benefitsLinks.length; x++ ){					
		benefitsLinks[x].href = 'javascript:FilterOn("Benefit", "' + benefitsDictionary[x] + '");';
		benefitsLinks[x].className = benefitsLinks[x].className.replace(" disabled","");
		if(document.getElementById("ben"+x) != null){
			document.getElementById("ben"+x).parentNode.removeChild(document.getElementById("ben"+x));		
		}		
		benefitsLinks[x].blur(); 
	}	
	for(var x = 0; x < benefitsLinks.length; x++ ){
		var SwitchIfOff = "YES";
		if(listedBenefits.indexOf(benefitsDictionary[x]) != -1 || listedBenefits == benefitsDictionary[x]){
			SwitchIfOff = "NO";	
		}			
		if(SwitchIfOff == "YES"){
			benefitsLinks[x].href = "javascript:this.blur();";
			benefitsLinks[x].className = benefitsLinks[x].className + " disabled";
		}
	}
	if( FilterObj.pBenefit != "" ){
		for(var x = 0; x < benefitsLinks.length; x++ ){
			if(benefitsDictionary[x] == FilterObj.pBenefit){				
				benefitsLinks[x].innerHTML = benefitsLinks[x].innerHTML + '<img id="ben'+x+'" src="/images/yourplan/paymonthly/xmarksthespot.gif" alt="selected" class="xmarksthespot" />';
			}
		}
	}	
			
	
	// Resetting Free Handset link
	if( handsetId != "" && handsetId != "0" ){	
		
		document.getElementById("freeSVPwithPhone").className = "chkBox";
		document.getElementById("freeSVPwithPhone").href = 'javascript:PlansWithFreeHandset("freeSVPwithPhone");';
		
		// Check if any free ones
		if( listedHandsetPrices.indexOf( "+&pound;0.00+" ) == -1 ){
			document.getElementById("freeSVPwithPhone").className = "chkBox disabled";
			document.getElementById("freeSVPwithPhone").href = 'javascript:this.blur();';	
		}
		
		// Check if all are free
		var eachHandPrice = listedHandsetPrices.split("+");
		var allFree = "YES"
		for( var x = 1; x < eachHandPrice.length-1; x++ ){
			if( eachHandPrice[x] != "&pound;0.00" ){				
				allFree = "NO";	
			}
		}
		if(allFree == "YES"){
			document.getElementById("freeSVPwithPhone").className = "chkBox active_and_disabled";
			document.getElementById("freeSVPwithPhone").href = 'javascript:this.blur();';
		}						
	}		
	
	// Resetting Anchor links
	var anchorLinks = getElementsByClassName("anchorLink", "LI", document.getElementById("TopPlansNavAnchorUL"))
	for(var x = 0; x < anchorLinks.length; x++ ){			
		if(anchorLinks[x].className.indexOf("hidden") == -1){
			anchorLinks[x].className = anchorLinks[x].className + " hidden";
		}
	}		
	for(var x = 0; x < anchorLinks.length; x++ ){
		var classToCheck = anchorLinks[x].className.split(" ")[1];			
		if(listedNames.toLowerCase().indexOf(classToCheck) != -1 || listedNames == classToCheck){
			anchorLinks[x].className = anchorLinks[x].className.replace(" hidden","");
		}
	}
	
	
	// Resetting 36 months anchor link
	if (listedTenure.indexOf("+36") == -1 ){
		document.getElementById("anchor36").style.display = "none";
		document.getElementById("goTo12").style.padding = "10px 0 10px 0";
	} else {
		document.getElementById("anchor36").style.display = "block";		
		document.getElementById("goTo12").style.padding = "10px 0 0 0";
	}
			
} 

function FilterTheList(PlansList){
	if(FilterObj.pTenure != ""){
		DebugThis("Tenure is now " + FilterObj.pTenure);
		var temArr = [];		
		var tenureValue = FilterObj.pTenure.split("-");
		for(var x = 0; x < PlansList.length; x++){		
			if(PlansList[x].pTenure == tenureValue[0] || PlansList[x].pTenure == tenureValue[1] || PlansList[x].pTenure == tenureValue[2] ){			
				temArr[temArr.length] = PlansList[x];
			} 
		}
		PlansList = temArr;
	}	
	if(FilterObj.pMinutes != ""){
		DebugThis("Minutes = "+FilterObj.pMinutes);
		var temArr = [];
		for(var x = 0; x < PlansList.length; x++){		
			if(PlansList[x].pMinutes == FilterObj.pMinutes){				
				temArr[temArr.length] = PlansList[x];
			} 
		}
		PlansList = temArr;
	}	
	if(FilterObj.pPrice != ""){
		DebugThis("Price = "+FilterObj.pPrice);
		var temArr = [];
		var priceValue = FilterObj.pPrice.split("-");
		var LowerBound = parseFloat(priceValue[0]);
		var UpperBound = parseFloat(priceValue[1]);		
		for(var x = 0; x < PlansList.length; x++){	
			if(PlansList[x].pPrice >= LowerBound && PlansList[x].pPrice <= UpperBound){
				temArr[temArr.length] = PlansList[x];
			} 
		}
		PlansList = temArr;
	}
	if(FilterObj.pName != ""){
		DebugThis("Name = "+FilterObj.pName);
		var temArr = [];
		for(var x = 0; x < PlansList.length; x++){	
			if( PlansList[x].pName.toLowerCase().indexOf(FilterObj.pName) != -1 ){						
				temArr[temArr.length] = PlansList[x];
			} 
		}
		PlansList = temArr;
	}
	if(FilterObj.pTexts != ""){
		DebugThis("Texts = "+FilterObj.pTexts);
		var temArr = [];
		for(var x = 0; x < PlansList.length; x++){	
			if(PlansList[x].pTexts == FilterObj.pTexts){			
				temArr[temArr.length] = PlansList[x];
			} 
		}
		PlansList = temArr;
	}
	if(FilterObj.pBenefit != ""){
		DebugThis("Benefit = "+FilterObj.pBenefit);
		var temArr = [];
		for(var x = 0; x < PlansList.length; x++){	
			if(PlansList[x].pCategory == FilterObj.pBenefit){			
				temArr[temArr.length] = PlansList[x];
			} 
		}
		PlansList = temArr;
	}	
	if(FilterObj.pHandsetPrice != ""){
		DebugThis("HandsetPrice = "+FilterObj.pHandsetPrice);
		var temArr = [];
		for(var x = 0; x < PlansList.length; x++){	
			if(PlansList[x].pHandsetPrice == FilterObj.pHandsetPrice){			
				temArr[temArr.length] = PlansList[x];
			} 
		}
		PlansList = temArr;
	}
	if(FilterObj.pTopSeller != ""){
		DebugThis("TopSeller = " + FilterObj.pTopSeller);
		var temArr = [];
		for(var x = 0; x < PlansList.length; x++){	
			if(PlansList[x].pTopSeller == FilterObj.pTopSeller){			
				temArr[temArr.length] = PlansList[x];
			} 
		}
		PlansList = temArr;
	}
	
	svpPlansFiltered = PlansList;	
}

function SetUpTopSellerLayers(){
	document.getElementById("tabTopPlans").className = "selected";	
	document.getElementById("tabTopPlans").blur();
	document.getElementById("tabFindAPlan").className = ""; 				// selected or ""	
	document.getElementById("12monthNavDiv").className = "hidden";			// hidden a ""	
	document.getElementById("pantherInfo").className = "hidden"; 			// hidden a ""
	document.getElementById("wantPanther").className = "hidden";			// hidden a ""
	document.getElementById("FindAPlanNavDiv").className = "hidden";
	document.getElementById("TopPlansNavDiv").className = "";
	document.getElementById("filterDiv").className = "TopPlans";
	
	// If handSet isSelected check for Panther
	if( handsetId != "" && handsetId != "0" ){			
		if(document.getElementById("ancPanther").className.indexOf(" hidden") != -1){			
			document.getElementById("pantherInfo").className = "";
			document.getElementById("wantPanther").className = "";
			document.getElementById("filter_total_js").className = "hidden";
		} else {
			// Re-arrange anchor links
			var anchorLinks = getElementsByClassName("anchorLink", "LI", document.getElementById("TopPlansNavAnchorUL"))
			for(var x = 0; x < anchorLinks.length; x++ ){			
				if(anchorLinks[x].className.indexOf("panther") != -1){							
					anchorLinks[x].parentNode.insertBefore(anchorLinks[x], anchorLinks[0]);									
				}
			}
			// Re-arrange svp plan groups
			var plansGroups = getElementsByClassName("grouping", "DIV", document.getElementById("plans_container_js"))			
			for(var x = 0; x < plansGroups.length; x++ ){			
				if(plansGroups[x].className.indexOf("Panther") != -1){
					plansGroups[x].parentNode.insertBefore(plansGroups[x], plansGroups[0]);									
				}
			}			
		}			
	}
}

function SetUp18and24Layers(){
	document.getElementById("filterDiv").className = "FindAPlan";
	document.getElementById("tabFindAPlan").className = "selected";	
	document.getElementById("tabFindAPlan").blur();
	document.getElementById("tabTopPlans").className = ""; 					// selected or ""	
	document.getElementById("12monthNavDiv").className = "hidden";			// hidden or ""	
	document.getElementById("pantherInfo").className = "hidden"; 			// hidden or ""
	document.getElementById("wantPanther").className = "hidden";			// hidden or ""
	document.getElementById("filter_total_js").className = "";
	document.getElementById("FindAPlanNavDiv").className = "";
	document.getElementById("TopPlansNavDiv").className = "hidden";	
}

function SetUp12onlyLayers(){
	document.getElementById("filterDiv").className = "FindAPlan";
	document.getElementById("tabFindAPlan").className = "selected";	
	document.getElementById("tabFindAPlan").blur();
	document.getElementById("tabTopPlans").className = ""; 					// selected or ""	
	document.getElementById("12monthNavDiv").className = "";				// hidden or ""	
	document.getElementById("pantherInfo").className = "hidden"; 			// hidden or ""
	document.getElementById("wantPanther").className = "hidden";			// hidden or ""
	document.getElementById("filter_total_js").className = "";
	document.getElementById("FindAPlanNavDiv").className = "hidden";
	document.getElementById("TopPlansNavDiv").className = "";	
}

function TopSellers(){
	ResetTheFilter();
	ChangeFilter("TopSeller", "Yes");
	FilterTheList(svpPlansALL);
	SetMenuDisplay(svpPlansFiltered);
	DisplayPlans(svpPlansFiltered);	
	SetUpTopSellerLayers(); 	
	TrackingVariable = "";
}

function Filter18and24(){
	ResetTheFilter();
	ChangeFilter("Tenure", "18-24-36");
	FilterTheList(svpPlansALL);
	SetMenuDisplay(svpPlansFiltered);
	DisplayPlans(svpPlansFiltered);
	SetUp18and24Layers(); 
	TrackingVariable = "Filtered";
}

function Filter12only(){
	ResetTheFilter();
	ChangeFilter("Tenure", "12-12");
	FilterTheList(svpPlansALL);
	SetMenuDisplay(svpPlansFiltered);
	DisplayPlans(svpPlansFiltered);
	SetUp12onlyLayers();
}


function PlansWithFreeHandset(btnID){		
	var linkObj = document.getElementById(btnID)
	if(linkObj.className == "chkBox active" ){	
		FilterOn("HandsetPrice", defaultSettings.pHandsetPrice);
		linkObj.className = "chkBox";					
	} else {				
		FilterOn("HandsetPrice", "&pound;0.00");
		linkObj.className = "chkBox active";		
	}
	linkObj.href = 'javascript:PlansWithFreeHandset("freeSVPwithPhone");';
	linkObj.blur();	
}

function DisplayPlans(plansList){

	var HTMLToDisplay = "";
	var HTMLMsgDisplay = "";	
		
	for(var a = 0; a < Categories.length; a++){	
		var theList = [];
		for(var d = 0; d < plansList.length; d++ ){
		if( plansList[d].pCategory == Categories[a] ){
				theList[theList.length] = plansList[d] 	
			}
		}
		
		// Used for debugging
		//DebugThis(Categories[a] + " count = " + theList.length);
		if(theList.length > 0){
			HTMLToDisplay = HTMLToDisplay + GroupHTML(Categories[a]); 
			
			for(var j = 0; j < PlanPrices.length; j++){	
				var theInnerList = [];
				for(var x = 0; x < theList.length; x++ ){	
					if( removeSpaces(theList[x].pName.toLowerCase()).indexOf(Animals[a]+PlanPrices[j]) != -1 ){				
						theInnerList[theInnerList.length] = theList[x]											
					}
				}	
				
				// Used for debugging
				//DebugThis(Animals[a]+PlanPrices[j] + " count = " + theInnerList.length);				
				if(theInnerList.length > 0){
					if( handsetId != "" && handsetId != "0" ){
						HTMLToDisplay = HTMLToDisplay + HTML_topBit(Animals[a]+PlanPrices[j], theInnerList[0].pHandsetPrice);
					} else {
						HTMLToDisplay = HTMLToDisplay + HTML_topBit(Animals[a]+PlanPrices[j]);
					} 
					for(var x = 0; x < theInnerList.length; x++){
						HTMLToDisplay = HTMLToDisplay + planTemplate(theInnerList[x],Animals[a]) 	
					}
					HTMLToDisplay = HTMLToDisplay + HTML_btmBit();
				}
			}
			
			HTMLToDisplay = HTMLToDisplay + GroupHTML_btmBit(); 
										
		}
	}	
	
	if( plansList.length == 1 ){
		HTMLMsgDisplay = "<p>displaying <span class='orangeTxt'>1</span> plan:</p>"
	} else {
		HTMLMsgDisplay = "<p>displaying <span class='orangeTxt'>" + plansList.length + "</span> plans:</p>"
	}
			
	document.getElementById("filter_total_js").innerHTML = HTMLMsgDisplay;	
	document.getElementById('plans_container_js').innerHTML = HTMLToDisplay;
}

