$(document).ready(function() {
  
  // router splash page
  $('#router ul li a').hover(
    function() {
      $(this).find('span').removeClass('visuallyhidden');
    },
    function() {
      $(this).find('span').addClass('visuallyhidden');
    }
  );
  

    $('#templates').change(function() {
      var str = "";
      str = $("#templates").val();
      pid = $("#pid").val();
      $.ajax({
        type: "POST",
        url: "/admin/page/content",
        data: "tpl=" + str + "&pid=" + pid,
        success: function(msg){
            $('#content').html(msg);
        }
      });
    });
    
    //Dynamically add text areas for the elements
    $('.add').click(function() {
        var btnid = this.id;
        var contentid = $('#' + btnid).closest('.content').attr("id");
        var newNum = $('#' + contentid).attr('id').replace(/([a-z]+)/, '');
        jQuery.fn.exists = function(){return jQuery(this).length>0;}

        if ( ! $('#new_content' + newNum).exists()) {
          $('#' + contentid).append('<textarea id="new_content' + newNum + '" name="new_content' + newNum + '" cols="90"></textarea>');
        }
    });
    
  // check for cookie support
  var TEST_COOKIE = 'test_cookie';
  jQuery.cookie( TEST_COOKIE, true );
  if ( jQuery.cookie ( TEST_COOKIE ) ) {
    jQuery.cookie( TEST_COOKIE, null );
  }
  else {
    $('#ns').replaceWith('<div id="noscript-warning"><img src="/images/noscript-warning.png" alt="johnson health tech fitness treadmill elliptical" /></div>');
    $('#page').css('margin-top', '40px');
  }
  
  // drop down locale options div on click
  $(".locale_select").click(function() {
    $("#header_red2").slideToggle("fast");
    $(this).toggleClass("active");
    return false;
  });
  
  // clear value of search input field on focus
  $('div#search_input_text input').focus(function() {
      $(this).val('');
    });

  // add "Search" back as value of search input field on blur
  $('div#search_input_text input').blur(function() {
      $(this).val('Search');
    });
  
  $('div#nav_global a').corner('7px');
  $('div#content_col1, div#content_col2').corner('7px');
  $('div.text_col1, div.text_col2').corner('7px bottom');
  $('#content h1.heavy').corner('7px top');
  $('div.brands_corners').corner('7px');
  $('div#home_col2, div.background').corner('7px');
  $('#sustainability').corner('7px');
  
  $(window).load(function(){ //Because webkit browsers set height and width after images load, don't compute height until loaded.
        computeColumnHeight();
  });
  
  //Financials
  $('.consolidated, .parent').click(function(){
    var detail = $(this).parent().next();
    if(detail.is(':hidden')){
      $('.financials').hide();
      detail.slideDown('slow');
    }
    else{
      detail.slideUp('slow');
    }
    return false;
  });
    
  //Careers
  $('#benefits1_link').click(function(){
      if ($('#benefits1').is(':hidden')){
          $('#benefits1').slideDown('slow', function(){
            computeColumnHeight();
          });
      }
      else {
          $('#benefits1').slideUp('slow', function(){
            computeColumnHeight();
          });
      }
      $('div#content_col1 .text_col1').height('auto'); 
      $('div#content_col2').height('auto');
  });
  
  $('#benefits2_link').click(function(){
      if ($('#benefits2').is(':hidden')){
          $('#benefits2').slideDown('slow', function(){
            computeColumnHeight();
          });
      }
      else {
          $('#benefits2').slideUp('slow', function(){
          computeColumnHeight();
          });
      }
      $('div#content_col1 .text_col1').height('auto'); 
      $('div#content_col2').height('auto');
  });
  
      // video pop-over
  $.widget('.modalcart', $.ui.dialog, {
    'config': {
      'contentsUrl': 'hello',
      'containerElem': null,
      'qtyElem': null
    },
    '_create': function() {
      $.ui.dialog.prototype._create.apply(this, arguments);
    },
    'init': function() {
      return $.ui.dialog.prototype._init.apply(this, arguments);
    },
    'options': {
      'autoOpen': false,
      'width': 550,
      'height': 450,
      'resizable': false,
      'closeText': 'Close',
      'title': null, 
      'open': function(event, ui) {

        var $closeSpan = $("div[role='dialog'] span.ui-icon-closethick");
        $closeSpan.css({
          'display': 'inline',
          'width': '100%',
          'height':'100%',
          'text-indent': 0,
          'overflow': 'visible'
        });
        var spanWidth = $closeSpan.width();
        var offset = 4;
        var textIndent = -(spanWidth + offset);
        textIndent = textIndent + 'px';
        $closeSpan.css({
          'display': 'block',
          'width': '16px',
          'height': '16px',
          'padding-top': '1px',
          'textIndent': '-39px',
          'line-height': '16px',
          'color': '#444',
          'font-size': '80%'
        });
      }
    }
  });
  
  var videoDialog = $('<div id="modal-cart-contents"></div>').modalcart({'width': 670, 'height': 435, 'modal': 'true', 'title': 'Watch Video'});
  $('.video-modal').click(function(){ 
      var url = $(this).attr('href'); 
      var loading = $('<div class="loading"><p><strong>Loading</strong></p></div>');
      $.ajax({
        url: url,
        cache: false,
        beforeSend: function() {
          videoDialog.html(loading).modalcart('open');
        },
        success: function(response) {
          //console.log('success fired'); 
          videoDialog.html(response).modalcart('open');
        }
      });
    return false;
  });
  
  //If user selects North America on careers page, redirect them to NA site.
  $('form select').change(function(){
      var location = $(this).val();
      if(location=='north america'){
          $(this).parent().parent().hide();
          $(this).parent().parent().parent().html('<p>To learn about opportunities in North America please visit the North America Johnson Health Tech website at: <a href="http://us.corporate.johnsonfitness.com/content/careers">http://us.corporate.johnsonfitness.com/content/careers</a></p>');
          computeColumnHeight();
      }
  });
  
  function computeColumnHeight(){
      var template = $('body').attr('id');
      if((template == 'j_template_1') || (template == 'j_template_2')  || (template == 'j_about_us')){
          var col1_height = $('body#j_template_1 div#content_col1, body#j_template_2 div#content_col1, body#j_about_us div#content_col1').height();
          var col2_height = $('body#j_template_1 div#content_col2, body#j_template_2 div#content_col2, body#j_about_us div#content_col2').height();
          if (col1_height > col2_height) {
              
              $('div#content_col1 .text_col1').height(col1_height-50); //Height of header (40) plus top padding on .text_col1 (10)
              $('div#content_col2').height(col1_height);
          }
          else {

              $('div#content_col1 .text_col1').height(col2_height-50); //Height of header (40) plus top padding on .text_col1 (10)
              $('div#content_col2').height(col2_height);
          }
      }
  }

  //jCarouselLite
  $('#carousel').jCarouselLite({
      btnNext: "#next",
      btnPrev: "#prev",
      circular: false,
      visible: 4
  });
  
  $('ul#timeline li div.inner').corner('7px');
  
  //Overlay on timeline.  Disabled.
  /*
  $('a[rel=#overlay]').overlay({
  
      onLoad: function() {
          $('#prev').hide();
          $('#next').hide();
      },
      
      onClose: function() {
          $('#prev').show();
          $('#next').show();
      }
      
  }); 
  $('.simple_overlay').corner('7px');*/
  
  /*//Tooltip
  //Select all anchor tag with rel set to tooltip
  $('a[rel=tooltip], span[rel=tooltip]').mouseover(function(e) {
          
    //Grab the title attribute's value and assign it to a variable
    var tip = $(this).attr('title');
    
    //Remove the title attribute's to avoid the native tooltip from the browser
    $(this).attr('title','');
    
    //Append the tooltip template and its value
    $('body').append('<div id="tooltip"><div class="tipHeader"></div><div class="tipBody">' + tip + '</div><div class="tipFooter"></div></div>');		
    
    //Set the X and Y axis of the tooltip  
    $('#tooltip').css('top', e.pageY - 80 );
    $('#tooltip').css('left', e.pageX - 250 );

    //Show the tooltip with faceIn effect
    $('#tooltip').fadeIn('500');
    $('#tooltip').fadeTo('10',0.9);
    
  }).mousemove(function(e) {
  
    //Keep changing the X and Y axis for the tooltip, thus, the tooltip move along with the mouse
    $('#tooltip').css('top', e.pageY + 10);
    $('#tooltip').css('left', e.pageX - 90);
          
  }).mouseout(function() {
  
    //Put back the title attribute's value
    $(this).attr('title',$('.tipBody').html());

    //Remove the appended tooltip template
    $('body').children('div#tooltip').remove();
          
  });*/
  
  //Tooltip

  //Make an ajax request to load all the tooltips into the DOM only if we're
  //on a page that requires them.
  if(!($('#brands.tooltip').length == 0)){
    var container = $('<div class="tooltips"></div>');
    $('body').append(container); 
    $.ajax({  
      type: 'GET',  
      url: '/tooltip/index/',   
      success: function(data){
          var html = '';
          for(key in data){ 
            html += '<div id="' + key
                        + '" class="tooltip"><div class="tipHeader"></div><div class="tipBody"><p>'
                        + data[key] + '</p></div><div class="tipFooter"></div></div>';
          }
          $('.tooltips').html(html);
      },
      dataType: 'json'
    });
  }
  
  //Manage the hiding, showing and position of tooltip
  $('a[rel=tooltip], span[rel=tooltip]').mouseenter(function(e){
    var brand = $(this).attr('id'); 
    var leftPosition = e.pageX - 90;
    var topPosition = e.pageY + 20; 
    $('.tooltips').find('#' + brand).show();
    $('.tooltips').css({'top' : topPosition, 'left' : leftPosition});
  }).mousemove(function(e){
      var brand = $(this).attr('id');
      var leftPosition = e.pageX - 90; 
      var topPosition = e.pageY + 20; 
      $('.tooltips').css({'top' : topPosition, 'left' : leftPosition});
  }).mouseleave(function(e){
      $(this).removeClass('hovered');
      $('.tooltips .tooltip').hide();
  });

  //Featured product rotating images
  $('.slideshow').cycle({fx: 'fade', random: 1, speed: 8000, pause: 1});
  
  //Home page rotating images on DE site
  $('.main_slideshow').cycle({fx: 'fade', speed: 2500});
  
  //Superfish menu
  $('ul.sf-menu').superfish({
    pathClass: 'current'
  });
  

  //  set width and position of secondary nav ul
  //  dynamically setting the width doesn't work because
  //  changing the text size in the browser does not refresh the page
  //  need to remove jquery menu plugin and rewrite in raw jquery
  //  for now, just set a diff width for IE7
  /*
  var width = 0;
  $('ul.sf-menu ul.subnav li').each(function() {
    width += $(this).outerWidth(true);
    // convert width from px to em
    widthEm = (width * 0.06);
  })
  alert('total width is: ' + width + '\nem width is: ' + widthEm);
  $('ul.sf-menu ul.subnav').css('width', widthEm+'em');
  */

  if($.browser.msie) {
    if($.browser.version == '7.0') {
      $('ul.sf-menu').css({'position': 'relative', 'top': '0', 'left': '-80'});
    }
    $('#content_col2').attr({'style': ''});
    $('.heavy').corner('7px top');
    $('.text_col2').attr({'style': ''}).corner('7px bottom');
  }
  
  //This code was an attempt to temporarily remove current class on hover, but
  //the class couldn't successfully be replaced on mouseout.
  /*
  $('ul.sf-menu li ul a').mouseover(function(){
    var parent = $('ul.sf-menu li ul li.current').parent().index();
    var child = $('ul.sf-menu li ul li.current').index();
    $('ul.sf-menu li ul li').removeClass('current');  
  }).mouseout(function(){  
    $('ul.sf-menu li:eq('+ parent +')').addClass('current');
    $('ul.sf-menu li ul li:eq('+ child +')').addClass('current'); 
  });
  */
});

window.name = 'main';
