$(document).ready(function() {
   
   setupGA();
   setupExternalLinks();
   displayMessages();
   
   //dropClosedSign();
   // $('.closed-dismiss').click(function(){$('#closed-sign').fadeOut();  });
});

function dropClosedSign() {
    
    $('#closed-sign').animate({
        'top': '0px'
    }, 2000, 'easeOutBounce');
    
}
function setupGA() {
   
   var regex_url = /^(https?:\/\/)([^/]+)(\/.*)?$/;
   var regex_loc_url = /(^$)|(^\/.*)$/;
   var regex_mailto_url = /^mailto:(.*)$/;
   var regex_doc_url = /^.+\.(pdf|doc|docx|xls|xlsx|ppt|pptx|txt)$/i;
   
   var cur_location = regex_url.exec(window.location);
   
   // get the custom variables that we'll pass along in the call
   var cv = null;
   if ((typeof customvars) == 'undefined')
      cv = { };
   else
      cv = customvars;
   
   $('a').each(function() {
      
      var href = $(this).attr('href');
      
      if (href) {
         
         var isLocal = (href.slice(0, 1) == '#' || href.search(cur_location[2]) > -1 || regex_loc_url.test(href));
         var isMailto = regex_mailto_url.test(href);
         var isDoc = regex_doc_url.test(href);
         
         if (isMailto) {
            
            $(this).click(function() {
               
               GATrackEventWithVariables("mailto", "click", $(this).attr('href').replace(/mailto:/, ""), cv)
               return true;
            });
            
         } else if (isDoc && isLocal) {
            
            $(this).click(function() {
               
               GATrackEventWithVariables("download", "click", $(this).attr('href'), cv)
               return true;
            });
         
         } else if (!isLocal) {
            
            $(this).click(function() {
               
               GATrackEventWithVariables("outbound", "click", $(this).attr('href'), cv);
               return true;
            });
            
         } else {
            
            // don't need to do anything else to track local links
         }
      }      
   });
   
   // set up rss subscribe link handler as well
   $('#rss a').click(function() {
      GATrackEventWithVariables("RSS", "RSS Subscriber", $(this).attr('href'), cv);
   });
}

function setupExternalLinks() {
   
   var regex_url = /^(https?:\/\/)([^/]+)(\/.*)?$/;
   var regex_loc_url = /(^$)|(^\/.*)$/;
   var regex_mailto_url = /^mailto:(.*)$/;
   var regex_anchor_url = /^#(.*)$/;
   
   var cur_location = regex_url.exec(window.location);

   $('a').each(function() {
      
      // skip over nyromodal links
      if($(this).hasClass("nyroModal")) {
         
         return false;
         
      }
      
      var href = $(this).attr("href");
      
      if (href) {

         if (!((href.search(cur_location[2]) > -1) || // is this domain in the href?
            (regex_loc_url.test(href)) || // is this a root-relative url?
            (regex_mailto_url.test(href)) || // is this a mailto? 
            (regex_anchor_url.test(href)) // is this an anchor link?
         
         )) {
            
            // open the link in a new window
            $(this).attr("target", "_blank");

            // add external-link or pdf-link class if this
            // does not have an image inside it
            if (!($(this).find('img').length))
               $(this).addClass('external');         
         }
      }
   });   
}

// display messages to the user
function displayMessages() {
   
   $('#messages').slideDown("slow");
}

// register the search box functionality
function registerSearchBox() {
   
   $('#id_search_keywords').focus(function() {
      if ($(this).val() == "Search")
         $(this).val("");
   });
}

// set up the channels menu in the left navigation
function setupChannelsMenu() {
   
   // hide the channels
   $('#nav_channels').slideUp(0);
   
   // register the more channels link button
   $('#more_channels').attr('href', '#');
   $('#more_channels').click(function() { 
      
      $('#more_channels').toggleClass( 'nav_open' );
      // toggle the channel visibility and
      // don't follow the link click
      $('#nav_channels').slideToggle();
      return false;
   });
}

function setupCUSignupForm() {
   
   // setup AJAX form submission
   $('#cuform-submit').click(function() {
      
      // put up the loader
      $('#ajax-loader').fadeIn();
      
      // get fields
      var fname = $('#cusignup-form input[name=fname]');
      var lname = $('#cusignup-form input[name=lname]');
      var company = $('#cusignup-form input[name=company]');
      var email = $('#cusignup-form input[name=email]');
      
      // setup AJAX data variable for POST request
      var data = 'fname=' + fname.val() + '&lname=' + lname.val() + '&company=' + company.val() + '&email=' + email.val();
      
      $.ajax({
         // POST url
          url: "/cu-signup/",
          type: "POST",
          data: data,
          // if iContact is having troubles, only wait 10 seconds for a response
          timeout: 10000,
          success: function (html) {             
              
              if(html != "") {
               
                 // populate the form div with the response
                 $('#cusignup-form').html(html);
                 
              } else {
                 // something's wrong with the response...
                 
                 // hide the loading spinner
                 $('#ajax-loader').hide();
                 // fade in the error message
                 $('#cusignup-form-ajax-error').fadeIn('fast');  
                 
              }
           },
           error: function() {
              // the POST didn't work...
              
              // hide the loading spinner
              $('#ajax-loader').hide();
              // fade in the error message
              $('#cusignup-form-ajax-error').fadeIn('fast');
              
           },
           cache: false 
      });
      
      // don't follow the link after the click
      return false;
   });
   
}

function setupCUSignupFormControl() {
   // show the form
   $('#cusignup-form').slideDown(0);
   
   // register button
   $('#cusignup-form-control').attr('href', '#');
   $('#cusignup-form-control').click(function() {
      
      // change the little arrow
      $(this).toggleClass('nav_open');
      
      // animate
      $('#cusignup-form').slideToggle();
      
      // don't follow the link!
      return false;
      
   });
}

function registerPagination() {
   
   $('.page_nav').hide();
   $('.ajax_page_nav').show();
   registerPaginationMoreHandler();
}

function registerPaginationMoreHandler() {
   
   // update the "more" copy
   var showing = parseInt($('.ajax_page_nav input[name="pagination_showing"]').val());
   var total = parseInt($('.ajax_page_nav input[name="pagination_total"]').val());
   
   var message = "Showing results 1-" + showing + " of " + total;
   if (showing < total)
      message += ' (<a href="#">show more</a>)';
   $('.ajax_page_nav p').html(message);
   
   // handle "show more" clicks
   $('.ajax_page_nav p a').unbind().click(function() {
      
      // unregister this handler for now
      unregisterPaginationMoreHandler();
      
      // what page are we currently on?
      var page = parseInt($('.ajax_page_nav input[name="pagination_page"]').val());
      var perPage = parseInt($('.ajax_page_nav input[name="pagination_per_page"]').val());
      
      // make the AJAX call
      $.ajax({
         url: paginationBaseURL + 'ajax-page/' + window.location.search,
         type: 'POST',
         data: {
            page: page + 1,
            per_page: perPage
         },
         dataType: 'json',
         success: function(data, status, request) {
            
            // set the hidden inputs to keep track of the pagination state
            $('.ajax_page_nav input[name="pagination_page"]').val(data.page);
            $('.ajax_page_nav input[name="pagination_per_page"]').val(data.per_page);
            $('.ajax_page_nav input[name="pagination_showing"]').val(data.showing);
            $('.ajax_page_nav input[name="pagination_total"]').val(data.total);
            
            // reveal the new results
            var oldTotal = $(paginationSelector).length;
            $(paginationSelector + ':last').after(data.results);
            
            var results = $(paginationSelector + ':gt(' + (oldTotal - 1) + ')');
            results.hide();
            
            function reveal(results, index) {
               
               $(results[index]).slideDown(100, function() {
                  if (index < results.length)
                     reveal(results, index + 1);
               });
            }
            reveal(results, 0);
            
            // now we can re-register this handler
            registerPaginationMoreHandler();
         },
         error: function(request, status, error) {
            
            // something went wrong
            // just re-register this handler
            registerPaginationMoreHandler();
         }
      });
      
      return false;
   });
}

function unregisterPaginationMoreHandler() {
   
   $('.ajax_page_nav p a').unbind().click(function() { return false; });
}

function registerSocialLinks(elements) {
    
    if (!elements)
        elements = $('p.social')
    
    elements.find('a.facebook').click(function() {
        
        // open this in a pop-up window
        var left = Math.round(($(document).width() - 550) / 2);
        var top = 250;
        window.open(
            $(this).attr('href'), 
            "facebook_share", 
            "width=550,height=350,left=" + left + ",top=" + top + ",location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no",
            true
        );
        return false;
    });
    
    elements.find('a.twitter').click(function() {
        
        // just open this in a new tab
        $(this).attr("target", "_blank");
        return true;
    });
    
    elements.find('a.linkedin').click(function() {
        
        // open this in a pop-up window
        var left = Math.round(($(document).width() - 520) / 2);
        var top = 200;
        window.open(
            $(this).attr('href'), 
            "facebook_share", 
            "width=520,height=450,left=" + left + ",top=" + top + ",location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no",
            true
        );
        return false;
    });
    
    elements.find('a.email').click(function() {
        
        // has this been resolved yet?
        if ($(this).attr('href').search('mailto:') != 0) {
            
            // synchronously resolve the mailto: url
            (function(elem) {
                
                $.ajax({
                    type: 'GET',
                    async: false,
                    url: $(elem).attr('href'),
                    success: function(data, status, request) {
                        // overwrite the href with the returned url
                        $(elem).attr('href', data.url);
                    },
                    dataType: 'json'
                });
            })($(this));
        }
        return true;
    })
}


// GA helpers
// maps the custom variable names to their index slots
// and scope level
var GA_CUSTOM_VARS = {
   'insights': {
      index: 1,
      scope: 1
   },
   'section': {
      index: 2,
      scope: 3
   },
   'channel_section': {
      index: 3,
      scope: 3
   }
};

// dummy function for SWFAddress framework to call
// (pageviews and events are fired manually from Flash)
function dummySWFAddressTracker(value) { }

// track a pageview and set the custom variables.
// custom variables should be passed in an Object mapping
// names to values.
// the slot and scope are automatically configured
// by the known set of variable names defined by GA_CUSTOM_VARS
function GATrackPageviewWithVariables(url, customvars) {
   
   var customvarsString = [];
   for (var key in customvars)
      customvarsString.push(key + ": " + customvars[key]);
   customvarsString = customvarsString.join("\n");
   
   try {
      
      if (customvars) {

         for (name in customvars) {
         
            if (customvars[name] && GA_CUSTOM_VARS[name]) {
            
               var cv_data = GA_CUSTOM_VARS[name];
               pageTracker._setCustomVar(cv_data.index, name, customvars[name], cv_data.scope)
            }
         }
      }
      
      if (url)
         pageTracker._trackPageview(url);
      else
         pageTracker._trackPageview();
      
   } catch (err) {
      
      // pageTracker not available
   }
}

// track an event and set custom variables
// (as in GATrackPageviewWithVariables)
function GATrackEventWithVariables(category, action, label, customvars) {
   
   try {
      
      if (customvars) {
         
         for (name in customvars) {
         
            if (customvars[name] && GA_CUSTOM_VARS[name]) {
            
               var cv_data = GA_CUSTOM_VARS[name];
               pageTracker._setCustomVar(cv_data.index, name, customvars[name], cv_data.scope)
            }
         }
      }
      
      pageTracker._trackEvent(category, action, label);
      
   } catch (e) {
      
      // pageTracker not available
   }
}

