var serviceAvailabilityJSON = {};

/**
* Network Type from OMF Web Service
*/
var networkType;
var dslInternetProduct = false;
var ftthMsgOrder = "";

/**
 * Service Check Ajax component
 */
serviceAvailabilityAjaxComponent.prototype = new BaseAjaxComponent();

/**
 * Creates new instance of components, sets timeout to 5 minutes and loads predefined meta data
 * @param id
 */
function serviceAvailabilityAjaxComponent(id) {
    BaseAjaxComponent.apply(this, arguments);
    this.ajaxHandlerName = "ServiceAvailabilityHandler";
    this.timeout = (60 * 60 * 1000); // 60 minutes
    this.persistenceKey = "ServiceAvailabilityKey";
    this.publish = new Publisher();
    this.publish.registerSubscriber(new UserData('User data'));
    this.publish.registerSubscriber(new MessagesArea('Messages'));
    this.publish.registerSubscriber(new FoundAddressList('Found address list'));
    this.publish.registerSubscriber(new AccountInfoSubscriber('Account Info'));
    this.publish.registerSubscriber(new NewExistingSubscriber('New Existing Light Box'));
    $.pageRender("#serviceCheckContainer");
}

serviceAvailabilityAjaxComponent.prototype.ajaxCallStarted = function() {    
    BaseAjaxComponent.prototype.ajaxCallStarted.call(this);
    $.ajaxLoader.show();
};


serviceAvailabilityAjaxComponent.prototype.ajaxCallFinished = function() {
    BaseAjaxComponent.prototype.ajaxCallFinished.call(this);
    $.ajaxLoader.hide();
};

/**
 * Callback method for updating front end
 *
 * @param data         - data returned by server in JSON format
 * @param html         - new html coming from server
 * @param newComponent - new component
 */
serviceAvailabilityAjaxComponent.prototype.update = function(data, html, newComponent) {
    serviceAvailabilityJSON = data;
	networkType = data.networkType;
	if(networkType == "FTTH") {
		disableFTTHOrdering();
	}
	setCallNumber(networkType);
    $("#checkByIndicatedAddressSection > div").each(function(){ $(this).removeClass("frmError")});
    this.publish.notifySubscribers(data);
};

/**
 * Callback for handling validation errors
 *
 * @param validationErrors
 */
serviceAvailabilityAjaxComponent.prototype.validationError = function(validationErrors) {
    $("#checkByIndicatedAddressSection > div").each(function(){ $(this).removeClass("frmError")});
    var requiredFields = false;
    var errorTitle = '';
    var errorMessages = '';
    for (var e in validationErrors) {
        if (validationErrors[e] == "required") {
            var selector = "#" + e + "Line";
            var fName = $(">div>label", selector).html();
            requiredFields = true;
            $(selector).addClass("frmError");
        } else if (e == "phoneNumber" && validationErrors[e] == "phone.business") {
            $.lightBox.showInPage("#businessPhoneLB", {modal:true});
        } else if (e == "phoneNumber" && validationErrors[e] == "phone.province") {
            $.cookies.set("phone_submit", "true");
            $.cookies.set("userPhone", $("#phoneNumber").val());
            $("#provincehidden").val(validationErrors["province"]);
            $.lightBox.showInPage("#changeProvinceLB", {modal:true});
        } else if (e == "b1" && validationErrors[e] == "phone.province") {
            $.cookies.set("b1_submit", "true");
            $.cookies.set("userB1", validationErrors["userB1"]);
            $("#provincehidden").val(validationErrors["province"]);
            $.lightBox.showInPage("#changeProvinceLB", {modal:true});
        } else {
            if (errorTitle == '') {
                errorTitle = validationErrors[e];
            } else {
                errorMessages = errorMessages + validationErrors[e] + "<br/>";
            }
        }
    }
    if (requiredFields) {
        setCheckResultMessage("Required fields", "", true);
    } else if (errorTitle != '') {
        setCheckResultMessage(errorTitle, errorMessages, true);
    }
    if ($("#subForwardId").val() && $.isFunction(ajaxComponent($("#subForwardId").val()).validationError)) {
        ajaxComponent($("#subForwardId").val()).validationError(validationErrors);
    }
};

/**
 * Callback for handling user errors
 *
 * @param errorString - error string
 * @param exception   - actual exception
 */
serviceAvailabilityAjaxComponent.prototype.userError = function(errorString, exception) {
    setCheckResultMessage(errorString, exception, true);
    if ($("#subForwardId").val() && $.isFunction(ajaxComponent($("#subForwardId").val()).userError)) {
        ajaxComponent($("#subForwardId").val()).userError(errorString, exception);
    }
};

/**
 * Callback for handling system errors
 *
 * @param errorString - error string
 */


serviceAvailabilityAjaxComponent.prototype.systemError = function(errorString) {
    setCheckResultMessage(errorString, 'SYSTEM ERROR', true);
    if ($("#subForwardId").val() && $.isFunction(ajaxComponent($("#subForwardId").val()).systemError)) {
        ajaxComponent($("#subForwardId").val()).systemError(errorString);
    }

};


/**
 * Implementation of observer pattern
 */
function Subscriber(id) {
    this.id = id;
}

/**
 * Each subscriber will have to define his own implementation
 */
Subscriber.prototype = {
    notify: function(data) {
    }
};

/**
 * Publisher
 */
function Publisher() {
    this.subscribers = [];
}

/**
 * Publisher implementation
 *
 * @param id - id of publisher
 */
Publisher.prototype = {
    /**
     * Registers subscriber
     *
     * @param subscriber - subscriber to registert
     */
    registerSubscriber: function(subscriber) {
        if (subscriber) {
            this.subscribers[this.subscribers.length] = subscriber;
        }
    },

    /**
     * Notifies registered subscribers with given data
     *
     * @param data - data for notifications
     */
    notifySubscribers: function(data) {
        for (var i = 0; i < this.subscribers.length; i++) {
            this.subscribers[i].notify(data);
        }
    }
};

/**
 * Subscriber responsible for rendering user input data
 *
 * @param id - subscriber id
 */
UserData.prototype = new Subscriber();
function UserData(id) {
    Subscriber.apply(this, arguments);
}

UserData.prototype.notify = function(data) {
    if (data.userForm == null) {
        if (data.disabledPhoneCheck) {
            $("#radioServiceCheckTypeAddress").trigger("click");
        } else {
            $("#radioServiceCheckTypePhone").trigger("click");
        }
    } else {
        var form = data.userForm;

        if ('checkServiceByPhone' == form.actionName) {
            $("#radioServiceCheckTypePhone").trigger("click");
            $("#phoneNumber").val(form.phoneNumber);
        } else if ('checkServiceByAddress' == form.actionName) {
            $("#radioServiceCheckTypeAddress").trigger("click");
            $("#streetNumber").val(form.streetNumber);

            if (form.streetSuffix == "") {
                $("#streetSuffix").val("-");
            } else {
                $("#streetSuffix").val(form.streetSuffix);
            }

            $("#streetName").val(form.streetName);

            if (form.streetDirection == "") {
                $("#streetDirection").val("-");
            } else {
                $("#streetDirection").val(form.streetDirection);
            }

            $("#apartment").val(form.apartment);
            $("#city").val(form.city);
            $("#postalCode").val(form.postalCode);
            $("#province").val(form.province);
        } else {
            if (data.disabledPhoneCheck) {
                $("#radioServiceCheckTypeAddress").trigger("click");
            } else {
                $("#radioServiceCheckTypePhone").trigger("click");
            }
        }
    }
};

/**
 * Subscriber responsible for updating messages area
 *
 * @param id - subscriber id
 */
MessagesArea.prototype = new Subscriber();
function MessagesArea(id) {
    Subscriber.apply(this, arguments);
}

MessagesArea.prototype.notify = function(data) {
    clearAndHideResultMessage();
    if (data.messages && data.messages.length > 0) {
        var isError = data.statusType == "error";
        var msg = "";

        for (var i = 0; i < data.messages.length; i++) {
            msg += data.messages[i] + "<br/>";
        }
        setCheckResultMessage(data.statusTitle, msg, isError);
    }
};


FoundAddressList.prototype = new Subscriber();
function FoundAddressList(id) {
    Subscriber.apply(this, arguments);
}

FoundAddressList.prototype.notify = function(data) {
    var items = [];
    if (data.foundAddresses) {
        for (var x = 0; x < data.foundAddresses.length; x++) {
            var addTxt = "";
            if (data.foundAddresses[x].streetNumber) {
                addTxt += " " + data.foundAddresses[x].streetNumber;
            }

            if (data.foundAddresses[x].streetSuffix) {
                addTxt += " " + data.foundAddresses[x].streetSuffix;
            }

            if (data.foundAddresses[x].streetName) {
                addTxt += " " + data.foundAddresses[x].streetName;
            }


            if (data.foundAddresses[x].streetDirection) {
                addTxt += " " + data.foundAddresses[x].streetDirection;
            }

            if (data.foundAddresses[x].apartment) {
                addTxt += " #" + data.foundAddresses[x].apartment;
            }

            if (data.foundAddresses[x].city) {
                addTxt += ", " + data.foundAddresses[x].city;
            }

            if (data.foundAddresses[x].province) {
                addTxt += ", " + data.foundAddresses[x].province;
            }

            if (data.foundAddresses[x].postalCode) {
                addTxt += ", " + data.foundAddresses[x].postalCode;
            }

            items.push({"optVal": data.foundAddresses[x].addressHash, "optText": addTxt});
        }

    }

    if (items.length > 0) {
        $.bell.fillDropDown("#addressList", items, "optVal", "optText");
        $("#checkByAddressList").show();
        $("#checkByAddress :input[name='addressCheckType'][value='list']").trigger("click");
    } else {
        $("#checkByAddressList").hide();
        $("#checkByAddress :input[name='addressCheckType'][value='form']").trigger("click");
    }
};

/**
 * Subscriber responsible for displaying account info (account number, current service)
 */

AccountInfoSubscriber.protopype = new Subscriber();
function AccountInfoSubscriber(id) {
    Subscriber.apply(this, arguments);
}

AccountInfoSubscriber.prototype.notify = function(data) {
    var checkState = data.checkState;
    if (checkState.loggedIn) {
        $("#mapB1Accounts input[value='" + checkState.b1 + "']").attr('checked', 1);
        $("#accountNumber").html(checkState.b1.b1);
        $("#currentService").html(checkState.b1.currentService);
    }
};

/**
 * Subscriber responsible for displaying New vs Existing Light Box
 */
NewExistingSubscriber.protopype = new Subscriber();
function NewExistingSubscriber(id) {
    Subscriber.apply(this, arguments);
}

NewExistingSubscriber.prototype.notify = function(data) {
    if (data.showNewExistingLightBox && $("#fromSolutionBuilder").val() === "true") {
        if (data.checkState.loggedIn) {
            $.lightBox.showInPage("#newVsExistingLinkLB", {modal:true, colClassName: "col8"});
        } else {
            $.lightBox.showInPage("#newVsExistingLoginLB", {modal:true, colClassName: "col8"});
        }
    }
};


/**
 * Triggers a call to server for getting data required on first page load.
 */
function loadServicePage() {
    $.bell.fillDropDown("#streetSuffix", internetSolutionDataStore["street_suffix"], "key", "value");
	//$.bell.fillDropDown("#streetDirection", internetSolutionDataStore["street_directions"], "key", "value");
    // $.bell.fillDropDown("#province", internetSolutionDataStore["provinces"], "key", "value");

     // CR - 12866
	 // CR - 13477
        var prov = internetSolutionDataStore["provinces"];
		var streetDir = internetSolutionDataStore["street_directions"];
        while (prov.length > 2) {
        	for (i=0; i < prov.length; i++) {
			if( (prov[i].key != "QC") && (prov[i].key != "ON") ) {
				prov.splice(i,1);
				break;
			}
        	}
        }
        prov.sort( function(a, b) { return (a.key > b.key)-(a.key < b.key);} );
		streetDir.sort( function(a, b) { return (a.key > b.key)-(a.key < b.key);} );
	$.bell.fillDropDown("#streetDirection", streetDir, "key", "value");
    $.bell.fillDropDown("#province", prov, "key", "value")




    if (userB1s) {
        if (!userB1s.loggedIn) {
            $("#userAccountInfoSection").hide();
            $("#checkServicePanelId").removeClass("tglJs");
            $("#checkServicePanelId").hide();
            $("#btnChangeB1Account").unbind("click");
            $("#changeB1Link").unbind("click");
            $("#checkServicePanel").show();
        } else {
            if ($("#mapB1Accounts").length) {
                $("#mapB1Accounts").remove();
            }

            if (userB1s.b1Accounts && userB1s.b1Accounts.length > 1) {
                $.bell.map("#mapB1Accounts-tpl", userB1s.b1Accounts, "mapB1Accounts", function($mapObj) {
                    $("> input", $mapObj).bind("click", function(event) {
                        $.bell.setElementActive(this, 'capsule', 'capSelected');

                    });
                });

                $("#mapB1Accounts input:eq(0)").each(function() {
                    $(this).attr('checked', 1);
                });

                $("#btnChangeB1Account").bind("click", function(event) {
                    var b1Value = $("#mapB1Accounts input[name='currentB1Account']:checked").val();
                    $.lightBox.hide();
                    ajaxComponent("#serviceCheckContainer").callAjaxAction('changeCurrentB1Account',
                    {fromSolutionBuilder: $("#fromSolutionBuilder").val(),
                        subForwardId:         $("#subForwardId").val(),
                        b1:                     b1Value});
                });

                $("#changeB1Link").bind("click", function(event) {
                    $.lightBox.showInPage("#changeAccountLightBoxId", {modal:false});
                });
                $("#changeB1Span").show();
            } else {
                $("#changeB1Span").hide();
            }


            // display the current B1 account information

            if (userB1s.b1Accounts && userB1s.b1Accounts.length > 0) {
                $("#accountNumber").html(userB1s.b1Accounts[0].b1);
                $("#currentService").html(userB1s.b1Accounts[0].currentService);
            }

            $("#checkServicePanelId").addClass("tglJs");
            $("#checkServicePanelId").show();
            $("#userAccountInfoSection").show();
        }
    }

    $("#btnCheckPhone").bind("click", function (event) {
      if ($.bell.external) {
        $.bell.external.tracker({
           appName: "lp",
           data: {
           componentName: "CheckAvailabilityService"
           }
        });

        if($("#fromSolutionBuilder").val()=="true"){
          $.bell.external.tracker({
	    appName:"lp",
            actionName:"solutionBuilder",
	    data: {
		 stepNumber: "Int-SB-1",
		 stepName: '"'+ajaxComponentI18n.message["solutionbuilder.step1.title"]+'"'
	    }
          });
        }
      }
        ajaxComponent("#serviceCheckContainer")
                .callAjaxAction('checkServiceByPhone', {fromSolutionBuilder: $("#fromSolutionBuilder").val(),
            subForwardId:        $("#subForwardId").val(),
            phoneNumber:         $("#phoneNumber").val()});
    });

    $("#btnCheckAddress").bind("click", function (event) {
      if ($.bell.external) {
          $.bell.external.tracker({
            appName: "lp",
            data: {
            componentName: "CheckAvailabilityService"
            }
          });

          if($("#fromSolutionBuilder").val()=="true"){
            $.bell.external.tracker({
	    appName:"lp",
            actionName:"solutionBuilder",
	    data: {
		 stepNumber: "Int-SB-1",
		 stepName: '"'+ajaxComponentI18n.message["solutionbuilder.step1.title"]+'"'
	      }
            });
          }
        }
        var jsonAddressObject = {fromSolutionBuilder: $("#fromSolutionBuilder").val(),
            subForwardId: $("#subForwardId").val(),
            streetNumber:   $("#streetNumber").val(),
            streetSuffix:   $("#streetSuffix").val().replace("-", ""),
            streetName:     $("#streetName").val(),
            streetDirection:$("#streetDirection").val().replace("-", ""),
            apartment:      $("#apartment").val(),
            city:           $("#city").val(),
            postalCode:     $("#postalCode").val(),
            province:       $("#province").val()};


        if ($("#checkByAddress input[name='addressCheckType']:checked").val() == 'list') {
            jsonAddressObject.addressHash = $("#addressList").val();
        }
        ajaxComponent("#serviceCheckContainer")
                .callAjaxAction('checkServiceByAddress', jsonAddressObject);
    });

    $("#checkByAddress input[name='addressCheckType']").each(function () {
        $(this).bind("click", function (event) {
            if ($(this).val() == "list") {
                $("#addressList").removeAttr('disabled');
                $("#checkByIndicatedAddressSection").hide();
            } else {
                $("#addressList").attr('disabled', 'disabled');
                $("#checkByIndicatedAddressSection").show();
            }
        });
    });

    var changeProvinceLBDom = $("#changeProvinceLB");
    $("#no", changeProvinceLBDom).bind("click", function(event) {
        $.lightBox.hide();
        $("#province").val(internetSolutionDataStore["user_province"]);
        $("#provincehidden").val("");
        $.cookies.remove("phone_submit");
        $.cookies.remove("userPhone");
        $.cookies.remove("address_submit");
        $.cookies.remove("userData");
        $.cookies.remove("b1_submit");
        $.cookies.remove("userB1");
        
        
        return false;
    });

    $("#yes", changeProvinceLBDom).bind("click", function(event) {
        $.lightBox.hide();
        var provUrl = $("a[title='" + $("#provincehidden").val() + "']").attr("href");
        $("#provincehidden").val("");
        window.location.href = provUrl;
        return false;
    });

    $("#province").bind("change", function(event) {
        if ($("#province").val() != internetSolutionDataStore["user_province"]) {
            $("#provincehidden").val($("#province").val());
            $.cookies.set("userData", JSON.stringify({streetNumber:   $("#streetNumber").val(),
                streetSuffix:   $("#streetSuffix").val(),
                streetName:     $("#streetName").val(),
                streetDirection:$("#streetDirection").val(),
                apartment:      $("#apartment").val(),
                city:           $("#city").val(),
                postalCode:     $("#postalCode").val(),
                province:       $("#province").val()}));

            $.cookies.set("address_submit", "true");
            $.lightBox.showInPage("#changeProvinceLB", {modal:true});

        }
    });

    $("#busPhoneNo").bind("click", function(event) {
        $.lightBox.hide();
        $("#phoneNumber").val("");
        return false;
    });

    $("#busPhoneYes").bind("click", function(event) {
        $.lightBox.hide();
        window.location = "http://www.bell.ca/shop/SmeSol_Internet_Landing.page";
        return false;
    });

	var getQuerystring = function(key, default_)
{
  if (default_==null) default_=""; 
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
};

var checkByAddress = getQuerystring("checkByAddress");
    //setting some default values
    $("#province").val(internetSolutionDataStore["user_province"]);
    $("#radioServiceCheckTypePhone").trigger("click");

    var resubmitPhone = $.cookies.get("phone_submit");
    var resubmitAddress = $.cookies.get("address_submit");
    var resubmitB1 = $.cookies.get("b1_submit");
    if (resubmitPhone == "true") {
        var phone = $.cookies.get("userPhone");
        $("#phoneNumber").val(phone);
        $.cookies.remove("phone_submit");
        $.cookies.remove("userPhone");
        $("#btnCheckPhone").trigger("click");

    } else if (resubmitAddress == "true") {
        var userData = JSON.parse($.cookies.get("userData"));
        $("#streetNumber").val(userData.streetNumber);
        $("#streetSuffix").val(userData.streetSuffix);
        $("#streetName").val(userData.streetName);
        $("#streetDirection").val(userData.streetDirection);
        $("#apartment").val(userData.apartment);
        $("#city").val(userData.city);
        $("#postalCode").val(userData.postalCode);
        $("#province").val(userData.province);

        $.cookies.remove("address_submit");
        $.cookies.remove("userData");
        $("#radioServiceCheckTypeAddress").trigger("click");
        $("#btnCheckAddress").trigger("click");
    } else if (resubmitB1 == "true") {
        var b1 = $.cookies.get("userB1");
        $.cookies.remove("b1_submit");
        $.cookies.remove("userB1");
        ajaxComponent("#serviceCheckContainer").callAjaxAction('changeCurrentB1Account',
        {fromSolutionBuilder: $("#fromSolutionBuilder").val(),
            subForwardId:         $("#subForwardId").val(),
            b1:                     b1});

    } 
	else if(checkByAddress=="true"&&checkByAddress!=null)
		{
		$("#radioServiceCheckTypeAddress").trigger("click");
		if (resubmitAddress == "true") {
        var userData = JSON.parse($.cookies.get("userData"));
        $("#streetNumber").val(userData.streetNumber);
        $("#streetSuffix").val(userData.streetSuffix);
        $("#streetName").val(userData.streetName);
        $("#streetDirection").val(userData.streetDirection);
        $("#apartment").val(userData.apartment);
        $("#city").val(userData.city);
        $("#postalCode").val(userData.postalCode);
        $("#province").val(userData.province);

        $.cookies.remove("address_submit");
        $.cookies.remove("userData");
        $("#radioServiceCheckTypeAddress").trigger("click");
        $("#btnCheckAddress").trigger("click");
    }
		  
		}
	else {
        ajaxComponent("#serviceCheckContainer").callAjaxAction('begin', {
            fromSolutionBuilder: $("#fromSolutionBuilder").val(),
            subForwardId:        $("#subForwardId").val()});
    }
}

/**
 * Shows and hides required sections. Used on switching between PSQT and CLT checks
 *
 * @param sectionToShow - section to show
 * @param sectionToHide - section to hide
 */
function toggleSection(currentObject, sectionToShow, sectionToHide) {
    $.bell.setElementActive(currentObject, 'eqJs', 'capSelected');
    $(sectionToHide).hide();
    $(sectionToShow).show();
}


/**
 * Clears and hides check result notification area
 */
function clearAndHideResultMessage() {
    $("#checkResultMessage .userMsg").removeClass("umVerified");
    $("#checkResultMessage .userMsg").removeClass("umUnverified");

    // Clearing the text
    $("#checkResultMessage .userMsg > h3").html("");
    $("#checkResultMessage .userMsg > p").html("");

    // Hiding the result message box
    $("#checkResultMessage").hide();
}

/**
 * Sets check result notification message
 *
 * @param title       - title to set
 * @param description - description
 * @param isError     - result type
 */
function setCheckResultMessage(title, description, isError) {
    if (isError) {
        $("#checkResultMessage > div").removeClass("umVerified");
        $("#checkResultMessage > div").addClass("umUnverified");
        //Omniture tagging
        if (typeof(s_oTrackPage)!== "undefined"){
            errorMessage = title + " " + description;
            errorMessage = errorMessage.replace("<br/>","");
            s_oTrackPage({s_oAPN:"psqt", s_oAPT:"error", s_oAPS:"2", s_oAPE:errorMessage});
        }
    } else {
        $("#checkResultMessage > div").removeClass("umUnverified");
        $("#checkResultMessage > div").addClass("umVerified");
        //Omniture tagging
        if (typeof(s_oTrackPage)!== "undefined"){
            s_oTrackPage({s_oAPN:"psqt", s_oAPT:"completed", s_oAPS:"2", s_oAPE:"", s_oAPI:""});
        }    
    }

    $("#checkResultMessage > div > h3").html(title);
    $("#checkResultMessage > div > p").html(description);
    $("#checkResultMessage > div").html($("#checkResultMessage > div").html().replace("current_page", window.location.href));

    $("#checkResultMessage").show();
}

function replaceCheckResultTitle(title) {
    $("#checkResultMessage > div > h3").html(title);
}

function disableFTTHOrdering() {
	if(dslInternetProduct) {
		$('#SBLinkJs').html("<br>" + ftthMsgOrder);
	}
}

function setCallNumber(network) {
	if(network=="FTTH") {
		$('.accent').text(' 310-BELL');
	} else {
		$('.accent').text(' 1 877 571-1278');
	}
}


