var spin = '<img src="/images/elements/progress-spinner.gif" width="16" height="16" alt="Loading&#8230;" id="spinner" />';
$(document).ready(function(){
  if($('body').attr('className') != 'popup') {
    minwidth();
    makepopups();
    $('#age').text(age($('#dob').text()));
    deletethis();
    $('label.overlabel').overlabel();
    calendar();
    $('#content form input[value=]:first').focus();
    $.getScript('/js/jquery-ui-1.7.2.custom.min.js', function() {
      dd_photos();
      show_photo_order();
    });
    blog_id = $('#your-photo-order').attr('blog');
    if (blog_id) {
      $('body').append('<ul id="photo-controlbar"><li id="view"><a href="" title="Mouse over to view larger"><img src="/images/blogs/photo-control-view.gif" width="20" height="16" border="0" alt="" onclick="return false;" /></a></li><li id="delete"><a href="" title="Click to remove photo from order" onclick="return false;"><img src="/images/blogs/photo-control-delete.gif" width="20" height="16" border="0" alt="Remove from photo order" /></a></li></ul>');
    }
  } else {
    $('li#close').children('a').click(function(){
      window.close();
      return false;
    });
    $('li.order-photo').children('a').click(function(){
      if (window.opener && !window.opener.closed) {
        window.opener.photo_order_crud($('img').attr('blog_id'),$('img').attr('pid'),0);
        self.close();
      } else {
        alert('There was an error adding the photo. Please return to the Album and try again.');
      }
      return false;
    });
  }
});

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

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 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')
  });
}

function psuedoflash(v,mess,loc) {
  v == 'error' ? d = '4000' : d = '1800';
  var flash = 'flash-' + v;
  $('#' + loc).prepend('<ul id="' + flash + '" style="display:none"><li>' + mess + '</li></ul>');
  $('#' + flash).fadeIn(400);
  setTimeout(function(){
    $('#' + flash).fadeOut(500, function(){
      $('#' + flash).remove()
    })
  }, d);
  return true;
} 

function show_photo_order() {
  $('#your-photo-order').each(function(){
    $('#your-photos').html(spin).ajaxStart(function(){
      $(this).html(spin);
    });
    $.ajax({
      type: 'GET',
      url: $(this).attr('ezp'),
      dataType: 'xml',
      error: function(XMLHttpRequest, textStatus, errorThrown) {
      },
      success: function(xml) {
        if($(xml).find('Asset').length > 0) {
          $(xml).find('Asset').each(function(){
            var src = $(this).attr('ScreenResUri');
            src = src.replace(/\.[^.]+$/, '.tiny');
            var id = 'p' + $(this).attr('Id');
            $('#your-photos').append(
              '<img src="' + src + '" id="' + id + '" />'
            );
            $('#' + id).attr({ className: 'photo' }).jqphotocontrol();
          });
          if($('#your-photo-order').find('button').length == 0) {
            $('#your-photo-order').append(
              '<p><button title="Order photo products using these photos" onclick="location.href=\'/order-photo-products\'">Order Photo Products</button></p>'
            );
          }
        } else {
          $('#your-photos').append('<p class="order-photos"><img src="/images/elements/photo-products/photo-products-sm-' +  randomize(5) + '.gif" width="100" height="75" alt="" />Select any photo to order it as a print, mug, calendar and more!</p>');
        }
      },
      complete: function(){
        $('#your-photos').find('#spinner').remove();
      }
    });
  });
}

function dd_photos() {
  $('img.photo').draggable({ revert: true });
  $("#contextual #your-photo-order").droppable({
    activate: function() {
      $('#your-photos').addClass('predrop'); 
    },
    deactivate: function() {
      $('#your-photos').removeClass('predrop');
    },
    over: function() {
      $('#your-photos').addClass('dropover');
    },
    out: function() {
      $('#your-photos').removeClass('dropover');
    },
    drop: function(event, ui) {
      var pid = $(ui.draggable).parent('a').attr('href').split('/');
      pid = pid[4];
      photo_order_crud(blog_id,pid,0);
    }
  });
}

function photo_order_crud(blog,pid,action){
  if(action == 0) { 
    var purl = '/blogs/' + blog + '/photo-order/';
    var pdata = 'photo_order_item[photo_id]=' + pid;
  } else {
    var purl = blog + '/photo-order/' + pid;
    var pdata = '_method=delete';
  }
  $.ajax({
    type: 'POST',
    url: purl,
    data: pdata,
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      if(textStatus == 'error') {
        action == 1 ? a = 'deleting' : a = 'adding';
        psuedoflash('error','There was an error ' + a + ' the  photo to your order. Please try again, or contact BabyBlogger.com if this problem persists.','your-photo-order');
      }
    },
    success: function(data,textStatus) {
      if(textStatus == 'success') {
        action == 1 ? a = 'deleted from' : a = 'added to';
        psuedoflash('notice','Photo was successfully ' + a + ' your order.','your-photo-order');
      }
    },
    complete: function(data,textStatus){
      if(action == 0) {
        $('#your-photos').removeClass('dropover');
      }
      show_photo_order();
    }
  });
}

$('#photo-controlbar #view a').live('mouseover', function() {
  var offset = $('#photo-controlbar').offset();
  var t = offset.top;
  var l = offset.left;
  $('body').append('<img src="' + $(this).attr('thumbsrc') + '" id="your-photo" class="photo" />');
  $('#your-photo').load(function(){
    $(this).attr( { height: $('#your-photo').height(), width: $('#your-photo').width() }).css({ top: (t - $('#your-photo').innerHeight()) + 'px', left: l - $('#your-photo').innerWidth() + 'px' });
  });
}).live('mouseout', function() {
  $('#your-photo').remove();
}).live('mousemove', function() {
  $('#your-photo').show();
});

$('#photo-controlbar #delete a').live('click', function() {
  if (confirm('Are you sure you want to remove this photo from your order?')) {
    photo_order_crud($(this).attr('href'),$(this).attr('pid'),1);
  } else {
    return false;
  }
});

(function($){
  $.fn.jqphotocontrol = function() {
    this.each(function() {
      $(this).hover(
        function () {
          var pid = $(this).attr('id').substr(1);
          var thumbsrc = $(this).attr('src').replace(/\.[^.]+$/, '.thumb');
          var offset = $(this).offset();
          var t = offset.top;
          var l = offset.left;
          var w = $(this).innerWidth();
          var h = $(this).innerHeight();
          $('#photo-controlbar').
            show().
            css({ top: ((t+h) - $('#photo-controlbar').height()) + 'px', left: (l) + 'px', width: w }
          ).find('#view a').attr({ thumbsrc: thumbsrc }).end().find('#delete a').attr({ href: '/blogs/' + blog_id, pid: pid });
        },
        function () {
          $('#photo-controlbar').hover(
            function(){$(this).show();},
            function(){$(this).hide();}
          );
          $('#photo-controlbar').hide();
        }
      );
    });
  };
})(jQuery);

function makeproductmenu(){
  $('ul.product-menu').each(function() {
    $(this).find('.category > a').toggle(function(){
      var $this = $(this).parent('.category');
      $this.siblings('li').children('a').removeClass('current-category').next('.products').slideUp(500);
      $this.children('a').addClass('current-category').next('.products').slideDown(500);
     return false;
    }, function() {
      $(this).removeClass('current-category').next('.products').slideUp(500);
      return false;
    });
    $(this).find('.products li > a').click(function(){
      $('.current-product').removeClass('current-product');
      sku = $(this).attr('href');
      app.setSku(sku);
      $(this).addClass('current-product');
      return false;
    });
    $(this).find('.products').hide().end().fadeIn('fast').find('.products li > a[href="10043"]').click();
  });
}

function activateproductmenu(sku) {
  $('a[href=' + sku + ']').addClass('current-product').closest('ul.products').slideDown(500).parents('li.category').children('a').addClass('current-category');
}

/* 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);
