// Cufon
Cufon.replace('#navigation ul li a', { hover: true });
Cufon.replace('h2', { hover: true });
Cufon.replace('.sideBarHeadline', { hover: true });
Cufon.replace('#fitlerTitle', { hover: true });
Cufon.replace('h4');


$(document).ready(function(){

  var rootURL = $('#rootURL').val();

  $('body.no-js').removeClass('no-js');

  $('.showIfJs').show();
  $('.hideIfJs').hide();

  // Columns (only IE, otherwise css3)
  if ($.browser.msie){
    $('.columns').columnize({
      columns: 2
    });
    $('#content .columns .first.column').css({
      'padding-right' : 15+'px'
    });
  }

  $('body.impressions.article p:first-child').insertAfter('#impressionsGallery').addClass('introduction');

  var hoverAnimationTime = 50;

  // Box hover
  $('.box:not(.open)').live('hover', function(){
    $('.gridThumbnail', this).animate({
      'opacity' : '0.5'
    },{ queue:false, duration: hoverAnimationTime });
    $('.name a, .website a', this).animate({
      'color' : '#c36'
    },{ queue:false, duration: hoverAnimationTime });
    $('ul.tags li a', this).animate({
      'color' : '#333'
    },{ queue:false, duration: hoverAnimationTime });
  });

  // Box mouseout
  $('.box:not(.open)').live('mouseleave', function(){
    $('.gridThumbnail', this).animate({
      'opacity' : '1'
    },{ queue:false, duration: hoverAnimationTime });
    $('.name a,', this).animate({
      'color' : '#000'
    },{ queue:false, duration: hoverAnimationTime });
    $('.website a', this).animate({
      'color' : '#fff'
    },{ queue:false, duration: hoverAnimationTime });
    $('ul.tags li a', this).animate({
      'color' : '#999'
    },{ queue:false, duration: hoverAnimationTime });
  });

  // Choose location
  $('#chooseLocation li').click(function(){
    $(this).addClass('active');
    $(this).siblings().removeClass('active');
  });

  // Share
  $('ul.actions li.share ul.sharePopup').css({
    'display':'none'
  });

  $('ul.actions li.share').toggle(function(){
    $('ul.actions li.share ul.sharePopup').slideDown('fast');
  },function(){
    $('ul.actions li.share ul.sharePopup').slideUp('fast');
  });

  $('ul.actions li.share ul.sharePopup li a').click(function(e){
    e.preventDefault();
    window.open($(this).attr('href'), '_blank');
  });

  // Init vars
  var clickedBox;
  var currentProfile = -1;
  var numberOfProfiles = $('.expandable').length;
  var windowHeight = $(window).height();
  $(window).resize(function(){
    windowHeight = $(window).height();
  });
  var profileID = 0;
  var profileType;

  // View big profile
  $('.expandable:not(.open)').live('click', function(){

    // Reset hover
    $('.gridThumbnail').css({
      'opacity' : '1'
    });
    $('.name a').css({
      'color' : '#000'
    });
    $('.website a').css({
      'color' : '#fff'
    });
    $('ul.tags li a').css({
      'color' : '#999'
    });

    clickedBox = $(this);
    currentProfile = clickedBox.index();
    profileID = $('.profileID', this).val();
    profileType = $('.profileType', this).val();
    if ( profileType == 'freelancer' ){
      path = 'freelancers';
    }else if ( profileType == 'studio' ) {
      path = 'agencies-studios';
    }
    $('.bigProfile').remove();
    $('.box').removeClass('open').css({
      'z-index' : '1'
    });
    if(! clickedBox.hasClass('open') ){
      $.ajax({
        url: rootURL+'profile'+'/'+profileID,
        success: function(data){
          $('body').animate({
            scrollTop: clickedBox.offset().top - (windowHeight / 2) +205
          }, 'slow');
          clickedBox.addClass('open').append(data);
          clickedBox.css({
            'z-index' : '2'
          });
          // Position in home view
          if ( $('body.home').length > 0 && clickedBox.hasClass('homeRow2')){
            $('.bigProfile').css({
              'top': -210+'px'
            });
          }
        }
      });
    }
    return false;
  });

  // Position in home view
  if ( $('body.home').length > 0){
    $('.box:eq(3),.box:eq(4),.box:eq(5),.box:eq(9),.box:eq(10),.box:eq(11)').addClass('homeRow2');
  }

  function prevProfile(){
    currentProfile--;
    if( currentProfile < 0 ){
      currentProfile = 0;
    }
    $('.expandable').eq(currentProfile).trigger('click');
  }

  function upProfile(){
    currentProfile-=3;
    if( currentProfile < 0 ){
      currentProfile = 0;
    }
    $('.expandable').eq(currentProfile).trigger('click');
  }

  function nextProfile(){
    currentProfile++;
    if( currentProfile > numberOfProfiles+1 ){
      currentProfile = numberOfProfiles;
    }
    $('.expandable').eq(currentProfile).trigger('click');
  }

  function downProfile(){
    currentProfile+=3;
    if( currentProfile > numberOfProfiles+1 ){
      currentProfile = numberOfProfiles;
    }
    $('.expandable').eq(currentProfile).trigger('click');
  }

  // Navigation with arrow keys
  function checkKey(e){
    switch (e.keyCode){
      case 37: // Left arrow key
        prevProfile();
      break;
      case 38: // Up arrow key
        upProfile();
      break;
      case 39: // Right arrow key
        nextProfile();
      break;
      case 40: // Down arrow key
        downProfile();
      break;
    }
  }

  if ($.browser.mozilla){
    $(document).keypress(checkKey);
  } else {
    $(document).keydown(checkKey);
  }

  // Close big profiles
  $('.closeProfile').live('click',function(){
    $('.bigProfile').remove();
    $('.box').removeClass('open').css({
      'z-index' : '1'
    });
    return false;
  });

  // Search
  var searchOpen = false;
  if( $('.searchItem.active').length > 0 ){
    searchOpen = true;
    $('.searchItem.active a').hide();
  }else{
    $('#search').hide();
  }

  $('#searchBtn').hide();

  $('.searchItem').click(function(){
    if( searchOpen == false ){
      searchOpen = true;
      $('a', this).fadeOut();
      $(this).animate({
        'width': 300+'px'
      }, 500, 'swing',function(){
        $('#search').show();
        $('#search input').focus();
      });

    }
    return false;
  });

  // To get search to work cross browser
  $('#searchInput').keydown(function(event) {
    if (event.keyCode == '13'){
      $('#search').submit();
    }
  });

  // Impression image gallery
  var imageNumber = 0;
  var galleryOpen = false;
  var imageHeight = 326;

  $('#sidebar .impressionImage:not(.home #sidebar .impressionImage)').click(function(){

    imageNumber = $('#sidebar .impressionImage').index(this);

    if ( galleryOpen === false ){
      $('#impressionsGallery').slideDown('fast');
      $('#impressionsGallery ul').animate({
        'margin-top' : - (imageNumber * imageHeight) + 'px'
      });
      $('.closeButton').slideDown('fast');
      galleryOpen = true;
    }
    $('#impressionsGallery ul').animate({
      'margin-top' : - (imageNumber * imageHeight) + 'px'
    });
    return false;
  });

  $('#impressionsGallery ul li img').click(function(){
    imageNumber = $('#impressionsGallery .impressionImage').index(this);
    if ( imageNumber == $('#impressionsGallery ul li').length - 1 ){
      $('#sidebar .impressionImage').eq(0).trigger('click');
    }else{
      $('#sidebar .impressionImage').eq(imageNumber + 1).trigger('click');
    }
  });

  $('.closeButton').click(function(){
    $(this).slideUp('fast');
    $('#impressionsGallery').slideUp('fast');
    galleryOpen = false;
    return false;
  });

  // Open links in a new window
  $('a[rel=ext]').live("click", function(event){
    event.preventDefault();
    window.open(this.href);
  });

  // Love
  $('#madeWithLove').hover(function(){
    $('.love').css({
      'color':'#f00'
    });
  },function(){
    $('.love').css({
      'color':'#fff'
    });
  });

  var loopcounter = 0;

  function setThirdClass(){
    loopcounter = 0;
    $('#content .box').each(function(){
      $(this).removeClass('third');
      if( loopcounter % 3 == 2 ){
        $(this).addClass('third');
      }
      loopcounter++;
    });
  }

  // Infinite scroll
  $('#content').infinitescroll({
    navSelector   : 'div.pagination',
    nextSelector  : 'div.pagination a.next_page',
    itemSelector  : '#content div.box',
    loadingImg    : rootURL+'/images/assets/ajax-loader.gif',
    loadingText   : '',
    donetext      : ''
  },function(){
    $('#infscr-loading').hide();
    setThirdClass();

    //$('.box:not(.old)').shuffle({},function(){
    //  setThirdClass();
    //});

    setThirdClass();

    $('.box').each(function(){
      $(this).addClass('old');
    });

    // Update variable
    numberOfProfiles = $('.expandable').length;
  });

  // Random profiles
  if( $('body.freelancers, body.agencies-studios').length > 0 ){
    //$('.box').shuffle({},function(){
    //  setThirdClass();
    //});

    setThirdClass();

    $('.box').each(function(){
      $(this).addClass('old');
    });

    if ( $('input').is(':checked') ) {
      //
    }else{
      $('.box').remove();
    }

    $(document).trigger('retrieve.infscr');

  }

  // Uniform
  $('input:checkbox, input:radio, input:file').uniform();

  // Hide filter submit
  $('#sidebar form.filter input:submit').hide();

  // Checks & radios
  var radioName;
  $('input:checkbox').click(function(){
    if ( $(this).parent().parent().siblings('.optionText').hasClass('active') ){
      $(this).parent().parent().siblings('.optionText').removeClass('active');
    }else{
      $(this).parent().parent().siblings('.optionText').addClass('active');
    }
    $(this).parents('fieldset').children('input:submit').trigger('click');
  });

  $('.optionText').click(function(){

    if ( $('body.submit').length > 0 ){
      $(this).siblings('div').children('span').children('input').trigger('click');
    }

    // Ugly code / ugly IE7 = 1
    if ( $.browser.msie && $.browser.version.substr(0,1)==7 && $('body.submit').length === 0 ) {
      if ( $(this).siblings('div').children('span').children('input').attr('checked') ){
        $(this).siblings('div').children('span').children('input').removeAttr('checked');
      }else{
        $(this).siblings('div').children('span').children('input').attr('checked','checked');
      }
      $(this).siblings('div').children('span').children('input').trigger('click');
    }

    if( $(this).siblings('div').children('span').hasClass('checked') ){
      $(this).siblings('div').children('span').removeClass('checked');
    }else{
      $(this).siblings('div').children('span').addClass('checked');
    }
  });

  $('input:radio').click(function(){
    radioName = $(this).attr('name');
    $('input:radio').each(function(){
      if( $(this).attr('name') == radioName ){
        $(this).parent().parent().siblings('.optionText').removeClass('active');
      }
    });
    $(this).parent().parent().siblings('.optionText').addClass('active');
  });

  if( $('input:checkbox:checked').length > 0 ){
    $('input:checkbox:checked').each(function(){
      $(this).parent().parent().siblings('.optionText').addClass('active');
    });
  }

  // View all categories
  $('.viewAllCategories').click(function(){
    $('.filterCategory').attr('checked', false);
    $(this).parent().siblings('.filter').children('fieldset:first').children('input:submit').trigger('click');
    return false;
  });

  if ( $('.filterCategory:checked').length > 0 ){
    $('.viewAllCategories').removeClass('active');
  }

  // View all categories
  $('.viewAllLocations').click(function(){
    $('.filterLocation').attr('checked', false);
    $(this).parent().siblings('fieldset:last').children('input:submit').trigger('click');
    return false;
  });

  if ( $('.filterLocation:checked').length > 0 ){
    $('.viewAllLocations').removeClass('active');
  }

  // Active or unactive talent/impression
  if ( $('#onlyShowTalentsCheckbox').attr('checked') ){
    $('.filterTalent a img').attr('src','/images/buttons/talentChecked.png');
    $('.filterTalent a').css({
      'color' : '#c36'
    });
  }
  if ( $('#onlyShowImpressionsCheckbox').attr('checked') ){
    $('.filterImpression a img').attr('src','/images/buttons/impressionsChecked.png');
    $('.filterImpression a').css({
      'color' : '#c36'
    });
  }


  // Impression thumbnails
  var vimeoID;
  var vimeoQuery;
  var impressionImage;

  $('.impressions .box').each(function(i){
    vimeoID = $('.vimeoID', this).val();
    $.ajax({
      url         : 'http://vimeo.com/api/v2/video/'+vimeoID+'.json',
      dataType    : 'jsonp',
      success     : function(data){
        impressionImage = $('.gridThumbnail',$('.impressions .box').eq(i));
        $.each(data, function(i,item){
          impressionImage.attr('src', item.thumbnail_large).hide().fadeIn('fast');
        });
        impressionImage.parent().siblings('.ajax-loader').remove();
      }
    });
  });

  if ( $('.home .vimeoID').length > 0 ){
    vimeoID = $('.home .vimeoID').val();
    $.ajax({
      url         : 'http://vimeo.com/api/v2/video/'+vimeoID+'.json',
      dataType    : 'jsonp',
      success     : function(data){
        impressionImage = $('.impressionImage');
        $.each(data, function(i,item){
          impressionImage.attr('src', item.thumbnail_large).hide().fadeIn('fast');
        });
        impressionImage.parent().siblings('.ajax-loader').remove();
      }
    });
  }

  // Filter talent / impression
  $('.filterTalent').click(function(){
    $('.filterTalentCheckbox')[0].checked = !$('.filterTalentCheckbox')[0].checked;
    $('.filterTalentCheckbox').trigger('click');
  });

  $('.filterImpression').click(function(){
    $('.filterImpressionCheckbox')[0].checked = !$('.filterImpressionCheckbox')[0].checked;
    $('.filterImpressionCheckbox').trigger('click');
  });

  // Simple form validation
  if ( $('body.submit, body.submit-impression').length > 0 ){

    var descriptionMax = 300;
    var descriptionLength = 0;
    var textarea = $('.fields textarea');

    textarea.keyup(function() {
      descriptionText = textarea.val();

      if ( ( descriptionMax-descriptionLength ) <= 0 ){
        textarea.val( descriptionText.substr(0, descriptionMax) );
      }
      descriptionLength = $(this).val().length;
      $('.charactersLeft').html(descriptionMax-descriptionLength);
    });

    try { $('.fields input:not(.submit), .emailValidation, .fields textarea').val().length; } catch(e) { }

    var validFormFields = 0;
    var validFormCategories = 0;
    var validFormLocations = 0;
    var validFormType = 0;
    var validFormTextarea = 0;
    var validFormEmail = 0;

    $('.selectList .optionText').click(function(){
      $('.selectList').children().find('.optionText').css({ 'color' : '#999' });
      $('.selectList').children().find('.optionText.active').css({ 'color' : '#333' });
    });

    $('.filterOption.location .optionText').click(function(){
      $('.filterOption.location').children().find('.optionText').css({ 'color' : '#999' });
      $('.filterOption.location').children().find('.optionText.active').css({ 'color' : '#333' });
    });

    $('.filterOption.type .optionText').click(function(){
      $('.filterOption.type').children().find('.optionText').css({ 'color' : '#999' });
      $('.filterOption.type').children().find('.optionText.active').css({ 'color' : '#333' });
    });

    $('input.submit').click(function(){

      // Reset
      validFormFields = 0;
      validFormCategories = 0;
      validFormLocations = 0;
      validFormTextarea = 0;
      validFormEmail = 0;

      $('.fields input:not(.submit), .emailValidation, .fields textarea').css({ 'background' : '#fff' });
      $('.selectList, .filterOption.location, .filterOption.type').children().find('.optionText').css({ 'color' : '#999' });
      $('.selectList, .filterOption.location, .filterOption.type').children().find('.optionText.active').css({ 'color' : '#333' });

      $('.fields input').each(function(){
        if ( $(this).val() == "" ){
          validFormFields++;
          $(this).css({ 'background' : '#c36' });
        }
      });

      if( isValidEmailAddress( $('.emailValidation').val() ) ){

      }else{
        validFormEmail = 1;
        $('.emailValidation').css({ 'background' : '#c36' });
      }


      // if ( $('.fields textarea').val() == "" ){
      //   validFormTextarea++;
      //   $('.fields textarea').css({ 'background' : '#c36' });
      // }

      $('.selectList input:checked').each(function(){
        validFormCategories++;
      });

      if ( validFormCategories == 0 ){
        $('.selectList').children().find('.optionText').css({ 'color' : '#c36' });
      }

      $('.filterOption.location input:checked').each(function(){
        validFormLocations++;
      });

      if ( validFormLocations == 0 ){
        $('.filterOption.location').children().find('.optionText').css({ 'color' : '#c36' });
      }

      $('.filterOption.type input:checked').each(function(){
        validFormType++;
      });

      if ( validFormType == 0 ){
        $('.filterOption.type').children().find('.optionText').css({ 'color' : '#c36' });
      }


      if ( $('body.submit').length > 0 ){
        // validFormTextarea > 0 ||
        if( validFormFields > 0 || validFormCategories == 0 || validFormLocations == 0 || validFormEmail > 0 ){
          // {"validFormFields":0,"validFormCategories":1,"validFormLocations":1,"validFormTextarea":1,"validFormEmail":0}
          return false; // Fail
        }
      }else if( $('body.submit-impression').length > 0 ){
        if( validFormFields > 0 || validFormEmail > 0 ){
          return false; // Fail
        }
      }
    });
  }

  // Create cookie
  function createCookie(name,value,days) {
    var expires;
    if (days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      expires = "; expires="+date.toGMTString();
    }
    else expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
  }

  // Read cookie
  function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
  }

  // Validate email
  function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
  }

  if ($('body.holding-page').length > 0) {
    HOLDINGPAGE.init();
  }


});


/*
 * Holding page module
 */
var HOLDINGPAGE = {

  init: function(){
    this.initSlides();
  },

  initSlides: function(){
    _this = this;
    var slides = $('.slide');
    slides.hide()
          .first()
          .show()
          .addClass('active');

    // Custom validation rules
    $.validator.addClassRules({
      image: {
        required: true,
        accept: "gif|png|jpe?g"
      }
    });

    // Events
    $('.slide .next').click(function(event){
      event.preventDefault();
      _this.validate();
      //_this.nextSlide();
    });

    $('.slide .previous').click(function(event){
      event.preventDefault();
      _this.previousSlide();
    });

    $('button[type=submit]').click(function(event){

    });

  },

  nextSlide: function(){
    var current_slide     = $('.slide.active');
    var current_slide_idx = $('.slide').index(current_slide);
    var next_slide_idx    = current_slide_idx + 1;
    var next_slide        = $('.slide:eq(' + next_slide_idx + ')');

    current_slide.removeClass('active');
    current_slide.fadeOut(300, function(){
      next_slide.addClass('active')
                .fadeIn(300);
    });
  },

  previousSlide: function(){
    var current_slide       = $('.slide.active');
    var current_slide_idx   = $('.slide').index(current_slide);
    var previous_slide_idx  = current_slide_idx - 1;
    var previous_slide      = $('.slide:eq(' + previous_slide_idx + ')');

    current_slide.removeClass('active');
    current_slide.fadeOut(300, function(){
      previous_slide.addClass('active')
                    .fadeIn(300);
    });
  },

  validate: function(){
    _this = this;
    var current_slide       = $('.slide.active');
    var current_slide_idx   = $('.slide').index(current_slide);

    switch(current_slide_idx) {
      case 0:
        if (!$('form').validate().element('input[name=lalala_creative_network_profile[profile_type]]')) return false;
        if (!$('form').validate().element('input[name=lalala_creative_network_profile[title]]')) return false;
        if (!$('form').validate().element('input[name=lalala_creative_network_profile[email]]')) return false;
        if (!$('form').validate().element('textarea[name=lalala_creative_network_profile[description]]')) return false;
        if (!$('form').validate().element('input[name=lalala_creative_network_profile[vat]]')) return false;
        if (!$('form').validate().element('input[name=lalala_creative_network_profile[url]]')) return false;
        if (!$('form').validate().element('input[name=lalala_creative_network_profile[image_big]]')) return false;
        break;
      case 1:
        break;
      case 2:
    }
    _this.nextSlide();
  }

};


