jQuery(function ($) {
    $.TXU = {};
    /* Extend the .NET function __doPostBack */
    (function () {
        var old = window.__doPostBack,
		called = false;
        window.__doPostBack = function () {
            if (window.event) {
                new $.Event(window.event).preventDefault();
            }
            if (called == true) return false;
            old.apply(this, arguments);
            called = true;
            return false;
        }
    })();
    /* Extend the .NET function WebForm_DoPostBackWithOptions */
    (function () {
        var old = window.WebForm_DoPostBackWithOptions,
		called = false;
        window.WebForm_DoPostBackWithOptions = function () {
            if (called == true) {
                if (window.event) {
                    new $.Event(window.event).preventDefault();
                }
                return false;
            }
            old.apply(this, arguments);
            called = true;
        }
    })();
    /* Update the form to always post to https */
    if (String(window.location).indexOf("https") != 0) {
        $("form:not(.noSecure)").each(function () {
            var $this = $(this);
            $this.attr("action", "https://" + window.location.host + $this.attr("action"));
        });
    }
    
    /*utility function to collect parseclass vals preferential to namespace */
    function nsParseClassVals(object, attribute, ns) {
		if(object[ns][attribute] !== undefined) {
			return object[ns][attribute];
		} else {
			return object[attribute];
		}
	}
    
    /* Handle read only select boxes */
    $("select.readonly").each(function () {
        var $this = $(this).hide();
        $this.after($this.clone().attr({ disabled: true, name: '', id: '' }).show());
    });
    (function () {
        var eles = $("input.onechecked").click(function (e, opts) {
            var $this = $(this),
			obj = $this.ParseClass(true);

            if (opts) {
                $this.attr("checked", opts.checked);
            } else {
                $this.attr("checked", $this.attr("checked"));
            }

            if (eles.filter("." + obj.key + ":checked").length >= 2) {
                $.ConfirmDialog({
                    confirmTitle: "",
                    confirmMessage: obj.dialogMessage,
                    cancelText: false,
                    continueText: obj.dialogContinueText || "Okay"
                });
                if ($this.is(":radio")) {
                    $("input[name='" + $this.attr("name") + "']").each(function () {
                        if (this !== $this[0]) {
                            $(this).attr("checked", true).trigger("change");
                            return false;
                        }
                    });
                } else {
                    $this.attr("checked", false);
                }
            }
            var checked = $this.attr("checked");
            setTimeout(function () {
                $this.attr("checked", checked).trigger("change");
            }, 1);
            return false;
        });
    })();
	(function(){
		$("a.checkall,a.uncheckall").live("click", function() {
            opts = {
                onlyVisible: true
            }
            var $this = $(this),
			obj = $this.ParseClass();
            obj = $.extend({}, opts, obj);
            selector = obj.selector ? obj.selector : "input[type='checkbox']",
			checkboxes = obj.parent ? $(selector, $(obj.parent)) : $(selector);
            checkboxes.filter((obj.onlyVisible == true) ? ':visible' : '*').attr('checked', $(this).hasClass("checkall") ? true : false);
        });
    })();
    (function () {
        $('input.checkedShowMore,span.checkedShowMore input').live("change", function (e, auto) {
            //fix for ie?
			if(auto && $.browser.msie && $.browser.version <= 8) {
                //ie does not respond to live change events
                $(this).bind("change", arguments.callee);
            }
            var $ele = $(this);
            $this = $ele.hasClass("checkedShowMore") ? $ele : $ele.parents(".checkedShowMore:first");
            var opts = {
                autoShow: true,
                autoHide: true,
                refreshInlineValidate: false
            }
            var obj = $this.ParseClass();
            obj = $.extend({}, opts, obj);
            $.fn.noop = $.noop;
			if(auto != undefined) {
                $(obj.selector)[$(this).is(":checked") ? (obj.autoShow == true) ? "show" : "noop" : (obj.autoHide == true) ? "hide" : "noop"]();
            } else {
                $ele.trigger("validationRefresh");
                $(obj.selector)[$(this).is(":checked") ? "show" : "hide"]();
            }
        }).trigger("change", "auto");
		if($.browser.msie && $.browser.version <= 8) {
			$('body').bind("DOMupdated", function(){
				//ie does not respond to live change events
				$('input.checkedShowMore,span.checkedShowMore input').trigger("change", "auto");
			});
		};
    })();

    (function () {
        $('input.checkedHideMore,span.checkedHideMore input').live("change", function (e, auto) {
            //fix for ie?
			if(auto && $.browser.msie && $.browser.version <= 8) {
                //ie does not respond to live change events
                $(this).bind("change", arguments.callee);
            }
            var $ele = $(this);
            $this = $ele.hasClass("checkedHideMore") ? $ele : $ele.parents(".checkedHideMore:first");
            var opts = {
                autoShow: true,
                autoHide: true,
                clearInputs: false
            }
            var obj = $this.ParseClass();
            obj = $.extend({}, opts, obj);
            $.fn.noop = $.noop;
			if(auto != undefined) {
                $(obj.selector)[$(this).is(":checked") ? (obj.autoHide == true) ? "hide" : "noop" : (obj.autoShow == true) ? "show" : "noop"]();
            } else {
                $(obj.selector)[$(this).is(":checked") ? "hide" : "show"]();
            }
            if(obj.clearInputs == true) {
				if((auto != undefined && obj.autoHide == true) || auto == undefined) {
					$("input", obj.selector).each(function(){
						if($(this).is(":radio") || $(this).is(":checkbox")) {
							$(this).attr("checked", false);
						} else if(!$(this).is(":button") && !$(this).is(":submit")) {
							$(this).val("");
						}
						$(this).trigger("validateNeutral");
					});
				}
			}
        }).trigger("change", 'auto');
		if($.browser.msie && $.browser.version <= 8) {
			$('body').bind("DOMupdated", function(){
				//ie does not respond to live change events
				$('input.checkedHideMore,span.checkedHideMore input').trigger("change", "auto");
			});
		};
    })();

    (function () {
        $('input.checkedRemoveClass,span.checkedRemoveClass input').live("click", function (e) {
            var $ele = $(this);
            $this = $ele.hasClass("checkedRemoveClass") ? $ele : $ele.parents(".checkedRemoveClass:first");
            var obj = $this.ParseClass();
            if ($(this).is(":checked")) {
                $(obj.selector).removeClass(obj.className);
            }
        }).triggerHandler("click");
    })();
    
    (function () {
        $('input.checkedAddClass,span.checkedAddClass input').live("click", function (e) {
            var ns = "checkedAddClass";
            var $ele = $(this),
            $this = $ele.hasClass("checkedAddClass") ? $ele : $ele.parents(".checkedAddClass:first");
            var obj = $this.ParseClass();
            if ($(this).is(":checked")) {
                //namespace preferred
                $(nsParseClassVals(obj, "selector", ns)).addClass(nsParseClassVals(obj, "className", ns));
            }
        }).triggerHandler("click");
    })();

    /* Confirm Logout Dialog */
    (function () {
        var dialog = $("div.confirmLogout"),
		ele;
        if (dialog.length > 0) {
            $("a").live("click", function (e) {
                ele = $(this);
                var href = ele.attr("href");
                if (!ele.is(".noConfirmLogout") && href && href.indexOf("/myaccount/") == -1 && href.indexOf("javascript") == -1 && href.substring(0, 1) != "?" && href != "#" && href.indexOf("/Handlers/") == -1 && href.indexOf("~/media") == -1) {
                    dialog.dialog("open");
                    return false;
                }
            });
            dialog.dialog({
                autoOpen: false,
                modal: true
            }).find("span.primary").click(function () {
                window.location = "/Logout.ashx?redirect=" + ele.attr("href");
            });
        }
    })();

    /* Select All Script */
    (function () {
        $("a.selectall,a.unselectall").live('click', function () {
            var $this = $(this),
			obj = $this.ParseClass(),
			checkboxes = $(obj.checkboxParent).find("input[type='checkbox']");
            if ($this.hasClass("selectall")) {
                checkboxes.not(":checked").trigger("click", { checked: true });
            } else {
                checkboxes.filter(":checked").trigger("click", { checked: false });
            }
        });
    })();

    /* checkOnSelect Script */
    (function () {
        $("select.checkOnSelect").change(function () {
            var $this = $(this),
			obj = $this.find("option:selected").ParseClass();
            if (obj.check) {
                $(obj.check).attr("checked", true).trigger("change");
            }
        });
    })();

    /* div.pledgePaymentOptions */
    $("div.pledgePaymentOptions").each(function () {
        var $this = $(this),
		radios = $this.find("input.radio"),
		remainingTotal = $this.find("input.remainingTotal"),
		remainingMinimum = $this.find("input.remainingMinimum"),
		pledgeOtherValue = $this.find("input.pledgeOtherValue"),
		updateValues = function () {
		    var amountPledged,
			obj = radios.filter(":checked").ParseClass();
		    if (typeof (obj.amount) == "undefined") {
		        amountPledged = 0;
		    } else if (typeof (obj.amount) == "string") {
		        amountPledged = $(obj.amount).val();
		    } else {
		        amountPledged = obj.amount;
		    }

		    var obj = remainingTotal.ParseClass();
		    remainingTotal.val((obj.amount - amountPledged).toFixed(2));

		    var obj = remainingMinimum.ParseClass();
		    remainingMinimum.val((obj.amount - amountPledged).toFixed(2));
		};

        radios.change(updateValues);
        pledgeOtherValue.change(updateValues);
        updateValues();
    });

    /* unrequire */
	(function(){
		var unrequireFunc = function(e) {
            var opts = {
				reqIcon:'.req',
                stopInlineValidation: true,
                validationMemNS: 'validationMem',
                restoreRequire: false,
                addRequiredLabel: false
            }
            var $this = ($(this).hasClass(e.data.container)) ? $(this) : $(this).parents(e.data.container);
            var visibility = "hidden",
			restoreValidationClass = null;
            obj = $this.ParseClass();
            obj = $.extend({}, opts, obj);
			if(!obj.key && !(obj.unrequire && obj.require)) {
                return;
            }
            //gather the selectors
            var sel = {};
            var initValClass = {};
			if(obj.key) {
                sel[obj.key] = (obj.restoreRequire == true) ? "restore" : "unrequire";
            } else {
                sel[obj.unrequire] = "unrequire";
                sel[obj.require] = "restore";
				if(obj.initValClass !== undefined) {
					$(obj.initValClass.split(",")).each(function(){
                        initValClass[this] = 1;
                    });
                }
            }
			for(key in sel) {
				if(sel[key] == "restore") {
                    visibility = 'visible';
                    restoreValidationClass = true;
                }
				$(key).each(function(){
					$(obj.reqIcon, this).css({visibility:visibility});
					if(obj.stopInlineValidation === true) {
                        $("input", this).toggleUnrequireValidationClass(restoreValidationClass, obj.validationMemNS, initValClass, obj.addRequiredLabel);
                        $("select", this).toggleUnrequireValidationClass(restoreValidationClass, obj.validaionMemNS, initValClass, obj.addRequiredLabel);
                    }
                });
            }
        }
        //check to see if item was being inline validated
		$.fn.toggleUnrequireValidationClass = function(restore, validationMemNS, initValClass, addRequiredLabel) {
            var R = $.InlineValidator.validatorClasses.length;
			return this.each(function(){
                $elm = $(this);
                if(addRequiredLabel == true){
					$label = $("label", $elm.parents(".item"));
					if($label.data().hasRequiredLabel !== true) {
						$label.prepend('<span class="req">*</span>');
						$label.data('hasRequiredLabel', true);
					}
				}
				if(restore === true) {
                    var valClasses = ($elm.data()[validationMemNS] != undefined) ? $elm.data()[validationMemNS] : initValClass;
					for(key in valClasses) {
                        $elm.addClass(key);
                    }
                } else {
					for(var i = R; i--;) {
                        var valClass = $.InlineValidator.validatorClasses[i];
						if($elm.hasClass(valClass)) {
							if($elm.data()[validationMemNS] != undefined) {
                                $elm.data()[validationMemNS][valClass] = 1
                            } else {
                                var classObj = {}
                                classObj[valClass] = 1;
                                $elm.data(validationMemNS, classObj);
                            }
                            $elm.removeClass(valClass);
                            var $error = $elm.parents(".error");
							if($error.length == 1) {
                                $error.removeClass("error");
                            }
                        }
                    }
                }
            });
        }
		$('span.unrequire > input').live("click", {container:".unrequire"}, unrequireFunc);
        //make sure forms loaded with default values are respected
		$('span.unrequire > input').each(function(){
            $input = $(this);
			if($input.is(":checked")) {
                $input.trigger("click");
            }
        });
    })();


    /* input.inputShowMore */
    (function () {
        var showMoreFunc = function (e) {
            var $this = $(this),
			obj = $this.ParseClass();
            if (!obj.key) {
                return;
            }
            var opts = $('input[name="' + $this.attr('name') + '"]:checked'),
			show = (opts.length) ? opts.ParseClass().show : '',
			eles = $('div,label,span,em,tr,fieldset').filter('.' + obj.key).hide();
            if (show.length > 0) {
                eles.filter("." + ((show instanceof Array) ? show.join(',.') : show))
				.show();
            }
        };
        $('input.inputShowMore').live("click", showMoreFunc).triggerHandler("click");
    })();

    /* .showAndHide */
    /* simultaneous show and hide */
    (function () {
        var showAndHideFunc = function (e) {
            var $this = $(this);
            var opts = {
				order: ['hide','show']
            };
            var obj = $this.ParseClass();
			if(!obj.show && obj.hide) {
                return;
            }
            var show, hide;
			if($this.is(":radio") || $this.is(":checkbox")) {
                $options = $('input[name="' + $this.attr('name') + '"]:checked');
                obj = $options.ParseClass();
				if(!obj.show && obj.hide) {
                    return;
                }
            } else {
                //item is a link, suppress it
				if(obj.nolink && obj.nolink === true) {
                    e.preventDefault();
                }
            }
            //establish options
            obj = $.extend({}, opts, obj);

            $((obj[obj.order[0]] instanceof Array) ? obj[obj.order[0]].join(',') : obj[obj.order[0]])[obj.order[0]]();
            $((obj[obj.order[1]] instanceof Array) ? obj[obj.order[1]].join(',') : obj[obj.order[1]])[obj.order[1]]();
        }
        $("a.showAndHide, input.showAndHide").live("click", showAndHideFunc);
    })();

    /* select.selectShowMore */
    (function () {
        var showMoreFunc = function (e, initialLoad) {
            var $this = $(this),
			obj = $this.ParseClass();
            if (!obj.key) {
                return;
            }
            var opts = $this.find('option:selected'),
			show = (opts.length) ? opts.ParseClass().show : '',
			eles = $('div,span,strong').filter('.' + obj.key).hide();

            if (show && show.length > 0) {
                eles.filter("." + ((show instanceof Array) ? show.join(',.') : show))
				.show();
            }

            if (obj.highlight && typeof initialLoad == "undefined") {
                $('.' + obj.highlight).each(function () {
                    if (this.tagName.toLowerCase() == 'tr') {
                        var origColor = $(this).find('td').css('backgroundColor');
                        $(this).find('td').css('backgroundColor', '#ffffcc').animate({
                            backgroundColor: origColor
                        }, 1000);
                    } else {
                        origColor = $(this).css('backgroundColor');
                        $(this).css('backgroundColor', '#ffffcc').animate({
                            backgroundColor: origColor
                        }, 1000);
                    }
                });
            }
        };
        $.TXU.ShowMoreFuncInit = function () {
            $('select.selectShowMore')
			.filter(function () { return !$(this).data("selectShowMoreInit") })
			.data("selectShowMoreInit", true)
			.bind("change", showMoreFunc)
			.trigger("change", true);
        };
        $.TXU.ShowMoreFuncInit();
    })();

    /* input.radioDisabled */
    (function () {
        var radioDisabledFunc = function (e) {
            var $this = $(this),
			obj = $this.ParseClass();
            if (!obj.key) {
                return;
            }
            var opts = $('input[name="' + $this.attr('name') + '"]:checked'),
			enable = (opts.length) ? opts.ParseClass().enable : '';

            $('input, select')
			.filter('.' + obj.key)
			.attr("disabled", true)
			.filter("." + ((enable instanceof Array) ? enable.join(',.') : enable))
			.attr("disabled", false);
        };
        $('input.radioDisabled').change(radioDisabledFunc).trigger("change");
    })();

    /* div.optionsMenu */
    $("a.triggerOptionsMenu").live("click", function () {
        var $this = $(this),
		clone = $this.data('clone'),
		pos = $this.offset(),
		height = $this.outerHeight(),
		opts = $this.ParseClass();
        if (!clone) {
            clone = $this.parent().find("div.box").hide().clone(true).appendTo('body').addClass('optionsMenu');
            $this.data('clone', clone);
        }
        if (clone.is(":visible")) {
            clone.hide();
        } else {
            clone.css({
                'top': pos.top + height,
                'left': pos.left - 20
            }).show();
            if (opts.width) {
                if (clone.data('roundboxinit')) {
                    // Special considerations when roundbox has been used (IE).
                    var extra = clone.width() - clone.find('div.i').width();
                    clone.width(opts.width + extra);
                } else {
                    clone.width(opts.width);
                }
            }
            $(document).bind('click', function (e) {
                var target = e.target;
                // Make sure click wasn't on or inside clone
                if (clone[0] != target && !clone.has(target).length) {
                    clone.hide();
                    $(document).unbind(e);
                }
            });
        }

        return false;
    });

    /* Button hover state */
    $('span.button').live('mouseover mouseout', function (event) {
        if (event.type == 'mouseover') {
            $(this).addClass('hover');
        } else {
            $(this).removeClass('hover');
        }
    });

    /* Select box fix width */
    if ($.browser.msie) {
        $('select.fixWidth').each(function () {
            $(this).wrap('<span class="fixWidthWrapper" />');
            $(this).parent().width($(this).width());
        });

        $('select.fixWidth').live('focus blur', function (event) {
            var width = $(this).width();
            //$(this).parent().width(width);
            if (event.type == 'focusin') {
                $(this).addClass('focus');
                if ($(this).width() < width) {
                    $(this).removeClass('focus'); // remove focus class if width is less than original
                }
            } else {
                $(this).removeClass('focus');
            }
        });
    }

    /* Remove alt text popups */
    if ($.browser.msie) {
        $('img').each(function () {
            var $this = $(this);
            if (!$this.attr('title')) {
                $this.attr('title', '');
            }
        });
    }

    /* div.box.shopping */
    $("div.box.landingTwo").each(function () {
        var box = $(this);
        box.find("a.ajaxFormLink").click(function () {
            var $this = $(this);
            box.find("div.leftCol li").removeClass("selected");
            box.find("div.rightCol img").hide();
            box.find("div.rightCol div.box.rBox").show();
            $this.parent().addClass("selected");
        });
        box.find("li.selected a.ajaxFormLink").triggerHandler("click");
    });

    $('a.toggle').click(function () {
        var $this = $(this),
		obj = $this.ParseClass(true);

        $(obj.content).toggle();

        if (obj.showHTML && obj.hideHTML) {
            $this.html(
				$(obj.content).is(":visible") ? obj.hideHTML : obj.showHTML
			);
        }
        //reapply the png fix in dialogs for IE6
        if (document.all && $.initFixPNGElements) {
            setTimeout($.initFixPNGElements, 10);
        }
        $this.blur();
        return false;
    });

    $("div.businessLanding").each(function () {
        var _finishExpandAnimation,
		_onCollapsibleHeaderClick = function (e) {
		    var ele = $(e.currentTarget);
		    ele.parents("div.collapsible:first").trigger("expand");
		},
		_onCollapsibleExpand = function (e) {
		    var ele = $(e.currentTarget);
		    if (!ele.hasClass("closed")) {
		        return;
		    }
		    if (_finishExpandAnimation) {
		        _finishExpandAnimation();
		    }
		    var oldPromoBox = collapsibleBoxes.filter(":not(.closed)").addClass("closed").find("div.content"),
			newPromoBox = $(e.currentTarget).removeClass("closed").find("div.content");

		    _finishExpandAnimation = $.proxy(function () {
		        oldPromoBox.stop().css("height", "").css("display", "none");
		        newPromoBox.stop().css({ "height": "", "overflow": "" });
		        _finishExpandAnimation = false;
		    }, this);

		    var height = newPromoBox.css("display", "").height();

		    oldPromoBox.animate({ height: 0 }, 1000, _finishExpandAnimation);
		    newPromoBox.css({ "height": 0 }).animate({ height: height }, 1000);
		},
		ele = $(this),
		collapsibleBoxes = ele.find("div.collapsible")
		.bind("expand", _onCollapsibleExpand, this);
        collapsibleBoxes.find("div.header").click(_onCollapsibleHeaderClick);
    });

    $("div.quickFind :button").click(function () {
        var field = $("div.quickFind select").val();
        if (!field) field = "desc";
        var query = $("div.quickFind :text").val();
        if (!query) query = "none";
        top.location.href = '/myaccount/business/accounts-invoices/search.aspx?field=' + field + '&query=' + query;
    });

    $("div.specialRequests :button").click(function () {
        var type = $("div.specialRequests select").val();
        if (type) top.location.href = '/myaccount/business/customer-care/new-inquiry.aspx?type=' + type;
    });

    $("a.print-link").click(function () {
        window.print();
    });

    //select option redirect
    (function () {
        $("select").change(function () {
            var $this = $(this),
			selected = $this.find('option:selected'),
			obj = selected.ParseClass(),
			clickItem;

            if (selected.hasClass('redirectOption') && obj.url) {
                $(document).change();
                $('<a href="' + obj.url + '" style="display:none;" />').click();
            }
            return this;
        });
    })();

	//select launchFormDialog
    (function () {
        $("select.launchFormDialog").change(function (e) {
			var ele = $(this),
            obj = ele.find('option:selected').ParseClass();

            if (obj.url) {
                $.LaunchFormDialog (obj.url, obj);
				ele.attr("selectedIndex", ele.data("selectedOptionIndex"));
				return false;
            }
			ele.data("selectedOptionIndex", ele.attr("selectedIndex"));
        }).each(function(i, ele) {
			$(ele).data("selectedOptionIndex", $(ele).attr("selectedIndex"));
		});
    })();

    /* Webtrends live tracking */
    (function () {
        $(document).bind('TrackWT', function (e) {
            $this = $(e.target);

            var wbtObj = $this.ParseClass(true);
            if (!wbtObj.Tags) { return; }

            var tagArray = new Array();
            for (var tagKey in wbtObj.Tags) {
                var tag = wbtObj.Tags[tagKey];
                tagArray.push(unescape(tag.name));
                tagArray.push(unescape(tag.content));
            }

            if (window.dcsMultiTrack) {
                try {
                    window.dcsMultiTrack.apply(this, tagArray);
                } catch (e) { };
            }
        });

        $('.webtrendTracking').live("mouseup", function (e) {
            $(this).trigger("TrackWT");
        });

        $('.autoWebtrendTracking').each(function () {
            $(this).trigger("TrackWT");
        });
    })();

    /* Scrollable Anchor */
    (function () {
        $(".scrollable-anchor").live("click", function () {
            var obj = $(this).ParseClass();
            if (!obj.anchor)
                return;
            $('html,body').animate({ scrollTop: $("#" + obj.anchor).offset().top }, 'slow');
        })
    })();

    /*Account Summary Messaging for Disconnect */
    (function () {
        $(document).bind('AccountStatusMessageEvent', function (e) {
            var $this = $(e.target);

            var status = $($this.find(".statusMessage"));
            $(".StatusContainer").html("").append(status);
            status.show();

            var dm = $($this.find(".disconnectMessage"));
            if (!dm || !dm.html()) {
                $(".accountStatusMessage").hide();
            }
            else {
                $(".accountStatusMessage").show();
                var obj = dm.ParseClass();
                var dsh = $(".disconnectMessageHolder");
                dsh.html("").append(dm);

                if (obj && obj.currentClass == "goodMsg") {
                    dm.closest(".accountStatusMessage").find("a.disconnectMessageMoreDetails").hide();
                }

                if (obj) {
                    dsh.removeClass(obj.removeClasses.replace(/,/gi, " ")).addClass(obj.currentClass);
                }

                dm.show();
            }

            obj = $this.ParseClass(true);
            $(obj.reloadContainerSelector).trigger("reload");

        });
    })();

    /* Fix the Tab Index */
    (function () {
        var i = 1;
        $("span.inTabIndex, input.inTabIndex, textarea.inTabIndex, a.inTabIndex, select.inTabIndex").each(function () {
            var $this = $(this);
            if (!$this.is("input,textarea,select,a")) $this = $this.find("input, textarea, select");
            $this.attr("tabIndex", i++);
        });
    })();

    /* Total Amount due */
    (function () {
        $("input.totalAmount, span.totalAmount").each(function () {
			opts = {
				initValue: 0,
				checkOnLoad: false
			}
            var $this = $(this),
			obj = $this.ParseClass(true);
			obj = $.extend({}, opts, obj);
			addends = $(obj.addendSelector).change(function () {
			    var sum = parseFloat(obj.initValue);
			    addends.each(function () {
			        var _this = $(this);
			        if (!_this.is(":checked")) return;
			        sum += parseFloat(_this.ParseClass(true).amount);
			    });
				$this[($this.is("input")) ? "val" : "html"](sum.toFixed(2));
			});
			if(obj.checkOnLoad == true) {
				addends.triggerHandler("change");
			}
        });
    })();

    /* Set Value */
    (function () {
        $("a.setValue").click(function () {
            var ele = $(this).ParseClass(true);

            $(ele.input).val(ele.value);
        });
    })();

    /* Transfer Value */
	var TransferInputValue = function() {
        $elm = $(this);
        var opts = {
            triggerValidation: true,
            forceOverwrite: true
        }
		if(($elm.is(":radio,:checkbox") && $elm.is(":checked")) || !$elm.is(":radio,:checkbox")) {
            var obj = $elm.ParseClass();
            obj = $.extend({}, opts, obj);
            var $to = (obj.to == "self") ? $elm : $(obj.to);
            var $from = (obj.from == "self") ? $elm : $(obj.from);
			if(obj.forceOverwrite == true) {
                $to.val($from.val());
				if(obj.triggerValidation === true) {
                    $to.trigger("validate");
                }
            }
        }
    };
	(function(){
        $("input.transferValue").click(TransferInputValue);
    })();

    //listen for autoComplete select and transfer value
	(function(){
        $("input.autoCompleteTransferValue").bind("changed.autoComplete", TransferInputValue);
    })();

    /* Export to Excel for MED */
    $(document).bind("DOMupdated", function (e) {
        var $form = $(e.target);

        if ($form.hasClass('exportExcelDialog')) {
            var updateFields = function () {
                var startDate = new Date($('input.startDate').val()),
				endDate = new Date($('input.endDate').val()),
				dayDiff = (endDate - startDate) / (1000 * 60 * 60 * 24),
				isSingleMonth = (startDate.getFullYear() == endDate.getFullYear() && startDate.getMonth() == endDate.getMonth()) ? true : false,
				hasAMS = $form.hasClass('hasAMS');

                $form.find('input[type="radio"]').attr('disabled', '').parents("li").removeClass('disabled');

                if (!hasAMS) {
                    // No AMS data
                    $('input.month').attr('checked', 'checked');
                    $('input.hour').attr('disabled', 'disabled').parents("li").addClass('disabled');
                    $('input.day').attr('disabled', 'disabled').parents("li").addClass('disabled');
                } else {
                    // AMS data
                    if (isSingleMonth) {
                        // < 30 days in a single month
                        $('input.month').attr('disabled', 'disabled').parents("li").addClass('disabled');
                        $('input.day').attr('checked', 'checked');
                    } else if (dayDiff >= 30) {
                        // > 30 days in multiple months
                        $('input.month').attr('checked', 'checked');
                        $('input.hour').attr('disabled', 'disabled').parents("li").addClass('disabled');
                    }
                }
            };

            updateFields();

            $('input.startDate, input.endDate').datepicker({
                onSelect: function (dateText, inst) {
                    updateFields();
                }
            });

        }
    });

    /* Check if a user has data (MED) */
    $("div.hasBillingData").each(function () {
        var $this = $(this),
		opts = $.extend($this.ParseClass(), opts);
        $.post(opts.ajaxURL, function (data) {
            if (data.hasData == false) {
                if ($("div.medModules").length) {
                    $("div.medModules").hide();
                    $("div.filtersMED div.filtersAppendix").hide();
                } else {
                    $("#content > *").hide();
                }
                $this.show();
            }
        }, "json");
    });

    $.fn.hideOption = function () {
        this.each(function () {
            if ($(this).is('option') && (!$(this).parent().is('span'))) {
                $(this).wrap('<span>').hide()
            }
        });
    }

    $.fn.showOption = function () {
        this.each(function () {
            if (this.nodeName.toLowerCase() === 'option') {
                var p = $(this).parent(), o = this;
                $(o).show();
                $(p).replaceWith(o)
            } else {
                var opt = $('option', $(this));
                $(this).replaceWith(opt);
                opt.show();
            }
        });
    }

	$(function() {
		var setHeight = function() {
			$("div.box.home").each(function() {
				$("#sidebar div.box div.inner").height("");
				$("#sidebar div.box").removeClass("updatedHeight");

				var contentHeight = $("#content").height(),
				sidebarHeight = $("#sidebar").height(),
				headerHeight = $("#sidebar div.box div.header").outerHeight();

				if (sidebarHeight < contentHeight) {
					var diff = $("#sidebar div.box div.inner").outerHeight() - $("#sidebar div.box div.inner").height() + $("#sidebar div.box div.b").outerHeight() + parseInt($("#sidebar div.box").css("border-bottom-width"));
					if ($.browser.msie) {
						diff++; // IE was 1px off. To lazy to figure out why.
					}
					$("#sidebar div.box div.inner").height(contentHeight - headerHeight - diff);
					$("#sidebar div.box").addClass("updatedHeight");
				}
			});
		}
		setHeight();
		$(document).bind("rBoxInit", setHeight);
		$(window).bind("load", function() {
			setHeight();
			setTimeout(setHeight, 100); // Chrome needs some time to render the webfont
		});
	});
	

    /* Fix the save password */
    /*(function () {
    var cancelled = false;
    $("input.loginButton").click(function () {
    if (cancelled) return;

    var $this = $(this),
    cont = $this.parents(".loginContainer:first"),
    username = cont.find("input.username").val(),
    password = cont.find("input.password").val();

    $("div.loginContainer input.username").val(username);
    var passwords = $("div.loginContainer input.password").val(password);

    cancelled = true;
    setTimeout(function () {
    passwords.attr("autocomplete", "");
    $this[0].click();
    }, 1);

    return false;
    });
    })();*/
});


