if (window.jQuery) {

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])] = 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.eVar20 = "";
            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) { } 
}

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;
	  

//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
        }

        $('.PersonalInformationUpdated').click(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'Personal Information Updated');
        });

        $('.GreetingNameUpdated').change(function(e) {
            sendSiteCatalystProp6ErrorProof($(this), 'prop6', 'Greeting Name Updated');
        });

        //AutoPay.aspx
//        if (recPaymentType == null) {
//            var recPaymentType = '';
//        }

//        $('.PaymentTypeACH input').click(function(e) {
//            debugger;
//            recPaymentType = 'checking - recurring';
//        });
//        $('.PaymentTypeSaving input').click(function(e) {
//            debugger;
//            recPaymentType = 'savings - recurring';
//        });
//        $('.PaymentTypeCreditCard input').click(function(e) {
//            debugger;
//            recPaymentType = 'credit card - recurring';
//        });
//        $('.PaymentTypeCancelRecurring input').click(function(e) {
//            debugger;
//            recPaymentType = 'Cancel Recurring Payments';
//        });

        //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');
        });

        //SinglePayment.aspx
        $('.SubmitOneTimePayment').click(function(e) {
            if (jQuery('.SinglePaymentTypeACH input').attr('checked') == true) {
                onePaymentType = 'checking - one time'
            };

            if (jQuery('.SinglePaymentTypeCreditCard input').attr('checked') == true) {
                onePaymentType = 'credit card - one time'
            };

            if (jQuery('.SinglePaymentTypeSaving input').attr('checked') == true) {
                onePaymentType = 'saving - one time'
            };

            if (onePaymentType.length > 0) {
                sendSiteCatalystEvar20($(this), 'eVar20', onePaymentType);
            }

        });
        $('.SubmitConfirmationUpdate').click(function(e) {
            if (paperless.length > 0) {
                sendSiteCatalystEvent8($(this), 'event8', paperless);
            }
        });

        //AutoPay.aspx
        $('.ContractTermsClientAcceptButton').click(function(e) {
            if (ReportingRecurringPayment != null && ReportingRecurringPayment.length > 0) {
                    sendSiteCatalystEvar20($(this), 'eVar20', ReportingRecurringPayment);
                }
        });

        $('.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';
        })
        $('.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);
        })

        $('.ElectronicEnable input').click(function(e) {
            paperless = 'ElectronicBill';
        });

        $('.ElectronicUpdate').click(function(e) {
            if (jQuery('.electronicButton input').attr('checked') != true) {
                sendSiteCatalystEvent8($(this), 'event8', 'Electronic Bill Pay')
            };
        });

        //End SiteCatalyst event tracking


        $('.OpenChatWindow').click(function(e) {
            window.open('http://www.comcastsupport.com/chat', '_blank', 'height=600,width=800');
            e.preventDefault();
        });

        if ($('#preloadgraphic').length == 1) {
            // perform an ajax get to the server with the original page url and the addition param preload=true
            if (swfobject.hasFlashPlayerVersion("9")) {
                var attributes = { data: "/images/customercentral/AppLoader.swf", width: "200", height: "80", align: "middle" };
                var params = { allowScriptAccess: "sameDomain", allowFullScreen: "false", quality: "high", bgcolor: "#ffffff" };
                swfobject.createSWF(attributes, params, "preloadStaticGraphic");
            } else {
                $('#preloadStaticGraphic').show();
            }
            $('#loadingMessage').show();
            $.ajax({
                url: window.location.toString() + "&preload=true",
                timeout: 60000, // 60 seconds seems reasonable enough for now
                complete: function(XMLHttpRequest, textStatus) {
                    var params = readQuerystring();
                    if ("success" == textStatus && !!params['backTo']) {
                        location.replace(params['backTo']);
                    } else if ("success" == textStatus) {
                        location.replace("../Secure/Home.aspx");
                    } else {
                        location.replace("../Pages/Exception.aspx");
                    }
                }
            });
        }

        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 ($('#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("");
                }
            });
        }

        $('.searchfield').keypress(function(e) {
            if (e.which == 13) {
                $('.searchbutton').click();
                return false;
            }
        });

        var handleContractButton = function() {
            if (this.checked) {
                $('.ContractTermsClientAcceptButton').removeClass('disabledBtn');
                $('.ContractTermsClientAcceptButton').attr('disabled', '');
            }
            else {
                $('.ContractTermsClientAcceptButton').addClass('disabledBtn');
                $('.ContractTermsClientAcceptButton').attr('disabled', 'disabled');
            }
        }

        $('.ContractTermsAcceptCheckBox input').click(handleContractButton);
        $('.ContractTermsAcceptCheckBox input').each(handleContractButton);

        $('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();
        });

        $('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;
                        }
                    }
                }
            }
        });


        $('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();
            });
        }

        fusion.checkFirstTimeRequiredActions();

        var time = parseInt($('span#loginTimeRaw').html());
        if (!isNaN(time)) {
            var now = new Date(time);
            $('span#loginTimeDisplay').html(formatLastLoginTime(now));
        }


        $('a.overlayItem').click(fusion.overlayClickEvent);

        $('.preventClicks').click(function() { return false; })

        $(window).resize(fusion.windowResized);

        $('#contactToggle').add('#contactClose a').click(function() {
            $('#contactOverlay').toggle();
            return false;
        });

        fusion.initScreen();

        fusion.markActivityTime();

        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);
        },

        loadDeviceList: function() {
            $.ajax({
                url: "/Secure/DeviceListAjaxResponse.aspx",
                timeout: 120000, // this list can take a while?
                dataType: "html",
                success: function(data, textStatus) {
                    $('#DeviceListContainer').html(data);
                    window.setTimeout(fusion.enableDeviceListLinks, 100);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $('#DeviceListContainer').html("");
                }
            });
        },

        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() {
            if (!$(this).hasClass('disabled')) {
                fusion.openScreen($(this).attr('rel'));
            }
            return false;
        },

        checkFirstTimeRequiredActions: function() {
            if ($('div.requireConditionsAcceptance:not(div.completed)').length > 0) {

                $('div.requireConditionsAcceptance').addClass('completed');
                fusion.openScreen('../Secure/FirstTimeLoginTerms.aspx', 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);
            }
        },

        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);
        },

        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);


            $(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="/images/customercentral/AppLoader.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><embed src="/images/customercentral/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="/images/customercentral/AppLoader.gif" width="200" height="80" alt="Loading..."/>',
		        '</div>'
		    ];
            $('.popupContent').append(loadingHTML.join(''));
            var overlayId = "overlayIframe" + (fusion.overlayId++);

            $('.popupContent').append('<iframe class="overlayIframe" id="' + overlayId + '" src="' + template + '" style="display:none;"></iframe>');
            $('.popup .close').click(function() {
                fusion.closeScreen();
                return false;
            });
            
			$('#' + 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').hide();
            $('.overlayIframe').hide();
            $('.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"><a href="#" class="btnSmall" id="overlayErrorDismissal">OK</a></div></div></div>');
            // 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.indexOf('/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 {
                $('#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);
                }

                $('.overlayIframe').show();
                $('.overlayIframe').width($('.popupContent').width());
                iframeDoc.initOverlay(fusion);
                fusion.adjustPopupHeight();
            }
        },

        isIE7p: (jQuery.browser.msie && (jQuery.browser.version == "7.0" || jQuery.browser.version == "8.0")),
        isIE6: (jQuery.browser.msie && jQuery.browser.version == "6.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) {

                var padding = (fusion.isIE7p ? 28 : 24);

                var contentHeight = iframeDoc.getHeight() + padding;
                var maxHeight = $(window).height() - (70 + padding);

                $('.popupContent').height(Math.min(contentHeight, maxHeight));
                $('.overlayIframe').height(Math.min(contentHeight, maxHeight));
                $('.popup').height(Math.min(contentHeight, maxHeight) + $('.topbar').height());

                if (fusion.isIE6) {
                    iframeDoc.fixIE6Width($('.overlayIframe').width(), (contentHeight > maxHeight));
                }
            }
        },

        windowResized: function() {
            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 {
                window.location.href = window.location.href;
            }
        },

        closeScreenAndLogout: function() {
            fusion.onScreenClose = null; // to heck with it, we're logging out
            // that might be a hack
            fusion.closeScreen();
            var url = "../LogOut/logout.aspx";
            document.location.replace(url);
        },

        closeScreen: function() {

            if ($('.overlay').length > 0) {
                // we mark activity at screen closing time because this happens prior to opening a new one anyway
                fusion.markActivityTime();

                $('.popup').remove();
                $('.overlay').remove();
                $('select').css('visibility', 'visible');
                $(document.documentElement || document.body).css('overflow', '');
                $(window).scrollTop(fusion.savedWindowScrollPosition);

                if (fusion.onScreenClose) {
                    var func = fusion.onScreenClose;
                    fusion.onScreenClose = null;
                    func();
                }
            }
        },
        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();
            $(ttID).appendTo(document.body).toggle().center().css('left', btnPos.left + 10).css('top', btnPos.top - ($(ttID).height() + 10));
            return false;
        },

        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);

}

