/*================================================== JAVASCRIPT */
/*
JS Document for Dairy Crest
Build: Adam Duncan on behalf of SAS
*/

$('html').addClass('js');

$(document).ready(function () {
  /*////////////////////////////////////// INIT */
  //------------------------ FIX IE6 BACKGROUND IMAGE CACHING
  if (jQuery.browser.msie) {
    try {
      document.execCommand("BackgroundImageCache", false, true);
    } catch (err) { }
  }

  //------------------------ SMOOTH SCROLL
  $('#main_container').localScroll();

  //------------------------ MODULE PANEL LINKS
  $(".module_link_panel, .content_link_panel").hover(function () {
    $(this).find(".arrow_button").addClass('arrow_button_hover');
    $(this).find('a').addClass('link_hover');
  },
    function () {
      $(this).find(".arrow_button").removeClass('arrow_button_hover');
      $(this).find('a').removeClass('link_hover');
    });

  $(".module_link_panel, .content_link_panel").click(function () {
    var location = $(this).find("a.arrow_button").attr("href");
    document.location = location;
  });

  //  $(".external_link_module").hover(function () {
  //    $(this).find(".arrow > a").addClass('hover');
  //  },
  //    function () {
  //      $(this).find(".arrow > a").removeClass('hover');
  //    });

  //------------------------ BRAND CAROUSEL AND PRODUCT PANEL LINKS
  $(".carousel .next, .carousel .prev").hover(function () {
    $(this).addClass('carousel_nav_hover');
  },
    function () {
      $(this).removeClass('carousel_nav_hover');
    });

  $(".carousel li, .product_panel").hover(function () {
    $(this).find(".arrow_link").addClass('arrow_link_hover');
  },
    function () {
      $(this).find(".arrow_link").removeClass('arrow_link_hover');
    });

  $(".carousel li, .product_panel").click(function () {
    var location = $(this).find("a.arrow_link").attr("href");
    document.location = location;
  });

  //------------------------ BRAND ON TV MODULE
  $("a.on_tv").hover(function () {
    $(this).find('img').stop().fadeOut();
  },
    function () {
      $(this).find('img').stop().fadeIn();
    });



  //------------------------ FORMS         
  InitInputDefaultValue("#form_globalsearch .input_text", ".button_submit", "Search");

  $('#frm_submit').hover(
    function () {
      $(this).attr({ src: '/images/btn_search_people_over.gif' });
    },
    function () {
      $(this).attr({ src: '/images/btn_search_people.gif' });
    }
    );

  // Search form
  $('#input_search').focus(
    function () {
      $(this).addClass('focus');
    });
  $('#input_search').blur(
    function () {
      if (!$(this).val()) {
        $(this).removeClass('focus');
      }
    });

  //------------------------ FORMAT CONTENT HEADINGS         
  //$('.content_holder_inner h2:not(h2:first), .content_holder_inner h3:not(h3:first)').before('<div class="spacer">&nbsp;</div>');


  //------------------------ HOTSPOT
  hotspotPopup();

  //------------------------ TAB NAVIGATION
  tabsNavigation();

  //------------------------ EXPANDABLE MODULES
  InitExpandableModules();

  //------------------------ B/CAROUSEL
  InitBarousel();
  InitCarousel();

  //------------------------ Styled Dropdown
  $('.styled-dropdown').sSelect();

  //------------------------ Product Slider
  InitBrandSlider();

});

function InitBrandSlider() {

  var scrollPane = $(".scroll-pane"),
  scrollContent = $(".scroll-content"),
  brandLogoWidth = 160,
  stepValue = 25; //step is 100 divided by the number of increments we want

  // these hold the values of the different brand sections in px
  var productSliderValues = [0, 713, 1123, 1373, 1529];
  var productCount = [7, 2, 2, 1, 1];

  //get current brandtype and update panel on first load
  //this makes the slider point to the section that the brand we are viewing belongs to.
  var currentBrandTypeValue = 0;
  if ($(".current-brandtype").length) {
    currentBrandTypeValue = $(".current-brandtype").attr("id").replace("pos-", '');
    upDatePanel(currentBrandTypeValue, false);
  }

  //build ui.slider
  var scrollbar = $(".scroll-bar").slider({
    step: stepValue,
    animate: true,
    value: currentBrandTypeValue,
    slide: function (event, ui) {
      if (scrollContent.width() > scrollPane.width()) {
        upDatePanel(ui.value, true);
      } else {
        scrollContent.css("margin-left", 0);
      }
    }
  });

  function upDatePanel(sliderValue, animate) {
    //var leftMargin = Math.round(sliderValue / 100 * (scrollPane.width() - scrollContent.width())) + "px";
    var indexValue = Math.round(sliderValue / stepValue); // sliderValue is a multiple of the stepValue. Div by stepValue to get an index for the array
    var leftMargin = -productSliderValues[indexValue] + "px"; // get value from array
    if (animate) scrollContent.animate({ marginLeft: leftMargin }, "slow");
    else scrollContent.css("margin-left", leftMargin);
  }

  //append image to handle
  var handleHelper = scrollbar.find(".ui-slider-handle").wrap("<div class='ui-handle-helper-parent'></div>").parent();

  //change overflow to hidden now that slider handles the scrolling
  scrollPane.css("overflow", "hidden");

  //size scrollbar handle
  function sizeScrollbar() {
    var handleSize = 177;
    scrollbar.find(".ui-slider-handle").css({
      width: handleSize,
      "margin-left": -handleSize / 2
    });
  }

  //animate brand image
  var brandHoverSpeed = 100;
  $(".brand-slider-image").hover(
    function () {
      var closest = $(this).closest(".current-brand");
      console.log(closest);

      //if (!$(this).closest(".current-brand")) {
      $(this).stop(true, true).animate({ height: 120, left: 10, top: -10 }, brandHoverSpeed);
      //}
    },
    function () {
      //if (!$(this).closest(".current-brand")) {
      $(this).stop(true, true).animate({ height: 100, left: 20, top: 0 }, brandHoverSpeed);
      //}
    }
  );

  //force text buttons to trigger slider
  $(".slider-title").click(function () {
    var sliderValue = $(this).attr("id").replace("pos-", "");
    $(".scroll-bar").slider("option", "value", sliderValue);
    upDatePanel(sliderValue, true);
    //console.log(sliderValue);
  });

  //arrow button triggers
  $("#scroll-prev").click(function () {
    var currentSliderValue = parseInt($(".scroll-bar").slider("option", "value"));
    if (currentSliderValue > 0) {
      $(".scroll-bar").slider("option", "value", currentSliderValue - stepValue);
      upDatePanel(currentSliderValue - stepValue, true);
    }
  });

  $("#scroll-next").click(function () {
    var currentSliderValue = parseInt($(".scroll-bar").slider("option", "value"));
    if (currentSliderValue < 100) {
      $(".scroll-bar").slider("option", "value", currentSliderValue + stepValue);
      upDatePanel(currentSliderValue + stepValue, true);
    }
  });

  setTimeout(sizeScrollbar, 10); //safari wants a timeout
}

//--------------------------------------------- FORMS
/* initialize the inputs which requires a 'default value' system */
function InitInputDefaultValue(input_class, submit_class, default_value) {
  var input_text = $(input_class);

  //Init the input field
  if (input_text.val() == "") {
    input_text.val(default_value);
  }

  //Add input field events
  input_text.click(function () {
    if ($(this).val() == default_value)
      $(this).val("");
  }).blur(function () {
    if ($(this).val() == "")
      $(this).val(default_value);
  });

  //Add form submit event
  $(submit_class).click(function () {
    if (input_text.val() == default_value) {
      input_text.val("");
    }
  });
}

function getURLParam(strParamName) {
  var strReturn = "";
  var strHref = window.location.href;

  if (strHref.indexOf("?") > -1) {
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for (var iParam = 0; iParam < aQueryString.length; iParam++) {
      if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1) {
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return strReturn;
}

function selectRedirect(select_id) {
  if ($(select_id).val() != '') {
    document.location.href = $(select_id).val();
  }
  return false;
}

function DropDownJumpNav(DropDown) {
  document.location = DropDown.options[DropDown.selectedIndex].value;
}

//--------------------------------------------- HOTSPOT POPUP
function hotspotPopup() {
  $(".hotspot").mouseover(function () {
    $(".hotspot_content", this).show();
    $(this).css("z-index", "99");
    $(this).addClass("current");
    //return false; commented out as there is a href within the hotspot that uses an external link
  });
  $(".hotspot").mouseleave(function () {
    $(".hotspot_content", this).hide();
    $(this).css("z-index", "5");
    $(this).removeClass("current");
  });
  $(".hotspot_content").mouseleave(function () {
    $(this).hide();
    $(this).parent('.hotspot').css("z-index", "5");
    $(this).parent('.hotspot').removeClass("current");
  });
}



//--------------------------------------------- TABS NAVIGATION
function tabsNavigation() {
  var tabToLoad = getURLParam('tab');
  if (tabToLoad != "") {
    loadTab(tabToLoad);
  }

  $('#tabbed_nav a').click(function () {
    var tab_id = $(this).parent("li").attr('id').split('tab_link_')[1];
    loadTab(tab_id);
    Cufon.refresh('#tabbed_nav li a');
    return false;
  });
}

function loadTab(tab_id) {
  $('#tabbed_nav li.current').removeClass('current');
  $('#tabbed_nav li#tab_link_' + tab_id).addClass('current');
  $('.tab_content.current').removeClass('current');
  $('#tab_content_' + tab_id).addClass('current');
}


//--------------------------------------------- EXPANDABLE MODULES
function InitExpandableModules() {
  $(".link_close").hide();

  $('.expand_link_holder').hover(
        function () {
          $(this).find('span.link_open').addClass("hover");
          $(this).find('.expand_link_title a').addClass("hover");
        },
        function () {
          $(this).find('span.link_open').removeClass("hover");
          $(this).find('.expand_link_title a').removeClass("hover");
        }
    );

  $(".expand_link_holder").click(function () {
    var link = $(this).find('a.expand_link');
    var module_parent_holder = $(this).parents('div.expand_module_holder');
    var module_expand = module_parent_holder.find("div.expand_module");
    var reveal_item = module_parent_holder.find('p.reveal_expand_item');

    module_expand.slideToggle("fast", function () {
      if (link.hasClass('closed')) {
        //if the module was CLOSED and is OPENING
        link.attr('class', 'expand_link opened');
        link.find('span.link_open').css("display", "none");
        link.find('span.link_close').css("display", "block");
      } else {
        //if the module was OPEN and is CLOSING
        link.attr('class', 'expand_link closed');
        link.find('span.link_open').css("display", "block");
        link.find('span.link_close').css("display", "none");
      }
    });

    //reveal item
    if (link.hasClass('closed')) {
      //if the module was CLOSED and is OPENING
      reveal_item.slideDown('fast');
    } else {
      //if the module was OPEN and is CLOSING
      reveal_item.slideUp('fast');
    }

    module_parent_holder.toggleClass('open');
    return false;
  });
}

//--------------------------------------------- B/CAROUSEL

function InitCarousel() {
  $(".carousel").jCarouselLite({
    btnNext: ".next",
    btnPrev: ".prev",
    easing: "easeInOutCubic",
    circular: true,
    visible: 1
  });
}

function InitBarousel() {
  $('#barousel').barousel({
    contentWrapper: '.barousel_content .content',
    manualCarousel: 0,
    contentPaddingBottom: 0,
    debug: 0
  });
}

//------------------------ SHADOWBOX
Shadowbox.init({
  animate: false,
  modal: true
});
