// Initial variable setup
var whichdropdown = '';
var quickfinderCategoryNames = new Array();
var openEngineIdentificationTimeout;
var closeEngineIdentificationTimeout;
var seriesSelectElementOnManualsPage;
var hpSelectElementOnManualsPage;
var shaftSelectElementOnManualsPage;

function enableAlphaImages(){
    if ($.browser.msie && (parseInt(jQuery.browser.version) < 7)) {
        var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
        var itsAllGood = (rslt != null && Number(rslt[1]) < 7);
        if (itsAllGood) {
            for (var i=0; i<document.all.length; i++){
                var obj = document.all[i];
                var bg = obj.currentStyle.backgroundImage;
                var img = document.images[i];
                if (bg && bg.match(/\.png/i) != null) {
                    var img = bg.substring(5,bg.length-2);
                    var offset = obj.style["background-position"];
                    obj.style.filter =
                    "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+img+"', sizingMethod='crop')";
                    obj.rel = img;
                    obj.style.backgroundImage = "url('/common/images/spacer.gif')";
                    obj.style["background-position"] = offset; // reapply
                } else if (img && (img.src.match(/\.png$/i) != null || img.src.match(/fmt=png-alpha/i) != null)) {
                    var src = img.src;
                    img.style.width = img.width + "px";
                    img.style.height = img.height + "px";
                    img.style.filter =
                    "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"', sizingMethod='crop')"
                    img.src = "/common/images/spacer.gif";
                }
            }
        }
    }
}

// Loop through all available category filters and create their dropdowns
function populateCategoryFilterSelects(r) {
    for (var i = 0; i < r.selects.length; i++) {
        populateOneCategoryFilterSelect($("#" + r.selects[i].id), r.selects[i].options);
    }
    $('#eng-quickfinder-count').text(r.count);
}

// Create a category filter dropdown
function populateOneCategoryFilterSelect(obj, options) {
    var selectedIdx = 0;
    var selectedValue = obj.find("option:selected")[0].value;
    var optionIndex = obj.attr('id').substring(9);
    var label = obj.find("option")[0].text;
    var displayedOptions = $('#displayed_filterOpt' + optionIndex + ' .eng-quickfinder-options');

    obj.children().remove(); // throw out the old options in the hidden form
    displayedOptions.children().remove(); // throw out the old divs representing the options

    obj.append('<option value="" class="quickfinder-all">' + label + '</option>');
    var displayedAllOption = $('<a href="#" class="displayed_quickfinder-all">' + label + '</a>');
    $(displayedAllOption).click(function() { updateQuickfinder(this); return false; });
    displayedOptions.append(displayedAllOption);
    
    for (var i = 0; i < options.length; i++) {
        if (selectedIdx == 0 && selectedValue.length > 0 && selectedValue == options[i].value) {
            selectedIdx = obj.find("option").length;  // getting the count *before* adding the new option
        }
        obj.append('<option value="' + options[i].value + '" id="opt' + optionIndex + '-' + i.toString() + '">' + options[i].value + '</option>');
        var displayedOption = $('<a href="#" id="displayed_opt' + optionIndex + '-' + i.toString() + '">' + options[i] .value+ '</a>');
        $(displayedOption).click(function() { updateQuickfinder(this); return false; });
        displayedOptions.append(displayedOption);
    }
    obj[0].selectedIndex = selectedIdx;
}

function categoryFilterUpdate(formData) {
    $.getJSON("/ajax/getFilteredCategoryFilters.htm?" + formData, function(r) {
        populateCategoryFilterSelects(r);
    });
}

function manualsCriteriaUpdate(formData) {
    // hack to get around jquery selector bug
    if (seriesSelectElementOnManualsPage == undefined && hpSelectElementOnManualsPage == undefined && shaftSelectElementOnManualsPage == undefined) {
        $('form#filters select').each(function() {
            if ($(this).attr('id') == 'filter\'ENGINE_SERIES\'') {
                seriesSelectElementOnManualsPage = $(this);
            } else if ($(this).attr('id') == 'filter\'HORSEPOWER_RANGE\'') {
                hpSelectElementOnManualsPage = $(this);
            } else if ($(this).attr('id') == 'filter\'SHAFT\'') {
                shaftSelectElementOnManualsPage = $(this);
            }
        });
    }
    
    $.getJSON("/ajax/getManualsFilteredCategoryFilters.htm?manuals=true" + formData, function(r) {
        for (var i = 0; i < r.selects.length; i++) {
            if (r.selects[i].label == 'Series') {
                updateOneManualsCriteria(seriesSelectElementOnManualsPage, 'Select an Engine Family', r.selects[i].options);
            } else if (r.selects[i].label == 'Horsepower (hp)') {
                updateOneManualsCriteria(hpSelectElementOnManualsPage, 'Select Horsepower', r.selects[i].options);
            } else if (r.selects[i].label == 'Shaft') {
                updateOneManualsCriteria(shaftSelectElementOnManualsPage, 'Select Shaft Orientation', r.selects[i].options);
            }
        }
    });
}

function updateOneManualsCriteria(obj, defaultMessage, options) {
    var selectedIdx = 0;
    var selectedValue = $(obj).find("option:selected")[0].value;
    $(obj).html('<option value="">' + defaultMessage + '</option>');
    for (var i = 0; i < options.length; i++) {
        if (selectedIdx == 0 && selectedValue.length > 0 && selectedValue == options[i].value) {
            selectedIdx = obj.find("option").length;  // getting the count *before* adding the new option
        }
        obj.append('<option value="' + options[i].value + '">' + options[i].value + '</option>');
    }
    obj[0].selectedIndex = selectedIdx;
}

function updateQuickfinder(element) {
    var quickfinderSelection = $(element).html();
    $(element).parent('.eng-quickfinder-options').prev('.eng-quickfinder-header').html(quickfinderSelection);
    $(element).parent('.eng-quickfinder-options').prev('.eng-quickfinder-header').css({ backgroundColor:"#283f59", color:"#FFFFFF" });
    $(element).parent('.eng-quickfinder-options').css('display','none');
    if ($(element).hasClass('displayed_quickfinder-all')) { // if 'All', unselect all options, select the 'All' option
        $(element).parents('.eng-quickfinder-select').find('option').each(function() { $(this).attr('selected', ''); });
        $(element).parents('.eng-quickfinder-select').find('option.quickfinder-all').attr('selected', 'selected');
    } else { // else select an option
        var optionId = $(element).attr('id').split('_');
        $('option#' + optionId[1]).attr('selected', 'selected');
    }
    return categoryFilterUpdate($("#categoryFilterForm").fastSerializeUrlStringIgnoreEmptyNotHidden());
}

function resetQuickfinder() {
    $('#categoryFilterForm option').each(function() { $(this).attr('selected', ''); });
    $('#categoryFilterForm option.quickfinder-all').attr('selected', 'selected');

    var i = 0;
    $('.eng-quickfinder-header').each(function() {
        $(this).text(quickfinderCategoryNames[i]).css({ backgroundColor:"#8597AA", color:"#08151D" });
        i++;
    });

    return categoryFilterUpdate($("#categoryFilterForm").fastSerializeUrlStringIgnoreEmptyNotHidden());
}

function categoryFilterSubmit(formData) {
    window.location = "/onlinecatalog/results.htm?" + formData;
	return false;
}

function showEquipmentPoweredBySection(element, section) {
    $('#equipmentPoweredBy-nav div').each(function() {
        var src = $(this).css('background-image');
        $(this).css('background-image', src.replace('-on', '-off'));
    })

    $('.eng-equipPoweredBy-links').hide().removeClass('clearfix');
    $('#eng-equipPoweredBy-links-' + section).addClass('clearfix').show();

    var src = $(element).parent('div').css('background-image');
    $(element).parent('div').css('background-image', src.replace('-off', '-on'));
}

function openEngineIdentificationInfo(element) {
    clearTimeout(closeEngineIdentificationTimeout);
	$(element).find('img.roundedCorners').css('display','block');	
    $(element).find('li').css('color','#FFFFFF');
	$(element).find('li').css('padding-top',0);
	$(element).find('li').css('background-position','9px 5px');
	$(element).find('li').css('background-image','url(/common/images/bullet-quickfinderArrow-on.gif)');
	var cssObj = {
		'height' : 'auto',
		'margin-bottom' : '20px',
		'background-image' : 'url(/common/images/bg-engineIdentificationSelection-on-middle.gif)',
		'background-repeat' : 'repeat-y'
    }
	$(element).css(cssObj);
	$(element).find('div').stop(true, true).slideDown(200);

    var numberType = $(element).find('li').text();
    var isVertical = $(element).parent('div').find('#modelNumber').size();
    var src;
    if (numberType == 'Model Number' && isVertical) {
        src = $('img#engineIdentification-label-vertical').attr('src');
        $('img#engineIdentification-label-vertical').attr('src', src.replace('.jpg', '-model.jpg'));
    } else if (numberType == 'Spec Number' && !isVertical) {
        src = $('img#engineIdentification-label-horizontal').attr('src');
        $('img#engineIdentification-label-horizontal').attr('src', src.replace('.jpg', '-spec.jpg'));
    }

    //$(element).css('background-color', '#a1aaaf').find('div').stop(true, true).slideDown(300);
}

function closeEngineIdentificationInfo(element) {
    var src = $('img#engineIdentification-label-vertical').attr('src');
    $('img#engineIdentification-label-vertical').attr('src', src.replace('-model.jpg', '.jpg'));
    src = $('img#engineIdentification-label-horizontal').attr('src');
    $('img#engineIdentification-label-horizontal').attr('src', src.replace('-spec.jpg', '.jpg'));
    
    $(element).find('div').stop(true, true).slideUp(200, function(){
		$(element).find('img.roundedCorners').css('display','none');
		var cssObj = {
			'height' : '42px',
			'margin-bottom' : '0',
			'background-image' : 'url(/common/images/bg-engineIdentificationSelection-off.gif)',
			'background-repeat' : 'no-repeat'
		}
	    $(element).css(cssObj);
		$(element).find('li').css('color','#A8B1B6');
		$(element).find('li').css('padding-top','8px');
		$(element).find('li').css('background-position','9px 15px');
		$(element).find('li').css('background-image','url(/common/images/spacer.gif)');
	});
}

function toggleWhereToBuyFields() {
    if ($('#eng-dealerLocator-form select#region').val() == 'USA' || $('#eng-dealerLocator-form select#region').val() == 'Canada') {
        $('#eng-dealerLocator-form select:not(#region), #eng-dealerLocator-form input:not(.submitbutton)').each(function() {
            $(this).attr('disabled', '');
            if (!$(this).hasClass('textfield-error')) {
                $(this).css('background-color', '#fafafa');
            }
        });
    } else {
        $('#eng-dealerLocator-form select:not(#region), #eng-dealerLocator-form input:not(.submitbutton)').attr('disabled', 'disabled').val('').css('background-color', '#eee');
    }
}

function trimTextarea(elem, maxlength) {
    if ($(elem).val().length > maxlength) {
        $(elem).val($(elem).val().substring(0, maxlength - 1));
    }
}

function fixGradientDescriptionHeights() {
    var tempHeight = 0;
    $('.gradientcontainer .gradient-description').each(function(){
        if($(this).height() > tempHeight) tempHeight = $(this).height();
    });
    $('.gradientcontainer .gradient-description').css("height", tempHeight+'px');
}

function fixTabContentHeights() {
    var tempHeight = 0;
    $('#eng-landing-tabbedcontent div.tabcontent').each(function(){
        if($(this).height() > tempHeight) tempHeight = $(this).height();
    });
    $('#eng-landing-tabbedcontent div.tabcontent').css("height", tempHeight+'px');
}

$(function(){
    enableAlphaImages();
    
	$("#sitesearch").attr({ value: 'Keyword or Item #' }).focus(function(){
		if($(this).val()=="Keyword or Item #"){
			$(this).val("");
		}
	});
	
	$("form#modelNumber .textfield").attr({ value: 'Enter model #' }).focus(function(){
		if($(this).val()=="Enter model #"){
			$(this).val("");
		}
	});

// Dropdown Nav Scripts
	$('div.navnode').not(':last').hover(
		function() {
			whichdropdown = $(this).find('a.navnode-link').attr('id');
			$('#navimg-' + whichdropdown).attr("src", $('#navimg-' + whichdropdown).attr("src").replace("-off","-on"));
			$('#eng-dropdown-' + whichdropdown).css('display','block');
		}, function() {
			$('#navimg-' + whichdropdown).not($(".active")).attr("src", $('#navimg-' + whichdropdown).attr("src").replace("-on","-off"));
			$('#eng-dropdown-' + whichdropdown).css('display','none');
		}
	);

    // Set up quickfinder
    $('.eng-quickfinder-options a').click(function() { updateQuickfinder(this); return false; });

    // Set up filter criteria update on manuals page
    $('#engn-manualsLanding-nomodelnum select').change(function() {
        return manualsCriteriaUpdate($("#engn-manualsLanding-nomodelnum form").fastSerializeUrlStringIgnoreEmptyNotHidden()); 
    });

    $("#categoryFormSubmit").click(function() {
        return categoryFilterSubmit($("#categoryFilterForm").fastSerializeUrlStringIgnoreEmpty());
    });
    
    $('#eng-quickfinder').hover(
		function() {
			$(this).css('color','#FFFFFF');
			$(this).children('#eng-quickfinder-dropdown').css('display','block')
		}, function() {
			$(this).css('color','#A2B2C4');
			$('.eng-quickfinder-options').css('display','none')
			$(this).children('#eng-quickfinder-dropdown').css('display','none')
		}
	);
	$('div.eng-quickfinder-select').click(
		function() {
			$('.eng-quickfinder-options').css('display','none')
			$(this).children('.eng-quickfinder-options').css('display','block')
		}
	);
    var quickfinderDropdownTimeout;
    $('.eng-quickfinder-header, .eng-quickfinder-options').hover(function() {
        clearTimeout(quickfinderDropdownTimeout);
    }, function() {
        quickfinderDropdownTimeout = setTimeout("$('.eng-quickfinder-options').hide()", 100);
    });
    $('.eng-quickfinder-options').each(function() { quickfinderCategoryNames.push($(this).find('a:first').text().replace('All ', '')); } );
    $('.eng-quickfinder-reset').click(resetQuickfinder);

    // Activate rollover images
    $('img.rollover').each(function() {
        var offSrc = $(this).attr('src');
        $(this).hover(function() {
            $(this).attr('src', offSrc.replace('-off', '-on'));
        }, function() {
            $(this).attr('src', offSrc);
        });
    });
	
	// Functions to set uniform height for certain objects. Use 1 ms delay to deal with Safari bug.
    setTimeout('fixGradientDescriptionHeights()', 1);
    setTimeout('fixTabContentHeights()', 1);
	
	//Funtion for Gradient container rollovers
	$('.gradientcontainer').hover(function() {
		$(this).css("width","166px");
		$(this).find('div.gradient-description').css("margin-right","2px");
		$(this).find('div.gradient-description').css("margin-bottom","2px");
		$(this).find('div.gradient-description').css("margin-left","2px");
		$(this).find('p.header').css("color","#7A9059");
		$(this).css("border-width","2px");
		$(this).css("border-color","#c2c2c2");
		$(this).css("background-image","url('/common/images/bg-gradient-on.gif')");
        $(this).find('.gradient-photo').css('margin-top', '-1px');
    }, function() {
		$(this).css("border-width","1px");
		$(this).find('div.gradient-description').css("margin-right","3px");
		$(this).find('div.gradient-description').css("margin-bottom","3px");
		$(this).find('div.gradient-description').css("margin-left","3px");
		$(this).find('p.header').css("color","#6B8896");
		$(this).css("border-color","#E3E2E2");
		$(this).css("width","168px");
		$(this).css("background-image","url('/common/images/bg-gradient-off.gif')");
        $(this).find('.gradient-photo').css('margin-top', '0');
    });

	// FAQs expansion script
	$('.eng-faq ul li a').click(
		function() {
			var whichQuestion = $(this).parents('div.eng-faq').attr('id');
			if($('#' + whichQuestion + '-answer').css("display")=="block") {
				$('#' + whichQuestion + '-answer').slideUp(500);
				$(this).css({'font-weight' : 'normal', 'font-style' : 'normal', 'color' : '#7A9059'});
				$(this).parent('li').css("background-image","url('/common/images/bullet-rightarrow.gif')");
			} else {
				$('.eng-faq-answer').slideUp(500);
				$('.eng-faq ul li').css("background-image","url('/common/images/bullet-rightarrow.gif')");
				$('.eng-faq ul li a').css({'font-weight' : 'normal', 'font-style' : 'normal', 'color' : '#7A9059'});
				$(this).css({'font-weight' : 'bold', 'font-style' : 'italic', 'color' : '#555555'});
				$('#' + whichQuestion + '-answer').slideDown(500);
				$(this).parent('li').css("background-image","url('/common/images/bullet-downArrowRotated.gif')");
			}
            return false;
        }
	);

    // Engine identification page effects
    $('.engineIdent-rolloverDef').hover(function() {
        var myDiv = this;
        openEngineIdentificationTimeout = setTimeout(function(){openEngineIdentificationInfo(myDiv)}, 100);
    }, function() {
        var myDiv = this;
        clearTimeout(openEngineIdentificationTimeout);
        closeEngineIdentificationTimeout = setTimeout(function(){closeEngineIdentificationInfo(myDiv)}, 100);
    });

    toggleWhereToBuyFields();
    $('#eng-dealerLocator-form select#region').change(toggleWhereToBuyFields);

    // Fix select element overlap bug in IE6
	$('.eng-dropdown').bgiframe();
    
    // prepare document overlay so that we can close popups by clicking outside them
    $("#document-overlay").css('height', $(document).height());
    $("#document-overlay").css('width', $(document).width());

    // Trim length of message input
    $('textarea#message').keyup(function() { trimTextarea(this, 500); });

    // Hook up survey link
    $('div#eng-foreseelink a').click(function() {
        window.open('http://www.kohler.com/feedback/enginescommentcard.jsp', 'Feedback', 'height=560,width=560,resizable,location=no');
        return false;
    });
});

// from tabs.js
// Initial variable setup
var whichDetailTab = '';

// Tab Swapping Function
function detailTabs() {
    $('#tabs div').each(function() {
        $(this).css("backgroundImage",$(this).css("backgroundImage").replace("-on","-off"));
    });
    if ($('#tabs div.active').size() > 0) {
        $('#tabs div.active').css("backgroundImage",$('#tabs div.active').css("backgroundImage").replace("-off","-on"));
    }
}

// Bind Functions to Dom on document ready
$(function(){
    // Tab-related functions
    detailTabs();
    $('#tabs div').click(
            function() {
                $('#tabs div').removeClass('active');
                $(this).addClass('active');
                detailTabs();
                $('.tabcontent').css('display','none');
                whichDetailTab = $(this).attr('id');
                $('#tabcontent-' + whichDetailTab).css('display','block');

                // Size uses panel on product detail page
                if ($(this).attr('id') == 'uses' && $('#engineuses-tabs').size() > 0) {
                    var usesHeight = $('#engineuses-tabs').height();
                    if ($.browser.msie && (parseInt(jQuery.browser.version) < 7)) {
                        $('#engineuses-list .engUsesList').css('height', usesHeight + 'px');
                    } else {
                        $('#engineuses-list .engUsesList').css('min-height', usesHeight + 'px');
                    }
                }
            }
    );
});