﻿// ****************************************************************************************************************************
// Code used across the entire site
// ****************************************************************************************************************************


$(document).ready(function() {
    $('a.a_cartitem').tooltip({
        track: true,
        delay: 0,
        showURL: false,
        bodyHandler: function() {
            if (this.tooltipText == "") return "";
            var result = "<ul class='tooltip'>";
            var parts = this.tooltipText.split('\n');
            for (var i = 0; i < parts.length; i++) {
                var ln = parts[i].split("\t");
                if (ln.length == 1)
                    result += "<li>" + parts[i] + "</li>";
                else
                    result += "<li class='subitem' style='padding-left:" + (ln.length * 15) + "px'>" + ln[ln.length - 1] + "</li>";
            }
            result += "</ul>";
            //alert(result);
            return result;
        },
        fade: 250
    })
});


function StickPanelToTop(panel_id) {
    if ($.browser.msie && $.browser.version < "8") return;

    var pnl = document.getElementById(panel_id);
    var pnlpos = $(pnl).position();
    var OriginalPosition = pnlpos.top;
    var OriginalPositionX = pnlpos.left;
    var OriginalWidth = pnl.offsetWidth;
    var pnl_body = document.getElementById("body");
    var pnl_top_margin = 5;

    if (pnl_body.offsetHeight > pnl.offsetHeight + pnl.offsetTop + 50) { // 50 ... or ... 180=? no idea why
        if (document.documentElement.clientHeight > pnl.offsetHeight + pnl_top_margin && window.XMLHttpRequest) {
            pnl.style.position = "absolute";
            pnl.style.width = OriginalWidth + "px";
            pnl.style.left = OriginalPositionX + "px";

            var on_scroll = function() {
                var scrollTop = (typeof window.pageYOffset != 'undefined') ? window.pageYOffset : document.documentElement.scrollTop;
                if (scrollTop > OriginalPosition - pnl_top_margin) {
                    var pnl = document.getElementById(panel_id);
                    var pnlbody = document.getElementById("body");

                    var pnlbody_offsetHeight = pnlbody.offsetHeight - 20; // 20=? no idea why
                    var pnlTop = pnl_top_margin;
                    if (scrollTop + pnl.offsetHeight + pnlTop > pnlbody_offsetHeight) {
                        pnlTop = pnlbody_offsetHeight - pnl.offsetHeight;
                        $('#' + panel_id).css('position', 'absolute');
                        $('#' + panel_id).css('top', pnlTop + 'px');
                    } else {
                        $('#' + panel_id).css('position', 'fixed');
                        $('#' + panel_id).css('top', pnlTop + 'px');
                    }
                } else if (scrollTop < OriginalPosition - pnl_top_margin) {
                    $('#' + panel_id).css('position', 'absolute');
                    $('#' + panel_id).css('top', OriginalPosition + 'px');
                }
            };

            $(window).scroll(on_scroll); // window.scroll

            $(window).resize(function() {
                pnl.style.position = "";
                pnl.style.width = "";
                pnl.style.left = "";

                OriginalPosition = pnl.offsetTop;
                OriginalPositionX = pnl.offsetLeft;
                OriginalWidth = pnl.offsetWidth;

                pnl.style.position = "absolute";
                pnl.style.width = OriginalWidth + "px";
                pnl.style.left = OriginalPositionX + "px";

                on_scroll();
            });
        } // if
    } // if
}



function ShowCityAndState() {
    $("#pnlCity").show();
    $("#pnlState").show();
    $("#pnlZip").hide();
    $("#pnlZip2").hide();
    $("#pnlNoZip").show();
    $("#pnlZip input")[0].value = "";
    return false;
}

function HideCityAndState() {
    $("#pnlCity").hide();
    $("#pnlState").hide();
    $("#pnlZip").show();
    $("#pnlZip2").show();
    $("#pnlNoZip").hide();
    return false;
}



function InitAddressEntryPanel() {
    $("#pnlZip input").change(function() {
        $("#pnlCity input").val("");
        $("#pnlState input").val("");
    });
    $("#pnlCity input, #pnlState input").change(function() {
        $("#pnlZip input").val("");
    });
}




// ****************************************************************************************************************************
// jQuery plugins
// ****************************************************************************************************************************


jQuery.fn.numeric = function(decimal, callback) {
    decimal = decimal || ".";
    callback = typeof callback == "function" ? callback : function() { };
    this.keypress(
		function(e) {
		    var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		    // allow enter/return key (only when in an input box)
		    if (key == 13 && this.nodeName.toLowerCase() == "input") {
		        return true;
		    }
		    else if (key == 13) {
		        return false;
		    }
		    var allow = false;
		    // allow Ctrl+A
		    if ((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true;
		    // allow Ctrl+X (cut)
		    if ((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true;
		    // allow Ctrl+C (copy)
		    if ((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true;
		    // allow Ctrl+Z (undo)
		    if ((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true;
		    // allow or deny Ctrl+V (paste), Shift+Ins
		    if ((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */
			|| (e.shiftKey && key == 45)) return true;
		    // if a number was not pressed
		    if (key < 48 || key > 57) {
		        /* '-' only allowed at start */
		        if (key == 45 && this.value.length == 0) return true;
		        /* only one decimal separator allowed */
		        if (key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1) {
		            allow = false;
		        }
		        var dot = ".";
		        if (key == dot.charCodeAt(0) && dot.charCodeAt(0) != decimal.charCodeAt(0)) {
		            allow = false;
		        } else
		        // check for other keys that have special purposes
		            if (
					key != 8 /* backspace */ &&
					key != 9 /* tab */ &&
					key != 13 /* enter */ &&
					key != 35 /* end */ &&
					key != 36 /* home */ &&
					key != 37 /* left */ &&
					key != 39 /* right */ &&
					key != 46 /* del */
				) {
		            allow = false;
		        }
		        else {
		            // for detecting special keys (listed above)
		            // IE does not support 'charCode' and ignores them in keypress anyway
		            if (typeof e.charCode != "undefined") {
		                // special keys have 'keyCode' and 'which' the same (e.g. backspace)
		                if (e.keyCode == e.which && e.which != 0) {
		                    allow = true;
		                }
		                // or keyCode != 0 and 'charCode'/'which' = 0
		                else if (e.keyCode != 0 && e.charCode == 0 && e.which == 0) {
		                    allow = true;
		                }
		            }
		        }
		        // if key pressed is the decimal and it is not already in the field
		        if (key == decimal.charCodeAt(0) && this.value.indexOf(decimal) == -1) {
		            allow = true;
		        }
		    }
		    else {
		        allow = true;
		    }
		    return allow;
		}
	)
	.blur(
		function() {
		    var val = jQuery(this).val();
		    if (val != "") {
		        var re = new RegExp("^\\d+$|\\d*" + decimal + "\\d+");
		        if (!re.exec(val)) {
		            callback.apply(this);
		        }
		    }
		}
	);
    return this;
}

// ****************************************************************************************************************************


;         (function($) {

    // the tooltip element
    var helper = {},
    // the current tooltipped element
		current,
    // the title of the current element, used for restoring
		title,
    // timeout id for delayed tooltips
		tID,
    // IE 5.5 or 6
		IE = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
    // flag for mouse tracking
		track = false;

    $.tooltip = {
        blocked: false,
        defaults: {
            delay: 200,
            fade: false,
            showURL: true,
            extraClass: "",
            top: 15,
            left: 15,
            id: "tooltip"
        },
        block: function() {
            $.tooltip.blocked = !$.tooltip.blocked;
        }
    };

    $.fn.extend({
        tooltip: function(settings) {
            settings = $.extend({}, $.tooltip.defaults, settings);
            createHelper(settings);
            return this.each(function() {
                $.data(this, "tooltip", settings);
                this.tOpacity = helper.parent.css("opacity");
                // copy tooltip into its own expando and remove the title
                this.tooltipText = this.title;
                $(this).removeAttr("title");
                // also remove alt attribute to prevent default tooltip in IE
                this.alt = "";
            })
				.mouseover(save)
				.mouseout(hide)
				.click(hide);
        },
        fixPNG: IE ? function() {
            return this.each(function() {
                var image = $(this).css('backgroundImage');
                if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
                    image = RegExp.$1;
                    $(this).css({
                        'backgroundImage': 'none',
                        'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
                    }).each(function() {
                        var position = $(this).css('position');
                        if (position != 'absolute' && position != 'relative')
                            $(this).css('position', 'relative');
                    });
                }
            });
        } : function() { return this; },
        unfixPNG: IE ? function() {
            return this.each(function() {
                $(this).css({ 'filter': '', backgroundImage: '' });
            });
        } : function() { return this; },
        hideWhenEmpty: function() {
            return this.each(function() {
                $(this)[$(this).html() ? "show" : "hide"]();
            });
        },
        url: function() {
            return this.attr('href') || this.attr('src');
        }
    });

    function createHelper(settings) {
        // there can be only one tooltip helper
        if (helper.parent)
            return;
        // create the helper, h3 for title, div for url
        helper.parent = $('<div id="' + settings.id + '"><h3></h3><div class="body"></div><div class="url"></div></div>')
        // add to document
			.appendTo(document.body)
        // hide it at first
			.hide();

        // apply bgiframe if available
        if ($.fn.bgiframe)
            helper.parent.bgiframe();

        // save references to title and url elements
        helper.title = $('h3', helper.parent);
        helper.body = $('div.body', helper.parent);
        helper.url = $('div.url', helper.parent);
    }

    function settings(element) {
        return $.data(element, "tooltip");
    }

    // main event handler to start showing tooltips
    function handle(event) {
        // show helper, either with timeout or on instant
        if (settings(this).delay)
            tID = setTimeout(show, settings(this).delay);
        else
            show();

        // if selected, update the helper position when the mouse moves
        track = !!settings(this).track;
        $(document.body).bind('mousemove', update);

        // update at least once
        update(event);
    }

    // save elements title before the tooltip is displayed
    function save() {
        // if this is the current source, or it has no title (occurs with click event), stop
        if ($.tooltip.blocked || this == current || (!this.tooltipText && !settings(this).bodyHandler))
            return;

        // save current
        current = this;
        title = this.tooltipText;

        if (settings(this).bodyHandler) {
            helper.title.hide();
            var bodyContent = settings(this).bodyHandler.call(this);
            if (bodyContent.nodeType || bodyContent.jquery) {
                helper.body.empty().append(bodyContent)
            } else {
                helper.body.html(bodyContent);
            }
            helper.body.show();
        } else if (settings(this).showBody) {
            var parts = title.split(settings(this).showBody);
            helper.title.html(parts.shift()).show();
            helper.body.empty();
            for (var i = 0, part; (part = parts[i]); i++) {
                if (i > 0)
                    helper.body.append("<br/>");
                helper.body.append(part);
            }
            helper.body.hideWhenEmpty();
        } else {
            helper.title.html(title).show();
            helper.body.hide();
        }

        // if element has href or src, add and show it, otherwise hide it
        if (settings(this).showURL && $(this).url())
            helper.url.html($(this).url().replace('http://', '')).show();
        else
            helper.url.hide();

        // add an optional class for this tip
        helper.parent.addClass(settings(this).extraClass);

        // fix PNG background for IE
        if (settings(this).fixPNG)
            helper.parent.fixPNG();

        handle.apply(this, arguments);
    }

    // delete timeout and show helper
    function show() {
        tID = null;
        if ((!IE || !$.fn.bgiframe) && settings(current).fade) {
            if (helper.parent.is(":animated"))
                helper.parent.stop().show().fadeTo(settings(current).fade, current.tOpacity);
            else
                helper.parent.is(':visible') ? helper.parent.fadeTo(settings(current).fade, current.tOpacity) : helper.parent.fadeIn(settings(current).fade);
        } else {
            helper.parent.show();
        }
        update();
    }

    /**
    * callback for mousemove
    * updates the helper position
    * removes itself when no current element
    */
    function update(event) {
        if ($.tooltip.blocked)
            return;

        if (event && event.target.tagName == "OPTION") {
            return;
        }

        // stop updating when tracking is disabled and the tooltip is visible
        if (!track && helper.parent.is(":visible")) {
            $(document.body).unbind('mousemove', update)
        }

        // if no current element is available, remove this listener
        if (current == null) {
            $(document.body).unbind('mousemove', update);
            return;
        }

        // remove position helper classes
        helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");

        var left = helper.parent[0].offsetLeft;
        var top = helper.parent[0].offsetTop;
        if (event) {
            // position the helper 15 pixel to bottom right, starting from mouse position
            left = event.pageX + settings(current).left;
            top = event.pageY + settings(current).top;
            var right = 'auto';
            if (settings(current).positionLeft) {
                right = $(window).width() - left;
                left = 'auto';
            }
            helper.parent.css({
                left: left,
                right: right,
                top: top
            });
        }

        var v = viewport(),
			h = helper.parent[0];
        // check horizontal position
        if (v.x + v.cx < h.offsetLeft + h.offsetWidth) {
            left -= h.offsetWidth + 20 + settings(current).left;
            helper.parent.css({ left: left + 'px' }).addClass("viewport-right");
        }
        // check vertical position
        if (v.y + v.cy < h.offsetTop + h.offsetHeight) {
            top -= h.offsetHeight + 20 + settings(current).top;
            helper.parent.css({ top: top + 'px' }).addClass("viewport-bottom");
        }
    }

    function viewport() {
        return {
            x: $(window).scrollLeft(),
            y: $(window).scrollTop(),
            cx: $(window).width(),
            cy: $(window).height()
        };
    }

    // hide helper and restore added classes and the title
    function hide(event) {
        if ($.tooltip.blocked)
            return;
        // clear timeout if possible
        if (tID)
            clearTimeout(tID);
        // no more current element
        current = null;

        var tsettings = settings(this);
        function complete() {
            helper.parent.removeClass(tsettings.extraClass).hide().css("opacity", "");
        }
        if ((!IE || !$.fn.bgiframe) && tsettings.fade) {
            if (helper.parent.is(':animated'))
                helper.parent.stop().fadeTo(tsettings.fade, 0, complete);
            else
                helper.parent.stop().fadeOut(tsettings.fade, complete);
        } else
            complete();

        if (settings(this).fixPNG)
            helper.parent.unfixPNG();
    }

})(jQuery);


// ****************************************************************************************************************************


(function($) {
    $.fn.updnWatermark = function(options) {
        options = $.extend({}, $.fn.updnWatermark.defaults, options);
        return this.each(function() {
            var $input = $(this);
            // Checks to see if watermark already applied.
            var $watermark = $input.data("updnWatermark");
            // Only create watermark if title attribute exists
            if (!$watermark && this.title) {
                // Inserts a span and set as positioning context
                var $watermark = $(options.tagName)
					.addClass(options.cssClass)
                    .insertBefore(this)
                    .hide()
                    .text(this.title)
                    .attr("for", this.id)
					.bind("show", function() {
					    $(this).fadeIn("fast");
					})
                    .bind("hide", function() {
                        $(this).hide();
                    });

                // Associate input element with watermark plugin.
                $input.data("updnWatermark", $watermark);
            }
            // Hook up blur/focus handlers to show/hide watermark.
            if ($watermark) {
                $input
                    .focus(function(ev) {
                        $watermark.trigger("hide");
                    })
                    .blur(function(ev) {
                        if (!$(this).val()) {
                            $watermark.trigger("show");
                        }
                    });
                // Sets initial watermark state.
                if (!$input.val()) {
                    $watermark.show();
                }
            }
        });
    };
    $.fn.updnWatermark.defaults = {
        cssClass: "updnWatermark",
        tagName: "<label/>"
    };
    $.updnWatermark = {
        attachAll: function(options) {
            $("input:text[title!=''],input:password[title!=''],textarea[title!='']").updnWatermark(options);
        }
    };
})(jQuery);












// ****************************************************************************************************************************
// Page-specific code
// ****************************************************************************************************************************








// ****************************************************************************************************************************
// Checkout
// ****************************************************************************************************************************


function InitCheckoutPage() {
    $("#btnNewCreditCard").click(function() {
        $("#pnlNewCreditCard").show();
        $("#pnlHouseAccount").hide();
        $(this).parent().siblings().css("font-weight", "normal");
        $(this).parent().css("font-weight", "bold");
        document.getElementById("p_PgCt_chkNewCreditCard__SaveOnFile").checked = true;
    });

    $("#btnCash").click(function() {
        $("#pnlNewCreditCard").hide();
        $("#pnlHouseAccount").hide();
        $(this).parent().siblings().css("font-weight", "normal");
        $(this).parent().css("font-weight", "bold");
    });

    $("#btnHouseAccount").click(function() {
        $("#pnlNewCreditCard").hide();
        $("#pnlHouseAccount").show();
        $(this).parent().siblings().css("font-weight", "normal");
        $(this).parent().css("font-weight", "bold");
    });

    $(".ccID").click(function() {
        $("#pnlNewCreditCard").hide();
        $("#pnlHouseAccount").hide();
        $(this).parent().siblings().css("font-weight", "normal");
        $(this).parent().css("font-weight", "bold");
    });

    $("#pnlCardHolder input").keyup(function() {
        document.getElementById("chkSameAsDelivery").checked = false;
    });


    $("div.payment input:checked").trigger("click");

    $("input[name='p$W$PgCt$rblCreditCardID']:checked").parent().css("font-weight", "bold");

    $(".phone").numeric("\t"); 
    
    $.updnWatermark.attachAll(); 
}

function CheckoutClicked(el) {
    $(el).hide();
    $('#btnCheckoutD').show();
}

function CopyValues(from_el, to_el) {
    var f = document.getElementById(from_el);
    var t = document.getElementById(to_el);
    if (f.value != t.value) t.value = f.value;
}

function CopyDeliveryAddress(el) {
    if (el.checked) {
        CopyValues("hdnShippingToName", "p_PgCt_txtNewCreditCard_CardName");
        CopyValues("hdnShippingAddress", "p_PgCt_txtNewCreditCard_BillingAddress");
        CopyValues("hdnShippingZip", "p_PgCt_txtNewCreditCard_BillingZip");
        setTimeout('document.getElementById("chkSameAsDelivery").checked = true;', 100);
    } else {
        document.getElementById("p_PgCt_txtNewCreditCard_CardName").value = "";
        document.getElementById("p_PgCt_txtNewCreditCard_BillingAddress").value = "";
        document.getElementById("p_PgCt_txtNewCreditCard_BillingZip").value = "";
    }

    return true;
}

/* Luhn algorithm number checker - (c) 2005-2008 shaman - www.planzero.org *
* This code has been released into the public domain, however please      *
* give credit to the original author where possible.                      */

function LuhnCheck(number) {
    if (number.length < 8) return false;


    // Strip any non-digits (useful for credit card numbers with spaces and hyphens)
    var number = number.replace(/\D/g, '');

    // Set the string length and parity
    var number_length = number.length;
    var parity = number_length % 2;

    // Loop through each digit and do the maths
    var total = 0;
    for (i = 0; i < number_length; i++) {
        var digit = number.charAt(i);
        // Multiply alternate digits by two
        if (i % 2 == parity) {
            digit = digit * 2;
            // If the sum is two digits, add them together (in effect)
            if (digit > 9) {
                digit = digit - 9;
            }
        }
        // Total up the digits
        total = total + parseInt(digit);
    }

    // If the total mod 10 equals 0, the number is valid
    if (total % 10 == 0) {
        return true;
    } else {
        return false;
    }
}

function ValidateCC(number) {
    $("#img_cc_ok").css("visibility", LuhnCheck(number) ? "visible" : "hidden");
}



// ****************************************************************************************************************************
// Home
// ****************************************************************************************************************************


var oldZipCode = "";
function CheckZone(ZipCode) {
    if (oldZipCode == ZipCode) return;
    oldZipCode = ZipCode;
    for (var i = 0; i < SpecialZones.length - 1; i++) {
        if (ZipCode == SpecialZones[i]) {
            document.getElementById('pnlSearch').className = "search fulladdress";
            //document.getElementById('p_PgCt_txtStreet').focus();
            //document.getElementById('p_PgCt_txtStreet').select();
            return;
        }
    }
    //document.getElementById('pnlSearch').className = "search";
}

function InitHomePage() {
    document.getElementById('p_PgCt_txtZipCode').focus();
    $("input.zip").numeric("\t");

    $.updnWatermark.attachAll();

    document.getElementById('p_PgCt_txtZipCode').focus();
}






// ****************************************************************************************************************************
// Menu Page
// ****************************************************************************************************************************

function InitMenuPage() {
    $(".menu-cont div a").each(function() {
        $(this).parent().click(function() {
            document.location = $(this).children("a")[0].href;
        });
        $(this).parent().hover(
            function() { $(this).addClass("jhover"); },
            function() { $(this).removeClass("jhover"); }
        );
    });


    StickPanelToTop("menu_panel");
    StickPanelToTop("shopping_cart");
}



// ****************************************************************************************************************************
// Menu Item Page
// ****************************************************************************************************************************

function ChangeElementClass(el, oldClass, newClass) {
    if (el == null || el.className == null) return;
    el.className = el.className.replace(new RegExp("( ?|^)" + oldClass + "\\b"), " " + newClass);
}

function SetElementClass(el, xClass) {
    if (el.className.match("( ?|^)" + xClass + "\\b")) return;
    el.className += " " + xClass;
}

function RemoveElementClass(el, xClass) {
    if (!el.className.match("( ?|^)" + xClass + "\\b")) return;
    ChangeElementClass(el, xClass, "");
}

function ValidateChoiceGroup(MenuOptionID) {
    var result = true;

    var groupDiv = document.getElementById('pc' + MenuOptionID);
    if (groupDiv == null) { alert('pc' + MenuOptionID); return; }

    var Minimum = parseInt(groupDiv.getAttribute("__minimum"));
    var Maximum = parseInt(groupDiv.getAttribute("__maximum"));

    var checkboxes = groupDiv.getElementsByTagName('input');
    var cnt = 0;

    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i].name == "c" + MenuOptionID) {
            if (checkboxes[i].checked) {
                $(checkboxes[i]).parent().addClass("nest");
                var weight = checkboxes[i].getAttribute("__weight");
                cnt += parseInt(weight);
            } else {
                $(checkboxes[i]).parent().removeClass("nest");
            }
            var pnlNestedItems = document.getElementById('p' + checkboxes[i].name + "_" + checkboxes[i].value);

            if (pnlNestedItems != null) {
                if (checkboxes[i].checked) {
                    $(pnlNestedItems).show("fast");
                    result = result && ValidateChoiceGroup(checkboxes[i].name.substring(1) + "_" + checkboxes[i].value);
                } else {
                    $(pnlNestedItems).hide("fast");
                    var nested_checkboxes = pnlNestedItems.getElementsByTagName('input');
                    for (var j = 0; j < nested_checkboxes.length; j++) {
                        nested_checkboxes[j].checked = false;
                        nested_checkboxes[j].disabled = false;
                    }
                }
            }
        }
    }

    if ((cnt >= Minimum) && (cnt <= Maximum) && result) {
        RemoveElementClass(groupDiv, 'box_orange');
        if (Minimum > 0) SetElementClass(groupDiv, 'box_green');
    } else {
        result = false;
        RemoveElementClass(groupDiv, 'box_green');
        SetElementClass(groupDiv, 'box_orange');
    }

    if (Maximum > Minimum) {
        for (var i = 0; i < checkboxes.length; i++) {
            if (checkboxes[i].name != "c" + MenuOptionID) continue;

            var weight = checkboxes[i].getAttribute("__weight");
            var doDisable = (cnt + parseInt(weight)) > Maximum;
            if (checkboxes[i].name == "c" + MenuOptionID && !checkboxes[i].checked) checkboxes[i].disabled = doDisable;
        }
    }

    RecalcPrice();

    return result;
}

function GetSubGroupPrice(groupDiv) {
    var MaxFree = parseInt(groupDiv.getAttribute("__maxfree"));
    var MaxBillable = parseInt(groupDiv.getAttribute("__maxbillable"));

    var checkboxes = groupDiv.getElementsByTagName('input');

    var optionsPrice = 0;
    var optionsWeight = 0;

    
    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i].checked && "p" + checkboxes[i].name == groupDiv.id) {
            optionsPrice += parseFloat(checkboxes[i].getAttribute("__price"));
            optionsWeight += parseInt(checkboxes[i].getAttribute("__weight"));
        }
    }

    if (optionsWeight > 0) {
        var avgOptionPrice = optionsPrice / optionsWeight;
        var BillableOptions = optionsWeight;
        if (MaxFree > 0) BillableOptions -= MaxFree;
        if (BillableOptions < 0) BillableOptions = 0;
        if (MaxBillable > 0 && BillableOptions > MaxBillable) BillableOptions = MaxBillable;

        return avgOptionPrice * BillableOptions;
    } else {
        return 0;
    }
}

function RecalcPrice() {
    var itemPrice = parseFloat(document.getElementById("item_base_price").value);

    $("#all_options div").each(function() { itemPrice += GetSubGroupPrice(this); });

    $("#item_price").text( "$" + itemPrice.toFixed(2) );
}

function InitMenuItemPage() {
    $(".quantity").numeric("\t");
    $("#all_options input").click(function() { ValidateChoiceGroup(this.name.substring(1).split('_')[0]); });
    $("#all_options input").each(function() { if (this.checked) ValidateChoiceGroup(this.name.substring(1)); });
}







// ****************************************************************************************************************************
// Restarants Page
// ****************************************************************************************************************************


function InitRestaurantsPage() {
    $("form").submit(function() { return false; });

    $(".restaurant_name").each(function() {
        $(this).parent().click(function() {
            document.location = $(this).children(".restaurant_name").children("a")[0].href;
        });
        $(this).parent().hover(function() { $(this).addClass("jhover"); }, function() { $(this).removeClass("jhover"); });
    });

    $.updnWatermark.attachAll();


    $("#txt_rsearch").keyup(function() {
        var txt = this.value.toLowerCase().replace(/ /g, "");
        var rx = new RegExp(txt, "i");

        var isOdd = true;
        var numFound = 0;
        var numHidden = 0;
        $(".restaurant_name a").each(function() {
            //if (this.innerHTML.toLowerCase().indexOf(txt) != -1)
            if (this.innerHTML.match(rx)) {
                $(this).parent().parent().show();
                numFound++;
                if (isOdd)
                    $(this).parent().parent().addClass("odd");
                else
                    $(this).parent().parent().removeClass("odd");
                isOdd = !isOdd;
            } else {
                $(this).parent().parent().hide();
                numHidden++;
            }
        });

        var pnlSearchResultInfo = document.getElementById("pnlSearchResultInfo");
        if (numHidden > 0) {
            $(".restaurants h2").hide();
            $(".restaurants h2 + table > tbody > tr > th").parent().hide();
            $(".restaurants").addClass("no_bottom_margin");
            $(".restaurants table").addClass("no_bottom_margin");

            if (pnlSearchResultInfo == null) {
                $("<div/>")
							.attr("id", "pnlSearchResultInfo")
							.insertBefore(".restaurants h2:first");
                pnlSearchResultInfo = document.getElementById("pnlSearchResultInfo");
            }

            pnlSearchResultInfo.innerHTML = "<h2>Search Result for \"" + txt + "\"</h2>";
            if (numFound == 0)
                pnlSearchResultInfo.innerHTML += "<br><p>No results were found. Try to <a href='#' onclick='$(\"#txt_rsearch\")[0].value=\"\"; $(\"#txt_rsearch\").trigger(\"keyup\"); return false;'>browse all restaurants</a>.</p>";
            $(pnlSearchResultInfo).show();
        } else {
            $(".restaurants h2").show();
            $(".restaurants h2 + table > tbody > tr > th").parent().show();
            $(".restaurants").removeClass("no_bottom_margin");
            $(".restaurants table").removeClass("no_bottom_margin");
            if (pnlSearchResultInfo != null) $(pnlSearchResultInfo).hide();
        }

        $(".content").css("min-height", $("#cuisines_panel").height() + 80);
    });

    StickPanelToTop("cuisines_panel");
}






// ****************************************************************************************************************************
// Register new customer web-control
// ****************************************************************************************************************************

function Register_ascx_InitPnlNewCustomer(txtPhone_ClientID, txtBusinessName_ClientID) {
    var el = $(txtBusinessName_ClientID);
    var pos = el.position();
    el.updnWatermark({ tagName: "<label/>", cssClass: "updnWatermark2" });
    $(".updnWatermark2").css("top", pos.top);
    $(".updnWatermark2").css("left", pos.left + 5);
    $(txtPhone_ClientID).numeric("\n");
}




// ****************************************************************************************************************************
// Login new customer web-control
// ****************************************************************************************************************************

function Login_ascx_InitPnlLogin() {
    $("#lnkRetrievePassword").click(function() { $("#pnl_login").addClass("retrieve"); return false; });
    $("#lnkRememberedPassword").click(function() { $("#pnl_login").removeClass("retrieve"); return false; });
}