// Adding in the ability to do smooth scrolling to an element with jQuery
jQuery.fn.extend({
  scrollTo : function(speed) {
    return this.each(function() {
      var targetOffset = jQuery(this).offset().top - 30;
      jQuery('html,body').animate({scrollTop: targetOffset}, speed);
    });
  }
});

// Form styling magic hacked from http://www.alistapart.com/articles/prettyaccessibleforms
function cmxform() {
	// Hide forms
	jQuery('.cmxform').hide().end();

	// Processing CMXForms that use LI format
	jQuery('.cmxform').find('li label').not('.nocmx').each(function(i) {
		// Fixing up block positioning by adding a SPAN
		var labelContent = this.innerHTML;
		var labelWidth = document.defaultView.getComputedStyle(this, '').getPropertyValue('width');
		var labelSpan = document.createElement('span');
		labelSpan.style.display = 'block';
		labelSpan.style.width = labelWidth;
		labelSpan.innerHTML = labelContent;
		this.style.display = '-moz-inline-box';
		this.innerHTML = '';
		this.appendChild(labelSpan);
	}).end();
	
	// And forms that use tables

	// Show forms
	jQuery('.cmxform').show().end();
}

// This adds highlighting to the row that you're currently working on in a CMXform
function cmxformActiveRow() {
	// Adding a handler to highlight the active row
	jQuery('.cmxform').find('li label').not('.nocmx').each(function(i) {
		jQuery(this).parent().find('input,select,textarea').not('.nocmx').each(function() {
			jQuery(this).focus(function() {
				jQuery(this).parents('li').addClass('active-row');
			});
		});
		jQuery(this).parent().find('input,select,textarea').not('.nocmx').each(function() {
			jQuery(this).blur(function() {
				jQuery(this).parents('li').removeClass('active-row');
			});
		});
	}).end();

	jQuery('.cmxform').find('table tr td').not('.nocmx').each(function() {
		// Adding a handler to highlight the active row	
		jQuery(this).find('input,select').not('.nocmx').each(function() {
			jQuery(this).focus(function() {
				jQuery(this).parent().parent().addClass('active-row');
			});
		});
		jQuery(this).find('input,select').not('.nocmx').each(function() {
			jQuery(this).blur(function() {
				jQuery(this).parent().parent().removeClass('active-row');
			});
		});
	}).end();
}

// Handle default values in text fields
function formDefault(elem_id, default_val) {
	jQuery('#' + elem_id).focus(function() { if (jQuery('#' + elem_id).val() == default_val) { jQuery('#' + elem_id).val(''); } });
	jQuery('#' + elem_id).blur(function() { if (jQuery('#' + elem_id).val() == '') { jQuery('#' + elem_id).val(default_val); } });
}

// Handle the privacy warning slidedown (signup and book options)
// t is the id of the radio button that determines that it *IS* a public book
function privacyWarning(t) {
	if (jQuery(t).attr('checked') == true) {
		jQuery('#privacy_warning').slideDown();
	} else {
		jQuery('#privacy_warning').slideUp();
	}
}

// Object def for listing books
function BabyBook(id, url, avatar, name, location) {
	this.id       = id;
	this.url      = url;
	this.avatar   = avatar;
	this.name     = name;
	this.location = location;
	return this;
}

function deleteImage(id) {
	if (!confirm("Are You Sure?\n\nYou are about to permanently delete this photo\nfrom this entry (and from your account).\n\nYou may upload it again later if you like.")) {
		return false;
	}
	
	// Set status indicator to show that we're "doing stuff" (taken from Thickbox)
	jQuery("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
	jQuery('#TB_load').show();//show loader
	
	// Do AJAX request to delete
	jQuery.ajax({
		url: deleteLink.replace(/<ID>/g, id),
		type: 'GET',
		error: function(xhttp, text, e) {
			jQuery('#TB_load').remove(); // done working
			alert("We couldn't delete this attachment for you.\n\nPerhaps you don't have sufficient permission.");
		},
		success: function(data, status) {
			jQuery('#TB_load').remove(); // done working
			if ('success' == status) {
				// Check the actual response text
				if (data == 'SUCCESS') {
					// Close thickbox
					tb_remove();
				
					// fadeOut image
					jQuery('#attach-' + id + ', .attach-' + id).animate({'height':'0', 'opacity':'0'}, 1500, function(){
						jQuery('#attach-' + id + ', .attach-' + id).remove();
					});
				
					// If we're on the posting UI page, there is more work to be done
					if (typeof POSTING_UI != 'undefined' && POSTING_UI) {
						loc = jQuery.inArray(id, idStack);
						removeAttachment(id);
						ed = tinyMCE.getInstanceById('post_content_' + (loc + 1));
						check = ed.getHTML();
						if (check.replace(/^\s+|\s+$/g, '').length == 0) {
							tinyMCE.removeMCEControl('post_content_' + (loc + 1));
							jQuery('#post_content_' + (loc + 1)).animate({'height':'0', 'opacity':'0'}, 1400, function(){
								jQuery('#post_content_' + (loc + 1)).remove();
							});
						}
					}
				} else {
					alert("We couldn't delete this attachment for you.\n\nPerhaps you don't have sufficient permission.");
				}
			} else {
				alert("We couldn't delete this attachment for you.\n\nPerhaps you don't have sufficient permission.");
			}
		}
	});
}

// Put all code to be executed once DOM is loaded in here
jQuery(document).ready(function(){
	// Automagic login defaults
	formDefault('email', 'email');
	formDefault('password', '********');
	
	// Adding active-row highlighting to forms
	cmxformActiveRow();
	
	// Protect email addresses
	jQuery('a.email').each(function(){
		e = this.rel.replace('/', '@');
		this.href = 'mailto:' + e;
	});
});

// Upgrade forms so they are pretty(er) (for Mozilla-based-browsers)
if (document.addEventListener) {
	document.addEventListener('DOMContentLoaded', cmxform, false);
}

/*
 
Correctly handle PNG transparency in Win IE 5.5 & 6.
http://homepage.ntlworld.com/bobosola. Updated 18-Jan-2006.

Use in <HEAD> with DEFER keyword wrapped in conditional comments:
<!--[if lt IE 7]>
<script defer type="text/javascript" src="pngfix.js"></script>
<![endif]-->

*/

var arVersion = navigator.appVersion.split("MSIE");
var version = parseFloat(arVersion[1]);
if ((version >= 5.5) && (document.body && typeof document.body.filters != 'undefined')) {
   for(var i=0; i<document.images.length; i++) {
      var img = document.images[i];
      var imgName = img.src.toUpperCase();
      if (imgName.substring(imgName.length-3, imgName.length).toUpperCase() == "PNG") {
         var imgID = (img.id) ? "id='" + img.id + "' " : "";
         var imgClass = (img.className) ? "class='" + img.className + "' " : "";
         var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
         var imgStyle = "display:inline-block;" + img.style.cssText;
         if (img.align == "left") imgStyle = "float:left;" + imgStyle;
         if (img.align == "right") imgStyle = "float:right;" + imgStyle;
         if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
         var strNewHTML = "<span " + imgID + imgClass + imgTitle
	         + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
	         + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
	         + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" ;
         img.outerHTML = strNewHTML;
         i = i-1;
      }
   }
}