﻿jQuery(function ($) {
    var initial = true;

    var nav = $('#nav');
    var navItems = [];

    var navIndex = 0;
    nav.find('a').each(function () {
        var thisItem = $(this);
        thisItem.click(function () {
            var $this = $(this);
            $this.activate();
            var hash = $this.attr('href');
            $.address.value(hash);

            //window.location.hash = hash;
            //navigateToHash(hash);

            return false;
        });

        navItems[navIndex] = thisItem;
        navIndex++;
    });

    $.fn.activate = function () {
        nav.find('a').each(function () {
            $(this).removeClass('active');
        });
        $(this).addClass('active');
    }

    var sectionWidth = 980;
    var sectionHeight = 516;
    var content = $('#content');
    data = [];

    var menus = $('.menu');

    var sectionMenus = [];
    for (var i = 0; i < menus.length; i++) {
        var menu = $(menus.get(i));
        var sectionID = menu.attr('id').replace(/menu-/gi, '');
        sectionMenus[sectionID] = menu;
    }

    hideMenu = function () {
        menus.each(function () {
            //herzog testing
            $(this).fadeOut(200);
        });
    }

    showMenu = function (sectionID) {
      
        menus.hide();
        //ie9 does not render the fadeIn properly
        if ($.browser.msie && $.browser.version == "9.0") {
            sectionMenus[sectionID].show();
        } else {
            sectionMenus[sectionID].fadeIn(200);
        }
        //  return confirm(sectionID);
    }

    setActiveMenuLink = function (sectionID, page) {
        $('#menus a').removeClass('selected');
        var link = $('#menu-' + sectionID + ' li:nth-child(' + (page + 1) + ') a');
        link.addClass('selected');
        try { Cufon.replace('#menus a'); } catch (e) { }
    }

    // get info on sections and calculate the size needed for #content
    loadContent = function () {
        // get json content from /api/GetContent.ashx
        $.getJSON('/api/GetContent.ashx', function (jsonData) {
            data = jsonData.content;

            // calculate area needed for #content
            var xMax = 0;
            var yMax = 0;
            for (var i = 0; i < data.length; i++) {
                if (data[i].xPosition > xMax)
                    xMax = data[i].xPosition;

                if (data[i].yPosition > yMax)
                    yMax = data[i].yPosition;

                // cache the containing div
                data[i].container = $('#container-' + data[i].id);

                // set absolute position of containing div
                data[i].container.css('left', (data[i].xPosition * sectionWidth))
                                 .css('top', (data[i].yPosition * sectionHeight));
            }

            // area needed for #content needs use a 1-based index instead of x/y's 0-based index
            content.css('width', ((xMax + 1) * sectionWidth))
                   .css('height', ((yMax + 1) * sectionHeight));

            // show the content now that it is all positioned correctly
            content.fadeIn('fast');

            var addressVal = $.address.value();
            if (addressVal != null && addressVal != '') {
                navigateToHash(addressVal);
            }
        });
    }

    navigateToHash = function (hash) {
        var x = 0;
        var y = 0;

        var nav = '';
        var page = '';
        var navMatch = hash.match(/^\/[^\/]*/gi);
        if (navMatch != null) {
            nav = navMatch[0];
        }

        switch (nav) {
            case '/who':
                x = 1;
                break;
            case '/what':
                x = 2;
                break;
            case '/fusionovation':
                x = 3;
                break;
            case '/contact':
                x = 4;
                break;
            case '/home':
            default:
                x = 0;
                break;
        }

        var newHash = hash.substring(nav.length);
        var pageMatch = newHash.match(/^\/\d+/gi);
        if (pageMatch != null) {
            page = pageMatch[0];
            try {
                // strip # off the beginning and then parse the number
                y = parseInt(page.substring(1));
            } catch (e) {
                // invalid page number
                y = 0;
            }
        }

        sfNavigate(x, y);
    }

    sfNavigate = function (x, y) {
        var xOffset = 0 - (x * sectionWidth);
        var yOffset = 0 - (y * sectionHeight);
        var delay = 500;
        var slideInProgress = true;

        // we don't want to apply the shrink animation on the initial load
        if (initial) {
            // next time we will apply the animation - remove the delay before
            // animation this time
            initial = false;
            delay = 0;
        } else {
            hideMenu();

            content.addClass('shrink');
        }
        setTimeout(function () {
            content.animate({
                marginLeft: xOffset,
                marginTop: yOffset
            },
            800,
            function () {
                // post-animation effects

                if (typeof (sectionMenus[x]) !== 'undefined' && sectionMenus[x] !== null) {
                    // if (typeof (sectionMenus[x]) !== 'undefined' && sectionMenus[x] !== null) {             
                    showMenu(x);
                    setActiveMenuLink(x, y);
                }

                else {

                    hideMenu();

                }


                content.removeClass('shrink');
            }
        );
        }, delay);

        if (typeof (navItems[x]) !== 'undefined' && navItems[x] !== null) {
                  
            navItems[x].activate();
        }
       
    }

    $('a.deep').address(function () {
        return $(this).attr('href');
    });

    $.address.change(function (event) {
        navigateToHash(event.value);
    });

    rotator = function (selector) {
        var container = $(selector);
        var items = container.find('img.frame');
        var next = container.find('.next');
        var previous = container.find('.previous');
        var index = 0;

        items.hide();
        $(items.get(0)).show();

        var updateImage = function (next) {
            $(items.get(index)).fadeOut(function () {
                $(items.get(next)).fadeIn();
                index = next;
            });
        }

        next.click(function () {
            var nextPosition = index + 1;
            if (nextPosition >= items.length) {
                nextPosition = 0;
            }

            updateImage(nextPosition);
            return false;
        });

        previous.click(function () {
            var nextPosition = index - 1;
            if (nextPosition < 0) {
                nextPosition = items.length - 1;
            }

            updateImage(nextPosition);
            return false;
        });
    }

    // set up any rotators
    $('.rotator').each(function () {
        rotator(this);
    });

    /* Speech section setup */
    // initalize statements
    var statements = $('#speech .statement');

    // initialize and preload arrows
    var arrows = $('#speech .arrow');
    for (var i = 1; i <= 10; i++) {
        var img = new Image();
        img.src = "/images/arrow_" + i + ".png";
    }

    // intialize people
    var people = $('#speech .person');
    people.each(function () {
        $(this).mouseover(function () {
            var index = parseInt($(this).attr('id').replace(/person-/gi, ''));
            updateStatements(index - 1);
        });
    });

    updateStatements = function (index) {
        statements.hide();
        $(statements.get(index)).show();

        arrows.hide();
        $(arrows.get(index)).show();
    }

    updateStatements(0);
    /* End Speech section setup */

    Cufon.replace('#menus', { hover: false });


    loadContent();

    Cufon.replace('h1', { hover: false });
    Cufon.replace('h2', { hover: false });
    Cufon.replace('.statement', { hover: false });

    $('.previous img').hover(function () {
        $('.previous img').attr('src', '/images/arrow_down_ovr.gif');
    });

    $('.previous img').mouseout(function () {
        $('.previous img').attr('src', '/images/arrow_down_active.gif');
    });

    $('.next img').hover(function () {
        $('.next img').attr('src', '/images/arrow_up_ovr.gif');
    });

    $('.next img').mouseout(function () {
        $('.next img').attr('src', '/images/arrow_up_active.gif');
    });



});




validateEmail = function(email){
   var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
   return pattern.test(email);
}

submitContactForm = function () {
    var form = $("#contact-us");

    // clear validation errors on each attempt
    var validation = form.find('.validation');
    validation.html('').hide();

    var postData = {};
    postData.name = form.find('input.name').val();
    postData.email = form.find('input.email').val();
    postData.subject = form.find('input.subject').val();
    postData.body = form.find('textarea.body').val();

    // client-side validation
    var errors = new Array();
    if (postData.name == null || postData.name == '') {
        errors.push('Name is required.');
    }
    if (postData.email == null || postData.email == '') {
        errors.push('Please enter a valid email.');
    } else if (!validateEmail(postData.email)) {
        errors.push('Please enter a valid email.');
    }
    if (postData.subject == null || postData.subject == '') {
        errors.push('Subject is required.');
    }
    if (postData.body == null || postData.body == '') {
        errors.push('Message is required.');
    }

    if (errors.length > 0) {
        var markup = '<ul>';
        for (var i = 0; i < errors.length; i++) {
            markup += '<li>' + errors[i] + '</li>';
        }
        markup += '</ul>';
        validation.html(markup).fadeIn();
    } else {
        $.post('/ajax/Contact.ashx',
            postData,
            function (data) {
                if (data !== "OK") {
                    // todo: decide what to do with server errors here.
                    alert(data);
                } else {
              
                    $('#contact-us-thanks').fadeIn('slow', $('#contact-us-thanks').show());
                    $('#contact-us-thanks').fadeOut(10000);
                    $('input:text').val("");
                    $('textarea').val("");
          
                 

                }
            }
        );
    }
}

   



submitNewsletterForm = function () {
    var form = $("#newsletter");

    // clear validation errors on each attempt
    var validation = form.find('.validation');
    validation.html('').hide();

    var postData = {};
    postData.email = form.find('input.email').val();

    // client-side validation
    var errors = new Array();
    if (postData.email == null || postData.email == '') {
        errors.push('Please enter a valid email.');
    } else if (!validateEmail(postData.email)) {
        errors.push('Please enter a valid email.');
    }

    if (errors.length > 0) {
        var markup = '<ul>';
        for (var i = 0; i < errors.length; i++) {
            markup += '<li>' + errors[i] + '</li>';
        }
        markup += '</ul>';
        validation.html(markup).fadeIn();
    } else {
        $.post('/ajax/Newsletter.ashx',
            postData,
            function (data) {
                if (data !== "OK") {
                    // todo: decide what to do with server errors here.
                    alert(data);
                } else {
                    $('#newsletter-thanks').fadeIn('slow', $('#newsletter-thanks').show());
                    $('#newsletter-thanks').fadeOut(10000);
                    $('input:text').val("");
                }
            }
        );
    }
}
