﻿/*globals Cufon: false */

// Remember: replace statements go outside document.ready.
Cufon.replace('h1, .h1, h2, .h2, h3, .h3');
Cufon.replace('.mainNavigation', { fontWeight: 'normal', hover: 'true' });
Cufon.replace('.cufon');

var Utils = {

  // Causes a text field (such as a search box) to be
  // cleared of the default text when given focus.
  installAutoClear: function (el) {
    var origVal = el.val();

    el.focus(function () {
      if (el.val() == origVal) {
        el.val('');
      }
    });

    el.blur(function () {
      if (el.val() == '') {
        el.val(origVal);
      }
    });
  },

  installHovered: function () {
    $('.unhovered').live('mouseenter', function () {
      $(this).removeClass("unhovered").addClass("hovered");
    });
    $('.hovered').live('mouseleave', function () {
      $(this).removeClass("hovered").addClass("unhovered");
    });
  },

  installSmartImageBox: function (box) {
    $('a', box).hide();
    $(box).hover(
            function () {
              $('a', this).addClass("hover");
              $('a', this).show();
            },
            function () {
              $('a', this).removeClass("hover");
              $('a', this).hide();
            }
        );

    $('.remove').click(function () {
      var obj = this;
      $.ajax({ url: $(this).attr("rel") + "/RemoveMainImage", context: document.body, success: function () {
        $('img', $(obj)).parent().hide();
        $('input', $(obj).parent()).removeClass("hide");
      }
      });
    });

    $('.delete').click(function () {
      var obj = this;
      $.ajax({ url: "/profiel/deleteimage", context: document.body, success: function () {
        $('img', $(obj).parent()).hide();
        $('input', $(obj).parent().parent()).removeClass("hide");
      }
      });
    });

    $('.deleteCaseImage').click(function () {
      var obj = this;
      $.ajax({ url: "DeleteCaseImage?stepName=" + $(this).attr("rel"), context: document.body, success: function () {
        $('img', $(obj).parent()).hide();
        $('input', $(obj).parent().parent()).removeClass("hide");
      }
      });
    });

  },

  installAndersNamelijk: function () {
    $('select').each(function (i, selectEl) {
      var id = selectEl.id;
      var otherOptionEl = $(selectEl).children('option[value=other]')[0];
      var otherTextEl = $('#' + id + '_');

      var showOtherEl = function () {
        otherTextEl.css('display', 'inline');
        $(selectEl).attr('name', id + '_');
        otherTextEl.attr('name', id);
      }

      if (otherOptionEl) {
        if (otherTextEl.val()) {
          $(selectEl).val('other');
          showOtherEl();
        }

        $(selectEl).change(function () {
          var selectedValue = selectEl.value;
          if (selectedValue == 'other') {
            showOtherEl();
            otherTextEl.focus();
          } else {
            otherTextEl.css('display', 'none');
            $(selectEl).attr('name', id);
            otherTextEl.attr('name', id + '_');
          }
        });
      }
    });
  },

  installCollapsor: function (containerSelector, headingSelector, toggleNow) {
    $(containerSelector).each(function () {
      var thisLevel = $(this);

      // On-load collapse of tips, for graceful degradability in a non-JS situation.
      if (toggleNow) {
        thisLevel.toggleClass('expanded collapsed');
      }

      $(headingSelector, thisLevel).click(function () {
        thisLevel.toggleClass('expanded collapsed');
      });
    });
  },

  installPartnerLogoCarousel: function () {
    var pos = 0;
    var nlogos = $('.partnerLogo').length;
    var maxPos = nlogos - 3;

    if (maxPos <= 0) {
      $('.partnerLogos .arrow-left img').css('display', 'none');
      $('.partnerLogos .arrow-right img').css('display', 'none');
    } else {
      var setEnabled = function (el, enabled) {
        el.css('cursor', enabled ? 'pointer' : 'auto');
        el.animate({ 'opacity': enabled ? '1' : '0.2' });
      };
      var set = function (i) {
        pos = i;

        $('.partnerLogosInner').animate({ 'left': ((i * -170)) }, 600);

        setEnabled($('.partnerLogos .arrow-left'), pos > 0);
        setEnabled($('.partnerLogos .arrow-right'), pos < maxPos);
      };
      var adjust = function (d) {
        pos += d;
        pos = Math.max(0, pos);
        pos = Math.min(pos, (maxPos));
        set(pos);
      };
      $('.partnerLogos .arrow-left').click(function () { adjust(-1); });
      $('.partnerLogos .arrow-right').click(function () { adjust(1); });
      set(0);
    }
  }
};

var LogoAnim = {
  init: function () {
    $("html body").live("mousemove", function (evt) {
      if ($(evt.target).closest("#logo").length > 0) {
        $("#logo img").attr("src", "/Content/Images/logo.gif")
      }
      else {
        $("#logo img").attr("src", "/Content/Images/logo-gradient.png");
      }
    });
  }
};

var MkCarousel = function (navSel, navClass, contentSel) {
  // Create function that selects a specific item.
  var oldDisplayMode = $(contentSel).css('display');
  var set = function (i) {
    $(contentSel).css('display', 'none');
    $($(contentSel)[i]).css('display', oldDisplayMode);
    $(navSel).removeClass(navClass);
    $($(navSel)[i]).addClass(navClass);
    Cufon.refresh();
  }

  // Install click handlers on selectors.
  $(navSel).each(function (i, el) {
    $(el).css('cursor', 'pointer');
    $(el).click(function () { set(i); return false; });
  });

  // Initialise by selecting the first item.
  set(0);
};

var MkCarouselAuto = function (navSel, navClass, contentSel) {
  var totalNavSels = 0;
  var currentSelection = 0;
  var timeout = null;
  var autoNext = true;

  var set = function (i) {
    currentSelection = i;

    $(contentSel).hide();
    $($(contentSel)[i]).fadeIn('slow');

    $(navSel).removeClass(navClass);
    $($(navSel)[i]).addClass(navClass);

    clearTimeout(timeout);
    if (autoNext) {
      timeout = setTimeout(next, 8000);
    }
  };

  var next = function () {
    var next = currentSelection + 1;
    if (next >= totalNavSels) next = 0;
    set(next);
  };

  // Install click handlers on selectors.
  $(navSel).each(function (i, el) {
    $(el).click(function (e) {
      autoNext = false;
      set(i);
      e.preventDefault();
    });
    totalNavSels++;
  });

  // Start with a random item:
  set(Math.floor(Math.random()*totalNavSels));
};


$(document).ready(function () {
  Utils.installAutoClear($('#queryInput'));
  if ($("#filterInput")) {
    Utils.installAutoClear($("#filterInput"));
  }

  LogoAnim.init();
  Utils.installHovered();
  Utils.installAndersNamelijk();

  // checklist page
  Utils.installCollapsor('.checklist-level2', '.checklist-level2-heading', true);
  Utils.installCollapsor('.checklist-level3', '.checklist-level3-heading', true);

  Utils.installSmartImageBox($('.smartImageBox'));

  // new case page
  Utils.installCollapsor('#checklistSteps .checklistStep', '.expandToggle', false);
  $("#checklistSteps .checklistStep").each(function (i) {
    if (i != 0) {
      $(this).toggleClass("expanded collapsed");
    }
  });

  Utils.installPartnerLogoCarousel();

  MkCarouselAuto('.topCarouselNav a', 'topCarouselSelected', '.videoShowcaseContentItem');
  MkCarousel('.caseCarouselNav li a', 'caseCarouselSelected', '.caseCarouselItems li');
  MkCarousel('.agendaNewsBlock h4', 'agendaNewsSelected', '.agendaNewsBlock div');
});

