$(document).ready(function() {

    // Load Cufon fonts when @FontFace is not available
    isFontFaceSupported.ready(function(bool) {
        if (!bool)
        // console.log("no fontface");
            $.getScript('/assets/js/cufon-yui.js', function() {
                $.getScript('/assets/fonts/Avenir_300.font.js', function() {
                    Cufon.replace('#navigation li a');
                    Cufon.replace('h1');
                    Cufon.replace('h2');
                    Cufon.replace('h3');
                    // Cufon.now();
                });
                $.getScript('/assets/fonts/AvenirBold_550.font.js', function() {
                    Cufon.replace('#navigation li a.selected');
                    // Cufon.now();
                });
                Cufon.now();
            });
    });

    //active tab
    var loc = window.location;

    if (location.href.indexOf('\/product\/') != -1) {
        $('#n1 a').addClass('active');
    } else if (location.href.indexOf('\/support\/') != -1) {
        $('#n2 a').addClass('active');
    } else if (location.href.indexOf('\/how-to-buy\/') != -1) {
        $('#n3 a').addClass('active');
    } else if (location.href.indexOf('\/contact\/') != -1) {
        $('#n4 a').addClass('active');
    }

    // image button hover
    $('input.bttn').hover(function() {
        $(this).css('background-position', '0 -33px');
    },
		function() {
		    $(this).css('background-position', '0 0');
		}
	);

    // Table Striping and hover controls
    $(function() {
        $("table.largetable tr:nth-child(even), table.largetable2 tr:nth-child(even)").addClass("striped");
    });
    $("table.largetable, table.smalltable").delegate('td', 'mouseover mouseleave', function(e) {
        if (e.type == 'mouseover') {
            $(this).parent().addClass("hover");
        }
        else {
            $(this).parent().removeClass("hover");
        }
    });
    $("table.largetable3").delegate('td', 'mouseover mouseleave', function(e) {
        if (e.type == 'mouseover') {
            $(this).parent().addClass("hover");
            $("colgroup").eq($(this).index()).addClass("hover");
        }
        else {
            $(this).parent().removeClass("hover");
            $("colgroup").eq($(this).index()).removeClass("hover");
        }
    });

    // lightbox for product diagrams
    if (document.getElementById("diagram")) {
        $("#diagram a").colorbox();
    }

    // product landing page grid
    //$("#product-landing li:nth-child(3n)").addClass("last"); // last item in each row gets no right margin

    // defuscate emails
    $('.obfuscated').defuscate();

    // sizing calculator: toggle the drawdown table
    var showText = 'Show drawdown chart';
    var hideText = 'Hide drawdown chart';
    var is_visible = false;

    $('#drawdowntable').prev().append(' (<a href="#" class="togglelink">' + showText + '</a>)');
    $('#drawdowntable').hide();
    $('a.togglelink').click(function() {

        // switch visibility
        is_visible = !is_visible;

        // change the link depending on whether the element is shown or hidden
        $(this).html((!is_visible) ? showText : hideText);

        // toggle the drawdown chart
        $(this).parent().next('#drawdowntable').toggle('300');

        // return false so any link destination is not followed
        return false;
    });

    // sizing calculator
    function calcDrawDown() {
        var rate, time, drawdown;

        rate = parseFloat($("#DeliveryRate").val());
        time = parseFloat($("#MinimumRunTime").val());

        if (!isNaN(rate) && !isNaN(time)) {
            drawdown = rate * time;

            if (!isNaN(drawdown)) {
                $("#DrawDown").val(drawdown.toFixed(2));

                $('#DrawDownFields1').show('fast');

                return;
            }

            $('#DrawDownFields1').show('fast');

            $('#DrawDownErrors1b').show('fast');

            return;
        }

        $('#DrawDownErrors1a').show('fast');
    }

    function calcDrawDownFactor(factorTable) {
        var cutIn, cutOut, factor;

        cutIn = parseInt($("#CutIn").val());
        cutOut = parseInt($("#CutOut").val());

        if (cutIn > 0 && cutOut > 0) {
            factor = parseFloat(factorTable["co" + cutOut]["ci" + cutIn]);

            if (!isNaN(factor)) {
                $("#DrawDownFactor").val(factor.toFixed(2));

                $('#DrawDownFields2').show('fast');

                return;
            }

            $('#DrawDownFields2').show('fast');

            $('#DrawDownErrors2b').show('fast');

            return;
        }

        $('#DrawDownErrors2a').show('fast');
    }

    function calcCapacity() {
        var drawdown, ddfactor, capacity;

        drawdown = parseFloat($("#DrawDown").val());
        ddfactor = parseFloat($("#DrawDownFactor").val());

        capacity = drawdown / ddfactor;

        return capacity;
    }

    function calcTank() {
        var capacity = calcCapacity();

        if (!isNaN(capacity) && capacity != Infinity) {
            $("#RequiredCapacity").text(capacity.toFixed(2));
            $('#formResult').show('fast');
            $('#FormErrors').hide();

            $.getJSON($("#calculator").attr("action"),
            {
                capacity: capacity,
                lowProfile: $("#LowProfile").is(':checked')
            },
            function(data) {
                $("#ModelNumber").html(data);
            });

        } else {
            $('#formResult').hide();
            $('#FormErrors').show('fast');
        }
    }

    function changeUom() {
        var uom = $("#VolumeUom").val();

        $(".uom").hide();
        $("." + uom).show();
    }

    if (document.getElementById("calculator")) {
        $(".uom").hide();

        var factorTable = new Object();

        factorTable["co30"] = { "ci20": "0.21" };
        factorTable["co35"] = { "ci20": "0.28", "ci25": "0.19" };
        factorTable["co40"] = { "ci20": "0.34", "ci25": "0.26", "ci30": "0.17" };
        factorTable["co45"] = { "ci20": "0.39", "ci25": "0.32", "ci30": "0.24", "ci35": "0.16" };
        factorTable["co50"] = { "ci20": "0.44", "ci25": "0.37", "ci30": "0.30", "ci35": "0.22", "ci40": "0.15" };
        factorTable["co55"] = { "ci20": "0.47", "ci25": "0.41", "ci30": "0.34", "ci35": "0.28", "ci40": "0.21", "ci45": "0.14" };
        factorTable["co60"] = { "ci20": "0.50", "ci25": "0.44", "ci30": "0.38", "ci35": "0.32", "ci40": "0.26", "ci45": "0.19", "ci50": "0.13" };
        factorTable["co65"] = { "ci20": "0.53", "ci25": "0.48", "ci30": "0.42", "ci35": "0.36", "ci40": "0.30", "ci45": "0.24", "ci50": "0.18", "ci55": "0.12" };
        factorTable["co70"] = { "ci20": "0.56", "ci25": "0.50", "ci30": "0.45", "ci35": "0.40", "ci40": "0.34", "ci45": "0.29", "ci50": "0.23", "ci55": "0.17", "ci60": "0.11" };
        factorTable["co75"] = { "ci25": "0.53", "ci30": "0.48", "ci35": "0.43", "ci40": "0.38", "ci45": "0.32", "ci50": "0.27", "ci55": "0.22", "ci60": "0.16", "ci65": "0.11" };
        factorTable["co80"] = { "ci30": "0.50", "ci35": "0.46", "ci40": "0.41", "ci45": "0.36", "ci50": "0.31", "ci55": "0.26", "ci60": "0.21", "ci65": "0.15", "ci70": "0.10" };
        factorTable["co85"] = { "ci35": "0.48", "ci40": "0.43", "ci45": "0.39", "ci50": "0.34", "ci55": "0.29", "ci60": "0.24", "ci65": "0.20", "ci70": "0.15", "ci75": "0.10" };
        factorTable["co90"] = { "ci40": "0.46", "ci45": "0.42", "ci50": "0.37", "ci55": "0.32", "ci60": "0.28", "ci65": "0.23", "ci70": "0.19", "ci75": "0.14", "ci80": "0.09" };
        factorTable["co95"] = { "ci45": "0.44", "ci50": "0.40", "ci55": "0.35", "ci60": "0.31", "ci65": "0.27", "ci70": "0.22", "ci75": "0.18", "ci80": "0.13", "ci85": "0.09" };
        factorTable["co100"] = { "ci50": "0.42", "ci55": "0.38", "ci60": "0.34", "ci65": "0.30", "ci70": "0.26", "ci75": "0.21", "ci80": "0.17", "ci85": "0.13", "ci90": "0.09" };
        factorTable["co105"] = { "ci55": "0.41", "ci60": "0.37", "ci65": "0.33", "ci70": "0.29", "ci75": "0.25", "ci80": "0.20", "ci85": "0.16", "ci90": "0.13", "ci95": "0.08" };
        factorTable["co110"] = { "ci60": "0.39", "ci65": "0.35", "ci70": "0.31", "ci75": "0.27", "ci80": "0.24", "ci85": "0.20", "ci90": "0.16", "ci95": "0.12", "ci100": "0.08" };
        factorTable["co115"] = { "ci65": "0.38", "ci70": "0.34", "ci75": "0.30", "ci80": "0.26", "ci85": "0.23", "ci90": "0.19", "ci95": "0.15", "ci100": "0.11", "ci105": "0.08" };
        factorTable["co120"] = { "ci70": "0.36", "ci75": "0.33", "ci80": "0.29", "ci85": "0.25", "ci90": "0.22", "ci95": "0.18", "ci100": "0.15", "ci105": "0.11", "ci110": "0.07" };
        factorTable["co125"] = { "ci75": "0.35", "ci80": "0.32", "ci85": "0.28", "ci90": "0.25", "ci95": "0.21", "ci100": "0.18", "ci105": "0.14", "ci110": "0.11" };

        $("#VolumeUom").change(function() { changeUom(); });

        $("#CalculateDrawDown1").click(function() {
            $('.calculator-error1').hide();

            var errorDiv = calcDrawDown();

            if (errorDiv != "") {
                $('#' + errorDiv).show('fast');
            }

            return false;
        });

        $("#CalculateDrawDown2").click(function() {
            $('.calculator-error2').hide();

            var errorDiv = calcDrawDownFactor(factorTable);

            if (errorDiv != "") {
                $('#' + errorDiv).show('fast');
            }

            return false;
        });

        $("#calculator").submit(function() {
            calcTank();
            return false;
        });
    }
    // end sizing calculator

    // how to buy

    function DisableForm() {
        $("#submit").fadeTo("fast", ".2");
        $("#submit").attr("disabled", "disabled").css("cursor", "progress");
    }

    function EnableForm() {
        $("#submit").fadeTo("fast", "1");
        $("#submit").removeAttr("disabled").css("cursor", "pointer");
    }

    function UpdateStateSelect() {
        DisableForm();
        $.getJSON($("#StateLookupUrl").val() + $("select#Country").val(), {}, function(j) {
            var options = '<option value="">' + $("#SelectState").val() + '</option>';

            if (j != null) {
                for (var i = 0; i < j.length; i++) {
                    options += '<option value="' + j[i].StateId + '">' + j[i].Name + '</option>';
                }
                $("select#State").html(options);

                if (j.length > 1) {
                    $("select#State").parent().show();
                    $("input#PostalCode").parent().show();
                } else {
                    $("select#State").parent().hide();
                    $("input#PostalCode").parent().hide();
                }
            }

            EnableForm();
        });
    }


    if (document.getElementById("howtobuy")) {
        if ($("select#Country").val() == "-1") {
            $("select#State").parent().hide();
        } else if ($("select#State option").length < 2) {
            UpdateStateSelect();
        }

        $("select#Country").change(function() {
            UpdateStateSelect();
        });

        $("#howtobuy").validate({
            rules: {
                Country: {
                    required: true
                },
                State: {
                    required: "#State:visible"
                },
                VisitorType: {
                    required: true
                }
            },
            errorElement: "div",
            wrapper: "div",  // a wrapper around the error message
            errorPlacement: function(error, element) {
                offset = element.offset();
                error.insertAfter(element)
                error.addClass('message');  // add a class to the wrapper
            }
        });
    }
    // end how to buy

    // contact form validation & country/state selector
    if (document.getElementById("contactform")) {
        if ($("select#Country").val() == "-1") {
            $("select#State").parent().hide();
        } else if ($("select#State option").length < 2) {
            UpdateStateSelect();
        }

        $("select#Country").change(function() {
            UpdateStateSelect();
        });

        $("#contactform").validate({
            rules: {
                RouteTo: {
                    required: true
                },
                FirstName: {
                    required: true
                },
                LastName: {
                    required: true
                },
                Address1: {
                    required: true
                },
                City: {
                    required: true
                },
                State: {
                    required: "#State:visible"
                },
                Phone: {
                    required: true
                },
                Zip: {
                    required: true
                },
                Email: {
                    required: true,
                    email: true
                },
                Comment: {
                    required: true
                }
            },
            errorElement: "div",
            wrapper: "div",  // a wrapper around the error message
            errorPlacement: function(error, element) {
                offset = element.offset();
                error.insertAfter(element)
                error.addClass('message');  // add a class to the wrapper
            }
        });

        $("select#Country").rules("add", { min: 1, messages: { min: "Please select a country."} });
        $("select#State").rules("add", { min: 1, messages: { min: "Please select a state."} });
    }

    // init product image rotator
    if (document.getElementById("thumbs")) {
        $('#thumbs').galleriffic({
            delay: 2500,
            numThumbs: 3,
            preloadAhead: 3,
            enableTopPager: false,
            enableBottomPager: false,
            imageContainerSel: '#slideshow',
            controlsContainerSel: '#controls',
            captionContainerSel: '#caption',
            loadingContainerSel: '#loading',
            renderSSControls: false,
            renderNavControls: true,
            playLinkText: 'Play Slideshow',
            pauseLinkText: 'Pause Slideshow',
            prevLinkText: '&lsaquo; Previous Photo',
            nextLinkText: 'Next Photo &rsaquo;',
            nextPageLinkText: 'Next &rsaquo;',
            prevPageLinkText: '&lsaquo; Prev',
            enableHistory: false,
            enableKeyboardNavigation: true,
            autoStart: true,
            syncTransitions: true,
            defaultTransitionDuration: 500,
            onSlideChange: function(prevIndex, nextIndex) { if (nextIndex == 0 && prevIndex > 0) { this.pause(); } }
        });
    }

    $('#gallery.content').show();
});
