// Hover Behaviour for Nav etc.
var HoverBehavior = Class.create({
  initialize: function() {
    // $A(document.styleSheets).each( function(stylesheet) {
    //   $A(stylesheet.rules).each( function(rule) {
    //     if( rule.selectorText.match(/:hover/i) ) {
    //       stylesheet.addRule( rule.selectorText.replace(/:hover/ig, '.hover'), rule.style.cssText );
    //     }
    //   });
    // });
    $A(arguments).each( function(arg) {
      $$(arg).each( function(tag) {
        Event.observe(tag, 'mouseenter', function() { Element.addClassName(tag, 'hover'); }, true);
        Event.observe(tag, 'mouseleave', function() { Element.removeClassName(tag, 'hover'); }, true);
      });
    });
  }
})

var InputDefaultValue = Class.create({	
  initialize: function(field){
    // Ensure container exists
    if (!$(field)) { return false; }

    this.field = $(field);
    this.defaultValue = $F(this.field);

    // Clear field on click
    Event.observe(this.field, "click", function(){
      if ($F(this.field)==this.defaultValue) { 
        $(this.field).clear(); 
      }
      $(this.field).activate();
    }.bind(this));

    // Restore field's default text when empty
    Event.observe(this.field, "blur", function(){
      if (!$(this.field).present()) { 
        $(this.field).setValue(this.defaultValue); 
      }
    }.bind(this));
  }
});




// Cookie functions from ---> http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(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;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}




var CNQ = Class.create();
CNQ.prototype = {
  
  slideshow: function(){
    if ($('masthead')){
      new Slides({
        delay             : 8000,
        container         : '#masthead',
        slides_container  : 'ul.slides',
        before_transition : function(current_slide, next_slide){ Cufon.replace('#'+ next_slide.id +' .overlay') }
      })      
    }
  },
  
  external_links: function(){
    var filter = new RegExp($A(arguments).join('|'))    
    $$('a[href^=http]').each(function(a){

      if (a.href.match(filter)) {
        // Force link to be internal
      } else {
        // Force link to be external
        a.observe('click', function(e){
          var new_window = window.open(a.href,'_blank')
          new_window.focus()
          e.stop()
        })
      }
    })
  },
  
  // Allow for media elements to be linked inline a text block 
  // <a class="inline_media" rel="media1">some inline text</a>
  inline_media: function(){
    $$('.inline_media').each(function(a){    
      var mediaelement = $(a.readAttribute('rel'))
      if (!mediaelement) { return }

      var new_link = '<a href="#{href}" title="#{title}">#{text}</a>'.interpolate({ 
        href: mediaelement.down('a').readAttribute('href'), 
        title: mediaelement.down('a').readAttribute('title'),
        text: a.innerHTML})

      a.replace(new_link)
      mediaelement.hide()
    })    
  }, 

  nav_parent_class: function(){
    $$("#nav ul.nav-list > li > a").each(function(a){
      if (a.next(0)) { a.addClassName('parent'); }
    });
  },  

  email_forms: function(){
    $$('a.email_form').each(function(a){
      a.observe('click',function(e){
        e.stop();
        window.open(a.href,'_blank','width=573,height=525');
      })
    })	  
  },

  search_box: function(){
    new InputDefaultValue('term');	  
  },
  
  initialize : function(){
    this.slideshow();
    this.external_links('cnrl.com');
    this.inline_media();
    this.nav_parent_class();
    this.email_forms();
    this.search_box();    
  }
};


// Global DOM onload
document.observe("dom:loaded", function() {

  // Let the CSS know JS is enabled
  $$('body').first().addClassName('js') 
  
  // Mark if we're in surf-to-edit
  if (location.href.match(/nterchange/g)) { 
    $$('body').first().addClassName('nterchange') 
    $$('body').first().insert('<div id="nterchange"></div>')
  }

  var cnq = new CNQ();


  // If no cookie has been set, rewrite all links to the disclaimer page
  if (readCookie('agree-careers')!='true') {
    $$('a[href^=/careers],a[href*=careers.cnrl.com],a[href*=careerscorp.cnrl.com]').each(function(a){
      if (!a.hasClassName('redirected')){
        a.href = '/careers-disclaimer.html?redirect=' + a.href;
        a.addClassName('redirected');
      }
    });
  }

  // If no cookie has been set, rewrite all links to the disclaimer page
  if (readCookie('agree')!='true') {
    $$('a[href*=cnrl.com],a[href^=/]').each(function(a){
      if (!a.hasClassName('redirected')){
        a.href = '/disclaimer.html?redirect=' + a.href.replace('?redirect','&redirect');
        a.addClassName('redirected');
      }
    });
  }

  switch(parseInt($$('meta[name=page_id]')[0].content)){

    // Disclaimer
    case 140: 
      $('disclaimer_form').onsubmit = function(){ return false; }
      $('disclaimer_form').down('input').onclick = function(){
        createCookie('agree','true',1);
        window.location.href = location.search.split('?redirect=')[1];
      }
      break;

    // Careers Disclaimer
    case 214: 
      if (readCookie('agree')=='true') {
        $$('.disclaimer-text').invoke('hide');
        $$('#disclaimer_form input')[0].value = "Continue";
        $$('#disclaimer_form input')[1].hide();
      }
      $('disclaimer_form').onsubmit = function(){ return false; }
      $('disclaimer_form').down('input').onclick = function(){
        createCookie('agree','true',1);
        createCookie('agree-careers','true',1);
        window.location.href = location.search.split('?redirect=')[1];
      }
      break;
  }

  // // If on the disclaimer page, set the cookie on agree and redirect
  // if ($('disclaimer_form')){
  //   $('disclaimer_form').onsubmit = function(){ return false; }
  //   $('disclaimer_form').down('input').onclick = function(){
  //     createCookie('agree','true',1);
  //     window.location.href = location.search.split('?redirect=')[1].replace('&redirect','?redirect');
  //   }
  //   if (readCookie('agree')=='true') {
  //     window.location.href = '/';
  //   }
  // }
  // if ($('careers_disclaimer_form')){
  //   $('careers_disclaimer_form').onsubmit = function(){ return false; }
  //   $('careers_disclaimer_form').down('input').onclick = function(){
  //     createCookie('careers-agree','true',1);
  //     window.location.href = location.search.split('?redirect=')[1];
  //   }
  // }
});


Event.observe(window, 'load', function(){
  
  // (don't enable if we're in surf-to-edit mode)  
  if (!$('nterchange')){
    addLinkerEvents() // addLinkerEvents-ga.js
  }
  
  // IE FIXES
  if (Prototype.Browser.IE) {
    // Set some classnames as an alternative hook to CSS 3 selectors
    $$('#nav > ul > li > a').invoke('addClassName','nav_anchor')
    $$('#side li.active > a').invoke('addClassName','active_anchor')
    $$('#nav li:last-child').each( function(tag) { tag.addClassName('last-child'); });
    new HoverBehavior('#nav li'); // keep at the end!
  }
});


