// apostropheReady is called at domReady
// it hooks into the a_js javascript framework
// it can be used for progressive enhancements at runtime
// such as Cufon text replacement

function apostropheReady()
{
  //-------------------------------------------------
  // Recreate placeholder functionality in unsupporting browsers
  var shim = $('<input type="text"/>')[0];

  if (!('placeholder' in shim)) {
    $('input[placeholder]').placeholder(); //jquery.placeholder.js
  }

  $('.placeholder-fallback').remove();

  //-------------------------------------------------
  // Initialize the load more functionality
  $('.load-more').loadMoreWithAjax();
}

$(document).ready(function () {
  
  var showExtensiveSearch = $('<p><span class="arrow-link">Uitgebreid zoeken</span></p>');

  $('.quicksearch').append(showExtensiveSearch);

  showExtensiveSearch.click(function () {
    var extensiveSearch = $('.header + .extensive-search'),
        innerHeight, padding = 0, height;

    if (extensiveSearch.css('height') === '0px') {
      extensiveSearch.css({
        'position': 'absolute',
        'height': 'auto',
        'visibility': 'hidden',
        'overflow': 'auto'
      });

      innerHeight = extensiveSearch.innerHeight();
      padding    += parseInt(extensiveSearch.css('padding-top'));
      padding    += parseInt(extensiveSearch.css('padding-bottom'));

      extensiveSearch.css({
        'position': '',
        'height': '',
        'visibility': '',
        'overflow': ''
      });

      height = innerHeight - padding;
    } else {
      height = 0;
    }

    extensiveSearch.animate({
      'height': height
    })
  });

  var filterBtns = $('.extensive-search .sections li'),
      searchFilters = $('.extensive-search .filters ul'),
      hiddenField = $('.extensive-search input[name="section"]').filter(':hidden');

  hiddenField.val(filterBtns.filter('.active').attr('data-section'));

  filterBtns.click(function () {
    var clickedBtn = $(this),
        section;

    if (clickedBtn.hasClass('news')) {
      section = 'news';
    } else if (clickedBtn.hasClass('advertising')) {
      section = 'advertising';
    } else if (clickedBtn.hasClass('knowledge')) {
      section = 'knowledge';
    } else if (clickedBtn.hasClass('organisation')) {
      section = 'organisation';
    }

    hiddenField.val(clickedBtn.attr('data-section'));

    filterBtns.removeClass('active');
    filterBtns.filter('.' + section).addClass('active');

    searchFilters.removeClass('active');
    searchFilters.filter('.' + section).addClass('active');

    searchFilters.filter(':not(' + section + ')').find(':checked').attr('checked', false);
  });

  //-------------------------------------------------
  // Initialize the replacement of the <select> elements
  $('select.faux-select').fauxSelect();

  //-------------------------------------------------
  // Initialize the network selector (and it's own fauxInput replacement)
  if ($('.network-selector').length > 0) {
    $('.network-selector input.faux-input').fauxInput({
      'template': '<span class="fauxinput" data-id="{inputId}" data-name="{inputName}">{inputLabel}</span>'
    });

    NetworkSelector.initialize();
  }

  // affects the select box on the specials page
  $('select.subsub-nav + dl.faux-select dd').bind('selectionMade', function (evt, selectedSpecial) {
    document.location = selectedSpecial;
  });

  $('.infobox').infoBox();
  $('.researchlightbox').researchLightbox();
  $('.bannersizes-popup').bannersizesLightbox();

  if ($('#program_filters_channel') && $('#program_filters_date')) {
    var dutchMonths = ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december'],
        urlTemplate = $('#program_filters_channel').closest('form.filter').attr('data-url');

    function replaceProgramItems (data) {
      var $filter = $('.filter'),
          html    = data.html;

      $filter.siblings('.program-item').remove();
      $filter.siblings('.load-more').remove();
      
      $filter.after(html);

      (function checkLink () {
        if ($('.load-more')) {
          $('.load-more').loadMoreWithAjax();
        } else {
          window.setTimeout(checkLink, 10);
        }
      })()
      
      var feedback = $('.program-feedback').size();
      
      if($('.program-item').size() > 0){
        $('.program-feedback').remove();
      }
      
      if(feedback > 1 ){
        
        $('.program-feedback:not(:first)').remove();
                
      }

    }

    function getNewListing(evt) {
      var year, monthNumber, monthIndex, ajaxUrl, channel, date, query;

      if (evt && evt.preventDefault) {
        evt.preventDefault();
      }

      channel = $('#program_filters_channel').val(),
      period  = $('#program_filters_date').val(),
      query   = $($('.filter input[type=text]')[0]).val();
      
      ajaxUrl = urlTemplate;
      ajaxUrl = ajaxUrl.replace('{year}', year);
      ajaxUrl = ajaxUrl.replace('{period}', period);
      ajaxUrl = ajaxUrl.replace('{channel}', channel);

      if (query != '') {
        ajaxUrl += '?q=' + query;
      }

      $.getJSON(ajaxUrl, replaceProgramItems);
    }

    $('.filter button').click(getNewListing);
    $('.filter dd').each(function () {
      $(this).bind('selectionMade', getNewListing);
    })
  }


  //-------------------------------------------
  // INITIATE SLIDESHOWS
  if (!$('body').hasClass('logged-in')) {
    $('.slideshow').slideshow();
    $('.a-area-home-slideshow').siblings('.index-dots').addClass('offset');
  }


  //-------------------------------------------
  // REPOSITION FILTER HEADERS
  $('.filters-nav').each(function () {
    var filterNav       = $(this),
        header          = filterNav.find('h4'),
        headerWidth     = header.width(),
        headerHeight    = header.height(),
        secondTab       = filterNav.find('li:last'),
        secondTabLeft   = secondTab.position().left,
        secondTabHeight = secondTab.height();

    header.css({
      'left': secondTabLeft - headerWidth,
      'top': (secondTabHeight - headerHeight) / 2
    });
  }); 

  
  //-------------------------------------------
  // FAQ
  $('.faq-box').hide();
  $('.faq-row').each(function() {
    $(this).find('.faq-title').click(function() {
      $(this).next().slideToggle('fast', function() {
        var cssDisplay = $(this).css('display');

        if (cssDisplay === 'none'){
          $(this).parent('.faq-row').find('.faq-title').removeClass('down');  
          $(this).parent('.faq-row').find('.faq-title').addClass('up');
          $(this).parent('.faq-row').find('.icon').removeClass('down');  
          $(this).parent('.faq-row').find('.icon').addClass('up');
        }
      });

      /* ONE OPEN
      $(this).closest('.faq-row').siblings().find('.faq-box:visible').slideUp('fast', function() {
        $(this).parent('.faq-row').find('.faq-title a').addClass('up');
      });
      */
     $(this).removeClass('up');
     $(this).addClass('down');
     $(this).parent('.faq-row').find('.icon').removeClass('up');
     $(this).parent('.faq-row').find('.icon').addClass('down');
    });
  });
  
  // CASES SAME HEIGHTS ON HOMEPAGE
  
  function equalHeight(group) {
    var tallest = 0;
    group.each(function() {
      var thisHeight = $(this).height();
      if(thisHeight > tallest) {
        tallest = thisHeight;
      }
    });
    group.height(tallest);
  }
  
  equalHeight($(".home_case"));
  
  //----------------------------------------------
  // PARALLAX SCROLLING
  
  $('#call-me').submit(function () {
    var name = $(this).find('#name').val();
    var phonenumber = $(this).find('#phonenumber').val();
    var email = $(this).find('#email').val();
    var company = $(this).find('#company').val();
    
    console.log(name);
    
    if( name !== '' && name !== 'Naam') {
      if (phonenumber !== '' && phonenumber !== 'Telefoonnummer' ){
        $.ajax({
          type:    'POST',
          url:     '/banners/call-me',
          data:    'name=' + name + '&telephone=' + phonenumber + '&email=' + email + '&company=' + company ,
          context: this,
          success: function (response) {
            $(this).parent('div').replaceWith(response);
          }
        });
      }        
    }else {
      $('#phonenumber').addClass('error');
      $('#name').addClass('error');
    }
    return false;
  });
  
  //----------------------------------------------
  // multiple share
  
  var addthis_share = {
    templates: { 
      twitter: "{{title}} {{url}} via @steronline" 
    },
    url_transforms : {
      shorten: {
        twitter: 'bitly'
      }
    },
    shorteners : {
      bitly : {
        login: 'doriendriebit',
        apiKey: 'R_95934c92a29e45b6d1eb448d67059ae5'
      }
    }
  }
  
});

$(window).load(function () {
  //-------------------------------------------------
  // Create behaviours for product browser
  
  //create and place arrow
  var arrow = $('<span class="arrow"></span>'),
      activeHead = $('.product-browser .product-link.active'),
      position = activeHead.position(),
      offsetLeft = position !== null ? position.left : 0,
      width = activeHead.width(),
      offsetArrow = Math.round(offsetLeft + (width / 2) - 8 - 33),
      updateParallax;

  $('.product-browser').append(arrow);
  arrow.css('left', offsetArrow);

  $('.product-browser .product-link').mouseover(function () {
    var arrow = $('.product-browser .arrow'),
        thisHead = $(this),
        thisOffsetLeft = thisHead.position().left,
        thisWidth = thisHead.children('h2').width(),
        thisP = thisHead.next(),
        activeHead = $('.product-browser .product-link.active'),
        activeP = activeHead.next(),
        arrowOffset = parseInt(thisOffsetLeft + (thisWidth / 2) - 8 - 65);

    activeP.removeClass('active');
    activeHead.removeClass('active');
    thisP.addClass('active');
    thisHead.addClass('active');

    arrow.css({'left': arrowOffset});
  });

  //----------------------------------------------
  // POSITION READ MORE LINKS IN TOP LISTS
  $('.toplists .readmore').each(function () {
    var readMore       = $(this),
        readMoreHeight = readMore.height(),
        image          = readMore.siblings('img'),
        imagePosition  = image.position(),
        imageTop       = imagePosition !== null ? imagePosition.top : 0,
        imageHeight    = image.height();

    readMore.css({
      'top': imageTop + imageHeight - readMoreHeight - 10
    })
  });

  //----------------------------------------------
  // PARALLAX SCROLLING
  (updateParallax = function () {
    var scrollTop = $(window).scrollTop(),
        ratio1 = 0.75,
        ratio2 = 0.5;

    $('body').css('background-position', '50% ' + parseInt(scrollTop - (scrollTop * ratio2), 10) + 'px');
    $('.wrapper').css('background-position', '50% ' + parseInt(scrollTop - (scrollTop * ratio1), 10) + 'px');
  })()
  
  $(window).bind('scroll', updateParallax);
});
