/* The Net is Dead site Javascript

   Dependencies: JQuery 1.2.1

   Feel free to study / use parts of this code
   in your own non-commercial project.
   
   Copyright 2007 (c) Marco van Hylckama Vlieg
   
   marco@i-marco.nl
   
   http://www.i-marco.nl/weblog/
   
   If you want me to (re)write anything for your
   own specific purposes:

   I might, but only if you pay me. 
   I'm too busy for freebies. I'm sorry. */

// JQuery scrollTo plugin
// Copyright (c) 2007 Ariel Flesler
//
// See: http://plugins.jquery.com/project/ScrollTo

(function($){$.scrollTo=function(a,b){return $('html,body').scrollTo(a,b)};$.scrollTo.defaults={axis:'y',speed:1};$.fn.scrollTo=function(d,e){e=$.extend({},$.scrollTo.defaults,e);e.queue=e.queue&&e.axis.length==2;if(e.queue)e.speed=Math.ceil(e.speed/2);if(typeof e.offset=='number')e.offset={left:e.offset,top:e.offset};return this.each(function(){var c=$(this),t=d,q,r={};switch(typeof t){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(t)){t={top:t,left:t};break}t=$(t,this);case'object':if(t.is||t.style)q=(t=$(t)).offset()}$.each(e.axis.split(''),parse);animate(e.onAfter);function parse(i,b){var P=b=='x'?'Left':'Top',p=P.toLowerCase(),k='scroll'+P,a=c[0][k];r[k]=q?q[p]+(c.is('html,body')?0:a-c.offset()[p]):t[p];if(e.margin&&t.css)r[k]-=parseInt(t.css('margin'+P))||0;if(e.offset&&e.offset[p])r[k]+=e.offset[p];if(!i&&e.queue){if(a!=r[k])animate(e.onAfterFirst);delete r[k]}};function animate(a){c.animate(r,e.speed,e.easing,function(){if(a)a.call(this,c,r,t)})}})}})(jQuery);

var imarco = function(){
	
/* imarco module containing all JS for this site
    only exposed (public) method is init() */


  var pub = {};

  function sideTabs() {

    // This methods makes the sidebar tabs work

    $('a.clicktab').click(function() {

    // fadeout whatever content pane is currently visible
    $('div.menutab:visible').fadeOut();

    // reset all tab backgrounds to 'not active'
    $('a.clicktab').css('background-position', 'top');

    // set the clicked tab's background to 'active'
    $(this).css('background-position', 'bottom');	

    // archivelink => archive etc. so fade in the appropriate content pane
    $('div#' + $(this).attr('id').replace('link', '')).fadeIn();

    // make sure we don't actually follow the link
    return false;
    });	
  };

  function checkEmail(value) {

    // simple email validator
    return /^[^\s,;]+@([^\s.,;]+\.)+[\w-]{2,}$/i.test(value);
  
  }

  function liveSearch() {

    // disable browser autocomplete on the searchbox

    $('#searchbox').attr('autocomplete', 'off');

    // When a key is pressed in the search box we start a timer that will 
    // fire off a search 
    // requests after 1 second. 

    $('#searchbox').keypress(function() {

      // If a timer was already running because of a previous keypress, 
      // cancel it!
    
      clearTimeout(imarco.t);

      // set the timer

      imarco.t = window.setTimeout(
        function() {

          // show the search spinner image to indicate activity
	
          $('img#spinner').css('visibility', 'visible');

          // fire an XHR
		  
          $.ajax({
                  type: "POST",
                  url: '/weblog/pivot/search2.php',
                  data: 'search=' + document.getElementById('searchbox').value,
                  success: function(html)  {
                    if(html !== '') {

                    /* There are results. Fade out the element with whatever 
                       was in it before,
                       empty the element, stick in the new results and fade
                       it back in. */
		    
                      $('#searchresults').fadeOut().empty().append(html).fadeIn();
                    }
                    else {

                      // There was nothing returned. If results were being displayed, fade them out
		    
                      $('#searchresults').fadeOut();
                    }
                    
                    // Hide the spinner animation
                    
                    $('#spinner').css('visibility', 'hidden');
                  }
                });
      } ,1000);
    });
  };

  function pulsate(elem) {

    // This look stupid but it perfectly emulates the scriptaculous pulsate 
    // effect I had before

    elem.fadeIn(100).fadeOut(300).fadeIn(100).fadeOut(300).fadeIn(100).fadeOut(300).fadeIn(100).fadeOut(300).fadeIn(100);

  }

  function initComments() {

    // legacy issue. I may be able to get rid of this but I can't be arsed :P

    hiddenElements = document.getElementsByTagName('input');
      for(i=0;i<hiddenElements.length;i++)  {
	    if(hiddenElements[i].type == 'hidden')  {
          if((hiddenElements[i].name == 'piv_spkey') || (hiddenElements[i].name == 'piv_code') || (hiddenElements[i].name == 'piv_weblog'))	{
            hiddenElements[i].setAttribute('id', hiddenElements[i].name);
          }
        }
      }

      // Attach a click event to the comment submit button
    
    $('#submit').click(
      
      function() {

        // Do some simple validation
      
        var fault = false;
        if($('#piv_name').val().length < 2)  {
          $('#comerror').empty().append('Error: please enter your name.');
          fault = true;				
        }
        if($('#piv_email').val().length > 0)  {
          if(!checkEmail($('#piv_email').val()))  {
            fault = true;
            $('#comerror').empty().append('Error: if you enter an email address it should be a valid one.');
          }
        }
      if($('#piv_comment').val().length < 5)  {
        fault = true;
        $('#comerror').empty().append('Error: please enter a comment.');	
      }

      // validation issues? Pulsate an error box and bail out
      
      if(fault) {
        pulsate($('#comerror'));
        return false;	
      }

      // We have a go!
      // show the comment spinner image to indicate activity 
      
      $('#commentspinner').css('visibility', 'visible');

      // prepare the parameters to send
      
      pars = 'piv_comment='       + $('textarea#piv_comment').val() +
             '&piv_url='          + $('input#piv_url').val() +
             '&piv_name='         + $('input#piv_name').val() +
             '&piv_email='        + $('input#piv_email').val() +
             '&piv_spkey='        + $('input#piv_spkey').val() +
             '&piv_code='         + $('input#piv_code').val() +
             '&piv_rememberinfo=' + $('input#piv_rememberinfo').val() +
             '&piv_notify='       + $('input#piv_notify').val() +
             '&piv_weblog='       + $('input#piv_weblog').val() +
             '&spammerspissoff=yes';
             
     // Fire off the comment, XHR style
	     
     $.ajax({
             type: "POST",
             url: '/weblog/pivot/ajax_submit.php',
             data: pars,
             success: function(html)  {

               // It worked. Append the response to the document
               // in the #commentholder element

               $('#commentholder').append(html);

               // Scroll to where the comment will be inserted. After the 
               // scrolling completes, slide down the newly inserted comment

               $.scrollTo($('#ankertje'), {speed:500, onAfter:function() {$('#commentholder').slideDown('slow');}});

               // Hide comment button to prevent a resubmit, show a notice
               // and hide the spinner image

               $('#cbuttons').css('display', 'none');	
               $('#commentposted').show();
               $('#commentspinner').css('visibility', 'hidden');
             }
           });		
      }
    );
  }

  function doMail()  {

    // AJAX contact form. 
    // Attach event to the submit button in the form

    $('#caction').click(function() {

      // Validation, similar to what happens in the comment form.
  
      var fault = false;
      if($('#cname').val() === '')  {
        fault = true;
        $('#cerror').empty().append('Error: please enter your name.');
      }
      if($('#csubject').val().length < 1)  {
        fault = true;
        $('#cerror').empty().append('Error: please enter a subject.');		
      }
      if(!checkEmail($('#cemail').val()))  {
        fault = true;
        $('#cerror').empty().append('Error: please enter a valid email address.');
      }
      if($('#cmessage').val().length < 10)  {
        fault = true;
        $('#cerror').empty().append('Error: You didn\'t enter anything that looks like a message.');
      }

       // Incomplete form? bail out and show an error.

      if(fault) {
        $('#cerror').show();
        pulsate($('#cerror'));
        return false;		
      }
      else  {

        // show spinner image to indicate activity
	
        $('#cspinner').css('visibility', 'visible');

        // prepare parameters to send
	
        pars = 'subject='  + $('#csubject').val() + 
               '&email='   + $('#cemail').val() + 
               '&name='    + $('#cname').val() + 
               '&url='     + $('#curl').val() + 
               '&message=' + $('#cmessage').val();

        // fire off an XHR to the email script

        $.ajax({
                type: "POST",
                url: '/weblog/pivot/mail.php',
                data: pars,
                success: function(html)  {
                
                  // If something comes back, hide the spinner,
                  // insert the response and fade it in
	     
                  $('#cspinner').css('visibility', 'hidden');
                  $('#contactform').hide().empty().append(html).fadeIn();
               }
        });
      }
    });
  }

  function doMiscStuff()  {	

    // Attach some enhancement events that don't really justify having their  
    // own method

    // make meta tab thingies slide in / out

    $('.metalink').click(function() { $(this).parent().prev().slideToggle('fast'); });	

    // same thing for the social bookmarking tabs
  
    $('.stab').click(function() { $(this).prev().slideToggle('fast'); });

    // make header clickable to go home

    $('#head').click(function() { window.location.href = '/weblog/';});

    // elegantly scroll down to the comments when the 'join the discussion' 
    // link is clicked
  
    $('#commentwarp').click(function() { $.scrollTo($('#commentform'), {speed:500}); });

    // warn spamming bastards when they start filling out their URL to not
    // bother if they want to trash my site with their commercial crap
  
    $('#piv_url').focus(function() { $('#urlalert').slideDown(); });

    $('#closesearchpanel').click(function() {
        $(this).parent().slideUp('fast');
	return false;
        });
    }

  // The inly public method fires off everything to initialize it all

  pub.init = function(){
	  sideTabs();
	  liveSearch();
	  doMiscStuff();
	  initComments();
	  doMail();
  };

  // expose the public method
  
  return pub;
  
}();

// document loaded? Do all that needs to be done in one nice call!

$(document).ready(function() {
  imarco.init();
  });

