	/*************************************************************************
	 * Ajax classes    
	 *************************************************************************/

	var ajaxHandlerName = 'WirelessSolutionHandler';
	var OperationTimeout = (60 * 1000 * 2);// 2 minute
	var loaderTimeout = (45 * 1000);// 45 sec
	var currentState;
	var revertState;
	var lastprepopId;
	
	//DataStore Objects
	var bundlesDataStore;
	var featuresDataStore;
	var ratePlansDataStore;
	var ratePlanCategoriesDataStore;
	var longDistanceDataStore;
	var cellPhonesListDataStore;
	var currentCellPhoneDetailsDataStore;
	var currentSubCellPhoneDetailsDataStore;	
	var currentBOGOPromotionDataStore;

	var reloadUrl = '/shopping/PrsShpWls_Solution_Builder.page'
	var errorPagePath = '/shopping/resources/error/server_error_redirect.jsp';
	var langAndRegionParam = '&lang='+language+'&region='+region;
	var promotionBlockUrl = '/shopping/jsp/pageblock_styles/Pricing/flexPricing_detail.jsp';
	var promotionBundleParameter = '&RESOURCENODE=MobileProduct'+langAndRegionParam;
	var timeoutRedirectUrl = '/home';


// BlackBerry Playbook
var standAloneSkus = new Array(); 
standAloneSkus = stand_alone_skus.split(",");


	var bbOnlyPlanSkus = ["QS40","QM40"];

	function GenericSolutionsBuilderComponent(id){
	}
	
	GenericSolutionsBuilderComponent.prototype = new BaseAjaxComponent();
		
	GenericSolutionsBuilderComponent.prototype.userError  = function(errorString, exception) {
		window.location.href = errorPagePath;
	}

	GenericSolutionsBuilderComponent.prototype.systemError  = function(errorString, exception) {
		if(exception && exception.message === "Error"){
			$(".warningTxtJS", "#warningPopupJs").html(ajaxComponentI18n.teamsiteBundles.session_expire_block);
		
			$.lightBox.showInPage("#warningPopupJs",{modal:true}, function(objLightBox) {
				//find "ok" button
				$(".btnDftAct", objLightBox).unbind('click').click(function() {
					$.lightBox.hide();
					window.location.href = reloadUrl;
					return false;			
				});
			});
		}else{
			window.location.href = errorPagePath;
		}
	}

	/***********************************************************************************************************************
	 * Main Ajax events
	 ***********************************************************************************************************************/
	
	function loadSession()
	{
		ajaxLoader("show","loadSolution");
		
		//Preload the catalog cache
		getDataStoreObject(dataStoreTypePreload,true);		
		
		WirelessSolutionStepsBuilderComponent.prototype.update = existingLogin;	
    	ajaxComponent('#WirelessSolutionSteps').callAjaxAction('loadSession');	
	}
	
	function existingLogin(data, html, newComponents)
	{
		WirelessSolutionStepsBuilderComponent.prototype.update = handleLoadMain;
	
		if(data.firstTime){
			ajaxLoader("hide","loadSolution");
	 		$.lightBox.showInPage("#newVsExistingLogin",{modal:true, colClassName:'col8'}, function(objLightBox){
	 			
	 			$(".btnLnkAlt", objLightBox).unbind('click').click(function() {
										$.lightBox.hide();	
										loadAction();
										return false;				
									});
	 			
	 		});	
 		}else{
 			loadAction();
 		}
	
	}		
	
	function loadAction()
	{
		ajaxLoader("show","loadSolution");

		var preSelectSmallImageUrl = "";
		var preSelectLargeImageUrl = "";
		var preSelectPhoneName = "";
		var preSelectCellPhoneCategory = "";
		var preSelectProductColourId = "";

		//Loading phone preselected
		if (!$.bell.isEmpty(preSelectCellPhoneSku))
		{
			var categoryDetailsList = getDataStoreObject(dataStoreTypeCellPhonesList,false);
			for (var idxCat in categoryDetailsList) {
				var dataDetailsList = getDataStoreObject(dataStoreTypeCellPhonesList,false)[idxCat];
				for (var idx in dataDetailsList) {
					var dataDetails = dataDetailsList[idx];	
					if(dataDetails.productSku == preSelectCellPhoneSku){
						preSelectCellPhoneCategory = idxCat;						
						break;
					}
				}
				if (!$.bell.isEmpty(preSelectCellPhoneCategory))
				{
					break;
				}				
			}
			
			var dataPhoneDetails = getCellDataStoreObject(dataStoreTypeCellPhoneDetails,preSelectCellPhoneSku,null,true);
			preSelectSmallImageUrl = dataPhoneDetails.smallImageUrl;
			preSelectLargeImageUrl = dataPhoneDetails.largeImageUrl;
			preSelectPhoneName = dataPhoneDetails.name;				
			
			if (!$.bell.isEmpty(preSelectCellPhoneSubSku) && !$.bell.isEmpty(dataPhoneDetails.colors))
			{
				for (var idxColor in dataPhoneDetails.colors) {
					var dataColor = dataPhoneDetails.colors[idxColor];
					if(dataColor.colourSubSku == preSelectCellPhoneSubSku){
						preSelectProductColourId = dataColor.productColourId;
						break;
					}
				}						
			}			
			
			//Loading the sub sku preselected
			if (!$.bell.isEmpty(preSelectCellPhoneSubSku))
			{
				var dataSubPhoneDetails = getCellDataStoreObject(dataStoreTypeSubCellPhoneDetails,preSelectCellPhoneSubSku,null,true);
				preSelectSmallImageUrl = dataSubPhoneDetails.smallImageUrl;
				preSelectLargeImageUrl = dataSubPhoneDetails.largeImageUrl;
			}			
		}

		var preSelectRatePlanPage = "";
		
		//Loading rate plan preselected
		if (!$.bell.isEmpty(preSelectRatePlanSku))
		{	
			var ratePlans = getDataStoreObject(dataStoreTypeRatePlans,false);
			for (var idxCat in ratePlans) {
				var pagerList = ratePlans[idxCat];	
				
				for (var idxPager in pagerList) {
					
					if(idxPager.indexOf("page_") != -1){
						var itemsList = pagerList[idxPager];
						
						for (var idxItem=0; idxItem <itemsList.length; idxItem ++) {
						
							var item = itemsList[idxItem];
							if(item.productSku == preSelectRatePlanSku){
								var lastIndex = idxPager.lastIndexOf("_");
								var idxPager = idxPager.substring(++lastIndex);
								
								preSelectRatePlanPage = idxPager;
								preSelectRatePlanCategorySku = idxCat;
								break;						
							}
						}
					}
					if (!$.bell.isEmpty(preSelectRatePlanPage))
					{
						break;
					}					
				}
				if (!$.bell.isEmpty(preSelectRatePlanPage))
				{
					break;
				}								
			}		
		}
	
		var preSelectBundlePage = "";
		
		//Loading bundle preselected
		if (!$.bell.isEmpty(preSelectAdditionalBundlesSku))
		{
			//Loading the bundle page from the selected bundle sku
			var bundlesMap = getDataStoreObject(dataStoreTypeBundles,false);
			var bundles = bundlesMap["bundles"];
			for (var idxCat in bundles) {
				var data = bundles[idxCat];	

				for (var idx in data) {
					var bundle = data[idx];	
					
					if(bundle.productSku == preSelectAdditionalBundlesSku[0])
					{
						preSelectBundlePage = idxCat;
						break;
					}
				}
				if (!$.bell.isEmpty(preSelectBundlePage))
				{
					break;
				}									
			}	
				
		}
		
		var preSelectBlundleElegible = false;
		if (!$.bell.isEmpty(preSelectOtherServices))
		{
			preSelectBlundleElegible = true;
		}		
		
		if(preSelectContractTermSku === prepaidTermSku){
			preSelectRatePlanCategorySku = prepaidRatePlansSku;
			var ratePlanDetails = getDataStoreObject(dataStoreTypeRatePlans, false);
			ratePlanDetails = ratePlanDetails[prepaidRatePlansSku];
			preSelectRatePlanSku = ratePlanDetails["ratePlanPagerList"][0].productSku;
		}

    	ajaxComponent('#WirelessSolutionSteps').callAjaxAction('mainLoadAction',{cellPhoneSku:preSelectCellPhoneSku,
    																				cellPhoneSubSku:preSelectCellPhoneSubSku,
    																				cellPhoneVariantSku:preSelectCellPhoneVariantSku,
    																				productColourId:preSelectProductColourId,
    																				contractTermSku:preSelectContractTermSku,
    																				smallImageUrl:preSelectSmallImageUrl,
    																				largeImageUrl:preSelectLargeImageUrl,
    																				phoneName:preSelectPhoneName,
    																				cellPhoneCategory:preSelectCellPhoneCategory,
    																				ratePlanSku:preSelectRatePlanSku,
    																				ratePlanPage:preSelectRatePlanPage,
    																				ratePlanCategorySku:preSelectRatePlanCategorySku,
    																				bundlePage:preSelectBundlePage,
    																				additionalAccessoriesSku:preSelectAdditionalAccessoriesSku,
    																				additionalFeaturesSku:preSelectAdditionalFeaturesSku,
    																				additionalBundlesSku:preSelectAdditionalBundlesSku,
    																				additionalLongDistancesSku:preSelectAdditionalLongDistancesSku,
    																				ratePlanBonusesSku:preSelectRatePlanBonusesSku,
    																				otherServices:preSelectOtherServices,
    																				blundleElegible:preSelectBlundleElegible,
    																				actionJS:preuid});
    																				
    	
		var $chooseCellPhoneStepObj = $("#ChooseCellPhoneStep"); 
		var $bundlesStepObj = $("#BundlesStep"); 	
    	
		// bind select smartphone/phone/mobile toggle events
		$(".cTabs li", $chooseCellPhoneStepObj).unbind('click').click(function() {
			var $this = $(this);
			if (!$this.hasClass("active")) {
				ajaxLoader("show","switchPhone");
				$.bell.setElementActive($this, "#ChooseCellPhoneStep .pkgToggleItemJs", "active", function() {
					var category = $this.attr("rel");
					chooseCellPhoneStepBuilder(category);

					if ($chooseCellPhoneStepObj.hasClass("hide")) {
						$chooseCellPhoneStepObj.removeClass("hide");
					}
						
					// initialize the scroller
					$chooseCellPhoneStepObj.scroller({fillSpace:false, toggle: true, itemsContainer: "#mapChoosePhones"});

				});	
				ajaxLoader("hide","switchPhone");							
			}
			return false;
		});  

	}
	
	/***********************************************************************************************************************
	 * PhoneSolutionsBuilderComponent Ajax events
	 ***********************************************************************************************************************/

	PhoneSolutionsBuilderComponent.prototype = new GenericSolutionsBuilderComponent();

	PhoneSolutionsBuilderComponent.prototype.initialize = function() 
	{
		this.ajaxHandlerName  = ajaxHandlerName;
	}

	function PhoneSolutionsBuilderComponent(id) 
	{
		this.timeout = OperationTimeout;
		this.persistenceKey = 'WirelessSolutionBuilderComponentKey';
		BaseAjaxComponent.apply(this, arguments);
	}

	PhoneSolutionsBuilderComponent.prototype.update = function(data, html, newComponents) 
	{
		var $phoneSolutionsObj = $("#PhoneSolutions");
		var $mapPhoneSolutionsObj = $("#mapPhoneSolutions");
		if($mapPhoneSolutionsObj.length)
		{
			$mapPhoneSolutionsObj.remove();
		}
			
		if (!$.bell.isEmpty(data))
		{
			if (!$.bell.isEmpty(data["solutionsList"]))
			{
				$.bell.map("#templatePhoneSolutions-tpl-solutionId", data["solutionsList"], "mapPhoneSolutions", function($mapObj) {
									
					// bind select events
					$(".itemGroup a:not('.bt_remove')", $mapObj).click(function() {
						var relSolutionId = $(this).attr("rel");
						selectSolution(relSolutionId);
						loadSolution(relSolutionId);
						tracker(ajaxComponentI18n.teamsiteBundles.choose_cell_phone_step_title_label,'0');	
						return false;
					});
										
					// Bind remove events
					$(".col3", $mapObj).each(function() {
						$(".bt_remove",$(this)).unbind('click').click(function() {
							var solutionId = $(this).attr("rel");	
							
							//show a pop up confirmation before removing it
							var $yesnoPopupJsObj = $("#yesnoPopupJs");
							$(".lightBoxTitleJs", $yesnoPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.remove_popup_title_label);
							$(".yesnoTxtJS", $yesnoPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.remove_popup_block);						
							$(".btnDftAct", $yesnoPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.confirm_label);
							$(".btnAltAct", $yesnoPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.cancel_label);
							$.pageRender($yesnoPopupJsObj, "lightBox");
		
							$.lightBox.showInPage($yesnoPopupJsObj,{modal:false}, function(objLightBox) {
								//find "yes" button
								$(".btnDftAct", objLightBox).unbind('click').click(function() {
									$.lightBox.hide();
									phoneSolutionRemove(solutionId);
									return false;					
								});
							});
							return false;
						});
					});
					
					
					// the itemsContainer of the scroller must be defined and have the refLine class or position relative css property
					$mapObj.addClass("refLine bord3");			
					
			   		$mapObj.children().each(function(i) {
			   			if (i!=0 && (i+1)%3==0) {
			   				$(this).addClass("colLast");
			   			}
			   		});
			   		
			   		//Change the icon for the "is ready" solution
					$.each(data["solutionsList"], function(i, value) {
						
						if(value.valid){
							$("#solutionReady-" + value.solutionId).addClass("ic_ready").removeClass("ic_error");					
						}else{
							$("#solutionReady-" + value.solutionId).addClass("ic_error").removeClass("ic_ready");											
						}
											
					});   		
					
					// Scrollers render
					$phoneSolutionsObj.scroller({
						fillSpace:false,
						fillSpacePaddingRight: $.getPageLang()==="en"?155:200,
						showNavigation: false,
						toggle: false,
						itemsContainer: "#mapPhoneSolutions"
					});

				});
						
			}  
			
			//Keep the active solution
			if (!$.bell.isEmpty(data["currentState"]))
			{
				// Set active
				selectSolution(data["currentState"].solutionId);
				currentState = data["currentState"];
			}
			else
			{
				resetForm();
			}			
										
    	}
    	
    	//Enable or disable the add phone events
		if(data["solutionsList"].length >= 5){
			$(".cFoot .btnDftAct", $phoneSolutionsObj).addClass("btnDeactive");	
			// bind add phone events
			$(".cFoot .btnDftAct", $phoneSolutionsObj).unbind('click').click(function() {
				return false;
			});											
		}
		else
		{
			$(".cFoot .btnDftAct", $phoneSolutionsObj).removeClass("btnDeactive");
			// bind add phone events
			$(".cFoot .btnDftAct", $phoneSolutionsObj).unbind('click').click(function() {
				ajaxLoader("show","addPhone");
				
				resetForm();
				currentState = null;
				phoneSolutionAdd();
				renderChooseCellPhone();			
				planCategoriesStepBuilder();
				ajaxLoader("hide","addPhone");	
				return false;
			});						
		}    	
    	
	
    	ajaxLoader("hide","phoneSolutionsBuilder");	
		
	}	
	
	function phoneSolutionsBuilder()
	{
		ajaxLoader("show","phoneSolutionsBuilder");	
    	ajaxComponent('#PhoneSolutions').callAjaxAction('phoneSolutionsBuilder',{});	
	}
	
	function phoneSolutionAdd()
	{
		ajaxLoader("show","phoneSolutionsBuilder");	
    	ajaxComponent('#PhoneSolutions').callAjaxAction('phoneSolutionAdd',{});	
	}
	
	function phoneSolutionRemove(solutionId)
	{
		ajaxLoader("show","phoneSolutionsBuilder");	
    	ajaxComponent('#PhoneSolutions').callAjaxAction('phoneSolutionRemove',{solutionId:solutionId});							
	}
	
	function selectSolution(solutionId)
	{
		//Highlight the active solution
		$(".unit", $("#mapPhoneSolutions")).each(function() {

			var $this = $(this);
			var unitRel = $this.attr("rel");

			if ($this.hasClass("active") && unitRel != solutionId) {
				$this.removeClass("active");	
			}
			
			if(unitRel == solutionId){
				$this.addClass("active");
			}
		});			
		
	}			

	/***********************************************************************************************************************
	 * ChooseCellPhoneStep events
	 ***********************************************************************************************************************/

	function chooseCellPhoneStepBuilder(category) 
	{
		var $chooseCellPhoneStepObj = $("#ChooseCellPhoneStep");
		var $phoneSolutionsObj = $("#PhoneSolutions");
				
		var $mapChoosePhonesObj = $("#mapChoosePhones");		
		if($mapChoosePhonesObj.length)
		{
			$mapChoosePhonesObj.remove(); 
		}
				
		var dataPhoneList;
		if(!$.bell.isEmpty(currentState) && !$.bell.isEmpty(currentState.parentSolutionIdLinked) && !$.bell.isEmpty(currentState.bogoRewardFlexPricingIds)){
		
			var isResetNeeded = false;
			if($.bell.isEmpty(currentBOGOPromotionDataStore) || !bogoFlexPricingsIdentical(currentBOGOPromotionDataStore["bogoRewardFlexPricingIds"], currentState.bogoRewardFlexPricingIds)){
				isResetNeeded = true;
			}
		
			dataPhoneList = getCellDataStoreObject(dataStoreTypeBOGOPromotion,0,currentState,isResetNeeded);		
			dataPhoneList = dataPhoneList["cellPhonesMap"];
			$chooseCellPhoneStepObj.attr("rel","bogolist");
		}else{
			dataPhoneList = getDataStoreObject(dataStoreTypeCellPhonesList,false);
			$chooseCellPhoneStepObj.removeAttr("rel");
		}
		
		//If category is empty, put one by default that contains cell phones
		if ($.bell.isEmpty(category))
		{
			for (var idxCat in dataPhoneList) {
				var dataDetailsList = dataPhoneList[idxCat];
				if (!$.bell.isEmpty(dataDetailsList))
				{
					category = idxCat;
					break;
				}				
			}		
		}		
		
		dataPhoneList = dataPhoneList[category];
		if (!$.bell.isEmpty(dataPhoneList))
		{		
			var $chooseCell = $("#templateChooseCellPhoneStep-tpl-productSku");
			var $price = $chooseCell.find(".priceTag .superscript");
			$price.before($price.text()).remove();
			
    		$.bell.map($chooseCell, dataPhoneList, "mapChoosePhones", function($mapObj) {
    				//on rendering, grey out none compatible phones if a category is already selected
    				var category = $("input[id*=itemPlanCategoriesStep_]:checked", $("#mapPlanCategoriesStep")).val();
    				dimIncompatiblePhones(category);
    				
    				//make all plans clickable
		    		togglePlanSelection(true);
    			
				
				// bind select button event
				$(".itemGroup a", $mapObj).each(function() {
					$(this).unbind('click').click(function() {
						var $this = $(this);
						var sku = $this.attr("rel");		
						var category = $("input[id*=itemPlanCategoriesStep_]:checked", $("#mapPlanCategoriesStep")).val();
						if(currentState == null){
							return false;
						}
						
						var isValid = false;
						//Get the selected cell phone details
						ajaxLoader("show","itemChooseCellPhoneStep");	
						var dataDetails = getCellDataStoreObject(dataStoreTypeCellPhoneDetails,sku,currentState,true);
						
						if (!$.bell.isEmpty(currentState.ratePlanCategorySku))
						{
							//Check if the previous plan category exist for this phone												
							for (var idxPlan in dataDetails.ratePlanCategoriesAvailable) {
								var valuePlan = dataDetails.ratePlanCategoriesAvailable[idxPlan];	
								if(valuePlan == currentState.ratePlanCategorySku){
									isValid = true;
								}
							}
						}else{
							isValid = true;
						}
						
						if (isValid)
						{
							revertState = JSON.clone(currentState);
							
							currentState.cellPhoneSku = sku;
							currentState.additionalAccessoriesSku = [];	
							currentState.additionalFeaturesSku = [];	
							currentState.additionalBundlesSku = [];
							currentState.bundlePage = null;
							currentState.additionalLongDistancesSku = [];	
							currentState.smallImageUrl = dataDetails.smallImageUrl;
							currentState.largeImageUrl = dataDetails.largeImageUrl;
							currentState.phoneName = dataDetails.name;	
							currentState.cellPhoneCategory = category;
							currentState.prepopId = null;
							currentState.ratePlanCategorySku = category;
							
							/*****************************************************
							 * CR10908  -- Start
							 *****************************************************/
							var  boolContracttermavailability = false ;
							//for (var idxPlan in dataDetails.ratePlanCategoriesAvailable) {
							//	var valuePlan = dataDetails.ratePlanCategoriesAvailable[idxPlan];	
							// 	var termsList = dataDetails.ratePlanCategoriesTermsAvailability[valuePlan];
					   		//	if(!$.bell.isEmpty(termsList) && termsList.indexOf(defaultTerm) > -1 ){
					   		//		boolContracttermavailability = true ;
					   			//	break ; 
					   		//	}
							//}// end for 
							if (!$.bell.isEmpty(dataDetails["terms"])) { 
								for(var idx in dataDetails["terms"]){
									var currentTerm = dataDetails["terms"][idx];
									if ( !$.bell.isEmpty(currentTerm) && (defaultTerm == currentTerm.productSku) ) { 
										boolContracttermavailability = true ;
										break ; 
									}//end if 
								}//end for
							}//end if 
							if ( false == boolContracttermavailability) 
								//default to the first available contract term.
								currentState.contractTermSku = dataDetails["terms"][0].productSku;
							else
								// if default term "term36m" is availabe to the selected cell phone.
								currentState.contractTermSku = defaultTerm;

							/*****************************************************
							 * CR10908  -- end
							 *****************************************************/


							if (!$.bell.isEmpty(dataDetails["colors"]) && dataDetails["colors"].length == 1)
							{	
								currentState.cellPhoneSubSku = dataDetails["colors"][0].colourSubSku;
								currentState.productColourId = dataDetails["colors"][0].productColourId;
							}
							else
							{
								currentState.cellPhoneSubSku = null;
								currentState.productColourId = null;
							}						
														
							if(currentState.cellPhoneSku && !currentState.ratePlanSku){
								currentState.ratePlanPage = null;
							}else if(currentState.ratePlanCategorySku === prepaidRatePlansSku){
								currentState.contractTermSku = prepaidTermSku;
								currentState.cellPhoneVariantSku = dataDetails.prepaidSku;
								var dataDetailPrepaid = getCellDataStoreObject('', dataDetails.prepaidSku,currentState,true);
								updateColorSku(dataDetailPrepaid);
							}
												
							ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);						
							$chooseCellPhoneStepObj.addClass("hide");
							cellPhoneDetailBuilder();
							if(!$.bell.isEmpty(currentState.ratePlanCategorySku)){
								LoadSteps();
							}
							phoneSolutionsBuilder();
							tracker(ajaxComponentI18n.teamsiteBundles.choose_cell_phone_step_title_label,'0');							
						}
						else
						{
							var $returnToPreviousCellPopupObj = $("#yesnoPopupWithNoHandlingJs");	
							$(".lightBoxTitleJs", $returnToPreviousCellPopupObj).html(ajaxComponentI18n.teamsiteBundles.warning_label);			
							$(".yesnoTxtJS", $returnToPreviousCellPopupObj).html(ajaxComponentI18n.teamsiteBundles.change_handset_warning_block);
							$.pageRender($returnToPreviousCellPopupObj, "lightBox");			
													
							$.lightBox.showInPage($returnToPreviousCellPopupObj,{modal:true}, function(objLightBox) {
								//find "yes" button
								$(".yesJs", objLightBox).unbind('click').click(function() {
									$.lightBox.hide();
									resetForm();	
									
									revertState = JSON.clone(currentState);
												
									currentState.cellPhoneSku = sku;
									currentState.additionalAccessoriesSku = [];	
									currentState.additionalFeaturesSku = [];	
									currentState.additionalBundlesSku = [];
									currentState.bundlePage = null;
									currentState.additionalLongDistancesSku = [];	
									currentState.smallImageUrl = dataDetails.smallImageUrl;
									currentState.largeImageUrl = dataDetails.largeImageUrl;
									currentState.phoneName = dataDetails.name;	
									currentState.cellPhoneCategory = category;
									currentState.contractTermSku = defaultTerm;
									currentState.prepopId = null;
									currentState.cellPhoneVariantSku = null;
									currentState.ratePlanSku = null;
									currentState.ratePlanCategorySku = null;
									
									if (!$.bell.isEmpty(dataDetails["colors"]) && dataDetails["colors"].length == 1)
									{	
										currentState.cellPhoneSubSku = dataDetails["colors"][0].colourSubSku;
										currentState.productColourId = dataDetails["colors"][0].productColourId;
									}
									else
									{
										currentState.cellPhoneSubSku = null;
										currentState.productColourId = null;
									}									
														
									ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);						
									$chooseCellPhoneStepObj.addClass("hide");							
									cellPhoneDetailBuilder();
									phoneSolutionsBuilder();
									planCategoriesStepBuilder();
								});
								
								//find "no" button
								$(".noJs", objLightBox).unbind('click').click(function() {
									$chooseCellPhoneStepObj.addClass("hide");
									handleLoad(currentState);
									$.lightBox.hide();					
								});
								
							});
							
						}
						ajaxLoader("hide","itemChooseCellPhoneStep");
						return false;							
					});
					
					$(".promoFlagJs", $mapObj).each(function() {
						var src = $(this).attr("src");
						if(src === ""){
							$(this).hide();
						}					
					});							
					
				});
				
				//Put the number of phone at the top of the scroller
				var itemsLabel = ajaxComponentI18n.teamsiteBundles.choose_cell_phone_step_items_label;
				$(".itemsCountJS",$chooseCellPhoneStepObj).html("("+dataPhoneList.length+" "+itemsLabel+")");
	
		   		$mapObj.children().each(function(i) {
		   			if (i!=0 && (i+1)%3==0) {
		   				$(this).addClass("colLast");
		   			}
		   		});
	
				// the itemsContainer of the scroller must be defined and have the refLine class or position relative css property
				$mapObj.addClass("refLine bord3"); 

    		});    	
   		   					
    	}
    	else
    	{
    		//Put the number of phone at the top of the scroller when it is empty
			var itemsLabel = ajaxComponentI18n.teamsiteBundles.choose_cell_phone_step_items_label;
			$(".itemsCountJS",$chooseCellPhoneStepObj).html("(0 "+itemsLabel+")");    	
    	}		
	}
	
	function dimIncompatiblePhones(currentCategory){
		$("div.col3",$("#mapChoosePhones")).each(function(){
			var $this = $(this);
			$this.removeClass("dim");
			if (currentCategory){
				var classCheck = currentCategory+"Js";
				if(!$this.hasClass(classCheck)){
					$this.addClass("dim");
				}
			}
 		});
	}

	
	/***********************************************************************************************************************
	 * CellPhoneDetailsBuilder events
	 ***********************************************************************************************************************/

	function cellPhoneDetailBuilder()
	{
		ajaxLoader("show","cellPhoneDetailBuilder");
	
        var $cellPhoneDetailsStepObj = $("#CellPhoneDetailsStep");
		//Get the selected phone details and do a clone of it
		var productSku = currentState.cellPhoneSku;	
		
		var resetPhoneData;
		if(!$.bell.isEmpty(currentCellPhoneDetailsDataStore) && currentCellPhoneDetailsDataStore.cellPhoneSku == productSku){
			resetPhoneData = false;
		}
		else{
			resetPhoneData = true;
		}		

		var dataDetails = JSON.clone(getCellDataStoreObject(dataStoreTypeCellPhoneDetails,productSku,currentState,resetPhoneData));

		//If sub sku exist, get the some details of this sub sku. We keep the description from the main sku.
		if (!$.bell.isEmpty(currentState.cellPhoneSubSku)){
			var resetSubPhoneData;
			if(!$.bell.isEmpty(currentSubCellPhoneDetailsDataStore) && currentSubCellPhoneDetailsDataStore.cellPhoneSubSku == currentState.cellPhoneSubSku){
				resetSubPhoneData = false;
			}
			else{
				resetSubPhoneData = true;
			}					
			var dataSubPhoneDetails = getCellDataStoreObject(dataStoreTypeSubCellPhoneDetails,currentState.cellPhoneSubSku,currentState,resetSubPhoneData);
			if(currentState.contractTermSku != grabAndGoTermSku && currentState.contractTermSku != prepaidTermSku) {
				//Catalog need to be changed
				//dataDetails.terms = dataSubPhoneDetails.terms;
			}
			dataDetails.imagesJspUrl = dataSubPhoneDetails.imagesJspUrl;
			dataDetails.productSku = dataSubPhoneDetails.productSku;										
			dataDetails.largeImageUrl = dataSubPhoneDetails.largeImageUrl;										
			dataDetails.smallImageUrl = dataSubPhoneDetails.smallImageUrl;										
		}
		
		//If phone variant exist, we get the colors and memories from it.
		if(!$.bell.isEmpty(currentState.cellPhoneVariantSku))
		{
			var dataVariantPhoneDetails = getCellDataStoreObject('',currentState.cellPhoneVariantSku,currentState,true);
			dataDetails.memories = dataVariantPhoneDetails.memories;	
			dataDetails.colors = dataVariantPhoneDetails.colors;
		}		
	
		var $mapDetailCellPhoneObj = $("#mapDetailCellPhone");
		if($mapDetailCellPhoneObj.length)
		{
			$mapDetailCellPhoneObj.remove(); 
		}

		if (!$.bell.isEmpty(dataDetails))
		{
			var tmpList = [];
			tmpList.push(dataDetails);
			
			// IE cuFon bug fix
			var $cellDetails = $("#templateCellPhoneDetailsStep-tpl-productSku");
			var originalText = $("cufontext", $cellDetails).text();
			
			if (originalText!=="") {
				$cellDetails.find("h2").empty().html(originalText);
			}
			
    		$.bell.map("#templateCellPhoneDetailsStep-tpl-productSku", tmpList, "mapDetailCellPhone", function($mapObj) {

				// Carousel handling
				var $carouselMedia = $(".carouselMedia", $mapObj);
				var htmlImg = "";
				var imgCounter = 0;
				
				// CR10899 Incorrect display of the Device images in IE
				// also fix image navigation toggler incorrect display
				// replacing "for (var idx in dataDetails["imagesJspUrl"]) {"
				for (imgCounter=0;imgCounter<dataDetails["imagesJspUrl"].length;imgCounter++) {
					var value = dataDetails["imagesJspUrl"][imgCounter];					
					htmlImg += "<img id='picItem_"+(imgCounter+1)+"' src='"+value+"' height='350' width='222' \/>";
					//imgCounter++;
				};
				$carouselMedia.empty().append(htmlImg);
				
				var $carouselNav = $(".carouselNav", $mapObj);
				var htmlNav = "";
				var active = "active";
				
				for (var cpt=0;cpt<imgCounter;cpt++) {
					if (cpt > 0) { active = ""; }
					// CR11307 use image thumbnails for switching between multiple images
					htmlNav += "<a href='\u0023picItem_"+(cpt+1)+"' title='' class='"+active+"'><img src='"+dataDetails["imagesJspUrl"][cpt]+"'><span>"+(cpt+1)+"</span></a>";	
				}
				$carouselNav.empty().append(htmlNav);
				
				if (!$.bell.isEmpty(dataDetails["colors"]) && dataDetails["colors"].length > 1)
				{
					// Color handling
					var html = $mapObj.html();
					$mapObj.html(html.replace(/-colorindex/gi,"-tpl-colourSubSku"));
					$("#colors-template-tpl-colourSubSku").addClass("htmlTemplate");
					if(!$.bell.isEmpty(currentState) && $.bell.isEmpty(currentState.cellPhoneSubSku)){							
						currentState.cellPhoneSubSku = dataDetails["colors"][0].colourSubSku;
						currentState.productColourId = dataDetails["colors"][0].productColourId;
					}
			
					$.bell.map("#colors-template-tpl-colourSubSku", dataDetails["colors"], function(o) {
					
						//Check the color selected
						$("#colorElement-"+dataDetails.productSku).attr("checked","checked");					
					
						//Bind the color selection events
				   		$("input[id*=colorElement-]",o).each(function(i) {
				   			var $this = $(this);
				   			var value = $this.val();
				   			if(value == currentState.productColourId){
								$this.attr("checked", true);
							}
							
							$this.unbind('click').click(function() {
								var $this = $(this);
								revertState = JSON.clone(currentState);
								currentState.productColourId = $this.val();
								currentState.cellPhoneSubSku = $this.attr("relSubSku");
								
								ajaxLoader("show","colorChanger");
								window.colorChangerTimer = setTimeout(function() {
									//Get the new images for this sub sku
									var dataSubPhoneDetails = getCellDataStoreObject(dataStoreTypeSubCellPhoneDetails,currentState.cellPhoneSubSku,currentState,true);
									currentState.smallImageUrl = dataSubPhoneDetails.smallImageUrl;
									currentState.largeImageUrl = dataSubPhoneDetails.largeImageUrl;														
									
									ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);
									cellPhoneDetailBuilder();
									phoneSolutionsBuilder();
									tracker(ajaxComponentI18n.teamsiteBundles.choose_cell_phone_step_title_label,'0');
											
									ajaxLoader("hide","colorChanger");	
									clearTimeout(window.colorChangerTimer);
								},1);									

					   		});
				   		});
											
					});
					
					$(".customizeProduct .fRadio", $cellPhoneDetailsStepObj).show();
				}
				else
				{
					$(".customizeProduct .fRadio", $cellPhoneDetailsStepObj).hide();
				}
				
				if (!$.bell.isEmpty(dataDetails["memories"]))
				{				
					// Memory
					var $memorySelect = $("#select-memory-0");
					$.bell.fillDropDown($memorySelect, dataDetails["memories"], "productSku", "name", function(){

						//Check the memory selected
						$memorySelect.val(currentState.cellPhoneSku);

						//Bind the change events			
						$memorySelect.change(function() {
							$this = $(this);
							revertState = JSON.clone(currentState);
							currentState.cellPhoneSku = $this.val();	
							
							ajaxLoader("show","memoryChanger");
							window.memoryChangerTimer = setTimeout(function() {							
								var dataPhoneDetails = getCellDataStoreObject(dataStoreTypeCellPhoneDetails,currentState.cellPhoneSku,currentState,true);
								currentState.smallImageUrl = dataPhoneDetails.smallImageUrl;
								currentState.largeImageUrl = dataPhoneDetails.largeImageUrl;
								currentState.phoneName = dataPhoneDetails.name;	
								updateColorSku(dataPhoneDetails);		
								ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);
								cellPhoneDetailBuilder();
								phoneSolutionsBuilder();
								tracker(ajaxComponentI18n.teamsiteBundles.choose_cell_phone_step_title_label,'0');
								
								ajaxLoader("hide","memoryChanger");	
								clearTimeout(window.memoryChangerTimer);
							},1);									
						});
						
						$(".memoryJs", $mapObj).show();
					});
				}
				else
				{
					$(".memoryJs", $mapObj).hide();
				}

				if (!$.bell.isEmpty(dataDetails["languages"]))
				{				
					// Language
					var $languageSelect = $("#select-language-0");
					$.bell.fillDropDown($languageSelect, dataDetails["languages"], "productSku", "name", function(){
					
						//Check the language selected
						$languageSelect.val(currentState.cellPhoneSku);
								
						//Bind the change events		
						$languageSelect.change(function() {
							revertState = JSON.clone(currentState);
							currentState.cellPhoneSku = $(this).val();				
							
							ajaxLoader("show","languageChanger");
							window.languageChangerTimer = setTimeout(function() {							
								var dataPhoneDetails = getCellDataStoreObject(dataStoreTypeCellPhoneDetails,currentState.cellPhoneSku,currentState,true);
								currentState.smallImageUrl = dataPhoneDetails.smallImageUrl;
								currentState.largeImageUrl = dataPhoneDetails.largeImageUrl;
								currentState.phoneName = dataPhoneDetails.name;	
								
								updateColorSku(dataPhoneDetails);						
								
								ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);
								cellPhoneDetailBuilder();
								phoneSolutionsBuilder();
								tracker(ajaxComponentI18n.teamsiteBundles.choose_cell_phone_step_title_label,'0');
								
								ajaxLoader("hide","languageChanger");	
								clearTimeout(window.languageChangerTimer);
							},1);								
						});
						
						$(".languageJs", $mapObj).show();
					});
				}
				else
				{
					$(".languageJs", $mapObj).hide();
				}
				
				if (!$.bell.isEmpty(dataDetails["terms"]))
				{
					// Contract
					var $contractSelect = $("#select-contract-0");
					//Don't show grab and go if a rateplan is already selected
					var finalTerms = [];
					// get Terms List for Rate Plan 
					var termsList = null;
					var loadTerms = false;	
					if(!$.bell.isEmpty(currentState.ratePlanSku)){
						for(var idx in dataDetails["terms"]){
							var currentTerm = dataDetails["terms"][idx];
							if(grabAndGoTermSku != currentTerm.productSku){
								// if Rate Plan is prepaid , the terms should be as is .
								if(!$.bell.isEmpty(termsList)) {
									if(termsList.indexOf(currentTerm.productSku) > -1) {
							   		 	if(currentTerm.productSku){
							   		 		finalTerms.push(currentTerm);
							   		 	}
									}
								}
								else {
									if(currentTerm.productSku){						        	
							   			finalTerms.push(currentTerm);
							   		}
								}
							}
						}
					}else{
						finalTerms = JSON.clone(dataDetails["terms"]);
					}
					
					$.bell.fillDropDown($contractSelect, finalTerms, "productSku", "name", defaultTerm, function(){
					
						if(!$.bell.isEmpty(currentState.contractTermSku)){
							//Check the term selected
							$contractSelect.val(currentState.contractTermSku);
						}	

						//load prepop promo
						if($contractSelect.val() !== prepaidTermSku){
							prepopPromoBuilder($contractSelect.val());
						}
						//Change the price label according to the selected term
						$(".contractLabelJs", $mapObj).text($(":selected", $contractSelect).text());
						$(".priceTag", $mapObj).text(finalTerms[$contractSelect.attr("selectedIndex")]["detailedPrice"]);
						$.bell.page.frontEnd.pricingFormats($mapObj);

						//Bind the change events
						$contractSelect.change(function() {
							var $this = $(this);
							revertState = JSON.clone(currentState);
							
							ajaxLoader("show","contractChanger");
							window.contractChangerTimer = setTimeout(function() {							
								var refreshSteps = false;
								if($this.val() == grabAndGoTermSku || $this.val() == prepaidTermSku)
								{
									var dataPhoneDetails = getCellDataStoreObject(dataStoreTypeCellPhoneDetails,currentState.cellPhoneSku,currentState,false);
									if($this.val() == grabAndGoTermSku)
									{
										currentState.cellPhoneVariantSku = dataPhoneDetails.grabAndGoSku;
										//if grab and go...reset everything except accessories and phone
										currentState.ratePlanSku = null;
										prepopPromoBuilder($this.val());
									}							
								
									if($this.val() == prepaidTermSku)
									{
										currentState.cellPhoneVariantSku = dataPhoneDetails.prepaidSku;
										//if grab and go...set rateplan category to prepaid and clear data except accessories
										currentState.ratePlanCategorySku = prepaidRatePlansSku;
										//force preselect of the first(and only) available prepaid plan
										var ratePlanDetails = getDataStoreObject(dataStoreTypeRatePlans, false);
										ratePlanDetails = ratePlanDetails[prepaidRatePlansSku];
										currentState.ratePlanSku = ratePlanDetails["ratePlanPagerList"][0].productSku;							
									}
									
									currentState.additionalFeaturesSku = [];	
									currentState.additionalBundlesSku = [];
									currentState.ratePlanBonusesSku = [];							
									currentState.ratePlanPage = null;
									
									var dataVariantPhoneDetails = getCellDataStoreObject('',currentState.cellPhoneVariantSku,currentState,true);
									updateColorSku(dataVariantPhoneDetails);						
									
									refreshSteps = true;
								}
								else
								{
									if(currentState.contractTermSku == grabAndGoTermSku || currentState.contractTermSku == prepaidTermSku)
									{
										currentState.ratePlanCategorySku = null;
										currentState.ratePlanSku = null;
										refreshSteps = true;
									}						
									currentState.cellPhoneVariantSku = null;
			
									var dataPhoneDetails = getCellDataStoreObject('',currentState.cellPhoneSku,currentState,true);
									updateColorSku(dataPhoneDetails);
		
									prepopPromoBuilder($this.val());
								}
								
								currentState.contractTermSku = $this.val();
								
								showHidePricingDetails(dataPhoneDetails["terms"]);
								
								if(refreshSteps){
									resetForm();
									LoadSteps();
								}
								
								ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);						
								
								var promoUrl = promotionBlockUrl+"?"+flexPricingSkuParameter+"="+currentState.cellPhoneSku+"&"+flexPricingTermParameter+"="+currentState.contractTermSku+getBogoFlexIdsParams(currentState)+promotionBundleParameter;
								$.toggleShowHide.update({
									linkElement:$("#promoLink-"+currentState.cellPhoneSku),
									ajax:true,
									url:promoUrl
								});
								phoneSolutionsBuilder();
								cellPhoneDetailBuilder();
								if(currentState.ratePlanCategorySku != prepaidRatePlansSku && currentState.ratePlanCategorySku != grabAndGoTermSku){ 
										var $ratePlanObj = $("#mapRatePlansStep");								
										if($ratePlanObj.length) {
											$ratePlanObj.children().each(function(i) {
					                            var $this = $(this);
									   			var ratePlansku = $("input:first",$this).val();
									   			var termsList = currentCellPhoneDetailsDataStore.ratePlanTermsAvailability[ratePlansku];
									   			if(!$.bell.isEmpty(termsList) && termsList.indexOf(currentState.contractTermSku) > -1 ){					
													$("div:first",$this).removeClass("capDisabled");
													$this.find("input").each(function(){
													    var $this = $(this);
													    $this.attr("disabled", false); 
								    				});						
					   							}else{
					   			    				$("div:first",$this).addClass("capDisabled");
					   			    				$this.find("input").each(function(){
														var $this = $(this);
														$this.attr("disabled", true); 
														$this.attr("checked", false);
								    				});
							   					}
									   		});	
								   		}
								   		
										var $ratePlanCategoriesObj = $("#mapPlanCategoriesStep");								
										if($ratePlanCategoriesObj.length) {
											$ratePlanCategoriesObj.children().each(function(i) {
					                            var $this = $(this);
									   			var ratePlanCategorysku = $("input:first",$this).val();
									   			var termsList = currentCellPhoneDetailsDataStore.ratePlanCategoriesTermsAvailability[ratePlanCategorysku];
									   			if(!$.bell.isEmpty(termsList) && termsList.indexOf(currentState.contractTermSku) > -1 ){					
													$("div:first",$this).removeClass("capDisabled");
													$this.find("input").each(function(){
													    var $this = $(this);
													    $this.attr("disabled", false); 
								    				});						
					   							}else{
					   			    				$("div:first",$this).addClass("capDisabled");
					   			    				$this.find("input").each(function(){
														var $this = $(this);
														$this.attr("disabled", true); 
														$this.attr("checked", false);
								    				});
							   					}
									   		});											
										}								   		
								   		
						   		}
								tracker(ajaxComponentI18n.teamsiteBundles.choose_cell_phone_step_title_label,'0');
								
								ajaxLoader("hide","contractChanger");	
								clearTimeout(window.contractChangerTimer);
							},1);									
						});	
							$(".contractJs", $mapObj).show();
							
							// BlackBerry Playbook
							if($(".memoryJs").hasClass("last")){ $(".memoryJs").removeClass("last"); }
							if ($.inArray(currentState.cellPhoneSku, standAloneSkus) != -1){    
								$(".memoryJs").addClass("last");								
								$(".contractJs", $mapObj).hide();
							}				
					});
				}
				else
				{
					$(".contractJs",$mapObj).hide();
				}

				// BlackBerry Playbook
				if ($.inArray(currentState.cellPhoneSku, standAloneSkus) != -1){    
					$(".memoryJs").addClass("last");								
					$(".contractJs", $mapObj).hide();
				}				
				
				//show/hide promo section if needed.
				showHidePricingDetails(dataDetails["terms"]);
				// bind change/remove events
				$(".cFoot .cFootOptions a", $cellPhoneDetailsStepObj).unbind('click').click(function() {
				
					var $this = $(this);
					var href = $this.attr("href");
					//IE fix: remove url before anchor
					if(href.indexOf("#") !== 0){
						href = href.substring(href.indexOf("#"), (href.length));
					}
					if(href == '#solutionChange'){
						var $cellPhoneDetailsStepObj = $("#CellPhoneDetailsStep");
						var $prepopPromoStepObj = $("#PrepopPromoContent");
						resetForm();
						renderChooseCellPhone();
						planCategoriesStepBuilder();
					}
					
					if(href == '#solutionRemove'){
						var solutionId = $this.attr("rel");	
						//Show a pop up for the remove confirmation
						var $yesnoPopupJsObj = $("#yesnoPopupJs");
						$(".lightBoxTitleJs", $yesnoPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.remove_popup_title_label);
						$(".yesnoTxtJS", $yesnoPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.remove_popup_block);
						$(".btnDftAct", $yesnoPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.confirm_label);
						$(".btnAltAct", $yesnoPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.cancel_label);
						$.pageRender($yesnoPopupJsObj, "lightBox");
		
						$.lightBox.showInPage($yesnoPopupJsObj,{modal:false}, function(objLightBox) {
							//find "yes" button
							$(".btnDftAct", objLightBox).unbind('click').click(function() {
								$.lightBox.hide();					
								phoneSolutionRemove(solutionId);
								return false;					
							});
						});	
					}					
				
					return false;
				});	
					
	    		$(".cFootOptions a", $mapObj).attr({rel: currentState.solutionId});	

				if ($cellPhoneDetailsStepObj.hasClass("hide")) {
					$cellPhoneDetailsStepObj.removeClass("hide");
				}
    		
	    		//build promotion link
	    		var promoUrl = promotionBlockUrl+"?"+flexPricingSkuParameter+"="+currentState.cellPhoneSku+"&"+flexPricingTermParameter+"="+currentState.contractTermSku+getBogoFlexIdsParams(currentState)+promotionBundleParameter;
	    		$("#promoLink-"+dataDetails.productSku).attr("href",promoUrl);
				//enable compatible plans
				enableValidPlans(dataDetails.ratePlanCategoriesAvailable);						
	    		// Render interface at the end
	    		$.bell.pageRender($mapObj,"sBuilderStepMobility");   
    		});
		}
		ajaxLoader("hide","cellPhoneDetailBuilder");
		
	}
	
	if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}
	
	function updateColorSku(phoneDataDetails){
		if(!$.bell.isEmpty(currentState) && !$.bell.isEmpty(currentState.cellPhoneSubSku)){
			var colorLabel = $("#colors-template-"+currentState.cellPhoneSubSku).attr("rel");
			for(var idx in phoneDataDetails["colors"]){
				var colorVO = phoneDataDetails["colors"][idx];
				if(colorVO.colourLabel == colorLabel){
					currentState.productColourId = colorVO.productColourId;
					currentState.cellPhoneSubSku = colorVO.colourSubSku;
					return;
				}
			}
		}
		if (!$.bell.isEmpty(phoneDataDetails["colors"]) && phoneDataDetails["colors"].length >= 1)
		{	
			currentState.cellPhoneSubSku = phoneDataDetails["colors"][0].colourSubSku;
			currentState.productColourId = phoneDataDetails["colors"][0].productColourId;
			return;	
		}
		currentState.cellPhoneSubSku = null;
		currentState.productColourId = null;
	}

	function showHidePricingDetails(phoneTerms){
		for(var idx in phoneTerms){
			var currentTerm = phoneTerms[idx];
			if(currentTerm.productSku == currentState.contractTermSku){
				if(currentTerm.groupId == hasPromotion){
					$(".promoOption").show();
				}else{
					$(".promoOption").hide();
				}
				break;
			}
		}
	}
			
	/***********************************************************************************************************************
	 * PrepopPromotionsComponent Ajax events
	 ***********************************************************************************************************************/
		
	PrepopPromotionsComponent.prototype = new GenericSolutionsBuilderComponent();
	
	PrepopPromotionsComponent.prototype.initialize = function() 
	{
		this.ajaxHandlerName  = ajaxHandlerName;
	}	
	
	function PrepopPromotionsComponent(id) {
		this.timeout = OperationTimeout;
		BaseAjaxComponent.apply(this, arguments);
		this.persistenceKey = 'WirelessSolutionBuilderComponentKey';		
	}

	//Receive data from AJAX
	PrepopPromotionsComponent.prototype.update = function(data, html, newComponents) 
	{
		if (html) 
		{
			//Load the html promo page
			var sbDom = this.getDom();
			var sdDomDiv = $("#"+sbDom.id);
			sdDomDiv.removeClass("hide");
			sdDomDiv.html(html);
			$.bell.pageRender("#PrepopPromoContent");
		}
			
		//bind events
		var $prepopObj = $("#PrepopPromoContent");
		$(".capsule", $prepopObj).each(function(){
			var $capsule = $(this);
			$capsule.unbind("click").click(function(){
				var $input = $(this).find("input");
				$input.attr("checked", true);
				$.bell.setElementActive($input,"#prepopCheckBoxesHolder .prepopPromoJs","capSelected", function(){
					revertState = JSON.clone(currentState);
					lastprepopId = revertState.prepopId; 
					currentState.prepopId = $input.val();
					ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);	

				});
				
			});
		});
		ajaxLoader("hide","prepopPromoBuilder");
	}
	function prepopPromoBuilder(termSku) {	
		if(!$.bell.isEmpty(currentState)){
			ajaxLoader("show","prepopPromoBuilder");
			ajaxComponent('#PrepopPromoContent').callAjaxAction('prepopPromotionsBuilder',{cellPhoneSku : currentState.cellPhoneSku, contractTermSku: termSku, parentSolutionIdLinked: currentState.parentSolutionIdLinked, bogoRewardFlexPricingIds: currentState.bogoRewardFlexPricingIds});
		}
	}
	
	
	/***********************************************************************************************************************
	 * UnqualifiesPromotionComponent Ajax events
	 ***********************************************************************************************************************/
		
	UnqualifiesPromotionComponent.prototype = new GenericSolutionsBuilderComponent();
	
	UnqualifiesPromotionComponent.prototype.initialize = function() 
	{
		this.ajaxHandlerName  = ajaxHandlerName;
	}	
	
	function UnqualifiesPromotionComponent(id) {
		this.timeout = OperationTimeout;
		BaseAjaxComponent.apply(this, arguments);
		this.persistenceKey = 'WirelessSolutionBuilderComponentKey';		
	}

	//Receive data from AJAX
	UnqualifiesPromotionComponent.prototype.update = function(data, html, newComponents) 
	{	
		var $unqualifiesPromotionsPopupJsObj = $("#yesnoPopupWithNoHandlingJs");	
		$(".lightBoxTitleJs", $unqualifiesPromotionsPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.unqualifies_promotion_popup_title_label);
		if (data.erasePromotion) {
			$(".yesnoTxtJS", $unqualifiesPromotionsPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.unqualifies_promotion_popup_block);
		}
		if (data.eraseBogoPromotion) {
			$(".yesnoTxtJS", $unqualifiesPromotionsPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.unqualifies_bogo_popup_block);
		}	
		$.pageRender($unqualifiesPromotionsPopupJsObj, "lightBox");	
								
		$.lightBox.showInPage($unqualifiesPromotionsPopupJsObj,{modal:true}, function(objLightBox) {
			//find "yes" button
			$(".yesJs", objLightBox).unbind('click').click(function() {
				$.lightBox.hide();
				ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',data);
				return false;					
			});
			//find "no" button
			$(".noJs", objLightBox).unbind('click').click(function() {
				$.lightBox.hide();
				handleLoad(revertState);
				ajaxComponent('#WirelessSolutionSteps').callAjaxAction('updateCurrentState',revertState);
				return false;					
			});
		});
								
	}
	
	

	/***********************************************************************************************************************
	 * PlanCategoriesStepBuilder events
	 ***********************************************************************************************************************/

	function planCategoriesStepBuilder()
	{
		ajaxLoader("show","planCategoriesStepBuilder");
		
		var $planCategoriesStepObj = $("#PlanCategoriesStep");	
		
		var data = getDataStoreObject(dataStoreTypeRatePlanCategories,false);
	
		var $mapPlanCategoriesStepObj = $("#mapPlanCategoriesStep");
		if($mapPlanCategoriesStepObj.length)
		{
			$mapPlanCategoriesStepObj.remove();
		}
	
		if (!$.bell.isEmpty(data))
		{   	

    		$.bell.map("#templatePlanCategoriesStepBuilder-tpl-productSku", data, "mapPlanCategoriesStep", function($mapObj) { 
    		
    			//if there is cellphone selection and the choose cellphone box is hidden: disable invalid plans
				if(!$.bell.isEmpty(currentState) && !$.bell.isEmpty(currentState.cellPhoneSku) && $("#ChooseCellPhoneStep").hasClass("hide")){	
					var dataDetails = getCellDataStoreObject(dataStoreTypeCellPhoneDetails,currentState.cellPhoneSku,currentState,false);
					enableValidPlans(dataDetails.ratePlanCategoriesAvailable);
				}else{
					//else enable everything
					togglePlanSelection(true);
				}

				// Hide all terms and conditions
				$("#Terms_Div").children().each(function(i) {
		   			$(this).addClass('hide');
	   			});
				
				//select current state rateplan
				if(!$.bell.isEmpty(currentState) && !$.bell.isEmpty(currentState.ratePlanCategorySku)){
					// Show terms and conditions for current rateplan
					$("#Terms_"+currentState.ratePlanCategorySku).removeClass('hide');
					//Check the rate plan category selected
					var objSelected = $("#itemPlanCategoriesStep_"+currentState.ratePlanCategorySku);
					$.bell.setElementActive(objSelected,"#mapPlanCategoriesStep .planCategoriesStepJs","capSelected");
					objSelected.attr("checked", true);
				}
				
	
				// bind radio click events
				$("input[id*=itemPlanCategoriesStep_]", $mapObj).unbind('click').click(function() {
						var $this = $(this);
						var previousCategory = currentState.ratePlanCategorySku;
						
						
						ajaxLoader("show","itemPlanCategoriesStep");
						$.bell.setElementActive($this,"#mapPlanCategoriesStep .planCategoriesStepJs","capSelected", function() {
							revertState = JSON.clone(currentState);
							
							currentState.additionalFeaturesSku = [];	
							currentState.additionalBundlesSku = [];
							currentState.ratePlanBonusesSku = [];	
							currentState.ratePlanSku = null;
							currentState.ratePlanPage = null;
							currentState.bundlePage = null;
							currentState.additionalLongDistancesSku = [];
							
							var $chooseCellPhoneStep = $("#ChooseCellPhoneStep");
							var chooseCellPhoneDisplayed = !$chooseCellPhoneStep.hasClass("hide");
							if($this.val() == prepaidRatePlansSku){
			    				if(!$.bell.isEmpty(currentState.cellPhoneSku)){
			    					var dataDetails = getCellDataStoreObject(dataStoreTypeCellPhoneDetails,currentState.cellPhoneSku,currentState,false);
			    					var dataDetailsPrepaid = getCellDataStoreObject('',dataDetails.prepaidSku,currentState,false);
									currentState.cellPhoneVariantSku = dataDetails.prepaidSku;
									updateColorSku(dataDetailsPrepaid);
								}
								currentState.contractTermSku = prepaidTermSku;
								cellPhoneDetailBuilder();
								
							}else if(previousCategory == prepaidRatePlansSku){
								var dataDetails = getCellDataStoreObject(dataStoreTypeCellPhoneDetails,currentState.cellPhoneSku,currentState,false);
								currentState.cellPhoneVariantSku = null;
								currentState.contractTermSku = defaultTerm;
								updateColorSku(dataDetails);
								cellPhoneDetailBuilder();
							}
							
							if (chooseCellPhoneDisplayed){
			    				dimIncompatiblePhones($this.val());
			    				hideStep($("#RatePlansStep"));
			    			}else{
			    				currentState.ratePlanCategorySku = $this.val();
			    				
			    				ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);
			    				cellPhoneDetailBuilder();
			    				LoadSteps();
			    				tracker(ajaxComponentI18n.teamsiteBundles.choose_plan_category_step_title_label,'1');
			    			}		
			    				
							ajaxLoader("hide","itemPlanCategoriesStep");
							return false;
						});
					});
					
			   		$mapObj.children().each(function(i) {
			   			var $this = $(this);
			   			if (i!=0 && (i+1)%3==0) {
			   				$this.addClass("colLast");
			   			}
			   			
			   			// Contract Term CR 
			   			var ratePlanCategorysku = $("input:first",$this).val();
			   			var termsList = null;
			   			if(!$.bell.isEmpty(currentState) && !$.bell.isEmpty(currentCellPhoneDetailsDataStore) && currentState.ratePlanCategorySku != prepaidRatePlansSku && currentState.ratePlanCategorySku != grabAndGoTermSku) {
				   			termsList = currentCellPhoneDetailsDataStore.ratePlanCategoriesTermsAvailability[ratePlanCategorysku];
				   			if(!$.bell.isEmpty(termsList) && termsList.indexOf(currentState.contractTermSku) > -1 ){					
								$("div:first",$this).removeClass("capDisabled");
								$this.find("input").each(function(){
								    var $this = $(this);
								    $this.attr("disabled", false); 
			    				});						
							}else{
			    				$("div:first",$this).addClass("capDisabled");
			    				$this.find("input").each(function(){
									var $this = $(this);
									$this.attr("disabled", true); 
									$this.attr("checked", false);
			    				});
		   					}					   
						
						}			   			
			   		});
					showStep($planCategoriesStepObj);	
					$mapObj.equalize({similarItem:"htmlMappedJs"});
    		});
    		 		   		
		}
		ajaxLoader("hide","planCategoriesStepBuilder");
	}
	
	function togglePlanSelection(enabled){
		if(enabled === true){
			$("div[id*=templatePlanCategoriesStepBuilder-] .capsule").each(function(){
				var $this = $(this);
				$.bell.enable($this, "capDisabled");					
			});
		}else{
			$("div[id*=templatePlanCategoriesStepBuilder-] .capsule").each(function(){
				var $this = $(this);
				$.bell.disable($this, "capDisabled");					
			});
		}
	}
	
	function enableValidPlans(categoryArray){
		togglePlanSelection(false);
		for(var idx in categoryArray){
			var category = categoryArray[idx];
			var $element = $("#templatePlanCategoriesStepBuilder-"+category+" .capsule");
			$.bell.enable($element, "capDisabled");
		}
	}
	
	function LoadSteps() {
		//Load the step in function of what category you selected
		var $ratePlansStepObj = $("#RatePlansStep");
		var $planCategoriesStepObj = $("#PlanCategoriesStep");	
		var $featuresStepObj = $("#FeaturesStep");
		var $accessoriesStepObj = $("#AccessoriesStep");
		var $longDistanceStepObj = $("#LongDistanceStep");
		var $otherServicesStepObj = $("#OtherServicesStep");
		var $bundlesStepObj = $("#BundlesStep");	
	
		if(currentState.contractTermSku == grabAndGoTermSku)
		{
			hideStep($planCategoriesStepObj);
			hideStep($ratePlansStepObj);
			hideStep($bundlesStepObj);
			hideStep($featuresStepObj);
			hideStep($longDistanceStepObj);

			accessoriesStepBuilder();
			otherServicesStepBuilder();
		}
		else
		{
			planCategoriesStepBuilder();
			
			if ($.bell.isEmpty(currentState.ratePlanCategorySku)){
				hideStep($ratePlansStepObj);
			}		
			
			if (!$.bell.isEmpty(currentState.ratePlanCategorySku)){
				ratePlansStepBuilder(currentState.ratePlanPage,'true');
				
				if(internetRatePlansSku == currentState.ratePlanCategorySku){
				
					hideStep($bundlesStepObj);
					// CR 10926 - allow features for mobile internet plans and devices
					featuresStepBuilder();
					//hideStep($featuresStepObj);
					hideStep($accessoriesStepObj);
					hideStep($longDistanceStepObj);
					otherServicesStepBuilder();			
				
				}
				else
				{				
		  			if(prepaidRatePlansSku == currentState.ratePlanCategorySku){
						hideStep($bundlesStepObj);
					}
					else
					{
						bundlesStepBuilder();
					}
					
					featuresStepBuilder();
					
					accessoriesStepBuilder();	
						
					if(prepaidRatePlansSku != currentState.ratePlanCategorySku){		
						longDistanceStepBuilder();
					}
					else
					{
						hideStep($longDistanceStepObj);
					}
					
					otherServicesStepBuilder();	
		  			
				}
				// BlackBerry Playbook
				if ($.inArray(currentState.cellPhoneSku, standAloneSkus) != -1) {
					//hideStep($ratePlansStepObj);
					hideStep($bundlesStepObj);
					hideStep($featuresStepObj);
					hideStep($longDistanceStepObj);
				}
				
			}	
		}
	}
	
	


	/***********************************************************************************************************************
	 * RatePlansStepBuilder events
	 ***********************************************************************************************************************/

	function ratePlansStepBuilder(page, reloadPager)
	{

		var data = getDataStoreObject(dataStoreTypeRatePlans,false);
		data = data[currentState.ratePlanCategorySku];
		
		if (!page)
		{
			page = 1;
		}

		if(reloadPager == 'true')
		{
			//Load the rate plans
			ratePlansStepUpdate(data,page);
			
			//Load the rate plans pagination
			ratePlansStepPagerUpdate(data,page);
		}
		else
		{
			//Load the rate plans
			ratePlansStepUpdate(data,page);
		}
	}
	
	function ratePlansStepUpdate(data, page)
	{
		ajaxLoader("show","ratePlansStepUpdate");
	
		var $ratePlansStepObj = $("#RatePlansStep");
		var $mapRatePlansStepObj = $("#mapRatePlansStep");
		if($mapRatePlansStepObj.length)
		{
			$mapRatePlansStepObj.remove(); 
		}	
		
		if (!$.bell.isEmpty(data) && (!$.bell.isEmpty(data["page_"+page]) || !$.bell.isEmpty(data["page_bb_"+page])))
		{		
			//If case for dataRatePlans to get the plans, otherwise use the whole collection
			var dataDetails	= [];
			var isBlackBerryPhone = false;
			if(dataRatePlans == currentState.ratePlanCategorySku && !$.bell.isEmpty(currentState.cellPhoneSku)){
			
				//Find the phone details to get the isblackberry phone
				var dataPhoneDetails = getCellDataStoreObject(dataStoreTypeCellPhoneDetails,currentState.cellPhoneSku,currentState,false);
				var isBlackBerryPhone = dataPhoneDetails.blackBerry;
				
				//Weird way to get the black berry plans, no time to do something else
				if(isBlackBerryPhone){
				    if(currentState.region == 'SK') { // Special hard coding for Prairies Expansion, hardcoded plan objects
					dataDetails[0] = data.page_1[0]; // Adding rateplan obj PR25
					dataDetails[1] = data.page_1[1]; // Adding rateplan obj PR30
					dataDetails[2] = data.page_bb_1[0]; // Adding rateplan obj PR50B
				    } else {
					    dataDetails = data["page_bb_"+page];
					    if($.bell.isEmpty(dataDetails)){
						    //fix problem when switching from a blackberry page 2 and non blackberry doesnt have page 2
						    currentState.ratePlanPage = 1;
						    page = 1;
						    dataDetails = data["page_bb_"+page];
					    }
				    }
				}else{
					dataDetails = data["page_"+page];	
					if($.bell.isEmpty(dataDetails)){
						//fix problem when switching from a blackberry page 2 and non blackberry doesnt have page 2
						currentState.ratePlanPage = 1;
						page = 1;
						dataDetails = data["page_"+page];
					}						
				}
			}
			else
			{
				if($.inArray(currentState.ratePlanSku, bbOnlyPlanSkus) != -1){
					dataDetails = data["page_bb_"+page];
					if($.bell.isEmpty(dataDetails)){
						//fix problem when switching from a blackberry page 2 and non blackberry doesnt have page 2
						currentState.ratePlanPage = 1;					
						page = 1;
						dataDetails = data["page_bb_"+page];
					}						
				}else{
					dataDetails = data["page_"+page];
					if($.bell.isEmpty(dataDetails)){
						//fix problem when switching from a blackberry page 2 and non blackberry doesnt have page 2
						currentState.ratePlanPage = 1;					
						page = 1;
						dataDetails = data["page_"+page];
					}					
				}
				
			}
			
			// CR 11755
			if(dataRatePlans == currentState.ratePlanCategorySku || allInOneRatePlans  == currentState.ratePlanCategorySku){
				for(var idx =0 ; idx < dataDetails.length; idx ++ ){
					var ipos ;
					var dollarvalue	; 
					if ("en" == language) {  
						ipos =dataDetails[idx].detailedPrice.indexOf('.');
						dollarvalue  = dataDetails[idx].detailedPrice.substring(1, ipos); 
					}
					else {
						ipos =dataDetails[idx].detailedPrice.indexOf(',');
						dollarvalue  = dataDetails[idx].detailedPrice.substring(0, ipos); 
					}
					
					if (dataDetails[idx].detailedPrice.indexOf('<span') <0){
						if ("en"== language)
							dataDetails[idx].detailedPrice	= '<span style="font-size: 10px; line-height: 10px; top: 10px; vertical-align: top;">$</span>' +
										dollarvalue +	
										'<span style="font-size: 10px; line-height: 10px; top: 10px; vertical-align: top;">/Mo</span>';
						else
							dataDetails[idx].detailedPrice	= dollarvalue +	'<span style="font-size: 10px; line-height: 10px; top: 10px; vertical-align: top;">$/Mois</span>';
					}						
				}//end for
				
			 
			}//end if
			
			
    		$.bell.map("#templateRatePlansStepBuilder-tpl-productSku", dataDetails, "mapRatePlansStep", function($mapObj) { 
	
				if(!$.bell.isEmpty(currentState.ratePlanSku)){
					if(dataRatePlans == currentState.ratePlanCategorySku){
						if(isBlackBerryPhone){
                            // Prairies Expansion, Adding check condition for region, below logic should NOT be processed for province SK
                            if(currentState.ratePlanSku.indexOf("B") === -1 && currentState.region != 'SK'){
								var foundIt = false;
								for (var idxPager in data) {
								
									if(idxPager.indexOf("page_") != -1 && idxPager.indexOf("page_bb_") === -1){
										var itemsList = data[idxPager];
										
										for (var idxItem in itemsList) {
											var item = itemsList[idxItem];
											if(item.productSku == currentState.ratePlanSku){
												currentState.ratePlanSku += "B";
												foundIt = true;
												break;						
											}
										}
									}
									if (foundIt)
									{
										break;
									}					
								}							
							}
						}
						else if($.inArray(currentState.ratePlanSku, bbOnlyPlanSkus)  == -1)
						{
							if(currentState.ratePlanSku.indexOf("B") >= 1){
								currentState.ratePlanSku = currentState.ratePlanSku.substring(0,currentState.ratePlanSku.length - 1);
							}
							else
							{
								var foundIt = false;
								for (var idxPager in data) {
								
									if(idxPager.indexOf("page_") != -1 && idxPager.indexOf("page_bb_") === -1){
										var itemsList = data[idxPager];
										
										for (var idxItem in itemsList) {
											var item = itemsList[idxItem];
											if(item.productSku == currentState.ratePlanSku){
												foundIt = true;
												break;						
											}
										}
									}
									if (foundIt)
									{
										break;
									}					
								}
								if (!foundIt)
								{
									currentState.ratePlanSku = null;
									currentState.ratePlanBonusesSku = [];
								}
							}
						}
					}
					//Check the rate plan selected
					var $objSelected = $("#itemRatePlansStep-"+currentState.ratePlanSku);
					
					if($objSelected.length > 0){
						$.bell.setElementActive($objSelected,"#mapRatePlansStep .ratePlanStepLineJs","capSelected");
						$objSelected.attr("checked", true);
					}
				}
								
				// bind radio click events
				$("input[id*=itemRatePlansStep-]", $mapObj).unbind('click').click(function() {
					var $this = $(this);
					
					ajaxLoader("show","ratePlanSelection");
					$.bell.setElementActive($this,"#mapRatePlansStep .ratePlanStepLineJs","capSelected", function() {					
						revertState = JSON.clone(currentState);
						
						currentState.ratePlanSku = $this.val();
						currentState.ratePlanBonusesSku = [];
						currentState.additionalFeaturesSku = [];	
						currentState.additionalBundlesSku = [];
						currentState.bundlePage = null;
						currentState.additionalLongDistancesSku = [];	
						
						var $contractSelectBox = $("#select-contract-0");
						if($contractSelectBox.length > 0){
							for(var idx in $contractSelectBox[0].options){
								var currentTerm = $contractSelectBox[0].options[idx];
								if(currentTerm && currentTerm.value == grabAndGoTermSku){
									$contractSelectBox[0].remove(idx);
								}
							}	
						}

						//Enable the bonus in function of the rate plan selected											
						var $ratePlanBonusContentDivObj = $("#RatePlanBonusContent");
						var planSku = $this.attr("value");
						$(".bonusesJs", $ratePlanBonusContentDivObj).each(function(){
							var $this = $(this);
							var id = $this.attr("id");
							if(id.indexOf(planSku) != -1){
								$this.addClass("capSelected");
								if(!$this.hasClass("noCapJs")){
									$this.removeClass("capDisabled");
								}
								
								$(".noBonusInputJs", $this).each(function(){
									var $this = $(this);
							    	var index = jQuery.inArray($this.attr("rel"),currentState.ratePlanBonusesSku);
							    	if (index < 0){							
										currentState.ratePlanBonusesSku.push($this.attr("rel"));
									}
								});
								
								$("input[id*=bonusCol]",$this).each(function(){
									$(this).removeAttr("checked");
								});
								
								if($.bell.isEmpty(currentState.ratePlanBonusesSku)){
									var $inputObj = $("input[id*=bonusCol]:first",$this);
									currentState.ratePlanBonusesSku.push($inputObj.val());
									$inputObj.attr("checked", true);
								}
								
								$this.find("input").each(function(){
									$(this).removeAttr("disabled"); 
								});
							}else{
								$this.removeClass("capSelected");
								if(!$this.hasClass("noCapJs")){
									$this.addClass("capDisabled");
								}							
								$this.find("input").each(function(){
									var $this = $(this);
									$this.attr("disabled", true); 
									$this.attr("checked", false);
								});
							}
						});
						
						ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);
						
						cellPhoneDetailBuilder();
						LoadSteps();
						tracker(ajaxComponentI18n.teamsiteBundles.choose_plan_title_label,'2');
						
						$(".minutesDurationJs", $ratePlanBonusContentDivObj).each(function(){
							var $this = $(this);
							var id = $this.attr("id");
							if(id.indexOf(planSku) != -1){
								$this.addClass("capSelected");
							}else{
								$this.removeClass("capSelected");
							}
						});
						
						$(".minutesPriceJs", $ratePlanBonusContentDivObj).each(function(){
							var $this = $(this);
							var id = $this.attr("id");
							if(id.indexOf(planSku) != -1){
								$this.addClass("capSelected");
							}else{
								$this.removeClass("capSelected");
							}
						});
						
						ajaxLoader("hide","ratePlanSelection");
					});
					
					return true;
				});
				
		   		$mapObj.children().each(function(i) {
		   			var $this = $(this);
 		   			if (i!=0 && (i+1)%4==0) {
		   				$this.addClass("colLast");
		   			}
		   			// Contract Term CR 
		   			var ratePlansku = $("input:first",$this).val();
		   			var termsList = null;
		   			if(!$.bell.isEmpty(currentCellPhoneDetailsDataStore) && currentState.ratePlanCategorySku != prepaidRatePlansSku && currentState.ratePlanCategorySku != grabAndGoTermSku) {
			   			termsList = currentCellPhoneDetailsDataStore.ratePlanTermsAvailability[ratePlansku];
			   			if(!$.bell.isEmpty(termsList) && termsList.indexOf(currentState.contractTermSku) > -1 ){					
							$("div:first",$this).removeClass("capDisabled");
							$this.find("input").each(function(){
							    var $this = $(this);
							    $this.attr("disabled", false); 
		    				});						
						}else{
		    				$("div:first",$this).addClass("capDisabled");
		    				$this.find("input").each(function(){
								var $this = $(this);
								$this.attr("disabled", true); 
								$this.attr("checked", false);
		    				});
	   					}					   
					
					}						
		   		
		   		});		
		   			   		
	    		showStep($ratePlansStepObj);    	
	    		$.bell.pageRender($ratePlansStepObj,"sBuilderStepMobility");
    		});	
		}	

		ajaxLoader("hide","ratePlansStepUpdate");	
	}	
	
	if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}	
	
	function ratePlansStepPagerUpdate(data, page)
	{
	 	var $mapRatePlansStepPagerObj = $("#mapRatePlansStepPager");
		if($mapRatePlansStepPagerObj.length)
		{
			$mapRatePlansStepPagerObj.children(":not(.htmlTemplate)").each(function(){
				$(this).remove();
			});
		}
	
		if (!$.bell.isEmpty(data) && (!$.bell.isEmpty(data["ratePlanPagerList"]) || !$.bell.isEmpty(data["bbRatePlanPagerList"])))
		{	
			var dataDetails	= [];
			if(dataRatePlans == currentState.ratePlanCategorySku && !$.bell.isEmpty(currentState.cellPhoneSku)){
				//Find the phone details to get the isblackberry phone
				var dataPhoneDetails = getCellDataStoreObject(dataStoreTypeCellPhoneDetails,currentState.cellPhoneSku,currentState,false);
				var isBlackBerryPhone = dataPhoneDetails.blackBerry;
			
				//Weird way to get the black berry page, no time to do something else
				if(isBlackBerryPhone){
					dataDetails = data["bbRatePlanPagerList"];
                    if(currentState.region == 'SK') { // Prairies Expansion - Hard Coding rate plans list
                        dataDetails[0].productSku='PR25--PR30--PR50B';
                    }
				}else{
					dataDetails = data["ratePlanPagerList"];
				}	
			}
			else
			{
				if($.inArray(currentState.ratePlanSku, bbOnlyPlanSkus)  != -1){
					dataDetails = data["bbRatePlanPagerList"];
				}else{
					dataDetails = data["ratePlanPagerList"];
				}
			}			
    		$.bell.map("#templateRatePlansStepPagerBuilder-tpl-name", dataDetails, function($mapObj) { 
    			if($mapObj){
	    		  	$mapObj.attr("id", "mapRatePlansStepPager");
	    		  	//Check the rate plan page selected
	  		  		var $ratePlanStepPagerObj = $("#templateRatePlansStepPagerBuilder-"+page);
	  		  		if($ratePlanStepPagerObj.length == 0){
	  		  			//fix problem when switching from a blackberry page 2 and non blackberry doesnt have page 2
	  		  			$ratePlanStepPagerObj = $("#templateRatePlansStepPagerBuilder-1");
	  		  		}
	   		  		$.bell.setElementActive($ratePlanStepPagerObj,"#mapRatePlansStepPager .ratePlansStepPagerLineJs","active");	
	    		  		
					// bind the page button click events
					$("a", $mapObj).click(function() {
						var $this = $(this);
						var relRatePlanskus = $this.attr("rel");
						var relRatePlanPage = $this.attr("relpage");
						currentState.ratePlanPage = relRatePlanPage;
						
						//Reload the rate plans in function of which page is selected
						ajaxLoader("show","ratePlanBonusBuilder");
						$.bell.setElementActive($this,"#mapRatePlansStepPager .ratePlansStepPagerLineJs","active", function() {
							ratePlanBonusBuilder(relRatePlanskus);	
							ratePlansStepBuilder(relRatePlanPage,'false');										
						});
						
						return false;
					});   		
	   		
	   				$("li:visible:first a",$mapObj).addClass("first");
	   				$("li:last a",$mapObj).addClass("last");
	   		  		
	   		  		//Load the bonus in function of which rate plan is selected
		    		var relRatePlanskus = $mapObj.find(".active").attr("rel");
		    		ratePlanBonusBuilder(relRatePlanskus); 	
		    		
		    		if(dataDetails.length == 1){
		    			$ratePlanStepPagerObj.addClass("hide");
		    		}
	    		}	    		   		  		
    		});		  		
    		    		    		
		}    		    		
	
	}

	
	/***********************************************************************************************************************
	 * RatePlanBonusComponent Ajax events
	 ***********************************************************************************************************************/
	
	RatePlanBonusComponent.prototype = new GenericSolutionsBuilderComponent();
	
	RatePlanBonusComponent.prototype.initialize = function() 
	{
		this.ajaxHandlerName  = ajaxHandlerName;
	}	
	
	function RatePlanBonusComponent(id) {
		this.timeout = OperationTimeout;
		BaseAjaxComponent.apply(this, arguments);
		this.persistenceKey = 'WirelessSolutionBuilderComponentKey';		
	}

	//Receive data from AJAX update the solution box
	RatePlanBonusComponent.prototype.update = function(data, html, newComponents) 
	{
		if (html) 
		{
			//Load the html bonuses page
			var sbDom = this.getDom();
			var $sdDomDiv = $("#"+sbDom.id);
			$sdDomDiv.html(html);

		}
		
		if(!$.bell.isEmpty(currentState.ratePlanSku)){		
		
			var $ratePlanBonusContentDivObj = $("#RatePlanBonusContent");
			var planSku = currentState.ratePlanSku;
			$(".bonusesJs", $ratePlanBonusContentDivObj).each(function(){
				var $this = $(this);
				var id = $this.attr("id");
				if(id.indexOf(planSku) != -1){
					$this.addClass("capSelected");
					if(!$this.hasClass("noCapJs")){
						$this.removeClass("capDisabled");
					}
					
					$this.find("input").each(function(){
						$(this).removeAttr("disabled"); 
					});
				}else{
					$this.removeClass("capSelected");
					if(!$this.hasClass("noCapJs")){
						$this.addClass("capDisabled");
					}							
					$this.find("input").each(function(){
						var $this = $(this);
						$this.attr("disabled", true); 
						$this.attr("checked", false);
					});
				}
							
				$("input[id*=bonusCol]",$this).each(function(){
					var $this = $(this);
					if(!$.bell.isEmpty(currentState.ratePlanBonusesSku) && id.indexOf(planSku) != -1){
				    	var index = jQuery.inArray($this.val(),currentState.ratePlanBonusesSku);
				    	if (index >= 0){								
							$this.attr("checked", true);
						}
					}				
				
					$this.unbind("click").click(function() {
						var $this = $(this);
						revertState = JSON.clone(currentState);
									    							
			    		currentState.ratePlanBonusesSku = [];
						currentState.ratePlanBonusesSku.push($this.val());	
						ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);
						tracker(ajaxComponentI18n.teamsiteBundles.choose_plan_title_label,'2');
						
						return true;
					});	
				});			
				
			});
			
			$(".minutesDurationJs", $ratePlanBonusContentDivObj).each(function(){
				var $this = $(this);
				var id = $this.attr("id");
				if(id.indexOf(planSku) != -1){
					$this.addClass("capSelected");
				}else{
					$this.removeClass("capSelected");
				}
			});
			
			$(".minutesPriceJs", $ratePlanBonusContentDivObj).each(function(){
				var $this = $(this);
				var id = $this.attr("id");
				if(id.indexOf(planSku) != -1){
					$this.addClass("capSelected");
				}else{
					$this.removeClass("capSelected");
				}
			});		
		}
		else
		{
			var $ratePlanBonusContentDivObj = $("#RatePlanBonusContent");
			$(".bonusesJs", $ratePlanBonusContentDivObj).each(function(){

				$("input[id*=bonusCol]",$(this)).unbind("click").click(function() {
					var $this = $(this);
					revertState = JSON.clone(currentState);
					
			    	var index = jQuery.inArray($this.val(),currentState.ratePlanBonusesSku);
			    	if (index < 0) {							
						currentState.ratePlanBonusesSku.push($this.val());
					}									
					ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);
					
					return true;
				});
				
			});		
		}
		$.bell.pageRender($ratePlanBonusContentDivObj,"sBuilderStepMobility");
		$ratePlanBonusContentDivObj.find(".capsule").each(function(){
			$.hasLayout($(this));
		});

		ajaxLoader("hide","ratePlanBonusBuilder");
	}
	
	function ratePlanBonusBuilder(skus) {
		ajaxLoader("show","ratePlanBonusBuilder");
		ajaxComponent('#RatePlanBonusContent').callAjaxAction('ratePlanBonusBuilder',{ratePlansSkuList: skus});		
	}

	/***********************************************************************************************************************
	 * BundlesStepBuilder events
	 ***********************************************************************************************************************/
	
	function bundlesStepBuilder()
	{

		ajaxLoader("show","bundlesStepBuilder");
	
		var $bundlesStepObj = $("#BundlesStep");
		var productSku = currentState.cellPhoneSku;
		
		var data = getDataStoreObject(dataStoreTypeBundles,false);
		
		//choose category
		var category = data["categories"][currentState.ratePlanCategorySku];
		
		var rel = $bundlesStepObj.attr("rel");
		var $mapBundlesStepObj = $("#mapBundlesStep");
		if(!rel || rel != category){
		
			if($mapBundlesStepObj.length)
			{
				$mapBundlesStepObj.remove(); 
			}
			
			// Show Data	
			var dataBundles;
			data = data["bundles"];
			if (!$.bell.isEmpty(data) && category)
			{		
				dataBundles	= data[category];
			}
		
			if (!$.bell.isEmpty(dataBundles))
			{
			
	    		$.bell.map("#templateBundlesStepBuilder-tpl-productSku", dataBundles, "mapBundlesStep", function($mapObj) { 
    		   		showStep($bundlesStepObj);
	    		   	loadBundlesAvailability($mapObj);
	    		   		
					// bind radio click events
					$("input[id*=bundleElement-]", $mapObj.parent()).unbind('click').click(function() {
						var $this = $(this);
						$.bell.setElementActive($this,"#BundlesStep .bundlesStepLineJs","capSelected");
						revertState = JSON.clone(currentState);
						currentState.additionalBundlesSku = [];
						
						if($this.val() != 'nothanks'){
	    					currentState.additionalBundlesSku.push($this.val());
	    				}
	    				
			    		ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);
			    		tracker(ajaxComponentI18n.teamsiteBundles.bundles_step_title_label,'3');
			    		return true;
			   		});
			   		$mapObj.children().each(function(i) {
			   			if (i!=0 && (i+2)%3==0) {
			   				$(this).addClass("colLast");
			   			}
			   		});   	
		    		  
		    		$.bell.pageRender($bundlesStepObj,"sBuilderStepMobility");  		
	    		});
			}else{
				hideStep($bundlesStepObj);
			}
			$bundlesStepObj.attr("rel",category);
		}else{
			if($mapBundlesStepObj.length){
				loadBundlesAvailability($mapBundlesStepObj);
				showStep($bundlesStepObj); 
			}else{
				hideStep($bundlesStepObj);
			}
		}
		ajaxLoader("hide","bundlesStepBuilder");
	}
	
	function loadBundlesAvailability($mapObj){

/*  cleanup before display   */
			//Loop in each bundle div to disable it
			$("input[id*=bundleElement-]", $mapObj).each(function(){
				var $this = $(this);
				var val = $this.val();
		
				if(val != 'nothanks'){
					$.bell.disable($this.parent(), "capDisabled");
				}
		
			});		
			
			//Select the no thanks by default
			var objSelected = $("#bundleElement-nothanks");
			$.bell.setElementActive(objSelected,"#BundlesStep .bundlesStepLineJs","capSelected");			
			objSelected.attr("checked", true);
/* end cleanup  */
	
		if (!$.bell.isEmpty(currentState.ratePlanSku) && !$.bell.isEmpty(currentState.cellPhoneSku)) {
		
			//Find the phone details to get the optional features list
			var dataPhoneDetails = getCellDataStoreObject(dataStoreTypeCellPhoneDetails,currentState.cellPhoneSku,currentState,false);
			var dataMap = dataPhoneDetails.optionalFeaturesSkus;
			
			//Check the selected bundles
			if(!$.bell.isEmpty(currentState.additionalBundlesSku)){
				for (var idx in currentState.additionalBundlesSku) {
					var value = currentState.additionalBundlesSku[idx];										
					var objSelected = $("#bundleElement-"+value);
					$.bell.setElementActive(objSelected,"#BundlesStep .bundlesStepLineJs","capSelected");			
					objSelected.attr("checked", true);									
				};				
			} else{
				//By default no thanks is selected
				var objSelected = $("#bundleElement-nothanks");
				$.bell.setElementActive(objSelected,"#BundlesStep .bundlesStepLineJs","capSelected");			
				objSelected.attr("checked", true);						
			}				
		
			//Loop in each bundle div to enable or disable it
			$("input[id*=bundleElement-]", $mapObj).each(function(){
				var $this = $(this);
				var val = $this.val();
		
				if(val != 'nothanks' && !$.bell.isEmpty(dataMap)){
					var featuresList = dataMap[currentState.ratePlanSku];
					
					if (!$.bell.isEmpty(featuresList)) {
					
						var index = jQuery.inArray(val, featuresList);
				    	if (index >= 0){
				    		$.bell.enable($this.parent(), "capDisabled"); 
					    }
					    else{				
							$.bell.disable($this.parent(), "capDisabled");
						}
					}
				}
		
			});
		}
		/*else
		{
			//Loop in each bundle div to disable it
			$("input[id*=bundleElement-]", $mapObj).each(function(){
				var $this = $(this);
				var val = $this.val();
		
				if(val != 'nothanks'){
					$.bell.disable($this.parent(), "capDisabled");
				}
		
			});		
			
			//Select the no thanks by default
			var objSelected = $("#bundleElement-nothanks");
			$.bell.setElementActive(objSelected,"#BundlesStep .bundlesStepLineJs","capSelected");			
			objSelected.attr("checked", true);
		}*/
	
	}	

	
	/***********************************************************************************************************************
	 * FeaturesStepBuilder events
	 ***********************************************************************************************************************/
	
	function featuresStepBuilder()
	{
		ajaxLoader("show","featuresStepBuilder");
	
		var $featuresStepObj = $("#FeaturesStep");	
	    var $mapFeaturesStepObj = $("#mapFeaturesStep");
	    var $mapFeaturesExclusiveStepObj = $("#mapFeaturesExclusiveStep");
		var render = false;
		if(currentState.ratePlanCategorySku == prepaidRatePlansSku){

			$("#prepaid-features-box").removeClass("hide");	
			if($mapFeaturesExclusiveStepObj.length)
			{				
				$mapFeaturesExclusiveStepObj.addClass("hide");
			}
			if($mapFeaturesStepObj.length)
			{			
				$mapFeaturesStepObj.addClass("hide");
			}	
			showStep($featuresStepObj);	   				
		}
		else
		{
			$("#prepaid-features-box").addClass("hide");
	   		var renderNeeded = false;
			if($mapFeaturesExclusiveStepObj.length)
			{
				loadFeaturesExclusiveAvailability($mapFeaturesExclusiveStepObj);
				$mapFeaturesExclusiveStepObj.removeClass("hide");
			}
			else
			{
				var data = getDataStoreObject(dataStoreTypeFeatures,false);
				data = data["featuresVOExclusiveList"];
				if (!$.bell.isEmpty(data))
				{
					render = true;
		    		$.bell.mapExtender("#templateFeaturesExclusiveStepBuilder-map-index", data,"mapFeaturesExclusiveStep", function($mapObj) { 
		    			
					    loadFeaturesExclusiveAvailability($mapObj);
			    		
						// bind radio click events
						$("input[id*=itemFeaturesExclusiveStep-]", $mapObj).unbind('click').click(function() {
							var $this = $(this);
							var group = $this.attr("rel");
							var relIndex = $this.attr("relIndex");
							var value = $this.val();
							revertState = JSON.clone(currentState);
							
							//remove the last features selected from the collection
							var relLast = $("#templateFeaturesExclusiveStepBuilder-"+relIndex).attr("relLast");
							if (!$.bell.isEmpty(relLast))
							{
								var index = jQuery.inArray(relLast,currentState.additionalFeaturesSku);
						    	if (index >= 0){
						    		currentState.additionalFeaturesSku.splice(index,1);
							    }					
							}
									
							$.bell.setElementActive(this,"#mapFeaturesExclusiveStep .featuresExclusiveStepLine"+group+"Js","capSelected");
							
							//Check if the feature exclusive exist in the array and add it
							$("#templateFeaturesExclusiveStepBuilder-"+relIndex).attr("relLast",value);
					    	var index = jQuery.inArray(value,currentState.additionalFeaturesSku);
					    	if (index < 0 && value != 'nothanks'){
					    		currentState.additionalFeaturesSku.push(value);
						    }
							
						    ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);	
						    tracker(ajaxComponentI18n.teamsiteBundles.features_step_title_label,'4');
						    return true;				
						});	    				
		
						$mapObj.children().each(function(i) {
				   			$(".mCol1", $(this)).each(function(x) {
					   			if (x!=0 && (x+1)%4==0) {
					   				$(this).addClass("colLast");
					   			}
				   			});
				   		});
		    		});		   	
		    		   				
				}
			}
			
			
			if($mapFeaturesStepObj.length)
			{
				loadFeaturesAvailability($mapFeaturesStepObj);
				$mapFeaturesStepObj.removeClass("hide");
			}
			else
			{					
				var data = getDataStoreObject(dataStoreTypeFeatures,false);
				data = data["featuresVOList"];				
				if (!$.bell.isEmpty(data))
				{
					render = true;	
		    		$.bell.mapExtender("#templateFeaturesStepBuilder-map-index", data, "mapFeaturesStep", function($mapObj) { 

	   					loadFeaturesAvailability($mapObj);
						//Bind check box change events			
						$("input[id*=itemFeaturesStep-]", $mapObj).click(function() {
							var $this = $(this);
							var value = $this.val();
							$.bell.toggleElementActive($(".featuresStepLine"+value+"Js",$mapObj),"capSelected");
							revertState = JSON.clone(currentState);
							
							//Check if feature exist in the array. Add it or remove it.
							if($this.attr("checked")){
						    	var index = jQuery.inArray(value,currentState.additionalFeaturesSku);
						    	if (index < 0){
						    		currentState.additionalFeaturesSku.push(value);
							    }	
						    }else{
						    	var index = jQuery.inArray(value,currentState.additionalFeaturesSku);
						    	if (index >= 0){
						    		currentState.additionalFeaturesSku.splice(index,1);
							    }				    
						    }
						    ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);
						    tracker(ajaxComponentI18n.teamsiteBundles.features_step_title_label,'4');			
										
						});				
				   		
						$mapObj.children().each(function(i) {
				   			$(".mCol1", $(this)).each(function(x) {
					   			if (x!=0 && (x+1)%4==0) {
					   				$(this).addClass("colLast");
					   			}
				   			});
				   		});		
		    		});		   	
		    		  		 		
				}
				
			}	
			showStep($featuresStepObj);	
			if(render === true){
				$.bell.pageRender($featuresStepObj,"sBuilderStepMobility");		
			}
		}
		ajaxLoader("hide","featuresStepBuilder");
	}
	
	function loadFeaturesExclusiveAvailability($mapObj){
	
		if($mapObj.length == 0)
		{
			return;
		}	
/* cleanup before display */
			//Loop in all features exclusive div to disable it
			$("input[id*=itemFeaturesExclusiveStep-]", $mapObj).each(function(){
				var $this = $(this);
				var val = $this.val();
		
				if(val != 'nothanks'){
					$.bell.disable($this.parent(), "capDisabled");
				}
		
			});	
			
			//Loop in all features exclusive div check the no thanks by default
			var data = getDataStoreObject(dataStoreTypeFeatures,false);
			data = data["featuresVOExclusiveList"];			
			for (var idxReset in data) {
				var value = data[idxReset];

				var $select = $("#itemFeaturesExclusiveStep-nothanks-"+value.categoryProductSku);
				if($select.length){	
					var relIndex = $select.attr("relIndex");
					$("#templateFeaturesExclusiveStepBuilder-"+relIndex).removeAttr("relLast");
					$.bell.setElementActive($select,"#mapFeaturesExclusiveStep .featuresExclusiveStepLine"+value.categoryProductSku+"Js","capSelected");
					$select.attr('checked','checked');
				}
			}					
/* end cleanup  */ 	
		if (!$.bell.isEmpty(currentState.ratePlanSku) && !$.bell.isEmpty(currentState.cellPhoneSku)) {
		
			//Find the cell phone details to get the optional features skus
			var dataPhoneDetails = getCellDataStoreObject(dataStoreTypeCellPhoneDetails,currentState.cellPhoneSku,currentState,false);
			var dataMap = dataPhoneDetails.optionalFeaturesSkus;			
			
			//Reset all check box to no thanks by default
			var data = getDataStoreObject(dataStoreTypeFeatures,false);
			data = data["featuresVOExclusiveList"];
			for (var idxReset in data) {
				var value = data[idxReset];

				var $select = $("#itemFeaturesExclusiveStep-nothanks-"+value.categoryProductSku);
				if($select.length){	
					var relIndex = $select.attr("relIndex");
					$("#templateFeaturesExclusiveStepBuilder-"+relIndex).removeAttr("relLast");
					$.bell.setElementActive($select,"#mapFeaturesExclusiveStep .featuresExclusiveStepLine"+value.categoryProductSku+"Js","capSelected");
					$select.attr('checked','checked');
				}
			}	
			
			//Check the features exclusive selected
	   		if (!$.bell.isEmpty(currentState.additionalFeaturesSku)) {
				for (var idx in currentState.additionalFeaturesSku) {
					var value = currentState.additionalFeaturesSku[idx];		    		
					var $select = $("#itemFeaturesExclusiveStep-"+value);
					if($select.length){	  
						var group = $select.attr("rel");
						var relIndex = $select.attr("relIndex");
						$("#templateFeaturesExclusiveStepBuilder-"+relIndex).attr("relLast",value);
						$.bell.setElementActive($select,"#mapFeaturesExclusiveStep .featuresExclusiveStepLine"+group+"Js","capSelected");
						$select.attr('checked','checked');
					}
				};
	   		}						
		
			//Loop in all features exclusive div to enable or disable it
			$("input[id*=itemFeaturesExclusiveStep-]", $mapObj).each(function(){
				var $this = $(this);
				var val = $this.val();
		
				if(val != 'nothanks' && !$.bell.isEmpty(dataMap)){
					var featuresList = dataMap[currentState.ratePlanSku];
					
					if (!$.bell.isEmpty(featuresList)) {
					
						var index = jQuery.inArray(val, featuresList);
				    	if (index >= 0){
				    		$.bell.enable($this.parent(), "capDisabled"); 
					    }
					    else{				
							$.bell.disable($this.parent(), "capDisabled");
						}
					}
				}
		
			});
		}
		/*else
		{
			//Loop in all features exclusive div to disable it
			$("input[id*=itemFeaturesExclusiveStep-]", $mapObj).each(function(){
				var $this = $(this);
				var val = $this.val();
		
				if(val != 'nothanks'){
					$.bell.disable($this.parent(), "capDisabled");
				}
		
			});	
			
			//Loop in all features exclusive div check the no thanks by default
			var data = getDataStoreObject(dataStoreTypeFeatures,false);
			data = data["featuresVOExclusiveList"];			
			for (var idxReset in data) {
				var value = data[idxReset];

				var $select = $("#itemFeaturesExclusiveStep-nothanks-"+value.categoryProductSku);
				if($select.length){	
					var relIndex = $select.attr("relIndex");
					$("#templateFeaturesExclusiveStepBuilder-"+relIndex).removeAttr("relLast");
					$.bell.setElementActive($select,"#mapFeaturesExclusiveStep .featuresExclusiveStepLine"+value.categoryProductSku+"Js","capSelected");
					$select.attr('checked','checked');
				}
			}					
		}	*/
	
	}

	function loadFeaturesAvailability($mapObj){
	
		if($mapObj.length == 0)
		{
			return;
		}	
/* start cleanup before displaying */
			//Loop in all features div to disable it and uncheck it
			$(".capsule",$mapObj).each(function(){
				var $this = $(this);	
				$.bell.setCheckBoxState($this,false,"capSelected");
				$.bell.disable($this, "capDisabled");
			});				
/* end cleanup */	
		if (!$.bell.isEmpty(currentState.ratePlanSku) && !$.bell.isEmpty(currentState.cellPhoneSku)) {
		
			//Find the cell phone details to get the optional features skus
			var dataPhoneDetails = getCellDataStoreObject(dataStoreTypeCellPhoneDetails,currentState.cellPhoneSku,currentState,false);
			var dataMap = dataPhoneDetails.optionalFeaturesSkus;
			
			//Loop in all features div to uncheck it
			$(".capsule",$mapObj).each(function(){
				var $this = $(this);	
				$.bell.setCheckBoxState($this,false,"capSelected");
			});	
			
			//Check the features exclusive selected
	   		if (!$.bell.isEmpty(currentState.additionalFeaturesSku)) {
				// MD CR 11671 problem with back button in IE
				// replacing for (var idx in currentState.additionalFeaturesSku)
				// to avoid wrong reading of indexes
				for (var idx=0; idx<currentState.additionalFeaturesSku.length;idx++) {
					var value = currentState.additionalFeaturesSku[idx];	
					var $obj = $(".featuresStepLine"+value+"Js",$mapObj);
					if($obj.length){	   
						$.bell.setCheckBoxState($obj,true,"capSelected"); 		
					}
				};    		
	   		} 					
		
			//Loop in all features div to enable or disable it
			$("input[id*=itemFeaturesStep-]", $mapObj).each(function(){
				var $this = $(this);
				var val = $this.val();
		
				if(!$.bell.isEmpty(dataMap)){
					var featuresList = dataMap[currentState.ratePlanSku];
					
					if (!$.bell.isEmpty(featuresList)) {
					
						var index = jQuery.inArray(val, featuresList);
				    	if (index >= 0){
				    		$.bell.enable($this.parent(), "capDisabled"); 
					    }
					    else{				
							$.bell.disable($this.parent(), "capDisabled");
						}
					}
				} 
				// CR 10926
				// temporary fix to allow the Mobile Internet Pan FEATURE SPD42TSSS
				// to be selectable when combined to stick Novatel U547
				else { 
					if(internetRatePlansSku == currentState.ratePlanCategorySku ) {
						if ("SPD42TSSS" == val && "70600" == currentState.cellPhoneSku) {
							$.bell.enable($this.parent(), "capDisabled"); 
						}
					}
				}
				// CR10926 end
			});
		}
		/*else
		{			
			//Loop in all features div to disable it and uncheck it
			$(".capsule",$mapObj).each(function(){
				var $this = $(this);	
				$.bell.setCheckBoxState($this,false,"capSelected");
				$.bell.disable($this, "capDisabled");
			});				
		}*/
	
	}	

	
	/***********************************************************************************************************************
	 * AccessoriesStepBuilder events
	 ***********************************************************************************************************************/
	
	function accessoriesStepBuilder()
	{
		ajaxLoader("show","accessoriesStepBuilder");
		
		var $accessoriesStepObj = $("#AccessoriesStep");
		
		var rel = $accessoriesStepObj.attr("rel");
		showStep($accessoriesStepObj);
		if(!rel || rel != currentState.cellPhoneSku){

			/* 	update $accessoriesStepObj.attr("rel") here to bypass if (!$.bell.isEmpty(data) 
			*	and prevent the undisplay of accessories when coming from a phone that as none 	
			*	therefore forcing the reload of available accessories () */									
			$accessoriesStepObj.attr("rel", currentState.cellPhoneSku);

			//Find the cell phone details to get the accessories collection
			var productSku = currentState.cellPhoneSku;
			var dataPhoneDetails = getCellDataStoreObject(dataStoreTypeCellPhoneDetails,currentState.cellPhoneSku,currentState,false);
			var data = dataPhoneDetails.accessories;

			var $mapAccessoriesStepObj = $("#mapAccessoriesStep");
			if($mapAccessoriesStepObj.length)
			{
				$mapAccessoriesStepObj.remove(); 
			}
			if (!$.bell.isEmpty(data))
			{		
	    		$.bell.map("#templateAccessoriesStepBuilder-tpl-productSku", data, "mapAccessoriesStep", function($mapObj) { 
	    		
	    			//Check the accessories selected
		    		if (!$.bell.isEmpty(currentState.additionalAccessoriesSku)) {
				// MD CR 11671 problem with back button in IE
				// replacing for (var idx in currentState.additionalAccessoriesSku)
				// to avoid wrong reading of indexes
						for (var idx=0; idx<currentState.additionalAccessoriesSku.length;idx++) {
							var value = currentState.additionalAccessoriesSku[idx];	
							$.bell.setCheckBoxState($(".accessoriesStepLine"+value+"Js",$mapObj),true,"capSelected"); 	    		
						};    		
		    		}
	    		
					// Bind check box change events
					$("input[id*=itemAccessoriesStep_]", $mapObj).click(function() {
						var $this = $(this);
						var value = $this.val();
						$.bell.toggleElementActive($(".accessoriesStepLine"+value+"Js",$mapObj),"capSelected");
						revertState = JSON.clone(currentState);

						//Check if accessory exist in the array. Add it or remove it.
						if($this.attr("checked")){
					    	var index = jQuery.inArray(value,currentState.additionalAccessoriesSku);
					    	if (index < 0){
					    		currentState.additionalAccessoriesSku.push(value);
						    }	
					    }else{
					    	var index = jQuery.inArray(value,currentState.additionalAccessoriesSku);
					    	if (index >= 0){
					    		currentState.additionalAccessoriesSku.splice(index,1);
						    }				    
					    }	
					    ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);	
					    tracker(ajaxComponentI18n.teamsiteBundles.accessories_step_title_label,'5');		
					});
					   	
			   		$mapObj.children().each(function(i) {
			   			if (i!=0 && (i+1)%2==0) {
			   				$(this).addClass("colLast");
			   			}
			   		});
			   		$accessoriesStepObj.attr("rel", currentState.cellPhoneSku);
		    		// Render interface at the end 
		    		$mapObj.equalize({similarItem:"htmlMappedJs"});
		    		$.bell.pageRender($mapObj,"sBuilderStepMobility");		
	    		});		
	    				  		
			}
		}
		  
		ajaxLoader("hide","accessoriesStepBuilder");
	}
	
	/***********************************************************************************************************************
	 * LongDistanceStepBuilder events
	 ***********************************************************************************************************************/			

	function longDistanceStepBuilder()
	{
		ajaxLoader("show","longDistanceStepBuilder");	
	
	    var $longDistanceStepObj = $("#LongDistanceStep");
	    		
	   	var $mapLongDistanceStepObj = $("#mapLongDistanceStep");
		if($mapLongDistanceStepObj.length)
		{	
			showStep($longDistanceStepObj);
			loadLongDistancesAvailability($mapLongDistanceStepObj);		
		}
		else
		{
			var data = getDataStoreObject(dataStoreTypeLongDistance,false);
			if (!$.bell.isEmpty(data))
			{
	
	    		$.bell.mapExtender("#templateLongDistanceStepBuilder-map-index", data, "mapLongDistanceStep", function($mapObj) { 
			
					loadLongDistancesAvailability($mapObj);
			
					//Bind radio click events
					$("input[id*=itemLongDistanceStep-]", $mapObj).unbind('click').click(function() {
						var $this = $(this);
						var group = $this.attr("rel");
						var relIndex = $this.attr("relIndex");
						var value = $this.val();
						revertState = JSON.clone(currentState);
						
						//Remove the last selected long distance from the collection
						var relLast = $("#templateLongDistanceStepBuilder-"+relIndex).attr("relLast");
						if (!$.bell.isEmpty(relLast))
						{
							var index = jQuery.inArray(relLast,currentState.additionalLongDistancesSku);
					    	if (index >= 0){
					    		currentState.additionalLongDistancesSku.splice(index,1);
						    }					
						}
								
						$.bell.setElementActive(this,"#mapLongDistanceStep .longDistanceStepLine"+group+"Js","capSelected");
						
						//Check if long distance exist in the array and add it
						$("#templateLongDistanceStepBuilder-"+relIndex).attr("relLast",value);
				    	var index = jQuery.inArray(value,currentState.additionalLongDistancesSku);
				    	if (index < 0 && value != 'nothanks'){
				    		currentState.additionalLongDistancesSku.push(value);
					    }
		
					    ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);
					    tracker(ajaxComponentI18n.teamsiteBundles.long_distance_step_title_label,'6');		
					    
					    return true;				
					});
					   	
					   	
					$mapObj.children().each(function(i) {
			   			$(".mCol1", $(this)).each(function(x) {
				   			if (x!=0 && (x+1)%4==0) {
				   				$(this).addClass("colLast");
				   			}
			   			});
			   		});				   	
			   		showStep($longDistanceStepObj);
		    		// Render interface at the end
		    		$.bell.pageRender($longDistanceStepObj,"sBuilderStepMobility");
					   	
	    		});		
		  		   		
			}
		}
		
		ajaxLoader("hide","longDistanceStepBuilder");		
	}
	
	function loadLongDistancesAvailability($mapObj){
	
		if($mapObj.length == 0)
		{
			return;
		}
/* cleanup before displaying */
			//Loop in each long distance div to disable it
			$("input[id*=itemLongDistanceStep-]", $mapObj).each(function(){
				var $this = $(this);
				var val = $this.val();
		
				if(val != 'nothanks'){
					$.bell.disable($this.parent(), "capDisabled");
				}
		
			});		
			
			//Reset all long distance div to no thanks by default
			for (var idxReset in getDataStoreObject(dataStoreTypeLongDistance,false)) {
				var value = getDataStoreObject(dataStoreTypeLongDistance,false)[idxReset];			
	
				var $select = $("#itemLongDistanceStep-nothanks-"+value.categoryProductSku);
				if($select.length){	
					var relIndex = $select.attr("relIndex");
					$("#templateLongDistanceStepBuilder-"+relIndex).removeAttr("relLast");
					$.bell.setElementActive($select,"#mapLongDistanceStep .longDistanceStepLine"+value.categoryProductSku+"Js","ted");
					$select.attr('checked','checked');
				}
			}				
/* end cleanup */	
		if (!$.bell.isEmpty(currentState.ratePlanSku) && !$.bell.isEmpty(currentState.cellPhoneSku)) {
		
			//Find the cell phone details to get the optional features skus
			var dataPhoneDetails = getCellDataStoreObject(dataStoreTypeCellPhoneDetails,currentState.cellPhoneSku,currentState,false);
			var dataMap = dataPhoneDetails.optionalFeaturesSkus;
			
			//Reset all long distance div to no thanks by default
			for (var idxReset in getDataStoreObject(dataStoreTypeLongDistance,false)) {
				var value = getDataStoreObject(dataStoreTypeLongDistance,false)[idxReset];			
	
				var $select = $("#itemLongDistanceStep-nothanks-"+value.categoryProductSku);
				if($select.length){	
					var relIndex = $select.attr("relIndex");
					$("#templateLongDistanceStepBuilder-"+relIndex).removeAttr("relLast");
					$.bell.setElementActive($select,"#mapLongDistanceStep .longDistanceStepLine"+value.categoryProductSku+"Js","capSelected");
					$select.attr('checked','checked');
				}
			}
		
			//Check the long distance selected
	   		if (!$.bell.isEmpty(currentState.additionalLongDistancesSku)) {
				for (var idx in currentState.additionalLongDistancesSku) {
					var value = currentState.additionalLongDistancesSku[idx];		    		
					var $select = $("#itemLongDistanceStep-"+value);
					if($select.length){	
						var group = $select.attr("rel");
						var relIndex = $select.attr("relIndex");
						$("#templateLongDistanceStepBuilder-"+relIndex).attr("relLast",value);
						$.bell.setElementActive($select,"#mapLongDistanceStep .longDistanceStepLine"+group+"Js","capSelected");
						$select.attr('checked','checked');
					}
				};    		
	   		}			
		
			//Loop in each long distance div to disable it or enable it
			$("input[id*=itemLongDistanceStep-]", $mapObj).each(function(){
				var $this = $(this);
				var val = $this.val();
		
				if(val != 'nothanks' && !$.bell.isEmpty(dataMap)){
					var featuresList = dataMap[currentState.ratePlanSku];
					
					if (!$.bell.isEmpty(featuresList)) {
					
						var index = jQuery.inArray(val, featuresList);
				    	if (index >= 0){
				    		$.bell.enable($this.parent(), "capDisabled"); 
					    }
					    else{				
							$.bell.disable($this.parent(), "capDisabled");
						}
					}
				}
		
			});
		}
		/*else
		{
			//Loop in each long distance div to disable it
			$("input[id*=itemLongDistanceStep-]", $mapObj).each(function(){
				var $this = $(this);
				var val = $this.val();
		
				if(val != 'nothanks'){
					$.bell.disable($this.parent(), "capDisabled");
				}
		
			});		
			
			//Reset all long distance div to no thanks by default
			for (var idxReset in getDataStoreObject(dataStoreTypeLongDistance,false)) {
				var value = getDataStoreObject(dataStoreTypeLongDistance,false)[idxReset];			
	
				var $select = $("#itemLongDistanceStep-nothanks-"+value.categoryProductSku);
				if($select.length){	
					var relIndex = $select.attr("relIndex");
					$("#templateLongDistanceStepBuilder-"+relIndex).removeAttr("relLast");
					$.bell.setElementActive($select,"#mapLongDistanceStep .longDistanceStepLine"+value.categoryProductSku+"Js","ted");
					$select.attr('checked','checked');
				}
			}				
		}*/
	
	}
	
	/***********************************************************************************************************************
	 * OtherServicesStepBuilder events
	 ***********************************************************************************************************************/	
	
	function otherServicesStepBuilder()
	{
		var $otherServicesStepObj = $("#OtherServicesStep");
		
		if (!$.bell.isEmpty(currentState))
		{

    		showStep($otherServicesStepObj);
    		
			if (currentState.blundleElegible == true)
			{
				enableBellService(true);
				//Check the other services selected
				if(!$.bell.isEmpty(currentState.otherServices))
				{
					for (var idx in currentState.otherServices) {
						var value = currentState.otherServices[idx];			
						$('#bell_service_'+value).attr('checked','checked');			
					};
				}
			}
			else
			{
				enableBellService(false);
			}  
			
			if($otherServicesStepObj.length){
				//Bind radio click events
				$("input[id*=itemServices]",$otherServicesStepObj).unbind('click').click(function() {			    		
	    			var $this = $(this);
	    			var value = $this.val();
	    			revertState = JSON.clone(currentState);
	    			
					currentState.blundleElegible = value;
					enableBellService(value);
					currentState.otherServices = [];
					currentState.actionJS = "step7update";
					ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);
					tracker(ajaxComponentI18n.teamsiteBundles.other_services_step_title_label,'7');
					
					return true; 
				});	
				
				//Bind check box change events
				$("input[id*=bell_service_]",$otherServicesStepObj).click(function() {
				
					//Check if service exist in the array
					var $this = $(this);
					var value = $this.val();
					revertState = JSON.clone(currentState);
					
					if($this.attr("checked")){
				    	var index = jQuery.inArray(value,currentState.otherServices);
				    	if (index < 0){
				    		currentState.otherServices.push(value);
					    }	
				    }else{
				    	var index = jQuery.inArray(value,currentState.otherServices);
				    	if (index >= 0){
				    		currentState.otherServices.splice(index,1);
					    }				    
				    }	
					currentState.actionJS = "step7update";
					ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);
					tracker(ajaxComponentI18n.teamsiteBundles.other_services_step_title_label,'7');
			
				});				
			}
		}
		
	
	}
	
	function enableBellService(value)
	{
		if (eval(value) == true)
		{
			$('#itemServicesYes').attr('checked','checked').parents(".capsule:first").addClass("capSelected");
			$('#itemServicesNo').parents(".capsule:first").removeClass("capSelected");

			$('#bell_service_wireline').removeAttr("disabled").removeAttr("checked");
			$('#bell_service_internet').removeAttr("disabled").removeAttr("checked");
			$('#bell_service_television').removeAttr("disabled").removeAttr("checked");		
		}
		else
		{
			$('#itemServicesYes').parents(".capsule:first").removeClass("capSelected");
			$('#itemServicesNo').attr('checked','checked').parents(".capsule:first").addClass("capSelected");

			$('#bell_service_wireline').attr("disabled","disabled").removeAttr("checked");
			$('#bell_service_internet').attr("disabled","disabled").removeAttr("checked");
			$('#bell_service_television').attr("disabled","disabled").removeAttr("checked");
		}
	}	

	/***********************************************************************************************************************
	 * WirelessSolutionStepsBuilderComponent Ajax events
	 ***********************************************************************************************************************/

	WirelessSolutionStepsBuilderComponent.prototype = new GenericSolutionsBuilderComponent();

	WirelessSolutionStepsBuilderComponent.prototype.initialize = function() 
	{
		this.ajaxHandlerName  = ajaxHandlerName;
	}

	function WirelessSolutionStepsBuilderComponent(id) 
	{
		this.timeout = OperationTimeout;
		this.persistenceKey = 'WirelessSolutionBuilderComponentKey';
		BaseAjaxComponent.apply(this, arguments);
	}
	
	function handleLoadMain(currentStateObj, html, newComponents) 
	{	
		
		if (!$.bell.isEmpty(currentStateObj))
		{
			//Keep the updated solution
			handleLoad(currentStateObj);
		}	
				
	}
	
	function handleLoad(currentStateObj){
			var $ratePlansStepObj = $("#RatePlansStep");
			var $planCategoriesStepObj = $("#PlanCategoriesStep");			
		    var $bundlesStepObj = $("#BundlesStep");
		    var $otherServicesStepObj = $("#OtherServicesStep");
		    var $featuresStepObj = $("#FeaturesStep");
		    var $accessoriesStepObj = $("#AccessoriesStep");
		    var $longDistanceStepObj = $("#LongDistanceStep");
			currentState = currentStateObj;
			resetForm();
			
			//Comming with preselect cell phone
			if ($.bell.isEmpty(currentStateObj.cellPhoneSku) && $.bell.isEmpty(currentStateObj.ratePlanSku))
			{		
				renderChooseCellPhone();
				planCategoriesStepBuilder();
				
   				var category = $("input[id*=itemPlanCategoriesStep_]:checked", $("#mapPlanCategoriesStep")).val();
   				dimIncompatiblePhones(category);					
			}
			//Comming with preselect rate plan
			else if ($.bell.isEmpty(currentStateObj.cellPhoneSku) && !$.bell.isEmpty(currentStateObj.ratePlanSku))
			{
				renderChooseCellPhone();
				planCategoriesStepBuilder();
				ratePlansStepBuilder(currentStateObj.ratePlanPage,'true');
				
   				var category = $("input[id*=itemPlanCategoriesStep_]:checked", $("#mapPlanCategoriesStep")).val();
   				dimIncompatiblePhones(category);					
			}
			else
			{
				if(currentState.contractTermSku == grabAndGoTermSku)
				{
					cellPhoneDetailBuilder();
				
					hideStep($planCategoriesStepObj);
					hideStep($ratePlansStepObj);
					hideStep($bundlesStepObj);
					hideStep($featuresStepObj);
					hideStep($longDistanceStepObj);
					
					accessoriesStepBuilder();					
					otherServicesStepBuilder();			
				}
				else
				{			
					cellPhoneDetailBuilder();
					planCategoriesStepBuilder();
					
					if (!$.bell.isEmpty(currentStateObj.ratePlanCategorySku))
					{
						ratePlansStepBuilder(currentStateObj.ratePlanPage,'true');
						
						if(internetRatePlansSku == currentStateObj.ratePlanCategorySku){
						
							hideStep($bundlesStepObj);
							// CR 10926 - allow features for mobile internet plans and devices
							featuresStepBuilder();
							//hideStep($featuresStepObj);
							hideStep($accessoriesStepObj);
							hideStep($longDistanceStepObj);
							otherServicesStepBuilder();

						}
						else
						{
							featuresStepBuilder();
							accessoriesStepBuilder();
							longDistanceStepBuilder();			
						
		    				if(prepaidRatePlansSku == currentStateObj.ratePlanCategorySku){
								hideStep($bundlesStepObj);
							}
							else
							{
								bundlesStepBuilder(currentStateObj.bundlePage);
							}
								
							if(prepaidRatePlansSku != currentStateObj.ratePlanCategorySku){	
								longDistanceStepBuilder();					
							}
							else
							{
								hideStep($longDistanceStepObj);
							}
							
							otherServicesStepBuilder();	
						}
						
					}
									
				}			
			}
			ajaxLoader("hide","loadSolution");
	}
	
	function loadSolution(solutionId){
		ajaxLoader("show","loadSolution");	
		ajaxComponent('#WirelessSolutionSteps').callAjaxAction('loadSolution',{solutionId:solutionId});	
	}
	
	/***********************************************************************************************************************
	 * SolutionBoxComponent Ajax events
	 ***********************************************************************************************************************/
	
	SolutionBoxComponent.prototype = new GenericSolutionsBuilderComponent();
	
	SolutionBoxComponent.prototype.initialize = function() 
	{
		this.ajaxHandlerName  = ajaxHandlerName;
	}	
	
	function SolutionBoxComponent(id) {
		this.timeout = OperationTimeout;
		BaseAjaxComponent.apply(this, arguments);
		
	}
	
	SolutionBoxComponent.prototype.goToCart = function(handlerName, actionName) 
	{
		this.callAjaxActionWithHandlerName(handlerName, actionName);
	}	

	//Receive data from AJAX update the solution box
	SolutionBoxComponent.prototype.update = function(data, html, newComponents) 
	{
		if (html) 
		{
			//Load the solution box html
			var sbDom = this.getDom();
			var sdDomDiv = $("#"+sbDom.id);
			sdDomDiv.html(html);
			$.bell.sBuilder.render();
			$.pageRender("#cSummary","summaryBox");
		}

		if (!$.bell.isEmpty(data)) {
        	
        	//enable or disable the add to cart button
		    if (data["isValidAddToCart"]) {
		    	$.bell.sBuilder.enable();
		    	toggleSolutionBoxUserActions(true);
		    	$("#addToCartButton").unbind("click").click(function() {		    		
		    		window.location.href='/shopping/PrsShpWls_Solution_Builder_Summary.page';
		    		return false;
		    	});
	    	}
		    else {
		    	$.bell.sBuilder.disable();
		    	toggleSolutionBoxUserActions(false);
		    }    
		    
		    //Events on the clear solutions button
		    if (data["hasSolutions"]) {
	        	$("#clearSolutionBoxButton").unbind("click").bind("click", clearSolutionBoxContent);
	    	}
		    else {
	        	$("#clearSolutionBoxButton").unbind("click").click(function() {return false;});
		    }

		    if (!$.bell.isEmpty(data["currentState"]) && !$.bell.isEmpty(currentState)) {
		    	if(data["currentState"].prepopId == null)data["currentState"].prepopId = "";
		    	if(currentState.prepopId == null)currentState.prepopId = "";
		    	
		    		var prevPopId ="";
		    		
		    		if ( lastprepopId != undefined && lastprepopId != null) { 
		    			prevPopId	= lastprepopId	;
		    			lastprepopId	= null		;
		    		}
		    		else
		    			prevPopId	= currentState.prepopId	;
				if(data["currentState"].prepopId !== prevPopId){
					data["currentState"] = setRatePlanPage(data["currentState"]);
					if($.bell.isEmpty(data["currentState"].prepopId)){
						prepopPromoBuilder(currentState.contractTermSku);
					}
					handleLoad(data["currentState"]);						
				}	
			}
			
			if (!$.bell.isEmpty(data["currentState"])){
				if(!$.bell.isEmpty(data["currentState"].bogoRewardFlexPricingIds) && data["currentState"].askedBogoReward == false){
				
					//show a pop up confirmation before removing it
					var $yesnoPopupJsObj = $("#yesnoPopupJs");
					$(".lightBoxTitleJs", $yesnoPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.bogo_eligibility_popup_title_label);
					$(".yesnoTxtJS", $yesnoPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.bogo_eligibility_popup_block);										
					$(".btnDftAct", $yesnoPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.bogo_select_phone_label);
					$(".btnAltAct", $yesnoPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.bogo_no_thanks_label);
					$.pageRender($yesnoPopupJsObj, "lightBox");	

					$.lightBox.showInPage($yesnoPopupJsObj,{modal:false}, function(objLightBox) {
						//find "yes" button
						$(".btnDftAct", objLightBox).unbind('click').click(function() {
							$.lightBox.hide();
							ajaxLoader("show","phoneSolutionsBuilder");	
							currentState.askedBogoReward = true;
							ajaxComponent('#WirelessSolutionSteps').callAjaxAction('bogoEligibility',{});
							return false;					
						});
						//find "no" button
						$(".btnAltAct", objLightBox).unbind('click').click(function() {
							$.lightBox.hide();
							currentState.askedBogoReward = true;
							ajaxComponent('#WirelessSolutionSteps').callAjaxAction('checkCurrentState',currentState);
							return false;					
						});						
					});				
				
				}				
			}
			
		}
	}
	
	
	function clearSolutionBoxContent() {
	
		//Show the pop up for the clear solutions button
		var $yesnoPopupJsObj = $("#yesnoPopupJs");
		$(".lightBoxTitleJs", $yesnoPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.clear_popup_title_label);
		$(".yesnoTxtJS", $yesnoPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.clear_popup_block);				
		$(".btnDftAct", $yesnoPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.confirm_label);
		$(".btnAltAct", $yesnoPopupJsObj).html(ajaxComponentI18n.teamsiteBundles.cancel_label);
		$.pageRender($yesnoPopupJsObj, "lightBox");	
		
		$.lightBox.showInPage($yesnoPopupJsObj,{modal:false}, function(objLightBox) {
			//find "yes" button
			$(".btnDftAct", objLightBox).unbind('click').click(function() {				
				$.lightBox.hide();
				ajaxLoader("show","phoneSolutionsBuilder");	
				currentState = null;
				window.setClearAddTimer = setTimeout(function() {
					ajaxComponent('#summaryBox').callAjaxAction('clearSolutionBox');
					resetForm();
					$.bell.sBuilder.unExpand();
					planCategoriesStepBuilder();
					renderChooseCellPhone();				
					clearTimeout(window.setClearAddTimer);
				},10);					
			});
		});	
		
	}
		

	/***********************************************************************************************************************
	 * Standard
	 ***********************************************************************************************************************/
	
	function setRatePlanPage(currentStateObj){
		var ratePlans = getDataStoreObject(dataStoreTypeRatePlans,false);
			for (var idxCat in ratePlans) {
				var pagerList = ratePlans[idxCat];	
				
				for (var idxPager in pagerList) {
				
					if(idxPager.indexOf("page_") != -1){
						var itemsList = pagerList[idxPager];
						
						for (var idxItem in itemsList) {
							var item = itemsList[idxItem];
							if(item.productSku == currentStateObj.ratePlanSku){
							
								var lastIndex = idxPager.lastIndexOf("_");
								var idxPager = idxPager.substring(++lastIndex);
								
								currentStateObj.ratePlanPage = idxPager;
								break;						
							}
						}
					}
					if (!$.bell.isEmpty(currentStateObj.ratePlanPage))
					{
						break;
					}					
				}
				if (!$.bell.isEmpty(currentStateObj.ratePlanPage))
				{
					break;
				}								
			}
		return currentStateObj;
	}
	
	
	function resetForm()
	{
		var $bundlesStepObj = $("#BundlesStep");
		var $prepopStepObj = $("#PrepopPromoContent");
	    var $ratePlansStepObj = $("#RatePlansStep");
		var $planCategoriesStepObj = $("#PlanCategoriesStep");
		var $cellPhoneDetailsStepObj = $("#CellPhoneDetailsStep");
		var $chooseCellPhoneStepObj = $("#ChooseCellPhoneStep");
		var $otherServicesStepObj = $("#OtherServicesStep");
		var $featuresStepObj = $("#FeaturesStep");
		var $accessoriesStepObj = $("#AccessoriesStep");
		var $longDistanceStepObj = $("#LongDistanceStep");
		
		if (!$chooseCellPhoneStepObj.hasClass("hide")) {
			dimIncompatiblePhones(null);
			$chooseCellPhoneStepObj.addClass("hide");
		}
		
		if (!$cellPhoneDetailsStepObj.hasClass("hide")) {
			$cellPhoneDetailsStepObj.addClass("hide");
		}
		$prepopStepObj.addClass("hide");
		hideStep($planCategoriesStepObj);
		hideStep($ratePlansStepObj);
		hideStep($bundlesStepObj);
		hideStep($featuresStepObj);
		hideStep($accessoriesStepObj);
		hideStep($longDistanceStepObj);
		hideStep($otherServicesStepObj); 	
	}
	
	
	function renderChooseCellPhone()
	{
		//Only show the loaded cell phone scrollers
	    var $chooseCellPhoneStepObj = $("#ChooseCellPhoneStep");	
	
		if($("#mapChoosePhones").length == 0 || 
				(!$.bell.isEmpty(currentState) && $chooseCellPhoneStepObj.attr("rel") == 'bogolist' && $.bell.isEmpty(currentState.parentSolutionIdLinked)) ||
				(!$.bell.isEmpty(currentState) && $.bell.isEmpty($chooseCellPhoneStepObj.attr("rel")) && !$.bell.isEmpty(currentState.parentSolutionIdLinked)))
		{
			var dataPhoneList;
			if(!$.bell.isEmpty(currentState) && !$.bell.isEmpty(currentState.parentSolutionIdLinked) && !$.bell.isEmpty(currentState.bogoRewardFlexPricingIds)){
			
				var isResetNeeded = false;
				if($.bell.isEmpty(currentBOGOPromotionDataStore) || !bogoFlexPricingsIdentical(currentBOGOPromotionDataStore["bogoRewardFlexPricingIds"], currentState.bogoRewardFlexPricingIds)){
					isResetNeeded = true;
				}
			
				dataPhoneList = getCellDataStoreObject(dataStoreTypeBOGOPromotion,0,currentState,isResetNeeded);		
				dataPhoneList = dataPhoneList["cellPhonesMap"];
				$chooseCellPhoneStepObj.attr("rel","bogolist");
			}else{
				dataPhoneList = getDataStoreObject(dataStoreTypeCellPhonesList,false);
				$chooseCellPhoneStepObj.removeAttr("rel");
			}		
		
			var category = $(".cTabs",$chooseCellPhoneStepObj).find(".active").attr("rel");
			var dataDetailsList = dataPhoneList[category];
			if ($.bell.isEmpty(dataDetailsList)) {
				for (var idxCat in dataPhoneList) {
					dataDetailsList = dataPhoneList[idxCat];
					if (!$.bell.isEmpty(dataDetailsList))
					{
						category = idxCat;
						$.bell.setElementActive($(".cTabs",$chooseCellPhoneStepObj).find("."+category+"Js"), "#ChooseCellPhoneStep .pkgToggleItemJs", "active");
						break;
					}				
				}	
			}			
			
			chooseCellPhoneStepBuilder(category);
		}	
	
		if ($chooseCellPhoneStepObj.hasClass("hide")) {
			$chooseCellPhoneStepObj.removeClass("hide");
		}
			
		// initialize the scroller
		$chooseCellPhoneStepObj.scroller({fillSpace:false, toggle: true, itemsContainer: "#mapChoosePhones"});
	}
	
	var loaderKey;
	var loaderVisible;
	function ajaxLoader(action,key){
		
		//The way that it works is the key that show the loader is the key to hide it.
		//The loader is kept between all steps, even if another step is trying to hide the loader.
		if(!loaderVisible && action == 'show'){
			loaderKey = key;
			loaderVisible = true;
			$.ajaxLoader.show({modal:true});
			setLoaderTimeout();
		}
		
		if(loaderVisible && action == 'hide' && loaderKey == key){
			clearLoaderTimeout();
			loaderVisible = false;
			$.ajaxLoader.hide();
		}
			
	}
	
	//Cloning method
	JSON.clone = function (obj) {
	  return JSON.parse( JSON.stringify( obj ) );
	};	
	
	
	function getDataStoreObject(objType, isasync){
	
		if (objType == dataStoreTypeCellPhonesList)
		{
			if($.bell.isEmpty(cellPhonesListDataStore)){
				$.ajax({url: dataStoreLink + dataStoreTypeCellPhonesList + langAndRegionParam, dataType:'json',cache:'false', success:function(data, textStatus){			
					cellPhonesListDataStore = data;				
				}, async:isasync});
			}
			return cellPhonesListDataStore;			
		}
		
		if (objType == dataStoreTypeBundles)
		{
			if($.bell.isEmpty(bundlesDataStore)){
				$.ajax({url: dataStoreLink + dataStoreTypeBundles + langAndRegionParam, dataType:'json',cache:'false', success:function(data, textStatus){
					bundlesDataStore = data;				
				}, async:isasync});		
			}
			return bundlesDataStore;
		}
		
		if (objType == dataStoreTypeFeatures)
		{
			if($.bell.isEmpty(featuresDataStore)){
				$.ajax({url: dataStoreLink + dataStoreTypeFeatures + langAndRegionParam, dataType:'json',cache:'false', success:function(data, textStatus){
					featuresDataStore = data;				
				}, async:isasync});	
			}
			return	featuresDataStore;
		}
		
		if (objType == dataStoreTypeRatePlans)
		{
			if($.bell.isEmpty(ratePlansDataStore)){
				$.ajax({url: dataStoreLink + dataStoreTypeRatePlans + langAndRegionParam, dataType:'json',cache:'false', success:function(data, textStatus){
					ratePlansDataStore = data;				
				}, async:isasync});	
			}
			return	ratePlansDataStore;
		}
		
		if (objType == dataStoreTypeRatePlanCategories)
		{
			if($.bell.isEmpty(ratePlanCategoriesDataStore)){
				$.ajax({url: dataStoreLink + dataStoreTypeRatePlanCategories + langAndRegionParam, dataType:'json',cache:'false', success:function(data, textStatus){
					ratePlanCategoriesDataStore = data;				
				}, async:isasync});	
			}
			return	ratePlanCategoriesDataStore;
		}
		
		if (objType == dataStoreTypeLongDistance)
		{
			if($.bell.isEmpty(longDistanceDataStore)){
				$.ajax({url: dataStoreLink + dataStoreTypeLongDistance + langAndRegionParam, dataType:'json',cache:'false', success:function(data, textStatus){
					longDistanceDataStore = data;				
				}, async:isasync});			
			}
			return longDistanceDataStore;
		}	
		
		if (objType == dataStoreTypePreload)
		{
			$.ajax({url: dataStoreLink + dataStoreTypePreload + langAndRegionParam, dataType:'json',cache:'false', success:function(data, textStatus){
				//Do nothing			
			}, async:isasync});			
		}										

	}

	function getCellDataStoreObject(objType, sku, currentState, reset){
	
		var bogoParams = "";
		if (!$.bell.isEmpty(currentState) && !$.bell.isEmpty(currentState.parentSolutionIdLinked) && !$.bell.isEmpty(currentState.bogoRewardFlexPricingIds)) {
			var bogoFLEXIDs = currentState.bogoRewardFlexPricingIds;
			for (var i in bogoFLEXIDs) {
				bogoParams += "&" + dataStoreParamBOGOFLEXID + "=" + bogoFLEXIDs[i];
			}
		}
	
		if (objType == dataStoreTypeCellPhoneDetails)
		{	
			if($.bell.isEmpty(currentCellPhoneDetailsDataStore) || reset){
					$.ajax({url: dataStoreLink + dataStoreTypeCellPhoneDetails +"&"+ dataStoreParamSku +"="+sku + bogoParams + langAndRegionParam, dataType:'json',cache:'false', success:function(data, textStatus){
					currentCellPhoneDetailsDataStore = data;				
					}, async:false});				
			}
			return currentCellPhoneDetailsDataStore;
		}	
		
		if (objType == dataStoreTypeSubCellPhoneDetails)
		{
			if($.bell.isEmpty(currentSubCellPhoneDetailsDataStore) || reset){
				$.ajax({url: dataStoreLink + dataStoreTypeSubCellPhoneDetails +"&"+ dataStoreParamSku +"="+sku + bogoParams + langAndRegionParam, dataType:'json',cache:'false', success:function(data, textStatus){
					currentSubCellPhoneDetailsDataStore = data;				
				}, async:false});
			}
			return currentSubCellPhoneDetailsDataStore;
		}
		
		if (objType == dataStoreTypeBOGOPromotion)
		{
			if($.bell.isEmpty(currentBOGOPromotionDataStore) || reset){
				$.ajax({url: dataStoreLink + dataStoreTypeBOGOPromotion + bogoParams + langAndRegionParam, dataType:'json',cache:'false', success:function(data, textStatus){
					currentBOGOPromotionDataStore = data;				
				}, async:false});
			}
			return currentBOGOPromotionDataStore;
		}
		
		if (objType == '')
		{
		    var dataDetails;
			$.ajax({url: dataStoreLink + dataStoreTypeCellPhoneDetails +"&"+ dataStoreParamSku +"="+sku + bogoParams + langAndRegionParam, dataType:'json',cache:'false', success:function(data, textStatus){
				dataDetails = data;				
			}, async:false});				
			
			return dataDetails;
		}			
	
	}	
	
	function showTimeoutLightBox(){
		var $timeoutPopup = $("#timeoutPopupJs");
		
		$.lightBox.showInPage($timeoutPopup,{modal:true}, function(objLightBox) {
			//find "yes" button
			$(".timeoutYesJs", objLightBox).unbind('click').click(function() {
				$.lightBox.hide();
				window.location.href = timeoutRedirectUrl;					
				return false;
			});
			
			//find "no" button
			$(".timeoutNoJs", objLightBox).unbind('click').click(function() {
				$.lightBox.hide();
				setLoaderTimeout();					
				return false;
			});
		});
	}
	
	function setLoaderTimeout(){
		if(loaderVisible){
			window.setElementActiveTimer = setTimeout(function() {
					showTimeoutLightBox();
					clearLoaderTimeout();
	            },loaderTimeout);
    	}
	}
	
	function clearLoaderTimeout(){
		clearTimeout(window.setElementActiveTimer);
	}
			
	function toggleSolutionBoxUserActions(enable){
		if (enable) {
			$("#emailPrintPdfId").show();
			$("#emailPrintPdfTextId").hide();
		} else {
			$("#emailPrintPdfId").hide();
			$("#emailPrintPdfTextId").show();
		}
	}
	
	function showStep($stepObj){
		if($.bell.sBuilder.stepManager.isCollapsed($stepObj)){
			$.bell.sBuilder.stepManager.show($stepObj);
		}
	}
	
	function hideStep($stepObj){
		if(!$.bell.sBuilder.stepManager.isCollapsed($stepObj)){
			$.bell.sBuilder.stepManager.hide($stepObj);
		}
	}
	
	function tracker(title,step){
	  $.bell.external.tracker({
	    appName:"lp",
	    actionName:"solutionBuilder",
	    data: {
	      stepNumber: "Wls-SB-"+step,
	      stepName: title
	    }
	  });

	}
	
	function bogoFlexPricingsIdentical(list1, list2) {
		var size1 = $.bell.isEmpty(list1) ? 0 : list1.length;
		var size2 = $.bell.isEmpty(list2) ? 0 : list2.length;
		if (size1 == size2) {
			if (size1 > 0) {
				var lookup = {};
				var matches = 0;
				for (var j in list2) {
					lookup[list2[j]] = list2[j];
				}
				for (var i in list1) {
					if (typeof lookup[list1[i]] != 'undefined') {
						matches++;
					}
				}
				return (size1 == matches);
			}
			else {
				return true;
			}
		}
		else {
			return false;
		}
	}
	
	function getBogoFlexIdsParams(currentState){
	
		var bogoParams = "";
		if (!$.bell.isEmpty(currentState) && !$.bell.isEmpty(currentState.parentSolutionIdLinked) && !$.bell.isEmpty(currentState.bogoRewardFlexPricingIds)) {
			var bogoFLEXIDs = currentState.bogoRewardFlexPricingIds;
			for (var i in bogoFLEXIDs) {
				bogoParams += "&" + flexPricingIdParameter + "=" + bogoFLEXIDs[i];
			}
		}
		return bogoParams;
	}
					


	PrintToPdfClass.prototype = new GenericSolutionsBuilderComponent();

	function  PrintToPdfClass(id)
	{
		this.timeout = 60 * 60 * 1000;
		BaseAjaxComponent.apply(this, arguments);
	}

	PrintToPdfClass.prototype.initialize = function() 
	{
		this.ajaxHandlerName  = ajaxHandlerName;
	}
	
	PrintToPdfClass.prototype.update = function(data, html, newComponents) 
	{
		if (!$.bell.isEmpty(html))
		{
			printOrGenerate(html);
		}
	}	
		

			
