(function($, window, undefined){

// private variables
var doc = $(window.document),
	timthumb_url = 'http://huntnewsnu.com/wp-content/themes/mimbo/scripts/timthumb.php';

// UTIL ///////////////////////////////////////////////////////////////////

var img_url = function(src) {
	return src.substring(src.indexOf('huntnewsnu.com')+14);
};

var util = {};

/**
 * Registers the given function as the page's onload function.
 *
 * If given a function, registers that function. If given a string,
 * registers the function found at load[f] (if there is one)
 *
 * @requires jQuery
 * @param f The function to register
 */
util.setOnload = function(f) {
	if (typeof(f) === 'function') {
		doc.ready(f);
	} else if (typeof(f) === 'string' && typeof(load[f] === 'function')) {
		doc.ready(load[f]);
	}   
};

// TODO jsdoc
util.fixExcerptImage = function(img, excerpt, img_div) {
    // rip the lead image out and move it into either the left or right
    // lead image div, depending on whether it is an alignright or
    // alignleft div
    if (img.length < 1) {
		if (excerpt) {
        	excerpt.css({'width': '100%'});
		}
		return;
    }   
    var src = img.attr('src');
	src = timthumb_url + '?src=' + escape(img_url(src));
	src = src + '&w=' + img_div.width() + '&h=' + img_div.height() + '&zc=1';
    img.remove();
    img = document.createElement('img');
    img.src = src;
    img_div.append(img).show();
    //$(img).centerInParent();
};

// ONLOAD FUNCTIONS ///////////////////////////////////////////////////////

var load = {};

load['index'] = function() {
	// fix the lead excerpt image
	var lead_img = $('#lead img');
	var lead_img_div = lead_img.hasClass('alignleft') ? $('#lead .img_left') : $('#lead .img_right');
	util.fixExcerptImage(lead_img, $('#lead-text'), lead_img_div);

	// fix all the other excerpt images
	$('div.recent-excerpts').each(function() {
		lead_img = $(this).find('img').first();
		lead_img_div = $(this).find('div.img_left');
		if (lead_img.length > 0) {
			$(this).find('div.img_left_container').show();
		}
		util.fixExcerptImage(lead_img, null, lead_img_div);
	});

	// right-float the social links
	$('div.textwidget:has(a[href*=facebook])').css({'text-align':'center'});
};

// JQUERY EXTENSIONS //////////////////////////////////////////////////////

/**
 * Centers the selected element inside its parent element
 */
$.fn.centerInParent = function() {
	var p = $(this).parent();
	var offset_x = $(this).width() - p.width();
	var offset_y = $(this).height() - p.height();
	offset_x = (offset_x != 0) ? offset_x / 2 : offset_x;
	offset_x = (offset_x > 0) ? offset_x * -1 : offset_x;
	offset_y = (offset_y != 0) ? offset_y / 2 : offset_y;
	offset_y = offset_y * -1;
	$(this).css({'margin-left': offset_x + 'px',
				 'margin-top': offset_y + 'px'});
	return this;
};

window.hn = {'util': util};

})(jQuery.noConflict(true), window);

