/* Catipedia Carousel Variables */
var catiData = null;
var cur = 0;
var carouselSize = "large";
/* Catipedia Carousel Variables end */

$(document).ready(function () {

  $(".search-input").focus(function () {
    if ($(this).val().match(/Search our site/)) {
      $(this).val("");
    }
  });
  $(".search-input").blur(function () {
    if ($(this).val().match(/^$/)) {
      $(this).val("Search our site");
    }
  });

  //main nav products flyout
  $("#products-main-nav").hover(
    function(){
      $(this).find("#products-flyout").show(); 
    },
    function(){
      $(this).find("#products-flyout").hide(); 
    }
  );
  //main nav products flyout
  $("#flyout-prods img").hover(
    function(){
      $(this).attr("src", $(this).attr("src").replace(/off/, "over"));
    },
    function(){
      $(this).attr("src", $(this).attr("src").replace(/over/, "off"));
    }
  );

  //right nav on homepage
  $("#icons-nav div").hover(
    function () {
      clearIcons();
      $(this).css('background-image', $(this).css('background-image').replace("_off", "_on"));
    });

  $("#bj-nav").hover(
    function () { },
    function () {
      clearPopUps();
      clearIcons();
      $('#icons-desc').show();
    });

  //setting up overlay
  $("#overlay-container").overlay({
    top: 260,
    mask: {
      color: '#555555',
      loadSpeed: 200,
      opacity: 0.8
    },
    close: "#close-btn",
    fixed: false
  });

  //produdcts home/landing page
  $('#main-products li').hover(
      function(){
        //hide old
        $(".mains-prods-descs").hide();
        $('#current-main-prod').remove();
        //show new
        $(this).append('<img id="current-main-prod" src="/Assets/images/product_description_grey_arrow.png" style="position: absolute; left: 50%; margin: 0 0 0 -9px; top: 302px;" />'); 
        $(this).children(".mains-prods-descs").show();
        $(this).children(".product-name").css("font-weight", "bold");
        $(this).siblings().each(function(){
          $(this).children(".product-name").css("font-weight", "normal");
        });
      });

  //products page - nutrition facts
  var curProd = "";
  if ($(".indoor-formula").length){
    curProd = "indoor_formula";
  }
  else if ($(".complete-formula").length){
    curProd = "complete_formula";
  }
  else if ($(".naturals").length){
    curProd = "naturals";
  }
  else if ($(".healthful-life").length){
    curProd = "healthful_life";
  }
  else if ($(".kitten-chow").length){
    curProd = "kitten_chow";
  }
  $('#nutri-cat-content li').click(function(){
    $('#nutri-cat-content li').css("background","none");
    $(this).css("background-image", "url(/Assets/images/"+curProd+"_nav_selected.png)");
    $('.feeding-content').css("display","none");
    $('.ingredients-content').css("display","none");
    $('.analysis-content').css("display","none");

    $("."+$(this).attr('id')+"-content").css("display", "block");
  });


  //bars for product details
  if ($(".products")){
    $(".analysis-content span").each(function(){
      if (/%/.exec($(this).html())){
        var percent = (parseFloat(/[0-9.]+/.exec($(this).html()))/100.0);
        var hundredPercent = 263;//px
        var width = percent*hundredPercent > 2?percent*hundredPercent:2;
        $(this).parent().find(".analysis-mid").css("width", width);
      }
    });
  }

  //Product Details print version Firefox 3.6
  //FF3.6 won't print floated or overflowed elements
  var ua = navigator.userAgent;
  if (typeof ua !== 'undefined' && ($(".complete-formula").length != 0 || $("indoor-formula").length != 0 || $(".kitten-chow").length != 0 || $(".naturals").length != 0 || $(".healthful-life").length != 0 ) && /firefox/i.test(ua) && /3\.6/.test(ua)){
    $("body").addClass("fftsh");
    $("#product-img").addClass("ffmlff");
    $("#product-info").addClass("fftsmlff fftsnp");
  }

  var wing = document.location.href.split("/")[4];
  /* Catipedia Carousel - uses variables in parent scope(top of file) */
  if ($(".catipedia-basics").length != 0 || $(".catipedia-behavior").length != 0 || $(".catipedia-health").length != 0 || $(".catipedia-nutrition").length != 0 ){
    
    //toollay cookie
    if ($.cookie("toollay") != null){
      $("#cati-toollay").hide();
    }
    else{
      $("#cati-toollay img").click(function(){
        $(this).parent().hide();
        $.cookie("toollay", "true", { expires: 300 , path:'/'});
      });
    }

    //carousel size part 1
    var sizeCookie = $.cookie('carouselSize');
    if (sizeCookie !== null){
      if (sizeCookie === "small"){
          $("#cati-carousel-thb").css("background-position", "0 0").siblings().css("background-position", "0 -11px");
          $("#cati-carousel-thb").css("cursor", "auto").siblings().css("cursor", "pointer");
        carouselSize = "small";
      }
      else if (sizeCookie === "large"){
          $("#cati-carousel-lrg").css("background-position", "0 0").siblings().css("background-position", "0 -11px");
          $("#cati-carousel-lrg").css("cursor", "auto").siblings().css("cursor", "pointer");
        carouselSize = "large";
      }
    }
    else{
      $.cookie('carouselSize', 'small', { expires: 300, path:'/' });
      carouselSize = "small";
    }
    //carousel size part 2
    $("#cati-thumb-toggle div").click(function(){
        $(this).css("background-position", "0 0").siblings().css("background-position", "0 -11px");
        $(this).css("cursor", "auto").siblings().css("cursor", "pointer");
      if ($(this).attr("id") === "cati-carousel-lrg"){
        if (carouselSize === "large"){ return; }
        carouselSize = "large";

        cur-=8;
        cur = cur>=0?cur:catiData.length-(catiData.length%8);

        carouselSetup();
      }
      else if ($(this).attr("id") === "cati-carousel-thb"){
        if (carouselSize === "small"){ return; }
        carouselSize = "small";

        cur--;
        cur = cur>=0?cur:cur+catiData.length;
        //set cur to closest multiple of 8 (Math.Floor)
        cur = ((cur/8)|0)*8;

        carouselSetup();
      }

      $.cookie('carouselSize', carouselSize, { expires: 300 , path:'/'});
    });

    $.ajax({
      url: "/Catipedia/Articles?wing="+wing+"&count=8000&startIdx=0",
      dataType: 'json',
      success: function(data){
        catiData = data;

        cur = 0;
        if ( ($.cookie('artPage') === "true") && ($.cookie("wing") === wing) ){
          var slide = $.cookie('cur');
          if (slide !== null) {
            cur = parseInt(slide);
            if (carouselSize === "small"){
              //the multiple of 8 that comes before "slide"
              cur = ((cur/8)|0)*8;
            }
          }
        }
        $.cookie("artPage", "false", {expires: 300, path:'/'});
        $.cookie("wing", wing, { expires: 300 , path:'/'});
        $.cookie('cur', cur, { expires: 300 , path:'/'});

        carouselSetup();
      }
    });
  }
  else if($(".cati-article").length != 0){
    var w = $.cookie("wing");
    var a = $.cookie("artPage");

    console.log("wing: "+w);
    console.log(w !== wing);

    console.log("artPage: "+a);
    console.log(a === "true");

    if ($.cookie("wing") !== wing || $.cookie("artPage") === "true"){
      console.log("ajaxing...");
      $.ajax({
        url: "/Catipedia/Articles?wing="+wing+"&count=8000&startIdx=0",
        dataType: 'json',
        success: function(data){
          var urlParts  = location.href.split("/");
          var len = urlParts.length;
          var curCatipediaUrl = "";
          for (var i=3; i<len; i++){
            curCatipediaUrl = curCatipediaUrl + "/"+urlParts[i];
          }

          len = data.length;
          var found = false;
          for(var i=0; i<len;i++){
            if (data[i].CatipediaUrl === curCatipediaUrl){ 
              $.cookie("cur", i, {expires: 300, path:'/'});
              found = true;
              console.log("found: "+i);
            }
          }
          if (!found){
            console.log("not found");
            $.cookie("cur", 0, {expires: 300, path:'/'});
          }
        }
      });
    }

    $.cookie("artPage", "true", { expires: 300 , path:'/'});
    $.cookie("wing", wing, { expires: 300 , path:'/'});
  }
  else{
    $.cookie("artPage", "false", { expires: 300 , path:'/'});
    $.cookie("wing", "not-catipedia", { expires: 300 , path:'/'});
  }


});

/* Catipedia Carousel */
function carouselSetup(){
  $("#cati-carousel-next").unbind("click");
  $("#cati-carousel-prev").unbind("click");

  if (carouselSize === "small"){
    $("#cati-carousel").css({ "margin-left": "226px", "width": "675px" });
    $("#cati-carousel ul").css("right", "1628px");

    if (catiData.length <= 8){ 
      $("#cati-carousel-next").css("opacity", ".5");
      $("#cati-carousel-prev").css("opacity", ".5");
    }
    else{
      $("#cati-carousel-next").css("opacity", "1").click(function(){ forward(); });
      $("#cati-carousel-prev").css("opacity", "1").click(function(){ backward(); });
    }
  }
  else if (carouselSize === "large"){
    $("#cati-carousel").css({ "margin-left": "0", "width": "100%" });
    $("#cati-carousel ul").css("right", "");
    $("#cati-carousel-next").css("opacity", ".5");
    $("#cati-carousel-prev").css("opacity", ".5");

    if (catiData.length <= 1){
      $("#cati-carousel-next").css("opacity", ".5");
      $("#cati-carousel-prev").css("opacity", ".5");
    }
    else{
      $("#cati-carousel-next").css("opacity", "1").click(function(){ forward(); });
      $("#cati-carousel-prev").css("opacity", "1").click(function(){ backward(); });
    }
  }

  $("#cati-carousel ul").html("");
  cur = decreCur(cur);
  cur = decreCur(cur);
  $("#cati-carousel ul").append(getCurMarkUp(cur));
  cur = increCur(cur);
  $("#cati-carousel ul").append(getCurMarkUp(cur));
  cur = increCur(cur);
  $("#cati-carousel ul").append(getCurMarkUp(cur));
  cur = increCur(cur);
  $("#cati-carousel ul").append(getCurMarkUp(cur));
}
function getCurMarkUp(aNum){
  if (carouselSize === "large"){
    var img = "<img src='"+catiData[aNum].LargeImage+"' width='772' height='543' />";
    var more = "Read more";
    if (catiData[aNum].CatipediaMediaType === "Video"){
      img += "<img src='/Assets/images/play_button.png' class='carousel-video-lrg' />";
      more = "See more";
    }
    img = "<a href="+catiData[aNum].CatipediaUrl+">"+img+"</a>";
    var title = "<a href='"+catiData[aNum].CatipediaUrl+"'><div class='slide-title'>"+catiData[aNum].Title+"</div></a>";
    var theTags = catiData[aNum].Tags;
    var len = theTags.length;
    var tags = "<a href='"+catiData[aNum].CatipediaUrl+"'><div class='slide-tags'>";
    for (var i=0; i<len; i++){
      if (i<len-1){ tags = tags + " " + theTags[i]+","; }
      else{ tags = tags + " " + theTags[i]; }
    }
    tags = tags + "</div></a>";
    var link = "<a href='"+catiData[aNum].CatipediaUrl+"' class='more-link-cati'>"+more+"</a>";
    var count = "<div class='out-of-cati'>"+(aNum+1)+" of "+catiData.length+"</div>";
    return "<li>"+img+"<div class='large-slide-info'>"+title+tags+link+count+"</div></li>";
  }
  else if (carouselSize === "small"){
    var content = "<div class='row'>";
    var vals = "";
    for (var i=aNum, j=0; i<catiData.length && j<8; i++, j++){
      var curDatum = catiData[i];

      var curCode = "<img src='"+curDatum.ThumbnailImage+"' width='160' height='168' />";
      if (catiData[i].CatipediaMediaType === "Video"){
        curCode += "<img src='/Assets/images/play_button_small.png' class='carousel-video-sml' />";
      }
      curCode = "<a href='"+curDatum.CatipediaUrl+"'>"+curCode+"</a>";
      curCode = "<div class='thb-img'>"+curCode+"</div>";
      curCode += "<div class='thb-title'><a href='"+curDatum.CatipediaUrl+"'>"+curDatum.Title+"</a></div>";

      content += "<div class='small-thb'>"+curCode+"</div>";
      if (j===3){ content += "</div><div class='row'>" };
    }
    content += "</div>";
    return "<li><div class='small-thumb'>"+content+"</div></li>";
  }
}
function forward(){
  $("#cati-carousel-next").unbind("click");
  $("#cati-carousel-prev").unbind("click");
  cur = increCur(cur);
  $("#cati-carousel ul").append(getCurMarkUp(cur));
  $("#cati-carousel li:first").animate( { width: 0 }, "fast", function(){ 
    $(this).remove(); 
    $("#cati-carousel-next").click(function(){ forward(); });
    $("#cati-carousel-prev").click(function(){ backward(); });
  });
  $.cookie('cur', decreCur(cur) , { expires: 300 , path:'/'});
}

function backward(){
  $("#cati-carousel-next").unbind("click");
  $("#cati-carousel-prev").unbind("click");
  var tal = cur;
  cur = decreCur(cur);

  tal = decreCur(tal);
  tal = decreCur(tal);
  tal = decreCur(tal);
  tal = decreCur(tal);

  $("#cati-carousel ul").prepend(getCurMarkUp(tal));
  $("#cati-carousel li:first").css("width", 0).animate( { width: 785 }, "fast", function(){
    $("#cati-carousel li:last").remove();
    $("#cati-carousel-next").click(function(){ forward(); });
    $("#cati-carousel-prev").click(function(){ backward(); });
  });
  $.cookie('cur', decreCur(cur) , { expires: 300 , path:'/'});
}
function increCur(num){
  if (carouselSize === "large"){
    num++;
    return num<catiData.length?num:num-catiData.length;
  }
  else if(carouselSize === "small"){
    num+=8;
    return num<catiData.length?num:0;
  }
}
function decreCur(num){
  if (carouselSize === "large"){
    num--;
    return num>=0?num:num+catiData.length;
  }
  else if(carouselSize === "small"){
    num-=8;
    if (num<0){
      var sub = catiData.length%8;
      if (sub == 0) {
        num = catiData.length-8;
      }
      else{
        num = catiData.length-sub;
      }
    }
    return num;
  }
}

/* Catipedia Carousel END */

/* overlay */
function toggleTranscript(){
  var parts = $('#transcript-tag span').html().split(" ");
  if (/View/.test($('#transcript-tag span').text())){
    $('#transcript-tag span').text("Hide "+parts[1]);
  }
  else{
    $('#transcript-tag span').text("View "+parts[1]);
  }
  $('#transcript-text').slideToggle('slow');
}

/* homepage */
function showPopUp(which) {
  clearPopUps();
  $("#" + which + "-pop").show();
  $("#" + which + "-icon").html('<img src="/Assets/images/icon_textbox_pointer.png" style="position: absolute; left:50%; margin: 0 0 0 -6px; top: 32px;" />');
}

/* homepage */
function clearPopUps() {
  $('#icons-desc').hide();
  $('#team-pop').hide();
  $('#team-icon').html('');
  $('#catpedia-pop').hide();
  $('#catpedia-icon').html('');
  $('#stories-pop').hide();
  $('#stories-icon').html('');
  $('#prod-pop').hide();
  $('#prod-icon').html('');
}

function clearIcons() {
  $("#icons-nav div").each(function () {
    $(this).css('background-image', $(this).css('background-image').replace("_on", "_off"));
  });
}

/* overlay */
function openOverlay(jsonContent){
  //Convert for videos from Facebook that are actually youtube videos
  if (typeof jsonContent.videos !== 'undefined' && /youtube/.test(jsonContent.videos[0].url)){
    jsonContent.type = "video";
    jsonContent.service = "youtube";
    jsonContent.url = jsonContent.videos[0].url;
  }

  var type = jsonContent.type;
  var service = jsonContent.service;

  jsonContent.more = "null";
  jsonContent.fb = "null";
  jsonContent.tw = "null";

  if (typeof jsonContent.story !== 'undefined'){
    jsonContent.more = jsonContent.seeMoreUrl;
    jsonContent.fb = encodeURIComponent(jsonContent.fburl);
    jsonContent.tw = jsonContent.seeMoreUrl;
  }
  else if (type === "image" || type === "video" && service === "facebook"){
    jsonContent.more = jsonContent.url;
    jsonContent.fb = encodeURIComponent(jsonContent.url);
    jsonContent.tw = jsonContent.url;
  }
  else if (type === "video" && service === "youtube"){
    if (typeof jsonContent.videos === 'undefined'){
      jsonContent.more = jsonContent.url;
      jsonContent.fb = encodeURIComponent(jsonContent.url);
      jsonContent.tw = jsonContent.url;
    }
    else{
      jsonContent.more = jsonContent.videos[0].seeMoreUrl;
      jsonContent.fb = encodeURIComponent(jsonContent.videos[0].url);
      jsonContent.tw = jsonContent.videos[0].url;
    }
  }
  else if (type === "image" && service === "flickr"){
    if (typeof jsonContent.images === 'undefined'){
      jsonContent.more = jsonContent.seeMoreUrl;
      jsonContent.fb = encodeURIComponent(jsonContent.containerUrl);
      jsonContent.tw = jsonContent.containerUrl;
    }
    else{
      jsonContent.more = jsonContent.images[0].seeMoreUrl;
      jsonContent.fb = encodeURIComponent(jsonContent.images[0].containerUrl);
      jsonContent.tw = jsonContent.images[0].containerUrl;
    }
  }

  if (typeof jsonContent.category !== 'undefined' && jsonContent.category === 'team'){
    jsonContent.more = jsonContent.seeMoreUrl;
  }

  //add all the images for carousel
  //All images except for stories
  if (type === "image" && typeof jsonContent.story == 'undefined'){
    $.ajax({
      url: "/home/socialfeedphotos/"+jsonContent.id,
      dataType: 'json',
      success: function(data){
        var firstPhoto = jsonContent.images[0].url;
        jsonContent.images = data.images;
        jsonContent.images.unshift({"url":firstPhoto, "seeMoreUrl":jsonContent.more});
        $("#overlay-content").html(new EJS({"url":"/Assets/scripts/ejs/overlay.ejs.txt"}).render(jsonContent));
        $("#overlay-container").data("overlay").load();
      }
    });
  }
  else{ 
    $("#overlay-content").html(new EJS({"url":"/Assets/scripts/ejs/overlay.ejs.txt"}).render(jsonContent));
    $("#overlay-container").data("overlay").load();
    $("#overlay-container").data("overlay").onClose(function() {
      //to stop video from playing in ie
      $("#overlay-content").html("");
    });
  }
}

/* Console Proxy : if console isn't around, hide console messages */
if (!window.console) {
      window.console = { };
      var empty = function(msg) { };
      console.log = empty;
      console.warn = empty;
      console.dir = empty;
  }

  /* Catipedia Nav Hover */

  $(document).ready(function () {
      $("#catipedia-intro-nav li a").hover(
      function () {
          var s = "#" + $(this).parent()[0].id + "-hover";
          $(s).show();
      },
      function () {
          var s = "#" + $(this).parent()[0].id + "-hover";
          $(s).hide();
      }
    );
  });

