/**
 * File version 1.2
 */
var internetSolutionBuilderJSON = {};
var servicesStepTitle = "";
var isbInitialized = false;
var dslIndex = 0;
var disableDSL = false;

var subscribed = new  Array();

//CR 11536 - display installation step header at all times
var isLoggedIn = false;
var isServiceSubscribed = false;
var isSubscribedTo = "";
//Introduced for IHG changes  fix for Bug#2532
var customerHasIHGModem = false;
/*******************************************************
 * AJAX framework code
 ******************************************************/
/**
 * internetSolutionBuilderComponent
 */
internetSolutionBuilderComponent.prototype = new BaseAjaxComponent();

function internetSolutionBuilderComponent(id) {
    BaseAjaxComponent.apply(this, arguments);
    this.ajaxHandlerName = 'InternetSolutionHandler';
    this.timeout = (5 * 60 * 1000); // 5 minutes
    this.persistenceKey = "InternetSolutionBuilderKey";
    $.bell.sBuilder.stepManager.hide("#step2, #step3, #step4, #stepInstallations");
}

internetSolutionBuilderComponent.prototype.ajaxCallStarted = function() {
    BaseAjaxComponent.prototype.ajaxCallStarted.call(this);
    $.ajaxLoader.show();
};


internetSolutionBuilderComponent.prototype.ajaxCallFinished = function() {
    BaseAjaxComponent.prototype.ajaxCallFinished.call(this);
    $.ajaxLoader.hide();
};

internetSolutionBuilderComponent.prototype.update = function(data, html, newComponent) {
    var events = [];
	
	if (data.upSpeedQualificationSuccess && data.upSpeedQualificationSuccess === true) {
		events.push({type: "upSpeedQualificationSuccess"});
	}

	if (data.upSpeedQualificationNegative && data.upSpeedQualificationNegative === true) {
		events.push({type: "upSpeedQualificationNegative"});
	}
       //IHG Changes Fix for QC Bug#2532 assign the value of customerHasIHGModem
        if(data&&data.customerHasIHGModem){
	     customerHasIHGModem = data.customerHasIHGModem;
        }
    if (data.availableServices) {
        data.availableServices.sort(function(a,b) {
            return (a.categoryID < b.categoryID) ? -1 : (a.categoryID > b.categoryID) ? 1 : 0;
        });
        events.push({type:"availableservcies",
            services: data.availableServices,
            vases: data.availableVAS,
            availabilityState: data.checkState,
            customerFound: data.customerFound,
            switchFlag: switchFlag});
        $("#clearSolutionBoxButton").unbind("click");
        
    } else {
        internetSolutionBuilderJSON = data;
        if (data.userForm && data.userForm.actionName == 'begin') {
            isbInitialized = true;
        }

        if (data.userForm && data.userForm != null) {
            events.push({type:"installation",
                         defaultInstallationType: data.defaultInstallationType,
                         installationTypesMap: data.installationTypesMap});

            events.push({type:"defSelection", selection: data.userForm});

            if (data.prices && data.prices != null) {
                events.push({type:"prices", prices: data.prices});
            }

            if (data.serviceVasUnavailable && data.serviceVasUnavailable === true) {
                events.push({type: "serviceUnavailable"});
            }
        }

        if (html) {
            var sbDom = $("#cSummary");
            $("#isbContent", sbDom).html(html);
            if (data.addToCartEnabled === true) {
                $("#addToCartButton").bind("click", function (event) {
                    ajaxComponent('#step2').callAjaxAction('addToCart');
                });
                $.bell.sBuilder.enable();
            } else {
                $("#addToCartButton").unbind("click");
                $.bell.sBuilder.disable();
            }
            $("#clearSolutionBoxButton").bind("click", function (event) {
                $.lightBox.showInPage("#clearSolutionBuilderLightBox", {modal:true});
            });
            $.pageRender(sbDom);
        }
    }
    var step2           = $("#step2");
    var step3           = $("#step3");
    var step4           = $("#step4");
    var stepInstalation = $("#stepInstallations");

    for (var i = 0; i < events.length; i++) {
        $(step2).trigger(events[i]);
        $(step3).trigger(events[i]);
        $(step4).trigger(events[i]);
        $(stepInstalation).trigger(events[i]);
    }
	
	// FTTH 
	if(disableDSL && data.networkType != null && data.networkType == "FTTH") {
		$("#services-category-id-"+dslIndex+" > h3").append(" - " + ajaxComponentI18n.message["solutionbuilder.ftth.msg"]);
		$("#services-category-id-"+dslIndex+" > fieldset > div > input").attr("checked", false);
		$("#services-category-id-"+dslIndex+" > fieldset > div > input").attr('disabled', true);
	}
	
	if(data.networkType != null && data.networkType == "FTTH" && data.b1Accounts.length > 0) {
		$("#vasContent").find("input").attr("checked", false);
		$("#vasContent").find("input").attr('disabled', true);
	}

};

internetSolutionBuilderComponent.prototype.validationError = function(validationErrors) {

    var isMutualExclusive = (validationErrors['sku'] == 'shopping.internet.error.solutionbuilder.mutualexclusive');
    var event = {type:"validationError", isMutualExclusive: isMutualExclusive};
    $("#step2").trigger(event);
    $("#step3").trigger(event);
    $("#step4").trigger(event);
    $("#stepInstallations").trigger(event);
    $("#cSummary").trigger(event);
};

internetSolutionBuilderComponent.prototype.userError = function(errorString, exception) {
    if (errorString == "handler.not.initialized") {
        window.location.href = "/";
    } else {
        var event = {type:"userError", errorString: errorString, exception: exception};
        $("#step2").trigger(event);
        $("#step3").trigger(event);
        $("#step4").trigger(event);
        $("#stepInstallations").trigger(event);
        $("#cSummary").trigger(event);
    }

};

internetSolutionBuilderComponent.prototype.systemError = function(errorString) {
    var event = {type:"systemError", errorString: errorString};
    $("#step2").trigger(event);
    $("#step3").trigger(event);
    $("#step4").trigger(event);
    $("#stepInstallations").trigger(event);
    $("#cSummary").trigger(event);
};

function generateJSONObject(availabilityDataReloaded) {
    var step2Dom = $("#step2");
    var step3Dom = $("#step3");

    var checkedServiceInput = $("input[name='internet-service-sku']:checked", step2Dom);
    var serviceGroupSku = $(checkedServiceInput).data("serviceGroupSku");
    var serviceGroupId  = $(checkedServiceInput).data("serviceGroupId");
    var serviceSku = $(checkedServiceInput).val();

    var includedFeatures = new Array();
    var optionalFeatures = new Array();
    var visibleServices = new Array();
    var visibleVASes = new Array();
    var hasServicesWithBell = $("#step4 input[name='existingCustomer']:checked").val();
    var lobs = new Array();
    var preselectServiceVas = "";
    var uploadSpeedSelected = false;

    $("input[name='internet-vas-sku-included']:checked", step3Dom).each(function() {
        includedFeatures.push($(this).val());
    });
    $("input[name='internet-vas-sku-optional']:checked", step3Dom).each(function() {
        optionalFeatures.push($(this).val());
    });
    $("input[name='internet-service-sku']:gt(0)", step2Dom).each(function() {
        visibleServices.push($(this).val());
    });
    $("input[name^='internet-vas-sku']:gt(0)", step3Dom).each(function() {
        visibleVASes.push($(this).val());
    });

    $("#existingCustomerSection input[name='lobs']:checked").each(function() {
        lobs.push($(this).val());
    });

    if (availabilityDataReloaded === true) {
        preselectServiceVas = $("#serviceSku").val();
    }

    var firstLoad = $("#firstLoad").val() === "true";
    $("#firstLoad").val(" ");

    var installationType = $("input[name='internetInstallationType']:checked").val();
    if (installationType != null && $.trim(installationType) == "") {
        installationType = null;
    }
	if(optionalFeatures!=null){
		for(var i=0;i<optionalFeatures.length;i++){
			if(optionalFeatures[i]!=null){
				if(optionalFeatures[i].indexOf('VasIntUPLSP')!=-1){
					uploadSpeedSelected = true;break;
				}
			}
		}
	}
    return {serviceGroupSku:       serviceGroupSku,
        packageSku:                 serviceSku,
        includedFeatures:          includedFeatures,
        optionalFeatures:          optionalFeatures,
        visibleServices:           visibleServices,
        visibleVas:                 visibleVASes,
        hasServices:                hasServicesWithBell,
        lobs:                        lobs,
        preselectServiceVas:       preselectServiceVas,
        firstLoad:                  firstLoad,
        availabilityDataReloaded: availabilityDataReloaded,
        installationType:			installationType,
        groupId:					serviceGroupId,
        uploadSpeedUpgradeSelected:  uploadSpeedSelected
    };
}

function loadInternetSolutionBuilder() {
    $.bell.sBuilder.stepManager.hide("#step2, #step3, #step4, #stepInstallations");
    bindStep2Handlers();
    bindStep3Handlers();
    bindStep4Handlers();
    bindInstalationsHandlers();
    bindSolutionSummary();
    servicesStepTitle = $("#step4 h2:first").text();
}

function bindStep2Handlers() {
    var step2 = $("#step2");
		$(step2).bind("upSpeedQualificationSuccess", function(event) {
			event.stopPropagation();
			$.lightBox.showInPage("#incompatibleUPSpeedFibes", {modal:false});
	
	});
	$(step2).bind("upSpeedQualificationNegative", function(event) {
			event.stopPropagation();
			$.lightBox.showInPage("#incompatibleUPSpeedQualification", {modal:false});
	});
	
    $(step2).bind("availableservcies", function(event) {
        event.stopPropagation();
        var availableServices = event.services;
        // allowing the QC customer to upgrade internet services
        var disableUpgrade = false;//event.switchFlag && event.customerFound === true && event.availabilityState.province == 'QC';
        var disableUpgradeContent = false;
        var showPOSOnly =  serviceAvailabilityJSON.userForm != null && serviceAvailabilityJSON.userForm.actionName == 'checkServiceByAddress';
        var foundCustomerServiceSku = false;

		//CR 11536 - display installation step header at all times
		isLoggedIn = event.availabilityState.loggedIn && event.customerFound;


        if (availableServices.length > 0) {
            var servCatTpl = $("#tpl-internet-service-category", step2).clone();
            var servIdTpl = $("#tpl-internet-service-id", step2).clone();

            // Don't you think it's sexiest selector here? :)
            $("#servicesContent > div:gt(0)", step2).remove();
            var holder = $("<div></div>");

            servCatTpl.removeAttr("id");
            servCatTpl.removeAttr("class");
            $("#tpl-internet-service-id", servCatTpl).remove();

            for (var i = 0; i < availableServices.length; i++) {
                var categoryService = availableServices[i];
                if (showPOSOnly && categoryService.categoryID != 'POS') {
                    continue;
                }
				
				if(categoryService.categoryID == "ENS") {
					dslIndex = i;
					disableDSL = true;
				}
				
                var categoryServiceHTML = $(servCatTpl).clone();
                var emptyCategory = true;
                $(categoryServiceHTML).attr("id", "services-category-id-" + i);

                $('> h3', categoryServiceHTML).text(categoryService.categoryName);
                for (var j = 0; j < categoryService.categoryMembers.length; j++) {
		        /*
                 * CR-9757: do not allow members of the service group Essential
                 * (sku staring with DSLTIEQC)
                 * to be purchasable online in the solution builder although    
                 * they are shown as available after psqt in the Internet Services
                 * Landing page. To be replaced by a backend solution that updates 
                 * the data object  
                */
                
         
		
                    var serviceHTML = $(servIdTpl).clone();
                    var childDiv = $("> div", serviceHTML).clone();
                    var inputName = $("> input", serviceHTML).attr("name");

                    if (disableUpgrade && categoryService.categoryMembers[j].customerSubscribed === true) {
                        var disabledDom = $("#disabledUpgrade");
                        var hiddenInput = $("> div > input", disabledDom);

                        $(hiddenInput).data("serviceGroupSku", categoryService.categoryID);
                        $(hiddenInput).data("serviceGroupId", categoryService.categoryMembers[j].groupId);
                        $(hiddenInput).data("features", categoryService.categoryMembers[j].features);
                        $(hiddenInput).data("subscribed", categoryService.categoryMembers[j].customerSubscribed);
                        $(hiddenInput).attr("name", inputName);
                        $(hiddenInput).attr("value", categoryService.categoryMembers[j].sku);
                        $(hiddenInput).attr("id", "internet-service-radio-id-" + i + "-" + j);
                        $(hiddenInput).attr("checked", 1);

                        continue;
                    }

                    emptyCategory = false;

                    $("> input", serviceHTML).remove();
                    $("> div", serviceHTML).remove();

                    $(serviceHTML).attr("id", "internet-service-id-" + i + "-" + j);

                    var radioInput;

					//CR 11536 - display installation step header at all times
					isServiceSubscribed =categoryService.categoryMembers[j].customerSubscribed;

                    if (categoryService.categoryMembers[j].customerSubscribed === true) {
                        radioInput = $("<input type='radio' name='" + inputName + "'checked='checked'/>");
                        $(serviceHTML).addClass("capSelected");
                        foundCustomerServiceSku = true;
						//CR 11536 - display installation step header at all times
                        isSubscribedTo = categoryService.categoryMembers[j].sku;

                    } else {
                        radioInput = $("<input type='radio' name='" + inputName + "'/>");
                    }

                    $(radioInput).data("serviceGroupSku", categoryService.categoryID);
                    $(radioInput).data("serviceGroupId", categoryService.categoryMembers[j].groupId);
                    $(radioInput).data("features", categoryService.categoryMembers[j].features);
                    $(radioInput).data("subscribed", categoryService.categoryMembers[j].customerSubscribed);
                    $(radioInput).attr("name", inputName);
                    $(radioInput).attr("value", categoryService.categoryMembers[j].sku);
                    $(radioInput).attr("id", "internet-service-radio-id-" + i + "-" + j);
                    if (categoryService.categoryMembers[j].future === true) {
                        $(radioInput).attr("disabled", "disabled");
                    } else {
                        $("> label > span:eq(2)", childDiv).remove();
                    }

                    if (disableUpgrade) {
                        $(radioInput).attr("disabled", "disabled");
                    }

                    $(radioInput).appendTo(serviceHTML);

                    $(radioInput).bind("click", function(event) {
						stepTracker(2);
                        $.bell.setElementActive(this, "#step2 .step2CapsuleJs",'capSelected');
                        var selectedVAS = [];
                        $("#step3 input[name='internet-vas-sku-optional']:checked").each(function() {
                            selectedVAS.push($(this).val());
                        });
                        updateStep3Vases($(this).data("features"), selectedVAS, true, false);
                        ajaxComponent('#step2').callAjaxAction('addRemoveItem', generateJSONObject(false));

                    });

                    $("> label", childDiv).attr("for", "internet-service-radio-id-" + i + "-" + j);

                    if (categoryService.categoryMembers[j].customerSubscribed === true) {
                        $("> label > span:eq(2)", childDiv).remove();
                    } else {
                        $("> label > span:eq(0)", childDiv).html(categoryService.categoryMembers[j].name);
                        $("> label > span:eq(1)", childDiv).attr("id", "sku-price-" + categoryService.categoryMembers[j].sku);
                        $("> p", childDiv).html(categoryService.categoryMembers[j].description);
                    }

                    $(childDiv).appendTo($(serviceHTML));
                    $(serviceHTML).appendTo($("> fieldset", categoryServiceHTML));
                    emptyCategory = false;
				               
			}

                if (!emptyCategory) {
                    $(categoryServiceHTML).appendTo($(holder));
                    disableUpgradeContent = true;
                }
            }


            $(holder).appendTo($("#servicesContent"));
            $.pageRender(step2);


            $.bell.sBuilder.stepManager.show("#step2");
            
            if (disableUpgrade) {
                $("#disabledUpgrade").show();
                if (disableUpgradeContent) {
                    $('#disabledUpgrade a.tglJs').show();                
                } else {
                    $('#disabledUpgrade a.tglJs').hide();                
                }
            } else {
                $("#disabledUpgrade").hide();
                $("#servicesContent").removeAttr("style");
                $("#servicesContent").show();
            }

            if (event.availabilityState.loggedIn && event.customerFound && !foundCustomerServiceSku) {
                $.lightBox.showInPage("#currentServiceUnavailableLB", {modal:false});
            }
        }
    });

    $(step2).bind("prices", function(event) {
        event.stopPropagation();
        $("input[name='internet-service-sku']:gt(0)", step2).each(function() {
            var sku = $(this).val();
            if (event.prices[sku]) {
                $("#sku-price-" + sku, step2).html(event.prices[sku]);
            }
        });
    });

    $(step2).bind("defSelection", function(event) {
        event.stopPropagation();
        if (event.selection.packageSku && event.selection.packageSku != null) {
            $("#step2 input[name='internet-service-sku']:[value='" + event.selection.packageSku + "']").attr("checked", 1);
        }
        if (event.selection.preselectServiceVas && event.selection.preselectServiceVas != null) {
            $("#step2 input[name='internet-service-sku']:[value='" + event.selection.preselectServiceVas + "']").attr("checked", 1);
        }
    });

    $(step2).bind("serviceUnavailable", function(event) {
        event.stopPropagation();
        $.lightBox.showInPage("#unavailableFeatureLB", {modal:false});
    });

    $(step2).bind("validationError", function(event) {
        event.stopPropagation();
        if (!event.isMutualExclusive) {
            $.bell.sBuilder.stepManager.hide("#step2");
        }

    });

    $(step2).bind("userError", function(event) {
        event.stopPropagation();
        $.bell.sBuilder.stepManager.hide("#step2");
    });

    $(step2).bind("systemError", function(event) {
        event.stopPropagation();
        $.bell.sBuilder.stepManager.hide("#step2");
    });
}

function bindStep3Handlers() {
    var step3 = $("#step3");
    $(step3).bind("availableservcies", function(event) {
        event.stopPropagation();
        var vases = event.vases;
        var selector = $("#step2 input[name='internet-service-sku']:checked");
        var preselectIncludedVas = false;
        if (selector.size() == 1) {
            vases = $(selector).data("features");
            preselectIncludedVas = true;
        }

        updateStep3Vases(vases, [], preselectIncludedVas, true);
    });

    $(step3).bind("prices", function(event) {
        event.stopPropagation();

        var floatPrices = {};
        for(var i in event.prices) {
            floatPrices[i] = parseFloat(event.prices[i].replace(/[^0-9\.]/g, ''));
        }
		// CR - 12737
		var checkBoxInputIds = new Array();
        var j = 0
        $("div[id^='internet-vas-id-'] > input", $("#step3")).each(function(i) {  
            var checkBoxId = $(this).attr('id');
           	if($('#'+ checkBoxId).attr("checked") == true) {
				 checkBoxInputIds[j] = checkBoxId;
				 j++;
			}
        });


        // Sort the VAS by price
        $("div[id^='vas-category-id-'] > fieldset", $("#step3")).each(function(i) {
            $(".capsule", $(this)).sort(function(a,b) {
                skuA = $(a).children("input").val();
                skuB = $(b).children("input").val();
                regDelta = floatPrices[skuA + "_reg"] - floatPrices[skuB + "_reg"];
                if(regDelta != 0)
                    return regDelta;
                else
                    return floatPrices[skuA + "_dis"] - floatPrices[skuB + "_dis"]
            }).appendTo($(this));
        });
        
        // CR - 12737 : fix the checkbox issue 
		for (var j = 0; j < checkBoxInputIds.length; j++) {
			$('#' + checkBoxInputIds[j]).attr("checked", "checked");
		}
		
		$("input[name^='internet-vas-sku']:gt(0)", step3).each(function() {
            
            var sku = $(this).val();
            var messageRegular  = "";
            var messageDiscount = "";
            if (event.prices[sku + "_reg"]) {
                messageRegular = event.prices[sku + "_reg"];
            }

            if (event.prices[sku + "_dis"]) {
                messageDiscount = event.prices[sku + "_dis"];
            }

            $("#vas-price1-" + sku).html(messageRegular);
			
			if (jQuery.inArray(sku, subscribed) > -1) { 
				$("#vas-price2-" + sku).html("");
			} else {
	            $("#vas-price2-" + sku).html(messageDiscount);
			}
        });
    });

    $(step3).bind("defSelection", function(event) {
        event.stopPropagation();
        var selector = $("#step2 input[name='internet-service-sku']:checked");
        if (selector.size() == 1) {
            var vases = $(selector).data("features");
            var preselectedOptionalVAS = [];
            if (event.selection.optionalFeatures && event.selection.optionalFeatures != null) {
                preselectedOptionalVAS = event.selection.optionalFeatures;
            }
            updateStep3Vases(vases, preselectedOptionalVAS, true, false);
        } else {
            if (event.selection.optionalFeatures && event.selection.optionalFeatures != null) {
                for (var l = 0; l < event.selection.optionalFeatures.length; l++) {
                    $("#step3 input[name^='internet-vas-sku']:[value='" + event.selection.optionalFeatures[l] + "']").attr("checked", 1);
                }
            }
        }

        if (event.selection.preselectServiceVas && event.selection.preselectServiceVas != null) {
            $("#step3 input[name^='internet-vas-sku']:[value='" + event.selection.preselectServiceVas + "']").attr("checked", 1);
        }

    });

    $(step3).bind("validationError", function(event) {
        event.stopPropagation();
        if (!event.isMutualExclusive) {
            $.bell.sBuilder.stepManager.hide("#step3");
        }
    });

    $(step3).bind("userError", function(event) {
        event.stopPropagation();
        $.bell.sBuilder.stepManager.hide("#step3");
    });

    $(step3).bind("systemError", function(event) {
        event.stopPropagation();
        $.bell.sBuilder.stepManager.hide("#step3");
    });

}

function bindStep4Handlers() {
    var step4 = $("#step4");
    $(step4).bind("availableservcies", function(event) {
        event.stopPropagation();
        $.bell.sBuilder.stepManager.hide("#step4");
        $("input[type='checkbox']", step4).each(function() {
            $(this).unbind("click");
        });
        ajaxComponent('#step2').callAjaxAction('begin', generateJSONObject(true));
    });

    $(step4).bind("prices", function(event) {
        event.stopPropagation();
        var emptyPrices = true;
        for (var p in event.prices) {
            emptyPrices = false;
            break;
        }

        if (!emptyPrices) {
            $.bell.sBuilder.stepManager.show("#step4");
            var addRemoveLob = function(event) {
				stepTracker(5);
                ajaxComponent('#step2').callAjaxAction('addRemoveItem', generateJSONObject(false));
            };
            $("input[type='checkbox']", step4).each(function() {
                $(this).bind("click", addRemoveLob);
            });
        } else {
            $.bell.sBuilder.stepManager.hide("#step4");
        }
    });

    $("input[type='radio']", step4).each(function() {
        $(this).bind("click", function() {
			stepTracker(5);
            $.bell.setElementActive(this, 'capsule', 'capSelected');
            if ($(this).val() == "true") {
                $("input[type='checkbox']", step4).each(function() {
                    $(this).removeAttr('disabled');
                });
            } else {
                $("input[type='checkbox']", step4).each(function() {
                    $(this).attr('disabled', true);
                });
            }
            ajaxComponent('#step2').callAjaxAction('addRemoveItem', generateJSONObject(false));
        });
    });

    $(step4).bind("defSelection", function(event) {
        event.stopPropagation();
        $("#step4 input[name='existingCustomer']:[value='" + event.selection.hasServices + "']").attr("checked", 1);
        if (event.selection.lobs && event.selection.lobs != null) {
            for (var k = 0; k < event.selection.lobs.length; k++) {
                $("#step4 input[name='lobs']:[value='" + event.selection.lobs[k] + "']").attr("checked", 1);
            }
        }
    });

    $(step4).bind("validationError", function(event) {
        event.stopPropagation();
        if (!event.isMutualExclusive) {
            $.bell.sBuilder.stepManager.hide("#step4");
        }
    });

    $(step4).bind("userError", function(event) {
        event.stopPropagation();
        $.bell.sBuilder.stepManager.hide("#step4");
    });

    $(step4).bind("systemError", function(event) {
        event.stopPropagation();
        $.bell.sBuilder.stepManager.hide("#step4");
    });

}

function bindSolutionSummary() {
    var sbDom = $("#cSummary");

    $(sbDom).bind("validationError", function(event) {
        event.stopPropagation();
        if (isbInitialized && !event.isMutualExclusive) {
            ajaxComponent('#step2').callAjaxAction('clearSolutionBox');
        }
    });

    $(sbDom).bind("userError", function(event) {
        event.stopPropagation();
        if (isbInitialized) {
            ajaxComponent('#step2').callAjaxAction('clearSolutionBox');
        }
    });

    $(sbDom).bind("systemError", function(event) {
        event.stopPropagation();
        if (isbInitialized) {
            ajaxComponent('#step2').callAjaxAction('clearSolutionBox');
        }
    });

    $("#clearAnswerButtonYes").bind("click", function (event) {
        $.lightBox.hide();
        $("#step2 input[name='internet-service-sku']:checked").attr("checked", 0);
        updateStep3Vases(serviceAvailabilityJSON.availableVAS, [], false, false);

        $("#step4 input[name='existingCustomer']:[value='true']").each(function (){
            $(this).attr("checked", 1);
        });

        $("#step4 input[type='checkbox']").each(function() {
                    $(this).attr("checked", 0);
                    $(this).removeAttr('disabled');
        });

        $.bell.setElementActive(this, 'capsule', 'capSelected');

        ajaxComponent('#step2').callAjaxAction('clearSolutionBox');
    });

    $("#clearAnswerButtonNo").bind("click", function (event) {
        $.lightBox.hide();
    });

}

function bindInstalationsHandlers() {
    var step = $("#stepInstallations");

    $("input[name='internetInstallationType']", step).each(function () {
        $(this).bind("click", function() {
			stepTracker(4);
            $.bell.setElementActive(this, "#stepInstallations .capsule", "capSelected");
            ajaxComponent('#step2').callAjaxAction('addRemoveItem', generateJSONObject(false));
        });
    });

    $(step).bind("availableservcies", function(event) {
        event.stopPropagation();
        var domElement = $("#stepInstallations");
        $.bell.sBuilder.stepManager.hide("#stepInstallations");

        $("div[id^='internetInstallationTypeSection_']", domElement).each(function() {
            $(this).hide();
        });

        $("[id^='internetInstallationPrice_']", domElement).each(function() {
            $(this).html("");
        });

        // Remove any installation type checked value
        $("input[name='internetInstallationType']", domElement).each(function(){
            $(this).removeAttr("checked");
            $(this).removeAttr("disabled");
        });

        // Set back the steps number
        $.bell.sBuilder.stepManager.setTitle("#step4",servicesStepTitle);
        $.pageRender(step);

    });

    $(step).bind("installation", function(event) {
        event.stopPropagation();
        var domElement = $("#stepInstallations");
        var installations = event.installationTypesMap;

		//CR 11536 - display installation step header at all times	
        if (installations != null && (customerHasIHGModem||($("input[name='internet-service-sku']:checked").val() != isSubscribedTo))) {
        	// Hide all the possible installation types
        	$("div[id^='internetInstallationTypeSection_']").hide();

			var INSTALLATION_PROPERTY_KEY_PRICE = $("#installationTypePropertyKeyPrice").val();
			var INSTALLATION_PROPERTY_KEY_DISABLED = $("#installationTypePropertyKeyDisabled").val();

			// Shows only the available installation types
            for(var installationTypeName in installations) {
            	if (installationTypeName == null) {
            		continue;
            	}

				// Showing the section
				$("#internetInstallationTypeSection_" + installationTypeName).show();

				for (var j = 0; j < installations[installationTypeName].length; j++) {
				    var keyValue2 = installations[installationTypeName][j];
				    // Set the price value
					if (keyValue2.key == INSTALLATION_PROPERTY_KEY_PRICE) {
						$("#internetInstallationPrice_" + installationTypeName).html(keyValue2.value);
					}
					// Set the enable/disable
					else if (keyValue2.key == INSTALLATION_PROPERTY_KEY_DISABLED) {
						if (keyValue2.value == 'true') {
							$("#internetInstallationType_" + installationTypeName).attr("disabled", "disabled");
						}
						else {
							$("#internetInstallationType_" + installationTypeName).removeAttr("disabled");
						}
					}
				}
            }

            if (event.defaultInstallationType && event.defaultInstallationType != null) {
            	$("#internetInstallationType_" + event.defaultInstallationType).attr("checked", 1);

            	$.bell.setElementActive($("#internetInstallationType_" + event.defaultInstallationType), "#stepInstallations .capsule", "capSelected");
            }

            // Set the new step number
            $.bell.sBuilder.stepManager.setTitle("#step4",servicesStepTitle);

            // Show the installation section
            $.bell.sBuilder.stepManager.show("#stepInstallations");
            $("#stepInstallations").show();
        } else {
			//CR 11536 - display installation step header at all times
            $("#stepInstallations").show().addClass("cBoxEmpty");
        }
    });

    $(step).bind("defSelection", function(event) {
        event.stopPropagation();
        if (event.selection.installationType && event.selection.installationType != null) {
            $("#stepInstallations input[name='internetInstallationType'][value='" + event.selection.installationType + "']").each(function() {
                $(this).attr("checked", 1);
                $.bell.setElementActive(this, "#stepInstallations .capsule", "capSelected");
            });
        }
    });

    $(step).bind("validationError", function(event) {
        event.stopPropagation();
        if (!event.isMutualExclusive) {
            $.bell.sBuilder.stepManager.hide("#stepInstallations");
        }
    });

    $(step).bind("userError", function(event) {
        event.stopPropagation();
        $.bell.sBuilder.stepManager.hide("#stepInstallations");
    });

    $(step).bind("systemError", function(event) {
        event.stopPropagation();
        $.bell.sBuilder.stepManager.hide("#stepInstallations");
    });

}


function updateStep3Vases(features, selectedFeatures, preselectFreeVas, preselectCustomerVAS) {
    $.bell.sBuilder.stepManager.hide("#step3");
    var step3 = $("#step3");
    if (features.length && features.length > 0) {
        var vasCatTpl = $("#tpl-internet-vas-category", step3).clone();
        var vasTpl = $("#tpl-internet-vas-id", step3).clone();

        $("#vasContent > div:gt(0)").remove();

		subscribed = [];

        var holder = $("<div></div>");
        $(holder).appendTo("#vasContent");

        vasCatTpl.removeAttr("class");

        $("#tpl-internet-vas-id", vasCatTpl).remove();

        for (var i = 0; i < features.length; i++) {
            var categoryVAS = features[i];
            var categoryVASHTML = $(vasCatTpl).clone();
            $(categoryVASHTML).attr("id", "vas-category-id-" + i);
            $(categoryVASHTML).appendTo($(holder));

            $('> h3', categoryVASHTML).text(categoryVAS.categoryName);
            for (var j = 0; j < categoryVAS.categoryMembers.length; j++) {
                var vas = categoryVAS.categoryMembers[j];
                var vasHTML = $(vasTpl).clone();
                $(vasHTML).appendTo($("> fieldset", categoryVASHTML));

                var preselected = ($.inArray(vas.sku, selectedFeatures) > -1)
                                  || (preselectCustomerVAS && vas.customerSubscribed)
                                  || (!vas.optional && preselectFreeVas);
                                  

                $(vasHTML).attr("id", "internet-vas-id-" + i + "-" + j);

                if (preselected) {
                    $(vasHTML).addClass("capSelected");
                }

                $("> input", vasHTML).attr("id", "internet-vas-checkbox-id-" + i + "-" + j);
                $("> input", vasHTML).attr("value", vas.sku);
                if (preselected) {
                    $("> input", vasHTML).each(function() {
                        $(this).attr("checked","checked");
                    });
                }

                if (!vas.optional && preselectFreeVas)  {
                    $("> input", vasHTML).attr("disabled", "disabled");
                }

				if (vas.customerSubscribed ) { /*&& vas.sku == "VasIntHomeNetworking"*/
                    $("> input", vasHTML).attr("disabled", "disabled");
                    $("> input", vasHTML).attr("checked", "checked");
                    
				}

                $("> input", vasHTML).bind("click", function (event) {
					stepTracker(3);
                    if (this.checked) {
                        $(this).parent().addClass("capSelected");
                        $(step3).data("lastchecked", $(this));
                        $(step3).one("validationError", function(event) {
                            event.stopPropagation();
                            var lastcheckbox = $(step3).data("lastchecked");
                            if (event.isMutualExclusive) {
                                $.lightBox.showInPage("#incompatibleVasLB");
                                if ($(lastcheckbox).length != 0) {
                                    $(lastcheckbox).removeAttr("checked");
                                    $(lastcheckbox).parent().removeClass("capSelected");
                                    $.pageRender($(lastcheckbox).parent());
                                }
                            }

                            $(step3).removeData("lastchecked");
                        });
                    } else {
                        $(this).parent().removeClass("capSelected");
                    }
                    $.pageRender($(this).parent());
                    ajaxComponent('#step2').callAjaxAction('addRemoveItem', generateJSONObject(false));

                });

                $("> div > label", vasHTML).attr("for", "internet-vas-checkbox-id-" + i + "-" + j);
                $("> div > label > span:eq(0)", vasHTML).html(vas.name);
                $("> div > label > span:eq(2)", vasHTML).attr("id", "vas-price1-" + vas.sku);
                $("> div > label > span:eq(4)", vasHTML).attr("id", "vas-price2-" + vas.sku);
                $("> div > label > span:eq(5)", vasHTML).hide();
				
                
            if (vas.customerSubscribed) {
				$("> div > label > span:eq(3)", vasHTML).html("");
				$("> div > label > span:eq(5)", vasHTML).show();
				$("> div > label > span:eq(4)", vasHTML).html("");
				subscribed.push(vas.sku);
			} 
                $("> div > p:eq(0)", vasHTML).html(vas.description);

                if (vas.optional) {
                    $("> input", vasHTML).attr("name", "internet-vas-sku-optional");
                } else {
                    $("> input", vasHTML).attr("name", "internet-vas-sku-included");
                }
                //$(vasHTML).appendTo($("> fieldset", categoryVASHTML));
            }
            //$(categoryVASHTML).appendTo($(holder));
            $.bell.sBuilder.stepManager.show("#step3");
        }
        //$(holder).appendTo("#vasContent");
        $.pageRender("#step3");

        //finding at least one feature which is not available
        if (selectedFeatures && selectedFeatures.length) {
            for (var a = 0; a < selectedFeatures.length; a++) {
                var featureFound = false;
                for (var b = 0; !featureFound && b < features.length; b++) {
                    for (var c = 0; !featureFound && c < features[b].categoryMembers.length; c++) {
                        if (selectedFeatures[a] == features[b].categoryMembers[c].sku) {
                            featureFound = true;
                            break;
                        }
                    }
                }
                if (!featureFound) {
                    $.lightBox.showInPage("#unavailableFeatureLB", {modal:false});
                    break;
                }
            }
        }
    }
}

function stepTracker(stepNb){
	var cmsStep = "";
	if(stepNb==4){
		cmsStep = "solutionbuilder.installationtype.steptitle";
	}
	else if (stepNb==5){
		cmsStep = "solutionbuilder.step4.title";
	}
	else{
		cmsStep = "solutionbuilder.step"+stepNb+".title";
	}
	$.bell.external.tracker({
		appName:"lp",
		actionName:"solutionBuilder",
		data: {
			 stepNumber: "Int-SB-"+stepNb,
			 stepName: '"'+ajaxComponentI18n.message[cmsStep]+'"'
	}
	});
}

	PrintToPdfClass.prototype = new BaseAjaxComponent();

	function  PrintToPdfClass(id)
	{
		this.timeout = 60 * 60 * 1000;
		BaseAjaxComponent.apply(this, arguments);
	}

	PrintToPdfClass.prototype.initialize = function() 
	{
		this.ajaxHandlerName  = 'InternetSolutionHandler';
	}
	
	PrintToPdfClass.prototype.update = function(data, html, newComponents) 
	{
		if (!$.bell.isEmpty(html))
		{
			printOrGenerate(html);
		}
	}	
		
	function printPdfInternet()
	{
		printOrGeneratePDF = "print";
		ajaxComponent('#print2pdfHtml').callAjaxAction('printToPdfAction',generateJSONObject(false));
	}

	function generatePdfInternet()
	{
		printOrGeneratePDF = "generate";
		ajaxComponent('#print2pdfHtml').callAjaxAction('printToPdfAction',generateJSONObject(false));
	}


