$(document).ready(function(){
  minwidth();
  randoms();
  makepopups();
  $('#age').text(age($('#dob').text()));
  deletethis();
  $('label.overlabel').overlabel();
  calendar();
  $('#content form input[value=]:first').focus();
});

jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept",
    "text/javascript")} 
})  

function minwidth() {
  /* DO SOME OBJECT DETECTION FOR JS LAYOUT EFFECTS */
  var ie5 = document.all && !document.fireEvent && !window.opera; /* IE < 5.5 */
  var ffie7op = window.XMLHttpRequest; /* FF, IE7 & OPERA */
  if (!ie5) {
    if(document.getElementById) {
      if(ffie7op) { /* NO NEED FOR MIN-WIDTH */
        return;
      }
      $('body').css({ width:'100%' }); /* MAKE LIQUID WIDTH FOR IE6 */
      window.onresize=function() {
        if (document.documentElement.offsetWidth < 941) {
          $('body').css({ width:'940px' });
        } else {
          $('body').css({ width:'100%' });
        }
      }
    }
  }
}


function randoms() {
  $('.slide-show p').each(function(){
    src = 'url(/images/modules/slideshow-anim-' + randomize(3) +'.gif)';
    $(this).css("backgroundImage", src );
    var ss = new Array('14','12','10');
    $(this).children('a.popup-link').attr({ href: '/blogs/1/albums/' + ss[(randomize(3)-1)] + '/slideshow' });
  });
  $('.blog-that-baby').each(function(){
    src = 'url(/images/elements/big-baby-' + randomize(2) +'.jpg) 50% 0 no-repeat';
    $(this).css("background", src );
  });
  $('.unlimited-photos').each(function(){
    src = 'url(/images/elements/unlimited-photos-' + randomize(3) +'.jpg) 50% 100% no-repeat';
    $(this).css("background", src );
  });
  $('.screenshot img').each(function(){
    src = '/images/modules/screen-shot-' + randomize(13) +'.jpg';
    $(this).attr({ src: src });
  });
}

function randomize(n) {
  x=(Math.floor(Math.random()*n)) + 1;
  return x;
}

function makepopups() {
  var defs = 'resizable=yes,toolbar=no,location=no,scrollbars=yes';
  var cw = 'width=' + $(document).width() + ',height=' + $(document).height() + ',' + defs;
  $('a.popup-link').click(function(event) {
    var r = $(this).attr('rel');
    if(!r){
      popup($(this).attr('href'),'bb',cw);
      return false;
    } else {
      r = $(this).attr('rel').split(' ');
      f = 'width=' + r[1] + ', height=' + r[2] + ',' + defs;
    }
    if (r[0]!='photo') {
      if('undefined' !== $(this).attr('href')) {
        if(r[0] == 'theme-picker') {
          var cu = $(this).attr('href');
          var st = $('#blog_template_id option:selected').attr('value');
          u = cu.replace(/\d+$/, st);         
        } else {
          var u = $(this).attr('href') + '?popup=1';
        }
      } else {
        return false;
      } 
    } else {
      var f = 'width=' + (parseInt(r[1]) + 55) + ',height=' + (parseInt(r[2]) + 80) + ',' + defs ;
      var u = $(this).attr('href');
      var n = r[0];
    }
    popup(u,n,f);
    return false;
  });
  $('#open-demo').click(function(event) {
    popup('','demo_blog',cw);
    $('#view-demo').attr({ target: 'demo_blog' }).submit();
    return false;
  });
}

function popup(u,n,f) {
  var newwin = window.open(u,n,f);
  newwin.focus();
}

function age(dob) {
  var bd = dob.split('/');
  var month = bd[0]; /* BIRTH MONTH */ 
  var day = bd[1]; /* BIRTH DAY */
  var year = bd[2]; /* BIRTH YEAR */
  var d = new Date(); /* GET FULL DATE */
  var thisYear = d.getFullYear(); /* CURRENT YEAR */
  var thisMonth = d.getMonth() + 1; /* CURRENT MONTH */
  var thisDay = d.getDate(); /* CURRENT DAY */
  var yearsold = thisYear - year, monthsold = 0, daysold = 0, string = '';
  if (thisMonth >= month) {
    monthsold = thisMonth - month;
  } else {
    yearsold--; monthsold = thisMonth + 12 - month;
  }
  if (thisDay >= day) {
    daysold = thisDay - day;
  } else {
    if (monthsold > 0) {
      monthsold--;
    } else {
      yearsold--; monthsold+=11;
    }
    daysold = thisDay + 31 - day;
  }
  if ((yearsold < 0) || ((yearsold == 0) && (monthsold == 0) && (daysold == 0))) { return 'Unknown'; }

  var age = new Array([ yearsold,' year' ], [ monthsold, ' month' ], [ daysold, ' day'] );
  for (i=0; i<age.length; i++) {
    if (parseInt(age[i][0]) > 0) {
      string += parseInt(age[i][0]) + age[i][1];
      if (parseInt(age[i][0]) > 1) {
	    string += 's';
        string += ' ';
      }
    }
  }
  return string;
}

function maketrash() {
  $('form.button-to').each(function() {
    $(this).children('div').children('input.button').addClass('delete-this');
  });
}
function deletethis() {
  $('a.delete-this').click(function(event) {
    if ($(this).parent('td').attr('className') == 'has-photos') {
      var a = confirm('Deleting an album containing photos will not delete the photos, but will result in them being \"Unassigned\". Unassigned photos will not display on your Babyblogger.com site until you assign them to an album on Your Photos page.\n\nClick "Cancel" if you do not wish to delete this album, otherwise click "OK".')
    } else {
      var a = confirm('This will delete this item permanently. Is this what you want to do? Click "Cancel" if you are unsure, otherwise click "OK".');
    }
    if(!a) { return false; }
  });
}

function zeroPad(n, digits) {
  n = n.toString();
  while (n.length < digits) {
    n = '0' + n;
  }
  return n;
}

function calendar() {
  Date.firstDayOfWeek = 7;
  $('#vital_birth_date').each(function() {
    var tid = '#' + $(this).attr('id');
    $(this).datePicker( {
        createButton: false,
        displayClose: 'true',
        startDate:
          zeroPad(($(tid + '_3i option:nth-child(2)').val()),2)  + '/' +
          zeroPad(($(tid + '_2i option:nth-child(2)').val()),2)  + '/' +
          $(tid + '_1i option:last-child').val(),
        endDate:
          zeroPad(($(tid + '_3i option:last-child').val()),2)  + '/' +
          zeroPad(($(tid + '_2i option:last-child').val()),2)  + '/' +
          $(tid + '_1i option:nth-child(2)').val()
      }
    ).bind(
      'click',
      function() {
        updateSelects($(this).dpGetSelected()[0]);
        $(this).dpDisplay();
        return false;
      }
    ).bind(
      'dateSelected',
      function(e, selectedDate, $td, state) {
        updateSelects(selectedDate);
      }
    ).bind(
      'dpClosed',
      function(e, selected) {
        updateSelects(selected[0]);
      }
    );
    var updateSelects = function (selectedDate) {
      var selectedDate = new Date(selectedDate);
      $(tid + '_3i option[value=' + selectedDate.getDate() + ']').attr('selected', 'selected');
      $(tid + '_2i option[value=' + (selectedDate.getMonth()+1) + ']').attr('selected', 'selected');
      $(tid + '_1i option[value=' + (selectedDate.getFullYear()) + ']').attr('selected', 'selected');
    }
    $(tid + '_3i' + ',' + tid + '_2i' + ',' + tid +'_1i').bind(
      'change',
      function() {
        if(($(tid + '_2i').val() != '') && ($(tid + '_3i').val() != '') && ($(tid + '_1i').val() != '')) {
          var d = new Date(
            $(tid + '_1i').val(),
            $(tid + '_2i').val()-1,
            $(tid + '_3i').val()
          );
          $(tid).dpSetSelected(d.asString());
        }
      }
    );
    $(tid + '_3i' + ',' + tid + '_2i' + ',' + tid +'_1i').trigger('change')
  });
}
/* Copyright (c) 2008 Brandon Aaron (http://brandonaaron.net) */
(function($){
  $.fn.overlabel = function() {
    this.each(function() {
      var $label = $(this), $input = $('#' + $label.attr('for'));
      $label
      .addClass('overlabel-apply')
      .bind('click', function(event) {
        $input.focus();
      });
      $input
      .bind('focus blur', function(event) {
      $label.css('display', (event.type == 'blur' && !$input.val() ? '' : 'none'));
    }).trigger('blur');
  });
  };
})(jQuery);
