/**
 * This file is a mess. Almost everything in it is un- or
 * under-documented. Nothing is tested or testable. Nothing
 * is structured.
 *
 * I have marked up a bunch of sections with @FIXME comments
 * but these are likely inadequate.
 *
 * The general remediation approach should be:
 *
 *  - Factor reusable pieces out into jQuery plugins -
 *    write tests for these (vows.js or similar) and
 *    add to the build.
 *  - Replace custom plugins with 3rd party ones where
 *    appropriate.
 *  - Move anything which can be accomplished with CSS
 *    or PHP to the relevant place.
 *  - Move anything which belongs to a specific module
 *    into $module/js/$module.js.
 *  - Remove everything which is not understood.
 *  - Document the crap out of everything left with 
 *    reference to PT stories, URLs etc. to provide
 *    context.
 */

jQuery(function($) {

  /*
   * Used to smooth scroll internal links
   */
  //@FIXME This can be moved into its own file
  $.fn.extend({scrollTo: function(speed, easing) {
    return this.each(function() {
      var targetOffset = $(this).offset().top;
      $('html,body').animate({scrollTop: targetOffset}, speed, easing);
    });
  }});

  /*
   * Add lightbox effect to selected links
   */
  $("a[rel^='prettyPhoto']").prettyPhoto({animation_speed:'fast',slideshow:10000});
  $("a[rel^='lightbox']").prettyPhoto({animation_speed:'fast',slideshow:10000});

  /*
   * pseudo link behaviour for things which are not links
   */
  //@FIXME make them links duh
  $([
    '.thumbnail-link',
    '#block-vu_expert_guide-expert-guide-search-results ul.results li',
    '#block-views-success_stories-block_4 .views-row'
  ].join(',')).not('.noimage').click(function(event) {
    event.stopPropagation();
    var a = $(this).find('a');
    if(a.attr('target').toLowerCase() == '_blank') {
      window.open(a.attr('href'));
    } else {
      location.href = a.attr('href');
    }
    return false;
  });

  /*
   * Remove link to username rememberer...
   */
  //@FIXME can we do this in form_alter or similar?
  var remb = $('.error a');
  if(remb.text() == 'Have you forgotten your password?') {
    remb.hide();
  }

  /*
   * =========================
   * = Reusable tooltip code =
   * =========================
   */
  //@FIXME factor out into separate script or plugin
  var open = 0;

  $('.tooltip').each(function() {
    var tooltip = $(this);
    var tipContent = $('<span class="tooltip-content"></span>');
    var re = new RegExp('\\[(.+)\\|(.+)\\]','g');
    var tiptext = tooltip.attr('title');
    tiptext = tiptext.replace(re,'<a href="$2">$1</a>');
    tipContent.html(tiptext);
    tooltip.after(tipContent);
    tooltip.removeAttr('title');

    $(this).hoverIntent({
      sensitivity: 7,
      interval: 300,  
      over: function(event) {
        tipContent.show();
      }, 
      timeout: 1000,  
      out: function(event) {
        tipContent.hide();
      }
    });
  });

  /*
   * Zebra stripes
   */
  $('table').attr('style', '');
  $('table, tr').attr('align', '');
  $('tr:odd').addClass('odd');

  /**
   * Force content min-height to sidebar height
   * @FIXME css? #content { min-height:400px; }
   * Am I missing something?
   */
  h = $('#sidebar-left').css('height');
  if(h >= 400) {
    $('#content').css('min-height', h);
  }

  /*
   * News and events tabs
   * @FIXME move to news/events module
   * @FIXME crazy magic numbers smell
   */
  $('.news h2, .news .content').addClass('active');
  $('.events h2').click(function() {
    $('.news .content, .news h2 ').removeClass('active');
    $('.news .content').css('z-index', '5');
    $('.events .content, .events h2').addClass('active');
    $('.events .content').css('z-index', '6');
    return false;
  });
  $('.news h2').click(function() {
    $('.events .content, .events h2 ').removeClass('active').css('z-index','5000');
    $('.events .content').css('z-index','5');
    $('.news .content, .news h2').addClass('active').css('z-index','5001');
    $('.news .content').css('z-index','6');
    return false;
  });

  /*
   * Add external link icon
   */
  var host = location.host;
  $('#page a').not('.noext').each(function() {
    var _host = this.innerHTML && this.href.split('/')[2];
    if (_host && _host != location.host) {
      $(this).addClass('ext');
      this.target = '_blank';
      //TODO: check if it's a subdomain
    }
  });

  /*
   * Add PDF icon
   */
  $('a').filter(function() {
    return this.href.match(/\.pdf[\s]*$/i);
  }).addClass('pdf');

  /*
   * Track all downloadable files
   */
  $('a').each(function() {
    var anchor = $(this);
    var href = anchor.attr("href") ? anchor.attr("href") : '';
    if(this.hostname == document.domain && href.match(/\.(pdf|doc|docx|xls|xlsx|zip|exe|ppt|swf|rtf|txt|dot|avi|wmv|mp3|mpeg|wav)$/i)) {
      var path = this.pathname;
      if(path.charAt(0) != '/') {path = '/' + path;}
      anchor.click(function() {
        _gaq.push(['_trackPageview', path]);
      });
    }
  });

  /*
   * Track outgoing links
   */
  $('a.ext').click(function() {
    // convert e.g. http://www.bankers.asn.au/default.aspx?ArticleID=1403
    // to /outgoing/www.bankers.asn.au/default.aspx?ArticleID=1403
    var path = ['/outgoing'].concat(this.href.split('/').slice(2)).join('/');
    _gaq.push(['_trackPageview', path]);

  });

  /*
   * Track mailto links
   */
  $('a[href^="mailto:"]').click(function() {
    _gaq.push(['_trackPageview', this.href]);
  });

  /*
   * Add GA campaign tracking to sidebar images
   */
  $('.view-campaigns a img').each(function() {
    var img    = $(this),
        alt    = img.attr('alt'),
        href   = img.parent('a').attr('href'),
        params = {
          'utm_source':   'VU Website',
          'utm_medium':   'Sidebar Image',
          'utm_campaign': 'Internal+Link Tracking'
        }

    if(alt.length) params['utm_content'] = alt;

    href += (href.match(/\?/) ? '&' : '?') + $.param(params);
    img.parent('a').attr('href', href);
  });

  /*
   * Increase / decrease font size
   */
  var fs = readCookie('textsize') || 0;
  function set_text_size(delta) {

    if($('body#home').length) return;

    fs = Math.max(0, Math.min(2, parseInt(fs, 10) + parseInt(delta, 10))) ;
    switch(fs) {
      case 0:
        $('body').css('zoom','100%').css('-moz-transform', '');
        $('a.decrease').addClass('disabled');
        $('a.increase').removeClass('disabled');
        break;
      case 1:
        $('body').css('zoom','116%')
          .css('-moz-transform', 'scale(1.15) translate(0,6.5%)');
        $('a.decrease').removeClass('disabled');
        break;
      case 2:
        $('body').css('zoom','132%')
          .css('-moz-transform', 'scale(1.3) translate(0,11.5%)');
        $('a.increase').addClass('disabled');
        break;
    }
    createCookie('textsize', fs, 365);
  }
  $('.increase').click(function() { set_text_size(1); return false; });
  $('.decrease').click(function() { set_text_size(-1); return false; });
  set_text_size(0);

  /*
   * Remove border-top for first h2
   */
  $('#content h2:first').addClass('first');

  /*
   * Add class to body on diff pages so they can be styled. Look for
   * body.diff selectors. This causes a flash but I think it's better
   * than setting CSS directly in JS. Improvements welcome.
   */
  if($('table.diff').length) {
    $('body').addClass('diff');
  }

  //@FIXME form_alter?
  $('.block-notifications_ui #edit-subscriptions-submit')
    .attr('value','Subscribe by email');

  /*
   * iPhone javascript
   */
  var mobile_redirect = is_mobile_webkit();
  mobile_redirect     &= location.hostname.indexOf('m.vu.edu.au') == -1;
  mobile_redirect     &= location.hostname.indexOf('i.vu.edu.au') == -1;

  if(mobile_redirect) {
    var ihref = '/m' + (location.pathname.charAt(0) == '/')
      ? location.pathname
      : '/' + location.pathname;
    $('<div class="switch"><a href="'+ihref+'">Go to mobile site</a></div>')
      .appendTo($("body"));
  }

  /*
   * Add unpublished flag to link titles
   */
  //@FIXME can be done in module?
  $('a.unpublished').each(function() {
    $(this).html(this.title + ' <em>(unpublished)</em>');
    this.title = 'UNPUBLISHED: ' + this.title;
  });

  /*
   * Fix up course testimonials
   * @FIXME do we still need this? What's wrong with them?
   */
  if($('#content-top div').length < 1) {
    $('#content-top').remove();
  }

  /*
   * IE 6, 7, 8 doesn't respond to "change" event correctly
   * @FIXME can this be done with a library e.g. modernizr?
   */
  $('input[name="iam"]').bind(($.browser.msie && $.browser.version < 9 ? 'propertychange' : 'change'), function() {
    var iam = $(this).val();
    $('body').toggleClass('international', (iam == 'non-resident'));
  });


  /*
   * focus username input on user field
   */
  $('.page-user #edit-name').focus();

  /*
   * Hide all permissions but the ones admins need
   * @FIXME document this, fix style etc
   */
  $('.content_access-div').eq(1).addClass('show');
  $('.show label:first').text('Editing rights for this page:');
  $('form#content-access-page .description').text('You can add and remove editing rights to this page using the form below. Simply select the groups for which you would like to grant or remove editing rights, and hit the "submit" button. Too easy!');
  $('form#content-access-page div.form-checkboxes input[value=1]').parent().css('display','none');
  $('form#content-access-page div.form-checkboxes input[value=2]').parent().css('display','none');

  var s = $('div#column-image #email a').text();
  var f = s.split('@');
  $('div#column-image #email a').html(f[0]+'@<br />'+f[1]);

  $('input#edit-group-events-contact-group-events-contact-add-more, input#edit-group-news-contact-group-news-contact-add-more').attr('value','Add more contacts');
  $(window).load(function() {
    $('body.add.webform table#edit-body_tbl').css('width','706px');
  });

  /*
   * Internal links
   */
  //@FIXME visited style is broken
  $('#content a[href^=#]').click(function() {
    if($('form').hasClass('#node-form')) return;
    $(this).addClass('visited');

    var target = $('[name=' + this.hash.slice(1) +']');

    // Fixes chrome bug where offset is not set on anchors
    target.css("display", "inline-block");
    target.css("position", "absolute");

    if (target.length > 0) {
      target.scrollTo(1000, 'easeOutCirc');
      return false;
    }

    return true;
  });

  //@FIXME move style to css
  var backup = $('<a id="back-up" style="margin-left:4px;" href="#page-top">Back to navigation links</a>');

  $('a#skiplink').click(function() {
    $('div#breadcrumb').append(backup);
    backup.focus();
    backup.css('position','static');
  });

  backup.click(function() {
    $('a#skiplink').focus();
    $(this).css('position','absolute').css('left','-5000em');
    return false;
  });

  /*
   * Set the webpage reference on feedback form
   */
  var referenceInput = $('body#website-feedback #edit-submitted-url');
  if (referenceInput.length && referenceInput.val() == '') {
    referenceInput.val(document.referrer);
  }


});

function is_mobile_webkit() {
  return navigator.userAgent.match(/iPhone|Android/); // sry android tablets :/
}

// Set cookie for text size settings  
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
  }
  else var expires = "";
  document.cookie = name + "=" + value + expires + "; path=/";
}

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).split(';')[0]; }
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name, '', -1);
}

