﻿var saveUserData = false;
var isGetAlertSaveUserData = false;
var asyncLogIn = false;
var isChannelTabLoaded = false;
var compareIDs = "";
var productIdforBaVo;
var numberOfAttempts = 0;
var currentProviderIds = "";
var isVerifyAddressClicked = false;
var isFormValid;
var timeoutIdForFadeEffect = 0;
var tempisLoggedIn = "";
var tempserviceType = "";
var isRefreshCookie = false;

/*
http://www.JSON.org/json2.js
2010-08-25

Public Domain.

NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

See http://www.JSON.org/js.html


This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html

USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.


This file creates a global JSON object containing two methods: stringify
and parse.

JSON.stringify(value, replacer, space)
value       any JavaScript value, usually an object or array.

replacer    an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.

space       an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or '&nbsp;'),
it contains the characters used to indent at each level.

This method produces a JSON text from a JavaScript value.

When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value

For example, this would serialize Dates as ISO strings.

Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}

return this.getUTCFullYear()   + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate())      + 'T' +
f(this.getUTCHours())     + ':' +
f(this.getUTCMinutes())   + ':' +
f(this.getUTCSeconds())   + 'Z';
};

You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.

If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.

Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.

The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.

If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.

Example:

text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'


text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'


JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.

The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.

Example:

// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.

myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});

myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});


This is a reference implementation. You are free to copy, modify, or
redistribute.
*/

/*jslint evil: true, strict: false */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON) {
    this.JSON = {};
}

(function() {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function(key) {

            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear() + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate()) + 'T' +
                 f(this.getUTCHours()) + ':' +
                 f(this.getUTCMinutes()) + ':' +
                 f(this.getUTCSeconds()) + 'Z' : null;
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function(key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

        // If the string contains no control characters, no quote characters, and no
        // backslash characters, then we can safely slap some quotes around it.
        // Otherwise we must also replace the offending characters with safe escape
        // sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function(a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

        // Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

        // If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

        // If we were called with a replacer function, then call the replacer to
        // obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

        // What happens next depends on the value's type.

        switch (typeof value) {
            case 'string':
                return quote(value);

            case 'number':

                // JSON numbers must be finite. Encode non-finite numbers as null.

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':

                // If the value is a boolean or null, convert it to a string. Note:
                // typeof null does not produce 'null'. The case is included here in
                // the remote chance that this gets fixed someday.

                return String(value);

                // If the type is 'object', we might be dealing with an object or an array or
                // null.

            case 'object':

                // Due to a specification blunder in ECMAScript, typeof null is 'object',
                // so watch out for that case.

                if (!value) {
                    return 'null';
                }

                // Make an array to hold the partial results of stringifying this object value.

                gap += indent;
                partial = [];

                // Is the value an array?

                if (Object.prototype.toString.apply(value) === '[object Array]') {

                    // The value is an array. Stringify every element. Use null as a placeholder
                    // for non-JSON values.

                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }

                    // Join all of the elements together, separated with commas, and wrap them in
                    // brackets.

                    v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }

                // If the replacer is an array, use it to select the members to be stringified.

                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        k = rep[i];
                        if (typeof k === 'string') {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {

                    // Otherwise, iterate through all of the keys in the object.

                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }

                // Join all of the member texts together, separated with commas,
                // and wrap them in braces.

                v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    }

    // If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function(value, replacer, space) {

            // The stringify method takes a value and an optional replacer, and an optional
            // space parameter, and returns a JSON text. The replacer can be a function
            // that can replace values, or an array of strings that will select the keys.
            // A default replacer method can be provided. Use of the space parameter can
            // produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

            // If the space parameter is a number, make an indent string containing that
            // many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

                // If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

            // If there is a replacer, it must be a function or an array.
            // Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

            // Make a fake root object containing our value under the key of ''.
            // Return the result of stringifying the value.

            return str('', { '': value });
        };
    }


    // If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function(text, reviver) {

            // The parse method takes a text and an optional reviver function, and returns
            // a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

                // The walk method is used to recursively walk the resulting structure so
                // that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


            // Parsing happens in four stages. In the first stage, we replace certain
            // Unicode characters with escape sequences. JavaScript handles many characters
            // incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function(a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

            // In the second stage, we run the text against regular expressions that look
            // for non-JSON patterns. We are especially concerned with '()' and 'new'
            // because they can cause invocation, and '=' because it can cause mutation.
            // But just to be safe, we want to reject all unexpected forms.

            // We split the second stage into 4 regexp operations in order to work around
            // crippling inefficiencies in IE's and Safari's regexp engines. First we
            // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
            // replace all simple value tokens with ']' characters. Third, we delete all
            // open brackets that follow a colon or comma or that begin the text. Finally,
            // we look to see that the remaining characters are only whitespace or ']' or
            // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

                // In the third stage we use the eval function to compile the text into a
                // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
                // in JavaScript: it can begin a block or an object literal. We wrap the text
                // in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

                // In the optional fourth stage, we recursively walk the new structure, passing
                // each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({ '': j }, '') : j;
            }

            // If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
} ());

function SendMail() {

    $.ajax({
        type: "POST",
        data: { "FromName": $("#divShare #FromName").val(),
            "Email": $("#divShare #Email").val(),
            "Subject": $("#divShare #Subject").val(),
            "Body": $("#divShare #Body").val()
        },
        url: "/PlanDetail/SharePlan",
        cache: false,
        success: function(data) {
            if (data.EmailSent == undefined) {
                $("#divShare").html($(data).filter("#divShare").html());
            }
            else if (data.EmailSent == true) {
                alert("Message Successfully Sent");
            }
            else {
                alert("An error occurred while sending email.");
            }
        }
    });
}
var isToggle = true;
function SavingsDD() {

    if ($.browser.msie && jQuery.browser.version.substr(0, 1) == "7") {
        $("#divSavingsDD").css("marginLeft", "-88px");
        $("#divSavingsDD").css("marginTop", "15px");
    }
    $("#divSavingsDD").toggle();

    if (isToggle) {
        $("#header").css("z-Index", "3000");
        isToggle = false;
    }
    else {
        $("#header").css("z-Index", "0");
        isToggle = true;
    }

}

function SavingCosts(typeService) {
    $.ajax({
        type: "POST",
        data: { "type": typeService
        },
        url: "/Recommendations/GetCostSavingsForServiceType",
        cache: false,
        success: function(data) {

            if (typeService == "Electric") {
                $("#divElectric").html(data);
            }
            if (typeService == "Water") {
                $("#divWater").html(data);
            }
            if (typeService == "TrashRemoval") {
                $("#divTrashRemoval").html(data);
            }
            if (typeService == "NaturalGas") {
                $("#divNaturalGas").html(data);
            }
        }
    });
}
function ChangeUpdateCartButtonInPlanDetail(isTrue) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ChangeUpdateCartButtonInPlanDetail("' + isTrue + '")');
    if (isTrue == "true") {
        $("a:contains('Add to cart')").attr("innerHTML", "Update Cart");
        $(".plan-details").addClass("update");
    }
    else {
        $("a:contains('Update Cart')").attr("innerHTML", "Add to cart");
        $(".plan-details").removeClass("update");
    }
}
(function($) {
    var m = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"': '\\"',
        '\\': '\\\\'
    },
        s = {
            'array': function(x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function(x) {
                return String(x);
            },
            'null': function(x) {
                return "null";
            },
            'number': function(x) {
                return isFinite(x) ? String(x) : 'null';
            },
            'object': function(x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            'string': function(x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

    $.toJSON = function(v) {
        var f = isNaN(v) ? s[typeof v] : s['number'];
        if (f) return f(v);
    };

    $.parseJSON = function(v, safe) {
        if (safe === undefined) safe = $.parseJSON.safe;
        if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v))
            return undefined;
        return eval('(' + v + ')');
    };

    $.parseJSON.safe = false;

})(jQuery);
function ClickSaveMessage(div) {
    if ($(div).attr("innerHTML").indexOf("Good Value") == -1) {
        if ($(div).closest('.recommendbox').find('.pr-dtls').length > 0) {
            $(div).closest('.recommendbox').find('.pr-dtlslnk').toggleClass('opened');
            $(div).closest('.recommendbox').find('.pr-dtls').slideToggle('slow');
        }
        else {
            $(div).closest('.toprecommendbox').find('.pr-dtlslnk').toggleClass('opened');
            $(div).closest('.toprecommendbox').find('.pr-dtls').slideToggle('slow');
        }
    }
}
function ChangeOnHover(div, mouse) {
    if ($(div).attr("innerHTML").indexOf("Good Value") == -1) {
        $(div).css("cursor", "hand");

        if (mouse == "over") {
            $(div).css("color", "#2584cf");
            $(div).css("cursor", "hand");
            $($(div)[0].childNodes[0].childNodes[0]).css("color", "#2584cf");
            $($(div)[0].childNodes[0]).css("color", "#2584cf");
            $($(div)[0].childNodes[1]).css("color", "#2584cf");

        }
        else {

            $(div).css("color", "#222");
            $($(div)[0].childNodes[0].childNodes[0]).css("color", "#222");
            $($(div)[0].childNodes[0]).css("color", "#eb3838");
            $($(div)[0].childNodes[1]).css("color", "#eb3838");

        }
    }
    else {
        $(div).css("cursor", "default");
    }
}


function LoadTvTopBox() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('LoadTvTopBox()');
    var result = "";

    $.getJSON("/FindSavings/GetStoredSelectedTV", function(data) {

        result = data;
        result = $("#tvSetTopboxNotation").val();

        var isClickText = true;
        if (result != "") {

            JSON = JSON || {};

            var jsonArr = JSON.parse(result);

            for (var i = 0; i < jsonArr.length; i++) {
                var arr = jsonArr[i];
                var r = i + 1;
                $("#tr" + r).removeClass("hideTvRow");
                $("#tr" + r).addClass("showTvRow");

                if (arr["TVName"] != "TV #" + r) {
                    isClickText = false;
                }

                $("#lbltv" + r).attr("innerHTML", arr["TVName"]);
                if (arr["DVR"] == true) {
                    $("#chkDVR" + r).attr("checked", "checked");
                }
                $("#sHD" + r).attr("selectedIndex", arr["HD"]);
            }
            if (jsonArr.length == 8) {
                $("#trAdd").removeClass("showAddTvRow");
                $("#trAdd").addClass("hideAddTvRow");
            }

            if (isClickText) {
                $("#lbltv1").attr("innerHTML", "TV #1" + '<span id=lblOptional class=name-instr>(click to edit name)</span>');

            }
            if (jsonArr.length == 1)
                SaveTvTopBox();

        }
        else {
            SaveTvTopBox();
        }

    });
    BindEvent();

}


function SaveTvTopBox() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SaveTvTopBox()');
    var tvSet = "";
    var jsonObj = new Array();
    for (var i = 1; i <= $("#tblTv tr.showTvRow").length; i++) {
        var tVName = $("#lbltv" + i).attr("innerHTML");
        if (i == 1 && tVName.indexOf("TV #1") > -1
                && tVName.toLowerCase().indexOf('>(click to edit name)</span>') > -1 && tVName.toLowerCase().indexOf('lbloptional') > -1
                && tVName.toLowerCase().indexOf('name-instr') > -1) {
            tVName = "TV #1";
        }
        var dVR = $("#chkDVR" + i).attr("checked");
        var hD = $("#sHD" + i).attr("selectedIndex");
        var row = { TVName: tVName, DVR: dVR, HD: hD }
        jsonObj.push(row);
    }

    $("#tvSetTopboxNotation").val($.toJSON(jsonObj));

}

function DeleteTv(rowNum) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('DeleteTv("' + rowNum + '")');
    $("#chkDVR" + rowNum).attr("checked", "");
    $("#sHD" + rowNum).attr("selectedIndex", "0");

    $("#tr" + rowNum).removeClass("showTvRow");
    $("#tr" + rowNum).addClass("hideTvRow");

    var totalRow = $("#tblTv tr.showTvRow").length;
    var row = $("#tblTv tr.showTvRow").length + 1;
    $("#lbltv" + rowNum).attr("innerHTML", "TV #" + row);

    $("#tr" + rowNum).attr("id", "tr" + row);

    $("#deleteTv" + rowNum).attr("id", "deleteTv" + row);
    $("#lbltv" + rowNum).attr("id", "lbltv" + row);
    $("#chkDVR" + rowNum).attr("id", "chkDVR" + row);
    $("#sHD" + rowNum).attr("id", "sHD" + row);
    $("#txtTv" + rowNum).attr("id", "txtTv" + row);

    if (totalRow == 7) {
        $("#addTV1").removeClass("hideAddTvRow");
        $("#addTV1").addClass("showAddTvRow");
    }

    for (var i = 1; i <= $("#tblTv tr.showTvRow").length; i++) {
        $($("#tblTv tr.showTvRow")[i - 1]).attr("id", "tr" + i);
        var curRow = $($("#tblTv tr.showTvRow")[i - 1]);

        if ((i - 1) > 0) {

            $($(curRow)[0].childNodes).find(".editable").attr("id", "lbltv" + i);

            if ($("#lbltv" + i).attr("innerHTML").indexOf("TV #") > -1) {
                $("#lbltv" + i).attr("innerHTML", "TV #" + i);
            }
            $($(curRow)[0].childNodes).find(".remove-tv").attr("id", "deleteTv" + i);
            $($(curRow)[0].childNodes).find(".txtbox").attr("id", "txtTv" + i);
            $($(curRow)[0].childNodes).find(":checkbox").attr("id", "chkDVR" + i);
            $($(curRow)[0].childNodes).find("select").attr("id", "sHD" + i);
        }

    }
    BindEvent();
    SaveTvTopBox();
}

function BindEvent() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('BindEvent()');
    $("#txtTv1").unbind();
    $("#txtTv2").unbind();
    $("#txtTv3").unbind();
    $("#txtTv4").unbind();
    $("#txtTv5").unbind();
    $("#txtTv6").unbind();
    $("#txtTv7").unbind();
    $("#txtTv8").unbind();

    $("#lbltv1").unbind();
    $("#lbltv2").unbind();
    $("#lbltv3").unbind();
    $("#lbltv4").unbind();
    $("#lbltv5").unbind();
    $("#lbltv6").unbind();
    $("#lbltv7").unbind();
    $("#lbltv8").unbind();

    $("#deleteTv2").unbind();
    $("#deleteTv3").unbind();
    $("#deleteTv4").unbind();
    $("#deleteTv5").unbind();
    $("#deleteTv6").unbind();
    $("#deleteTv7").unbind();
    $("#deleteTv8").unbind();


    $("#txtTv1").keydown(function(e) {
        return DisableEnter('1', e);
    });
    $("#txtTv2").keydown(function(e) {
        return DisableEnter('2', e);
    });
    $("#txtTv3").keydown(function(e) {
        return DisableEnter('3', e);
    });
    $("#txtTv4").keydown(function(e) {
        return DisableEnter('4', e);
    });
    $("#txtTv5").keydown(function(e) {
        return DisableEnter('5', e);
    });
    $("#txtTv6").keydown(function(e) {
        return DisableEnter('6', e);
    });
    $("#txtTv7").keydown(function(e) {
        return DisableEnter('7', e);

    });
    $("#txtTv8").keydown(function(e) {
        return DisableEnter('8', e);
    });


    $("#txtTv1").keypress(function(e) {
        return DisableEnter('1', e);
    });
    $("#txtTv2").keypress(function(e) {
        return DisableEnter('2', e);
    });
    $("#txtTv3").keypress(function(e) {
        return DisableEnter('3', e);
    });
    $("#txtTv4").keypress(function(e) {
        return DisableEnter('4', e);
    });
    $("#txtTv5").keypress(function(e) {
        return DisableEnter('5', e);
    });
    $("#txtTv6").keypress(function(e) {
        return DisableEnter('6', e);
    });
    $("#txtTv7").keypress(function(e) {
        return DisableEnter('7', e);

    });
    $("#txtTv8").keypress(function(e) {
        return DisableEnter('8', e);
    });

    $("#txtTv1").keyup(function(e) {
        RemoveMarkupText(this, e);
    });
    $("#txtTv2").keyup(function(e) {
        RemoveMarkupText(this, e);
    });
    $("#txtTv3").keyup(function(e) {
        RemoveMarkupText(this, e);
    });
    $("#txtTv4").keyup(function(e) {
        RemoveMarkupText(this, e);
    });
    $("#txtTv5").keypress(function(e) {
        RemoveMarkupText(this, e);
    });
    $("#txtTv6").keyup(function(e) {
        RemoveMarkupText(this, e);
    });
    $("#txtTv7").keyup(function(e) {
        RemoveMarkupText(this, e);

    });
    $("#txtTv8").keyup(function(e) {
        RemoveMarkupText(this, e);
    });



    $("#txtTv1").blur(function() {
        BlurTextBox('1');
    });
    $("#txtTv2").blur(function() {
        BlurTextBox('2');
    });
    $("#txtTv3").blur(function() {
        BlurTextBox('3');
    });
    $("#txtTv4").blur(function() {
        BlurTextBox('4');
    });
    $("#txtTv5").blur(function() {
        BlurTextBox('5');
    });
    $("#txtTv6").blur(function() {
        BlurTextBox('6');
    });
    $("#txtTv7").blur(function() {
        BlurTextBox('7');

    });
    $("#txtTv8").blur(function() {
        BlurTextBox('8');
    });

    $("#lbltv1").click(function() {
        ShowTextBox('1');
    });
    $("#lbltv2").click(function() {
        ShowTextBox('2');
    });
    $("#lbltv3").click(function() {
        ShowTextBox('3');
    });
    $("#lbltv4").click(function() {
        ShowTextBox('4');
    });
    $("#lbltv5").click(function() {
        ShowTextBox('5');
    });
    $("#lbltv6").click(function() {
        ShowTextBox('6');
    });
    $("#lbltv7").click(function() {
        ShowTextBox('7');
    });
    $("#lbltv8").click(function() {
        ShowTextBox('8');
    });


    $("#deleteTv2").click(function() {
        DeleteTv('2');
    });
    $("#deleteTv3").click(function() {
        DeleteTv('3');
    });
    $("#deleteTv4").click(function() {
        DeleteTv('4');
    });
    $("#deleteTv5").click(function() {
        DeleteTv('5');
    });
    $("#deleteTv6").click(function() {
        DeleteTv('6');
    });
    $("#deleteTv7").click(function() {
        DeleteTv('7');
    });
    $("#deleteTv8").click(function() {
        DeleteTv('8');
    });
}
function ClearSetting() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ClearSetting()');
    if ($("#lbltv1").attr("innerHTML").indexOf("TV #1") == -1) {
        $("#lbltv1").attr("innerHTML", "TV #1");
    }
    $("#chkDVR1").attr("checked", "");
    $("#sHD1").attr("selectedIndex", "0");


    SaveTvTopBox();
}

function RemoveMarkupText(txt, eve) {

    var key = eve.which;
    if (window.event)
        key = window.event.keyCode; //IE
    else
        key = eve.which; //firefox

    if (key == 188 || key == 190) {

        var str = "";
        var text = $(txt).val();

        for (var i = 0; i < text.length; i++) {


            if (!(text.charAt(i) == '<' || text.charAt(i) == '>')) {

                str += text.charAt(i);
            }
        }

        $(txt).val(str);
    }
}

function DisableEnter(rowNum, eve) {
    var key;
    if (window.event) {
        key = window.event.keyCode; //IE
    }
    else
        key = eve.which;  //firefox
    if (key == 13) {
        BlurTextBox(rowNum);
    }
    return (key != 13);

}
function BlurTextBox(rowNum) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('BlurTextBox("' + rowNum + '")');
    if ($.trim($("#txtTv" + rowNum).val()) != "") {

        var text = $("#txtTv" + rowNum).val();
        if (text.indexOf(">") > -1 || text.indexOf("<") > -1) {
            var str = "";
            for (var i = 0; i < text.length; i++) {

                if (!(text.charAt(i) == '<' || text.charAt(i) == '>')) {

                    str = str + text.charAt(i);
                }
            }

            $("#txtTv" + rowNum).val(str);
        }
        $("#lbltv" + rowNum).attr("innerHTML", $.trim($("#txtTv" + rowNum).val()));
    }

    $("#txtTv" + rowNum).css("display", "none");
    $("#lbltv" + rowNum).css("display", "");



    SaveTvTopBox(); return false;
}

function ShowTextBox(rowNum) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ShowTextBox("' + rowNum + '")');
    $("#lblOptional").remove();
    $("#txtTv" + rowNum).val("");

    var t = "TV #" + rowNum;

    if (!($.trim($("#lbltv" + rowNum).attr("innerHTML")) == t)) {
        var str = "";
        var text = $("#lbltv" + rowNum).attr("innerHTML");

        if (text.indexOf("&amp;") > -1 || text.indexOf("&apos;") > -1 || text.indexOf("&quot;") > -1) {

            for (var i = 0; i < text.length; i++) {

                if (text[i] == '&' && text[i + 1] == 'a' && text[i + 2] == 'm' && text[i + 3] == 'p' && text[i + 4] == ';') {
                    str += "&";
                    i = i + 4;
                }
                else if (text[i] == '&' && text[i + 1] == 'a' && text[i + 2] == 'p' && text[i + 3] == 'o' && text[i + 4] == 's' && text[i + 5] == ';') {
                    str += "\"";
                    i = i + 5;
                }
                else if (text[i] == '&' && text[i + 1] == 'q' && text[i + 2] == 'u' && text[i + 3] == 'o' && text[i + 4] == 't' && text[i + 5] == ';') {
                    str += "\"";
                    i = i + 5;
                }
                else {
                    str += text[i];
                }
            }


            $("#txtTv" + rowNum).val(str);
        }
        else {
            $("#txtTv" + rowNum).val($("#lbltv" + rowNum).attr("innerHTML"));
        }
    }
    $("#txtTv" + rowNum).css("display", "");
    $("#lbltv" + rowNum).css("display", "none");
    $("#txtTv" + rowNum).focus();


}
function AddAnotherTV() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('AddAnotherTV()');
    var totalRow = $("#tblTv tr.showTvRow").length + 1;
    if (totalRow == 8) {
        $("#addTV1").removeClass("showAddTvRow");
        $("#addTV1").addClass("hideAddTvRow");
    }
    var row = $("#tr" + totalRow);
    $("#tblTv").remove($("#tr" + totalRow));
    $("#tblTv").append(row);
    $("#tr" + totalRow).removeClass("hideTvRow");
    $("#tr" + totalRow).addClass("showTvRow");
    SaveTvTopBox();
}

function SetBundleSelected(serviceType, chk, updateBundle) {
    if ($(chk).attr("checked")) {
        $("#maxPrice").val("300");
        $("#showBundleCheckbox").attr("checked", "checked");
    }
    else {
        $("#showBundleCheckbox").attr("checked", "");
        $("#maxPrice").val("200");
    }
    $.ajax({
        url: "/FindSavings/SetBundleSelected",
        type: "POST",
        async: false, //Fix for 46964
        data: { "isBundle": $(chk).attr("checked"), "currentType": serviceType, "updateBundleType": updateBundle, "price": $("#monthlyBillID" + serviceType).val() },
        cache: false,
        success: function(data) {

            var arr = data.split("^");
            var str = "";
            if (arr.length >= 3) {
                str = "TV, Internet and Phone";
            }
            else {
                if (data.indexOf("TV") > -1 && data.indexOf("Internet") > -1) {
                    str = "TV and Internet";
                }
                else if (data.indexOf("TV") > -1 && data.indexOf("Phone") > -1) {
                    str = "TV and Phone";
                }
                else if (data.indexOf("Internet") > -1 && data.indexOf("Phone") > -1) {
                    str = "Internet and Phone";
                }
            }
            if ($(chk).attr("checked")) {


                $($("#divAcc" + arr[0]).find("span")[0]).text("My Monthly " + str + " Bill:");
                $("#bundle" + arr[0]).attr("checked", "checked");



                $($("#divAcc" + arr[1]).find("span")[0]).text("My Monthly " + str + " Bill:");
                $("#bundle" + arr[1]).attr("checked", "checked");


                if (arr.length >= 3) {
                    $($("#divAcc" + arr[2]).find("span")[0]).text("My Monthly " + str + " Bill:");
                    $("#bundle" + arr[2]).attr("checked", "checked");


                }
                $("#maxPrice").val("300");
            }
            else {

                $($("#divAcc" + arr[0]).find("span")[0]).text("My Monthly " + arr[0] + " Bill:");
                $("#bundle" + arr[0]).attr("checked", "");
                $($("#divAcc" + arr[1]).find("span")[0]).text("My Monthly " + arr[1] + " Bill:");
                $("#bundle" + arr[1]).attr("checked", "");
                if (arr.length >= 3) {
                    $($("#divAcc" + arr[2]).find("span")[0]).text("My Monthly " + arr[2] + " Bill:");
                    $("#bundle" + arr[2]).attr("checked", "");
                } $("#maxPrice").val("200");
            }
            if ($(chk).attr("checked")) {
                if ($("#monthlyBillID" + arr[0]).val() != "" || $("#monthlyBillID" + arr[0]).val() != "0") {
                    $("#monthlyBillID" + arr[1]).val($("#monthlyBillID" + arr[0]).val());
                    if (arr.length >= 3)
                        $("#monthlyBillID" + arr[2]).val($("#monthlyBillID" + arr[0]).val());
                }
                else if ($("#monthlyBillID" + arr[1]).val() != "" || $("#monthlyBillID" + arr[1]).val() != "0") {
                    $("#monthlyBillID" + arr[0]).val($("#monthlyBillID" + arr[1]).val());
                    if (arr.length >= 3)
                        $("#monthlyBillID" + arr[2]).val($("#monthlyBillID" + arr[1]).val());
                }
                else if (arr.length >= 3 && ($("#monthlyBillID" + arr[2]).val() != "" || $("#monthlyBillID" + arr[2]).val() != "0")) {
                    $("#monthlyBillID" + arr[1]).val($("#monthlyBillID" + arr[2]).val());
                    $("#monthlyBillID" + arr[2]).val($("#monthlyBillID" + arr[2]).val());
                }
            }
        }
    });

}

function SetContractSelected(serviceType, chk) {
    $.ajax({
        url: "/FindSavings/SetContractSelected",
        type: "POST",
        async: false, //Fix for 46964
        data: { "isContract": $(chk).attr("checked"), "currentType": serviceType },
        cache: false,
        success: function(data) {
        }
    });

}

function GetBundlePartialView(showBundleView, serviceID, bundleViewLoaded, showConfirmation, accordionBundleChk, chk, sType) {

    if ($("#showBundleCheckbox").attr("checked")) {
        $("#" + accordionBundleChk).attr("checked", "checked");
    }
    else {
        $("#" + accordionBundleChk).attr("checked", "");
    }
    if (typeof ClickTaleExec == 'function') ClickTaleExec('GetBundlePartialView(' + showBundleView + ', "' + serviceID + '", ' + bundleViewLoaded + ', ' + showConfirmation + ')');
    if (billValueCleared) {
        showConfirmation = false;
    }
    if (showConfirmation) {
        ShowBundleConfirmation(showBundleView, serviceID, bundleViewLoaded);

    }
    else {
        if ($("#showBundleCheckbox").attr("checked")) {
            //            LoadBundleView(showBundleView, serviceID, bundleViewLoaded);
            $("#bundleViewID").css("display", "");
            $("#maxPrice").val("300");
        }
        else {
            $("#maxPrice").val("200");
            $("#bundleList").attr("selectedIndex", "-1");
            $("#bundleViewID").css("display", "none");
        }
    }
    //    if ($("#showBundleCheckbox").attr("checked")) {
    //        $("#monthlyBillText").text("My total bundle bill per month is about:");
    //    }
    //    else {
    //        $("#monthlyBillText").text("My bill per month is about:");
    //    }
    SetBundleSelected(sType, chk, false);
}
function GetContractPartialView(elem, serviceType) {
    if ($(elem).attr("checked")) {
        $("#contract" + serviceType).attr("checked", "checked");
        $("#showContractCheckbox").attr("checked", "checked");

    }
    else {
        $("#contract" + serviceType).attr("checked", "");
        $("#showContractCheckbox").attr("checked", "");
    }
    var val = $(elem).attr("checked");
    if (typeof ClickTaleExec == 'function') ClickTaleExec('GetContractPartialView("' + val + '", "' + serviceType + '")');

    if (val) {
        $("#divContract").css("display", "");
    }
    else {
        $("#contractTimeRemaining").attr("selectedIndex", "0");
        $("#datepicker").val("");
        $("#terminationFee").val("0.00");
        $("#divContract").css("display", "none");
    }
    SetContractSelected(serviceType, elem);

}

(function($, undefined) {
    '$:nomunge'; // Used by YUI compressor.

    $.fn.serializeObject = function() {
        var obj = {};

        $.each(this.serializeArray(), function(i, o) {
            var n = o.name,
        v = o.value;

            obj[n] = obj[n] === undefined ? v
          : $.isArray(obj[n]) ? obj[n].concat(v)
          : [obj[n], v];
        });

        return obj;
    };

})(jQuery);

function SaveServiceNext(serviceType) {
    $("#isNext").val(true);
    $.ajax({
        type: 'POST',
        url: "/FindSavings/" + serviceType,
        data: $("#serviceForm").serialize(),
        success: function(json) {
            // handle response
        },
        async: false, //Fix for 46964
        dataType: "json"
    });

}
function GetRecommendationModal(serviceType, isInterview) {
    if ($("#Busy").val() == "false") {
        if (serviceType != 'None' ||
        ($("#CategoriesSelected").val() == "false" && serviceType == 'None')) {
            if (serviceType == 'Halo') {
                serviceType = 'None';
            }
            $.ajax({
                url: "/FindSavings/GetRecommendationModal",
                type: "POST",
                data: { "service": serviceType, "isInterview": isInterview },
                cache: false,
                error: function(jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                },
                success: function(data) {
                    if (serviceType != "none" || serviceType != "None") {
                        $("#serviceAccordion").css("position", "absolute");
                        // Case 46966 $("#serviceAccordion").css("z-Index", "6000");
                    }
                    var h1 = 0;
                    var h2 = 0;
                    if ($.browser.msie && jQuery.browser.version.substr(0, 1) == "8" ||
                    $.browser.msie && jQuery.browser.version.substr(0, 1) != "7") {
                        h1 = $(".progress-header").css("height").substring(0, $(".progress-header").css("height").length - 2) * 1;
                    }
                    h2 = $(".page").attr("clientHeight");
                    $("#RecFinderModalBg").css("width", $(".page").css("width"));
                    $("#RecFinderModalBg").css("height", h1 + h2 + "px");
                    $("#RecFinderModal").css("marginTop", h1 + "px");
                    $("#RecFinderModalBg").show();

                    $("#RecFinderModal").empty();
                    $("#RecFinderModal").append(data);
                    $("#RecFinderModal").show();
                    LogOmnitureModalShow("Top Recommendations Finder - " + serviceType);
                }
            });
        }
        else
            location.href = '/Recommendations';
    }
    else {
        alert("Retrieving results from slidder, please wait until page is refreshed");
    }

}

function SaveUserProfile(url, doRedirect) {
    if (isPageDirty) {
        isPageDirty = false;
        var formData = $("[:checkbox][checked]");
        $.ajax({
            url: "/MyProfile/PostData",
            type: "POST",
            data: formData,
            cache: false,
            success: function(data) {
                if (data != null && doRedirect) {
                    location.href = url;
                }
                else if (!doRedirect) {
                    LogOff();
                }
            }
        });
    }
    else {
        if (doRedirect) {
            location.href = url;
        }
        else {
            LogOff();
        }
    }
}

//   function SaveChanges(url, doRedirect) {
//   		$.ajax({
//   			url: "/FindSavings/SaveChanges",
//   			type: "POST",
//   			cache: false,
//   			success: function(data) {
//   				if (data != null && doRedirect) {
//   					$(location).attr('href', url);
//   				}
//   			}
//   		});
//   }


function isRequestCompleted() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('isRequestCompleted()');
    if (!completed) {
        t = window.setTimeout(function() {
            isRequestCompleted();
        }, 2000);
    }
    return completed;
}
function LoadBundleView(showBundleView, serviceID, bundleViewLoaded) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('LoadBundleView(' + showBundleView + ', "' + serviceID + '", ' + bundleViewLoaded + ')');
    if (showBundleView) {
        $("#maxPrice").val("300");
        $("#monthlySliderTouch").slider({
            max: 300
        });
        if (!isBundleViewLoaded) {
            isBundleViewLoaded = bundleViewLoaded;
        }
        if (!isBundleViewLoaded) {
            $.ajax({
                type: "GET",
                cache: false,
                url: "/FindSavings/BundleView/" + serviceID,
                success: function(data) {
                    if (data != null && data.length > 0) {
                        $("#bundleViewID").css("display", "block");
                        $("#creditSeperator").css("display", "none");
                        $("#bundleViewID").append(data);
                        isBundleViewLoaded = true;
                    }

                }
            });
        }
        else {

            $("#bundleViewID").css("display", "block");
            $("#creditSeperator").css("display", "none");
        }

    }
    else {

        if (!billValueCleared) {
            //default is set tot 10
            //$("#monthlySlider").slider("option", "value", 10);
            $("#monthlySliderTouch").slider("value", -1);
            $("#monthlyBillID").val("");
            billValueCleared = true;
        }
        $("#bundleViewID").css("display", "none");
        $("#creditSeperator").css("display", "block");
        $("input[name=MyCurrentService.TypeOfBundle]").each(function() {
            if (this.checked) {
                this.checked = false;
            }
        });
        $("#maxPrice").val("200");
        $("#monthlySlider").slider({
            max: 200

        });
    }
}

function CheckRecommendations() {
    $.ajax({
        type: "GET",
        dataType: 'json',
        url: "/Interstitial/HasRecommendations",
        cache: false,
        success: function(data) {
            if (data != null) {
                if (data.hasRecommendations || (numberOfAttempts > data.maxNumberOfAttempts)) {
                    numberOfAttempts = 0;
                    location.href = $("#redirectUrl").val();
                } else {
                    t = window.setTimeout(function() {
                        CheckRecommendations();
                        GetShoppingCartListFromCookies();
                    }, 3000);
                }
            }
            else {
                t = window.setTimeout(function() {
                    CheckRecommendations();
                    GetShoppingCartListFromCookies();
                }, 3000);
            }

        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert('error');
            location.href = $("#redirectUrl").val();
        }
    });
    numberOfAttempts++;
}

function FormatChannelUI(isChannelTabSelected) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('FormatChannelUI(' + isChannelTabSelected + ')');
    if (isChannelTabSelected) {
        $("#divChannels").show();
        $("#divfeatures").hide();
        $('#aChannels').removeClass('tab').addClass('tab active');
        $('#aFeatures').removeClass('tab active').addClass('tab');
        if (!isChannelTabLoaded) {
            LoadTVChannels();
        }
        $("#HasChannelPackage").val("false")

    }
    else {
        $("#divChannels").hide();
        $("#divfeatures").show();
        $('#aFeatures').removeClass('tab').addClass('tab active');
        $('#aChannels').removeClass('tab active').addClass('tab');
        $("#HasChannelPackage").val("true")
    }
}
function ShowChannelAlert(isChannelTabClicked) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ShowChannelAlert(' + isChannelTabClicked + ')');
    $("#dialog-channel-confirm").dialog({
        resizable: false,
        height: 185,
        width: 440,
        modal: true,
        buttons: {
            'Continue': function() {
                $(this).dialog('close');
                FormatChannelUI(isChannelTabClicked);
                ResetChannelUI();
            },
            Cancel: function() {
                $(this).dialog('close');
            }
        }
    });

}

function ResetChannelUI() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ResetChannelUI()');
    $(".selected").each(function(index) {
        $(this).removeClass('selected');
    });
    $("input[name='ServiceOptions']:checked").each(function(index) {
        $(this).attr('checked', false);
    });
}
function LoadSelectedChannelsText(divId, anchorId) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('LoadSelectedChannelsText("' + divId + '", "' + anchorId + '")');
    if ($("#" + divId + " li.selected").length > 0) {

        $("#" + anchorId).attr("innerHTML", $("#" + divId + " li.selected").length + " channels selected");
    }
    else {
        $("#" + anchorId).attr("innerHTML", "(choose channels)");
    }
}
function LoadTVChannels() {
    $.ajax({
        type: "POST",
        cache: false,
        url: "/FindSavings/TVChannels",
        success: function(data) {
            if (data != null && data.length > 0) {
                {
                    if ($("#divchannelcats").length == 0) {
                        $("#divChannelList").append(data);
                    }

                    $.ajax({
                        type: "POST",
                        cache: false,
                        url: "/FindSavings/GetStoredSelectedTVChannel",
                        dataType: "json",
                        success: function(res) {


                            if ($(".selected").length > 0) {
                                $(".selected").each(function(index) {
                                    $(this).removeClass("selected");
                                });
                            }
                            if (res != "") {
                                var arrSelected = res.split(",");

                                if ($(".channel").length > 0) {
                                    for (var cnt = 0; cnt < arrSelected.length; cnt++) {
                                        $(".channel").each(function(index) {
                                            if ($(this).attr("channelID") == arrSelected[cnt]) {
                                                $(this).addClass("selected");
                                            }
                                        });
                                    }
                                }
                            }


                            $("#tv_general").click(function() {


                                if ($("#tv_general").attr("checked")) {
                                    FindAndShowResources("tv_general");
                                }
                                else {
                                    if ($("#divAllChannels td input:checked").length > 0)
                                        FindAndShowResources($("#divAllChannels td input:checked")[0].id);
                                    else {
                                        CloseChannelPopUp();
                                    }
                                }

                            });
                            $("#tv_Sports").click(function() {

                                if ($("#tv_Sports").attr("checked")) {
                                    FindAndShowResources("tv_Sports");
                                }
                                else {
                                    if ($("#divAllChannels td input:checked").length > 0)
                                        FindAndShowResources($("#divAllChannels td input:checked")[0].id);
                                    else {
                                        CloseChannelPopUp();
                                    }

                                }
                            });
                            $("#tv_Movies").click(function() {

                                if ($("#tv_Movies").attr("checked")) {
                                    FindAndShowResources("tv_Movies");
                                }
                                else {
                                    if ($("#divAllChannels td input:checked").length > 0)
                                        FindAndShowResources($("#divAllChannels td input:checked")[0].id);
                                    else {
                                        CloseChannelPopUp();
                                    }
                                }
                            });
                            $("#tv_Music").click(function() {

                                if ($("#tv_Music").attr("checked")) {
                                    FindAndShowResources("tv_Music");
                                }
                                else {
                                    if ($("#divAllChannels td input:checked").length > 0)
                                        FindAndShowResources($("#divAllChannels td input:checked")[0].id);
                                    else {
                                        CloseChannelPopUp();
                                    }
                                }
                            });
                            $("#tv_Adult").click(function() {

                                if ($("#tv_Adult").attr("checked")) {
                                    FindAndShowResources("tv_Adult");
                                }
                                else {
                                    if ($("#divAllChannels td input:checked").length > 0)
                                        FindAndShowResources($("#divAllChannels td input:checked")[0].id);
                                    else {
                                        CloseChannelPopUp();
                                    }
                                }
                            });
                            $("#tv_Family").click(function() {

                                if ($("#tv_Family").attr("checked")) {
                                    FindAndShowResources("tv_Family");
                                }
                                else {
                                    if ($("#divAllChannels td input:checked").length > 0)
                                        FindAndShowResources($("#divAllChannels td input:checked")[0].id);
                                    else {
                                        CloseChannelPopUp();
                                    }

                                }

                            });
                            $("#tv_News").click(function() {

                                if ($("#tv_News").attr("checked")) {
                                    FindAndShowResources("tv_News");
                                }
                                else {
                                    if ($("#divAllChannels td input:checked").length > 0)
                                        FindAndShowResources($("#divAllChannels td input:checked")[0].id);
                                    else {
                                        CloseChannelPopUp();
                                    }
                                }
                            });
                            $("#tv_Education").click(function() {

                                if ($("#tv_Education").attr("checked")) {
                                    FindAndShowResources("tv_Education");
                                }
                                else {
                                    if ($("#divAllChannels td input:checked").length > 0)
                                        FindAndShowResources($("#divAllChannels td input:checked")[0].id);
                                    else {
                                        CloseChannelPopUp();
                                    }

                                }
                            });
                            $("#tv_International").click(function() {

                                if ($("#tv_International").attr("checked")) {
                                    FindAndShowResources("tv_International");
                                }
                                else {
                                    if ($("#divAllChannels td input:checked").length > 0)
                                        FindAndShowResources($("#divAllChannels td input:checked")[0].id);
                                    else {
                                        CloseChannelPopUp();
                                    }
                                }
                            });

                        }


                    });

                }
                isChannelTabLoaded = true;
            }

        }
    });
}
function ShowBundleConfirmation(showBundleView, serviceID, bundleViewLoaded) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ShowBundleConfirmation(' + showBundleView + ', "' + serviceID + '", ' + bundleViewLoaded + ')');
    if (!billValueCleared) {
        $("#dialog-confirm").dialog({
            resizable: false,
            height: 160,
            width: 400,
            modal: true,
            buttons: {
                'Continue': function() {
                    $(this).dialog('close');
                    LoadBundleView(showBundleView, serviceID, bundleViewLoaded);
                    ResetBillUI();

                },
                Cancel: function() {
                    $(this).dialog('close');
                    if (!showBundleView) {
                        $("#noBundle").attr('checked', false);
                        $("#yesBundle").attr('checked', 'checked');
                    }
                    else {
                        $("#noBundle").attr('checked', 'checked');
                        $("#yesBundle").attr('checked', false);
                    }


                }
            }
        });
        var closeSpan = $("div[role='dialog'] span.ui-icon-closethick");

        closeSpan.parent().remove();


    }
}

function ClearBillInformation() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ClearBillInformation()');
    if (!billValueCleared) {
        $("#monthlyBillID").val('');
        $("#monthlySliderTouch").slider("value", -1);

        //        if (parseInt(billAmount) > 0) {
        //            $("#monthlyBillID").val(0);
        //            $("#datepicker").val("");
        //            $("#terminationFee").val("0");
        //            //default is set to 10
        //            //$("#monthlySlider").slider("option", "value", 10);
        //            $("#monthlySlider").slider("option", "value", 0);
        //            billValueCleared = true;
        //        }
    }
    $("#ClearBillInfoID").val("true");
}

function ShowCalc() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ShowCalc()');
    LogOmnitureModalShow("Refrigerator Calculation");
    $('#RefrigeratorModal').jqmShow();
}

function ShowSignIn() {
    $("#header").css("z-Index", "0");
    $("#divSavingsDD").css("display", "none");
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ShowSignIn()');
    $('#ForgotPwdModal').jqmHide();
    LogOmnitureModalShow("Sign In");
    $('#RegSignModal').jqmShow();
}


function ShowSignInPrePopulate(email) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ShowSignInPrePopulate("' + email + '")');
    $('#EmailAddress').val(email);
    ShowSignIn();
}

function ShowRegister() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ShowRegister()');
    $('#ForgotPwdModal').jqmHide();
    LogOmnitureModalShow("Register");
    $('#RegSignModal').jqmShow();
}

function ShowForgotPwd() {
    if (typeof ClickTaleTag == 'function') ClickTaleTag('Forgot Password');
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ShowForgotPwd()');
    $('#RegSignModal').jqmHide();
    LogOmnitureModalShow("Forgot password");
    $('#ForgotPwdModal').jqmShow();
}


function ConfigureLogOff() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ConfigureLogOff()');
    if (isPageDirty) {
        SaveUserProfile("/Home", false);
    }
    else {
        LogOff();
    }
}
function LogOff() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('LogOff()');
    $.ajax({
        url: "/Account/Logoff",
        type: "GET",
        cache: false,
        success: function(result) {
            ToggleSignInLink();
            window.location.href = '/';
            asyncLogIn = false;
        }
    });

}

function IsRegisterValid(obj1) {
    var valid = false;
    if (document.getElementById('hdn').value != "13" && document.getElementById('hdn').value != "valid") {
        obj1.srcElement.value = obj1.srcElement.value + chr(obj1.keyCode);
    }
    if (document.getElementById('hdn').value == "13"
        || (obj1.type == "click" && (document.getElementById('hdn').value == "valid"))) {

        valid = true;
    }

    return valid;
}

function Register(valid) {
    if (valid) {
        var firstName, lastName, email, password, confirmPassword, sendAlert, sendNewsletter;
        if (typeof ClickTaleTag == 'function') ClickTaleTag('Create Profile');
        firstName = $("#Register_FirstName").val();
        lastName = $("#Register_LastName").val();
        email = $("#Register_Email").val();
        nickname = $("#Register_Nickname").val();
        regPassword = $("#Register_RegPassword").val();
        confirmPassword = $("#Register_ConfirmPassword").val();
        sendAlert = $("#Register_SendEmailAlerts").attr("checked");
        sendNewsletter = $("#Register_SendNewsletter").attr("checked");

        //Omniture
        sendCode = "";
        if (sendAlert == true) {
            sendCode = "alerts";
        }
        if (sendNewsletter == true) {
            if (sendCode.length > 0) {
                sendCode += ",";
            }
            sendCode += "newsletter";
        }
       

        $.ajax({
            url: "/Account/Register",
            type: "POST",
            cache: false,
            data: { "Register.FirstName": firstName, "Register.LastName": lastName, "Register.Email": email, "Register.Nickname": nickname, "Register.RegPassword": regPassword, "Register.ConfirmPassword": confirmPassword, "Register.SendEmailAlerts": sendAlert, "Register.SendNewsLetter": sendNewsletter },
            success: function(result) {
                if (result.length > 2 && result.substring(0, 1) == 'S') {
                    $('#RegSignModal').jqmHide();
                    //$('#RegisterModal').jqmHide();
                    ToggleSignInLink();
                    if (saveUserData) {
                        $("#UserStatusChanged").val("loggedin");
                        if (!isGetAlertSaveUserData) {
                            PostMyServicesData();
                        }
                        isGetAlertSaveUserData = false;
                        saveUserData = false;
                    }
                }
                else if (result.length > 2 && result.substring(0, 1) == 'R') {
                    var redirect = result.substring(2);
                    $(location).attr('href', redirect);
                }
                else {
                    if (typeof ClickTaleTag == 'function') ClickTaleTag('Register: Failed');
                    $('#RegSignModal').jqmHide();
                    //$('#RegisterModal').jqmHide();
                    $("#RegSignModalContainer").empty();
                    $("#RegSignModalContainer").append(result);
                    ShowRegister();
                }
            }
        });
    }
}

function ResetSaveUserData() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ResetSaveUserData()');
    saveUserData = false;
    isGetAlertSaveUserData = false;
}
function ShowAlertsModal() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ShowAlertsModal()');
    saveUserData = true;
    isGetAlertSaveUserData = true;
    ShowSignIn();
}

function IsSignInValid(obj1) {
    var valid = false;
    if (document.getElementById('hdn').value != "13" && document.getElementById('hdn').value != "valid") {
        obj1.srcElement.value = obj1.srcElement.value + chr(obj1.keyCode);
    }
    if (document.getElementById('hdn').value == "13"
        || (obj1.type == "click"
            && (document.getElementById('hdn').value == "valid"))) {

        valid = true;
    }

    return valid;
}

function SignIn(valid) {
    if (valid) {
        var email, password;
        if (typeof ClickTaleTag == 'function') ClickTaleTag('Sign In: Start');
        email = $("#LogOn_EmailAddress").val();
        password = $("#LogOn_Password").val();

        $.ajax({
            url: "/Account/Logon",
            type: "POST",
            cache: false,
            data: { "LogOn.EmailAddress": email, "LogOn.Password": password },
            success: function(result) {
                CheckAddressChange();
                if (result.length > 7 && result.substring(0, 7) == 'Success') {
                    if (typeof ClickTaleExec == 'function') ClickTaleExec('$("#RegSignModal").jqmHide();');
                    $('#RegSignModal').jqmHide();
                    //$('#SignInModal').jqmHide();

                    if (typeof ClickTaleExec == 'function') ClickTaleExec('ToggleSignInLink()');
                    ToggleSignInLink();
                    asyncLogIn = true;
                    if (typeof ClickTaleTag == 'function') ClickTaleTag('Sign In: Success');
                    //LogOmnitureSignIn(email);
                    if (saveUserData) {
                        $("#UserStatusChanged").val("loggedin");
                        if (!isGetAlertSaveUserData) {
                            PostMyServicesData();
                        }
                        isGetAlertSaveUserData = false;
                        saveUserData = false;


                    }

                    window.location.href = "/MyProfile";



                }
                else {
                    if (typeof ClickTaleTag == 'function') ClickTaleTag('Sign In: Failed');
                    if (typeof ClickTaleExec == 'function') ClickTaleExec('$("#RegSignModal").jqmHide()');
                    $('#RegSignModal').jqmHide();
                    //$('#SignInModal').jqmHide();
                    if (typeof ClickTaleExec == 'function') ClickTaleExec('$("#RegSignModalContainer").empty()');
                    $("#RegSignModalContainer").empty();
                    if (typeof ClickTaleExec == 'function') ClickTaleExec('$("#RegSignModalContainer").append(result)');
                    $("#RegSignModalContainer").append(result);
                    ShowSignIn();
                }
            }
        });
    }
}

function CheckAddressChange() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('CheckAddressChange()');
    $.ajax({
        url: "/Account/IsAddressSame",
        cache: false,
        success: function(result) {
            if (result != null) {
                if (result.showAddressModal) {
                    ShowAddressModal();
                }
                else if (result.hasRedirect) {
                    $(location).attr('href', result.redirectUrl);
                }
                else {
                    location.reload();
                }
            }
        }
    });
}


function ShowAddressModal() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ShowAddressModal()');
    $.ajax({
        url: "/Account/AddressModal",
        cache: false,
        success: function(result) {
            if (result != null) {
                $('#AddressModal').jqmHide();
                $("#AddressModal").empty();
                $("#AddressModal").append(result);
                LogOmnitureModalShow("Address Modal");
                $('#AddressModal').jqmShow();
            }
        }
    });
}

function PostAddressChange() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('PostAddressChange()');
    if ($('input:radio[name|=address]:checked').val() == '0') {
        UpdateCurrentAddress();
    }
    else {
        UpdateUserAddress();
    }
    $('#AddressModal').jqmHide();
}
function UpdateUserAddress() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('UpdateUserAddress()');
    $.ajax({
        url: "/Account/UpdateAddress",
        type: "POST",
        cache: false,
        success: function(result) {
            if (result != null) {
                if (result.hasRedirect) {
                    $(location).attr('href', result.redirectUrl);
                }
                else if (result.refreshPage) {
                    location.reload();
                }
            }
        }
    });
}
function UpdateCurrentAddress() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('UpdateCurrentAddress()');
    $.ajax({
        url: "/Account/AccountRedirect",
        type: "POST",
        cache: false,
        success: function(result) {
            if (result != null) {
                if (result.hasRedirect) {
                    $(location).attr('href', result.redirectUrl);
                }
                else if (result.refreshPage) {
                    location.reload();
                }
            }
        }
    });
}
function PostMyServicesData() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('PostMyServicesData()');
    PopulateChannelList();
    $("#serviceForm").submit();
}

function ToggleSignInLink() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ToggleSignInLink()');
    $('#signin').toggle();
    $('#signout').toggle();
    $('#homeServicesID').toggle();
    $('#alertsID').toggle();
    $('#registerSaveCostSaving').toggle();
    $('#saveCostSaving').toggle();
    $('#registerShoppingCart').toggle();
    $('#shoppingCartCheckout').toggle();
    $('#registerSummaryBarAlert').toggle();
    $('#summaryBarAlert').toggle();
    if ($('#recomgreenbox')) {
        $('#recomgreenbox').toggle();
    }
}

function RetrievePassword() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('RetrievePassword()');
    var email;

    email = $("#UserEmailAddress").val();

    $.ajax({
        url: "/Account/ForgotPassword",
        type: "POST",
        cache: false,
        data: { UserEmailAddress: email },
        success: function(result) {
            if (result.length > 7 && result.substring(0, 7) == 'Success') {
                $('#forgotMessage').show();
                ShowSignIn();
            }
            else {
                $('#ForgotPwdModal').jqmHide();
                $("#ForgotPwdModalContainer").empty();
                $("#ForgotPwdModalContainer").append(result);
                ShowForgotPwd();
            }
        }
    });
}

var isBundleViewLoaded = false;

function VerifyAddress() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('VerifyAddress()');

    var cityStateZip = $("#CityStateZip").val();
    var aptCondoNo = $("#AptCondoNo").val();
    var homeAddress = $("#HomeAddress").val();


    VerifyAddressAjax(homeAddress, aptCondoNo, cityStateZip);
}

function SearchModalAddress() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SearchModalAddress()');

    var cityStateZip = $("#SearchHomeAddress").val();
    var aptCondoNo = $("#SearchAptCondoNo").val();
    var homeAddress = $("#SearchCityStateZip").val();

    VerifyAddressAjax(cityStateZip, aptCondoNo, homeAddress);

}

function UpdateProgressbar() {
    $.ajax({
        url: "/FindSavings/UpdateProgressbar",
        type: "GET",
        cache: false,
        success: function(result) {
            $("#progressbarContainer").html(result);
        }
    });
}

function VerifyAddressAjax(homeAddress, aptCondoNo, cityStateZip) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('VerifyAddressAjax("' + homeAddress + '", "' + aptCondoNo + '", "' + cityStateZip + '")');
    $.ajax({
        url: "/FindSavings/Summary",
        type: "POST",
        cache: false,
        data: { CityStateZip: cityStateZip, HomeAddress: homeAddress, AptCondoNo: aptCondoNo },
        success: function(result) {
            HandleResponse(result);
        }
    });
}


function HandleResponse(response) {
    if (response.length > 7 && response.substring(0, 15) == 'window.location') {
        //Redirect: /MyHomeServices/Summary
        var url = response.substring(16, response.length);
        window.href = url;
    }
    else if (response.toString().indexOf("/Interstitial/Bundle") > -1) {
        var url = response.substring(16, response.length)
        $.ajax({
            url: url,
            type: "GET",
            cache: false

        });
    }
    else {
        $("#SpecifyAddressModal").remove(); //In case this is the second time they've requested the dialog.
        $("#summaryview").empty();
        $("#summaryview").append(response);
    }

}
function ContractTimeRemainingOption() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ContractTimeRemainingOption()');
    var i = 1;
    for (var providerID = 3; providerID <= 24; providerID = providerID * 2) {

        var today = new Date();
        Date.prototype.addMonths = function(n) {
            this.setMonth(this.getMonth() + n);

            return this;
        }
        var d = new Date().addMonths(providerID * 1);

        var month = d.getMonth();
        var year = d.getFullYear();

        //Get the last date of the month
        var m = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];


        //Get the last date of the month
        if (month != 1) { d.setDate(m[month]); }
        if (year % 4 != 0 && month == 1) { d.setDate(m[1]); }
        if (year % 100 == 0 && year % 400 != 0) { d.setDate(m[1] + 1); }

        var temp = "";
        month = month + 1;
        if (month >= 1 && month <= 9) {
            temp = "0" + month + "/" + d.getDate() + "/" + d.getFullYear();
        }
        else {
            temp = month + "/" + d.getDate() + "/" + d.getFullYear();
        }
        if (temp == $("#datepicker").val()) {
            $("#contractTimeRemaining").attr("selectedIndex", i);
            break;
        }

        i++;

    }
}
function ContractTimeRemainingChanged() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ContractTimeRemainingChanged()');
    var providerID = $("#contractTimeRemaining option:selected").val();
    if (providerID != "-1") {
        var today = new Date();
        Date.prototype.addMonths = function(n) {
            this.setMonth(this.getMonth() + n);

            return this;
        }
        var d = new Date().addMonths(providerID * 1);

        var month = d.getMonth();
        var year = d.getFullYear();

        //Get the last date of the month
        var m = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        if (month != 1) { d.setDate(m[month]); }
        if (year % 4 != 0 && month == 1) { d.setDate(m[1]); }
        if (year % 100 == 0 && year % 400 != 0) { d.setDate(m[1] + 1); }

        month = month + 1;
        if (month >= 1 && month <= 9) {
            $("#datepicker").val("0" + month + "/" + d.getDate() + "/" + d.getFullYear());
        }
        else {
            $("#datepicker").val(month + "/" + d.getDate() + "/" + d.getFullYear());
        }
    }
    else {
        $("#datepicker").val("");
    }
}

function ProviderListChanged() {
    if ($("#CurrentProvider").val() != "") {
        $("#ConfirmationPV").show();
        $("#PrefencesBox").hide();

        $('input:radio[name=radioChangeProvider]')[0].checked = false;
        $('input:radio[name=radioChangeProvider]')[1].checked = false;
    }
    else {
        ProviderChangedStep2();
    }

}

function ProviderChangedStep2() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ProviderListChanged()');
    $("#CurrentProvider").val($("#providerList > option:selected").attr("value"));
    var providerID = $("#providerList > option:selected").attr("value");
    var providerName = $("#providerList > option:selected").text();
    var showProv = showProviderInfo();
    if (!showProv) {
        $("#otherLabel").css("display", "block");
    }
    else {
        $("#otherLabel").css("display", "none");
    }
    if (showProv) {

        $("#providerName").val(providerName);
        var productID = providerID.split("-");
        var serviceID = productID[2];
        var logoID = productID[0];
        //No need to make ajax call.
        $.ajax({
            type: "GET",
            cache: false,
            url: "/ProviderRatings/" + providerID + "/" + serviceID,
            success: function(data) {
                if (data != null) {
                    $("#ratingsControl").empty();
                    $("#ratingsControl").append(data);
                    $("#serviceProviderRating").css("display", "block");
                    $("#serviceProviderLogo").attr({ src: "http://www.allconnect.com/shared/providers/" + logoID + "/img/small.gif" });
                    $("#serviceProviderName").text(providerName);
                }

            }
        });


    }
    else {
        $("#serviceProviderRating").css("display", "none");

    }
}

/*Hes Calculators Start*/
/*Electric*/
function SubmitRefrigerator() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitRefrigerator()');
    if (isFormValid != false) {
        var number, type1, year1, size1, type2, year2, size2, type3, year3, size3, electricrate;
        number = $("#RefrigNumber").val();
        type1 = $("#Type1").val();
        year1 = $("#Year1").val();
        size1 = $("#Size1").val();
        type2 = $("#Type2").val();
        year2 = $("#Year2").val();
        size2 = $("#Size2").val();
        type3 = $("#Type3").val();
        year3 = $("#Year3").val();
        size3 = $("#Size3").val();
        electricrate = $("#txtRate").val();
        var url = "/HesCalculators/Refrigerator";
        $.ajax({
            url: url,
            type: "POST",
            cache: false,
            data: { Number: number, Type1: type1, Year1: year1, Size1: size1, Type2: type2, Year2: year2, Size2: size2, Type3: type3, Year3: year3, Size3: size3, ElectricRate: electricrate },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url);
            }
        });
    }
}
function SubmitDishwasher() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitDishwasher()');
    if (isFormValid != false) {
        var fuel, er, gr, wr, lw;
        fuel = $("#hdnFuel").val();
        er = $("#txtER").val();
        gr = $("#txtGR").val();
        wr = $("#txtWR").val();
        lw = $("#txtLW").val();
        var url = "/HesCalculators/Dishwasher";
        $.ajax({
            url: url,
            type: "POST",
            cache: false,
            data: { Fuel: fuel, LW: lw, ER: er, GR: gr, WR: wr },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url);
            }
        });
    }
}
function SubmitOvenStove(serviceArea) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitOvenStove(' + serviceArea + ')');
    if (isFormValid != false) {
        var uw, er, gr;
        uw = $("#txtUW").val();
        er = $("#txtER").val();
        gr = $("#txtGR").val();
        url1 = getUrl(serviceArea);
        $.ajax({
            url: url1,
            type: "POST",
            cache: false,
            data: { UW: uw, ER: er, GR: gr },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url1);
            }
        });
    }
}
function SubmitCentralAC() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitCentralAC()');
    if (isFormValid != false) {
        var city, td, seer, age, size, er, nu;
        city = $("#City").val();
        td = $("#hdnTD").val();
        seer = $("#Seer").val();
        age = $("#Age").val();
        size = $("#Size").val();
        er = $("#txtER").val();
        nu = $("#txtNU").val();
        var url = "/HesCalculators/CentralAC";
        $.ajax({
            url: url,
            type: "POST",
            cache: false,
            data: { City: city, TD: td, Seer: seer, Age: age, Size: size, ER: er, NU: nu },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url);
            }
        });
    }
}
function SubmitHeatPump() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitHeatPump()');
    if (isFormValid != false) {
        var city, td, seer, age, size, er, nu;
        city = $("#City").val();
        td = $("#hdnTD").val();
        seer = $("#Seer").val();
        er = $("#txtER").val();
        var url = "/HesCalculators/HeatPump";
        $.ajax({
            url: url,
            type: "POST",
            cache: false,
            data: { City: city, TD: td, Seer: seer, ER: er },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url);
            }
        });
    }
}
function SubmitProgThermostat() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitProgThermostat()');
    if (isFormValid != false) {
        var unit, city, td, seer, age, size, er, nu;
        unit = $("#hdnUT").val();
        city = $("#City").val();
        td = $("#hdnTD").val();
        seer = $("#Seer").val();
        seer1 = $("#Seer1").val();
        age = '10';
        size = '3.5';
        nu = '1';
        if (unit == '5') {
            age = $("#Age").val();
            size = $("#Size").val();
            nu = $("#txtNU").val();
        }
        er = $("#txtER").val();
        var url = "/HesCalculators/ProgThermostat";
        $.ajax({
            url: url,
            type: "POST",
            cache: false,
            data: { Unit: unit, City: city, TD: td, Seer: seer, Seer1: seer1, Age: age, Size: size, ER: er, NU: nu },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url);
            }
        });
    }
}
function SubmitEWaterHeater() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitEWaterHeater()');
    if (isFormValid != false) {
        var year, er;
        year = $("#Year").val();
        er = $("#txtER").val();
        var url = "/HesCalculators/WaterHeater";
        $.ajax({
            url: "/HesCalculators/WaterHeater",
            type: "POST",
            cache: false,
            data: { Year: year, ER: er },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
               // LogOmnitureCalcFindSavings(url);
            }
        });
    }
}
function SubmitClothesWasher() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitClothesWasher()');
    if (isFormValid != false) {
        var fuel, er, gr, wr, lw;
        fuel = $("#hdnFuel").val();
        er = $("#txtER").val();
        gr = $("#txtGR").val();
        wr = $("#txtWR").val();
        lw = $("#txtLW").val();
        var url = "/HesCalculators/ClothesWasher";
        $.ajax({
            url: url,
            type: "POST",
            cache: false,
            data: { Fuel: fuel, LW: lw, ER: er, GR: gr, WR: wr },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url);
            }
        });
    }
}
function SubmitClothesDryer() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitClothesDryer()');
    if (isFormValid != false) {
        var er, lw;
        er = $("#txtER").val();
        lw = $("#txtLW").val();
        var url = "/HesCalculators/ClothesDryer";
        $.ajax({
            url: url,
            type: "POST",
            cache: false,
            data: { LW: lw, ER: er },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url);
            }
        });
    }
}
function SubmitChangeHeatTemp() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitChangeHeatTemp()');
    if (isFormValid != false) {
        var fuel, city1, td, seer, er;
        fuel = $("#hdnFuel").val();
        city1 = $("#City1").val();
        td = $("#hdnTD").val();
        seer = $("#Seer").val();
        er = $("#txtER").val();
        var city, year, size, gr;
        city = $("#City").val();
        year = $("#Year").val();
        size = $("#txtSize").val();
        gr = $("#txtGR").val();
        var ct, nt;
        ct = $("#txtCT").val();
        nt = $("#txtNT").val();
        var sa = $("#MyServiceAreaMode").val();
        var url = "/HesCalculators/ChangeHeatingTemp";
        $.ajax({
            url: url,
            type: "POST",
            cache: false,
            data: { Fuel: fuel, CT: ct, NT: nt, ER: er, GR: gr, City1: city1, TD: td, Seer: seer, City: city, Year: year, Size: size, GR: gr, MyServiceAreaMode: sa },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url);
            }
        });
    }
}
function SubmitChangeCoolTemp() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitChangeCoolTemp()');
    if (isFormValid != false) {
        var er, gr, ct, nt, city, td, seer, age, size, nu;
        er = $("#txtER").val();
        ct = $("#txtCT").val();
        nt = $("#txtNT").val();
        city = $("#City").val();
        td = $("#hdnTD").val();
        seer = $("#Seer").val();
        age = $("#Age").val();
        size = $("#Size").val();
        nu = $("#txtNU").val();
        var url = "/HesCalculators/ChangeCoolTemp";
        $.ajax({
            url: url,
            type: "POST",
            cache: false,
            data: { CT: ct, NT: nt, ER: er, City: city, TD: td, Seer: seer, Age: age, Size: size, NU: nu },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url);
            }
        });
    }
}

function SubmitChangeWaterHeaterTemp() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitChangeWaterHeaterTemp()');
    if (isFormValid != false) {
        var fuel, er, gr, ct, nt, year;
        fuel = $("#hdnFuel").val();
        er = $("#txtER").val();
        gr = $("#txtGR").val();
        ct = $("#txtCT").val();
        year = $("#Year").val();
        nt = $("#txtNT").val();
        var sa = $("#MyServiceAreaMode").val();
        url = "/HesCalculators/ChangeWaterHeaterTemp";
        $.ajax({
            url: url,
            type: "POST",
            cache: false,
            data: { Fuel: fuel, CT: ct, NT: nt, ER: er, GR: gr, Year: year, MyServiceAreaMode: sa },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url);
            }
        });
    }
}
function SubmitLighting() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitLighting()');
    if (isFormValid != false) {
        var hr, er, wt, nu;
        hr = $("#txtHours").val();
        er = $("#txtER").val();
        wt = $("#Watts").val();
        nu = $("#txtNumber").val();
        var url = "/HesCalculators/Lighting";
        $.ajax({
            url: url,
            type: "POST",
            cache: false,
            data: { Number: nu, Watts: wt, Hours: hr, ER: er },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url);
            }
        });
    }
}
/*Natural Gas*/
function SubmitNaturalGas(serviceArea) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitNaturalGas(' + serviceArea + ')');
    if (isFormValid != false) {
        var city, year, size, gr;
        city = $("#City").val();
        year = $("#Year").val();
        size = $("#txtSize").val();
        gr = $("#txtGR").val();
        url1 = getUrl(serviceArea);
        $.ajax({
            url: url1,
            type: "POST",
            cache: false,
            data: { City: city, Year: year, Size: size, GR: gr },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url1);
            }
        });
    }
}
function SubmitNGWaterHeater() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitNGWaterHeater()');
    if (isFormValid != false) {
        var year, gr;
        year = $("#Year").val();
        gr = $("#txtGR").val();
        var url = "/HesCalculators/NGWaterHeater";
        $.ajax({
            url: url,
            type: "POST",
            cache: false,
            data: { Year: year, GR: gr },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url);
            }
        });
    }
}
function SubmitLFToilet() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitLFToilet()');
    if (isFormValid != false) {
        var nh, lf, wr;

        nh = $("#txtNH").val();
        lf = $("#ddLF").val();
        wr = $("#txtWR").val();
        var url = "/HesCalculators/LFToilets";
        $.ajax({
            url: url,
            type: "POST",
            cache: false,
            data: { NH: nh, LF: lf, WR: wr },
            success: function(response) {

                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url);
            }
        });
    }
}
function SubmitBath(serviceArea) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitBath(' + serviceArea + ')');
    if (isFormValid != false) {
        var nh, mu, wr;

        nh = $("#txtNH").val();
        mu = $("#txtMU").val();
        wr = $("#txtWR").val();
        url1 = getUrl(serviceArea);
        $.ajax({
            url: url1,
            type: "POST",
            cache: false,
            data: { NH: nh, MU: mu, WR: wr },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url1);
            }
        });
    }
}
function SubmitWasher(serviceArea) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitWasher(' + serviceArea + ')');
    if (isFormValid != false) {
        var wr, lw;
        wr = $("#txtWR").val();
        lw = $("#txtLW").val();
        url1 = getUrl(serviceArea);
        $.ajax({
            url: url1,
            type: "POST",
            cache: false,
            data: { LW: lw, WR: wr },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url1);
            }
        });
    }
}
function SubmitWCarWash(serviceArea) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitWCarWash(' + serviceArea + ')');
    if (isFormValid != false) {
        var wr, fw, url1;
        wr = $("#txtWR").val();
        fw = $("#txtFW").val();
        url1 = getUrl(serviceArea);
        $.ajax({
            url: url1,
            type: "POST",
            cache: false,
            data: { FW: fw, WR: wr },
            success: function(response) {
                $("#CalculatorModal").empty();
                $("#CalculatorModal").append(response);
                $("#RecFinderModalBg2").show();
                //LogOmnitureCalcFindSavings(url1);
            }
        });
    }
}
function CancelClose() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('CancelClose()');
    $("#CalculatorModal").empty();
    $("#RecFinderModalBg2").hide();
}
function getUrl(ServiceArea) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('getUrl(' + ServiceArea + ')');
    var url1;
    //ServiceArea = ServiceArea * 1;
    switch (ServiceArea) {
        case 1:
            url1 = "/HESCalculators/Refrigerator";
            break;
        case 2:
            url1 = "/HESCalculators/Dishwasher";
            break;
        case 3:
            url1 = "/HESCalculators/Oven";
            break;
        case 4:
            url1 = "/HESCalculators/Stove";
            break;
        case 5:
            url1 = "/HESCalculators/CentralAC";
            break;
        case 6:
            url1 = "/HESCalculators/HeatPump";
            break;
        case 7:
            url1 = "/HESCalculators/ProgThermostat";
            break;
        case 8:
            url1 = "/HESCalculators/WaterHeater";
            break;
        case 9:
            url1 = "/HESCalculators/ClothesWasher";
            break;
        case 10:
            url1 = "/HESCalculators/ClothesDryer";
            break;
        case 11:
            url1 = "/HESCalculators/ChangeHeatingTemp";
            break;
        case 12:
            url1 = "/HESCalculators/ChangeCoolTemp";
            break;
        case 13:
            url1 = "/HesCalculators/Lighting";
            break;
        case 14:
            url1 = "/HESCalculators/IndividualElectricalItem";
            break;
        case 15:
            url1 = "/HESCalculators/NGFurnace";
            break;
        case 16:
            url1 = "/HESCalculators/NGProgThermostat";
            break;
        case 17:
            url1 = "/HESCalculators/NGWaterHeater";
            break;
        case 19:
            url1 = "/HESCalculators/NGChangeHeatingTemp";
            break;
        case 21:
            url1 = "/HESCalculators/LFToilets";
            break;
        case 22:
            url1 = "/HESCalculators/LFBathFaucets";
            break;
        case 23:
            url1 = "/HESCalculators/LFShowerHeads";
            break;
        case 24:
            url1 = "/HESCalculators/WClothesWasher";
            break;
        case 25:
            url1 = "/HESCalculators/WDishwasher";
            break;
        case 26:
            url1 = "/HESCalculators/WCarWashOverall";
            break;
        case 27:
            url1 = "/HESCalculators/WCarWashClosingNozzle";
            break;
        case 29:
            url1 = "/HESCalculators/Donations";
            break;
        case 30:
            url1 = "/HESCalculators/ChangeWaterHeaterTemp";
            break;
        case 31:
            url1 = "/HESCalculators/NGChangeWaterHeaterTemp";
            break;
        default:
            return true;
    }
    return url1;
}
function ShowCalculator(ServiceArea, type) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ShowCalculator(' + ServiceArea + ')');
    var url1;
    url1 = getUrl(ServiceArea);
    var closeOnRefresh = function(hash) {
        window.location.reload();
    };
    //show loading    
    $("#CalculatorModal").empty();
    $("#CalculatorModal").append("<div class='top'></div><div class='modaltext'><div class='modal_whitebox'><div class='inter-om'><p>Loading</p></div></div></div><div class='bottom'></div>");
    $("#RecFinderModalBg2").show();
    $("#CalculatorModal").show();

    //$("#CalculatorModal").jqmShow();
    //make call to render calculator
    if (url1 != undefined) {
        if (type != null) {
            $.ajax({

                url: "/Recommendations/SetServiceTypeAndGetHESCalculator",
                data: { sType: type, redirectTo: url1 },
                type: "GET",
                cache: false,
                success: function(response) {
                    //                    $.ajax({
                    //                        url: url1,
                    //                        type: "GET",
                    //                        cache: false,
                    //                        success: function(response) {
                    $("#CalculatorModal").empty();
                    $("#CalculatorModal").append(response);
                    $('#CalculatorModal').jqm({ onHide: closeOnRefresh });
                    var slashPosition = url1.lastIndexOf("/");
                    if (slashPosition > 0) {
                        //LogOmnitureShowCalculator(url1.substring(slashPosition + 1));
                        //                            }
                    }
                    //                    });
                }
            });
        }
        else {

            $.ajax({
                url: url1,
                type: "GET",
                cache: false,
                success: function(response) {
                    $("#CalculatorModal").empty();
                    $("#CalculatorModal").append(response);
                    $('#CalculatorModal').jqm({ onHide: closeOnRefresh });
                    var slashPosition = url1.lastIndexOf("/");
                    if (slashPosition > 0) {
                        //LogOmnitureShowCalculator(url1.substring(slashPosition + 1));
                    }
                }
            });
        }
    }

}
/*Hes Calculators end*/

function FilterResults(item) {
    var tabID, bundleTypeID, requestedPage, sortID, ignoreBundleSubTabs
    var providers = [];
    var maxRecurringPrice
    var basicLocal, extendedDigital, highDef, movieChannels, sportsChannels, kidsChannels, tvsToConnect, dvrsNeeded, creditRating
    var internetServiceLevel
    var voiceMail, callWaiting, callerID
    var includeTV, includeInternet, includePhone;
    var realTabId;
    //LogOmnitureFacetChange(item);

    //get sort order
    sortID = $("#sortID").val();

    //get current tab.
    if ($(".tabSelected") != null) {
        tabID = $(".tabSelected").attr("tag")
        realTabId = tabID;
    }
    if (realTabId == 4 || realTabId == 5 || realTabId == 6 || realTabId == 7) {
        tabID = 14;
    }
    if (realTabId == 15 || realTabId == 9 || realTabId == 10 || realTabId == 11 || realTabId == 12) {
        tabID = 13;
    }
    if (realTabId == 13) {
        realTabId = 15;
    }

    ignoreBundleSubTabs = false;
    if ($('#IgnoreBundleSubTabs') != null) {

        if ($('#IgnoreBundleSubTabs').val() == "1") {
            ignoreBundleSubTabs = true;
        }
    }

    //get current page.
    if ($(".pageSelected") != null) {
        requestedPage = $(".pageSelected").attr("tag")
    }

    //Get List of Providers that are checked.
    $('input[name|=Providers]:checked').each(function(index) {
        providers[providers.length] = this.value;
    });
    // maxRecurringPrice = $('#lblMontlyCost').text();
    maxRecurringPrice = $('#monthlySliderTouchTV').text();

    if ($('#tvheading')) {
        includeTV = true;
        basicLocal = $('#BasicLocal').is(':checked');
        extendedDigital = $('#ExtendedDigital').is(':checked');
        highDef = $('#HighDef').is(':checked');
        movieChannels = $('#MovieChannels').is(':checked');
        sportsChannels = $('#SportsChannels').is(':checked');
        kidsChannels = $('#KidsChannels').is(':checked');
        tvsToConnect = $('#TVsToConnect').val();
        dvrsNeeded = $('#DVRsNeeded').val();
        creditRating = $('#CreditRating').val();
    }

    if ($('#internetheader')) {
        includeInternet = true;
        internetServiceLevel = $("input[name='internet']:checked").val();
    }

    if ($('#phoneheader')) {
        includePhone = true;
        voiceMail = $('#VoiceMail').is(':checked');
        callWaiting = $('#CallWaiting').is(':checked');
        callerID = $('#CallerID').is(':checked');
    }
    //if (tabID == )
    //var

    $.ajax({
        url: "/FilterFacet/Filter",
        type: "POST",
        cache: false,
        data: { SelectedTabID: tabID, SortID: sortID, IgnoreBundleSubTabs: ignoreBundleSubTabs, CompareIDs: compareIDs, CurrentPage: requestedPage, AllowedProviders: providers, MaxRecurringPrice: maxRecurringPrice, BasicLocal: basicLocal, ExtendedDigital: extendedDigital, HighDef: highDef, MovieChannels: movieChannels, SportsChannels: sportsChannels, KidsChannels: kidsChannels, TVSToConnect: tvsToConnect, DVRsNeeded: dvrsNeeded, CreditRating: creditRating, InternetServiceLevel: internetServiceLevel, VoiceMail: voiceMail, CallWaiting: callWaiting, CallerID: callerID, IncludeTVFilter: includeTV, IncludeInternetFilter: includeInternet, IncludePhoneFilter: includePhone, RealSelectedTabID: realTabId },
        success: function(response) {
            realTabId = realTabId + "";
            realTabId = realTabId.replace(/^\s+/g, '').replace(/\s+$/g, '');
            
            switch (realTabId) {
                case "4":
                    location.href = '/Recommendations/ElectricList';
                    break;
                case "5":
                    location.href = '/Recommendations/NaturalGasList';
                    break;
                case "6":
                    location.href = '/Recommendations/WaterList';
                    break;
                case "7":
                    location.href = '/Recommendations/TrashRemovalList';
                    break;
                default:
                    if (response.indexOf("topRecBanner") > -1) {
                        $(".top-rec-btn").attr("href", "/Recommendations/Index");
                    }
                    else {
                        $(".top-rec-btn").attr("href", "javascript:");
                    }
                    $("#RecommendedPlans").empty();
                    $("#RecommendedPlans").append(response);
                    $('#recommendmenu').trigger("changed");
                    if ($(item).hasClass("tabitem")) {
                        ToggleFilters($(item).attr("title"));
                    }
                    break;
            }


        }
    });

}
function BillFilter(val, serviceType1) {
    $("#Busy").val("true");
    $.ajax({
        url: "/Recommendations/SetMonthlyPrice",
        type: "POST",
        cache: false,
        data: { price: $("#" + val).val(), serviceType: serviceType1 },
        error: function(jqXHR, textStatus, errorThrown) {
            $("#Busy").val("false");
        },
        success: function(response) {
            $("#Busy").val("false");
            var str = response.split("~");
            var arr = str[1].split("^");
            var title = serviceType1;
            if (serviceType1 == "TV") {
                title = "TV & Satellite";
            }

            if (str[0] == "true" || str[0] == "True") {

                if (window.location.href.indexOf("Bundle") > -1) {
                    $("a[title='" + title + "']").addClass("tabSelected");
                    var item = $("a[title='" + title + "']");
                    //remove pageing
                    if ($(".pageSelected")) {
                        $(".pageSelected").removeClass("pageSelected");
                    }
                    FilterResults(this);
                }
                else {
                    window.location = "/Recommendations/Bundle";
                }
                if ($("#monthlyBillID" + arr[0]).val() != "" || $("#monthlyBillID" + arr[0]).val() != "0") {
                    $("#monthlyBillID" + arr[1]).val($("#monthlyBillID" + arr[0]).val());
                    if (arr.length >= 3)
                        $("#monthlyBillID" + arr[2]).val($("#monthlyBillID" + arr[0]).val());
                }
                else if ($("#monthlyBillID" + arr[1]).val() != "" || $("#monthlyBillID" + arr[1]).val() != "0") {
                    $("#monthlyBillID" + arr[0]).val($("#monthlyBillID" + arr[1]).val());
                    if (arr.length >= 3)
                        $("#monthlyBillID" + arr[2]).val($("#monthlyBillID" + arr[1]).val());
                }
                else if (arr.length >= 3 && ($("#monthlyBillID" + arr[2]).val() != "" || $("#monthlyBillID" + arr[2]).val() != "0")) {
                    $("#monthlyBillID" + arr[1]).val($("#monthlyBillID" + arr[2]).val());
                    $("#monthlyBillID" + arr[2]).val($("#monthlyBillID" + arr[2]).val());
                }
            }
            else {
                if (window.location.href.indexOf(serviceType1) > -1) {
                    $("a[title='" + title + "']").addClass("tabSelected");
                    var item = $("a[title='" + title + "']");
                    //remove pageing
                    if ($(".pageSelected")) {
                        $(".pageSelected").removeClass("pageSelected");
                    }
                    FilterResults(this);
                }
                else {
                    window.location = "/Recommendations/" + serviceType1;
                }
            }

        }
    });
}

function showProviderInfo() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('showProviderInfo()');
    var isChecked = $("#noServiceCheckbox").attr('checked');
    var providerID = $("#providerList > option:selected").attr("value");
    return !isChecked && providerID != "" && providerID != "-1";
}

function NoServiceCheckBoxChanged() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('NoServiceCheckboxChanged()');
    var isChecked = $("#noServiceCheckbox").attr('checked');
    var providerID = $("#providerList > option:selected").attr("value");
    if (!isChecked) {
        $("#providerList").attr("disabled", false);
        if (providerID != "" && providerID != "-1") {
            $("#serviceProviderRating").css("display", "block");
        }
    }
    else {

        $("#providerList").attr("disabled", true);
        $("#serviceProviderRating").css("display", "none");
        $("#providerList").val("");

    }
}
//Consolidate all the service submit method in to one method
function MyServicesSubmit(isLoggedIn, serviceType) {
    if (RequiresAuthentication(isLoggedIn)) {
        ShowSignIn();
        saveUserData = true;
        return false;
    }
    else {
        if (serviceType == 'TV') {
            PopulateChannelList();
        }
        //LogOmnitureUsageData(serviceType);

        return true;
    }

}

function SaveCalculation(isLoggedIn) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitHeatPump(' + isLoggedIn + ')');
    if (!isLoggedIn) {
        ShowSignIn();
    }
}
function GetRecommendations(isLoggedIn) {
    $("#RecommendationRedirect").val("true");
    if (RequiresAuthentication(isLoggedIn)) {
        ShowSignIn();
        saveUserData = true;
    }
    else {
        PostMyServicesData();
    }

}

function PopulateChannelList() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('PopulateChannelList()');
    var channelIDs = "";
    var packageIDs = "";
    if ($(".selected").length > 0) {
        $(".selected").each(function(index) {
            if (channelIDs.indexOf($(this).attr("channelID")) == -1) {
                if (channelIDs == "") {
                    channelIDs = $(this).attr("channelID");
                }
                else {
                    channelIDs = channelIDs + "," + $(this).attr("channelID");
                }
            }

        });
        $("#HasChannelPackage").val("false");
        $("#ChannelList").val(channelIDs);
    }
    var arr = $('#divChannels table label');
    var arrlbl = $('#divChannels table label');
    for (var i = 0; i < arr.length; i++) {
        if ($(arr[i]).prev().attr("checked")) {
            packageIDs += $(arr[i]).attr("innerHTML") + ",";
        }
    }
    $("#ChannelPackage").val(packageIDs);

}
function RequiresAuthentication(isLoggedIn) {
    var isChecked = $("#save-entries").attr('checked');
    if (asyncLogIn) {
        $("#UserStatusChanged").val("loggedin");
        isLoggedIn = true;
    }
    if (isChecked && !isLoggedIn) {
        return true;
    }
    else {
        return false;
    }
}

function LeftNavSubmit(url, isLoggedIn) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('LeftNavSubmit("' + url + '",' + isLoggedIn + ')');
    $("#LeftNavUrl").val(url);
    if (RequiresAuthentication(isLoggedIn)) {
        MyServicesSubmit(isLoggedIn, url);
    }
    else {
        //LogOmnitureUsageData(url);
        PostMyServicesData();
    }
}
function RedirectToMyProfile() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('RedirectToMyProfile()');
    if (document.location.href.indexOf("FindSavings") > -1
            && (document.location.href.indexOf("Internet") || document.location.href.indexOf("TV") || document.location.href.indexOf("Phone")
                   || document.location.href.indexOf("HomeSecurity") || document.location.href.indexOf("Electricity")
                   || document.location.href.indexOf("Water") || document.location.href.indexOf("NaturalGas")
                   || document.location.href.indexOf("TrashRemoval"))
            ) {
        $.ajax({
            url: "/FindSavings/StoreOtherProviderDetail",
            type: "POST",
            cache: false,

            success: function() {
            }
        });
        window.location = "/Interstitial/Index/MyProfile";


    }
    else {
        window.location = "/MyProfile";
    }
}
function SaveCostSavingTips() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SaveCostSavingTips()');
    var serviceAreaList = [];
    //Get List of service area that are checked.
    $('input[name|=ServiceArea]:checked').each(function(index) {
        serviceAreaList[serviceAreaList.length] = this.value;
    });

    $.ajax({
        url: "/Recommendations/UtilityUpdate",
        type: "POST",
        cache: false,
        data: { ServiceAreaIDs: serviceAreaList },
        success: function(response) {
            $('#successDiv').show();
        }
    });
}
var showCompareButton = false;
function ToggleCompare(externalID) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ToogleCompare("' + externalID + '")');

    if ($("#compareIDs").val().length > 0) {
        showCompareButton = true;
        var externalIDs = $("#compareIDs").val().split(',');
        var removed = false;
        //Remove if we already have
        $("#compareIDs").val("");
        $.each(externalIDs, function(n, val) {
            if (val != externalID) {
                if ($("#compareIDs").val().length == 0) {
                    $("#compareIDs").val(val);
                }
                else {
                    $("#compareIDs").val($("#compareIDs").val() + ',' + val);
                }
            }
            else {
                //We already had in list, so don't add its a remove
                removed = true;

            }
        });

        if (!removed) {
            externalIDs = $("#compareIDs").val().split(',');
            if (externalIDs.length > 2) {
                alert('You may only compare up 3 items at a time.')
                return false;
            }
            else {
                $("#compareIDs").val($("#compareIDs").val() + ',' + externalID);
            }
        }
    }
    else {
        $("#compareIDs").val(externalID);
    }

    return true;
}

function ToggleCompareButton(checkboxItem) {
    var externalIDs = $("#compareIDs").val().split(',');

    $('input[name="compare"]').each(function(i, item) {
        $("#" + $(item).attr('id') + "_label").html('Compare');
        $(item).parent().removeClass("btn-compare");
    });

    if (externalIDs.length > 1) {
        for (var i = 0; i < externalIDs.length; i++) {
            $("#compare_" + externalIDs[i] + "_label").html('<a href="#" onclick="RedirectToCompare(); return false;" class="compare-now">Compare Now</a>');
            $("#compare_" + externalIDs[i] + "_label").parent().parent().addClass("btn-compare");
        }
    }
}

function RedirectToCompare() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('RedirectToCompare()');
    var len = $("#compareIDs").val().split(',').length;
    if ($("#compareIDs").val().length == 0 || len == 1) {
        alert('Please select at least 2 items to compare');
        return false;
    }
    else {
        document.location = "/PlanComparison/" + $("#compareIDs").val();
    }
}


function OpenAddRatings(pId) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('OpenAddRatings(' + pId + ')');
   

    window.open('/RatingsandReviews/Reviews/' + pId + "?bvauthenticateuser=false", 'ratings', 'toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=yes,width=825,height=690,Left=275,Top=150');
}

function OpenViewRatings(pId) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('OpenViewRatings(' + pId + ')');
    window.open('/RatingsandReviews/ViewRatings/' + pId + "?bvauthenticateuser=false", 'ratings', 'toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=yes,width=951,height=690,Left=160,Top=150');
}

function SignInBazaarVoice(obj1) {

    var pId = '<%=ViewData["ProductIDforBazaarvoice"]%>';
    var hsabvId = '<%=Html.RenderBazaarVoiceDomainString()%>';
    var valid = false;
    if (document.getElementById('hdn').value != "13" && document.getElementById('hdn').value != "valid") {
        obj1.srcElement.value = obj1.srcElement.value + chr(obj1.keyCode);
    }
    if (document.getElementById('hdn').value == "13"
        || (obj1.type == "click"
            && (document.getElementById('hdn').value == "valid"))) {

        valid = true;
    }
    if (valid) {
        var email, password
        if (pId.length > 0)
            productIdforBaVo = pId;

        email = $("#EmailAddress").val();
        password = $("#Password").val();
        $.ajax({
            url: "/RatingsandReviews/Logon",
            type: "POST",
            cache: false,
            data: { EmailAddress: email, Password: password, productId: pId },
            success: function(result) {
                if (result.length > 7 && result.substring(0, 7) == 'Success') {
                    ToggleSignInLink();
                    if (saveUserData) {
                        PostMyServicesData();
                        saveUserData = false;
                    }
                    ShowAddRatings(productIdforBaVo, hsabvId);
                }
                else {
                    $("#SignInContainer").empty();
                    $("#SignInContainer").append(result);
                }
            }
        });
    }
}

function RegisterBazaarVoice(obj1) {
    var pId = '<%=ViewData["ProductIDforBazaarvoice"]%>';
    var hsabvId = '<%=Html.RenderBazaarVoiceDomainString()%>';
    var valid = false;
    if (document.getElementById('hdn').value != "13" && document.getElementById('hdn').value != "valid") {
        obj1.srcElement.value = obj1.srcElement.value + chr(obj1.keyCode);
    }
    if (document.getElementById('hdn').value == "13"
        || (obj1.type == "click"
            && (document.getElementById('hdn').value == "valid"))) {

        valid = true;
    }
    if (valid) {
        var firstName, lastName, email, password, confirmPassword, sendAlert, sendNewsletter
        firstName = $("#FirstName").val();
        lastName = $("#LastName").val();
        email = $("#Email").val();
        regPassword = $("#RegPassword").val();
        confirmPassword = $("#ConfirmPassword").val();
        sendAlert = $('input[name|=bavoSendEmailCheckbox]:checked').val() == 'on' ? true : false;
        sendNewsletter = $('input[name|=bavoSendNewsCheckbox]:checked').val() == 'on' ? true : false;

        if (pId.length > 0)
            productIdforBaVo = pId;

        $.ajax({
            url: "/RatingsandReviews/Register",
            type: "POST",
            cache: false,
            data: { FirstName: firstName, LastName: lastName, Email: email, RegPassword: regPassword, ConfirmPassword: confirmPassword, SendEmailAlerts: sendAlert, SendNewsLetter: sendNewsletter, productId: pId },
            success: function(result) {
                if (result.length > 7 && result.substring(0, 7) == 'Success') {
                    ToggleSignInLink();
                    ShowAddRatings(productIdforBaVo, hsabvId);
                }
                else {
                    $("#RegisterContainer").empty();
                    $("#RegisterContainer").append(result);
                }
            }
        });
    }
}

function ShowAddRatings(pId, hsabvId) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ShowAddRatings(' + pId + ',' + hsabvId + ')');
    //Need to Revert this
    window.open('http://reviews.allconnect.com' + hsabvId + '/3019/' + pId + '/submission.htm?bvauthenticateuser=false&return=', 'ratings', 'toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=yes,width=825,height=690,Left=275,Top=150');

    //For temp only ---	http: //reviews.allconnect.com/3019/productId/submission.htm?submissionurl=http://advisor.allconnect.com/RatingsandReviews/AddRatings&return	
    //window.open('http://reviews.allconnect.com' + hsabvId + '/3019/' + pId + '/submission.htm?submissionurl=http://advisor.allconnect.com/RatingsandReviews/AddRatings&return=', 'ratings', 'toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=yes,width=825,height=690,Left=275,Top=150');
}


function AddtoShoppingCartBundle(eIds, hasPvr, ctProExIds,phones,referrid) {
    if (typeof ClickTaleTag == 'function') ClickTaleTag('Cart Add');
    currentProviderIds = ctProExIds;
    $.ajax({
        url: "/PersistentShoppingCart/AddShoppingCartItemsBundle",
        type: "POST",
        cache: false,
        data: { ExternalIDs: eIds, HasCurrentProvider: hasPvr, CurrentProvidersExternalIDs: ctProExIds },
        success: function(result) {
             
            //LogOmnitureAddBundleToShoppingCart(eIds);
            if (hasPvr == true) {
                ShowCurrentProviderforBundle(ctProExIds);
            }
            else {
                if (result == 'isexist') {
                    WarningShoppingCart();
                }
                ShowItemAddedtoShoppingCart();
                $("div#PersistantShoppingCart").empty();
                $("div#PersistantShoppingCart").append(result);
                RefreshShoppingCartItems();

            }
        }
    });
}



function OpenCurrentProviderModel(eId) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('OpenCurrentProviderModel("' + eId + '")');
    if (eId.length > 0) {
        var cpIds = new Array();
        cpIds = currentProviderIds.split(',');
        var newIds = "";
        for (i = 0; i < cpIds.length; i = i + 1) {
            if (cpIds[i] != eId) {
                newIds = newIds + cpIds[i] + ",";
            }
        }
        newIds = newIds.length > 0 ? newIds.substring(0, newIds.length - 1) : newIds;
        currentProviderIds = newIds;
        if (newIds.length > 1) {
            ShowCurrentProviderforBundle(newIds);
        }
    }
}

function ShowCurrentProviderforBundle(ctProExIds) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ShowCurrentProviderforBundle("' + ctProExIds + '")');
    $.ajax({
        url: "/PersistentShoppingCart/ShowCurrentProviderDialog",
        type: "POST",
        cache: false,
        data: { CurrentProvidersExternalIDs: ctProExIds },
        success: function(result) {
            $("#CurrentProviderShoppingCartContainer").empty();
            $("#CurrentProviderShoppingCartContainer").append(result);
            LogOmnitureModalShow("Provider for Bundle shopping");
            $('#CurrentProviderShoppingCartModal').jqmShow();
        }
    });
}

function CheckandRefresh(eId) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('CheckandRefresh("' + eId + '")');
    if (currentProviderIds.length > 0) {
        OpenCurrentProviderModel(eId);
        $("#CurrentProviderShoppingCartModal").jqmHide();
        if (currentProviderIds.length == 0) {
            $.ajax({
                url: "/PersistentShoppingCart/CheckandRefreshCurrentProvider",
                type: "POST",
                cache: false,
                data: { ExternalID: eId },
                success: function(result) {
                    if (result != 'notrequired' && result != 'isexist' && result.indexOf("##phonerequired##") > -1) {
                        if (result.indexOf("##warning##") > -1) {
                            WarningShoppingCart();
                            result = result.split("##warning##")[1];
                        }
                        result = result.split("##phonerequired##")[1];
                        RefreshShoppingCartItems();
                        PhoneRequiredDialog(result, eId, "", '', "", "", "true");
                    }
                    else if (result == 'isexist') {
                        WarningShoppingCart();
                    }
                    ShowItemAddedtoShoppingCart();
                }

            });

            RefreshShoppingCartItems();
        }
    }
    else {
        $.ajax({
            url: "/PersistentShoppingCart/CheckandRefreshCurrentProvider",
            type: "POST",
            cache: false,
            data: { ExternalID: eId },
            success: function(result) {

                if (result != 'notrequired' && result != 'isexist' && result.indexOf("##phonerequired##") > -1) {
                    if (result.indexOf("##warning##") > -1) {
                        WarningShoppingCart();
                        result = result.split("##warning##")[1];
                    }
                    result = result.split("##phonerequired##")[1];
                    RefreshShoppingCartItems();
                    PhoneRequiredDialog(result, eId, "", '', "", "", "true");
                }
                else if (result == 'isexist') {
                    WarningShoppingCart();
                }
                ShowItemAddedtoShoppingCart();
            }

        });
        RefreshShoppingCartItems();
    }
}



function CheckMissingSelection() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('CheckMissingSelection()');
    var sts = false;
    $('input[name|=externalFeatureOptionsTVChk]:checked').each(function(index) {
        var ddlid = "select#ddl_" + $(this).val();
        //alert($(ddlid).val() +"--"+ $(this).val())
        //alert($(ddlid).val() == $(this).val())

        if ($(ddlid).val() == $(this).val()) {
            $(ddlid).attr("style", "width: 115px; font-size: 11px; background-color:yellow;");
            sts = true;
        }
    });
    return sts;
}

function RequiredMessage() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('RequiredMessage()');
    $("#requiredmessagedialog").dialog({
        resizable: false,
        height: 180,
        width: 450,
        modal: true,
        buttons: {
            'Ok': function() {
                $(this).dialog('close');
            }
        }
    });
}

function AddtoShoppingCartBundleByPlanDetails(eId, hasPvr, bundleType, bundleID, category, isInternet,phones, refID) {
    AddtoShoppingCartBundleByPlanDetails(eId, hasPvr, bundleType, bundleID, category, isInternet, false, null,phones,refID);
}

function AddtoShoppingCartBundleByPlanDetails(eId, hasPvr, bundleType, bundleID, category, isInternet, isPlanDetail, refreshItemId, phones, refID) {
    if (typeof ClickTaleTag == 'function') ClickTaleTag('Cart Add');
    if (category == null) {
        category = "";
    }
    var extFeatureOptIdList;
    var extFeatureIdList;

    if (CheckMissingSelection()) {
        RequiredMessage();
    }
    else {
        if (bundleType == 9 || bundleType == 11 || bundleType == 12) //TVPhoneInternet
        {
            extFeatureOptIdList = GetExternalFeatureOptIDs();
            extFeatureIdList = GetExternalFeatureIDs();
        }
        else if (bundleType == 10) //TVInternet
        {
            extFeatureOptIdList = GetExternalFeatureOptIDs();
        }

        if (hasPvr == true) {
            $.ajax({
                url: "/PersistentShoppingCart/CheckandAddShoppingCartItemsBundleForPlanDetails",
                type: "POST",
                cache: false,
                data: { ExternalID: eId, BundleType: bundleType, ExternalFeatureIds: extFeatureIdList, ExternalFeatureOptIds: extFeatureOptIdList },
                success: function(result) {

                    //					if (result == 'isexist') {
                    //						WarningShoppingCart();
                    //					}
                    //					else {
                    $("#CurrentProviderShoppingCartContainer").empty();
                    $("#CurrentProviderShoppingCartContainer").append(result);
                    LogOmnitureModalShow("Provider Shopping Cart");
                    $('#CurrentProviderShoppingCartModal').jqmShow();
                    LogOmnitureAddToShoppingCart(eId,phones,refID);
                    if (isPlanDetail)
                        RefreshPlanDetail(refreshItemId);
                    //					}
                }
            });
        }
        else {
            $.ajax({
                url: "/PersistentShoppingCart/AddtoShoppingCartBundleByPlanDetails",
                type: "POST",
                cache: false,
                data: { ExternalID: eId, BundleType: bundleType, ExternalFeatureIds: extFeatureIdList, ExternalFeatureOptIds: extFeatureOptIdList },
                success: function(result) {
                    ShowItemAddedtoShoppingCart();
                    if (isInternet == "True") {


                        if (result != 'notrequired' && result != 'isexist' && result.indexOf("##phonerequired##") > -1) {
                            if (result.indexOf("##warning##") > -1) {
                                WarningShoppingCart();
                                result = result.split("##warning##")[1];
                            }
                            result = result.split("##phonerequired##")[1];
                            RefreshShoppingCartItems();
                            PhoneRequiredDialog(result, eId, hasPvr, '', bundleID, extFeatureIdList);
                            document.location = document.location;
                        }
                        else if (result == 'isexist') {
                            WarningShoppingCart();
                            RefreshShoppingCartItems();
                            document.location = document.location;
                        }
                        else {
                            $("div#PersistantShoppingCart").empty();
                            $("div#PersistantShoppingCart").append(result);
                            LogOmnitureAddToShoppingCart(eId, phones, refID);
                             document.location = document.location;
                        }
                    }

                    else if (result == 'isexist') {
                        WarningShoppingCart();
                        RefreshShoppingCartItems(); document.location = document.location;
                    }
                    else {
                        $("div#PersistantShoppingCart").empty();
                        $("div#PersistantShoppingCart").append(result);
                        LogOmnitureAddToShoppingCart(eId, phones, refID);
                        document.location = document.location;
                    }

                    //		            if (result == 'isexist') {
                    //		                WarningShoppingCart();
                    //		                RefreshShoppingCartItems();
                    //		            }
                    //		            else {
                    //		                $("div#PersistantShoppingCart").empty();
                    //		                $("div#PersistantShoppingCart").append(result);
                    //		                LogOmnitureAddToShoppingCart(eId);
                    //		            }
                    if (isPlanDetail)
                        RefreshPlanDetail(refreshItemId);
                }
            });
        }
    }
}
function GetShoppingCartListFromCookies(isRefresh) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('GetShoppingCartListFromCookies()');
    $.ajax({
        url: "/PersistentShoppingCart/GetShoppingCartListFromCookies",
        type: "POST",
        cache: false,

        success: function(result) {
            if (isRefresh) {
                isRefreshCookie = isRefresh;
                RefreshShoppingCartItems();
            }

        }
    });
}

function AddtoShoppingCart(eId, hasPvr, isFeature, bundleID, category, isInternet,phones,refID) {
    if (typeof ClickTaleTag == 'function') ClickTaleTag('Cart Add');
    if (category == null) {
        category = "";
    }
    if (bundleID > 8 && bundleID < 13) {
        if (hasPvr == true) {
            $.ajax({
                url: "/PersistentShoppingCart/CheckandAddShoppingCartItemsBundle",
                type: "POST",
                cache: false,
                data: { ExternalID: eId, BundleID: bundleID },
                success: function(result) {

                    //					if (result == 'isexist') {
                    //						WarningShoppingCart();						
                    //					}
                    //					else {
                    $("#CurrentProviderShoppingCartContainer").empty();
                    $("#CurrentProviderShoppingCartContainer").append(result);
                    LogOmnitureModalShow("Provider Shopping Cart");
                    $('#CurrentProviderShoppingCartModal').jqmShow();
                    LogOmnitureAddToShoppingCart(eId,phones,refID);
                    $('#spAddCart').addClass('enabled');


                    //if (isPlanDetail)
                    // RefreshPlanDetail(refreshItemId);
                    //					}
                }
            });
        }
        else {
            $.ajax({
                url: "/PersistentShoppingCart/AddShoppingCartItemsBundleForRecom",
                type: "POST",
                cache: false,
                data: { ExternalID: eId, BundleID: bundleID },
                success: function(result) {
                    if (isInternet == "True") {

                        $.ajax({
                            url: "/PersistentShoppingCart/IsPhoneRequiredForInternet",
                            type: "POST",
                            cache: false,
                            data: { ExternalID: eId, ExternalFeatureIds: extFeatureIdList },
                            success: function(result) {

                                if (result != 'notrequired') {
                                    PhoneRequiredDialog(result, eId, hasPvr, isFeature, bundleID, extFeatureIdList);
                                }
                                $('#spAddCart').addClass('enabled');
                            }
                        });
                    }

                    ShowItemAddedtoShoppingCart();
                    if (result == 'isexist') {
                        WarningShoppingCart();
                        RefreshShoppingCartItems();
                    }
                    else {
                        $("div#PersistantShoppingCart").empty();
                        $("div#PersistantShoppingCart").append(result);
                        LogOmnitureAddToShoppingCart(eId, phones, refID);
                        
                        $('#spAddCart').addClass('enabled');
                    }

                    //		            if (isPlanDetail)
                    //		                RefreshPlanDetail(refreshItemId);
                }
            });
        }
    }
    else {
        if (isFeature && CheckMissingSelection()) {
            RequiredMessage();
        }
        else {
            var extFeatureIdList;
            if (isFeature) {
                extFeatureIdList = GetExternalFeatureIDs();
            }
            if (hasPvr == true) {
                $.ajax({
                    url: "/PersistentShoppingCart/CheckandAddShoppingCartItems",
                    type: "POST",
                    cache: false,
                    data: { ExternalID: eId, ExternalFeatureIds: extFeatureIdList },
                    success: function(result) {
                        //						if (result == 'isexist') {
                        //							WarningShoppingCart();
                        //						}
                        //						else {
                        $("#CurrentProviderShoppingCartContainer").empty();
                        $("#CurrentProviderShoppingCartContainer").append(result);
                        LogOmnitureModalShow("Provider Shopping Cart");
                        $('#CurrentProviderShoppingCartModal').jqmShow();
                        LogOmnitureAddToShoppingCart(eId, phones, refID);
                      
                        $('#spAddCart').addClass('enabled');

                        //if (isPlanDetail)
                        //  RefreshPlanDetail(refreshItemId);
                        //						}
                    }
                });
            }
            else {
                $.ajax({
                    url: "/PersistentShoppingCart/AddShoppingCartItems",
                    type: "POST",
                    cache: false,
                    data: { ExternalID: eId, ExternalFeatureIds: extFeatureIdList },
                    success: function(result) {

                        if (category.indexOf('Internet') > -1) {

                            $.ajax({
                                url: "/PersistentShoppingCart/IsPhoneRequiredForInternet",
                                type: "POST",
                                cache: false,
                                data: { ExternalID: eId, ExternalFeatureIds: extFeatureIdList },


                                success: function(result) {
                                    if (result != 'notrequired') {
                                        PhoneRequiredDialog(result, eId, hasPvr, isFeature, bundleID, extFeatureIdList);
                                    }
                                    $('#spAddCart').addClass('enabled');

                                }
                            });
                        }
                        ShowItemAddedtoShoppingCart();

                        if (result == 'isexist') {

                            WarningShoppingCart();
                            RefreshShoppingCartItems();

                        }
                        else {
                            $("div#PersistantShoppingCart").empty();
                            $("div#PersistantShoppingCart").append(result);
                            LogOmnitureAddToShoppingCart(eId, phones, refID);
                            
                            $('#spAddCart').addClass('enabled');
                        }

                        //			            if (isPlanDetail)
                        //			                RefreshPlanDetail(refreshItemId);
                    }
                });

            }
        }
    }
}

function AddtoShoppingCartByPlanDetails(eId, hasPvr, serviceType, bundleID, category, isInternet,phones,refID) {
    AddtoShoppingCartByPlanDetails(eId, hasPvr, serviceType, bundleID, category, isInternet, false, null,phones,refID);
}

function AddtoShoppingCartByPlanDetails(eId, hasPvr, serviceType, bundleID, category, isInternet, isPlanDetail, refreshItemId,phones,refID) {
    if (typeof ClickTaleTag == 'function') ClickTaleTag('Cart Add');
    // alert(window.location.href);
    if (category == null) {
        category = "";
    }
    if (CheckMissingSelection()) {
        RequiredMessage();
    }
    else {
        var extFeatureIdList;

        if (serviceType == 1)
            extFeatureIdList = GetExternalFeatureOptIDs();
        else if (serviceType == 2)
            extFeatureIdList = GetExternalFeatureOptIDs();
        else
            extFeatureIdList = GetExternalFeatureIDs();


        if (hasPvr == true) {
            $.ajax({
                url: "/PersistentShoppingCart/CheckandAddShoppingCartItemsForPlanDetails",
                type: "POST",
                cache: false,
                data: { ExternalID: eId, ServiceID: serviceType, ExternalFeatureIds: extFeatureIdList },
                success: function(result) {

                    //					if (result == 'isexist') {
                    //						WarningShoppingCart();
                    //					}
                    //					else {
                    $("#CurrentProviderShoppingCartContainer").empty();
                    $("#CurrentProviderShoppingCartContainer").append(result);
                    LogOmnitureModalShow("Provider Shopping Cart");
                    $('#CurrentProviderShoppingCartModal').jqmShow();
                    LogOmnitureAddToShoppingCart(eId, phones, refID);

                    if (isPlanDetail) {
                        //RefreshPlanDetail(refreshItemId);
                    }
                    //					}
                }
            });
        }
        else {
            $.ajax({
                url: "/PersistentShoppingCart/AddtoShoppingCartByPlanDetails",
                type: "POST",
                cache: false,
                data: { ExternalID: eId, ServiceID: serviceType, ExternalFeatureIds: extFeatureIdList },
                success: function(result) {

                    ShowItemAddedtoShoppingCart();
                    if (category.indexOf('Internet') > -1) {
                        if (result != 'notrequired' && result != 'isexist' && result.indexOf("##phonerequired##") > -1) {
                            if (result.indexOf("##warning##") > -1) {
                                WarningShoppingCart();
                                result = result.split("##warning##")[1];
                            }
                            result = result.split("##phonerequired##")[1];
                            RefreshShoppingCartItems();
                            PhoneRequiredDialog(result, eId, hasPvr, '', bundleID, extFeatureIdList, "true");
                        }
                        else if (result == 'isexist') {
                            WarningShoppingCart();
                            RefreshShoppingCartItems();
                            document.location = document.location;
                        }
                        else {
                            $("div#PersistantShoppingCart").empty();
                            $("div#PersistantShoppingCart").append(result);
                            LogOmnitureAddToShoppingCart(eId, phones, refID);

                            document.location = document.location;
                        }
                    }

                    else if (result == 'isexist') {
                        WarningShoppingCart();
                        RefreshShoppingCartItems();
                        document.location = document.location;
                    }
                    else {
                        $("div#PersistantShoppingCart").empty();
                        $("div#PersistantShoppingCart").append(result);
                        LogOmnitureAddToShoppingCart(eId, phones, refID);

                        document.location = document.location;
                    }

                    if (isPlanDetail) {
                        //RefreshPlanDetail(refreshItemId);
                    }
                }
            });
        }
    }
}

function GetExternalFeatureOptIDs() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('GetExternalFeatureOptIDs()');
    var extFeatureIdList = [];
    //Get List of external feature ids that are checked.
    $('input[name|=externalFeatureOptionsTVChk]:checked').each(function(index) {
        //alert($(this).val());
        var ctl = "ddl_" + $(this).val();
        //ctl = ctl.before("ddl_");
        if ($("#" + ctl + " option:selected").text() != "Choose an option") {
            //alert($("#" + ctl + " option:selected").text());
            extFeatureIdList[extFeatureIdList.length] = "[{\"" + this.value + "\":\"" + $("#" + ctl + " option:selected").val() + "\"}]";
        }
    });

    return extFeatureIdList;
}

var isRedirect;
function AddtoShoppingCartFromCompare(eId, hasPvr, isFeature, redirectURL, bundleID, category, isInternet,phones,refID) {
    if (typeof ClickTaleTag == 'function') ClickTaleTag('Cart Add');
    if (category == null) {
        category = "";
    }
    if (bundleID > 8 && bundleID < 13) {
        if (hasPvr == true) {
            $.ajax({
                url: "/PersistentShoppingCart/CheckandAddShoppingCartItemsBundle",
                type: "POST",
                cache: false,
                data: { ExternalID: eId, BundleID: bundleID },
                success: function(result) {
                    //					if (result == 'isexist') {
                    //						WarningShoppingCart();
                    //					}
                    //					else {
                    $("#CurrentProviderShoppingCartContainer").empty();
                    $("#CurrentProviderShoppingCartContainer").append(result);
                    LogOmnitureModalShow("Provider Shopping Cart");
                    $('#CurrentProviderShoppingCartModal').jqmShow();
                    LogOmnitureAddToShoppingCart(eId, phones, refID);

                    //					}
                }
            });
        }
        else {
            $.ajax({
                url: "/PersistentShoppingCart/AddShoppingCartItemsBundleForRecom",
                type: "POST",
                cache: false,
                data: { ExternalID: eId, BundleID: bundleID },
                success: function(result) {

                    ShowItemAddedtoShoppingCart();
                    if (isInternet == "True") {


                        if (result != 'notrequired' && result != 'isexist' && result.indexOf("##phonerequired##") > -1) {
                            if (result.indexOf("##warning##") > -1) {
                                WarningShoppingCart();
                                result = result.split("##warning##")[1];
                            }
                            result = result.split("##phonerequired##")[1];
                            RefreshShoppingCartItems();
                            PhoneRequiredDialog(result, eId, hasPvr, '', bundleID, "");
                            result = "phonerequired";

                        }
                        else if (result == 'isexist') {
                            //  document.location = document.location;
                            WarningShoppingCart();
                            RefreshShoppingCartItems();

                        }
                        else {
                            $("div#PersistantShoppingCart").empty();
                            $("div#PersistantShoppingCart").append(result);
                            LogOmnitureAddToShoppingCart(eId, phones, refID);

                            //document.location.href = redirectURL;
                        }
                    }

                    else if (result == 'isexist') {
                        //document.location = document.location;
                        WarningShoppingCart();
                        //RefreshShoppingCartItems();

                    }
                    else {
                        $("div#PersistantShoppingCart").empty();
                        $("div#PersistantShoppingCart").append(result);
                        LogOmnitureAddToShoppingCart(eId, phones, refID);

                        // document.location.href = redirectURL;
                    }
                    if (result == "isexist" || result == "phonerequired") {
                        $('form').submit(function() { return false; });

                    }

                    else {
                        document.location.href = redirectURL;
                    }
                }



            });
        }
    }
    else {
        if (hasPvr == true) {
            $.ajax({
                url: "/PersistentShoppingCart/CheckandAddShoppingCartItems",
                type: "POST",
                cache: false,
                data: { ExternalID: eId, ExternalFeatureIds: extFeatureIdList },
                success: function(result) {
                    //					if (result == 'isexist') {
                    //						WarningShoppingCart();
                    //					}
                    //					else {
                    $("#CurrentProviderShoppingCartContainer").empty();
                    $("#CurrentProviderShoppingCartContainer").append(result);
                    LogOmnitureModalShow("Provider Shopping Cart");
                    $('#CurrentProviderShoppingCartModal').jqmShow();
                    LogOmnitureAddToShoppingCart(eId, phones, refID);

                    //					}
                }
            });
        }
        else {
            var extFeatureIdList;
            if (isFeature) {
                extFeatureIdList = GetExternalFeatureIDs();
            }

            $.ajax({
                url: "/PersistentShoppingCart/AddShoppingCartItems",
                type: "POST",
                cache: false,
                data: { ExternalID: eId, ExternalFeatureIds: extFeatureIdList },
                success: function(result) {

                    if (category.indexOf('Internet') > -1) {

                        $.ajax({
                            url: "/PersistentShoppingCart/IsPhoneRequiredForInternet",
                            type: "POST",
                            cache: false,
                            data: { ExternalID: eId, ExternalFeatureIds: extFeatureIdList },
                            success: function(result) {
                                if (result != 'notrequired') {
                                    PhoneRequiredDialog(result, eId, hasPvr, isFeature, bundleID, extFeatureIdList);
                                }
                                RefreshShoppingCartItems();
                                if (isRedirect == "isexist") {
                                    // document.location = document.location;
                                    $('form').submit(function() { return false; });
                                }
                                else if (result == 'notrequired') {
                                    document.location.href = redirectURL;
                                }
                            }
                        });
                    }
                    ShowItemAddedtoShoppingCart();
                    if (result == 'isexist') {
                        WarningShoppingCart();
                        RefreshShoppingCartItems(); //document.location = document.location;
                    }
                    else {
                        $("div#PersistantShoppingCart").empty();
                        $("div#PersistantShoppingCart").append(result);
                        LogOmnitureAddToShoppingCart(eId, phones, refID);

                        // document.location.href = redirectURL;
                    }
                    isRedirect = result;
                    if (isRedirect == "isexist" && category.indexOf("Internet") == -1) {
                        // document.location = document.location;
                        $('form').submit(function() { return false; });
                    }
                    else if (category.indexOf("Internet") == -1) {
                        document.location.href = redirectURL;
                    }
                }
            });
        }
    }
}

function GetExternalFeatureIDs() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('GetExternalFeaturedIDs()');
    var extFeatureIdList = [];
    //Get List of external feature ids that are checked.
    $('input[name|=externalFeatureOptions]:checked').each(function(index) {
        extFeatureIdList[extFeatureIdList.length] = this.value;
    });
    return extFeatureIdList;
}

function RemoveItem(eId, prName, isPhone) {
    $.ajax({
        url: "/PersistentShoppingCart/RemoveShoppingCartItems",
        type: "POST",
        cache: false,
        data: { ExternalID: eId },
        success: function(result) {
            if (isPhone) {
                GoToPhone("Phone", prName);
            } //alert(result);
            //if (result == "isUpdate") {

            //RefreshShoppingCartItems();
            //}
            //else {
            $("div#PersistantShoppingCart").empty();
            $("div#PersistantShoppingCart").append(result);
            //}
            //LogOmnitureRemoveFromShoppingCart(eId);
        }
    });
}

function RemoveCurrentProviderItems(provId, eId) {
    $.ajax({
        url: "/PersistentShoppingCart/RemoveCurrenProviderShoppingCartItems",
        type: "POST",
        cache: false,
        data: { ProviderID: provId },
        success: function(result) {
            $("div#PersistantShoppingCart").empty();
            $("div#PersistantShoppingCart").append(result);
            $("#CurrentProviderShoppingCartModal").jqmHide();
            OpenCurrentProviderModel(eId);
            //LogOmnitureRemoveFromShoppingCart(eId);
        }
    });
}

function RemoveandRedirect(eId) {
    $.ajax({
        url: "/PersistentShoppingCart/RemoveShoppingCartItems",
        type: "POST",
        cache: false,
        data: { ExternalID: eId },
        success: function(result) {
            //LogOmnitureRemoveFromShoppingCart(eId);
            window.location.href = '/';
        }
    });
}
function ShowItemAddedtoShoppingCart() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ShowItemAddedtoShoppingCart()');
    CartFadeEffect();

}
function RefreshShoppingCartItems(isBackButton) {
    if (isBackButton == undefined || isBackButton == null) {
        isBackButton = "";
    }
    if (typeof ClickTaleExec == 'function') ClickTaleExec('RefreshShoppingCartItems("' + isBackButton + '")');
    $.ajax({
        url: "/PersistentShoppingCart/RefreshShoppingCartItems",
        type: "POST",
        cache: false,
        data: { IsBackButton: isBackButton },
        success: function(result) {
            if (isRefreshCookie) {
                ShowItemAddedtoShoppingCart();
                isRefreshCookie = false;
            }
            $("div#PersistantShoppingCart").empty();
            $("div#PersistantShoppingCart").append(result);
            $("#CurrentProviderShoppingCartModal").jqmHide();
        }
    });
}

function RefreshPlanDetail(id) {
    $.ajax({
        url: "/PlanDetail/RefreshPlanDetail/" + id,
        type: "GET",
        cache: false,
        success: function(result) {
            $("div.main").empty();
            $("div.main").append(result);
        }
    });
}

function FadeInDiv(a) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('FadeInDiv("' + a + '")');
    ChangeBackColorForFadeEffect(a);
    timeoutIdForFadeEffect = setTimeout('FadeInDiv1("#FFFF99")', 3000);

}
function FadeInDiv1(a) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('FadeInDiv("' + a + '")');
    ChangeBackColorForFadeEffect(a);
    timeoutIdForFadeEffect = setTimeout('FadeInDiv2("#FFFFCC")', 3000);


}
function FadeInDiv2(a) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('FadeInDiv2("' + a + '")');
    ChangeBackColorForFadeEffect(a);
    timeoutIdForFadeEffect = setTimeout('FadeInDiv3()', 3000);


}
function FadeInDiv3() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('FadeInDiv3()');
    $("#divFade").css("background-color", "transparent");
    $("#divFade").removeClass("divFade");
}
function ChangeBackColorForFadeEffect(a) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ChangeBackColorForFadeEffect("' + a + '")');
    $("#divFade").css("background-color", a);
    $("#divFade").css("height", "0px");
}
function CartFadeEffect() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('CartFadeEffect()');
    if ($("div#PersistantShoppingCart").html().indexOf("Your cart is currently empty") > -1) {
        $("#divFade").css("height", $("div#PersistantShoppingCart").attr("offsetHeight") + 380);
    }
    else {
        $("#divFade").css("height", $("div#PersistantShoppingCart").attr("offsetHeight") + 150);
    }
    $("#divFade").css("background-color", "yellow");

    $("#divFade").addClass("divFade");

    timeoutIdForFadeEffect = setTimeout('FadeInDiv("#FFFF66")', 1000);

}
function GoToPhone(serviceType, pName) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('GoToPhone("' + serviceType + '", "' + pName + '")');
    //Current Provider
    serviceType = "Phone"
    var noCurrentService = $("#noServiceCheckbox").attr('checked');
    var providerName = pName;

    //MonthlyBill
    var billAmount = 0;
    //Current Contract
    var contractInfo = "Unspecified";

    //Bundle Stuff
    var isBundle = false;
    var bundleType = "";


    var creditScore = 0;

    var featuresIncludedRadio = $("input[name='CurrentServiceHasAllFeatures']:checked");
    var featuresIncluded = "No";
    if (featuresIncludedRadio && $(featuresIncludedRadio).val() == 'True') {
        featuresIncluded = "Yes";
    }

    s.events = "event39";
    s.prop23 = providerName;
    s.eVar33 = providerName;
    s.prop24 = billAmount;
    s.eVar34 = billAmount;
    s.prop25 = contractInfo;
    s.eVar35 = contractInfo;
    s.prop26 = bundleType;
    s.eVar37 = bundleType;
    s.prop27 = creditScore;
    s.eVar17 = creditScore;
    s.prop29 = featuresIncluded;
    s.eVar19 = featuresIncluded;

    var featureData = "";
    var featuresIncluded = "";


    //Phone
    if (serviceType == 'Phone') {
        var longDistance = $("input[name='LongDistanceMinutesOption']:checked");
        if (longDistance) {
            if ($(longDistance).attr("omniture") != null) {
                if (featureData.length > 0) {
                    featureData += ","
                }
                featureData += $(longDistance).attr("omniture");
            }
        }
        var phoneFeatures = $("input[name='ServiceOptions']:checked");
        if (phoneFeatures) {
            $(phoneFeatures).each(function(index) {
                if ($(this).attr("omniture") != null) {
                    if (featureData.length > 0) {
                        featureData += ","
                    }
                    featureData += $(this).attr("omniture");
                }
            });
        }
    }

    

   
   

    window.location = "/Recommendations/Phone";

}
function PhoneRequiredDialog(names, eId, hasPvr, isFeature, bundleID, extFeatureIdList) {
    var arr = names.split("^");
    // var str = '';
    $("#phoneplanrequireddialog").attr("title", arr[0] + " Phone Plan Required"); //= $("#phoneplanrequireddialog").innerHTML.
    $("#phoneplanrequireddialog").html('<P><div style="MARGIN: 0px 7px 20px 0px; FLOAT: left;width:5%"><SPAN  class="ui-icon ui-icon-alert"></SPAN></div><div style="text-align:justify;float:right;width:93%"><B>Important: </B>'
    + 'You must also add a phone plan from ' + arr[0] + ' in order to purchase the service you requested ' + arr[1] + '<BR/><br/>'
    + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a style="color:blue;text-decoration:underline;" href="#" id="impAA" >See ' + arr[0]
    + ' Phone Plan Recommendations</a></div> </P>');
    $('#impAA').click(function() {
        $(this).dialog('close');
        GoToPhone("Phone", arr[0]);
    });
    $("#phoneplanrequireddialog").dialog({
        resizable: false,
        height: 240,
        width: 450,
        modal: true
    });

    var closeSpan = $("div[role='dialog'] span.ui-icon-closethick");
    if ($("#addspanClose") != null) {
        if ($("#addspanClose").text() == "") {
            closeSpan.parent().before(
                            '<span id="addspanClose" style="float:right;margin-right:10px">Close</span>');
        }
    }
    else {
        closeSpan.parent().before(
                            '<span id="addspanClose" style="float:right;margin-right:10px">Close</span>');
    }



}

function RemoveFromShoppingCart(eId, category, prId, prName, plName) {
    if (typeof ClickTaleTag == 'function') ClickTaleTag('Cart Remove');
    if (prName.indexOf("^") > -1) {
        prName = prName.split("^")[0] + "'" + prName.split("^")[1].substr(1, prName.split("^")[1].length);
    }
    if (plName.indexOf("^") > -1) {
        plName = plName.split("^")[0] + "'" + plName.split("^")[1].substr(0, plName.split("^")[1].length);
    }
    $("#mycartlist").hide();
    if (category.indexOf("Phone") > -1) {

        $.ajax({
            url: "/PersistentShoppingCart/VerifyItemToBeRemoved",
            type: "POST",
            cache: false,
            data: { ProviderId: prId },
            success: function(result) {
                if (result == "isexist") {
                    $("#removephoneplanrequireddialog").attr("title", prName + " Phone Plan Required");
                    $("#removephoneplanrequireddialog").html('<p> <div style="MARGIN: 0px 7px 20px 0px; FLOAT: left;width:5%"><SPAN  class="ui-icon ui-icon-alert"></SPAN></div><div style="text-align:justify;float:right;width:93%">' +
                    '<b>Important: </b>In order to purchase the ' + plName + ' service you requested, ' + prName + ' requires that you also purchase a phone plan.' +
                    ' To remove this phone plan and view others, choose See ' + prName + ' phone plan recommendations link, or Close to keep the existing phone plan in your cart.<br />' +
                    '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="#" style="color:blue;text-decoration:underline;" id="aaRemove">See ' + prName + ' Phone Plan Recommendations</a> </div> </p>');
                    $('#aaRemove').click(function() {

                        $(this).dialog('close');
                        RemoveItem(eId, prName, true);
                    });
                    $("#removephoneplanrequireddialog").dialog({
                        resizable: false,
                        height: 240,
                        width: 400,
                        modal: true

                    });
                    var closeSpan = $("div[role='dialog'] span.ui-icon-closethick");
                    if ($("#spanClose") != null) {
                        if ($("#spanClose").text() == "") {
                            closeSpan.parent().before(
                            '<span id="spanClose" style="float:right;margin-right:10px">Close</span>');
                        }
                    }
                    else {
                        spanClose.parent().before(
                            '<span id="spanClose" style="float:right;margin-right:10px">Close</span>');
                    }
                }
                else {



                    $("#confirmdialog").dialog({
                        resizable: false,
                        height: 170,
                        width: 400,
                        modal: true,
                        buttons: {
                            'Yes': function() {
                                $(this).dialog('close');
                                clearTimeout(timeoutIdForFadeEffect);
                                FadeInDiv3();
                                RemoveItem(eId);


                            },
                            'No': function() {
                                $(this).dialog('close');
                            }
                        }
                    });
                }
            }
        });



    }
    else {
        $("#confirmdialog").dialog({
            resizable: false,
            height: 170,
            width: 400,
            modal: true,
            buttons: {
                'Yes': function() {
                    $(this).dialog('close');
                    clearTimeout(timeoutIdForFadeEffect);
                    FadeInDiv3();
                    RemoveItem(eId);


                },
                'No': function() {
                    $(this).dialog('close');
                }
            }
        });

    }

}

function WarningShoppingCart() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('WarningShoppingCart()');
    $("#warningdialog").dialog({
        resizable: false,
        height: 200,
        width: 560,
        modal: true,
        buttons: {
            'Ok': function() {
                $(this).dialog('close');
            }
        }
    });
}

function Checkout(phones,refID) {
    LogOmnitureCheckoutShoppingCart(cartItems, phones, refID);
    $("#mycartlist").hide();
    if (typeof ClickTaleExec == 'function') ClickTaleExec('Checkout()');
    if (typeof ClickTaleTag == 'function') ClickTaleTag('Checkout');
    $("#ShoppingCartLoadingModal").empty();
    $("#ShoppingCartLoadingModal").append("<div class='top'></div><div class='modaltext'><div class='modal_whitebox'><div class='inter-om-sl'><p>Redirecting to checkout process</p></div></div></div><div class='bottom'></div>");
    LogOmnitureModalShow("Provider Shopping Cart");
    $("#ShoppingCartLoadingModal").jqmShow();
    $.ajax({
        url: "/PersistentShoppingCart/Checkout",
        type: "POST",
        cache: false,
        data: {},
        success: function(result) {
            
            if (result != "No URL") {
                var sessionPos = result.indexOf("&sessionID=");
                var sessionID = "";
                if (sessionPos > 0 && result.length > sessionPos + 11) {
                    sessionID = result.substring(sessionPos + 11);
                    result = result.substring(0, sessionPos);


                }
                var url = result;
                //alert(url);
                //same window
                document.location.href = url;
                //popup
                //window.open(url, 'checkout', 'toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=yes,width=925,height=590,Left=175,Top=150');
            }
        }
    });
}

function ShowCurrentProviderDialog() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('ShowCurrentProviderDialog()');
    LogOmnitureModalShow("Provider Shopping Cart");
    $('#CurrentProviderShoppingCartModal').jqmShow();
}

function CloseCurrentProviderModel(eId) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('CloseCurrentProviderModel("' + eId + '")');
    $("#CurrentProviderShoppingCartModal").jqmHide();
    RemoveItem(eId)
    OpenCurrentProviderModel(eId);
}

//BEGIN Individual Electrical Item Savings Calculator functions
function UpdatePartialCalcsForIndividualElectricalItem(id) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('UpdatePartialCalcsForIndividualElectricalItem("' + id + '")');
    var item = $("#" + id).find("#HoursUsedPerDay");
    var userGuid = $("#UserId").val();
    var elecrate = $("#ElectricityRate").val();
    var hours = parseInt(item.val());
    if (!isNaN(hours) && hours >= 0 && hours <= 24) {
        $("#validation_summary_custom").html("");
        $("#" + id).find("#val_HoursUsedPerDay").html("");
        var updatedInDb = CalcIndividualElectricalItemCosts(userGuid, elecrate, id, hours);
        if (updatedInDb == false) {
            //have to run JS calc
            UpdateTotalCalcsForIndividualElectricalItems();
        }
    }
    else {
        $("#validation_summary_custom").html("Please enter a valid number between 0 and 24");
        $("#" + id).find("#val_HoursUsedPerDay").html("*");
        item.val("0");
        item.focus().focus();   //IE7 workaround
    }
}
function CalcIndividualElectricalItemCosts(userGuid, elecrate, id, hours) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('CalcIndividualElectricalItemCosts("' + userGuid + '", "' + elecrate + '", "' + id + '", "' + hours + '")');
    var updatedInDb = false;    //assume false

    $.getJSON(
                "/HESCalculators/CalcIndividualElectricalItemCosts",
                { UserId: userGuid, ElectricityRate: elecrate, ItemId: id, HoursUsedPerDay: hours },
                function(result) {
                    var cac = $("#" + id).find("#CurrentAnnualCost");
                    cac.html(result.CurrentAnnualCost);
                    var eac = $("#" + id).find("#EnergyEfficientAnnualCost");
                    eac.html(result.EnergyEfficientAnnualCost);
                    var acs = $("#" + id).find("#AnnualCostSavings");
                    acs.html(result.AnnualCostSavings);
                    var err = $("#iei_ErrorMessage");
                    err.val(result.ErrorMessage);
                    //if user is logged in we can run calcs from db
                    if (userGuid != '00000000-0000-0000-0000-000000000000') {
                        updatedInDb = true;
                    }
                    if (updatedInDb == true) {
                        //update calcs with values from db (more accurate)
                        var totalCac = $("#iei_potentialsavings").find("#CurrentAnnualCost");
                        var totalEac = $("#iei_potentialsavings").find("#EnergyEfficientAnnualCost");
                        var totalAcs = $("#iei_potentialsavings").find("#AnnualCostSavings");
                        var totalAcsBox = $("#iei_savingsbox").find("#AnnualCostSavings");
                        var totalAcsText = $("#iei_savings_text").find("#AnnualCostSavings");
                        totalCac.html(result.TotalCurrentAnnualCost);
                        totalEac.html(result.TotalEnergyEfficientAnnualCost);
                        totalAcs.html(result.TotalAnnualCostSavings);
                        totalAcsBox.html(result.TotalAnnualCostSavings);
                        totalAcsText.html(result.TotalAnnualCostSavings);
                    }
                }
            );
    return updatedInDb;
}
function UpdateTotalCalcsForIndividualElectricalItems() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('UpdateTotalCalcsForIndividualElectricalItems()');
    var lastItem = parseInt($("#iei_TotalItems").val());
    var userGuid = $("#UserId").val();
    var elecrate = $("#ElectricityRate").val();
    var result = new Array();
    for (i = 1; i <= lastItem; i = i + 1) {
        var id = i;
        var hours = parseInt($("#" + i).find("#HoursUsedPerDay").val());
        var row = { UserId: userGuid, ElectricityRate: elecrate, ItemId: id, HoursUsedPerDay: hours }
        result.push(row);
    }
    var rows = result;
    $.ajax({
        url: "/HESCalculators/IndividualElectricalItemPotentialSavings",
        type: "POST",
        cache: false,
        data: $.postify(rows),
        dataType: "json",
        success: function(result) {
            var err = $("#iei_ErrorMessage");
            err.val(result.ErrorMessage);
            var totalCac = $("#iei_potentialsavings").find("#CurrentAnnualCost");
            var totalEac = $("#iei_potentialsavings").find("#EnergyEfficientAnnualCost");
            var totalAcs = $("#iei_potentialsavings").find("#AnnualCostSavings");
            var totalAcsBox = $("#iei_savingsbox").find("#AnnualCostSavings");
            var totalAcsText = $("#iei_savings_text").find("#AnnualCostSavings");
            totalCac.html(result.CurrentAnnualCost);
            totalEac.html(result.EnergyEfficientAnnualCost);
            totalAcs.html(result.AnnualCostSavings);
            totalAcsBox.html(result.AnnualCostSavings);
            totalAcsText.html(result.AnnualCostSavings);
        },
        error: function(result, msg, exception) {
            var err = $("#iei_ErrorMessage");
            err.val(msg + ': ' + exception);
        }
    }
    );
}
//WG: This function converts an array of objects into a json object that can be posted.
$.postify = function(value) {
    var result = {};
    var buildResult = function(object, prefix) {
        for (var key in object) {
            var postKey = isFinite(key) ? (prefix != "" ? prefix : "") + "[" + key + "]" : (prefix != "" ? prefix + "." : "") + key;
            switch (typeof (object[key])) {
                case "number": case "string": case "boolean":
                    result[postKey] = object[key];
                    break;
                case "object":
                    if (object[key].toUTCString)
                        result[postKey] = object[key].toUTCString().replace("UTC", "GMT");
                    else {
                        buildResult(object[key], postKey != "" ? postKey : key);
                    }
            }
        }
    };
    buildResult(value, "");
    return result;
};
function InitializeIndElecItemSlider(sliderID, className, parentTargetID, targetID, initialValue) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('InitializeIndElecItemSlider("' + sliderID + '", "' + className + '", "' + parentTargetID + '", "' + targetID + '", ' + initialValue + ')');
    var maxValue = 24;
    var stepValue = 4;
    var sliderItem = $("#" + parentTargetID).find("#sliderdiv").find(sliderID);
    sliderItem.slider({
        value: initialValue,
        from: 0,
        to: maxValue,
        step: stepValue,
        limits: false,
        onstatechange: function(value) {
            $("#" + parentTargetID).find(targetID).val(value);
            //$(parentTargetID).find(targetID).blur();
            UpdatePartialCalcsForIndividualElectricalItem(parentTargetID);
        }

    });
    //$(parentTargetID).find(sliderID).removeClass('ui-widget-content').addClass(className);
    //$(parentTargetID).find(sliderID + " a").removeClass('ui-state-focus').removeClass('ui-corner-all').removeClass('ui-state-hover').removeClass('ui-state-hover').removeClass('ui-state-default');
    //$(parentTargetID).find(sliderID + " a").addClass('ui-slider-handle-default').addClass('ui-slider-state-hover').addClass('ui-slider-state-focus');

    setFilterNonIntegerKeys("#" + parentTargetID, targetID);
    var sliderTxt = $("#" + parentTargetID).find(targetID);
    sliderTxt.blur(function() {
        if (parseInt(sliderTxt.val()) > parseInt(maxValue)) {
            sliderTxt.val(maxValue);
        }
        if (parseInt(sliderTxt.val()) > parseInt(maxValue)) {
            sliderItem.slider("to", sliderTxt.val());
            sliderItem.slider("value", sliderTxt.val());
        }
        else {
            sliderItem.slider("value", parseFloat(sliderTxt.val()));
        }
    });
}
//END Individual Electrical Item Savings Calculator functions
//BEGIN Donations Calculator functions
function UpdatePartialCalcsForDonations(id) {
    //alert(id);
    if (typeof ClickTaleExec == 'function') ClickTaleExec('UpdatePartialCalcsForDonations("' + id + '")');
    var qty = $("#" + id).find("#Quantity").val();
    var cond = $("#" + id).find("#Condition").val();
    //alert(qty + ' ' + cond);
    var val = parseFloat(qty) * parseFloat(cond);
    //alert(val);
    $("#" + id).find("#Value").html(formatCurrency(val));
}
function SubmitDonations() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SubmitDonations()');
    var lastItem = parseInt($("#donations_TotalItems").val());
    var tax = $("#TaxRate");

    var result = new Array();
    for (i = 1; i <= lastItem; i = i + 1) {
        var id = $("#" + i).find("#ItemId").val(); ;
        var qty = $("#" + i).find("#Quantity").val();
        var cond = $("#" + i).find("#Condition").val();
        var taxRate = 0;
        if (tax != null) {
            taxRate = tax.val();
        }
        var row = { ItemNumber: i, ItemId: id, Quantity: qty, Condition: cond, TaxRate: taxRate }
        result.push(row);
    }
    var rows = result;
    $.ajax({
        url: "/HESCalculators/Donations",
        type: "POST",
        cache: false,
        data: $.postify(rows),
        success: function(result) {
            $("#CalculatorModal").empty();
            $("#CalculatorModal").append(result);
            LogOmnitureModalShow("Calculator Modal");
            $('#CalculatorModal').jqmShow();
        },
        error: function(result, msg, exception) {
            var err = $("#donations_ErrorMessage");
            err.val(msg + ': ' + exception);
        }
    }
    );
}
//END Donations Savings Calculator functions
//BEGIN Years To Pay Back Recalc
function RecalcYearsToPayBack() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('RecalcYearsToPayBack()');
    var costOfUpgrade = $("#txtUpgradeCost").val();
    var estimatedSavings = $("#EstimatedSavingsValue").val();
    var serviceAreaId = $("#ServiceAreaId").val();
    $.ajax({
        url: "/HESCalculators/ReCalcYearsToPayBack",
        type: "POST",
        cache: false,
        data: { CostOfUpgrades: costOfUpgrade, EstimatedSavings: estimatedSavings, ServiceAreaId: serviceAreaId },
        success: function(result) {
            $("#YearsToPayback").html(result.YearsToPayBack);
            //reformat user input as currency
            $("#txtUpgradeCost").val(result.CostOfUpgrades);
        },
        error: function(result, msg, exception) {
            var err = $("#donations_ErrorMessage");
            err.val(msg + ': ' + exception);
        }
    });
}
//END Years To Pay Back Recalc
function RefeshUtility(serviceType) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('RefreshUtility("' + serviceType + '")');
    $.ajax({
        url: "/Recommendations/" + serviceType,
        type: "POST",
        cache: false,
        data: {},
        success: function(result) {
        }
    });
}

function SetMyCurrentProvider(provId, sId, prdId) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('SetMyCurrentProvider("' + provId + '", "' + sId + '", "' + prdId + '")');
    $.ajax({
        url: "/Recommendations/SetMyCurrentProvider",
        type: "POST",
        cache: false,
        data: { ProviderID: provId, ServiceId: sId, ProductID: prdId },
        success: function(result) {
            $("#divMakeMyctProvider").toggle();
            $("#divMakeMyctProviderAddRatings").toggle();
        }
    });
}
function UpdateElectricRate(city, rateBox) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('UpdateElectricRate("' + city + '", "' + rateBox + '")');
    var cityId = $(city).val();
    $.getJSON(
                "/HESCalculators/GetElectricRate",
                { cityId: cityId },
                function(result) {
                    $(rateBox).val(result);
                });
}
function UpdateNaturalGasRate(city, rateBox) {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('UpdateNaturalGasRate("' + city + '", "' + rateBox + '")');
    var cityId = $(city).val();
    $.getJSON(
                "/HESCalculators/GetNaturalGasRate",
                { cityId: cityId },
                function(result) {
                    $(rateBox).val(result);
                });
}

function KioskOrderNow() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('KioskOrderNow()');
    if (typeof ClickTaleTag == 'function') ClickTaleTag('Checkout');
    $.ajax({
        url: "/PersistentShoppingCart/KioskOrderNow",
        type: "GET",
        cache: true,
        data: {},
        success: function(result) {
            $("#ShoppingCartLoadingModal").html(result);
            LogOmnitureModalShow("Shopping Cart Loading");
            $('#ShoppingCartLoadingModal').jqmShow();
        }
    });
}
function KioskCancelClose() {
    if (typeof ClickTaleExec == 'function') ClickTaleExec('KioskCancelClose()');
    $("#ShoppingCartLoadingModal").empty();
    $('#ShoppingCartLoadingModal').jqmHide();
}

function SendEmailPlanShare(frm) {
    $.ajax({
        type: "POST",
        data: { "FromName": $("#divShare #FromName").val(),
            "Email": $("#divShare #Email").val(),
            "FriendsEmail": $("#divShare #FriendsEmail").val(),
            "Subject": $("#divShare #Subject").val(),
            "Body": $("#divShare #Body").val()
        },
        url: "/PlanDetail/SharePlan",
        cache: false,
        success: function(data) {
            $("#divShare").html($(data).filter("#divShare").html());
        }
    });
}

function SharePlanBodyChange(charLength) {
    var chars = $("#divShare #Body").html().length;
    $("#divShare #spanCharacterRemain").html(charLength - chars);
}

function toggleChannels(show) {
    if (show) {
        $("#showHideChannel").text("Hide");

        $('.channel-list-content').show();
        $('.channels-count-list').parent().css('height', '');
        $('.channels-count-list').prev().css({ 'font-size': '14px', 'font-weight': 'bold' });
        $('.channels-count-list').show();
        $('.channel-selection').show();
        $('#channel-category-cell').attr('rowspan', '2');
        $("#showHideAll").text("Hide All");
    }
    else {
        $("#showHideChannel").text("Show");
        $('.channel-list-content').hide();
        $('.channels-count-list').parent().css('height', '20px');
        $('.channels-count-list').prev().css({ 'font-size': '12px', 'font-weight': 'normal' });
        $('.channels-count-list').hide();
        $('.channel-selection').hide();
        $('#channel-category-cell').attr('rowspan', '1');
    }
}

function toggleFeatures(show) {
    if (show) {
        $("#showHideFeatures").text("Hide");
        $('.features-table-body').show();
        $("#showHideAll").text("Hide All");
    }
    else {
        $("#showHideFeatures").text("Show");
        $('.features-table-body').hide();
    }
    /*if ($('.features-table-body').css('display') == 'none') {
    $('.toggle-features').html('Show Features');
    }
    else {
    $('.toggle-features').html('Hide Features'); 
    }*/
}

function toggleHighlights(show) {
    if (show) {
        $("#showHideHighlights").text("Hide");
        $('.highlights-content').show();
        $('.highlights-hide-state').hide();
        $("#showHideAll").text("Hide All");
    }
    else {
        $("#showHideHighlights").text("Show");
        $('.highlights-content').hide();
        $('.highlights-hide-state').show();
    }
}

function togglePrice(show) {
    if (show) {
        $("#showHide").text("Hide");
        $("#showHideAll").text("Hide All");
        $('.togglePriceClass').show();
    }
    else {
        $("#showHide").text("Show");
        $('.togglePriceClass').hide();
    }
}
function toggleAdditionalTiers(show) {
    if (show) {
        $("#showHideAdditionalTiers").text("Hide");
        $("#showHideAll").text("Hide All");
        $('.toggleAdditionalTiersClass').show();
    }
    else {
        $("#showHideAdditionalTiers").text("Show");
        $('.toggleAdditionalTiersClass').hide();
    }
}

function isHidingAny() {
    if ($("#showHideAll").text() == "Hide All") {
        return false;
    }
    else {
        return true;
    }
    //    if ($('.price-month-content').css('display') == 'none')
    //        return true;
    //    if ($('.highlights-content').css('display') == 'none')
    //        return true;
    //    if ($('.features-table-body').css('display') == 'none')
    //        return true;
    //    if ($('.channels-body').css('display') == 'none')
    //        return true;

    return false;
}

function toggleAllCompare() {
    if (isHidingAny()) {
        $("#showHideAll").text("Hide All");
        togglePrice(true);
        toggleHighlights(true);
        toggleFeatures(true);
        toggleChannels(true);
        toggleAdditionalTiers(true);
    }
    else {
        $("#showHideAll").text("Show All");
        togglePrice(false);
        toggleHighlights(false);
        toggleFeatures(false);
        toggleChannels(false);
        toggleAdditionalTiers(false);
    }
}

function removeFromCompare(id) {
    $(".remove a").addClass("disabled");

    $.ajax({
        url: "/PlanComparison/RemoveItem/" + id,
        type: "GET",
        cache: false,
        dataType: 'json',
        success: function(data) {
            if (data != null) {
                $(location).attr('href', data.URL);
            }
            else {
                $(".remove a").removeClass("disabled");
            }
        },
        error: function(err) {
            $(".remove a").removeClass("disabled");
        }
    });
}

