var bannerIntervalID = 0;

// DOCUMENT-READY HANDLERS

// global handler for all pages
global_docready = function() {
    // Set up modal dialogs
    $(".confirmationDialog").each(function() {
        $(this).dialog({
            modal: true,
            autoOpen: false,
            resizable: false,
            draggable: false,
            width: "500px",
            buttons: {
                "続行" : function() {
                    var href = $("#hidDestination").val(); // Retrieve the destination URL and navigate there.
                    if ($(this).is("#leavingCountryDialog")) {
                        // Check to see if we're supposed to set the country cookie
                        if ($("#chkChangeCountry:checked")[0]) {
                            $.cookies.set("country", "");
                        }
                    }
                    $(this).dialog("close");
                    if (href) {
                        if ($("#hidNewWindow").val() == "1") {
                            window.open(href);
                        }
                        else {
                            location.href = href;
                        }
                    }
                },
                "取消": function() {
                    $(this).dialog("close");
                    return false;
                }
            },
            open: function() {
                var buttons = $("button", $(this).parent());
                $(buttons[0]).addClass("defaultButton").focus();
            }
        });
    });
    $("#importantMessageDialog").dialog({
        modal: true,
        autoOpen: false,
        resizable: false,
        draggable: false,
        width: "500px",
        buttons: {
            "続行" : function() {
                $(this).dialog("close");
                $.get("/confirmation-dialog-accepted.php");
                return true;
            },
            "取消": function() {
                $(this).dialog("close");
                location.href = "/";
                return true;
            }
        },
        open: function() {
            var buttons = $("button", $(this).parent());
            $(buttons[0]).addClass("defaultButton").focus();
            $(".ui-dialog-titlebar-close").hide(); // So that the dialog can only be "cancelled" via the cancel button
        }
    });
    // Set up country links to invoke modal dialog
    $(".changeCountryLink").bind("click", function() {
        $("#hidDestination").val($(this).attr("href")); // Store the destination URL in a hidden field
        $("#hidCountry").val($(this).attr("name")); // Store the country here in case we need to set the default country cookie
        $("#leavingCountryDialog").dialog("open");
        return false;
    });
    // Set up external links to invoke modal dialog
    $("a.external").attr("target", "_blank").bind("click", function() {
        $("#hidDestination").val($(this).attr("href"));
        $("#hidNewWindow").val("1");
        $("#leavingKCIDialog").dialog("open");
        return false;
    });

    if ($("#sendToFriendDialog")) {
        // Set up "send to friend" dialog
        $("#sendToFriendDialog").dialog({
            modal: true,
            autoOpen: false,
            resizable: false,
            draggable: false,
            width: "500px",
            open: function() {
                $("#txtYourEmail").focus();
                $("#hidSendToFriendTitle").val(document.title);
            }
        });
        // Set up "send to friend" link to invoke dialog
        $(".sendToFriend a").bind("click", function() {
            $("#sendToFriendDialog").dialog("open");
        });

        // Show a friendly message in the "send to a friend" textarea if it's blank
        $("#txtSendToAFriendMessage").bind("focus", function() {
            if ($(this).hasClass("empty")) {
                $(this).removeClass("empty").val("");
            }
        }).bind("blur", function() {
            if ($.trim($(this).val()) == "") {
                $(this).addClass("empty").val("ここにメッセージを入力してください");
            }
        });
    }

    // Set up terms of use and privacy policy modal dialogs
    $("#termsAndConditionsDialog").dialog({
        modal: true,
        autoOpen: false,
        resizable: false,
        draggable: false,
        width: "630px",
        open: function() {
            $("a.bttLink", this).bind("click", function() {
                $("#termsAndConditionsDialogInner").scrollTop(0);
                return false;
            });
        }
    });
    $(".termsLink").bind("click", function() {
        $("#termsAndConditionsDialog").dialog("open");
    });
    $("#privacyPolicyDialog").dialog({
        modal: true,
        autoOpen: false,
        resizable: false,
        draggable: false,
        width: "630px",
        open: function() {
            $("a.bttLink", this).bind("click", function() {
                $("#privacyPolicyDialogInner").scrollTop(0);
                return false;
            });
        }
    });
    $(".privacyLink").bind("click", function() {
        $("#privacyPolicyDialog").dialog("open");
    });
}

// index
index_docready = function() {
    // Set up banner area
    $("#btnNextBanner").bind("click", function() {
        goto_next_banner();
        return false;
    });
    $("#bannerNav li a").each(function(i) {
        $(this).bind("click", function() {
            goto_banner(i);
            return false;
        });
    });
    $("#banners .banner:first").show();
    goto_banner(0);
};

goto_next_banner = function() {
    var curVis = $("#banners .banner:visible")[0];
    var banners = $("#banners .banner");
    var curIdx = banners.index(curVis);
    var nextIdx = (curIdx + 1) % banners.length;
    goto_banner(nextIdx);
}

goto_banner = function(idx) {
    clearInterval(bannerIntervalID);
    bannerIntervalID = setInterval("goto_next_banner()", 7000); // auto-rotate the banners every 7 seconds
    var curVis = $("#banners .banner:visible")[0];
    var banners = $("#banners .banner");
    var curIdx = banners.index(curVis);
    if (curIdx != idx) {
        if (is_ieLT7()) {
            $(curVis).hide(); // IE 6 is terrible
        }
        else {
            $(curVis).fadeOut();
        }
        var curClass = "b" + curIdx;
        var nextClass = "b" + idx;
        $("#bannerNav ." + curClass + "_on").addClass(curClass).removeClass(curClass + "_on").removeClass("on");
        $("#bannerNav ." + nextClass).addClass(nextClass + "_on").addClass("on").removeClass(nextClass);
        if (is_ieLT7()) {
            $("#banners .banner:eq(" + idx + ")").show(); // IE 6 is terrible
        }
        else {
            $("#banners .banner:eq(" + idx + ")").fadeIn();
        }
    }
}

// vac_therapy
vac_therapy_docready = function() {
    $("#tabs").tabs().show();
}

// vac_therapy_subpage - any subpage - this sets up the left nav
vac_therapy_subpage_docready = function() {
    $(".subCategory ul").hide();

    $(".subCategory > a, .subCategoryOn > a").bind("click", function() {
        $(this).siblings("ul").slideToggle(500);
        return false;
    });
}

// vac_therapy_about
vac_therapy_about_docready = function() {
    vac_therapy_subpage_docready();
    init_img_dialogs();
}

// generic handler for vac product pages
vac_product_docready = function() {
    vac_therapy_subpage_docready();
    init_img_dialogs();
    if ($("#tabs")[0]) $("#tabs").tabs().show();
}

// contact_us
contact_us_docready = function() {
    // Show a friendly message in the textarea if it's blank
    $("textarea").bind("focus", function() {
        if ($(this).hasClass("empty")) {
            $(this).removeClass("empty").val("");
        }
    }).bind("blur", function() {
        if ($.trim($(this).val()) == "") {
            $(this).addClass("empty").val("ここにメッセージを入力してください");
        }
    });
}

// PRODUCT DISCLAIMER FUNCTIONS
show_product_disclaimer = function() {
    $("#importantMessageDialog").dialog("open");
}

// SEND TO FRIEND FORM FUNCTIONS
validate_sendtofriend = function() {
    try {
        $(".fieldError").unbind("blur", field_error_blur).removeClass("fieldError");
        $("#sendToFriendForm input.requiredField").each(function() {
            if ($(this).attr("type") == "text" && $.trim($(this).val()) == "") {
                $(this).addClass("fieldError");
            }
            else if ($(this).attr("type") == "checkbox" && !$(this).is(":checked")) {
                $(this).parent().addClass("fieldError");
            }
            else if ($(this).attr("id") == "txtYourEmail") {
                var email = $.trim($(this).val());
                var re = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
                if (!re.test(email)) {
                    $(".invalidEmailAddress", $(this).parent()).show();
                    $(this).addClass("fieldError");
                }
            }
        });
        // Set up required fields to turn off their error notification if the user
        // fills out a value
        // Set up required fields to turn off their error notification if the user
        // fills out a value
        $("#sendToFriendForm .fieldError").each(function() {
            if ($(this).hasClass("agreeCheckbox")) {
                $("input:first", $(this)).bind("blur", field_error_blur);
            }
            else {
                $(this).bind("blur", field_error_blur);
            }
        });

        if ($("#sendToFriendForm .fieldError")[0]) {
            $("#sendToFriendForm .fieldError")[0].focus();
            return false;
        }
    }
    catch (ex) {
        if (console) {
            console.log(ex);
        }
        return false;
    }
    return true;
}

// CONTACT US FORM FUNCTIONS
validate_contact_us = function() {
    try {
        $(".fieldError").unbind("blur", field_error_blur).removeClass("fieldError");
        $("#contactUsForm input.requiredField, #contactUsForm textarea.requiredField").each(function() {
            if ($(this).attr("type") == "text" && $.trim($(this).val()) == "") {
                $(this).addClass("fieldError");
            }
            else if ($(this).attr("type") == "checkbox" && !$(this).is(":checked")) {
                $(this).parent().addClass("fieldError");
            }
            else if ($(this).attr("id") == "txtMessage") {
                var val = $.trim($(this).val());
                if (val == "" || val == "ここにメッセージを入力してください") {
                    $(this).addClass("fieldError");
                }
            }
            else if ($(this).attr("id") == "txtEmail") {
                var email = $.trim($(this).val());
                var re = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
                if (!re.test(email)) {
                    $("#invalidEmailAddress").show();
                    $(this).addClass("fieldError");
                }
            }
        });
        // Set up required fields to turn off their error notification if the user
        // fills out a value
        $("#contactUsForm .fieldError").each(function() {
            if ($(this).hasClass("agreeCheckbox")) {
                $("input:first", $(this)).bind("blur", field_error_blur);
            }
            else {
                $(this).bind("blur", field_error_blur);
            }
        });

        if ($("#contactUsForm .fieldError")[0]) {
            $("#contactUsForm .fieldError")[0].focus();
            return false;
        }
        else {
            return true;
        }
    }
    catch (ex) {
        if (console) {
            console.log(ex);
        }
        return false;
    }
}

field_error_blur = function() {
    if ($(this).attr("type") == "text" && $.trim($(this).val()) != "") {
        if ($(this).attr("id") == "txtEmail") {
            var email = $.trim($(this).val());
            var re = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
            if (re.test(email)) {
                $("#invalidEmailAddress").hide();
                $(this).removeClass("fieldError");
            }
        }
        else {
            $(this).removeClass("fieldError");
        }
    }
    else if ($(this).attr("type") == "checkbox" && $(this).is(":checked")) {
        $(this).parent().removeClass("fieldError");
    }
    else if ($(this).attr("id") == "txtMessage") {
        var val = $.trim($(this).val());
        if (val != "" && val != "ここにメッセージを入力してください") {
            $(this).removeClass("fieldError");
        }
    }
}

// UTILITY FUNCTIONS
// Detect IE 4 - 6
is_ieLT7 = function() {
    // document.all is IE 4+ only, so all other browsers will return false
    // the other clause is only true if IE 7+, so we want this to be false so its inverse is true
    return (document.all && !(document.documentElement && typeof document.documentElement.style.maxHeight!="undefined"));
}

init_img_dialogs = function() {
    $(".imgDialog").each(function() {
        $(this).dialog({
            modal: true,
            autoOpen: false,
            resizable: false,
            draggable: false,
            width: $("img:first", this).width() + 30
        });
    });
    $(".imgDialogLink").bind("click", function() {
        var href = $(this).attr("href");
        $(href + "_dialog").dialog("open");
        return false;
    });
}