$(document).ready(function() {

  // language selector
  $("li#languages").hover(
        function() {
          $(this).children('div').css('left', '-1px');
        },
        function() {
          $(this).children('div').css('left', '-9999px');
        }
    );

  // search bar
  /*var searchDefaultText = $('#search div input').val();
  var searchBackground = $('#search div input').css('backgroundImage');

    $('#search div input').focus(function() {
  if ($(this).val() == searchDefaultText) {
  $(this).val('');
  $(this).css('backgroundImage', 'none')
  }
  });
  $('#search div input').blur(function() {
  if ($(this).val() == '') {
  $(this).val(searchDefaultText);
  $(this).css('backgroundImage', searchBackground)
  }
  });*/

  $('#nav > li:last a').css('padding-right', 0);

  $.each($('#nav > li > a:first-child'), function(index, navItem) {
    if ($(this).hasClass('active')) $(this).parent().addClass('active');

    var mySubnav = $(navItem).parent('li').children('ul');

    if (mySubnav.length != 0) {

      $(navItem).parent('li').hover(
                function() {
                  $(this).addClass('sfhover');

                  if ($(mySubnav).hasClass('tertiary')) {
                    var w = $(this).position().left + ($(mySubnav).width() + 48); // 48 for padding
                    if (w > 960) {
                      $(mySubnav).css('left', '-' + (w - 960) + 'px');
                    }
                  }
                },
                function() {
                  $(this).removeClass('sfhover');
                  if ($(mySubnav).hasClass('tertiary')) {
                    $(mySubnav).css('left', '');
                  }
                }
            );

      if ($(mySubnav).hasClass('tertiary')) {
        var myChildren = $(this).parent().find('ul.tertiary > li');

        // get tallest list item
        var liHeight = 0;
        $.each($(myChildren), function(index, myChild) {
          var h = $(myChild).height();
          if (liHeight < h) {
            liHeight = h;
          }
        });

        $(myChildren).css('height', liHeight + 'px')

        if (myChildren.length > 5) {
          $(mySubnav).css('width', '912px');
        }
        else {
          $(mySubnav).css('width', myChildren.length * 180);
        }



      }


    } else {
      $(navItem).parent('li').hover(
              function() {
                $(this).addClass('hover');
              },
              function() {
                $(this).removeClass('hover');
              }
            );
    }
  });

  if ($("#controller").length > 0) {
    var w = $("#controller .selecteditem").width();
    $("#controller .selecteditem ul").css('width', w + 30);
    $("#controller ul.pageselector li").hover(
            function() {
              $(this).children('ul').css('display', 'block');
            },
            function() {
              $(this).children('ul').css('display', 'none');
            }
        );
  }

  if ($(".tabsnavigation").length > 0) {
    $(".tabsnavigation li a").click(function(e) {
      if (!$(this).attr("rel")) return;
      e.preventDefault();
      var tabcontainer = $(this).parent().parent().parent().parent();
      $(tabcontainer).find(".tabsnavigation").find(".active").removeClass("active");

      // should not be implemented because it's not styled
      $(tabcontainer).find(".tabscontent .tabsinner > div").hide();
      $(tabcontainer).find('.' + $(this).attr("rel")).show();
      $(this).parent().addClass("active");
    });
  }
  if ($(".additional").length > 0) {

    $('.additional #carousel:visible').jcarousel({
      scroll: 1,
      initCallback: mycarousel_initCallback
    });
  }

  $('.dropdown .trigger').click(
        function() {
          var target = $(this).parent().children('div.dropelement');
          var isClosed = target.css('left') == '-9999px';
          target.css('left', isClosed ? 'auto' : '-9999px');
        }
    );

  $.each($('.dropdown .dropelement li'), function(index, dropElement) {
    if (index % 2 == 1) $(this).addClass('alt');
  });

  $('.dropdown .dropelement a').click(function(event) {
    event.preventDefault();

    var dd = $(this).parent().parent().parent().parent();
    $(dd).find('.current').html($(this).html());

    if ($(this).attr('rel')) {
      $(dd).find('.current').attr('rel', $(this).attr('rel'));
    }
    else {
      $(dd).find('.current').attr('rel', '');
    }

    $(dd).find('.dropelement').css('left', '-9999px');

  });
  var changeStep = function(i) {
    i = Math.min(3, Math.max(i, 1));
    $('.step-entry').hide();
    $('.step-' + i).show();
    $('.migration-controller #controller a.prev').css('visibility', i <= 1 ? 'hidden' : 'visible');
    $('.migration-controller #controller a.next').css('visibility', i >= 3 ? 'hidden' : 'visible');
    $('.migration-controller #controller li').removeClass('current').eq(i - 1).addClass('current');
  };
  var refreshStep = function() { changeStep(getIndex() + 1); };
  var getIndex = function(x) {
    return $('.migration-controller #controller li')
                .index(x || $('.migration-controller #controller li.current'));
  }
  $(document).delegate('.migration-controller #controller a.prev', 'click', function() {
    changeStep(getIndex());
  });
  $(document).delegate('.migration-controller #controller a.next', 'click', function() {
    changeStep(getIndex() + 2);
  });
  $(document).delegate('.migration-controller #controller li', 'click', function() {
    var index = getIndex(this) + 1;
    changeStep(index);
  });

  $('#choose-competitor')
        .val(document.location.hash.replace('#', ''))
        .change(function(e) {
          var prefixes = $(this).find('option');
          prefixes = $.map(prefixes, function(x, i) { return x.value; });
          var targetClasses = '.competitor-' + prefixes.join(', .competitor-');
          $(targetClasses).hide();
          if (document.location.hash == '') this.value = prefixes[0];
          $('.competitor-' + this.value).show();
          document.location.hash = this.value;
          refreshStep();
        }).trigger('change');
});

function mycarousel_initCallback(carousel) {

    carousel.buttonNext.bind('click', function() {
        buttonNextCallback()
    });

    carousel.buttonPrev.bind('click', function() {
        buttonPrevCallback()
    });

    $("#carouselfilter a").click(function() {
        hideExpanded();
        
        var a = $(this).attr("href").substring(1);
        var i = $("#carousel > li");
        i.hide();
        i.filter("." + a).show();
        carousel.scroll($.jcarousel.intval(0), false);
    });

    $('a.bottombutton').click(function(event) {
        var p = $(this).parent().parent().parent();
        if (p.hasClass('expanded')) {
            collapse(p);
            $(this).text($('#moreText').val());
        }
        else {
            expand(p);
            $(this).text($('#lessText').val());
        }
        return false;
    });
}
function expand(parent) {
    //parent.animate({}, "slow");
    var myLeft = Math.abs(parseInt($('#carousel').css('left')));
    var mySC = parent.find(".smlcolumn").length;    
    var myWidth = 780;
    var myExpanded = 586;

    if(mySC == 1){
        myWidth = 382;
        myExpanded = 188;
    } else if (mySC == 2){
        myWidth = 581;
        myExpanded = 387;
    }
        
    parent.css({
        'width': myWidth + 'px',
        'position': 'absolute',
        'top': '0',
        'z-index': '99',
        'left': myLeft + 9 + 'px'
    });
    parent.parent().prepend("<li class='carouselleftbg'></li>");
    parent.find(".view, .expandedcontent").css("padding", "11px 10px 11px 1px");
    parent.find(".expandedcontent").css("width", myExpanded + "px");    
    parent.addClass('expanded');
}
function collapse(parent) {
    parent.removeAttr('style');
    parent.parent().find(".carouselleftbg").remove();
    parent.find(".view, .expandedcontent").css("padding", "0");
    parent.removeClass('expanded');
}

function buttonNextCallback() {
    hideExpanded();
};

function buttonPrevCallback() {
    hideExpanded();
};

function hideExpanded() {
    $.each($('ul#carousel li.expanded'), function(index, myElm) {
        collapse($(myElm));
        var mychildlink = $(myElm).children('div.view').children('p').children('a.bottombutton');
        mychildlink.text($('#moreText').val());
    });
  }

function PIEforIE(pieele){    
    if ($.browser.msie && (($.browser.version >= 8.0 || document.documentMode >= 8) || ($.browser.version < 7.0 || document.documentMode < 7))) {
      $.getScript('/global/sqlserver/RenderingAssets/js/PIE.js', function() {
        if (window.PIE) {
          var newpieele = pieele.join(',');
          $(newpieele).each(function() {
            try { PIE.attach(this); } catch (e) { }
          });
        }
      });
    } 
}

  $(function() {
    /* PIE for CTA container */
    PIEforIE(['.ctacontainer']);
  });


  var st_px = [];
  st_px.push(
    '', '', '', '', '', '',
    'clickfacebook',  // 6
    'clicktwitter',   // 7
    'clickyoutube',   // 8
    'shareemail',     // 9
    'sharetwitter',   // 10
    'sharefacebook',  // 11
    'sharedigg',      // 12
    'sharestumbleupon',   // 13 "sharestumble"
    'sharedelicious', // 14
    'sharetumblr',    // 15
    'sharereddit',    // 16
    'sharelinkedin'   // 17
  );

  function sqlR2ShareThisCallback(event, service) {
    if (typeof service != 'undefined' && service != ''){
      var action = (event == 'link') ? 'click' : 'share';
      service = service.toLowerCase();

      $.each(st_px, function(i) {
        if (st_px[i] == action + service && $('#TRACKER' + i).length != 0) {
          var pID = st_px[i];
		  var cv = new Date();
		  
          if (i == 13) // 13 "sharestumble"
            pID = st_px[i].replace('upon', '');
          document.getElementById('TRACKER' + i).src = 'http://thesearchagency.net/pixspike.php?siteid=854&wayid=7665&productID=' + pID + '&cv=' + cv.getTime();
          return true;
        }
      });
    }
  }
