/******************************************
 * Global Functions/Helper, Variables
 *****************************************/
_defaultScheme = 'black';
_currentScheme = '';
_historyInit = null;
_gridDelay = 200; // 200ms delay between loading grid blocks
_coverUp = null;
// this flag determines whether the site can use ajax to transition
// from page to page or if it has to use the native browser refresh
// false - browser refresh, true - can transition
_canTransition = false;

/*******************************************************************************
 * MAIN DOCUMENT READY (GLOBAL)
 ******************************************************************************/
$(document).ready(function() {
    
    // Analytics, downloadables
    $("a.download").live("click", function () {
        _gaq.push(['_trackEvent', 'Download', $(this).attr("title") == "" ? $(this).attr("href") : $(this).attr("title"), location.href]);
        return true;
    });

    // Add on-click events to all external links
    $("a.external").live("click", function (e) {
        _gat._getTrackerByName()._trackEvent('Outbound Links', this.href);
        setTimeout('window.open("' + this.href + '", "New Tab/Window")', 100);
        e.preventDefault();
    });

    // all tweets should be outbound
    $('#twitter_div a').attr('target', '_blank');
    
    // links to external sites, .pdf's
    $('a[href^="http"]').not('a[href*="' + document.domain + '"]').addClass('external');

    /**********************************
     * OUR WORK
     * 
     * View by visuals and view by list
     */
    $('#viewType a').live('click', function(e) {
        // visual view selected
        if($(this).attr('id') == 'lnk-visualView' && ! $(this).hasClass('active'))
        {
            $('#listView').slideUp('fast', function(){
                $('.visualViewGrid').slideDown('fast');
            })
        }
        // list view selected
        else if($(this).attr('id') == 'lnk-listView' && ! $(this).hasClass('active'))
        {
            $('.visualViewGrid').slideUp('fast', function(){
                $('#listView').slideDown();
            });
        }
        
        $('#viewType a').removeClass('active');
        $(this).addClass('active');
        
        e.preventDefault();
    });
    
    /**********************************
     * Color Scheme Changer 
     *********************************/
    var $schemeChangers = $('#schemeNav a');

    $($schemeChangers).live('click', function(){
        $($schemeChangers).removeClass('active')
        $(this).addClass('active');
        
        // modify body class
        var newScheme = (this.getAttribute('rel'));
        setColorScheme(newScheme);
        
        return false;
    });
 
    // set background color active link
    $($schemeChangers).removeClass('active');
    $('#schemeNav a[rel="' + _currentScheme + '"]').addClass('active');
    
    /**********************************
     * Faux Links
     * 
     * Grid blocks should respond to hover's but the markup within them is
     * often too complicated and won't fit standards if the block is created
     * using an anchor link
     */
    $('.fauxLink').live('click', function(){
        $anchors = $(this).find('a');

        // if only one link, entire blok is hot
        if($anchors.length == 1)
        {
            $($anchors).trigger('click');
        }
    });
    
    // hover used to change background color of different schemes on rollover
    $('.fauxLink').live('hover', function(){
        $(this).toggleClass('blokHover');
        
        // if only one link, the entire blok is hot
        if($(this).find('.active a').length == 1)
        {
            $(this).css('cursor', 'pointer');
        }
    });
    
    // h4 category link
    $('h4.catLnk a').live('click', function(){
        $span = $(this).find('span');
        
        if($($span).text() == '+')
        {
            $(this).addClass('active').parent().next().slideDown();
            $($span).text('-');
        }
        else
        {
            $(this).removeClass('active').parent().next().slideUp();
            $($span).text('+'); 
        }
        
        return false;
    });
});

/*******************************************************************************
 * Page specific functionality
 ******************************************************************************/

/** Home **/
var homeFx = function(){
    // show hidden items if page has already been ignited.
    if(readCookie('ignitedHome')){
        $('#homegrid .gridBlok').each(function(i){
            $(this).delay(i * _gridDelay).fadeIn();
        });
    }
    else
    {
        $('.initHidden').hide();
        $('#igniteSomething').fadeIn();
    }
    
    $('#blok-readthebook a.readme').live('hover', function(e){
       $('#blok-readthebook .overlay').show();
    });
    
    $('#blok-readthebook .overlay').live('mouseleave', function(e){
       $('#blok-readthebook .overlay').hide();
    });    
    
    $('#igniteSomething').live('click', function(){
        $(this).fadeOut();
        
        // set ignitedCookie
        createCookie('ignitedHome', 'true', 0);
        
        // show all prehidden elements
        $('#homegrid, #mainNav, #footer, .initHidden').fadeIn();
        
        $('#homegrid .gridBlok').each(function(i){
            $(this).delay(i * _gridDelay).fadeIn();
        });
                
        return false;
    });

    //-----------------------------------------
    // Home Page Cycles
    //-----------------------------------------
    var cycleOnAfter = function(curr, next, opts, fwd){
        var ht = ($(this).height() == 0) ? $(this).parent().height() : $(this).height();
        $(this).parent().animate({height: ht});
    }
    
    $('#blok-featuredinsights ul').cycle({
        fx: 'scrollUp',
        timeout: 6000,
        after: cycleOnAfter
    });

    $('#blok-gyroblog ul, #blok-advtoforbes ul').cycle({
        fx: 'scrollUp',
        timeout: 7000,
        after: cycleOnAfter
    });
    
    $('#blok-twitter ul, #blok-latestnews ul').cycle({
        fx: 'scrollUp',
        timeout: 5000,
        after: cycleOnAfter
    }); 
    
    $('#blok-clientwork ul').cycle({
        fx: 'fade',
        timeout: 5500
    });

    $('#blok-globalideas ul').cycle({
        fx: 'fade',
        timeout: 5500
    });

    /**
     * This segment halts/pauses/stops the cycles
     * whenever a transition link has been clicked.
     * This stops the carousel from trying to run when the home page
     * has been dynamically removed from the screen and a new page loaded.
     * 
     * a.transition also has another event bound to 'click' in the file
     * navigation.js
     * 
     * We preventDefault only when _canTransition is true
     */
    $('a.transition').live('click', function(e){
        if(_canTransition)
        {
            e.preventDefault();
        }
        
        // Destroy all cycles
        $('#blok-featuredinsights ul, #blok-gyroblog ul').cycle('destroy');
        $('#blok-twitter ul, #blok-latestnews ul, #blok-clientwork ul').cycle('destroy');
    });    
};

/** Offices */
var officesFx = function(){
    
    // --------------------------------
    // SHOW FORMS
    // --------------------------------
    $('#lnkGeneralRequests, #lnkNewBusiness').live('click', function(){
        // return on current
        if($(this).hasClass('active')) {return false;}
        
        // hide/show forms
        $hide_me = $('.otherFrm').slideUp();
        $('#' + this.rel).slideDown();
        
        _reset_form($hide_me);
        
        // activate/deactivate
        $('.copySideNav a').removeClass('active');
        $(this).addClass('active');
        
        // TASK: initialize form
        
        return false;
    })
    
    $('.baseBox a.closeme').live('click', function(){
        $obj_to_close = $(this).parent().parent();
        
        $($obj_to_close).slideUp();
        $('.copySideNav a').removeClass('active');
        
        // reset form
        _reset_form($obj_to_close);
        
        return false;
    });
    
    // Since we will be replacing the current image with the highlight, we only
    // are worried about the image for mouseenter
    $('#visualViewGrid a').live('mouseenter', function(){
        _coverUp = $(this);
        $(this).addClass('invisible');
        // manipulate hiliter
        var $hilitePos = $(this).position();
        $('#hiliteTitle').text(this.title);
        $('#vvHilite').css({left: $hilitePos.left, top: $hilitePos.top}).show();
    });
 
    $('#visualViewGrid #vvHilite').live('mouseleave',
        function(){
        $('#visualViewGrid a.invisible').removeClass('invisible');
        $(this).hide();
    });
    // trigger a click when the user clicks the office banner
    $('#vvHilite').live('click', function(){
        $(_coverUp).trigger('click');
    })   
    
    //------------------------------------
    // FORM VALIDATION
    // 
    // GENERAL REQUEST FORMS
    //------------------------------------
    $errorContainer = $('.errorContainer');
    
    $frmGeneralRequest = $('#frmGeneralRequest');
    
    $($frmGeneralRequest).validate({
        errorLabelContainer: $errorContainer,
        wrapper: 'li',
        messages: {
            firstname: 'Please enter your first name',
            lastname: 'Please enter your last name',
            phone: 'Please enter your phone number',
            email: {
                required: 'Please enter your email address'
            },
            companyname: 'Please enter your company name', 
            country: 'Please enter your country',
            comments: 'Please let us know what we can help you with'
        },
        highlight: function(element, errorClass, validClass) {
         $(element.form).find("label[for=" + element.id + "]")
                        .addClass(errorClass);
        },
        unhighlight: function(element, errorClass, validClass) {
         $(element.form).find("label[for=" + element.id + "]")
                        .removeClass(errorClass);
        },
        submitHandler: function() {
            // show loading icon
            var loadingImgClass = (_currentScheme == 'white') ? 'white' : 'neutral';
            $('.loadingIcon img.' + loadingImgClass).css('visibility','visible');
            
            var ajaxSettings = {
                type: 'POST',
                url: $($frmGeneralRequest).attr('action'),
                data: $($frmGeneralRequest).serialize(),
                success: function(data, status, xhr) {
                    
                    var strOutput = '<div id="afterSubmission" style="height: ' + $($frmGeneralRequest).outerHeight() + 'px; width: ' + $($frmGeneralRequest).outerWidth() + 'px;">' + data + '</div>';

                    // call form success callback
                    $($frmGeneralRequest).after(strOutput);
                    
                    // destroy loading icon
                    $('.loadingIcon img').css('visibility', 'hidden');
                }
            }
            
            $.ajax(ajaxSettings);
        }
    });
   
    //------------------------------------
    // FORM VALIDATION
    // 
    // NEW BUSINESS FORMS
    //------------------------------------
    $frmNewBusiness = $('#frmNewBusiness');

    $($frmNewBusiness).validate({
        errorLabelContainer: $errorContainer,
        wrapper: 'li',
        messages: {
            firstname: 'Please enter your first name',
            lastname: 'Please enter your last name',
            phone: 'Please enter your phone number',
            email: {
                required: 'Please enter your email address'
            },
            companyname: 'Please enter your company name', 
            country: 'Please enter your country',
            comments: 'Please let us know what we can help you with'
        },
        highlight: function(element, errorClass, validClass) {
         $(element.form).find("label[for=" + element.id + "]")
                        .addClass(errorClass);
        },
        unhighlight: function(element, errorClass, validClass) {
         $(element.form).find("label[for=" + element.id + "]")
                        .removeClass(errorClass);
        },
        submitHandler: function() {
            var loadingImgClass = (_currentScheme == 'white') ? 'white' : 'neutral';
            $('.loadingIcon img.' + loadingImgClass).css('visibility','visible');
            
            // submit 
            var ajaxSettings = {
                type: 'POST',
                url: $($frmNewBusiness).attr('action'),
                data: $($frmNewBusiness).serialize(),
                success: function(data, status, xhr) {
                    
                    var strOutput = '<div id="afterSubmission" style="height: ' + $($frmNewBusiness).outerHeight() + 'px; width: ' + $($frmNewBusiness).outerWidth() + 'px;">' + data + '</div>';

                    // call form success callback
                    $($frmNewBusiness).after(strOutput);
                    
                    // destroy loading icon
                    $('.loadingIcon img').css('visibility', 'hidden');
                }
            }
            
            $.ajax(ajaxSettings);
        }
    });

    var _reset_form = function(frm)
    {
        $(frm).find('.frmHolder input[type="text"], .frmHolder textarea').val('');
        $(frm).find('#afterSubmission').remove();
    }
};

/* What we love */
var welove_Fx = function()
{
    // Thumbnail hovers
    $('.caseThumb a.overlay').hover(function(){
        $(this).toggleClass('showOverlay');
    });    
}

//--------------------------------------------------
// CONTACT US NOW
//--------------------------------------------------

/* google maps setup */
var initializeGMAP = function(lat, lon, off_name, off_addy)
{
    var latlng = new google.maps.LatLng(lat, lon);
    var opt = {
        zoom: 14,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    
    var map = new google.maps.Map(document.getElementById("mapHolder"), opt);
    var marker = new google.maps.Marker({
        position: latlng,
        map: map
    });
    
    var balloon = new google.maps.InfoWindow({
        content: "<div class='mapBalloon'><h1>gyro: " + off_name + "</h1><p>" + off_addy + "</p></div>"
    });
    google.maps.event.addListener(marker, "click", function() {
        balloon.open(map, marker);
    });    
}

/* page(s): Everywhere */
var everywhere_Fx = function(){
    //------------------------------------
    // FORM VALIDATION
    // 
    // CONTACT FORM
    //------------------------------------
    var $errorContainer = $('div.errorContainer');
    var $frmContactOffice = $('#frmContactOffice');
    
    $($frmContactOffice).validate({
        errorLabelContainer: $errorContainer,
        wrapper: 'li',
        messages: {
            fullname: 'Please enter your full name',
            phone: 'Please enter your phone number',
            email: {
                required: "Please enter your email address"
            },
            comments: 'Please let us know what we can help you with'
        },
        highlight: function(element, errorClass, validClass) {
         $(element.form).find("label[for=" + element.id + "]")
                        .addClass(errorClass);
        },
        unhighlight: function(element, errorClass, validClass) {
         $(element.form).find("label[for=" + element.id + "]")
                        .removeClass(errorClass);
        },
        submitHandler: function() {
            var loadingImgClass = (_currentScheme == 'white') ? 'white' : 'neutral';
            $('.loadingIcon img.' + loadingImgClass).css('visibility','visible');
            
            // submit 
            var ajaxSettings = {
                type: 'POST',
                url: $($frmContactOffice).attr('action'),
                data: $($frmContactOffice).serialize(),
                success: function(data, status, xhr) {
                    
                    var strOutput = '<div id="afterSubmission" style="height: ' + $($frmContactOffice).outerHeight() + 'px; width: ' + $($frmContactOffice).outerWidth() + 'px;">' + data + '</div>';

                    // call form success callback
                    $($frmContactOffice).after(strOutput);
                    
                    // destroy loading icon
                    $('.loadingIcon img').css('visibility', 'hidden');
                }
            }
            
            $.ajax(ajaxSettings);
        }
    });
}

/* page: Client Work */
var clientwork_Fx = function()
{
    $('.csfeature a.overlay').hover(function(){
        $(this).toggleClass('showOverlay');
    });  
    
    $('#csFeaturettes a').lightBox({
        fixedNavigation:true,
        overlayOpacity: 0.9,
        imageLoading: 'assets/images/ajax-loader.gif',
        imageBtnClose: 'assets/images/lightbox-btn-close.png',
        imageBtnNext: 'assets/images/lightbox-btn-next.png',
        imageBtnPrev: 'assets/images/lightbox-btn-prev.png',
        containerBorderSize: 0
    });    
}

/* page: Careers */
var careers_Fx = function(careersOffSlug)
{
    var defaultSelect = (typeof careersOffSlug == 'function') ? 'all' : careersOffSlug;
    
    // Stylish Selects
    $('select').sSelect({defaultText: defaultSelect}).change(function(event){   
        if(event.target.value == 'all')
        {
            $('.careercity').show();
        }
        else
        {
            $('.careercity').hide();
            $('#careers-' + event.target.value).show()
        }

        $('.panelGrid').animate({height: $('#careersHolder').height() + 340});
    });
    
    $('.careerInfoFlag').live('click', function(){
        if($(this).html() == '+')
        {
            // height of #careers to auto
            $('.panelGrid').css('height', 'auto');
            $(this).html('-').siblings('.careermeta').slideDown();
        }
        else
        {
            $(this).html('+').siblings('.careermeta').slideUp();
        }     
    });

    $('.hdrCareerInfoFlag').live('click', function(){
        $(this).parent().siblings('.careerInfoFlag').trigger('click');
    });
    
    // preselected office careers
    if(typeof careersOffSlug != 'function')
    {
        $('.careercity').hide();
        $('#careers-' + careersOffSlug).show()       
    }
    
    /**********************************
     * Careers Application
     *********************************/
    $('.career .applyLnk').live('click', function(){
        var ids = $(this).attr('rel').split(":");
        $('#oid').val(ids[0]);
        $('#cid').val(ids[1]);
        $('#jobrole').val($('.cid-' + ids[1]).html());
        $('#application').show();
        $('#gridKeeper').css({position: 'relative'});
        $('.panelGrid, #gridKeeper').animate({
            left: '-728px',
            height: $('#application').height()
        });
        $('html, body').animate({scrollTop:100}, 'slow');
        return false;
    });
    
    $('#backtocareers').live('click', function(){
        if($(this).hasClass('reduceHeight'))
        {
            $('.panelGrid').height(($('.panelGrid').height() - 300));
        }
        
        // TASK: after hiding, reset the form; clearing out all fields
        $('.panelGrid, #gridKeeper').animate({
            left: '0',
            height: $('#careers').height()
        }, 'slow', function() {
            $('#gridKeeper').css({position: 'static'}); 
            $('#application').hide();
        });   
        return false;
    });    
    
    $("input[type=file]").filestyle({ 
         image: "/assets/images/btn_fileselect.png",
         imageheight : 26,
         imagewidth : 53,
         width : 492
    });    
    
    //------------------------------------
    // FORM VALIDATION
    // 
    // CAREERS APPLICATION
    //------------------------------------
    // Validate file extension
    $.validator.addMethod("uploadFile", function(val, element) {
        var ext = $('.file').val().split('.').pop().toLowerCase(); 
        var allow = new Array('pdf','doc','docx'); 
        return ($.inArray(ext, allow) == -1) ? false : true;
    }, "Please select a resume/cv that is a Word Doc or PDF");

    $errorContainer = $('.errorContainer');
    
    /* Application FORM */
    $('#frmCareerApp').validate({
        errorLabelContainer: $errorContainer,
        wrapper: 'li',
        messages: {
            firstname: 'Please enter your first name',
            lastname: 'Please enter your last name',
            address1: 'Please enter your address',
            city: 'Please enter your city',
            state: 'Please enter your state',
            postalcode: 'Please enter your postal code',
            country: 'Please enter your country',
            phone: 'Please enter your phone number',
            email: {
                required: "Please enter your email address"
            },
            resume: {
                required: "Please select a resume/cv"
            },
            message: 'Please enter a message'
        },
        rules : {
            resume: {
                uploadFile: true
            }       
        },
        highlight: function(element, errorClass, validClass) {
         $(element.form).find("label[for=" + element.id + "]")
                        .addClass(errorClass);
        },
        unhighlight: function(element, errorClass, validClass) {
         $(element.form).find("label[for=" + element.id + "]")
                        .removeClass(errorClass);
        },
        invalidHandler: function(form, validator) {
            $('.panelGrid').height(($('.panelGrid').height() + 300));
            $('#backtocareers').addClass('reduceHeight');
        }
    });      
}

/*******************************************************************************
 * MISCELLANEOUS FUNCTIONS
 ******************************************************************************/

// Browser detection for MSIE
var ie_accept = function()
{
    if (navigator.appName == 'Microsoft Internet Explorer')
    {
        var ua = navigator.userAgent;
        var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
          rv = parseFloat( RegExp.$1 );
        
        return (rv < 7) ? false : true;
    }
    // default is true for non-ie
    return true;
}

/**
 * Set color scheme for site.  If a new scheme is given, then we retrieve the
 * last scheme selected from a cookie.
 **/
var setColorScheme = function(newScheme) {
    // Repurposed code from http://www.dynamicdrive.com
    // See: http://www.dynamicdrive.com/forums/showthread.php?p=259199 for more info
    var i, cacheobj, altsheets=[""];
    if(setColorScheme.chosen)
    {
        try{
            document.getElementsByTagName('head')[0].removeChild(setColorScheme.chosen);
        } catch(e){}
    }

    for(i=0; (cacheobj=document.getElementsByTagName("link")[i]); i++)
    {
        // under normal circumstance we would check to make sure that these
        // stylesheets were "alternates", but the black isn't an alternate so
        // we just confirm it has a title
        if(cacheobj.getAttribute("title")) 
        {
            cacheobj.disabled = true
            altsheets.push(cacheobj) //store reference to alt stylesheets inside array
            if(cacheobj.getAttribute("title") == newScheme)
            { //enable alternate stylesheet with title that matches parameter
                cacheobj.disabled = false //enable chosen style sheet
                setColorScheme.chosen = document.createElement('link');//cloneNode(false);
                setColorScheme.chosen.rel = 'stylesheet';
                setColorScheme.chosen.type = 'text/css';
                if(cacheobj.media)
                {
                    setColorScheme.chosen.media = cacheobj.media;
                    setColorScheme.chosen.href = cacheobj.href;
                    document.getElementsByTagName('head')[0].appendChild(setColorScheme.chosen);
                }
                   
                _currentScheme = newScheme;
    
                createCookie('colorScheme', _currentScheme, 3650);
            }
        }
    }    
}

// Create client side cookie
var createCookie = function(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

// Read client side cookie
var readCookie = function(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}


/*******************************************************************************
 * EXTENSIONS
 ******************************************************************************/

/**
 * Extend jquery for a convenient way to determine if the current selection
 * returns anything
 * 
 * example: $('#selection').exists();
 * @see: http://stackoverflow.com/questions/920236/jquery-detect-if-selector-returns-null
 */
$.fn.exists = function () {
    return this.length !== 0;
}


/*******************************************************************************
 * INITIALIZE
 ******************************************************************************/

// Begin Initialization of file
var colorScheme = readCookie('colorScheme');
    _currentScheme = (colorScheme == null) ? _defaultScheme : colorScheme;
setColorScheme(_currentScheme);
_canTransition = ie_accept(); 
_ignitedHome = readCookie('ignitedHome');

// Set cookie for ignitedHome if a user visits any page before the home page and
// the cookie hasn't been set
if( ! _ignitedHome && (location.hash != '' || location.pathname != '/'))
{
    // set ignitedCookie
    createCookie('ignitedHome', 'true', 0);
}

