﻿// JavaScript Document


// Drop down menu variables
var timeout = 0; //500
var closetimer = 0;
var ddmenuitem = 0;


// Drop down menu functions
function jsddm_open() {
    jsddm_canceltimer();
    jsddm_close();
    ddmenuitem = $(this).find('ul').css('visibility', 'visible');
    if ($(this).attr("class") == "navproducts" && $.browser.msie && $.browser.version <= 6) {
        $("select#title").css('visibility', 'hidden');
    }
}

function jsddm_close() {
    if (ddmenuitem) ddmenuitem.css('visibility', 'hidden');
    if ($.browser.msie && $.browser.version <= 6) {
        $("select#title").css('visibility', 'visible');
    }
}

function jsddm_timer() {
    closetimer = window.setTimeout(jsddm_close, timeout);
}

function jsddm_canceltimer() {
    if (closetimer) {
        window.clearTimeout(closetimer);
        closetimer = null;
    }
}


// Start jQuery
$(document).ready(function () {

    // Initialise scrolling logos
    $("#scroller").simplyScroll({
        autoMode: 'loop',
        frameRate: '45'
    });


    // Bind the menu elements to the drop-down menu functions
    $('#menu > li').bind('mouseover', jsddm_open);
    $('#menu > li').bind('mouseout', jsddm_timer);


    // Replace the default action for link anchors to scroll smoothly instead of jumping
    $('a[href*=#]').click(function () {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var $target = $(this.hash);
            $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
            if ($target.length) {
                var targetOffset = $target.offset().top - 20;
                $('html,body').animate({ scrollTop: targetOffset }, 1000);
                return false;
            }
        }
    });


    // Initialise the cycling of universal selling points
    $('.cycle').cycle({
        fx: 'fade',
        /*speed: 'fast',*/
        timeout: 5000,
        pause: 1,
        pauseOnPagerHover: true
    });


    // Initialise animation for the FAQs section
    var old = null;
    $('ul.faqs h5').click(function () {
        var x = this;
        if (old != null) {
            if (old[0] != $(this.parentNode).find("div")[0]) {
                $(old.parentNode).find("h5").toggleClass("selected", false);
                old.slideUp("fast", function () {
                    $(x.parentNode).find("div").slideDown("fast");
                });
            } else {
                return;
            }
        } else {
            $(this.parentNode).find("div").slideDown("fast");
        }
        $(this).toggleClass("selected", true);
        old = $(this.parentNode).find("div");
    }).mouseover(function () {
        $(this).toggleClass("hover", true);
    }).mouseout(function () {
        $(this).toggleClass("hover", false);
    }).css("cursor", "pointer");
    $('ul.faqs div').hide();


    // Validate contact form on on keyup and submit
    $("#contactform").validate({
        rules: {
            name: "required",
            email: {
                required: true,
                email: true
            },
            phone: "required",
            reason: "required",
            message: "required"
        },
        messages: {
            name: "",
            email: {
                required: "",
                email: ""
            },
            phone: {
                required: ""
            },
            reason: {
                required: ""
            },
            message: {
                required: ""
            }
        },
        errorElement: "span",
        invalidHandler: function (form, validator) {
            var errors = validator.numberOfInvalids();
            if (errors) {
                var message = (errors == 1 ? 'You missed 1 required field. It has been highlighted for you.' : 'You missed ' + errors + ' required fields. They have been highlighted for you.');
                $("#contactform div.errorsummary p").html(message);
                $("#contactform div.errorsummary").show();
            } else {
                $("#contactform div.errorsummary").hide();
            }
        }
    });


    // Validate the "Get A Quote" form
    $("#getquote").validate({
        rules: {
            title: "required",
            othertitle: {
                required: function (element) {
                    return $("#title").val() == "Other";
                }
            },
            firstname: "required",
            lastname: "required",
            dob_day: "required",
            dob_month: "required",
            dob_year: "required",
            smoker: "required",
            telephone: "required",
            email: {
                required: true,
                email: true
            },
            policy: "required",
            jointtitle: {
                required: function (element) {
                    return $("input[name=policy]:checked").val() == 2;
                }
            },
            jointothertitle: {
                required: function (element) {
                    return ($("input[name=policy]:checked").val() == 2 && $("#jointtitle").val() == "Other");
                }
            },
            jointfirstname: {
                required: function (element) {
                    return $("input[name=policy]:checked").val() == 2;
                }
            },
            jointlastname: {
                required: function (element) {
                    return $("input[name=policy]:checked").val() == 2;
                }
            },
            jointdob_day: {
                required: function (element) {
                    return $("input[name=policy]:checked").val() == 2;
                }
            },
            jointdob_month: {
                required: function (element) {
                    return $("input[name=policy]:checked").val() == 2;
                }
            },
            jointdob_year: {
                required: function (element) {
                    return $("input[name=policy]:checked").val() == 2;
                }
            },
            jointsmoker: "required",
            covertype: "required",
            amount: {
                required: true,
                number: true
            },
            term: "required",
            howhear: "required"
        },
        messages: {
            title: "",
            othertitle: "",
            firstname: "",
            lastname: "",
            dob_day: "",
            dob_month: "",
            dob_year: "",
            smoker: "",
            telephone: "",
            email: {
                required: "",
                email: ""
            },
            policy: "",
            jointtitle: "",
            jointothertitle: "",
            jointfirstname: "",
            jointlastname: "",
            jointdob_day: "",
            jointdob_month: "",
            jointdob_year: "",
            jointsmoker: "",
            covertype: "",
            amount: {
                required: "",
                number: ""
            },
            term: "",
            howhear: ""
        },
        errorElement: "span",
        invalidHandler: function (form, validator) {
            var errors = validator.numberOfInvalids();
            if (errors) {
                var message = (errors == 1 ? 'You missed 1 required field. It has been highlighted for you.' : 'You missed ' + errors + ' required fields. They have been highlighted for you.');
                $("#getquote div.errorsummary p").html(message);
                $("#getquote div.errorsummary").show();
            } else {
                $("#getquote div.errorsummary").hide();
            }
        }
    });


    // Hide the "other title" field by default
    if ($("#title").val() != "Other") {
        $("#othertitle").hide();
        $("#othertitle").val('');
    }
    // If the "title" option is changed to "other" then the "other title" field needs to be shown, otherwise it needs to be hidden
    $("#title").change(function () {
        if ($(this).val() == "Other") {
            $("#othertitle").fadeIn("fast");
        } else {
            if (!$("#othertitle").is(':hidden')) {
                $("#othertitle").fadeOut("fast");
                $("#othertitle").val('');
            }
        }
    });
    // Make sure to validate the "other title" field if the "title" is set to "other"
    $("#title").change(function () {
        $("#othertitle").valid();
    });


    // If a "single policy" is chosen then hide the extra fields
    if ($("input[name=policy]:checked").val() != 2) {
        $("#jointdetails").hide();
    }
    // If a "policy" option is changed to "joint" then display the extra policy holder's fields, otherwise hide them again
    $("input[name=policy]").click(function () {
        if ($(this).val() == 2) {
            $("#jointdetails").slideDown();
        } else {
            $("#jointdetails").slideUp();
        }
    });


    // Hide the "other title" field for the joint policy holder by default
    if ($("#jointtitle").val() != "Other") {
        $("#jointothertitle").hide();
        $("#jointothertitle").val('');
    }
    // If the "title" option is changed to "other" then the "other title" field needs to be shown, otherwise it needs to be hidden
    $("#jointtitle").change(function () {
        if ($(this).val() == "Other") {
            $("#jointothertitle").fadeIn("fast");
        } else {
            if (!$("#jointothertitle").is(':hidden')) {
                $("#jointothertitle").fadeOut("fast");
                $("#jointothertitle").val('');
            }
        }
    });
    // Make sure to validate the "other title" field if the "title" is set to "other"
    $("#jointtitle").change(function () {
        $("#jointothertitle").valid();
    });


    // Create the modal backdrop on document load so all modal tooltips can use it
    $('<div id="blanket">')
		.css({
		    position: 'absolute',
		    top: 0, //$(document).scrollTop(), // Use document scrollTop so it's on-screen even if the window is scrolled
		    left: 0,
		    height: $(document).height(), // Span the full document height...
		    width: '100%', // ...and full width

		    opacity: 0.5, // Make it slightly transparent
		    backgroundColor: 'black',
		    zIndex: 5000  // Make sure the zIndex is below 6000 to keep it below tooltips!
		})
		.appendTo(document.body) // Append to the document body
		.hide(); // Hide it initially


    // Create qTip tooltips for all matching elements
    $("input[type=text][title], input[type=password][title], textarea[title]").qtip({
        show: 'focus',
        hide: 'blur',
        style: {
            name: 'green',
            tip: true
        },
        position: {
            corner: {
                target: 'rightMiddle',
                tooltip: 'leftMiddle'
            }
        }
    });
    $('a[title]:not(.social), select[title], acronym[title], object[title]').qtip({
        style: {
            name: 'green',
            tip: true
        },
        position: {
            corner: {
                target: 'topMiddle',
                tooltip: 'bottomLeft'
            }
        }
    });
    $('a.social[title]').qtip({
        style: {
            name: 'green',
            tip: true
        },
        position: {
            corner: {
                target: 'topMiddle',
                tooltip: 'bottomRight'
            }
        }
    });


    // Initialise the Callback popup
    $("div.popup").hide();


    // Show the callback popup when the callback button is clicked
    $("a[rel=callback]").click(function () {
        $("#blanket").fadeIn("fast");
        $("div.popup").fadeIn("fast");
        $("div.popup").css({
            left: ($(document).width() - $("div.popup").width()) / 2,
            top: ($(document).scrollTop() + $("div.popup").height()) / 2
        });
    });


    // Make the close button on the popup, close the popup
    $("div.popup-close").click(function () {
        $("div.popup").fadeOut("fast");
        $("#blanket").fadeOut("fast");
    });


    // Override the default action of the form so that we can use an ajax submission instead
    $("#callbackform").submit(function (event) {
        event.preventDefault();

        // Check the form is valid and post the result int othe validator variable
        var validator = $("#callbackform").validate({
            rules: {
                cbfirstname: "required",
                cblastname: "required",
                cbtelephone: "required",
                cbmobile: {
                    required: false
                },
                cbemail: {
                    required: false,
                    email: true
                }
            },
            messages: {
                cbfirstname: "",
                cblastname: "",
                cbtelephone: "",
                cbmobile: "",
                cbemail: {
                    required: "",
                    email: ""
                }
            },
            errorElement: "span",
            invalidHandler: function (form, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                    var message = (errors == 1 ? 'You missed 1 required field. It has been highlighted for you.' : 'You missed ' + errors + ' required fields. They have been highlighted for you.');
                    $("#callbackform div.errorsummary p").html(message);
                    $("#callbackform div.errorsummary").show();
                } else {
                    $("#callbackform div.errorsummary").hide();
                }
            }
        }).form();

        // If the form is valid then run the form submission using ajax
        if (validator) {
            $("#callbackform div.controls").prepend('<img src="images/loading.gif" height="16" width="16" alt="Loading..." />');
            $.post("/ajax.callback.php", { cbfirstname: $("#cbfirstname").val(), cblastname: $("#cblastname").val(), cbtelephone: $("#cbtelephone").val(), cbmobile: $("#cbmobile").val(), cbemail: $("#cbemail").val(), MM_REQUEST: 'callback' }, function (result) {
                $("div.popup-content").html(result);
            });
        }

        return false; // Make sure that the form doesn't use the default action
    });


    // Create the sliding panel animations based on what classes are set
    // To switch directions up/down and left/right just place a "-" in front of the top/left attribute  
    // Vertical Sliding  
    $('.boxgrid.slidedown').hover(function () {
        $(".cover", this).stop().animate({ top: $(this).height() }, { queue: false, duration: 300 });
    }, function () {
        $(".cover", this).stop().animate({ top: '0px' }, { queue: false, duration: 300 });
    });
    // Horizontal Sliding  
    $('.boxgrid.slideright').hover(function () {
        $(".cover", this).stop().animate({ left: $(this).width() }, { queue: false, duration: 300 });
    }, function () {
        $(".cover", this).stop().animate({ left: '0px' }, { queue: false, duration: 300 });
    });
    // Diagnal Sliding  
    $('.boxgrid.thecombo').hover(function () {
        $(".cover", this).stop().animate({ top: $(this).height(), left: $(this).width() }, { queue: false, duration: 300 });
    }, function () {
        $(".cover", this).stop().animate({ top: '0px', left: '0px' }, { queue: false, duration: 300 });
    });
    // Partial Sliding (Only show some of background)  
    $('.boxgrid.peek').hover(function () {
        $(".cover", this).stop().animate({ top: '90px' }, { queue: false, duration: 160 });
    }, function () {
        $(".cover", this).stop().animate({ top: '0px' }, { queue: false, duration: 160 });
    });
    // Full Caption Sliding (Hidden to Visible)  
    $('.boxgrid.captionfull').hover(function () {
        var scrollto = $(this).height() - $(".cover", this).outerHeight();
        $(".cover", this).stop().animate({ top: scrollto }, { queue: false, duration: 160 });
    }, function () {
        $(".cover", this).stop().animate({ top: $(this).height() }, { queue: false, duration: 160 });
    });
    // Caption Sliding (Partially Hidden to Visible)  
    $('.boxgrid.caption').hover(function () {
        var scrollto = $(this).height() - $(".cover", this).outerHeight();
        $(".cover", this).stop().animate({ top: scrollto }, { queue: false, duration: 160 });
    }, function () {
        var scrollto = $(this).height() - 25;
        $(".cover", this).stop().animate({ top: scrollto }, { queue: false, duration: 160 });
    });
});

// Close the popup menu when a link is clicked
document.onclick = jsddm_close;


