var proLinksTimer = null;
var whatImg = '';

function positionToMiddle(whichLightbox) {
	var lightboxHeight = 0;
	lightboxHeight = $('#' + whichLightbox).height();
	lightboxHeight = Math.round(lightboxHeight/2);
	$('#' + whichLightbox).css("top", "50%")
	$('#' + whichLightbox).css("margin-top", "-" + lightboxHeight + "px")
}

/**
 * This function sets a universal height for each individual result so layout will not break
 */
function showMoreOptions() {
    $('#moreOptions').slideToggle();
    $('#showMoreOptions').hide();
    $('#showLessOptions').show();
}

function showLessOptions() {
    $('#moreOptions').slideToggle();
    $('#showMoreOptions').show();
    $('#showLessOptions').hide();
}

function textAreaMax() {
    if(this.value.length > 1000) {
        this.value = this.value.substring(0,999);
    }
}

(function($){
    $(function() {
        $("#message").bind("keyup",textAreaMax);
        $("#message").bind("change",textAreaMax);
        $('input.button_rollover,input.button_back_rollover,div.btn-back,div.btn-send,div.btn-top,input.submitbutton,div.mira-productResults-compareNow a').hover(function() {
			$(this).css('background-color','#9D9C9C');
			$(this).children('a').css('text-decoration','underline')
		}, function() {
			$(this).css('background-color','#E6E6E6');
			$(this).children('a').css('text-decoration','none')
		});

		$('img.btn-print, img.btn-printFaqs, img.btn-email, .rollover').hover(function() {
			$(this).attr("src",$(this).attr("src").replace("-off","-on"));
		}, function() {
			$(this).attr("src",$(this).attr("src").replace("-on","-off"));
		});

		$('#miraTrendArticle-mayWeSuggest').css('height',$('#miraTrendArticle-copyArea').height() + 'px');

		// Set correct left nav height
		var leftNavHeight = $('#mira-leftnav').height();
		var contentHeight = $('.content-withLeftNav #mira-contentarea').height();
		if (leftNavHeight < contentHeight) {
			$('#mira-leftnav').css("height", contentHeight+'px')
		}

        $(".mira-dropdown").bgiframe();

        // A quick jquery plugin to add functions that dropdown menus with a bit of delay
        (function() {
            var OPEN_DELAY = 100;
            var CLOSE_DELAY = 100;
            $.fn.extend({
                showDropDown : function(speed, callback) {
                    this.each(function() {
                        var elem = this;
                        clearTimeout($(elem).data("DD_openTimer"));
                        clearTimeout($(elem).data("DD_closeTimer"));
                        var openTimer = setTimeout(function() {
                            $(elem).not(":animated").slideDown(speed, callback);
                        }, OPEN_DELAY);
                        $(elem).data("DD_openTimer", openTimer);
                    });
                    return this;
                },
                hideDropDown : function(speed, callback) {
                    this.each(function() {
                        var elem = this;
                        clearTimeout($(elem).data("DD_openTimer"));
                        var closeTimer = setTimeout(function() {
                            $(elem).slideUp(speed, callback);
                        }, CLOSE_DELAY);
                        $(elem).data("DD_closeTimer", closeTimer);
                    });
                    return this;
                }
            });
        })();

        //Dropdown nav script
        $('div.navNode, div.navNode-last').hover(
			function() {
				$(this).css('background-color','#FF0000');
				var whichdropdown = $(this).find('a.navNode-link').attr('id');
                $('div.navNode .mira-dropdown, div.navNode-last .mira-dropdown').not('#mira-dropdown-' + whichdropdown).hideDropDown(150);
                $('#mira-dropdown-' + whichdropdown).showDropDown(150);
			}, function() {
                $('div.navNode .mira-dropdown, div.navNode-last .mira-dropdown').hideDropDown(150);
            }
		);

        // Rollovers
        $(".rollover-off").mouseover(function() {
            if ($(this).siblings(".rollover-on").size() == 0) {
                return;
            }
            var display = $(this).css("display");
            $(this).css("display", "none");
            $(this).siblings(".rollover-on").css("display", display);
        });

        $(".rollover-on").mouseout(function() {
            $(this).css("display", "");
            $(this).siblings(".rollover-off").css("display", "");
        });

		// Professional Quick Links
		$('a.proList').mouseover(
			function() {
				clearTimeout(proLinksTimer);
				$('#footer-proLinks').slideDown();
			}
		);
		$('a.proList').mouseout(
			function() {
				if (proLinksTimer) {clearTimeout(proLinksTimer)}
				proLinksTimer = setTimeout('$("#footer-proLinks").slideUp()',250);
			}
		);
		$('#footer-proLinks').mouseover(
			function() {
				if (proLinksTimer) { clearTimeout(proLinksTimer); }
			}
		);

		$("#footer-proLinks").mouseout(
			function() {
				if (proLinksTimer) {clearTimeout(proLinksTimer)}
				proLinksTimer = setTimeout('$("#footer-proLinks").slideUp()',250);
			}
		);


		// Inspiration Dropdowns Scripts
		$('div.inspiration-nav').hover(
			function() {
				$(this).children('.inspiration-dropdown').showDropDown(150);
			}, function() {
				$(this).children('.inspiration-dropdown').hideDropDown(150);
			}
		);

		/**/
		$('.faultDiagnosis-problem a.expandProblem').click(
			function() {
				$(this).parents('.faultDiagnosis-problem').children('.faultDiagnosis-cause').slideToggle();
			}
		);

		// Lightbox overlay script
		$('.closeLightbox a,#lightbox-overlay').click(
			function() {
				$('link[rel*=style]').each(function(i) {
		            //if ($(this).attr('href').indexOf('printLightbox.css') > -1) $(this).attr('href', 'css/print.css');
		        });
                $(this).parents(".lightbox-content:first").hideLightbox();
				$("#emailToAFriendForm input, #emailToAFriendForm textarea").val("");
				$("#emailFriend-Form").css("display","block");
				$("#emailFriend-success").css("display","none");
                return false;
            }
		);

		// Lightbox for email a friend  script
		$('#prodDtl-email').click(
			function() {
				 $("#lightbox-email").children('btn-printMe').remove();
                $('#lightbox-email').showLightbox();
                return false;
            }
		);
		// Lightbox for product detail print friendly script
		$('.btn-print').click(
			function() {
                $('#lightbox-printDetail').showLightbox();
				$('link[rel*=style]').each(function(i) {
					//if ($(this).attr('href').indexOf('print.css') > -1) $(this).attr('href', '/css/printLightbox.css');
				});
                return false;
            }
		);

        // Filter Explanation Lighboxes
        $("a.icon-definition").click(function() {
            var filterName = $(this).attr("rel");
			if(filterName == 'APPROVALS') {
				$("#lightbox-scrollableArea-prodApprovals").showLightbox(function() {
					$(this).find('.lightbox-scrollMe-content').css('display','block');
				 	$(this).find('.lightbox-scrollMe').jScrollPane({showArrows:false, scrollbarWidth:10});
	            });
			} else {
	            $(".filter-explanation[title='" + filterName + "']").showLightbox(function() {
	                $(this).find('.lightbox-scrollMe-content').css('display','block');
	                $(this).find('.lightbox-scrollMe').jScrollPane({showArrows:false, scrollbarWidth:10});
	            });
			}
            return false;
        });

        $('.mira-productResults-sortingOptions').hover(
                function() {
                    $(this).children('.sortOrder-sortOptions').showDropDown(150);
                }, function() {
            		$(this).children('.sortOrder-sortOptions').hideDropDown(150);
        }
                );

        $('.sortOrder-sortOptions a').click(function() {
            $('.sortOrder-sortOptions a').removeClass('active');
			var activeSort = $(this).attr('id');
			activeSort = activeSort.substring(0,activeSort.length-1)
            $('#' + activeSort + '1').addClass('active');
			$('#' + activeSort + '2').addClass('active');
        });

        // Enlarged images
        $("#miraTrendArticle-bannerImages a,.pressPhoto a,#waterSystems-content .supportApproval-logo a").click(function() {
            whatImg = $(this).attr('id');
			if (whatImg == '' || whatImg == null) {
                return false;
            }
            $("#lightbox-imageEnlarge-single img#lightbox-enlargedImage").attr("src",whatImg);
            $("#lightbox-imageEnlarge-single").showLightbox();
            return false;
        });

        // Press photo
        //$("#miraTrendArticle-bannerImages a, .pressPhoto a").click(function() {
            //$(this).find(".enlarge a").triggerHandler("click"); 
        //});
    });


    // Email to a friend
    $(document).ready(function() {

        $("#emailToAFriendForm").attachAjaxValidator({
            url : "/ajax/emailToAFriendAjaxValidator.htm"
        });

        $("#emailToAFriendForm :text, #emailToAFriendForm textarea").bind("validationSuccess", function(event){
            var name = $(this).attr("name");
            $(this).prev("label").removeClass("error");
			$(this).removeClass("errorField");
        });

        $("#emailToAFriendForm :text, #emailToAFriendForm textarea").bind("validationFailure", function(event, errors){
            var name = $(this).attr("name");
            $(this).prev("label").addClass("error");
			$(this).addClass("errorField");
			$("#errorMsg").show();
        });

        $("#emailToAFriendForm :text, #emailToAFriendForm textarea").bind("validationReset", function(event){
            $(this).prev("label").removeClass("error");
        });

        var formBlockSubmit = false;
        $("#emailToAFriendForm").bind("validationSuccess", function(event) {
            if (!formBlockSubmit) {

           var form = $("#emailToAFriendForm");
                form.find(".btn-send").addClass("sending");
                form.find(".loadingSpinner").css("display", "block");
                form.find("#emailForm-copyToMyself .error").css("display", "");
                formBlockSubmit = true;
                $.ajax({
                    type : "POST",
                    dataType : "json",
                    url : form.attr("action"),
                    data : form.serialize(),
                    error : function() {
                        form.find(".btn-send").removeClass("sending");
                        form.find(".loadingSpinner").css("display", "");
                        form.find("#emailForm-copyToMyself .error").fadeIn();
                    },
                    success : function(data) {
                        formBlockSubmit = false;
                        form.find(".btn-send").removeClass("sending");
                        form.find(".loadingSpinner").css("display", "");

                        if (data.submitted) {
							$("#emailFriend-Form").fadeOut();
                            $("#emailFriend-success").fadeIn();
                            setTimeout(function() {
                                $("label").removeClass("error");
								$("input").removeClass("errorField");
								$("#errorMsg").css('display','none');
                            }, 500);
                        } else {
                            $("#emailToAFriendForm").triggerHandler("validationFailure", [data.globalErrors]);
                        }
                    }
                });
            }
        });

        $("#emailToAFriendForm div.btn-send").click(function() {
            $("#emailToAFriendForm").doValidation();
            return false;
        });
    });


    $(document).ready(function() {

        // Attach validators to the various forms of the site
        attachValidator("#contact", "/ajax/contactUsAjaxValidator.htm");
        attachValidator("#requestAnEngineer", "/ajax/servicevisitAjaxValidator.htm");
        attachValidator("#unsubscribe", "/ajax/unsubscribeAjaxValidator.htm");
        attachValidator("#guarantee", "/ajax/guaranteeRegistrationAjaxValidator.htm");
        attachValidator("#spareparts", "/ajax/contactUsAjaxValidator.htm");
        attachValidator("#brochure", "/ajax/requestABrochureAjaxValidator.htm");
        attachValidator("#training", "/ajax/trainingRegistrationAjaxValidator.htm");
        attachValidator("#headStartRegistration", "/ajax/headStartRegistrationAjaxValidator.htm");

        function attachValidator(selector, ajaxValidationUrl) {
            var formElem = $(selector);
            if (formElem.size() == 0) {
                return;
            }
            formElem.attachAjaxValidator({
                url : ajaxValidationUrl
            });

            formElem.find(":text, :select, textarea, :checkbox").bind("validationSuccess", function(event, globalErrors, fieldErrorMap){
                var name = $(this).attr("name");
                $(this).parent(".formfield").children("label").removeClass("error");
                $(this).parents(".formfield-checkboxes").find("p:first").removeClass("error");
                $(this).removeClass("errorField");
                
                var phoneNumberInput = formElem.find("#phoneNumber");
                var mobileNumberInput = formElem.find("#mobileNumber");
                if (phoneNumberInput[0].value == '' && mobileNumberInput[0].value != '' &&
                        (mobileNumberInput[0].value).match(/[0-9]*/)) {
                    phoneNumberInput.prev("label").removeClass("error");
                    phoneNumberInput.removeClass("errorField");
                }
                if (mobileNumberInput[0].value == ''  && phoneNumberInput[0].value != '' &&
                        (phoneNumberInput[0].value).match(/[0-9]*/)) {
                    mobileNumberInput.prev("label").removeClass("error");
                    mobileNumberInput.removeClass("errorField");
                }
                
                $(this).parents("form:first").prev("p.error").children("div.fieldError-" + name).fadeOut(function() {
                    $(this).remove();
                });

                var hasInvalid = false;
                var hasUnfilledRequired = false;
                for (var key in fieldErrorMap) {
                    var errorArr = fieldErrorMap[key];
                    for (var i = 0; i < errorArr.length; i++) {
                        if (errorArr[i] == 'INVALID') {
                            hasInvalid = true;
                        }
                        if (errorArr[i] == 'REQUIRED') {
                            hasUnfilledRequired = true;
                        }
                    }
                }

                if (!hasInvalid) {
                    $("#invalidErrorMsg").hide();
                }
                if (!hasUnfilledRequired) {
                    $("#errorMsg").hide();
                }
                if (!hasInvalid && !hasUnfilledRequired) {
                    $("p.errorMsg").hide();
                }
            });

            formElem.find(":text, :select, :textarea, :radio, :checkbox").bind("validationFailure", function(event, errors, globalErrors, fieldErrorMap){
                $(this).parents(".formfield").children("label:first").addClass("error");
                $(this).parents(".formfield-checkboxes").children("p:first").addClass("error");
                $(this).addClass("errorField");
                
                if(errors[0] == "INVALID") {
                    $("p.errorMsg").show();
                    $("#invalidErrorMsg").show();
                }
                if(errors[0] == "REQUIRED") {
                    $("p.errorMsg").show();
                    $("#errorMsg").show();
                }
            });

            formElem.find("div.btn-send").click(function() {
                formElem.doValidation();
                return false;
            });

            formElem.bind("validationSuccess", function(event) {
                formElem[0].submit();
            });
        }
    });


})(jQuery);



