/*  File: nav.js
 *  Author: Nick Hoffman
 *  Metro Studios
 *  Handles AJAX navigation events
 * 
 * Secondary navigation, loaded elements depend on page template of source and target pages
 * Template 1 = Landing page
 * Template 2 = Without photo slider, without right sidebar
 * Template 3 = Without photo slider, with right sidebar
 * Template 4 = With photo slider, without right sidebar
 * Template 5 = With photo slider, with right sidebar
 * 
 * Todo: 
 *      Show active subnavigation when url is manually inputted (or always redirect to template)
 */  

 



$(document).ready( function() 
{       
    var oldUrl = window.location.pathname + window.location.search;
    var oldTemplate = null;
    var newUrl = null;
    var newTemplate = null;
    var selector = '.subnav a[href="' + oldUrl + '"]';    
    
    
    $('.about-board-minutes .left-pane a').live('click',function(e) {
        e.preventDefault();
    })
    $('a:not(.nolink)').address();
        
    // If navigating to page manually set page's selector to active
    if (!($(selector).hasClass('active')))
    {
        $('.subnav li').removeClass('active');
        $(selector).parent().addClass('active');        
    }    

    // External linking/navigation, less restrictive     
     $.address.externalChange(function(e) {
        if (typeof e !== 'function') {   
            newTemplate = e.parameters.t;
            var newUrl = (e.queryString.length > 0) ? e.path + '?' + e.queryString : e.path;
            if (!window.location.href.match('#'))
                window.location = "http://" + window.location.hostname + "/#" + window.location.pathname;
            if (newTemplate == null || newTemplate == 1 || ($('#page-wrapper').css('display') == 'none'))
                var target = '#page-wrapper';
            else
                var target = '#main-col';
            loadContent(target, newUrl);
            oldTemplate = newTemplate;            
            oldUrl = newUrl; 
        }   
    });
        
     // Internal linking/navigation, more restrictive (won't load if attempting to visit same page)
    $.address.internalChange(function(e) {
        if (typeof e !== 'function') {
            newTemplate = e.parameters.t;
            var newUrl = (e.queryString.length > 0) ? e.path + '?' + e.queryString : e.path;

            if  (oldUrl.match(/recycle-guide/) && newUrl.match(/recycle-guide/))
                oldUrl = newUrl;    

            else if (oldUrl != newUrl) {
                if (oldUrl.match(/news/) && newUrl.match(/news/))
                    var target = '#main-col';                                                    
                else if (oldUrl.match(/events/) && newUrl.match(/events/))  
                    var target = '#main-col';                                
                else if (newTemplate == null || newTemplate == 1 || ($('#page-wrapper').css('display') == 'none'))
                    var target = '#page-wrapper';                
                else
                    var target = '#main-col';                                
                loadContent(target, newUrl);
                oldTemplate = newTemplate;            
                oldUrl = newUrl;                 
            }
        }   
    });
    

    
      
});


// Main content loading function
function loadContent(target, newUrl) { 
        var selector =  newUrl + ' ' + target + ' > *';
        $(target).animate(
            { opacity: 0.01 }, 
            500, 
            function() {
                $(target).load(selector, function() { 
                    $(target).css('display','block');  
                    $(target).animate(
                        {opacity: 1.00 },
                        1000
                    );
                      // Load external scripts for specific pages   
                     if ($.address.path() == '/recycle-guide/')
                        $.getScript('/recycle-guide/include/getrecycle.js');
                        
                     if ($.address.path() == '/')
                        $.getScript('/js/home-slider.js');
                        
                     if ($.address.path() == '/about/contact/')
                        $.getScript('/js/form-contact.js'); 
                        
                     if ($.address.path() == '/education/request-educator/') {
                        $.getScript('/js/form-educator-request.js');  
                        }               
                     
                     if ($.address.path() == '/search/') {
                          query = $.address.queryString();
                            $('#content').load('/sphider/search.php?' + query + ' #result_report', function() { 
                                   $("html, body").animate({ scrollTop: 0 }, "slow");
                            });                               
                     }                        
                        
                        // Update left sidebar with active page    
                        $('.subnav li').removeClass("active");
                        $('.subnav a[href="' + newUrl + '"]').parent().addClass("active");
                        
                        // Reassign recycling module event handlers after AJAX load
                        $('.recycle form').submit( function(e) {
                            e.preventDefault();   
                            var cat = escape($('select[name="cat"] option:selected').text());
                            var search = escape($('#recycle-search').val());
                            var getString = (search.length > 0) ? '?cat=' + cat + '&rsearch=' + search : '?cat=' + cat;
                            $.address.value('/recycle-guide/' + getString);
                            $.getScript('/recycle-guide/include/getrecycle.js'); 
                         });
                         
                         // Reassign newsletter signup event handlers
                            $('.newsletter form').live('submit', function(event) {
                                event.preventDefault();
                                var name = $('.newsletter #name').val();
                                var email = $('.newsletter #email').val();
                                
                                if (!name.length > 0 || !name.length >0) {
                                    alert("You must fill in both fields to sign up for the newsletter");
                                    return;
                                }
                                $('.newsletter .button').hide();            
                                $('.newsletter .loadbar').fadeIn('1000');
                                
                                if (name.indexOf(' ') != -1) {
                                    first_name = name.substring(0, name.indexOf(' '));
                                    last_name = name.substring(name.indexOf(' '),name.length);
                                }   
                                else {
                                    first_name = name;
                                    last_name = '';
                                }
                                $.ajax({
                                   url: '/include/addContact.php',
                                   type: 'post',
                                   data: 'first_name=' + first_name + '&last_name=' + last_name + '&email=' + email,
                                   success: function(result) {
                                       if (result == 'add') {
                                            $('.newsletter .loadbar').html('Successfully added!');
                                       }
                                       else if (result == 'update') {
                                           $('.newsletter .loadbar').html('Successfully updated!');
                                       }
                                       else {
                                            alert("There was a problem adding your name to the list: " + result);
                                            $('.newsletter .loadbar').html('Error!');
                                       }
                                   },
                                   error: function(jqXHR, textStatus, errorThrown) {
                                       alert(errorThrown);
                                   }
                                });
                           });    
                                            
                        // Newsletter inline field labels
                        $('.inline label').inFieldLabels(); 
                        
                        // jScrollPane for History Timeline
                        $('.scroll-pane').jScrollPane();
                        
                        // Iterate through all links, if they point to an external site open site normally
                        $('a').each(function() {
                            var href = $(this).attr('href');
                            if(this.hostname && this.hostname !== location.hostname) {   
                                $(this)
                                    .addClass('nolink')
                                    .click(function() {
                                        window.open($(this).attr('href'));
                                        $.address.value($.address.value());
                                        return false;
                                    });              
                                 
                             }
                             if (href.indexOf('pdf') != -1 || href.indexOf('doc') != -1 || href.indexOf('docx') !=-1) {
                                $(this)
                                    .addClass('nolink')
                                    .click(function() {
                                        window.open($(this).attr('href'));
                                        return false;
                                    });
                             }
                             if (href.indexOf('mailto:') != -1) {
                                $(this)
                                    .addClass('nolink')
                                    .click(function() {
                                        window.open($(this).attr('href'));
                                        return false;
                                    });                     
                             }                         
                    });
                    
                    // Load/update breadcrumb paths (outside of page-wrapper, has to be loaded separately)
                    $('.breadcrumbs').load(newUrl + ' ' + ' .breadcrumbs > *', function() {               
                        $(target).animate(
                            {opacity: 1.00 }, 
                            1000
                        );                        
                    });
            });       
      });      
}
                           

function strpos (haystack, needle, offset) {
      var i = (haystack+'').indexOf(needle, (offset || 0));
      return i === -1 ? false : i;
}

