$(function () {

    // iPad detaction
    function isiPad() {
        return (navigator.platform.indexOf("iPad") != -1);
    }
    var ua = navigator.userAgent,
    event = (ua.match(/iPad/i)) ? "touchstart" : "click";

    // load twitter feed
    $("#tweets").tweet({
        avatar_size: 32,
        count: 2,
        username: "RedArrowLabs",
        loading_text: "Loading Tweets ..."
    });

    // Capabilities/Benefits slider
    /* ----------------------------------------------------- */
    $('ul.slider a.expand').live('click', function (e) {
        var slideOut = $(this).attr('rel');
        var openDescriptions = $('li.description:visible');
        $(openDescriptions).hide();
        $(this).parent().next().show('slide', { direction: slideOut }, 300);
        e.preventDefault();
    });

    $('ul.slider a.close').live('click', function (e) {
        hideDescription($(this));
        e.preventDefault();
    });

    $('ul.slider li.description').live('click', function (e) {
        var slideOut = $(this).find('a.close').attr('rel');
        $(this).hide('slide', { direction: slideOut }, 300);
        e.preventDefault();
    });

    function hideDescription(el) {
        var slideOut = $(el).attr('rel');
        $(el).parent('li').hide('slide', { direction: slideOut }, 300);
    }

    // Homepage
    /* ----------------------------------------------------*/
    $('#box-labels li a').live('mouseover', function () {
        showCopy(this);
        animateBoxUp(this);
    }).live('mouseout', function () {
        hideCopy(this);
        animateBoxDown(this);
    }); -

    $('#box-labels li a').live('click', function () {
        clearTimeout($('#box-copy').data('timeoutId'));
        hideCopy(this);
    });

    // trigger the default message after a delay if the mouse leaves the UL
    $('#box-labels').live('mouseover', function () {
        clearTimeout($('#box-copy').data('timeoutId'));
        $('p.default').hide();
    }).live('mouseout', function () {
        var timeoutId = setTimeout(function () { $('p.default').show(); }, 600);
        $('#box-copy').data('timeoutId', timeoutId); //set the timeoutId, allowing us to clear this trigger if the mouse comes back over
    });

    function animateBoxUp(el) {
        var block = '#homepage-box div.' + $(el).attr('class');
        $(block).stop(true, false).animate({ top: '-25' }, 1000)
    };

    function animateBoxDown(el) {
        var block = '#homepage-box div.' + $(el).attr('class');
        $(block).stop(true, false).animate({ top: '0' }, 1000)
    };

    function showCopy(el) {
        var copyBlock = '#box-copy p.' + $(el).attr('class');
        $(copyBlock).stop(true, false).fadeTo(200, 1.0);
    };

    function hideCopy(el) {
        var copyBlock = '#box-copy p.' + $(el).attr('class');
        $(copyBlock).stop(true, false).fadeTo(200, 0);
    };

    // Case Studies
    /* ----------------------------------------------------- */
    // case study jump menu
    $("ul.sf-menu a.default").live('click', function (e) {
        e.preventDefault();
    });

    var allCSLevels = "cs1 cs2 cs3 cs4";
    var allCSLevelSelectors = splitClassesIntoSelectors(allCSLevels);

    $.get("/assets/js/data/map-casestudy.txt", function (mapLegend) {
        if (!isiPad()) {
            $("#casestudy-map").live('mousemove', function (e) {
                var offset = $(this).offset();
                var mapX = e.pageX - parseInt(offset.left);
                var mapY = e.pageY - parseInt(offset.top);

                // get the character out of the legend
                var mapKey = mapLegend.charAt((mapY * 252) + mapX);  // 252 is the width of the image

                // uncomment the below if you want to see some real-time tracking of the mouse position
                // $("#position").text(mapKey + ": " + mapX + "x" + mapY + " = " + ((mapY * 632) + mapX));

                if (mapKey == "a") { /* do something for region a */ }
                if (mapKey == "b") { highlightCSLevels("cs1"); }
                if (mapKey == "c") { highlightCSLevels("cs2"); }
                if (mapKey == "d") { highlightCSLevels("cs3"); }
                if (mapKey == "e") { highlightCSLevels("cs4"); }
            });

            $("#casestudy-map").live('mouseout', function (e) {
                $("#mo").find(allCSLevelSelectors).attr('style', 'display:none');
                $("#off").find(allCSLevelSelectors).attr('style', 'display:block');
            });
        }

        $("#casestudy-map").live(event, function (e) {
            var offset = $(this).offset();
            var mapX = e.pageX - parseInt(offset.left);
            var mapY = e.pageY - parseInt(offset.top);
            if (isiPad()) {
                mapX = e.originalEvent.touches[0].pageX - 265;
                mapY = e.originalEvent.touches[0].pageY - ($('#casestudies-header-inner div.w').height() + 265);
            }

            // get the character out of the legend
            var mapKey = mapLegend.charAt((mapY * 252) + mapX);  // 252 is the width of the image

            // uncomment the below if you want to see some real-time tracking of the mouse position
            //$("#position").text(mapKey + ": " + mapX + "x" + mapY + " = " + ((mapY * 632) + mapX));

            if (mapKey == "a") { /* do something for region a */ }
            if (mapKey == "b") { selectCSLevels("cs1"); }
            if (mapKey == "c") { selectCSLevels("cs2"); }
            if (mapKey == "d") { selectCSLevels("cs3"); }
            if (mapKey == "e") { selectCSLevels("cs4"); }
        });

        if (!isiPad()) {
            $("#casestudy-map").live('mouseout', function (e) {
                $("#mo").find(allCSLevelSelectors).attr('style', 'display:none');
                $("#off").find(allCSLevelSelectors).attr('style', 'display:block');
            });
        }
    });

    function highlightCSLevels(csLevels) {
        var csSelectors = splitClassesIntoSelectors(csLevels);
        $("#mo").find(csSelectors).attr('style', 'display:block');
        $("#off").find(csSelectors).attr('style', 'display:none');
    }

    function selectCSLevels(csLevels) {
        var csSelectors = splitClassesIntoSelectors(csLevels);

        // remove old selected classes
        $('#mo li').removeClass('selected');
        $('#off li').removeClass('selected').attr('style', 'display:block');
        $("#selected li").attr('style', 'display:none');
        $("#description div").attr('style', 'display:none');

        // add 'selected' class to selected list item to hide mo images;
        // show selected image
        $("#mo").find(csSelectors).hide().addClass('selected');
        $("#off").find(csSelectors).hide().addClass('selected');
        $("#selected").find(csSelectors).attr('style', 'display:block');
        $("#description").find(csSelectors).attr('style', 'display:block');

    }

    // Process
    /* ----------------------------------------------------- */
    var allProcessLevels = "pr1 pr2 pr3 pr4 pr5 pr6 pr7";
    var allProcessLevelSelectors = splitClassesIntoSelectors(allProcessLevels);

    $.get("/assets/js/data/map-process.txt", function (mapLegend) {
        if (!isiPad()) {
            $("#process-wrapper").live('mousemove', function (e) {
                var offset = $(this).offset();
                var mapX = e.pageX - parseInt(offset.left);
                var mapY = e.pageY - parseInt(offset.top);

                // get the character out of the legend
                var mapKey = mapLegend.charAt((mapY * 710) + mapX);  // 710 is the width of the image

                // uncomment the below if you want to see some real-time tracking of the mouse position
                // $("#position").text(mapKey + ": " + mapX + "x" + mapY + " = " + ((mapY * 710) + mapX));

                if (mapKey == "a") { }
                if (mapKey == "b") { highlightProcessLevels("pr1"); }
                if (mapKey == "c") { highlightProcessLevels("pr4"); }
                if (mapKey == "d") { highlightProcessLevels("pr7"); }
                if (mapKey == "e") { highlightProcessLevels("pr3"); }
                if (mapKey == "f") { highlightProcessLevels("pr2"); }
                if (mapKey == "g") { highlightProcessLevels("pr6"); }
                if (mapKey == "h") { highlightProcessLevels("pr5"); }
            });
        }

        $("#process-wrapper").live(event, function (e) {
            var offset = $(this).offset();
            var mapX = e.pageX - parseInt(offset.left);
            var mapY = e.pageY - parseInt(offset.top);
            if (isiPad()) {
                mapX = e.originalEvent.touches[0].pageX - 265;
                mapY = e.originalEvent.touches[0].pageY - 360;
            }

            // get the character out of the legend
            var mapKey = mapLegend.charAt((mapY * 710) + mapX);  // 710 is the width of the image

            // uncomment the below if you want to see some real-time tracking of the mouse position
            //$("#position").text(mapKey + ": " + mapX + "x" + mapY + " = " + ((mapY * 710) + mapX));

            if (mapKey == "a") { }
            if (mapKey == "b") { selectProcessLevels("pr1"); }
            if (mapKey == "c") { selectProcessLevels("pr4"); }
            if (mapKey == "d") { selectProcessLevels("pr7"); }
            if (mapKey == "e") { selectProcessLevels("pr3"); }
            if (mapKey == "f") { selectProcessLevels("pr2"); }
            if (mapKey == "g") { selectProcessLevels("pr6"); }
            if (mapKey == "h") { selectProcessLevels("pr5"); }

            //e.preventDefault();
        });

        if (!isiPad()) {
            $("#process-wrapper").live('mouseout', function (e) {
                $("#mo").find(allProcessLevelSelectors).attr('style', 'display:none');
                $("#off").find(allProcessLevelSelectors).attr('style', 'display:block');
            });
        }

    });

    function highlightProcessLevels(processLevels) {
        var processSelectors = splitClassesIntoSelectors(processLevels);
        $("#mo").find(processSelectors).attr('style', 'display:block');
        $("#off").find(processSelectors).attr('style', 'display:none');
    }

    function selectProcessLevels(processLevels) {
        var processSelectors = splitClassesIntoSelectors(processLevels);

        // remove old selected classes
        $('#mo li').removeClass('selected');
        $('#off li').removeClass('selected').attr('style', 'display:block');
        $("#selected li").attr('style', 'display:none');
        $("#description div").attr('style', 'display:none');

        // add 'selected' class to selected list item to hide mo images;
        // show selected image
        $("#mo").find(processSelectors).hide().addClass('selected');
        $("#off").find(processSelectors).hide().addClass('selected');
        $("#selected").find(processSelectors).attr('style', 'display:block');
        $("#description").find(processSelectors).attr('style', 'display:block');

    }

    // splits a string of css classes (separated by spaces) into an "or"-style selector suitable for use with jquery
    // example: "a b c" becomes ".a, .b, .c"
    function splitClassesIntoSelectors(classes) {
        return "." + classes.replace(/ /g, ", .");
    }


    // Team Member Photo/Info swap
    /* ----------------------------------------------------- */
    var configTeamMemberHover = {
        over: showTeamMember, // function = onMouseOver callback (REQUIRED)    
        timeout: 400, // number = milliseconds delay before onMouseOut    
        out: hideTeamMember // function = onMouseOut callback (REQUIRED)    
    };

    //$('#our-team li').hoverIntent(configTeamMemberHover);
    // using hoverIntent plugin with .live() rndnext.blogspot.com/2009/02/jquery-live-and-plugins.html
    $('#our-team li').live('mouseover', function () {
        if (!$(this).data('init')) {
            $(this).data('init', true);
            $(this).hoverIntent(configTeamMemberHover);
            $(this).trigger('mouseover');
        }
    });

    // lightbox
    $('a.teammember').live('click', function (e) {
        $.fn.colorbox({ href: $(this).attr('href'), open: true });
        e.preventDefault();
    });

    // show Team Member
    function showTeamMember() {
        $(this).children('img').hide('slide', { direction: 'down' }, 300);
        $(this).children('.person').show();
    };

    // hide Team Member
    function hideTeamMember() {
        $(this).children('img').show('slide', { direction: 'down' }, 300);
    };

    // Form Validations
    /* ----------------------------------------------------- */
    // contact form validation
    $('#contactform #submit').live('click', function () {
        $('#contactform').validate({
            rules: {
                FullName: {
                    required: true
                },
                Company: {
                    required: true
                },
                Phone: {
                    required: true,
                    digits: true,
                    minlength: 10
                },
                Email: {
                    required: true,
                    email: true
                },
                Employees: {
                    required: false,
                    digits: true
                },
                YearsInBusiness: {
                    required: false,
                    digits: 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
            }
        });
    });

    // home form validation
    $('#homeform #submit').live('click', function () {
        $("#homeform").validate({
            rules: {
                FullName: {
                    required: true
                },
                Email: {
                    required: true,
                    email: 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
            }
        });
    });

});
