if (window.jQuery) {

    var uagent = navigator.userAgent.toLowerCase();
    var mobileAgent = {
		android : (uagent.indexOf('android') > -1), 
		iphone : (uagent.indexOf('iphone') > -1), 
		ipad : (uagent.indexOf('ipad') > -1)
	};

    function ValidationSummaryOnSubmitCCentral(validationGroup)
    {
        if (typeof (Page_ValidationSummaries) == "undefined")
            return;
        var summary, sums, s;
        for (sums = 0; sums < Page_ValidationSummaries.length; sums++)
        {
            summary = Page_ValidationSummaries[sums];
            summary.style.display = "none";
            
            var errorCount = 0;
            if (!Page_IsValid && IsValidationGroupMatch(summary, validationGroup))
            {
                var i;
                if (summary.showsummary != "False")
                {
                    summary.style.display = "";
                    if (typeof (summary.displaymode) != "string")
                    {
                        summary.displaymode = "BulletList";
                    }
                    var countedValidators = new Array();


                    for (i = 0; i < Page_Validators.length; i++)
                    {
                        if (!Page_Validators[i].isvalid && typeof (Page_Validators[i].errormessage) == "string")
                        {
                            var valid = true;
                            
                            for (var j = 0; j < countedValidators.length; j++)
                            {
                                if (Page_Validators[i].errormessage == Page_Validators[countedValidators[j]].errormessage)
                                {
                                    valid = false;
                                    j = i;
                                }
                            }
                            if (valid == true)
                            {
                                countedValidators.push(i);
                                errorCount++;
                            }
                        }
                    }
                    s = "";
                    switch (errorCount)
                    {
                        case 0:
                            break;
                        case 1:
                            s = "<div>" + Page_Validators[countedValidators[0]].errormessage + "</div>";
                            break;
                        default:
                            s += "<ul>";
                            for (i = 0; i < countedValidators.length; i++)
                            {
                                s += "<li>" + Page_Validators[countedValidators[i]].errormessage + "</li>";
                            }
                            s += "</ul>";
                            break;
                            
                    }
                    summary.innerHTML = s;
                    window.scrollTo(0, 0);
                }
            }
        }
    }
    if (window.ValidationSummaryOnSubmit)
    {
        ValidationSummaryOnSubmit = ValidationSummaryOnSubmitCCentral;
    }
var days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

function formatHour(hour) {
    var value = hour % 12;
    if (value == 0) value = 12;
    return value;
}

function formatMinute(minute) {
    return minute < 10 ? "0" + minute : minute;
}

function getMeridien(hour) {
    return hour > 11 ? 'pm' : 'am';
}

function formatLastLoginTime(time) {
	var output = [];

	output[output.length] = "You last signed in on ";
	output[output.length] = days[time.getDay()];
	output[output.length] = ' ';
	output[output.length] = months[time.getMonth()];
	output[output.length] = ' ';
	output[output.length] = time.getDate();
	output[output.length] = ", ";
	output[output.length] = time.getFullYear();
	output[output.length] = " at ";
	output[output.length] = formatHour(time.getHours());
	output[output.length] = ":";
	output[output.length] = formatMinute(time.getMinutes());
	output[output.length] = getMeridien(time.getHours());

	return output.join('');
}

function readQuerystring() {
    var result = {};
    var query = location.search;
    if (!!query) query = query.substring(1);
    var pairs = query.split('&');
    for (var i = 0; i < pairs.length; ++i) {
        var pair = pairs[i].split('=');
        result[unescape(pair[0]).toLowerCase()] = pair.length == 2 ? unescape(pair[1]) : null;
    }
    return result;
}

function getSiteCatalystSuiteID() {
    var s_account="comcastdotcomqa";
    if(location.href.indexOf('localhost') > -1)s_account="comcastdotcomdev";
    if(location.href.indexOf('ccqa4') > -1 || location.href.indexOf('ccperf') > -1 || location.href.indexOf('ccpfix') > -1 || location.href.indexOf('ccbeta') > -1){
        s_account="comcastdotcomqa";
    }
    else if (location.href.indexOf('.comcast.com') > -1) {
        s_account="comcastdotcomprod";        
    }
    return s_account;
}

function sendSiteCatalystProp6(obj, propID, propDescription) {
    try {
        if (typeof s_gi == 'function') {
            var s = s_gi(getSiteCatalystSuiteID());
            var existVar = s.linkTrackVars;
            s.linkTrackVars = existVar + ",prop6";
            s.prop6 = propDescription;
            s.tl(obj, 'o', propDescription);
            s.prop6 = "";
            s.linkTrackVars = existVar;
            existVar = "";
        }
    } catch (e) { }
}

function sendSiteCatalystEvent(eventID, eventDescription) {
    try {
        if (typeof s_gi == 'function') {
            var s = s_gi(getSiteCatalystSuiteID());
            s.linkTrackVars = "events";
            s.linkTrackEvents = eventID;
            s.events = eventID;
            s.tl($(this), 'o', eventDescription);
        }
    } catch (e) { } 
}

//Set eVar20 = event7
function sendSiteCatalystEvar20(obj, evarID, evarDescription) {
    try {
        if (typeof s_gi == 'function') {
            var s = s_gi(getSiteCatalystSuiteID());
            var existVar = s.linkTrackVars;
            s.linkTrackVars = existVar + ",eVar20,events";
            s.linkTrackEvents = "event7"
            s.eVar20 = evarDescription;
            s.events = "event7";
            s.tl(obj, 'o', evarDescription);
            s.events = "";
            s.linkTrackEvents = "None"
            s.linkTrackVars = existVar;
            existVar = "";
        }
    } catch (e) { }
}
//Set event8
function sendSiteCatalystEvent8(obj, eventID, eventDescription) {
    try {
        if (typeof s_gi == 'function') {
            var s = s_gi(getSiteCatalystSuiteID());
            var existVar = s.linkTrackVars;
            s.linkTrackVars = existVar + ",events";
            s.linkTrackEvents = "event8"
            s.events = "event8";
            s.tl(obj, 'o', eventDescription);
            s.events = "";
            s.linkTrackEvents = "None"
            s.linkTrackVars = existVar;
            existVar = "";
        }
    } catch (e) { } 
}

//Set event7
function sendSiteCatalystEvent7(obj, eventID, eventDescription) {
    try {
        if (typeof s_gi == 'function') {
            var s = s_gi(getSiteCatalystSuiteID());
            var existVar = s.linkTrackVars;
            s.linkTrackVars = existVar + ",events";
            s.linkTrackEvents = "event7";
            s.events = "event7";
            s.tl(obj, 'o', eventDescription);
            s.events = "";
            s.linkTrackEvents = "None";
            s.linkTrackVars = existVar;
            existVar = "";
        }
    } catch (e) { } 
}
//Link Tracking 1106
function scTrkLnk(lnk) {
    try {
        if (typeof s_gi == 'function') {  
            var p=window.location.pathname;
            var ln= 'CustomerCentral'+(p.replace(/.aspx/gi,':').replace(/\//gi,":")+lnk[0].text).toUpperCase();
            s.linkTrackVars="NONE";
            s.linkTrackEvents="NONE";
            s.tl(lnk[0], "o", ln); 
        }
    }
    catch (e) { } 
}

// Set ViewWI2goClick Event and send
function sendSiteCatalystWI2goClick(lnk, pageDescription, lnk_HrefEquivalent) {
    try {
        if (typeof s_gi == 'function') {
						var hrEq = lnk[0].rel;
						var hr = lnk[0].href;
            var s = s_gi(getSiteCatalystSuiteID());
            var existVar = s.linkTrackVars;
						// Sample 1 from ReqDoc           
            s.pageName=pageDescription;
						s.channel="customercentral";
						s.prop31="com";
						s.prop32="customercentral";
						s.prop33="Comcast.com";
						s.prop34="Manager User Accounts";
						s.prop35=pageDescription;
						s.prop37="com";
						s.eVar32="D=c32";
						s.eVar33="D=c33";
						s.eVar34="D=c34";
						s.eVar35="D=c35";
						s.eVar37="D=pageName";
						// Sample 2 from ReqDoc           
            s.linkTrackVars="NONE";
						s.linkTrackEvents="NONE";
						if("undefined"!=hr && hr.indexOf("#",hr)<0 )
						{
							s.tl(lnk[0], "o", lnk[0].href);
						}
						else
						{
							s.tl(lnk[0], "o", hrEq);
						}
						// Cleanup
            s.events = "";
            s.linkTrackEvents = "None"
            s.linkTrackVars = existVar;
            existVar = "";
        }
    } catch (e) { } 
}


function isValidEmailAddress(emailAddress) {
    return emailAddress != null && isValidEmailAddress.regex.test(emailAddress);
}

isValidEmailAddress.regex = /^(?:[A-Za-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[A-Za-z0-9-]*[A-Za-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
function pad(n, len) {

    s = n.toString();
    if (s.length < len) {
        s = ('0000000000' + n.toString()).slice(-len);
    }

    return s;

}


function redirectFromOverlayTo(redirectURL)
{
	if(null != redirectURL) window.top.location = redirectURL;
}
//jQuery.noConflict();

(function($) {


    $(function() {
        var emailAutoReply = '';
        var emailRestricts = '';
        var emailForward = '';
        var emailSpam = '';
        var accountType = '';
        var hsiPlaxoAutoSharing = '';
        var hsiPersonalWebPages = '';
        var paperless = '';
        //Start SiteCatalyst var tracking
        function sendSiteCatalystProp6ErrorProof(arg1, arg2, arg3) {
            try {
                sendSiteCatalystProp6(arg1, arg2, arg3);
            } catch (e) { } // ivan drago style: if it dies, it dies
        }
        //Check for mobile overlay exception message.
        if (($('#MobileOverlayException').length > 0) &&
			(mobileAgent.android || mobileAgent.iphone || mobileAgent.ipad)) {
            $('.GenOk a').attr('href', '../Secure/Mobile/OTT/Home.aspx');
        }
        $('.PersonalInformationUpdated').click(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'Personal Information Updated');
        });

        $('.GreetingNameUpdated').change(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'Greeting Name Updated');
        });

        //ManageSecondaryType.aspx
        $('.AccountType_Unrestricted input').click(function(e) {
            accountType = 'Set Secondary Account type: unrestricted';
        });

        $('.AccountType_Restricted input').click(function(e) {
            accountType = 'Set Secondary Account type: restricted';
        });
        $('.manageSecondaryTypeUpdate').click(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', accountType);
        })
        //AddSecondaryAccount.aspx
        $('.SecondaryAccountCreated').click(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'Secondary Account Created');
        });

        if ($('.AccountInformation').length > 0) {
            fusion.roundCorner('roundedge', 'roundedges', 'roundedges_border');

        }

        if ($('#ctl00_ContentArea_ContractTerms1_divTermsText').length > 0 && fusion.isIE8p) {

            var premoved;

            $('#ctl00_ContentArea_ContractTerms1_divTermsText li').each(function() {
                premoved += '<li style="list-type:circle;">';
                premoved += '<b>' + $(this).find('b').html() + '</b>';
                premoved += $(this).text().replace($(this).find('p b').text(), '') + '<br/>';
                premoved += '</li><br/>';
            });
            $('#ctl00_ContentArea_ContractTerms1_divTermsText').empty();
            $('#ctl00_ContentArea_ContractTerms1_divTermsText').append('<ul>' + premoved.replace('undefined', '') + '</ul>');

        }
        //Lnk Trkng              
        $('.Lnk2Trk').click(function(e) { scTrkLnk($(this)); });
        //Wireless Clicks
        $('.ViewWI2goClickEPPD').click(function(e) {
            sendSiteCatalystWI2goClick($(this), 'Equipment and Protection Plan Details');
        });
        $('.ViewWI2goClick2goUD').click(function(e) {
            sendSiteCatalystWI2goClick($(this), 'View Internet 2go Usage Details');
        });
        $('.ViewWI2goClick2goUM').click(function(e) {
            sendSiteCatalystWI2goClick($(this), 'View Internet 2go Usage Meter');
        });

        //DomainHelper.aspx
        $('.DomainHelperSubmit').click(function(e) {
            if (jQuery('.DomainHelperOn input').attr('checked') == true) {
                action = 'Domain Helper ON'
            };
            if (jQuery('.DomainHelperOff input').attr('checked') == true) {
                action = 'Domain Helper OFF'
            };
            if (null != action && action.length > 0) {
                sendSiteCatalystProp6ErrorProof($(this), 'prop6', action);
            }
        });
        //SinglePayment.aspx
        if ($('.SubmitedOneTimePayment').length > 0) {
            if ($('.OTPCredit').length > 0) {
                onePaymentType = 'credit card - one time';
            }
            if ($('.OTPDebit').length > 0) {
                onePaymentType = 'debit card - one time';
            }
            if ($('.OTPCheck').length > 0) {
                onePaymentType = 'checking - one time';
            }
            if ($('.OTPSavings').length > 0) {
                onePaymentType = 'savings - one time';
            }
            if (null != onePaymentType && onePaymentType.length > 0) {
                sendSiteCatalystEvar20($(this), 'eVar20', onePaymentType);
                sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'One Time Payment');
            }
        }
        //RecurringPayment.aspx
        if ($('.SubmitedRecPayment').length > 0) {
            rpAct = 'Recurring Payment';
            if ($('.RPCredit').length > 0) {
                rpType = 'credit card - recurring';
            }
            if ($('.RPDebit').length > 0) {
                rpType = 'debit card - recurring';
            }
            if ($('.RPCheck').length > 0) {
                rpType = 'checking - recurring';
            }
            if ($('.RPSavings').length > 0) {
                rpType = 'savings - recurring';
            }
            if ($('.RPCancel').length > 0) {
                rpType = 'cancel - recurring'; rpAct += " Cancelled";
            }
            if (null != rpType && rpType.length > 0) {
                sendSiteCatalystEvar20($(this), 'eVar20', rpType);
                sendSiteCatalystProp6ErrorProof($(this), 'prop6', rpAct);
            }
        }
        // COPPA SC Logic
        if ($('.scCoppaA').length > 0) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'COPPA accepted');
        }
        if ($('.scCoppaB').length > 0) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'COPPA bypassed');
        }

        if ($('.TV_RATING').length > 0) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'parental control TV rating locks set');
        }
        if ($('.MOVIE_RATING').length > 0) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'parental control movie rating locks set');
        }
        if ($('.CHANNEL').length > 0) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'parental control network locks set');
        }
        // COPPA extras
        if ($('.scParConOff').length > 0) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'parental control turned OFF');
        }
        if ($('.scParConPinU').length > 0) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'parental control pin updated');
        }
        if ($('.scParConRaS').length > 0) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'parental control pin set');
        }
        //AutoPay.aspx and SinglePayment but Single Payment will not be used becuase ReportingRecurring is set to null
        $('.ContractTermsClientAcceptButton').click(function(e) {
            if (typeof (ReportingRecurringPayment) != "undefined") {
                if (ReportingRecurringPayment.length > 0) {
                    sendSiteCatalystEvar20($(this), 'eVar20', ReportingRecurringPayment);
                }
            }
        });
        $('.ElectronicEnable input').click(function(e) {
            paperless = 'ElectronicBill';
        });
        $('.ElectronicUpdate').click(function(e) {
            if (jQuery('.electronicButton input').attr('checked') != true) {
                sendSiteCatalystEvent8($(this), 'event8', 'Electronic Bill Enrollment')
            };
        });


        $('.register').click(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'New Account Created');
        });

        if ($('.UserWasReconciled').length == 1) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'Account Reconciled');
        }

        $('.PaperlessBill').click(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'Register for Paperless Billing');

        })

        $('.ViewBillPDF').click(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'View Bill Details PDF');
        });

        $('.ChangeSecurityPIN').click(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'Change Security PIN');
        });

        $('.AccountAliasUpdated').click(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'Account Alias Updated');
        });

        //EmailSpamFilter.aspx
        $('.EmailSpamFiltering_Enabled input').click(function(e) {
            emailSpam = 'Email Spam Filtering Enabled';
        })
        $('.EmailSpamFiltering_Disabled input').click(function(e) {
            emailSpam = 'Email Spam Filtering Disabled';
        })
        $('.emailSpamFilterUpdate').click(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', emailSpam);
        })

        //EmailForwarding.aspx
        $('.EmailForwarding_Enabled input').click(function(e) {
            emailForward = 'Email Fowarding Enabled';
        });
        $('.EmailForwarding_Disabled input').click(function(e) {
            emailForward = 'Email Fowarding Disabled';
        })
        $('.emailForwardingUpdate').click(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', emailForward);
        })

        //EmailAuotReply.aspx
        $('.EmailAutoReply_Enabled input').click(function(e) {
            emailAutoReply = 'Email Auto-Reply Enabled';
        })
        $('.EmailAutoReply_Disabled input').click(function(e) {
            emailAutoReply = 'Email Auto-Reply Disabled';
        })
        $('.emailAutoReplyUpdate').click(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', emailAutoReply);
        })

        //EmailRestrictions.aspx
        $('.EmailRestrictions_Allow input').click(function(e) {
            emailRestricts = 'Email Restrictions Allow All';
        })
        $('.EmailRestrictions_Block input').click(function(e) {
            emailRestricts = 'Email Restrictions Block All';
        })
        $('.EmailRestrictions_Filter input').click(function(e) {
            emailRestricts = 'Only Allow Email From Addresses';
        })
        $('.emailRestrictionsUpdate').click(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', emailRestricts);
        })

        //HSIPlaxoAutoSharing.aspx
        $('.HSIPlaxoAutoSharing_Enabled input').click(function(e) {
            hsiPlaxoAutoSharing = 'Plaxo Sharing Enabled';
        })
        $('.HSIPlaxoAutoSharing_Disabled input').click(function(e) {
            hsiPlaxoAutoSharing = 'Plaxo Sharing Disabled';
        })
        $('.hsiPlaxoAutoSharingUpdate').click(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', hsiPlaxoAutoSharing);
        })

        //HSIPersonalWebPages
        $('.HSIPersonalWebPages_Enabled input').click(function(e) {
            hsiPersonalWebPages = 'Personal Webpages Enabled';
        })
        $('.HSIPersonalWebPages_Disabled input').click(function(e) {
            hsiPersonalWebPages = 'Personal Webpages Disabled';
        })
        $('.hsiPersonalWebPagesUpdate').click(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', hsiPersonalWebPages);
        })

        // --------------EasySolve  events ---------------------------------

        if ($("#addressTypeChk").length > 0) {
            var validationChk = {
                //BrowserChk : (jQuery.browser.msie && (jQuery.browser.version == "6.0" ||jQuery.browser.version == "7.0" || jQuery.browser.version == "8.0" || jQuery.browser.version == "9.0")),
                OS: (navigator.appVersion.indexOf("Win") != -1),
                Residential: ($("#addressTypeChk").val() == "Residential"),
                NonResidential: ($("#addressTypeChk").val() == "NonResidential"),
                NonHsi: ($("#addressTypeChk").val() == "NonHSI"),
                AddressTypeEmpty: ($("#addressTypeChk").val() == "")

            };
            //Set the help tab to active. 
            $(".cat-home").removeClass("active");
            $(".cat-help").addClass("active");


            // Check Operation system Mac/Windows. Show message for non Windows OS
            if (!validationChk.OS) {
                // OS  Failure  Msg
                $("#PnlErrorMessage").show();
                $("#OSMsg").show();
            } else if (validationChk.AddressTypeEmpty) {
                // Service  Failure  Msg
                $("#PnlErrorMessage").show();
                $("#ServerErrorMsg").show();
            } else if (validationChk.NonHsi) {
                // HSI  failure  Msg
                $("#PnlErrorMessage").show();
                $("#NonHsiMsg").show();
            } else if (validationChk.NonResidential) {
                // Residential failure  Msg
                $("#PnlErrorMessage").show();
                $("#NonResidentialMsg").show();
            } else if (validationChk.Residential) {
                // AddressType returns "True" for Residential/Home User Only
                $("#PnlDownloadInstructions").show();
                setTimeout("location.replace('" + $('#downloadLink').attr('href') + "');", 1000);
            }
        }
        //  Show and provide link for customer promo logo in U+S Page
        $('#custinfologo').click(function(e) {
            window.location.href = $('#custinfologo a').attr('href');
        })




        //End SiteCatalyst event tracking

        // ODOL lock image synchronizer
        function synchronizeLocks(checkbox) {
            // parentNode is kinda fragile but .NET wraps checkboxes in spans... because IDK why.  MS rocks!
            var classes = checkbox.parentNode.className.split(/\s+/);
            var len = classes.length;
            for (var i = 0; i < len; ++i) {
                if (classes[i].indexOf("Index_") != -1) {
                    var lockImage = $('img.' + classes[i]);
                    checkbox.checked ? lockImage.removeClass('lockHidden') : lockImage.addClass('lockHidden');
                    break;
                }
            }
        }

        // ODOL ratings checkbox auto-clicker
        var odolRatingsCheckboxes = $('.RatingResource input');

        // uncheck all boxes till the one that was manipulated,
        // check everything after
        // this runs on the assumption that the list is in source order
        odolRatingsCheckboxes.click(function() {
            var checkedBox = this;
            var checkThem = false;
            odolRatingsCheckboxes.each(function() {
                if (checkedBox == this) {
                    checkThem = true;
                } else {
                    this.checked = checkThem;
                }
                synchronizeLocks(this);
            });
        });

        //ODOL Rating Lock Checker
        $('.ODOLLock input').click(function() {
            synchronizeLocks(this);
        });


        $('.TierDoNotAllowAdditionalCharges input').click(function(e) {
            fusion.openTipAt('#tipAutobillFalseSelected', $(this).offset());
        });

        $('.OpenChatWindow').each(function() {
            var linkTag = $(this);
            linkTag.attr('href', 'http://www.comcastsupport.com/chat');
            linkTag.attr('target', '_blank');
            linkTag.click(function(e) {
                window.open('http://www.comcastsupport.com/chat', '_blank', 'height=700,width=800,scrollbars=yes');
                e.preventDefault();
            });
        });

        $('.OpenChatWindowPlus').each(function() {
            var linkTag = $(this);
            linkTag.attr('href', 'http://www.comcastsupport.com/chat');
            linkTag.attr('target', '_blank');
            linkTag.click(function(e) {
                window.open('http://www.comcastsupport.com/chat', '_blank', 'height=700,width=800,scrollbars=yes');
                sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'Inactive Account Pay Bill Chat Initiated');
                e.preventDefault();
            });
        });

        $('.OpenReconcilliationChatWindow').each(function() {
            var linkTag = $(this);
            linkTag.attr('href', 'https://www.comcastsupport.com/sdcxuser/rrn/issue_new.asp?contact_method=1&Kernel::Kernel::sik_iss_type=4fe5ce86-a64e-4ae9-8389-13dfde454d85');
            linkTag.attr('target', '_blank');
            linkTag.click(function(e) {
                window.open('https://www.comcastsupport.com/sdcxuser/rrn/issue_new.asp?contact_method=1&Kernel::Kernel::sik_iss_type=4fe5ce86-a64e-4ae9-8389-13dfde454d85', '_blank', 'height=700,width=800,scrollbars=yes');
                sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'Inactive Account Chat Initiated');
                e.preventDefault();
            });
        });

        if ($('.ScrollerContainer').length == 1) {
            $(window).scrollTop($('#tierOptionsScrollTop').offset().top);
        }

        if ($('#preloadgraphic').length == 1) {

            function mobileSetup() {
                $('#container').hide();
                $('#loadingMessage').text('Retrieving Information');
            }
            function androidSetup() {
                $('#preloadgraphic').attr("style", "width:500px; padding-left: 60px;");
                $('#core').css("position", "absolute").css("left", "0px");
                mobileSetup();
            }

            var backTo = readQuerystring()['backto'];
            $('#container').show();
            if (swfobject.hasFlashPlayerVersion("9")) {
                var attributes = { data: '/App_Themes/Default/swf/AppLoader.swf', width: '200', height: '80', align: 'middle' };
                if (mobileAgent.android) {
                    androidSetup();
                    attributes.data = '/App_Themes/Default/swf/AppLoaderMobile.swf';
                }
                var params = { allowScriptAccess: 'sameDomain', allowFullScreen: 'false', quality: 'high', bgcolor: '#ffffff' };
                swfobject.createSWF(attributes, params, 'preloadStaticGraphic');
            } else {
                if (mobileAgent.ipad || mobileAgent.iphone) {
                    mobileSetup();
                }
                if (mobileAgent.android) {
                    androidSetup();
                }
                $('#preloadStaticGraphic').show();
            }

            $('#loadingMessage').show();

            $.ajax({
                url: window.location.toString() + '&preload=true',
                timeout: 60000,
                complete: function(XMLHttpRequest, textStatus) {
                    if ('success' == textStatus && !!backTo && backTo.indexOf('/') == 0) {
                        location.replace(backTo);
                    } else if ('success' == textStatus) {
                        location.replace('../Secure/Home.aspx');
                    } else {
                        location.replace('../Pages/Exception.aspx');
                    }
                }
            });
        }
        //This function might be redunctant if the 'back' is handle correctly cima 
        function CheckMobileAgent(redirectUrl) {
            var rtnUrl = redirectUrl;
            if ($('#MobileType').length > 0) {
                var getMobileType = $('#MobileType').val();
                if ($('#MobileType').val() == "ipad") {
                    rtnUrl = "../Secure/mobile/ott/Home.aspx";

                } else if ($('#MobileType').val() == "iphone") {
                    rtnUrl = "../Secure/mobile/ott/Home.aspx";
                }
            }
            return rtnUrl;
        }

        var inServiceOutageAjaxRequest = false;
        $('a.ServiceOutageAjaxClicker').click(function(e) {
            e.preventDefault();
            if (!inServiceOutageAjaxRequest) {
                inServiceOutageAjaxRequest = true;
                var link = $(this);
                link.addClass('busy');
                $.ajax({
                    url: '/Secure/ServiceOutageAjaxPage.aspx?mode=' + $('a.ServiceOutageAjaxClicker span').text(),
                    timeout: 60000,
                    dataType: 'html',
                    success: function(data, textStatus) {
                        link.removeClass('busy');
                        var container = $('#ServiceOutageContainer');
                        //container.fadeOut('fast');
                        container.html(data);
                        //container.slideDown(500);
                        inServiceOutageAjaxRequest = false;
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        link.removeClass('busy');
                        var container = $('#ServiceOutageContainer');
                        //container.fadeOut('fast');
                        container.html(
						'<div id="ServiceOutageContainer">' +
							'<h2 style="color:#444444">Comcast Service Health Status</h2>' +
							'<ul><li><div class="service-alert icon-service">We&apos;re sorry; we cannot obtain service outage information for your account at this time.</div></li></ul>' +
						'</div>');
                        //container.slideDown(500);
                        inServiceOutageAjaxRequest = false;
                    }
                });
            }
        });

        $('select.WirelessUsageGraphDeviceSelector').change(fusion.loadWirelessUsageMeter);

        if ($('div.WirelessUsageLoadingDiv').length > 0) { fusion.loadWirelessUsageMeter(); }
        if ($('div.HighSpeed2GoLoadingDiv').length > 0) { fusion.loadWirelessLinks(); }

        // usage meter accordions
        $('.MeterAccordion').each(function() {
            if (!!$(this).accordion) $(this).accordion();
        });

        if ($('div.PerformHSIUpgradeAjaxRequest').length == 1) {
            fusion.performHSIUpgradeIfNeeded();
        }

        if ($('div.DeviceListLoadingMessage').length == 1) {
            fusion.loadDeviceList();
        }

        if ($('#UsageMeterLoadingMessage').length == 1) {
            $.ajax({
                url: "/Secure/UsageMeterAjaxPage.aspx",
                timeout: 60000, // 60 seconds seems reasonable enough for now
                dataType: "html",
                success: function(data, textStatus) {
                    $('#UsageMeterContainer').html(data);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $('#UsageMeterContainer').html("");
                }
            });
        }

        if ((!!$('a.UsageMeterPieChartLink').length) && swfobject.hasFlashPlayerVersion("8")) {
            $('a.UsageMeterPieChartLink').show();
        }

        if ((!!$('a.UsageMeterPieChartMonthlyLink').length)) {
            if (swfobject.hasFlashPlayerVersion("8")) {
                $('a.UsageMeterPieChartMonthlyLink').show();
            } else {
                $('a.UsageMeterPieChartMonthlyLink').each(function() {
                    var link = $(this);
                    link.replaceWith(link.html());
                });
            }
        }

        if ($('#DMCANotificationLoadingMessage').length == 1) {
            $.ajax({
                url: "/Secure/DMCANotificationLinkAjaxPage.aspx",
                timeout: 60000, // 60 seconds seems reasonable enough for now
                dataType: "html",
                success: function(data, textStatus) {
                    $('#DMCANotificationLinkId').html(data);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $('#DMCANotificationLinkId').html("");
                }
            });
        }

        function displayMessageBody(bodyDiv, anchor, td) {
            var div = bodyDiv[0];
            if ((displayMessageBody.currentlyOpen || { div: null }).div == div) {
                bodyDiv.slideUp(200);
                anchor.addClass('closearrow');
                anchor.removeClass('openarrow');
                anchor.attr('title', 'Open');
                td.addClass('close');
                td.removeClass('open');
                $('.readmore', bodyDiv.parent()).remove();
                displayMessageBody.currentlyOpen = null;
            } else {
                if (displayMessageBody.currentlyOpen != null) {
                    var oldBody = $(displayMessageBody.currentlyOpen.div);
                    oldBody.slideUp(200);
                    var a = displayMessageBody.currentlyOpen.anchor;
                    var firsttd = displayMessageBody.currentlyOpen.td;
                    a.removeClass('openarrow');
                    a.addClass('closearrow');
                    a.attr('title', 'Open');
                    firsttd.addClass('close');
                    firsttd.removeClass('open');
                    $('.readmore', oldBody.parent()).remove();
                }
                var force = bodyDiv.hasClass('errormsg');
                var readmoreLines = parseInt($.trim($('#readmoreTriggerLines').html())) || 3;
                var maxHeight = readmoreLines /* lines */ * 17.5 /* line height */;
                bodyDiv.css('overflow', 'hidden')
                if (!fusion.isIE6 && !force) bodyDiv.css('max-height', maxHeight + 'px');
                bodyDiv.slideDown(600, function() {
                    if (!fusion.isIE6 && !force && bodyDiv[0].scrollHeight > maxHeight) {
                        var parentCell = bodyDiv.parent();
                        $('.readmore', parentCell).remove();
                        var readmore = $('<span><a>Read More</a></span>');
                        readmore.addClass('readmore');
                        parentCell.append(readmore);
                        var messageId = $.trim($('.messageid', parentCell).html());
                        var pageNumber = $.trim($('.pagenumber', parentCell).html());
                        var link = $('a', readmore);
                        link.attr('href', '/Secure/AlertDetail.aspx?MessageId=' + messageId + '&PageNumber=' + pageNumber);
                    }
                });
                anchor.addClass('openarrow');
                anchor.removeClass('closearrow');
                anchor.attr('title', 'Close');
                td.removeClass('close');
                td.addClass('open');
                displayMessageBody.currentlyOpen = {
                    div: div,
                    anchor: anchor,
                    td: td
                };
            }
        }
        displayMessageBody.currentlyOpen = null;

        var alertLoadErrorHTML = $('#alertBodyErrorMessage').html();
        var messageTrigger = function(e) {
            var tr = $(this).parent();
            var firsttd = $('td.arrowopen', tr);
            var a = $('a', firsttd);
            var messageId = $.trim($('.messageid', tr).html());
            var outputDiv = $('.alertipsum', tr);
            if ($.trim(outputDiv.html()) == "") {
                e.preventDefault();
                if (!tr.ajaxInProgress) {
                    tr.ajaxInProgress = true;
                    var to = window.setTimeout(function() {
                        a.removeClass('closearrow');
                        a.addClass('busy');
                    }, 250);
                    $.ajax({
                        url: "/Secure/AlertBodyAjaxPage.aspx?MessageId=" + messageId,
                        timeout: 30000,
                        dataType: "html",
                        success: function(data) {
                            tr.ajaxInProgress = false;
                            if (!!to) window.clearTimeout(to);
                            a.removeClass('busy');
                            if (data != "") {
                                tr.removeClass('unread');
                                outputDiv.html(data);
                                displayMessageBody(outputDiv, a, firsttd);
                            } else {
                                outputDiv.html(alertLoadErrorHTML);
                                outputDiv.addClass('errormsg');
                                displayMessageBody(outputDiv, a, firsttd);
                            }
                        },
                        error: function() {
                            tr.ajaxInProgress = false;
                            if (!!to) window.clearTimeout(to);
                            a.removeClass('busy');
                            outputDiv.html(alertLoadErrorHTML);
                            outputDiv.addClass('errormsg');
                            displayMessageBody(outputDiv, a, firsttd);
                        }
                    });
                }
            } else if (e.target.className != 'alertipsum' &&
                       $(e.target).parents('.alertipsum').length == 0 &&
                       e.target.className != 'readmore' &&
                       $(e.target).parents('.readmore').length == 0) {
                e.preventDefault();
                displayMessageBody(outputDiv, a, firsttd);
            }
        }

        var deleteTrigger = function(e) {
            e.preventDefault();
            var a = $(this);
            var tr = a.parent().parent();
            var messageId = $.trim($('.messageid', tr).html());
            var container = $('#Message_' + messageId);
            var pageNumber = $.trim($('#CurrentPageNumber').html());

            if (!tr.ajaxInProgress) {
                tr.ajaxInProgress = true;
                var to = window.setTimeout(function() {
                    a.removeClass('deletebackground');
                    a.addClass('busy');
                }, 250);
                $.ajax({
                    timeout: 30000,
                    dataType: "html",
                    url: "/Secure/DeleteAlertAjaxPage.aspx?MessageId=" + messageId + "&PageNumber=" + pageNumber,
                    success: function(data) {
                        if (!!to) window.clearTimeout(to);
                        a.addClass('deletebackground');
                        a.removeClass('busy');
                        data = $.trim(data);
                        if (data != "") {
                            container.slideUp(400, function(e) { container.remove(); });
                            var workspace = $('.AlertsWorkspace');
                            workspace.html(data);
                            var newAlert = $('.AlertToAdd', workspace).children();
                            var newPagingLinks = $.trim($('.NewPagingLinks', workspace).html());
                            if ($.trim($('.GoToPreviousPage', workspace).html()) == 'true') {
                                window.location.href = $('#PreviousAlertsPage').attr('href');
                            } else if ($('.NoMoreAlerts', workspace).length == 1) {
                                $('.alertsTable').html($('.NoMoreAlerts', workspace).html());
                                $('.alertsTable').addClass('alertsMessage');
                                $('#PageNavContainer').html('');
                            } else {
                                $('#PageNavContainer').html(newPagingLinks);
                                if (newAlert.length == 1) {
                                    $('.alertsTable').append(newAlert);
                                    $('a.delete', newAlert).click(deleteTrigger);
                                    $('.messagetrigger', newAlert).click(messageTrigger);
                                    newAlert.slideDown(400);
                                }
                            }
                            workspace.html('');
                        } else {
                            // somehow indicate the error
                            tr.ajaxInProgress = false;
                            fusion.centerTipOn('#tipDeleteError', a);
                        }
                    },
                    error: function() {
                        if (!!to) window.clearTimeout(to);
                        a.addClass('deletebackground');
                        a.removeClass('busy');
                        tr.ajaxInProgress = false;
                        fusion.centerTipOn('#tipDeleteError', a);
                    }
                });
            }
        }

        $('a.delete').click(deleteTrigger);
        $('.messagetrigger').click(messageTrigger);
        $('a.displayThisAlert').click();

        if ($.ui && $.ui.autocomplete) {
            var searchField = $('.searchfield');
            var searchButton = $('.searchbutton');

            function autocompleteFilter(info) {
                var output = [];
                if (info && info.length) {
                    var matchRE = new RegExp(info[0], 'gi');
                    for (var i = 2, l = info.length; i < l; ++i) {
                        if (info[i]) output[output.length] = {
                            label: info[i].replace(matchRE, autocompleteFilter.subber),
                            value: info[i]
                        }
                        // only use 10
                        if (output.length == 10) break;
                    }
                }

                if (jQuery.support.boxModel && output[0]) output[0].label = output[0].label + '<div class="suggestions-banner">Suggestions</div>';
                return output;
            }

            autocompleteFilter.subber = function(text) {
                return '<strong>' + text + '</strong>';
            }

            autocompleteFilter.cache = {};

            autocompleteFilter.stayClosed = false;

            $.widget('custom.autocompleteWithClose', $.ui.autocomplete, {
                _renderMenu: function(ul, items) {
                    var self = this;
                    var last = null;
                    $.each(items, function(index, item) {
                        last = self._renderItem(ul, item);
                    });
                    var closer = $('<span class="autocomplete-closer">Close</span>');
                    last.append(closer);
                    closer.click(function() { autocompleteFilter.stayClosed = true; self.close(); });
                }
            });

            autocompleteFilter.checkReopen = function() {
                if (!this.value) autocompleteFilter.stayClosed = false;
            }

            searchField.autocompleteWithClose({
                delay: 0, // just go baby
                //offset: "-6px 6px",
                source: function(request, response) {
                    var self = this;
                    if (autocompleteFilter.cache[request.term]) {
                        response(autocompleteFilter.cache[request.term]);
                    }
                    else {
                        $.ajax({
                            cache: true,
                            // if it takes longer than 1 second it's pointless anyway
                            timeout: 1000 * 1,
                            url: "/Pages/SearchSuggest.aspx",
                            data: request,
                            dataType: "json",
                            success: function(data) {
                                autocompleteFilter.cache[request.term] = autocompleteFilter(data);
                                response(autocompleteFilter.cache[request.term]);
                            },
                            error: function() {
                                // close the suggestions for now, not
                                // sure what else makes sense here
                                //self.close();
                            }
                        });
                    }
                },
                select: function(event, ui) {
                    if (ui.item) {
                        searchField.val(ui.item.value);
                    }
                    searchButton.inclick = true;
                    searchButton.click();
                    return false;
                },
                open: function(event, ui) {
                    return true;
                },
                search: function(event, ui) {
                    return !autocompleteFilter.stayClosed;
                }
            });

            searchField.change(autocompleteFilter.checkReopen);
            searchField.focus(function() { searchField.focused = true; });
            searchField.blur(function() { searchField.focused = false; });
            searchField.keydown(function(event) {
                if ((fusion.isIE7p || fusion.isIE6) &&
					(event.keyCode == $.ui.keyCode.ENTER ||
					event.keyCode == $.ui.keyCode.NUMPAD_ENTER)) {
                    searchButton.click();
                    event.preventDefault();
                }
                autocompleteFilter.checkReopen();
            });
            searchField.mouseup(autocompleteFilter.checkReopen);
            searchButton.mousedown(function() { searchButton.inclick = true; });
            searchButton.click(function(e) {
                if (!searchField.focused && !searchButton.inclick) {
                    e.preventDefault();
                } else if (searchField.val() == "") {
                    alert('Please enter keyword(s) and try again');
                    e.preventDefault();
                }
                searchButton.inclick = false;
            });
        }

        var handleContractButton = function() {
            if (this.checked) {
                $('.ContractTermsClientAcceptButton').removeClass('disabledBtn');
                $('.ContractTermsClientAcceptButton').attr('disabled', false);
            }
            else {
                $('.ContractTermsClientAcceptButton').addClass('disabledBtn');
                $('.ContractTermsClientAcceptButton').attr('disabled', true);
            }
        }

        $('.ContractTermsAcceptCheckBox input').click(handleContractButton);
        $('.ContractTermsAcceptCheckBox input').each(handleContractButton);

        var handleCOPPAContractButton = function() {
            if (this.checked) {
                $('.COPPAContractTermsClientAcceptButton').removeClass('disabledBtn');
            }
            else {
                $('.COPPAContractTermsClientAcceptButton').addClass('disabledBtn');
            }
        }

        $('.COPPAContractTermsAcceptCheckBox input').click(handleCOPPAContractButton);
        $('.COPPAContractTermsAcceptCheckBox input').each(handleCOPPAContractButton);

        $('input.ReconciliationRadioButton').click(function() {
            // hide all the passwords
            $('div.ReconciliationPasswordBundle').hide();
            if (this.checked) $('div#' + this.id + '_password_bundle').show();
        });

        $('input.ReconciliationRadioButton:checked').each(function() {
            if (this.checked) $('div#' + this.id + '_password_bundle').show();
        });


        $('div.validationSummary').each(function() {
            if ($(this).find("li").length == 1) {
                $(this).html($($(this).find("li")[0]).html())
            }
        });
        $('input.noPaste').bind('paste', function(e) {
            e.preventDefault();
            $('#noPastingEmailsTip').click();
        });

        $('input.AccountNumberEntryField').bind('keyup', function(e) {
            var keyCode = e.which;
            // Ignore backspace, delete, left and right
            if (keyCode != 8 && keyCode != 46 && keyCode != 39 && keyCode != 37) {
                var number = this.value;
                if (number.length > 0) {
                    if (number.charAt(0) == '8') {
                        this.maxLength = 16;
                    } else {
                        if (number.indexOf("  ") > 0) {
                            number = number.replace("  ", " ");
                            this.value = number;
                        }
                        if (number.indexOf("--") > 0) {
                            number = number.replace("--", "-");
                            this.value = number;
                        }
                        this.maxLength = 17;

                        var oRegCorp = /^(\d{5}$)/;
                        var oRegHouse = /^(\d{5})(?: |-)(\d{6}$)/;
                        var oRegCust = /^(\d{5})(?: |-)(\d{6})-(\d{2}$)/;
                        var oRegFull = /^(\d{5})(?: |-)(\d{1,6})-(\d{1,2})-(\d$)/;
                        if (oRegCorp.test(number)) {
                            this.value = number + " ";
                        }
                        else if (oRegHouse.test(number)) {
                            this.value = number + "-";
                        }
                        else if (oRegCust.test(number)) {
                            this.value = number + "-";
                        }
                        else if (oRegFull.test(number)) {
                            var zeros = "000000"
                            var m = number.match(oRegFull);
                            var Corp = m[1];
                            var House = m[2];
                            var Cust = m[3];
                            var Check = m[4];
                            if (House.length < 6) // pad with leading zeros
                                House = zeros.substr(0, 6 - House.length) + House
                            if (Cust.length < 2)
                                Cust = zeros.substr(0, 2 - Cust.length) + Cust
                            this.value = Corp + " " + House + "-" + Cust + "-" + Check;
                        }
                    }
                }
            }
        });
        // validate US phone number only
        var phoneNumberPattern = new RegExp(/^\d{3}-\d{3}-\d{4}$/);
        // This is Pref.Cent. validate  New Home and Work No#
        $('#validateHomePhone input.piPhoneInput').bind('keyup', function() {
            phoneNumberPattern.test($.trim($('#validateHomePhone input.piPhoneInput').val())) == true ? switchPhoneNoButtons(true) : switchPhoneNoButtons(false);
        });

        $('#validateWorkPhone input.piPhoneInput').bind('keyup', function() {
            phoneNumberPattern.test($.trim($('#validateWorkPhone input.piPhoneInput').val())) == true ? switchPhoneNoButtons(true) : switchPhoneNoButtons(false);
        });


        function switchPhoneNoButtons(status) {
            if (status) {
                $('.piPhoneButton.disabledBtn').removeClass('disabledBtn');
                $('.piPhoneButton').attr('disabled', false);
            }
            else {
                $('.piPhoneButton').addClass('disabledBtn');
                $('.piPhoneButton').attr('disabled', true);
            }
        }

        $('input.newPassword').bind('keyup', function() {
            var ps = Math.round(fusion.pwdStrength($(this).val()));
            //console.warn(ps);
            $('#passStrength p').width(ps + '%').text(ps + '%');
        });

        // 'Select All Alerts' button on Home Page
        $('#alertSummary #selectall').click(function() {
            $('#alertSummary li input').attr('checked', true);
            return false;
        });

        // Dropdown selection of bill history
        if (document.forms.chooseBill) {
            $(document.forms.chooseBill).find('input[type=submit]').hide();
            $(document.forms.chooseBill.bill).bind('change', function() {
                document.forms.chooseBill.submit();
            });
        }



        var time = parseInt($('span#loginTimeRaw').html());
        if (!isNaN(time)) {
            var now = new Date(time);
            $('span#loginTimeDisplay').html(formatLastLoginTime(now));
        }


        $('a.overlayItem').click(fusion.overlayClickEvent);

        $('.printButton').click(function(e) { window.print(); e.preventDefault(); return false; });

        $('.preventClicks').click(function() { return false; })

        $(window).resize(fusion.windowResized);

        $('#contactToggle').add('#contactClose a').click(function() {
            $('#contactOverlay').toggle();
            return false;
        });

        var saveditems = {};

        var personalInfoFields = { "Fields":
            [
                { "Name": "#ctl00_ContentArea_FirstName" },
                { "Name": "#ctl00_ContentArea_LastName" },
                { "Name": "#ctl00_ContentArea_DisplayName" },
                { "Name": "#ctl00_ContentArea_NewContactEmailTxt" },
                { "Name": "#ctl00_ContentArea_ConfirmContactEmailTxt" },
                { "Name": "#ctl00_ContentArea_ConfirmAccountEmailTxt" },
                { "Name": "#ctl00_ContentArea_NewAccountEmailTxt" },
                { "Name": "#ctl00_ContentArea_SendAllCommunications" }

            ]
        };
        if ($('.PersonalInfoPage').length > 0) {
            for (i = 0; i < personalInfoFields.Fields.length; i++) {
                if ($(personalInfoFields.Fields[i].Name).attr('type') == 'checkbox')
                    saveditems[personalInfoFields.Fields[i].Name] = ($(personalInfoFields.Fields[i].Name).attr('checked') == true ? '1' : '0');
                else
                    saveditems[personalInfoFields.Fields[i].Name] = $.trim($(personalInfoFields.Fields[i].Name).val());
            }

        }

        $('.PersonalInfoPage').click(function() {
            for (i = 0; i < personalInfoFields.Fields.length; i++) {
                if ($(personalInfoFields.Fields[i].Name).attr('type') == 'checkbox') {
                    saveditems[personalInfoFields.Fields[i].Name] != ($(personalInfoFields.Fields[i].Name).attr('checked') == true ? '1' : '0');
                    return true;
                }
                else if (saveditems[personalInfoFields.Fields[i].Name].toLowerCase() != $.trim($(personalInfoFields.Fields[i].Name).val()).toLowerCase()) {
                    return true;
                }
            }
            document.fusion.closeScreen();
            return false;
        });





        fusion.initScreen();

        fusion.markActivityTime();
        fusion.checkFirstTimeRequiredActions();

        if ((window.location.hash || "").length > 1) {
            var overlay = $("." + window.location.hash.substring(1) + "Link");
            if (overlay.hasClass('overlayItem')) {
                overlay.click();
            }
        } else if ((window.location.search || "").length > 1) {
            var overlay = $("." + window.location.search.substring(1) + "Link");
            if (overlay.hasClass('overlayItem')) {
                overlay.click();
            }
        }

        if ($('span#loginTimeDisplay').length > 0) { // if time is present, someone is authenticated
            window.setInterval(fusion.checkActivityTimeout, 20 * 1000 + 100); // every 20ish seconds, check if the activity timeout has expired
        }



    });


    $.fn.extend({

        center: function() {
            return this.each(function() {

                var myWidth = $(this).outerWidth(),
					myHeight = $(this).outerHeight(),
					winWidth = $(window).width(),
					winHeight = $(window).height(),
					leftScroll = $(window).scrollLeft(),
					topScroll = $(window).scrollTop();

                var newTop = ((winHeight / 2) - (myHeight / 2)) + topScroll,
					newLeft = ((winWidth / 2) - (myWidth / 2)) + leftScroll;

                if (newTop < 0) {
                    newTop = 0;
                } else if (newTop < topScroll) {
                    newTop = topScroll;
                }

                if (newLeft < 0) {
                    newLeft = 0;
                } else if (newLeft < leftScroll) {
                    newLeft = leftScroll;
                }

                $(this).css('position', 'absolute');
                $(this).css('top', newTop);
                $(this).css('left', newLeft);

            });
        }

    });


    var fusion = window.fusion = {



        /// device list stuff


        enableDeviceListLinks: function() {
            var context = $('div.DeviceListOutputDiv');
            $('a.overlayItem', context).click(fusion.overlayClickEvent);
            $('a[rel=tooltip]', context).click(fusion.openTooltip);
            $('#tipDomainHelper').click(fusion.closeTooltip);
        },

        loadWirelessLinks: function() {
            $.ajax({
                url: '/Secure/WirelessLinksAjaxPage.aspx',
                timeout: 60000, // 60 seconds seems reasonable enough for now
                dataType: 'html',
                success: function(data, textStatus) {
                    if (data.indexOf('<div class="wrapper">') != -1) {
                        $('#WirelessLinksContainer').html(data);
                        window.setTimeout(function() {
                            var context = $('#WirelessLinksContainer');
                            $('a[rel=tooltip]', context).click(fusion.openTooltip);
                            $('a.overlayItem', context).click(fusion.overlayClickEvent);
                            $('div.tooltip a.tipClose', context).click(fusion.closeTooltip);
                        }, 150);
                    } else {
                        $('#WirelessLinksContainer').html('');
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $('#WirelessLinksContainer').html('');
                }
            });
        },

        loadWirelessUsageMeter: function() {
            var device = !!this.options ? this.options[this.selectedIndex].value : null;
            var errorMessage = !!device ? '<p>An error occurred while servicing your request.</p>' : '';
            $.ajax({
                url: '/Secure/WirelessUsageMeterAjaxPage.aspx' + (!!device ? '?device=' + device : ''),
                timeout: 60000, // 60 seconds seems reasonable enough for now
                dataType: 'html',
                success: function(data, textStatus) {
                    if (data.indexOf('<div class="module">') < 10) {
                        $('#WirelessUsageMeterContainer').html(data);
                        window.setTimeout(function() {
                            $('select.WirelessUsageGraphDeviceSelector').change(fusion.loadWirelessUsageMeter);
                        }, 150);
                    } else {
                        $('#WirelessUsageMeterContainer').html(errorMessage);
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $('#WirelessUsageMeterContainer').html(errorMessage);
                }
            });
        },

        loadDeviceList: function() {
            $.ajax({
                url: "/Secure/DeviceListAjaxResponse.aspx",
                timeout: 120000, // this list can take a while?
                dataType: "html",
                success: function(data, textStatus) {
                    if (data.indexOf('<div class="module">') < 10) {
                        $('#DeviceListContainer').html(data);
                        window.setTimeout(fusion.enableDeviceListLinks, 100);
                        //Make image visible
                    } else {
                        $('#DeviceListContainer').html('<p>An error occurred while servicing your request.</p>');
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $('#DeviceListContainer').html('<p>An error occurred while servicing your request.</p>');
                }
            });
        },


        performHSIUpgradeIfNeeded: function() {
            $.ajax({
                url: "/Secure/PerformHSIUpgradeAjax.aspx",
                timeout: 120000,
                dataType: "html",
                success: function() { },
                error: function() { }
            });
        },

        lastActivityTime: 0,
        activityTimeout: 15 * 60 * 1000, // fifteen minutes

        markActivityTime: function() {
            fusion.lastActivityTime = new Date().getTime();
        },

        checkActivityTimeout: function() {

            var now = new Date().getTime();

            if (now - fusion.lastActivityTime > fusion.activityTimeout) {
                fusion.closeScreen();
                window.location.replace('/LogOut/logout.aspx?m=to');
            }
        },

        onScreenClose: null,

        overlayClickEvent: function() {
            var noCloseButton = $(this).hasClass('noOverlayCloseButton');

            if (!$(this).hasClass('disabled')) {
                fusion.openScreen($(this).attr('rel'), noCloseButton);
            }
            return false;
        },

        redirectCOPPAClose: function() {
            window.location.pathname = '/Secure/Users.aspx';
        },

        moversUrl: null,
        redirectSinglePaymentClose: function() {
            window.location.href = fusion.moversUrl;
        },

        alernateemailOnClose: function() {
            fusion.closeScreenAndLogout()
        },


        checkFirstTimeRequiredActions: function() {

            if ($('div.alternateEmail:not(div.completed)').length > 0) {

                $('div.alternateEmail').addClass('completed');
                fusion.openScreen("/Secure/AddAlternativeEmailAddress.aspx?m=Downgrade", false, fusion.alernateemailOnClose);

            } else if ($('div.undeliverableEmail:not(div.completed)').length > 0) {

                $('div.undeliverableEmail').addClass('completed');
                fusion.openScreen("/Secure/AddAlternativeEmailAddress.aspx?m=ReplaceUndeliverableStatus", true, fusion.checkFirstTimeRequiredActions);

            } else if ($('div.singlePayment:not(div.completed)').length > 0) {
                $('div.singlePayment').addClass('completed');
                fusion.moversUrl = $('div.singlePayment').text();
                fusion.openScreen("/Secure/SinglePayment.aspx", false, fusion.redirectSinglePaymentClose);

            } else if ($('a.CPNIEnablementLink:not(a.completed)').length > 0) {

                $('a.CPNIEnablementLink').addClass('completed');
                fusion.openScreen($('a.CPNIEnablementLink').attr('rel'), true, fusion.checkFirstTimeRequiredActions);

            } else if ($('div.requireConditionsAcceptance:not(div.completed)').length > 0) {

                $('div.requireConditionsAcceptance').addClass('completed');
                var params = readQuerystring();
                fusion.openScreen('/Secure/FirstTimeLoginTerms.aspx' + (params['ecobill'] ? '?ecobill=' + params['ecobill'] : ''), true, fusion.checkFirstTimeRequiredActions);

            } else if ($('div.requireSecurityQuestionSetup:not(div.completed)').length > 0) {

                $('div.requireSecurityQuestionSetup').addClass('completed');
                fusion.openScreen("/Secure/UpdateSQA.aspx", true, fusion.checkFirstTimeRequiredActions);
            } else if ($('div.informAccountNotActive:not(div.completed)').length > 0) {

                $('div.informAccountNotActive').addClass('completed');
                fusion.openScreen("/Pages/Fallout2.aspx", false, fusion.checkFirstTimeRequiredActions);

                //EcoBill check should always be last
            } else if ($('div.ecobill:not(div.completed)').length > 0) {
                $('div.ecobill').addClass('completed');
                fusion.openScreen("/Secure/EcoBill.aspx", false, fusion.checkFirstTimeRequiredActions);
            } else {
                $('.deepLinkItem').click();
            }
        },

        pwdStrength: function(passwd) {

            /* ************************************************************
            Created: 20060120
            Author:  Steve Moitozo <god at zilla dot us> -- geekwisdom.com
            Description: This is a quick and dirty password quality meter 
            written in JavaScript so that the password does 
            not pass over the network.
            License: MIT License (see below)
            Modified: 20060620 - added MIT License
            Modified: 20061111 - corrected regex for letters and numbers
            Thanks to Zack Smith -- zacksmithdesign.com
            ---------------------------------------------------------------
            Copyright (c) 2006 Steve Moitozo <god at zilla dot us>
        			
            Permission is hereby granted, free of charge, to any person 
            obtaining a copy of this software and associated documentation 
            files (the "Software"), to deal in the Software without 
            restriction, including without limitation the rights to use, 
            copy, modify, merge, publish, distribute, sublicense, and/or 
            sell copies of the Software, and to permit persons to whom the 
            Software is furnished to do so, subject to the following 
            conditions:
        			
            The above copyright notice and this permission notice shall 
            be included in all copies or substantial portions of the 
            Software.
        			
            THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY 
            KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
            WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE 
            AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
            HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
            WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
            FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 
            OR OTHER DEALINGS IN THE SOFTWARE. 
            ************************************************************ */

            var score = 0;
            var maxScore = 38;
            var strLog = "";

            // PASSWORD LENGTH

            // length 4 or less
            if (passwd.length < 5) {
                score += 3;
                strLog += "3 points for length (" + passwd.length + ")\n";
                // length between 5 and 7
            } else if (passwd.length > 4 && passwd.length < 8) {
                score += 6;
                strLog += "6 points for length (" + passwd.length + ")\n";
                // length between 8 and 15
            } else if (passwd.length > 7 && passwd.length < 16) {
                score += 12;
                strLog += "12 points for length (" + passwd.length + ")\n";
                // length 16 or more
            } else if (passwd.length > 15) {
                score += 18;
                strLog += "18 points for length (" + passwd.length + ")\n";
            }

            // LETTERS (Not exactly implemented as dictacted above because of my limited understanding of Regex)

            // [verified] at least one lower case letter
            if (passwd.match(/[a-z]/)) {
                score += 1;
                strLog += "1 point for at least one lower case char\n";
            }

            // [verified] at least one upper case letter
            if (passwd.match(/[A-Z]/)) {
                score += 5;
                strLog += "5 points for at least one upper case char\n";
            }

            // NUMBERS

            // [verified] at least one number
            if (passwd.match(/\d+/)) {
                score += 5;
                strLog += "5 points for at least one number\n";
            }

            // [verified] at least three numbers
            if (passwd.match(/(.*[0-9].*[0-9].*[0-9])/)) {
                score += 5;
                strLog += "5 points for at least three numbers\n";
            }

            // SPECIAL CHAR

            // [verified] at least one special character
            /*if (passwd.match(/.[!,@,#,$,%,^,&,*,?,_,~]/)) {
            score += 5;
            strLog += "5 points for at least one special character\n";
            }*/

            // [verified] at least two special characters
            /*if (passwd.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) {
            score += 5;
            strLog += "5 points for at least two special characters\n";
            }*/

            // COMBOS

            // [verified] both upper and lower case
            if (passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) {
                score += 2;
                strLog += "2 combo points for upper and lower letters\n";
            }

            // [verified] both letters and numbers
            if (passwd.match(/([a-zA-Z])/) && passwd.match(/([0-9])/)) {
                score += 2;
                strLog += "2 combo points for letters and numbers\n";
            }

            // [verified] letters, numbers, and special characters
            /*if (passwd.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/)) {
            score += 2;
            strLog += "2 combo points for letters, numbers and special characters\n";
            }*/

            // original code modified to return percent score
            return ((score / maxScore) * 100);

        },

        loadingMessages: [
	        "Comcastic",
	        "Triple Play",
	        "Digital Cable",
	        "High-Speed Internet",
	        "Digital Voice"
	    ],



        doLoadingMessages: function() {
            var index = Math.floor(Math.random() * fusion.loadingMessages.length);
            $('#loadingMessage').html(fusion.loadingMessages[index]);
            window.setTimeout(fusion.doLoadingMessages, 5000);
        },
        roundCorner: function(input_id, container_class, border_class) {
            var input = $('#' + input_id + '');
            var input_width = input.css("width"); //get the width of input
            var wrap_width = parseInt(input_width) + 7; //add 10 for padding
            wrapper = input.wrap("<div class='" + container_class + "'></div>").parent();
            wrapper.wrap("<div class='" + border_class + "' style='width: " + wrap_width + "px;'></div>"); //apply border

            wrapper.corner("round 7px").parent().css('padding', '0.09em').corner("round 8px"); //round box and border
        },

        openScreen: function(template, noCloseButton, onclose) {
            // remove any previous overlay screens that may be present
            fusion.closeScreen();

            if (onclose) {
                fusion.onScreenClose = onclose;
            } else {
                fusion.onScreenClose = null;
            }

            $(document.body).append('<div class="overlay"></div>');
            $(document.body).append('<div class="popup"><div class="topbar">' +
			    (noCloseButton != true ? '<a href="#" class="cancel close">close</a>' : '') +
			    '</div><div class="popupContent"></div></div>');

            // hide any select boxes to avoid overlapping
            $('select').css('visibility', 'hidden');

            // remove the scrolling on the body temporarily, save the scroll position first
            fusion.savedWindowScrollPosition = $(window).scrollTop();
            $(document.documentElement || document.body).css('overflow', 'hidden');

            $('.overlay').hide().width($(window).width()).height($(window).height()).show();
            $(window).scrollTop(0);
            $('.popup').center().css('top', 35);
            $('.popup .close').click(function() {
                fusion.closeScreen();
                return false;
            });


            $(window).scrollTop(0);
            fusion.openOverlay(template, null);
        },

        openOverlay: function(template, params) {
            var loadingHTML = ['<div id="loadingGraphic" style="text-align: center; background-color: #FFF;">',
		        swfobject.hasFlashPlayerVersion("9") ?
		            '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="200" height="80" id="Object1" align="middle"><param name="allowScriptAccess" value="sameDomain" /><param name="allowFullScreen" value="false" /><param name="movie" value="/App_Themes/Default/swf/AppLoader.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><embed src="/App_Themes/Default/swf/AppLoader.swf" quality="high" bgcolor="#ffffff" width="200" height="80" name="COM001_AppLoader_200x80" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"/></object>' :
		            '<img src="../App_Themes/Default/img/AppLoader.gif" width="200" height="80" alt="Loading..."/>',
		        '</div>'
		    ];
            $('.popupContent').append(loadingHTML.join(''));
            var overlayId = "overlayIframe" + (fusion.overlayId++);

            var iframeHTML = [
				'<iframe class="overlayIframe" scrolling="auto" frameborder="0" id="',
				overlayId,
				'" src="',
				template,
				'" style="display:none;"></iframe>'
            ].join('');

            $('.popupContent').append(iframeHTML);
            $('#' + overlayId).load(fusion.postOverlayOpen);
            //$('.popupContent .wrapper').load(template,params,fusion.postOverlayOpen);
        },

        overlayId: 1,

        getIframeDocument: function() {
            try {
                var iframe = $('.overlayIframe')[0];
                if (iframe == null) return null;
                var doc = iframe.contentWindow || iframe.contentDocument;
                return doc.document || doc;
            } catch (e) {
                return null;
            }
        },

        overlayDidNotLoad: function() {
            $('#loadingGraphic').remove();
            $('.overlayIframe').remove();
            $('.popupContent').append(
                '<div class="transaction">' +
                    '<div class="wrapper">' +
                        '<h3>Your request could not be processed</h3>' +
                        '<p>An error occurred while processing your request.  Please try again later.</p>' +
                        '<div class="formControl">' +
                            '<div class="GenOk"><a href="#" class="redbuttonnoarrow" id="overlayErrorDismissal"><span>OK</span></a></div>' +
                        '</div>' +
                    '</div>' +
                '</div>'
            );
            var padding = (fusion.isIE7p ? 28 : 24);
            var contentHeight = 104 + padding;
            var maxHeight = $(window).height() - (70 + padding);
            $('.popupContent').height(Math.min(contentHeight, maxHeight));
            $('.popup').height(Math.min(contentHeight, maxHeight) + $('.topbar').height());
            // don't bother running the post events
            fusion.onScreenClose = null;
            $('#overlayErrorDismissal').click(fusion.closeScreen);
        },

        postOverlayOpen: function() {
            var iframeDoc = fusion.getIframeDocument();

            if (iframeDoc == null) {
                // the overlay didn't load, for whatever reason.
                fusion.overlayDidNotLoad();
            } else if (iframeDoc.location.href.toLowerCase().indexOf('public/home.aspx') != -1) {
                fusion.onScreenClose = null;
                fusion.closeScreen();
                window.location.replace("../Public/Home.aspx?m=to");
            } else if (iframeDoc.initOverlay == null) {
                // server responded, but not in a way we expected
                fusion.overlayDidNotLoad();
            } else {
                var finishInit = function() {
                    $('#loadingGraphic').hide();

                    //gs -- temp fix popup width for familyplan
                    // see changes to adjustPopupHeight() below
                    if (iframeDoc.location.href.indexOf("/Secure/ManageFamilyPlan.aspx") != -1) {
                        $('.popupContent').width(883);
                        $('.popup').width($('.popupContent').width());
                        $('.popup').center().css('top', 35);
                    }
                    else if (iframeDoc.location.href.indexOf("/Secure/RescheduleAppointment.aspx") != -1) {
                        $('.popupContent').width(750);
                        $('.popup').width($('.popupContent').width());
                        $('.popup').center().css('top', 35);
                    }


                    $('.overlayIframe').show();
                    $('.overlayIframe').width($('.popupContent').width());


                    iframeDoc.initOverlay(fusion);
                    fusion.adjustPopupHeight();
                    iframeDoc.fireOpenEvent();
                }
                window.setTimeout(finishInit, 150);
            }
        },

        isIE7p: (jQuery.browser.msie && (jQuery.browser.version == "7.0" || jQuery.browser.version == "8.0")),
        isIE6: (jQuery.browser.msie && jQuery.browser.version == "6.0"),
        isIE8p: (jQuery.browser.msie && jQuery.browser.version == "8.0"),

        adjustPopupWidth: function() {
            var iframeDoc = fusion.getIframeDocument();
            if (iframeDoc != null) {
                var padding = fusion.isIE7p ? 28 : 24;
                var isUPOverlay = (iframeDoc.location.href.indexOf("/Secure/ManageFamilyPlan.aspx") != -1);
                var width = ""

            }
        },

        adjustPopupHeight: function() {
            var iframeDoc = fusion.getIframeDocument();
            if (iframeDoc != null && iframeDoc.getHeight != null) {

                var padding = (fusion.isIE7p ? 28 : 24);

                var topbarHeight = $('.topbar').height();
                var contentHeight = Math.max(topbarHeight, iframeDoc.getHeight());
                var maxHeight = Math.max(topbarHeight, $(window).height() - (70 + padding));

                $('.popupContent').height(Math.min(contentHeight, maxHeight));
                $('.overlayIframe').height(Math.min(contentHeight, maxHeight));
                $('.popup').height(Math.min(contentHeight, maxHeight) + topbarHeight);

                if (fusion.isIE6) {
                    iframeDoc.fixIE6Width($('.overlayIframe').width(), (contentHeight > maxHeight));
                }
            }
        },

        windowResized: function() {
            var iframeDoc = fusion.getIframeDocument();
            if (iframeDoc != null) {
                if ($('.overlay').length) {
                    $('.overlay').width($(window).width()).height($(window).height());
                    $('.popup').center().css('top', 35);
                    fusion.adjustPopupHeight();
                }
            }
        },

        closeScreenAndRefresh: function() {
            fusion.closeScreen();
            if ($('.refreshMe').length > 0) {
                $('.refreshMe').change();
            } else {
                top.location.replace(top.location.href);
            }
        },

        closeScreenAndLogout: function() {
            fusion.onScreenClose = null; // to heck with it, we're logging out
            // that might be a hack
            fusion.closeScreen();
            top.location.replace("/LogOut/logout.aspx");
        },

        closeScreen: function() {

            fusion.markActivityTime();

            $('.overlay').remove();
            var popup = $('.popup');

            if (popup.length > 0) {
                // we mark activity at screen closing time because this happens prior to opening a new one anyway
                popup.hide();
                $('select').css('visibility', 'visible');
                $(document.documentElement || document.body).css('overflow', '');
                $(window).scrollTop(fusion.savedWindowScrollPosition);

                // delete the popup after a small delay to let cleanup run
                window.setTimeout(function() {
                    popup.remove();
                    if (fusion.onScreenClose) {
                        var func = fusion.onScreenClose;
                        fusion.onScreenClose = null;
                        func();
                    }
                }, 250);
            }
        },
        openTooltip: function() {
            var ttID = $(this).attr('href');
            ttID = ttID.substring(ttID.lastIndexOf('#'));
            var btnPos = $(this).offset();

            if (btnPos.left == 0 && btnPos.top == 0) {
                btnPos = $(this).parent().offset();
            }

            $('div.tooltip').not(ttID).hide();

            // calculate the top as a minimum of ten pixels down from the viewable top of the window

            $(ttID).appendTo(document.body).toggle();
            var ttTop = Math.max((btnPos.top - ($(ttID).height() + 10)), $(window).scrollTop() + 10);
            $(ttID).css('top', ttTop);
            $(ttID).css('left', btnPos.left + 10);


            return false;
        },

        openTipAt: function(tipId, offset) {
            $('div.tooltip').not(tipId).hide();
            $(tipId).appendTo(document.body).toggle().center().css('left', offset.left + 10).css('top', offset.top - ($(tipId).height() + 10));
        },

        centerTipOn: function(tipId, element) {
            $('div.tooltip').not(tipId).hide();
            var offset = element.offset();
            var toolTip = $(tipId);
            toolTip.appendTo(document.body).toggle();
            var ttTop = Math.max((offset.top - (toolTip.height() + 10)), $(window).scrollTop() + 10);
            var ttLeft = offset.left - (toolTip.width() / 2);
            toolTip.css('top', ttTop).css('left', ttLeft);
        },


        closeTooltip: function() {
            $('div.tooltip').hide();
            return false;
        },

        initScreen: function() {

            $('.popup .close').click(function() {
                fusion.closeScreen();
                return false;
            });

            $('.popup .submit').click(function() {
                fusion.postScreen();
                return false;
            });

            $('.popup .autopay').click(function() {
                fusion.openScreen($(this).attr('href'));
                return false;
            });

            $('div.transaction form').bind('submit', function() {
                return fusion.validateInput();
            });

            // TOOLTIPS

            $('a[rel=tooltip]').click(fusion.openTooltip);

            $('div.tooltip a.tipClose').click(fusion.closeTooltip);

            var overlayForm = $('.overlayForm');
            if (overlayForm.length) { // we only try to register if the form exists
                // Secure/PayBill.aspx, Secure/AutoPay.aspx
                // switches the active form based on the click of a radio button
                // disables the inactive portion of the form
                var paymentTypes = $('.paymentTypes input', overlayForm);
                if (paymentTypes.length > 1) {
                    paymentTypes.click(function() {
                        if (this.checked) {
                            var val = $(this).val();
                            if (val == 'debit') {
                                $('#accountPayment').slideUp("fast", function() {
                                    $('#creditBillingAddress').append($('#billingAddress'));
                                    $('#billingAddress').show();
                                    $('#debidCardText').show();
                                    $('#creditTableBody').append($('.amountRow'));
                                    $('#cardPayment input, #cardPayment select').each(function() { this.disabled = false; });
                                    $('#debitCardTypeRow').show();
                                    $('#creditCardTypeRow').hide();
                                    $('#accountPayment input, #accountPayment select').each(function() { this.disabled = true; });
                                    $('#cardPayment').slideDown("normal", fusion.adjustPopupHeight);
                                });
                            } else if (val == 'credit') {
                                $('#accountPayment').slideUp("fast", function() {
                                    $('#creditBillingAddress').append($('#billingAddress'));
                                    $('#billingAddress').show();
                                    $('#debidCardText').hide();
                                    $('#creditTableBody').append($('.amountRow'));
                                    $('#cardPayment input, #cardPayment select').each(function() { this.disabled = false; });
                                    $('#creditCardTypeRow').show();
                                    $('#debitCardTypeRow').hide();
                                    $('#accountPayment input, #accountPayment select').each(function() { this.disabled = true; });
                                    $('#cardPayment').slideDown("normal", fusion.adjustPopupHeight);
                                });
                            } else if (val == 'checking' || val == 'savings') {
                                $('#cardPayment').slideUp("fast", function() {
                                    if (val == 'checking' && $('#showCheckNum').val == 'true') {
                                        $('#checkNumberRow').show();
                                    }
                                    $('#bankBillingAddress').append($('#billingAddress'));
                                    $('#billingAddress').show();
                                    $('#debidCardText').hide();
                                    $('#bankTableBody').append($('.amountRow'));
                                    $('#cardPayment input, #cardPayment select').each(function() { this.disabled = true; });
                                    $('#accountPayment input, #accountPayment select').each(function() { this.disabled = false; });
                                    $('#accountPayment').slideDown("normal", fusion.adjustPopupHeight);
                                });
                            } else if (val == 'cancel') {
                                $('#accountPayment').slideUp("fast", function() {
                                    $('#cardPayment').slideUp("fast", function() {
                                        $('#cardPayment input, #cardPayment select').each(function() { this.disabled = true; });
                                        $('#accountPayment input, #accountPayment select').each(function() { this.disabled = true; });
                                        fusion.adjustPopupHeight();
                                    });
                                });
                            }
                        }
                    });

                    $('.paymentTypes input[type=radio][checked]').triggerHandler("click");
                } else {
                    // enable the form elements for whatever one is present
                }

                if (overlayForm && overlayForm.newpassword) {
                    $(overlayForm.newpassword).bind('keyup', function() {
                        var ps = Math.round(fusion.pwdStrength($(this).val()));
                        //console.warn(ps);
                        $('#passStrength p').width(ps + '%').text(ps + '%');
                    });
                }

                if (overlayForm && overlayForm.accountType) {
                    $(overlayForm.accountType).click(function() {
                        if ($(this).val() == 'restricted') {
                            $('#restrictedOptions').show();
                            $('#unrestrictedOptions').hide();
                        } else {
                            $('#restrictedOptions').hide();
                            $('#unrestrictedOptions').show();
                        }
                    });
                }

                if (overlayForm && overlayForm.paymentType) {
                    $(overlayForm.paymentType).click(function() {
                        $('.popup .submit').show();
                        if ($(this).val() == 'card') {
                            $('#cardPayment').show();
                            $('#accountPayment').hide();
                        } else if ($(this).val() == 'bank') {
                            $('#cardPayment').hide();
                            $('#accountPayment').show();
                        }
                        fusion.clearError();
                    });
                }

                if (overlayForm && overlayForm.existingAddr) {
                    $(overlayForm.existingAddr).click(function() {
                        if ($(this).val() == 'false') {
                            $('#billingAddress').show();
                        } else {
                            $('#billingAddress').hide();
                        }
                    });
                }
            }

            $('#btnEmailBlockAdd').click(function() {
                var ebEntry = overlayForm.emailblocking_entry;
                var ebList = overlayForm.emailblocking_list;
                if (ebEntry.value.length) {
                    ebList.options[ebList.options.length] = new Option(ebEntry.value, ebEntry.value);
                }
                ebEntry.value = '';
                return false;
            });

            $('#btnEmailBlockRemove').click(function() {
                var ebList = overlayForm.emailblocking_list;
                ebList.options[ebList.selectedIndex] = null;
                return false;
            });

        },


        postScreen: function(form) {

            var myForm = $('.overlayForm');
            var myData = {};
            var postTemplate = $(myForm).attr('action');
            var validation = fusion.validateInput();

            if (myForm.emailblocking_list) {
                $(myForm.emailblocking_list.options).attr('selected', 'selected');
            }

            $('input, select, textarea', myForm).each(function() {
                if (fusion.shouldBePosted(this)) {
                    myData[this.name] = $(this).val();
                }
            });

            $(window).scrollTop(0);

            if (validation) {
                $('.popupContent').empty();
                fusion.openOverlay(postTemplate, myData);
            }

        },

        shouldBePosted: function(element) {
            return (element.name.length) &&
		           !element.disabled &&
		           ((element.type != 'radio' && element.type != 'checkbox') ||
		            ((element.type == 'radio' || element.type == 'checkbox') && element.checked));
        },


        validateInput: function() {

            fusion.clearError();

            if ($('#payBill form').length) {

                var myForm = $('#payBill form').get(0);
                var payType = '';
                var existingAddr = '';
                var error = false;
                var errorMsg = [];
                var errorObj = [];

                if (myForm.paymenType) {
                    for (var i = 0; i < myForm.paymentType.length; i++) {
                        if (myForm.paymentType[i].checked) {
                            payType = $(myForm.paymentType[i]).val();
                            break;
                        }
                    }
                }

                if (payType == 'card') {

                    // card specific validation

                    if (myForm.pin && !$(myForm.pin).val().length) {
                        error = true;
                        errorMsg[errorMsg.length] = 'You must provide your billing pin.';
                        errorObj[errorObj.length] = $(myForm.pin);
                    }

                    if (myForm.debitCard.checked) {
                        if (myForm.debitCardType && !$(myForm.debitCardType).val().length) {
                            error = true;
                            errorMsg[errorMsg.length] = 'You must provide a valid card type.';
                            errorObj[errorObj.length] = $(myForm.debitCardType);
                        }
                    }

                    if (myForm.creditCard.checked) {
                        if (myForm.creditCardType && !$(myForm.creditCardType).val().length) {
                            error = true;
                            errorMsg[errorMsg.length] = 'You must provide a valid card type.';
                            errorObj[errorObj.length] = $(myForm.creditCardType);
                        }
                    }

                    if (myForm.cardNumber && !$(myForm.cardNumber).val().length) {
                        error = true;
                        errorMsg[errorMsg.length] = 'You must provide a valid card number.';
                        errorObj[errorObj.length] = $(myForm.cardNumber);
                    }

                    if (myForm.expDate_month && !$(myForm.expDate_month).val().length) {
                        error = true;
                        errorMsg[errorMsg.length] = 'You must provide a valid month.';
                        errorObj[errorObj.length] = $(myForm.expDate_month);
                    }

                    if (myForm.expDate_year && !$(myForm.expDate_year).val().length) {
                        error = true;
                        errorMsg[errorMsg.length] = 'You must provide a valid year.';
                        errorObj[errorObj.length] = $(myForm.expDate_year);
                    }

                    if (myForm.securityNumber && !$(myForm.securityNumber).val().length) {
                        error = true;
                        errorMsg[errorMsg.length] = 'You must provide a valid security number.';
                        errorObj[errorObj.length] = $(myForm.securityNumber);
                    }

                    if (myForm.cardholderName && !$(myForm.cardholderName).val().length) {
                        error = true;
                        errorMsg[errorMsg.length] = 'You must provide a valid cardholder name.';
                        errorObj[errorObj.length] = $(myForm.cardholderName);
                    }

                    if (myForm.existingAddr) {
                        for (var i = 0; i < myForm.existingAddr.length; i++) {
                            if (myForm.existingAddr[i].checked) {
                                existingAddr = $(myForm.existingAddr[i]).val();
                                break;
                            }
                        }
                    }

                    if (existingAddr == 'false') {

                        if (myForm.address1 && !$(myForm.address1).val().length) {
                            error = true;
                            errorMsg[errorMsg.length] = 'You must provide a valid address.';
                            errorObj[errorObj.length] = $(myForm.address1);
                        }

                        if (myForm.city && !$(myForm.city).val().length) {
                            error = true;
                            errorMsg[errorMsg.length] = 'You must provide a valid city.';
                            errorObj[errorObj.length] = $(myForm.city);
                        }

                        if (myForm.state && !$(myForm.state).val().length) {
                            error = true;
                            errorMsg[errorMsg.length] = 'You must provide a valid state.';
                            errorObj[errorObj.length] = $(myForm.state);
                        }

                        if (myForm.zip && !$(myForm.zip).val().length) {
                            error = true;
                            errorMsg[errorMsg.length] = 'You must provide a valid zipcode.';
                            errorObj[errorObj.length] = $(myForm.zip);
                        }

                    }

                } else if (payType == 'account') {

                    // account specific validation
                }
            }

            if (error) {

                $('div.transaction div.errormsg').append('<ul></ul>');
                for (i = 0; i < errorMsg.length; i++) {
                    $('div.transaction div.errormsg ul').append('<li>' + errorMsg[i] + '</li>');
                }
                for (i = 0; i < errorObj.length; i++) {
                    errorObj[i].addClass('error');
                }
                $('div.transaction div.errormsg').show();

                $(window).scrollTop(0);

                return false;

            } else {

                return true;

            }

        },


        clearError: function() {

            $('div.transaction div.errormsg').hide().empty();
            $('.error').removeClass('error');

        }
    }


})(jQuery);

}

